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
chore(scripts): the rest of the directory under the formatter (#95)
Matthew Kissinger5771fd6e64d5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 99353e95..cf33ac97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,31 @@Changes to `@kiln/engine`. Source and installable packages are distributed throughGitHub. The package is not published on the npm registry.+## Every directory that holds code is linted now — 2026-09-12++- 14.4 left the one-off tools in `scripts/` out and priced the alternative at 26 lint+ findings, a 1,530-line reflow, and 162 lines of coverage slack. After the ratchet got+ a scope the third term is **zero** — `scripts/**` is not instrumented at all — so what+ was left was a diff, and it is taken. **480 files where 442 were.**+- Thirty-four format findings and thirty-two real ones, over `.mjs` and `.ts` alike; the+ `.ts` files under `scripts/` had never been linted either, since the pattern was+ `src/**/*.ts`.+- Twenty-five `useTemplate`, seventeen of them one idiom: `JSON.stringify(…) + '\n'`,+ the receipt-file shape, across eleven files. A shared helper is the obvious DRY move+ and is deliberately not taken — `package-plugin.mjs` ships in the package `files`+ list, so importing one means shipping another file for a cosmetic win.+- Three findings were not cosmetic. **Two `any` in the pilot evaluation host**: one read+ as `previous.config` / `previous?.deadline`, now typed; one feeding a budget estimator+ through optional chains, now a declared `PilotToolInput` that names exactly the fields+ the image-cell budget depends on — documentation the estimator did not have. A loop's+ update step hiding in its condition in `smoke-package.mjs`. And **a literal ESC byte**+ in `harness.mjs`'s ANSI stripper, invisible in every diff and editor, now `\u001B`.+- Also surfaced, and deliberately left for its own change: `docs/tools.md` is stale and+ its `docs:tools --check` drift checker runs in no workflow and no test. The cause is+ the `zod` 4.4.3 → 4.6.2 bump — `z.toJSONSchema` now emits `items: false`, `minItems`+ and `maxItems` for fixed-length tuples — so the published tool reference has+ understated every tuple schema since. Ledger 14.8.+## render-service joins the lint surface — 2026-09-12- It was left out because `render-service/src/**` is `-text` in `.gitattributes` and thediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 61b52962..988e1b4a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -23,9 +23,8 @@ bun run test:coveragetolerated baseline to compare against, so any diagnostic your change produces isyours -- either fix it, or suppress it with a `biome-ignore` comment that says why.-The surface is `src/`, `site/src/`, `site/*.ts`, `render-service/`, and in `scripts/`-the gates and their tests (`check-*.mjs`, `**/*.test.mjs`). The one-off tools beside-them are out -- see ledger 14.4 for what taking them costs. If you add+The surface is every directory that holds code: `src/`, `site/src/`, `site/*.ts`,+`render-service/` and `scripts/`. If you adda directory, add it to `files.includes` in `biome.json`: Biome silently processesnothing outside that list, which is how `scripts/` went unlinted while the coveragerun measured it. Note that `biome` prints at most 20 diagnostics by default, so adiff --git a/biome.json b/biome.jsonindex 64c7914d..02b96d4e 100644--- a/biome.json+++ b/biome.json@@ -6,8 +6,8 @@"src/**/*.ts","site/src/**/*.{ts,tsx}","site/*.ts",- "scripts/check-*.mjs",- "scripts/**/*.test.mjs",+ "scripts/**/*.mjs",+ "scripts/**/*.ts","render-service/src/**/*.mjs","render-service/test/**/*.mjs"],diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.mdindex f8a87f4d..0929e11f 100644--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md@@ -1679,6 +1679,7 @@ the installed tree.| 14.1 | Re-ground 7.12 / SEP-2640 against an authoritative source | **Done 2026-09-12.** Deferred still, for a stronger reason. See below || 14.2 | Establish what actually blocks the `ai` 7 family, and gate it | **Done 2026-09-12.** `@strands-agents/[email protected]` is latest, declares peer `@ai-sdk/provider: ^3.0.0`, and its `VercelModel` is typed on `LanguageModelV3` in 21 places. `@openrouter/[email protected]` requires `ai: ^7.0.0`; `[email protected]` depends on `@ai-sdk/[email protected]`. The family cannot be taken until Strands ships a release accepting the v4 spec -- no budget changes that. `scripts/peer-ranges.test.mjs` now fails on a peer range the version beside it does not meet, verified by patching the installed `@openrouter/ai-sdk-provider` manifest to peer `ai: ^7.0.0` and watching it report `installed 6.0.282` || 14.3 | Assert the prompt-cache breakpoint on the wire, offline | **Done 2026-09-12.** Both native transports captured in `src/agent/providers.test.ts`, both differential. See below |+| 14.7 | The rest of `scripts/` under the formatter, now that 14.5 made it free | **Done 2026-09-12.** 480 files where 442 were; every directory holding code is in the surface. Turned up two findings nothing else would have: two `any` in the evaluation host, and a stale generated doc -- see 14.8 || 14.6 | `render-service/` into the lint surface, which needed its line endings settled first | **Done 2026-09-12.** 442 files where 416 were. See below || 14.5 | Give the coverage ratchet a scope, so repo-only code cannot move the engine's contract | **Done 2026-09-12.** Measured over `src/` alone; baseline re-measured at 95.39% functions / 92.59% lines; `lines` raised 92 to 92.1 so the narrowing does not quietly hand back slack. See below || 14.4 | Bring the repository's own gates under the lint gate, which they were never under | **Done 2026-09-12** for the gates and their tests: 416 files checked where 405 were, and the tree reports nothing. The one-off tools beside them are measured and deliberately left, below |@@ -1890,3 +1891,56 @@ it was outside every lint gate this repository has.`reliability.test.mjs` pins both include patterns and asserts the `-text` line staysgone, since the next edit to a CRLF-era file is what would reintroduce the mix.render-service's own 37 tests pass on the normalized sources.++### 14.7 -- the objection to the rest of `scripts/` was the coverage cost, and 14.5 removed it++14.4 left the one-off tools out and priced the alternative at 26 lint findings, a+1,530-line reflow, and 162 lines of coverage slack. After 14.5 the third term is+**zero** -- `scripts/**` is not instrumented at all -- so what remained was a diff+and a taste question, and the owner's call was to take it.++Thirty-four format findings and thirty-two real ones, over `.mjs` and `.ts` alike+(the `.ts` files under `scripts/` had never been linted either, since the pattern+was `src/**/*.ts`). The reflow is +1,993 lines, on repo-only code with tests.++Twenty-five were `useTemplate`, and seventeen of those were one idiom:+`JSON.stringify(...) + '\n'`, the receipt-file shape, repeated across eleven files.+Rewritten by walking back from each `) + '\n'` with a depth counter rather than+matching the argument, because those calls contain nested parens, objects and their+own string literals -- a regex over them misses the multi-line ones or stops at the+wrong paren. A shared helper is the obvious DRY move and is deliberately not taken:+`package-plugin.mjs` is in the package's `files` list, so importing one would mean+shipping another file for a cosmetic win.++Three findings were not cosmetic:++- **Two `any` in `scripts/evaluation/server.ts`**, the pilot evaluation host.+ `let previous: any` is read as `previous.config`, `previous?.deadline` and for+ truthiness, so it is now `{ config?: unknown; deadline?: number } | undefined`.+ And `args as Record<string, any>` fed a budget estimator that reaches through+ optional chains -- `Record<string, unknown>` does not typecheck there, which is+ presumably why it was `any`. It is now a declared `PilotToolInput` naming exactly+ the fields the image-cell budget depends on, which is documentation the estimator+ did not have.+- **`noAssignInExpressions` in `smoke-package.mjs`**: a loop's update step inside its+ condition, now a `for` header where a reader looks for it.+- **The literal ESC byte in `harness.mjs`'s ANSI stripper**, invisible in every diff+ and editor, now `\u001B` with the rule suppressed on the adjacent line -- matching+ ESC is the point of that expression, not an accident.++### 14.8 -- `docs/tools.md` is stale, and its drift checker runs nowhere++Found by the lint pass touching `generate-tool-reference.ts`.+`bun run docs:tools --check` exists, reports drift, exits non-zero -- and appears in+no workflow and no test. The same shape as 13.7, where a shipped subsystem's 37+tests ran on nobody's machine.++It is drifting now, and the cause is 13.2: `zod` 4.4.3 to 4.6.2 changed+`z.toJSONSchema` to emit `"items": false`, `"minItems"` and `"maxItems"` for+fixed-length tuples, so the published tool reference has understated every tuple+schema since that bump. Verified to predate this phase by stashing the rewrite and+re-running the check.++Not folded into 14.7: regenerating a shipped document and wiring its gate is its own+change with its own reasoning, and burying it in a formatting pass is how a doc+artifact changes without anyone reading why.diff --git a/scripts/authorship.ts b/scripts/authorship.tsindex 4f60166a..ba470f63 100644--- a/scripts/authorship.ts+++ b/scripts/authorship.ts@@ -92,7 +92,13 @@ export function readAuthorship(source: string): Authorship {// No header means the program was written against this repository rather than// dispatched into a clean directory, which so far has always meant Claude.if (!m) {- return { model: null, display: 'Claude Opus 5', claude: true, harness: 'Claude Code', cleanRoom };+ return {+ model: null,+ display: 'Claude Opus 5',+ claude: true,+ harness: 'Claude Code',+ cleanRoom,+ };}const model = m[1]!.trim();// The bracketed id when there is one, otherwise whatever stands after `via`.@@ -100,7 +106,8 @@ export function readAuthorship(source: string): Authorship {// reader would say it, so it passes through untouched.const id = (m[3] ?? m[4]!).trim();const harness = HARNESS_DISPLAY[id.toLowerCase()] ?? m[2]?.trim() ?? id;- if (CLAUDE.test(model)) return { model, display: 'Claude Opus 5', claude: true, harness, cleanRoom };+ if (CLAUDE.test(model))+ return { model, display: 'Claude Opus 5', claude: true, harness, cleanRoom };return {model,display: MODEL_DISPLAY.find(([re]) => re.test(model))?.[1] ?? null,diff --git a/scripts/build-runtime.mjs b/scripts/build-runtime.mjsindex 7ad181bd..47f207d4 100644--- a/scripts/build-runtime.mjs+++ b/scripts/build-runtime.mjs@@ -10,11 +10,14 @@ const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');async function sources(directory, prefix = '') {const entries = [];- for (const item of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {+ for (const item of (await readdir(directory, { withFileTypes: true })).sort((a, b) =>+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0,+ )) {if (item.name === '__tests__' || item.name.endsWith('.test.ts')) continue;const name = prefix ? `${prefix}/${item.name}` : item.name;- if (item.isDirectory()) entries.push(...await sources(join(directory, item.name), name));- else if (/\.(?:ts|mjs|html|css)$/.test(item.name)) entries.push([name, sha(await readFile(join(directory, item.name)))]);+ if (item.isDirectory()) entries.push(...(await sources(join(directory, item.name), name)));+ else if (/\.(?:ts|mjs|html|css)$/.test(item.name))+ entries.push([name, sha(await readFile(join(directory, item.name)))]);}return entries;}@@ -33,32 +36,66 @@ export async function runtimeBuildIdentity(root) {}export async function buildRuntime(target, root = repo) {- const entries = { cli: 'src/cli.ts', mcp: 'src/mcp-server.ts', worker: 'src/evaluator/worker.ts', 'agent-run': 'src/agent/run.ts', 'agent-providers': 'src/agent/providers.ts' };- const outputs = { cli: 'cli.mjs', mcp: 'mcp-server.mjs', worker: 'evaluator-worker.mjs', 'agent-run': 'agent-run.mjs', 'agent-providers': 'agent-providers.mjs' };+ const entries = {+ cli: 'src/cli.ts',+ mcp: 'src/mcp-server.ts',+ worker: 'src/evaluator/worker.ts',+ 'agent-run': 'src/agent/run.ts',+ 'agent-providers': 'src/agent/providers.ts',+ };+ const outputs = {+ cli: 'cli.mjs',+ mcp: 'mcp-server.mjs',+ worker: 'evaluator-worker.mjs',+ 'agent-run': 'agent-run.mjs',+ 'agent-providers': 'agent-providers.mjs',+ };if (!entries[target]) throw new Error('Choose cli, mcp, or worker.');const before = await runtimeBuildIdentity(root);- const built = spawnSync('bun', ['build', entries[target], '--target=node', '--packages=external', `--outfile=dist/${outputs[target]}`], { cwd: root, stdio: 'inherit', windowsHide: true });+ const built = spawnSync(+ 'bun',+ [+ 'build',+ entries[target],+ '--target=node',+ '--packages=external',+ `--outfile=dist/${outputs[target]}`,+ ],+ { cwd: root, stdio: 'inherit', windowsHide: true },+ );if (built.status !== 0) throw new Error(`Building ${target} failed.`);const after = await runtimeBuildIdentity(root);- if (before.identity !== after.identity) throw new Error('Runtime source changed during build. Rebuild from a stable tree.');+ if (before.identity !== after.identity)+ throw new Error('Runtime source changed during build. Rebuild from a stable tree.');const path = join(root, 'dist/build.json');let previous = { schemaVersion: 1, entries: {} };- try { previous = JSON.parse(await readFile(path, 'utf8')); } catch {}+ try {+ previous = JSON.parse(await readFile(path, 'utf8'));+ } catch {}if (previous.schemaVersion !== 1) previous = { schemaVersion: 1, entries: {} };- const entry = { ...after, file: outputs[target], bundleHash: `sha256:${sha(await readFile(join(root, 'dist', outputs[target])))}` };+ const entry = {+ ...after,+ file: outputs[target],+ bundleHash: `sha256:${sha(await readFile(join(root, 'dist', outputs[target])))}`,+ };previous.entries[target] = entry;await mkdir(join(root, 'dist'), { recursive: true });- await writeFile(path, JSON.stringify(previous, null, 2) + '\n');+ await writeFile(path, `${JSON.stringify(previous, null, 2)}\n`);return entry;}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {try {- const targets = process.argv[2] === 'all' ? ['worker', 'agent-run', 'agent-providers', 'mcp', 'cli'] : [process.argv[2]];+ const targets =+ process.argv[2] === 'all'+ ? ['worker', 'agent-run', 'agent-providers', 'mcp', 'cli']+ : [process.argv[2]];for (const target of targets) {const entry = await buildRuntime(target);console.log(`${entry.file} ${entry.bundleHash} (${entry.identity})`);}+ } catch (error) {+ console.error(error.message);+ process.exitCode = 1;}- catch (error) { console.error(error.message); process.exitCode = 1; }}diff --git a/scripts/build-viewer.mjs b/scripts/build-viewer.mjsindex 0ad047b6..a752f8d7 100644--- a/scripts/build-viewer.mjs+++ b/scripts/build-viewer.mjs@@ -1,44 +1,33 @@-import { spawnSync } from "node:child_process";-import { copyFile, mkdir, readFile, writeFile, unlink } from "node:fs/promises";-import { fileURLToPath } from "node:url";-import { dirname, join, resolve } from "node:path";-const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");-await mkdir(join(root, "dist/viewer"), { recursive: true });+import { spawnSync } from 'node:child_process';+import { copyFile, mkdir, readFile, writeFile, unlink } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { dirname, join, resolve } from 'node:path';+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+await mkdir(join(root, 'dist/viewer'), { recursive: true });const result = spawnSync(- "bun",- [- "build",- "src/viewer/app.ts",- "--target=browser",- "--minify",- "--outfile=dist/viewer/app.js",- ],- { cwd: root, stdio: "inherit", windowsHide: true },+ 'bun',+ ['build', 'src/viewer/app.ts', '--target=browser', '--minify', '--outfile=dist/viewer/app.js'],+ { cwd: root, stdio: 'inherit', windowsHide: true },);if (result.status !== 0) process.exit(result.status ?? 1);-for (const file of ["index.html", "style.css"])- await copyFile(- join(root, "src/viewer", file),- join(root, "dist/viewer", file),- );+for (const file of ['index.html', 'style.css'])+ await copyFile(join(root, 'src/viewer', file), join(root, 'dist/viewer', file));const chat = spawnSync(- "bun",+ 'bun',[- "build",- "src/viewer/chat-app.ts",- "--target=browser",- "--minify",- "--outfile=dist/viewer/chat-app.js",+ 'build',+ 'src/viewer/chat-app.ts',+ '--target=browser',+ '--minify',+ '--outfile=dist/viewer/chat-app.js',],- { cwd: root, stdio: "inherit", windowsHide: true },+ { cwd: root, stdio: 'inherit', windowsHide: true },);if (chat.status !== 0) process.exit(chat.status ?? 1);-const script = await readFile(join(root, "dist/viewer/chat-app.js"), "utf8");-const html = await readFile(join(root, "src/viewer/chat.html"), "utf8");+const script = await readFile(join(root, 'dist/viewer/chat-app.js'), 'utf8');+const html = await readFile(join(root, 'src/viewer/chat.html'), 'utf8');await writeFile(- join(root, "dist/viewer/chat.html"),- html.replace("/* KILN_CHAT_APP */", () =>- script.replace(/<\/script/gi, "<\\/script"),- ),+ join(root, 'dist/viewer/chat.html'),+ html.replace('/* KILN_CHAT_APP */', () => script.replace(/<\/script/gi, '<\\/script')),);-await unlink(join(root, "dist/viewer/chat-app.js"));+await unlink(join(root, 'dist/viewer/chat-app.js'));diff --git a/scripts/create-workspace.mjs b/scripts/create-workspace.mjsindex 73366133..17077502 100644--- a/scripts/create-workspace.mjs+++ b/scripts/create-workspace.mjs@@ -1,5 +1,17 @@#!/usr/bin/env node-import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';+import {+ cp,+ lstat,+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ realpath,+ rename,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises';import { createHash } from 'node:crypto';import { realpathSync } from 'node:fs';import { spawnSync } from 'node:child_process';@@ -14,48 +26,107 @@ const harnesses = ['claude', 'codex', 'opencode', 'hermes', 'agy'];const skillRegistries = ['.claude/skills', '.agents/skills'];const core = ['kiln-author-asset', 'kiln-refine-asset', 'kiln-qa-asset'];const optional = { compose: 'kiln-compose-scene', batch: 'kiln-batch-dispatch' };-const inside = (parent, child) => { const rel = relative(parent, child); return !rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)); };+const inside = (parent, child) => {+ const rel = relative(parent, child);+ return !rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));+};export async function preflightRuntime(runtime, skills) {- if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('Kiln requires Node.js 22 or later.');+ if (Number(process.versions.node.split('.')[0]) < 22)+ throw new Error('Kiln requires Node.js 22 or later.');let pkg;try {pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));- for (const file of ['dist/cli.mjs', 'dist/mcp-server.mjs', 'dist/evaluator-worker.mjs', 'dist/build.json', ...skills.map((name) => `skills/${name}/SKILL.md`)]) {+ for (const file of [+ 'dist/cli.mjs',+ 'dist/mcp-server.mjs',+ 'dist/evaluator-worker.mjs',+ 'dist/build.json',+ ...skills.map((name) => `skills/${name}/SKILL.md`),+ ]) {if (!(await stat(join(runtime, file))).isFile()) throw new Error(file);}const build = JSON.parse(await readFile(join(runtime, 'dist/build.json'), 'utf8'));- for (const [name, file] of [['cli', 'cli.mjs'], ['mcp', 'mcp-server.mjs'], ['worker', 'evaluator-worker.mjs']]) {+ for (const [name, file] of [+ ['cli', 'cli.mjs'],+ ['mcp', 'mcp-server.mjs'],+ ['worker', 'evaluator-worker.mjs'],+ ]) {const entry = build.entries?.[name];- if (build.schemaVersion !== 1 || entry?.identity !== build.entries.cli?.identity || entry?.bundleHash !== `sha256:${hash(await readFile(join(runtime, 'dist', file)))}`) throw new Error(`Inconsistent ${name} build`);+ if (+ build.schemaVersion !== 1 ||+ entry?.identity !== build.entries.cli?.identity ||+ entry?.bundleHash !== `sha256:${hash(await readFile(join(runtime, 'dist', file)))}`+ )+ throw new Error(`Inconsistent ${name} build`);}- } catch (error) { throw new Error(`Kiln installation is incomplete or inconsistent at ${runtime}. Install dependencies and run bun run build:runtime before setup.`, { cause: error }); }- const probe = spawnSync(process.execPath, ['--input-type=module', '-e', 'const m = await import(process.argv[1]); if (typeof m.main !== "function") throw new Error("Missing CLI entry");', pathToFileURL(join(runtime, 'dist/cli.mjs')).href], { cwd: runtime, encoding: 'utf8', timeout: 30000, windowsHide: true });- if (probe.status !== 0) throw new Error(`Kiln runtime dependencies could not load. Reinstall dependencies at ${runtime}. ${probe.error?.message ?? probe.stderr.trim()}`);+ } catch (error) {+ throw new Error(+ `Kiln installation is incomplete or inconsistent at ${runtime}. Install dependencies and run bun run build:runtime before setup.`,+ { cause: error },+ );+ }+ const probe = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ 'const m = await import(process.argv[1]); if (typeof m.main !== "function") throw new Error("Missing CLI entry");',+ pathToFileURL(join(runtime, 'dist/cli.mjs')).href,+ ],+ { cwd: runtime, encoding: 'utf8', timeout: 30000, windowsHide: true },+ );+ if (probe.status !== 0)+ throw new Error(+ `Kiln runtime dependencies could not load. Reinstall dependencies at ${runtime}. ${probe.error?.message ?? probe.stderr.trim()}`,+ );return pkg;}function managedFiles(root, runtime, harness, nodeExecutable) {const store = join(root, '.kiln', 'programs');const server = join(runtime, 'dist', 'mcp-server.mjs');- const mcp = { command: nodeExecutable, args: [server], env: { KILN_PROGRAM_STORE: store, KILN_RENDER: 'auto' } };+ const mcp = {+ command: nodeExecutable,+ args: [server],+ env: { KILN_PROGRAM_STORE: store, KILN_RENDER: 'auto' },+ };const files = {'kiln.mjs': `// Generated runtime launcher. Repair paths with kiln-init <workspace> --repair.\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nprocess.env.KILN_PROGRAM_STORE = join(dirname(fileURLToPath(import.meta.url)), '.kiln', 'programs');\ntry {\n const { main } = await import(${quote(pathToFileURL(join(runtime, 'dist/cli.mjs')).href)});\n process.exitCode = await main(process.argv.slice(2));\n} catch (error) {\n console.error(error.message + '\\nIf the installation moved, run kiln-init <workspace> --repair from the current Kiln installation.');\n process.exitCode = 1;\n}\n`,};if (harness === 'claude') files['.mcp.json'] = quote({ mcpServers: { kiln_workspace: mcp } });- if (harness === 'codex') files['.codex/config.toml'] = `[mcp_servers.kiln_workspace]\ncommand = ${quote(mcp.command)}\nargs = [${quote(server)}]\n[mcp_servers.kiln_workspace.env]\nKILN_PROGRAM_STORE = ${quote(store)}\nKILN_RENDER = "auto"\n`;+ if (harness === 'codex')+ files['.codex/config.toml'] =+ `[mcp_servers.kiln_workspace]\ncommand = ${quote(mcp.command)}\nargs = [${quote(server)}]\n[mcp_servers.kiln_workspace.env]\nKILN_PROGRAM_STORE = ${quote(store)}\nKILN_RENDER = "auto"\n`;if (harness === 'agy') {files['.agents/mcp_config.json'] = quote({ mcpServers: { kiln_workspace: mcp } });- files['agy.mjs'] = `import { spawn } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst args = process.argv.slice(2);\nconst has = names => args.some(arg => names.some(name => arg === name || arg.startsWith(name + '=')));\nif (!has(['--project', '--new-project', '--conversation', '--continue', '-c'])) args.unshift('--new-project');\nargs.unshift('--add-dir', root);\nif (has(['--print', '--prompt', '-p']) && !has(['--disable-slash-commands'])) args.unshift('--disable-slash-commands');\nconst child = spawn('agy', args, { cwd: root, stdio: 'inherit', windowsHide: true });\nchild.on('error', error => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', code => { process.exitCode = code ?? 1; });\n`;+ files['agy.mjs'] =+ `import { spawn } from 'node:child_process';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst args = process.argv.slice(2);\nconst has = names => args.some(arg => names.some(name => arg === name || arg.startsWith(name + '=')));\nif (!has(['--project', '--new-project', '--conversation', '--continue', '-c'])) args.unshift('--new-project');\nargs.unshift('--add-dir', root);\nif (has(['--print', '--prompt', '-p']) && !has(['--disable-slash-commands'])) args.unshift('--disable-slash-commands');\nconst child = spawn('agy', args, { cwd: root, stdio: 'inherit', windowsHide: true });\nchild.on('error', error => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', code => { process.exitCode = code ?? 1; });\n`;}- if (harness === 'opencode') files['opencode.json'] = quote({ $schema: 'https://opencode.ai/config.json', skills: { paths: [join(root, 'skills')] }, mcp: { kiln_workspace: { type: 'local', command: [mcp.command, server], environment: mcp.env, enabled: true } } });+ if (harness === 'opencode')+ files['opencode.json'] = quote({+ $schema: 'https://opencode.ai/config.json',+ skills: { paths: [join(root, 'skills')] },+ mcp: {+ kiln_workspace: {+ type: 'local',+ command: [mcp.command, server],+ environment: mcp.env,+ enabled: true,+ },+ },+ });if (harness === 'hermes') {// Hermes scans project-local skills only inside a git checkout (nearest// ancestor with .git), and a workspace is deliberately not one. `external_dirs`// is unconditional, so it is what actually registers them here. YAML is a// superset of JSON, so the JSON form below is valid config.- files['.hermes/config.yaml'] = quote({ mcp_servers: { kiln_workspace: mcp }, skills: { external_dirs: [join(root, '.agents', 'skills')] } });- files['hermes.mjs'] = `import { spawn } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst child = spawn('hermes', process.argv.slice(2), { cwd: root, stdio: 'inherit', windowsHide: true, env: { ...process.env, HERMES_HOME: join(root, '.hermes'), TERMINAL_CWD: root } });\nchild.on('error', (error) => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', (code) => { process.exitCode = code ?? 1; });\n`;+ files['.hermes/config.yaml'] = quote({+ mcp_servers: { kiln_workspace: mcp },+ skills: { external_dirs: [join(root, '.agents', 'skills')] },+ });+ files['hermes.mjs'] =+ `import { spawn } from 'node:child_process';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst root = dirname(fileURLToPath(import.meta.url));\nconst child = spawn('hermes', process.argv.slice(2), { cwd: root, stdio: 'inherit', windowsHide: true, env: { ...process.env, HERMES_HOME: join(root, '.hermes'), TERMINAL_CWD: root } });\nchild.on('error', (error) => { console.error(error.message); process.exitCode = 1; });\nchild.on('exit', (code) => { process.exitCode = code ?? 1; });\n`;}return { files, store, server };}@@ -94,15 +165,19 @@ Keep .kiln/programs while working. Source files are portable; references resolve`;async function readManifest(root) {- try { return JSON.parse(await readFile(join(root, '.kiln/workspace.json'), 'utf8')); }- catch { throw new Error('This is not a managed Kiln workspace. Existing files were not changed.'); }+ try {+ return JSON.parse(await readFile(join(root, '.kiln/workspace.json'), 'utf8'));+ } catch {+ throw new Error('This is not a managed Kiln workspace. Existing files were not changed.');+ }}async function fileHashes(directory, prefix = '') {const hashes = {};for (const entry of await readdir(directory, { withFileTypes: true })) {const name = prefix ? `${prefix}/${entry.name}` : entry.name;- if (entry.isDirectory()) Object.assign(hashes, await fileHashes(join(directory, entry.name), name));+ if (entry.isDirectory())+ Object.assign(hashes, await fileHashes(join(directory, entry.name), name));else if (entry.isFile()) hashes[name] = hash(await readFile(join(directory, entry.name)));}return hashes;@@ -118,36 +193,77 @@ export async function createWorkspace(directory, harness = 'claude', options = {if (previous) harness = previous.harness;if (!harnesses.includes(harness)) throw new Error(`Choose ${harnesses.join(', ')}.`);const extras = options.skills ?? [];- if (extras.some((name) => !Object.hasOwn(optional, name))) throw new Error('Optional skills: compose,batch.');+ if (extras.some((name) => !Object.hasOwn(optional, name)))+ throw new Error('Optional skills: compose,batch.');const skills = previous?.skills ?? [...core, ...new Set(extras.map((name) => optional[name]))];- if (!Array.isArray(skills) || skills.some((name) => ![...core, ...Object.values(optional)].includes(name))) throw new Error('Invalid workspace skill manifest.');+ if (+ !Array.isArray(skills) ||+ skills.some((name) => ![...core, ...Object.values(optional)].includes(name))+ )+ throw new Error('Invalid workspace skill manifest.');const pkg = await preflightRuntime(runtime, skills);let exists = false;try {const info = await lstat(root);- if (!info.isDirectory() || info.isSymbolicLink()) throw new Error('Choose a real directory, not a symbolic link.');+ if (!info.isDirectory() || info.isSymbolicLink())+ throw new Error('Choose a real directory, not a symbolic link.');exists = true;- if (inside(runtime, await realpath(root))) throw new Error('Choose a directory outside the Kiln installation.');- } catch (error) { if (error.code !== 'ENOENT') throw error; }+ if (inside(runtime, await realpath(root)))+ throw new Error('Choose a directory outside the Kiln installation.');+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }// Resolve the nearest existing parent so symlinks cannot bypass the installation check.let ancestor = dirname(root);- while (true) { try { ancestor = await realpath(ancestor); break; } catch (error) { if (error.code !== 'ENOENT') throw error; const parent = dirname(ancestor); if (parent === ancestor) throw error; ancestor = parent; } }- if (inside(runtime, root) || inside(runtime, ancestor)) throw new Error('Choose a directory outside the Kiln installation.');- if (!previous && exists && (await readdir(root)).length) throw new Error('The destination must be empty; no existing files were changed.');+ while (true) {+ try {+ ancestor = await realpath(ancestor);+ break;+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ const parent = dirname(ancestor);+ if (parent === ancestor) throw error;+ ancestor = parent;+ }+ }+ if (inside(runtime, root) || inside(runtime, ancestor))+ throw new Error('Choose a directory outside the Kiln installation.');+ if (!previous && exists && (await readdir(root)).length)+ throw new Error('The destination must be empty; no existing files were changed.');const { files, store, server } = managedFiles(root, runtime, harness, nodeExecutable);- const manifest = { schemaVersion: 1, harness, runtime, runtimeVersion: pkg.version, runtimeHashes: { cli: hash(await readFile(join(runtime, 'dist/cli.mjs'))), mcp: hash(await readFile(join(runtime, 'dist/mcp-server.mjs'))) }, node: nodeExecutable, skills, skillHashes: previous?.skillHashes, generated: Object.fromEntries(Object.entries(files).map(([name, body]) => [name, hash(body)])) };+ const manifest = {+ schemaVersion: 1,+ harness,+ runtime,+ runtimeVersion: pkg.version,+ runtimeHashes: {+ cli: hash(await readFile(join(runtime, 'dist/cli.mjs'))),+ mcp: hash(await readFile(join(runtime, 'dist/mcp-server.mjs'))),+ },+ node: nodeExecutable,+ skills,+ skillHashes: previous?.skillHashes,+ generated: Object.fromEntries(Object.entries(files).map(([name, body]) => [name, hash(body)])),+ };if (previous) {if (previous.schemaVersion !== 1) throw new Error('Unsupported workspace manifest version.');const originals = {};for (const name of Object.keys(files)) {if (!Object.hasOwn(previous.generated ?? {}, name)) {- try { await lstat(join(root, name)); throw new Error(`Refusing to replace existing ${name}.`); }- catch (error) { if (error.code !== 'ENOENT') throw error; }+ try {+ await lstat(join(root, name));+ throw new Error(`Refusing to replace existing ${name}.`);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }originals[name] = undefined;continue;}const original = await readFile(join(root, name), 'utf8');- if (hash(original) !== previous.generated?.[name]) throw new Error(`Refusing to replace edited ${name}. Preserve your changes and update its runtime paths manually.`);+ if (hash(original) !== previous.generated?.[name])+ throw new Error(+ `Refusing to replace edited ${name}. Preserve your changes and update its runtime paths manually.`,+ );originals[name] = original;}const oldManifest = await readFile(join(root, '.kiln/workspace.json'), 'utf8');@@ -155,7 +271,10 @@ export async function createWorkspace(directory, harness = 'claude', options = {for (const [name, body] of Object.entries(files)) await writeFile(join(root, name), body);await writeFile(join(root, '.kiln/workspace.json'), quote(manifest));} catch (error) {- for (const [name, body] of Object.entries(originals)) { if (body === undefined) await rm(join(root, name), { force: true }); else await writeFile(join(root, name), body); }+ for (const [name, body] of Object.entries(originals)) {+ if (body === undefined) await rm(join(root, name), { force: true });+ else await writeFile(join(root, name), body);+ }await writeFile(join(root, '.kiln/workspace.json'), oldManifest);throw error;}@@ -165,12 +284,16 @@ export async function createWorkspace(directory, harness = 'claude', options = {const stage = await mkdtemp(join(dirname(root), '.kiln-init-'));const installed = [];try {- for (const [name, body] of Object.entries(files)) { await mkdir(dirname(join(stage, name)), { recursive: true }); await writeFile(join(stage, name), body); }+ for (const [name, body] of Object.entries(files)) {+ await mkdir(dirname(join(stage, name)), { recursive: true });+ await writeFile(join(stage, name), body);+ }await mkdir(join(stage, '.kiln'), { recursive: true });await writeFile(join(stage, '.kiln/workspace.json'), quote(manifest));await writeFile(join(stage, '.gitignore'), '.kiln/programs/\n.hermes/\n*.glb\n*.png\n');for (const name of ['AGENTS.md', 'CLAUDE.md']) await writeFile(join(stage, name), guide);- for (const name of skills) await cp(join(runtime, 'skills', name), join(stage, 'skills', name), { recursive: true });+ for (const name of skills)+ await cp(join(runtime, 'skills', name), join(stage, 'skills', name), { recursive: true });// Registration copies. No harness scans a bare `skills/`: Claude Code reads// only `.claude/skills/`, while codex, opencode, hermes and agy read// `.agents/skills/`. Without these the workspace has skill files that the@@ -182,17 +305,35 @@ export async function createWorkspace(directory, harness = 'claude', options = {await cp(join(runtime, 'skills', name), join(stage, registry, name), { recursive: true });manifest.skillHashes = await fileHashes(join(stage, 'skills'));await writeFile(join(stage, '.kiln/workspace.json'), quote(manifest));- const command = harness === 'hermes' ? 'node hermes.mjs --ignore-rules' : harness === 'agy' ? 'node agy.mjs' : harness;- const launch = harness === 'hermes' ? 'Hermes uses a separate profile; authenticate in that profile or supply provider credentials through the environment.' : harness === 'agy' ? 'The launcher supplies the absolute project directory. For headless runs, use node agy.mjs --model MODEL --print \"Read AGENTS.md and the project skills. Use only kiln_workspace MCP tools. YOUR TASK.\". Print mode disables automatic slash-command/skill expansion to avoid automatic expansion of a global skill. Use absolute task-file paths in headless prompts and verify that tool calls use kiln_workspace; global configuration and authentication remain unchanged.' : `This directory is configured for ${harness}.`;- await writeFile(join(stage, 'START.md'), `# Start making assets\n\n\`\`\`bash\ncd ${root}\n${command}\n\`\`\`\n\n${launch} Accept the project/MCP trust prompts. Ask the agent to read AGENTS.md and create an asset. Kiln needs no separate model key.\n\nCore author/refine/QA skills are installed and registered for this harness. Optional compose/batch skills are selected at setup with --skills compose,batch.\n\nKeep assets here and engine source outside. This separates task context, not operating-system permissions. User instructions and authentication can still apply.\n\nRun repair after anything that invalidates the generated absolute paths: moving this workspace, moving or reinstalling the runtime, or replacing the Node that setup recorded -- an nvm switch or uninstall does that, because the manifest pins the exact interpreter the preflight check validated.\n\n\`\`\`bash\nnode ${join(runtime, 'scripts/create-workspace.mjs')} ${root} --repair\n\`\`\`\n\nThat path is where the installation was at setup. If the installation itself moved, run the same command from its current location; \`runtime\` in .kiln/workspace.json records where this workspace last expected it.\n\nRepair updates generated runtime paths only and refuses edited configuration; it preserves skills, assets, and saved revisions.\n`);+ const command =+ harness === 'hermes'+ ? 'node hermes.mjs --ignore-rules'+ : harness === 'agy'+ ? 'node agy.mjs'+ : harness;+ const launch =+ harness === 'hermes'+ ? 'Hermes uses a separate profile; authenticate in that profile or supply provider credentials through the environment.'+ : harness === 'agy'+ ? 'The launcher supplies the absolute project directory. For headless runs, use node agy.mjs --model MODEL --print "Read AGENTS.md and the project skills. Use only kiln_workspace MCP tools. YOUR TASK.". Print mode disables automatic slash-command/skill expansion to avoid automatic expansion of a global skill. Use absolute task-file paths in headless prompts and verify that tool calls use kiln_workspace; global configuration and authentication remain unchanged.'+ : `This directory is configured for ${harness}.`;+ await writeFile(+ join(stage, 'START.md'),+ `# Start making assets\n\n\`\`\`bash\ncd ${root}\n${command}\n\`\`\`\n\n${launch} Accept the project/MCP trust prompts. Ask the agent to read AGENTS.md and create an asset. Kiln needs no separate model key.\n\nCore author/refine/QA skills are installed and registered for this harness. Optional compose/batch skills are selected at setup with --skills compose,batch.\n\nKeep assets here and engine source outside. This separates task context, not operating-system permissions. User instructions and authentication can still apply.\n\nRun repair after anything that invalidates the generated absolute paths: moving this workspace, moving or reinstalling the runtime, or replacing the Node that setup recorded -- an nvm switch or uninstall does that, because the manifest pins the exact interpreter the preflight check validated.\n\n\`\`\`bash\nnode ${join(runtime, 'scripts/create-workspace.mjs')} ${root} --repair\n\`\`\`\n\nThat path is where the installation was at setup. If the installation itself moved, run the same command from its current location; \`runtime\` in .kiln/workspace.json records where this workspace last expected it.\n\nRepair updates generated runtime paths only and refuses edited configuration; it preserves skills, assets, and saved revisions.\n`,+ );if (exists) {// Windows cannot remove the caller's current directory, even when empty.// Move only staged entries and track them so a failed install rolls back.- if ((await readdir(root)).length) throw new Error('The destination changed during setup; no files were replaced.');+ if ((await readdir(root)).length)+ throw new Error('The destination changed during setup; no files were replaced.');for (const name of await readdir(stage)) {const target = join(root, name);- try { await lstat(target); throw new Error(`Refusing to replace ${target}.`); }- catch (error) { if (error.code !== 'ENOENT') throw error; }+ try {+ await lstat(target);+ throw new Error(`Refusing to replace ${target}.`);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }await rename(join(stage, name), target);installed.push(target);}@@ -208,18 +349,24 @@ export async function createWorkspace(directory, harness = 'claude', options = {function isDirectSetupEntry() {if (!process.argv[1]) return false;- try { return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url)); }- catch { return false; }+ try {+ return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }}if (isDirectSetupEntry()) {try {const args = process.argv.slice(2);if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: kiln-init <empty-directory> [--harness claude|codex|opencode|hermes|agy] [--skills compose,batch]\n kiln-init <managed-workspace> --repair');+ console.log(+ 'Usage: kiln-init <empty-directory> [--harness claude|codex|opencode|hermes|agy] [--skills compose,batch]\n kiln-init <managed-workspace> --repair',+ );} else {const directory = args.shift();- if (!directory || directory.startsWith('--')) throw new Error('Provide a workspace directory. Run kiln-init --help for usage.');+ if (!directory || directory.startsWith('--'))+ throw new Error('Provide a workspace directory. Run kiln-init --help for usage.');let harness = 'claude';const options = {};while (args.length) {@@ -228,11 +375,16 @@ if (isDirectSetupEntry()) {else if (flag === '--harness' || flag === '--skills') {const value = args.shift();if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value.`);- if (flag === '--harness') harness = value; else options.skills = value.split(',');+ if (flag === '--harness') harness = value;+ else options.skills = value.split(',');} else throw new Error(`Unknown option: ${flag}`);}- if (options.repair && options.skills) throw new Error('--repair does not change installed skills.');+ if (options.repair && options.skills)+ throw new Error('--repair does not change installed skills.');console.log(quote(await createWorkspace(directory, harness, options)));}- } catch (error) { console.error(error.message); process.exitCode = 1; }+ } catch (error) {+ console.error(error.message);+ process.exitCode = 1;+ }}diff --git a/scripts/curate-texture-library.mjs b/scripts/curate-texture-library.mjsindex 4ea74fc3..a5c27192 100644--- a/scripts/curate-texture-library.mjs+++ b/scripts/curate-texture-library.mjs@@ -13,33 +13,121 @@ import { writeFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';import sharp from 'sharp';-const OUTPUT = fileURLToPath(new URL('../src/material-texture-library.generated.ts', import.meta.url));+const OUTPUT = fileURLToPath(+ new URL('../src/material-texture-library.generated.ts', import.meta.url),+);const USER_AGENT = 'KilnTextureCuration/1.0 (matthew-kissinger/kiln)';const TARGET_SIZE = 128;const FAMILIES = [- { slug: 'bark-brown-01', asset: 'bark_brown_01', label: 'Brown furrowed bark', recipes: ['kiln.material.bark.v1', 'kiln.material.wood.v1'] },- { slug: 'weathered-planks', asset: 'brown_planks_03', label: 'Weathered brown planks', recipes: ['kiln.material.wood.v1'] },- { slug: 'rough-concrete', asset: 'rough_concrete', label: 'Rough concrete', recipes: ['kiln.material.stone.v1'] },- { slug: 'denim', asset: 'denim_fabric', label: 'Blue denim weave', recipes: ['kiln.material.cloth.v1'] },- { slug: 'rusted-metal', asset: 'rust_coarse_01', label: 'Coarse rusted metal', recipes: ['kiln.material.painted-metal.v1'] },- { slug: 'rock-face', asset: 'rock_face_03', label: 'Layered rock face', recipes: ['kiln.material.stone.v1'] },- { slug: 'dry-soil', asset: 'brown_mud_dry', label: 'Dry compacted soil', recipes: ['kiln.material.stone.v1'] },- { slug: 'brick-wall', asset: 'brick_wall_005', label: 'Weathered brick wall', recipes: ['kiln.material.stone.v1'] },- { slug: 'brown-leather', asset: 'brown_leather', label: 'Brown grained leather', recipes: ['kiln.material.skin.v1', 'kiln.material.cloth.v1'] },- { slug: 'forest-leaves', asset: 'forest_leaves_03', label: 'Forest leaf litter', recipes: ['kiln.material.leaf.v1'] },- { slug: 'rubber-tiles', asset: 'rubber_tiles', label: 'Studded rubber tiles', recipes: ['kiln.material.rubber.v1'] },- { slug: 'metal-plate', asset: 'metal_plate', label: 'Riveted steel plate', recipes: ['kiln.material.painted-metal.v1'] },- { slug: 'clay-roof-tiles', asset: 'clay_roof_tiles', label: 'Clay roof tiles', recipes: ['kiln.material.stone.v1'] },- { slug: 'cobblestone-floor', asset: 'cobblestone_floor_01', label: 'Cobblestone paving', recipes: ['kiln.material.stone.v1'] },- { slug: 'oak-veneer', asset: 'oak_veneer_01', label: 'Finished oak veneer', recipes: ['kiln.material.wood.v1'] },- { slug: 'polished-marble', asset: 'marble_01', label: 'Polished marble', recipes: ['kiln.material.stone.v1'] },+ {+ slug: 'bark-brown-01',+ asset: 'bark_brown_01',+ label: 'Brown furrowed bark',+ recipes: ['kiln.material.bark.v1', 'kiln.material.wood.v1'],+ },+ {+ slug: 'weathered-planks',+ asset: 'brown_planks_03',+ label: 'Weathered brown planks',+ recipes: ['kiln.material.wood.v1'],+ },+ {+ slug: 'rough-concrete',+ asset: 'rough_concrete',+ label: 'Rough concrete',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'denim',+ asset: 'denim_fabric',+ label: 'Blue denim weave',+ recipes: ['kiln.material.cloth.v1'],+ },+ {+ slug: 'rusted-metal',+ asset: 'rust_coarse_01',+ label: 'Coarse rusted metal',+ recipes: ['kiln.material.painted-metal.v1'],+ },+ {+ slug: 'rock-face',+ asset: 'rock_face_03',+ label: 'Layered rock face',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'dry-soil',+ asset: 'brown_mud_dry',+ label: 'Dry compacted soil',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'brick-wall',+ asset: 'brick_wall_005',+ label: 'Weathered brick wall',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'brown-leather',+ asset: 'brown_leather',+ label: 'Brown grained leather',+ recipes: ['kiln.material.skin.v1', 'kiln.material.cloth.v1'],+ },+ {+ slug: 'forest-leaves',+ asset: 'forest_leaves_03',+ label: 'Forest leaf litter',+ recipes: ['kiln.material.leaf.v1'],+ },+ {+ slug: 'rubber-tiles',+ asset: 'rubber_tiles',+ label: 'Studded rubber tiles',+ recipes: ['kiln.material.rubber.v1'],+ },+ {+ slug: 'metal-plate',+ asset: 'metal_plate',+ label: 'Riveted steel plate',+ recipes: ['kiln.material.painted-metal.v1'],+ },+ {+ slug: 'clay-roof-tiles',+ asset: 'clay_roof_tiles',+ label: 'Clay roof tiles',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'cobblestone-floor',+ asset: 'cobblestone_floor_01',+ label: 'Cobblestone paving',+ recipes: ['kiln.material.stone.v1'],+ },+ {+ slug: 'oak-veneer',+ asset: 'oak_veneer_01',+ label: 'Finished oak veneer',+ recipes: ['kiln.material.wood.v1'],+ },+ {+ slug: 'polished-marble',+ asset: 'marble_01',+ label: 'Polished marble',+ recipes: ['kiln.material.stone.v1'],+ },];const MAPS = [{ key: 'Diffuse', suffix: 'albedo', usage: 'albedo', colorSpace: 'srgb', slot: 'baseColor' },{ key: 'nor_gl', suffix: 'normal', usage: 'normal', colorSpace: 'linear', slot: 'normal' },- { key: 'arm', suffix: 'arm', usage: 'metallicRoughness', colorSpace: 'linear', slot: 'metallicRoughness' },+ {+ key: 'arm',+ suffix: 'arm',+ usage: 'metallicRoughness',+ colorSpace: 'linear',+ slot: 'metallicRoughness',+ },];const hash = (algorithm, bytes) => createHash(algorithm).update(bytes).digest('hex');@@ -78,7 +166,13 @@ for (const family of FAMILIES) {}const derived = await sharp(original).resize(TARGET_SIZE, TARGET_SIZE, { fit: 'fill', kernel: sharp.kernel.lanczos3 })- .png({ compressionLevel: 9, adaptiveFiltering: true, palette: map.suffix !== 'normal', colours: 256, quality: 90 })+ .png({+ compressionLevel: 9,+ adaptiveFiltering: true,+ palette: map.suffix !== 'normal',+ colours: 256,+ quality: 90,+ }).toBuffer();records.push({...family,@@ -93,7 +187,9 @@ for (const family of FAMILIES) {}const ids = records.map((record) => ` ${quote(record.id)},`).join('\n');-const descriptors = records.map((record) => ` ${quote(record.id)}: Object.freeze({+const descriptors = records+ .map(+ (record) => ` ${quote(record.id)}: Object.freeze({schemaVersion: 1,id: ${quote(record.id)},version: 1,@@ -112,15 +208,25 @@ const descriptors = records.map((record) => ` ${quote(record.id)}: Object.freez}),allowedSlots: Object.freeze([${quote(record.slot)}] as const),recipeIds: Object.freeze(${JSON.stringify(record.recipes)} as const),- }),`).join('\n');-const payloads = records.map((record) => ` ${quote(record.id)}:- ${wrappedBase64(record.bytes)},`).join('\n');-const provenance = records.map((record) => ` ${quote(record.id)}: Object.freeze({+ }),`,+ )+ .join('\n');+const payloads = records+ .map(+ (record) => ` ${quote(record.id)}:+ ${wrappedBase64(record.bytes)},`,+ )+ .join('\n');+const provenance = records+ .map(+ (record) => ` ${quote(record.id)}: Object.freeze({sourceAsset: ${quote(record.asset)},sourceUrl: ${quote(record.sourceUrl)},sourceMd5: ${quote(record.sourceMd5)},transform: ${quote(`sharp ${TARGET_SIZE}x${TARGET_SIZE} Lanczos3 PNG`)},- }),`).join('\n');+ }),`,+ )+ .join('\n');const total = records.reduce((sum, record) => sum + record.bytes.byteLength, 0);const generated = `/**@@ -151,4 +257,11 @@ ${provenance}await writeFile(OUTPUT, generated, 'utf8');execFileSync('bun', ['x', 'biome', 'format', '--write', OUTPUT], { stdio: 'inherit' });-console.log(JSON.stringify({ output: OUTPUT, families: FAMILIES.length, resources: records.length, embeddedBytes: total }));+console.log(+ JSON.stringify({+ output: OUTPUT,+ families: FAMILIES.length,+ resources: records.length,+ embeddedBytes: total,+ }),+);diff --git a/scripts/dispatch-asset.mjs b/scripts/dispatch-asset.mjsindex 4664d502..063c7f95 100644--- a/scripts/dispatch-asset.mjs+++ b/scripts/dispatch-asset.mjs@@ -31,7 +31,15 @@ import { HARNESSES, REPO, makeSandbox, parseDuration, run } from './harness.mjs'* script runs before anything is built and cannot import the TypeScript source.* `src/__tests__/dispatch-categories.test.ts` fails if the two ever drift.*/-const ASSET_CATEGORIES = ['prop', 'character', 'vfx', 'environment', 'architecture', 'vegetation', 'vehicle'];+const ASSET_CATEGORIES = [+ 'prop',+ 'character',+ 'vfx',+ 'environment',+ 'architecture',+ 'vegetation',+ 'vehicle',+];/*** Extra guidance appended to the brief, and EXPERIMENTAL -- read the entry for@@ -53,16 +61,20 @@ const ASSET_CATEGORIES = ['prop', 'character', 'vfx', 'environment', 'architectu* drop first.*/const CATEGORY_BRIEF = {- architecture: 'This is ARCHITECTURE. Get the mass and the storey rhythm right before any ornament: floor heights consistent, openings on a grid, a roof that meets its walls with a real eave rather than hovering. Repeated elements (bays, columns, windows) should be generated in a loop from one set of numbers so they stay aligned.',- character: 'This is a CHARACTER. Proportion beats detail: block the silhouette to a believable height first, then subdivide. Build it symmetric about the +X forward axis, standing on Y=0, in a neutral stance with limbs slightly away from the body so nothing interpenetrates.',- vegetation: 'This is VEGETATION. Nothing on a plant is straight or evenly spaced. Drive branching from a small recursive rule with varied angle and length rather than placing limbs by hand, taper every stem toward its tip, and let the crown be an irregular volume rather than a sphere.',- vehicle: 'This is a VEHICLE. It has to look like it works: wheels or tracks touching Y=0 and equally spaced, a cabin sized for whoever drives it, and a clear front. Build it along +X forward so it points the way the frame says it points.',- environment: 'This is an ENVIRONMENT piece. It will be placed among others, so keep the footprint honest and the origin sensible, and make the parts that meet the ground actually meet it.',+ architecture:+ 'This is ARCHITECTURE. Get the mass and the storey rhythm right before any ornament: floor heights consistent, openings on a grid, a roof that meets its walls with a real eave rather than hovering. Repeated elements (bays, columns, windows) should be generated in a loop from one set of numbers so they stay aligned.',+ character:+ 'This is a CHARACTER. Proportion beats detail: block the silhouette to a believable height first, then subdivide. Build it symmetric about the +X forward axis, standing on Y=0, in a neutral stance with limbs slightly away from the body so nothing interpenetrates.',+ vegetation:+ 'This is VEGETATION. Nothing on a plant is straight or evenly spaced. Drive branching from a small recursive rule with varied angle and length rather than placing limbs by hand, taper every stem toward its tip, and let the crown be an irregular volume rather than a sphere.',+ vehicle:+ 'This is a VEHICLE. It has to look like it works: wheels or tracks touching Y=0 and equally spaced, a cabin sized for whoever drives it, and a clear front. Build it along +X forward so it points the way the frame says it points.',+ environment:+ 'This is an ENVIRONMENT piece. It will be placed among others, so keep the footprint honest and the origin sensible, and make the parts that meet the ground actually meet it.',vfx: 'This is a VFX asset. It reads as motion and light rather than as an object: build it from layered, mostly emissive or transparent shells, keep the triangle count low, and make sure it looks right from every angle because a viewer will orbit it.',prop: '',};-function parseArgs(argv) {const opts = {harness: 'agy',@@ -129,7 +141,7 @@ function composePrompt({ name, subject, file, tris, animate, category }) {const motion = animate? ['- THIS ASSET MUST MOVE. Hang every moving part off a pivot: pass',- " `pivot: [x, y, z]` to createPart and name the part `Joint_<Thing>`, then",+ ' `pivot: [x, y, z]` to createPart and name the part `Joint_<Thing>`, then',' parent the geometry that turns with it to that joint.','- Export `function animate()` returning'," [createClip(name, duration, [rotationTrack('Joint_X', keys), ...])].",@@ -167,7 +179,11 @@ function composePrompt({ name, subject, file, tris, animate, category }) {].join('\n');}-const toPascal = (s) => s.split(/[-_\s]+/).map((w) => w[0].toUpperCase() + w.slice(1)).join('');+const toPascal = (s) =>+ s+ .split(/[-_\s]+/)+ .map((w) => w[0].toUpperCase() + w.slice(1))+ .join('');/*** Record the author in the file itself.@@ -216,8 +232,7 @@ function stampAuthor(file, model, harness, { cleanRoom = true, interrupted = fal// `session limit` is Claude Code's wording and matches none of the others, so a// batch that hit one used to report three flat failures in a row and give up// instead of falling back or waiting out the window.-const RATE_LIMITED =- /RESOURCE_EXHAUSTED|429|rate.?limit|quota|exhausted|(session|usage) limit/i;+const RATE_LIMITED = /RESOURCE_EXHAUSTED|429|rate.?limit|quota|exhausted|(session|usage) limit/i;const sleep = (ms) => new Promise((r) => setTimeout(r, ms));/**@@ -268,19 +283,29 @@ async function main() {// Built from the table rather than typed out: the list drifted once// already, and omitted the harness that had written six of the gallery.const names = Object.keys(HARNESSES).join('|');- console.error(`usage: dispatch-asset.mjs [--harness ${names}] [--model M] [--category ${ASSET_CATEGORIES.join('|')}] --name <slug> "<subject>"`);+ console.error(+ `usage: dispatch-asset.mjs [--harness ${names}] [--model M] [--category ${ASSET_CATEGORIES.join('|')}] --name <slug> "<subject>"`,+ );process.exit(2);}- opts.name ??= opts.subject.toLowerCase().replaceAll(/[^a-z0-9]+/g, '-').slice(0, 40);+ opts.name ??= opts.subject+ .toLowerCase()+ .replaceAll(/[^a-z0-9]+/g, '-')+ .slice(0, 40);- const models = [opts.model ?? harness.defaultModel, ...(opts.model ? [] : harness.fallbackModels)];+ const models = [+ opts.model ?? harness.defaultModel,+ ...(opts.model ? [] : harness.fallbackModels),+ ];// Checked before anything is created on disk. A harness with no default model// (Codex, whose entitlements this repository cannot know) must be told one:// this path stamps the author into the program and writes it into the// gallery's provenance note, and an asset whose author cannot be named is one// that already shipped once reading "Authored by: null".if (models[0] == null) {- console.error(`--model is required for the ${opts.harness} harness: it has no default, and the author has to be recorded`);+ console.error(+ `--model is required for the ${opts.harness} harness: it has no default, and the author has to be recorded`,+ );process.exit(2);}@@ -312,12 +337,16 @@ async function main() {}process.stdout.write(`[${opts.name}] ${opts.harness} / ${model} ... `);const started = Date.now();- result = await run(harness.bin, harness.argv({ model, prompt, timeout: opts.timeout, logFile, sandbox }), {- logFile,- cwd: sandbox,- timeoutMs: parseDuration(opts.timeout),- env: harness.env?.({ model }) ?? null,- });+ result = await run(+ harness.bin,+ harness.argv({ model, prompt, timeout: opts.timeout, logFile, sandbox }),+ {+ logFile,+ cwd: sandbox,+ timeoutMs: parseDuration(opts.timeout),+ env: harness.env?.({ model }) ?? null,+ },+ );const secs = ((Date.now() - started) / 1000).toFixed(0);if (result.code === 0 && existsSync(sandboxFile)) {console.log(`wrote ${opts.name}.kiln.js in ${secs}s`);@@ -356,7 +385,9 @@ async function main() {break outer;}if (Date.now() >= deadline) break;- console.log(`[${opts.name}] all models rate limited; waiting 10 min (giving up at ${new Date(deadline).toLocaleTimeString()})`);+ console.log(+ `[${opts.name}] all models rate limited; waiting 10 min (giving up at ${new Date(deadline).toLocaleTimeString()})`,+ );await sleep(10 * 60_000);}writeFileSync(join(opts.outDir, `${opts.name}.log`), result?.out ?? '');@@ -379,24 +410,28 @@ async function main() {// this" is not something you can reconstruct later from the file itself.writeFileSync(join(opts.outDir, `${opts.name}.result.json`),- `${JSON.stringify({- name: opts.name,- subject: opts.subject,- harness: opts.harness,- model: authoredBy,- // Recorded rather than assumed: the gallery's provenance note is written- // from this field, and assets predating the sandbox must not inherit a- // claim about isolation they never had.- cleanRoom: true,- // Set when a provider limit ended the session with a program already- // written. `promote-asset.mjs` reads it, because an asset whose authoring- // loop was cut short must not carry a header claiming the loop ran.- interrupted,- at: new Date().toISOString(),- tris: /(\d+) tris/.exec(check.out)?.[1] ?? null,- bounds: /bounds\s+(.+)/.exec(check.out)?.[1]?.trim() ?? null,- rendered: check.code === 0,- }, null, 2)}+ `${JSON.stringify(+ {+ name: opts.name,+ subject: opts.subject,+ harness: opts.harness,+ model: authoredBy,+ // Recorded rather than assumed: the gallery's provenance note is written+ // from this field, and assets predating the sandbox must not inherit a+ // claim about isolation they never had.+ cleanRoom: true,+ // Set when a provider limit ended the session with a program already+ // written. `promote-asset.mjs` reads it, because an asset whose authoring+ // loop was cut short must not carry a header claiming the loop ran.+ interrupted,+ at: new Date().toISOString(),+ tris: /(\d+) tris/.exec(check.out)?.[1] ?? null,+ bounds: /bounds\s+(.+)/.exec(check.out)?.[1]?.trim() ?? null,+ rendered: check.code === 0,+ },+ null,+ 2,+ )}`,);process.exit(check.code === 0 ? 0 : 1);diff --git a/scripts/dogfood-collections.mjs b/scripts/dogfood-collections.mjsindex ef2fdd6d..ddfa28ad 100644--- a/scripts/dogfood-collections.mjs+++ b/scripts/dogfood-collections.mjs@@ -8,21 +8,44 @@ import { createWorkspace } from './create-workspace.mjs';import { HARNESSES, run } from './harness.mjs';const choices = {- codex: { model: null, subject: 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.' },- claude: { model: 'sonnet', subject: 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.' },- opencode: { model: 'opencode-go/glm-5.3-flash', subject: 'A compact botanical research trolley: four rubber wheels touching the ground, a lower tray, two planted specimen containers with distinct broad leaf silhouettes, a small articulated inspection lamp, and a clipped-on instrument panel. Sage green powder-coated frame, terracotta pots, warm ivory instrument. A coherent finished prop for a stylized exploration game, about 90 cm tall.' },- agy: { model: 'gemini-3.8-flash-high', subject: 'A tabletop mechanical orrery: stepped circular pedestal, a tilted brass orbital ring held by a real bracket, a central sun sphere, and three planets on distinct supported radial arms at different radii. Midnight blue enamel and warm brass. A coherent finished prop for a stylized exploration game, about 45 cm tall. Include a slow looping orbit animation if you can review its intermediate poses.' },+ codex: {+ model: null,+ subject:+ 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.',+ },+ claude: {+ model: 'sonnet',+ subject:+ 'A portable field recording machine: two exposed tape reels, a sloped control panel with distinct knobs and VU meters, a sturdy carry handle, rubber feet, and a removable-looking protective frame. Warm ivory panels, dark graphite case, restrained orange details. A coherent finished prop for a stylized exploration game, about 40 cm wide.',+ },+ opencode: {+ model: 'opencode-go/glm-5.3-flash',+ subject:+ 'A compact botanical research trolley: four rubber wheels touching the ground, a lower tray, two planted specimen containers with distinct broad leaf silhouettes, a small articulated inspection lamp, and a clipped-on instrument panel. Sage green powder-coated frame, terracotta pots, warm ivory instrument. A coherent finished prop for a stylized exploration game, about 90 cm tall.',+ },+ agy: {+ model: 'gemini-3.8-flash-high',+ subject:+ 'A tabletop mechanical orrery: stepped circular pedestal, a tilted brass orbital ring held by a real bracket, a central sun sphere, and three planets on distinct supported radial arms at different radii. Midnight blue enamel and warm brass. A coherent finished prop for a stylized exploration game, about 45 cm tall. Include a slow looping orbit animation if you can review its intermediate poses.',+ },};-const harnessName = process.argv[2]; const choice = choices[harnessName];-if (!choice) throw new Error('Choose claude, codex, opencode, or agy. This command spends model quota.');-const stamp = new Date().toISOString().replaceAll(':','-').replaceAll('.','-');-const output = resolve('.dogfood','collections',`${stamp}-${harnessName}`); await mkdir(output,{recursive:true});-const parent = await mkdtemp(join(tmpdir(),'kiln-collections-dogfood-')); const workspace = join(parent,'workspace');-await createWorkspace(workspace,harnessName);-const base = JSON.parse(await readFile(join(workspace,'.kiln','workspace.json'),'utf8'));-const sourceStore = join(workspace,'.kiln','programs');-const roots = { project: join(workspace,'assets','kiln'), personal: join(workspace,'personal-library') };-await writeFile(join(workspace,'.kiln','collections.json'),JSON.stringify(roots,null,2));+const harnessName = process.argv[2];+const choice = choices[harnessName];+if (!choice)+ throw new Error('Choose claude, codex, opencode, or agy. This command spends model quota.');+const stamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-');+const output = resolve('.dogfood', 'collections', `${stamp}-${harnessName}`);+await mkdir(output, { recursive: true });+const parent = await mkdtemp(join(tmpdir(), 'kiln-collections-dogfood-'));+const workspace = join(parent, 'workspace');+await createWorkspace(workspace, harnessName);+const base = JSON.parse(await readFile(join(workspace, '.kiln', 'workspace.json'), 'utf8'));+const sourceStore = join(workspace, '.kiln', 'programs');+const roots = {+ project: join(workspace, 'assets', 'kiln'),+ personal: join(workspace, 'personal-library'),+};+await writeFile(join(workspace, '.kiln', 'collections.json'), JSON.stringify(roots, null, 2));const prompt = ['Read this workspace AGENTS.md and skills/kiln-author-asset/SKILL.md. Use only the configured kiln_workspace server. Do not read the engine source or example collection. Do not install software, publish, or use another agent.',`Make this asset: ${choice.subject}`,@@ -31,27 +54,111 @@ const prompt = ['Then exercise the new workflow: kiln_assets list; kiln_export; kiln_import copying the saved revision from project to personal; kiln_assets restore from personal. Make one small intentional dimension/detail refinement with kiln_edit and save the child into personal with the original assetId and parentRevision. Export the child resource links. Preserve both revisions.','Write dogfood-result.json with assetId, originalRevisionId, refinedRevisionId, programRefs, review observations, any tool/UX issues, and whether render images were actually visible to you. Use the host Write tool for this report. Finish within 10 minutes. Never spend the whole time polishing; leave time to test save/copy/restore/refine.',].join(' ');-await writeFile(join(output,'brief.txt'),prompt);-const harness = HARNESSES[harnessName]; const logFile = join(output,'harness.log');-let args = harness.argv({model:choice.model,prompt,timeout:'10m',logFile,sandbox:workspace});-if (harnessName === 'claude') args = ['-p',prompt,'--model',choice.model,'--permission-mode','acceptEdits','--strict-mcp-config','--mcp-config',join(workspace,'.mcp.json'),'--allowedTools','mcp__kiln_workspace__* Read Write Edit Glob Grep','--output-format','stream-json','--verbose'];-if (harnessName === 'agy') args = ['--new-project',...args,'--disable-slash-commands'];-console.log(JSON.stringify({harness:harnessName,requestedModel:choice.model,workspace,output}));-await writeFile(join(output,'run.json'),JSON.stringify({harness:harnessName,requestedModel:choice.model,workspace,output,workspaceSetup:base,startedAt:new Date().toISOString(),authorization:'User requested different harness/model dogfoods after implementing collections.',renderer:'cpu',runtimeBuild:JSON.parse(await readFile('dist/build.json','utf8'))},null,2));-const result = await run(harness.bin,args,{cwd:workspace,timeoutMs:10*60*1000,logFile:harness.needsLogFile?logFile:null,env:{KILN_RENDER:'cpu',KILN_PROGRAM_STORE:sourceStore,KILN_COLLECTIONS:JSON.stringify(roots),...(harness.env?.({model:choice.model}) ?? {})}});-await writeFile(join(output,'transcript.txt'),result.out);-await cp(workspace,join(output,'workspace'),{recursive:true,filter:path=>!path.includes('node_modules')&&!path.includes(`${join('.kiln','cache')}`)});+await writeFile(join(output, 'brief.txt'), prompt);+const harness = HARNESSES[harnessName];+const logFile = join(output, 'harness.log');+let args = harness.argv({+ model: choice.model,+ prompt,+ timeout: '10m',+ logFile,+ sandbox: workspace,+});+if (harnessName === 'claude')+ args = [+ '-p',+ prompt,+ '--model',+ choice.model,+ '--permission-mode',+ 'acceptEdits',+ '--strict-mcp-config',+ '--mcp-config',+ join(workspace, '.mcp.json'),+ '--allowedTools',+ 'mcp__kiln_workspace__* Read Write Edit Glob Grep',+ '--output-format',+ 'stream-json',+ '--verbose',+ ];+if (harnessName === 'agy') args = ['--new-project', ...args, '--disable-slash-commands'];+console.log(+ JSON.stringify({ harness: harnessName, requestedModel: choice.model, workspace, output }),+);+await writeFile(+ join(output, 'run.json'),+ JSON.stringify(+ {+ harness: harnessName,+ requestedModel: choice.model,+ workspace,+ output,+ workspaceSetup: base,+ startedAt: new Date().toISOString(),+ authorization:+ 'User requested different harness/model dogfoods after implementing collections.',+ renderer: 'cpu',+ runtimeBuild: JSON.parse(await readFile('dist/build.json', 'utf8')),+ },+ null,+ 2,+ ),+);+const result = await run(harness.bin, args, {+ cwd: workspace,+ timeoutMs: 10 * 60 * 1000,+ logFile: harness.needsLogFile ? logFile : null,+ env: {+ KILN_RENDER: 'cpu',+ KILN_PROGRAM_STORE: sourceStore,+ KILN_COLLECTIONS: JSON.stringify(roots),+ ...(harness.env?.({ model: choice.model }) ?? {}),+ },+});+await writeFile(join(output, 'transcript.txt'), result.out);+await cp(workspace, join(output, 'workspace'), {+ recursive: true,+ filter: (path) => !path.includes('node_modules') && !path.includes(`${join('.kiln', 'cache')}`),+});const manifests = [];for (const [collection, directory] of Object.entries(roots)) {- for (const asset of await readdir(directory).catch(()=>[])) {- for (const revision of await readdir(join(directory,asset,'revisions')).catch(()=>[])) {- try { const record = JSON.parse(await readFile(join(directory,asset,'revisions',revision,'manifest.json'),'utf8')); manifests.push({collection,record}); } catch {}+ for (const asset of await readdir(directory).catch(() => [])) {+ for (const revision of await readdir(join(directory, asset, 'revisions')).catch(() => [])) {+ try {+ const record = JSON.parse(+ await readFile(join(directory, asset, 'revisions', revision, 'manifest.json'), 'utf8'),+ );+ manifests.push({ collection, record });+ } catch {}}}}let actualModel = harness.actualModel?.(result.out) ?? null;if (harnessName === 'codex') actualModel = /^model:\s*(.+)$/m.exec(result.out)?.[1]?.trim() ?? null;-if (harnessName === 'claude') for (const line of result.out.split('\n')) { try { const item=JSON.parse(line); if(item.type==='system'&&item.subtype==='init') actualModel=item.model; } catch {} }-const summary = {harness:harnessName,requestedModel:choice.model,actualModel,exitCode:result.code,finishedAt:new Date().toISOString(),savedRevisions:manifests.map(({collection,record})=>({collection,name:record.name,assetId:record.assetId,revisionId:record.revisionId,parentRevision:record.parentRevision,artifactHash:record.files['asset.glb'].sha256})),transcriptHash:createHash('sha256').update(result.out).digest('hex'),output};-await writeFile(join(output,'result.json'),JSON.stringify(summary,null,2)); console.log(JSON.stringify(summary));+if (harnessName === 'claude')+ for (const line of result.out.split('\n')) {+ try {+ const item = JSON.parse(line);+ if (item.type === 'system' && item.subtype === 'init') actualModel = item.model;+ } catch {}+ }+const summary = {+ harness: harnessName,+ requestedModel: choice.model,+ actualModel,+ exitCode: result.code,+ finishedAt: new Date().toISOString(),+ savedRevisions: manifests.map(({ collection, record }) => ({+ collection,+ name: record.name,+ assetId: record.assetId,+ revisionId: record.revisionId,+ parentRevision: record.parentRevision,+ artifactHash: record.files['asset.glb'].sha256,+ })),+ transcriptHash: createHash('sha256').update(result.out).digest('hex'),+ output,+};+await writeFile(join(output, 'result.json'), JSON.stringify(summary, null, 2));+console.log(JSON.stringify(summary));process.exitCode = result.code === 0 && manifests.length >= 3 ? 0 : 1;diff --git a/scripts/evaluation/conditions.test.ts b/scripts/evaluation/conditions.test.tsindex 9b062a95..824cfa2f 100644--- a/scripts/evaluation/conditions.test.ts+++ b/scripts/evaluation/conditions.test.ts@@ -2,35 +2,62 @@ import { expect, test } from 'bun:test';import { createConditionRegistry, assertConditionSource } from './conditions';test('A/B deny new helper access through aliases but permit raw THREE and harmless strings', () => {- expect(() => assertConditionSource('const f = meshGeo; f({positions:[]});', 'A')).toThrow('condition-policy');- expect(() => assertConditionSource('const f = parametricSurface;', 'B')).toThrow('condition-policy');- expect(() => assertConditionSource('const s="meshGeo"; const g=new THREE.BufferGeometry();', 'B')).not.toThrow();+ expect(() => assertConditionSource('const f = meshGeo; f({positions:[]});', 'A')).toThrow(+ 'condition-policy',+ );+ expect(() => assertConditionSource('const f = parametricSurface;', 'B')).toThrow(+ 'condition-policy',+ );+ expect(() =>+ assertConditionSource('const s="meshGeo"; const g=new THREE.BufferGeometry();', 'B'),+ ).not.toThrow();expect(() => assertConditionSource('meshGeo({positions:[]});', 'C')).not.toThrow();});test('A hides progressive lookup and advanced camera fields; B retains them', async () => {const a = createConditionRegistry('A');const b = createConditionRegistry('B');const discovery = a.find((d) => d.name === 'kiln_list_primitives')!;- expect(discovery.inputSchema.safeParse({query:'holes'}).success).toBe(false);- const output = await b.find((d) => d.name === 'kiln_list_primitives')!.run({name:'meshGeo'});- expect((output as {total:number}).total).toBe(0);+ expect(discovery.inputSchema.safeParse({ query: 'holes' }).success).toBe(false);+ const output = await b.find((d) => d.name === 'kiln_list_primitives')!.run({ name: 'meshGeo' });+ expect((output as { total: number }).total).toBe(0);const render = a.find((d) => d.name === 'kiln_render')!;- expect(render.inputSchema.safeParse({code:'x',capture:{version:'kiln.capture.v1',shots:[{}]}}).success).toBe(false);+ expect(+ render.inputSchema.safeParse({+ code: 'x',+ capture: { version: 'kiln.capture.v1', shots: [{}] },+ }).success,+ ).toBe(false);});test('all conditions preserve public source-reference tool names and C exposes new helpers', async () => {- const rows = ['A','B','C'].map((condition) => createConditionRegistry(condition as 'A'|'B'|'C'));- expect(rows[0]!.map((d)=>d.name)).toEqual(rows[2]!.map((d)=>d.name));- const output = await rows[2]!.find((d)=>d.name==='kiln_list_primitives')!.run({name:'meshGeo'});- expect((output as {total:number}).total).toBe(1);+ const rows = ['A', 'B', 'C'].map((condition) =>+ createConditionRegistry(condition as 'A' | 'B' | 'C'),+ );+ expect(rows[0]!.map((d) => d.name)).toEqual(rows[2]!.map((d) => d.name));+ const output = await rows[2]!+ .find((d) => d.name === 'kiln_list_primitives')!+ .run({ name: 'meshGeo' });+ expect((output as { total: number }).total).toBe(1);});test('reference edits cannot bypass the disabled-helper policy at evaluation', async () => {- const definitions=createConditionRegistry('B');- const code="const meta={name:'Box',category:'prop'};function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r});return r;}";- const render=definitions.find((entry)=>entry.name==='kiln_render')!;- const first=await render.run({code,capture:{preset:'1x1'}}) as {ok:boolean;programRef:string};+ const definitions = createConditionRegistry('B');+ const code =+ "const meta={name:'Box',category:'prop'};function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r});return r;}";+ const render = definitions.find((entry) => entry.name === 'kiln_render')!;+ const first = (await render.run({ code, capture: { preset: '1x1' } })) as {+ ok: boolean;+ programRef: string;+ };expect(first.ok).toBe(true);- const edited=await definitions.find((entry)=>entry.name==='kiln_edit')!.run({programRef:first.programRef,edits:[{oldString:'boxGeo(1,1,1)',newString:'meshGeo({positions:[0,0,0,1,0,0,0,1,0]})'}],capture:{preset:'1x1'}}) as {ok:boolean;programRef:string;render:{ok:boolean;error:string}};+ const edited = (await definitions+ .find((entry) => entry.name === 'kiln_edit')!+ .run({+ programRef: first.programRef,+ edits: [+ { oldString: 'boxGeo(1,1,1)', newString: 'meshGeo({positions:[0,0,0,1,0,0,0,1,0]})' },+ ],+ capture: { preset: '1x1' },+ })) as { ok: boolean; programRef: string; render: { ok: boolean; error: string } };expect(edited.ok).toBe(true);expect(edited.render.ok).toBe(false);expect(JSON.stringify(edited)).toContain('condition-policy');@@ -38,8 +65,10 @@ test('reference edits cannot bypass the disabled-helper policy at evaluation', a});test('B grouped lookup preserves requested order without advertising disabled helpers', async () => {- const lookup=createConditionRegistry('B').find(d=>d.name==='kiln_list_primitives')!;- const result=await lookup.run({names:['sphereGeo','boxGeo']}) as {primitives:Array<{name:string}>};- expect(result.primitives.map(x=>x.name)).toEqual(['sphereGeo','boxGeo']);- await expect(lookup.run({names:['boxGeo','meshGeo']})).rejects.toThrow('Unknown');+ const lookup = createConditionRegistry('B').find((d) => d.name === 'kiln_list_primitives')!;+ const result = (await lookup.run({ names: ['sphereGeo', 'boxGeo'] })) as {+ primitives: Array<{ name: string }>;+ };+ expect(result.primitives.map((x) => x.name)).toEqual(['sphereGeo', 'boxGeo']);+ await expect(lookup.run({ names: ['boxGeo', 'meshGeo'] })).rejects.toThrow('Unknown');});diff --git a/scripts/evaluation/conditions.ts b/scripts/evaluation/conditions.tsindex 5bcb35f5..3f96c55e 100644--- a/scripts/evaluation/conditions.ts+++ b/scripts/evaluation/conditions.ts@@ -5,7 +5,11 @@ import { z } from 'zod';import { geometryPrimitives } from '../../src/geometry-catalog';import { listPrimitives } from '../../src/list-primitives';import { resolveEvaluatorPortV1 } from '../../src/evaluator/protocol';-import { createKilnProgramToolRegistry, type KilnToolContext, type KilnToolDef } from '../../src/tools/registry';+import {+ createKilnProgramToolRegistry,+ type KilnToolContext,+ type KilnToolDef,+} from '../../src/tools/registry';export type Condition = 'A' | 'B' | 'C';export const disabledHelperNames = geometryPrimitives.map((entry) => entry.name).sort();@@ -14,83 +18,193 @@ export const disabledHelperNames = geometryPrimitives.map((entry) => entry.name)export function assertConditionSource(code: string, condition: Condition): void {if (condition === 'C') return;const disabled = new Set(disabledHelperNames);- const file = parse(code, {ecmaVersion:'latest', sourceType:'script', allowAwaitOutsideFunction:true});+ const file = parse(code, {+ ecmaVersion: 'latest',+ sourceType: 'script',+ allowAwaitOutsideFunction: true,+ });full(file, (node) => {if (node.type === 'Identifier' && disabled.has(node.name))- throw new Error(`condition-policy: ${node.name} is unavailable in condition ${condition}. Use the supplied catalog or ordinary THREE geometry.`);+ throw new Error(+ `condition-policy: ${node.name} is unavailable in condition ${condition}. Use the supplied catalog or ordinary THREE geometry.`,+ );});}-const legacyCapture = z.object({- preset: z.enum(['1x1', '1x2', '2x1', '3x1', '2x2', '3x2', '3x3']).optional(),- cells: z.array(z.object({ azimuthDeg: z.number(), elevationDeg: z.number(), zoom: z.number().positive().optional(), name: z.string().optional() }).strict()).min(1).max(9).optional(),-}).strict();+const legacyCapture = z+ .object({+ preset: z.enum(['1x1', '1x2', '2x1', '3x1', '2x2', '3x2', '3x3']).optional(),+ cells: z+ .array(+ z+ .object({+ azimuthDeg: z.number(),+ elevationDeg: z.number(),+ zoom: z.number().positive().optional(),+ name: z.string().optional(),+ })+ .strict(),+ )+ .min(1)+ .max(9)+ .optional(),+ })+ .strict();function conditionDiscovery(def: KilnToolDef, condition: Condition): KilnToolDef {if (condition === 'C') return def;- const schema = condition === 'A' ? z.object({category:z.string().optional()}).strict() : def.inputSchema;+ const schema =+ condition === 'A' ? z.object({ category: z.string().optional() }).strict() : def.inputSchema;const entries = listPrimitives().filter((entry) => !disabledHelperNames.includes(entry.name));return {...def,- description: condition === 'A' ? 'List available Kiln helpers with signatures and examples. Optionally filter by category.' : def.description,+ description:+ condition === 'A'+ ? 'List available Kiln helpers with signatures and examples. Optionally filter by category.'+ : def.description,inputSchema: schema,run: async (value) => {- const input = schema.parse(value) as {category?:string;query?:string;name?:string;names?:string[];overview?:boolean;capabilities?:boolean;offset?:number;limit?:number};+ const input = schema.parse(value) as {+ category?: string;+ query?: string;+ name?: string;+ names?: string[];+ overview?: boolean;+ capabilities?: boolean;+ offset?: number;+ limit?: number;+ };if (input.capabilities) {- const output = await def.run(input) as {capabilities:Record<string,unknown>};- const capabilities = {...output.capabilities,geometry:{...(output.capabilities.geometry as object),newHelpers:false,implicitSurfaces:'unavailable in this condition'}};- return {capabilities,text:`Capabilities\n${JSON.stringify(capabilities,null,2)}`};+ const output = (await def.run(input)) as { capabilities: Record<string, unknown> };+ const capabilities = {+ ...output.capabilities,+ geometry: {+ ...(output.capabilities.geometry as object),+ newHelpers: false,+ implicitSurfaces: 'unavailable in this condition',+ },+ };+ return { capabilities, text: `Capabilities\n${JSON.stringify(capabilities, null, 2)}` };}- const matches = input.names ? input.names.map((name)=>{- const entry=entries.find((candidate)=>candidate.name.toLowerCase()===name.toLowerCase());- if (!entry) throw new Error(`Unknown helper in this condition: ${name}`);- return entry;- }) : entries.filter((entry) => (!input.category || entry.category === input.category.toLowerCase()) && (!input.name || entry.name.toLowerCase() === input.name.toLowerCase()) && (input.query?.toLowerCase().split(/\s+/) ?? []).every((word) => `${entry.name} ${entry.signature} ${entry.description} ${entry.example} ${entry.promptNotes ?? ''}`.toLowerCase().includes(word)));+ const matches = input.names+ ? input.names.map((name) => {+ const entry = entries.find(+ (candidate) => candidate.name.toLowerCase() === name.toLowerCase(),+ );+ if (!entry) throw new Error(`Unknown helper in this condition: ${name}`);+ return entry;+ })+ : entries.filter(+ (entry) =>+ (!input.category || entry.category === input.category.toLowerCase()) &&+ (!input.name || entry.name.toLowerCase() === input.name.toLowerCase()) &&+ (input.query?.toLowerCase().split(/\s+/) ?? []).every((word) =>+ `${entry.name} ${entry.signature} ${entry.description} ${entry.example} ${entry.promptNotes ?? ''}`+ .toLowerCase()+ .includes(word),+ ),+ );const categories = [...new Set(entries.map((entry) => entry.category))].sort();- const overview = condition === 'B' && (input.overview ?? !(input.name || input.names || input.query || input.category || input.offset || input.limit));- const offset = condition === 'A' ? 0 : input.offset ?? 0;- const selected = overview || condition === 'A' ? matches : matches.slice(offset,offset+(input.limit ?? 6));- const nextOffset = overview || offset + selected.length >= matches.length ? null : offset+selected.length;+ const overview =+ condition === 'B' &&+ (input.overview ??+ !(+ input.name ||+ input.names ||+ input.query ||+ input.category ||+ input.offset ||+ input.limit+ ));+ const offset = condition === 'A' ? 0 : (input.offset ?? 0);+ const selected =+ overview || condition === 'A'+ ? matches+ : matches.slice(offset, offset + (input.limit ?? 6));+ const nextOffset =+ overview || offset + selected.length >= matches.length ? null : offset + selected.length;const text = overview? [- 'Kiln helper overview. Use name for a signature/example, query for an operation, or category to browse.',- ...categories.map((category) => `${category}: ${matches.filter((entry)=>entry.category===category).map((entry)=>entry.name).join(', ')}`),- 'Ordinary THREE.BufferGeometry and source functions are available. Send code once and reuse programRef. Use capture version kiln.capture.v1 for exact part paths, part-relative cameras, projection and separate images. Check viewFidelity before judging materials.',- ].join('\n\n')- : [`${matches.length} matching helpers.`, ...selected.map((entry)=>`${entry.signature} -> ${entry.returns}\n${entry.description}\ne.g. ${entry.example}${entry.promptNotes ? `\nNote: ${entry.promptNotes}` : ''}`), ...(nextOffset === null ? [] : [`More results: offset:${nextOffset}.`])].join('\n\n');- return { primitives:selected, total:matches.length, nextOffset,categories,text };+ 'Kiln helper overview. Use name for a signature/example, query for an operation, or category to browse.',+ ...categories.map(+ (category) =>+ `${category}: ${matches+ .filter((entry) => entry.category === category)+ .map((entry) => entry.name)+ .join(', ')}`,+ ),+ 'Ordinary THREE.BufferGeometry and source functions are available. Send code once and reuse programRef. Use capture version kiln.capture.v1 for exact part paths, part-relative cameras, projection and separate images. Check viewFidelity before judging materials.',+ ].join('\n\n')+ : [+ `${matches.length} matching helpers.`,+ ...selected.map(+ (entry) =>+ `${entry.signature} -> ${entry.returns}\n${entry.description}\ne.g. ${entry.example}${entry.promptNotes ? `\nNote: ${entry.promptNotes}` : ''}`,+ ),+ ...(nextOffset === null ? [] : [`More results: offset:${nextOffset}.`]),+ ].join('\n\n');+ return { primitives: selected, total: matches.length, nextOffset, categories, text };},};}-export function createConditionRegistry(condition: Condition, context: KilnToolContext = {}): KilnToolDef[] {- const evaluator = resolveEvaluatorPortV1(context.evaluatorPort, context.evaluatorProfile ?? 'trusted-local');+export function createConditionRegistry(+ condition: Condition,+ context: KilnToolContext = {},+): KilnToolDef[] {+ const evaluator = resolveEvaluatorPortV1(+ context.evaluatorPort,+ context.evaluatorProfile ?? 'trusted-local',+ );const registry = createKilnProgramToolRegistry({...context,// Separate evaluator identities keep experimental conditions from sharing admission state.evaluatorCacheIdentity: undefined,- evaluatorPort: { render: (code,options,controls) => { assertConditionSource(code,condition); return evaluator.render(code,options,controls); } },+ evaluatorPort: {+ render: (code, options, controls) => {+ assertConditionSource(code, condition);+ return evaluator.render(code, options, controls);+ },+ },});// This frozen authoring experiment predates collections. Keep the same eight// verbs in each condition so storage tools cannot change its measured context.- return registry.filter(def => !['kiln_save','kiln_assets','kiln_export','kiln_import','kiln_present'].includes(def.name)).map((def) => {- if (def.name === 'kiln_list_primitives') return conditionDiscovery(def,condition);- let schema = def.inputSchema;- if (condition === 'A' && schema instanceof z.ZodObject) {- const overrides: Record<string,z.ZodType> = {};- if ('capture' in schema.shape) overrides.capture = legacyCapture.optional();- for (const name of ['shot','anchors','frameTimes','framing']) if (name in schema.shape) overrides[name] = z.never().optional();- schema = schema.safeExtend(overrides);- }- return { ...def,- inputSchema:schema,- description:condition === 'A' && ['kiln_render','kiln_edit','kiln_inspect','kiln_screenshot_animation','kiln_view_interior'].includes(def.name)- ? `${def.name}: build, edit or inspect the supplied code or saved programRef using the legacy view controls in this schema. Check viewFidelity before judging materials. Use kiln_source to read saved revisions.` : def.description,- run: async (value) => {- const input = schema.parse(value) as Record<string,unknown>;- if (typeof input.code === 'string') assertConditionSource(input.code,condition);- return def.run(input);- },- };- });+ return registry+ .filter(+ (def) =>+ !['kiln_save', 'kiln_assets', 'kiln_export', 'kiln_import', 'kiln_present'].includes(+ def.name,+ ),+ )+ .map((def) => {+ if (def.name === 'kiln_list_primitives') return conditionDiscovery(def, condition);+ let schema = def.inputSchema;+ if (condition === 'A' && schema instanceof z.ZodObject) {+ const overrides: Record<string, z.ZodType> = {};+ if ('capture' in schema.shape) overrides.capture = legacyCapture.optional();+ for (const name of ['shot', 'anchors', 'frameTimes', 'framing'])+ if (name in schema.shape) overrides[name] = z.never().optional();+ schema = schema.safeExtend(overrides);+ }+ return {+ ...def,+ inputSchema: schema,+ description:+ condition === 'A' &&+ [+ 'kiln_render',+ 'kiln_edit',+ 'kiln_inspect',+ 'kiln_screenshot_animation',+ 'kiln_view_interior',+ ].includes(def.name)+ ? `${def.name}: build, edit or inspect the supplied code or saved programRef using the legacy view controls in this schema. Check viewFidelity before judging materials. Use kiln_source to read saved revisions.`+ : def.description,+ run: async (value) => {+ const input = schema.parse(value) as Record<string, unknown>;+ if (typeof input.code === 'string') assertConditionSource(input.code, condition);+ return def.run(input);+ },+ };+ });}diff --git a/scripts/evaluation/dispatch.mjs b/scripts/evaluation/dispatch.mjsindex 3ea63822..8409f720 100644--- a/scripts/evaluation/dispatch.mjs+++ b/scripts/evaluation/dispatch.mjs@@ -4,70 +4,275 @@ import { join, resolve } from 'node:path';import { pathToFileURL } from 'node:url';import { createHash } from 'node:crypto';import { spawn } from 'node:child_process';-const base=process.argv[2] ? resolve(process.argv[2]) : '';-if (!base || process.argv[3]!=='--run-authorized-pilot') throw new Error('Usage: node scripts/evaluation/dispatch.mjs FROZEN_DIRECTORY --run-authorized-pilot. This dispatches up to 12 live model calls plus their same-session follow-ups; authorization must already be recorded.');-const freeze=JSON.parse(await readFile(join(base,'freeze.json'),'utf8'));-const bun='C:/Users/Mattm/.bun/bin/bun.exe',node='C:/Program Files/nodejs/node.exe';-const sha=x=>'sha256:'+createHash('sha256').update(x).digest('hex');-const followup='Use the saved revision. Read only the source section you need, increase `serviceOffset` by 0.15 metres, and render the edit by reference. Keep unrelated source unchanged. Show the named `ServiceAssembly` closely enough to check its attachment and in a wider view that establishes its location. Use the camera controls available in this condition. Sample the translation animation before, during and after its movement to check that attached pieces travel together. Export the revised source and GLB and report the final revision reference.';-const prompt='Read AGENTS.md, BRIEF.md and CONDITION.md. Build the brief using the configured Kiln MCP tools. Work only in this directory; do not read the engine installation, examples, other projects, previous runs, personal memories or global skills. Do not use web/network/provider tools or spawn agents. This is the first submission: save first.kiln.js and first.glb through node kiln.mjs, write first-result.json with programRef and honest image-review/remaining-issue notes, then stop for the follow-up. Keep at least 10 of the total 30 Kiln calls and some of the 15-minute total deadline for the subsequent edit. Do not bypass the experimental condition with direct engine imports or CLI authoring; the CLI is only for exporting saved source/GLB.';-await mkdir(join(base,'runs'));-async function phase(run,phase,sessionId) {- const {workspace,configPath,harness,model,deadline}=run;- const common=['-c','approval_policy="on-request"','-c','approvals_reviewer="auto_review"','-c','features.memories=false','-c','features.apps=false','-c','model_reasoning_effort="high"','-c',`mcp_servers.kiln_workspace.command=${JSON.stringify(bun)}`,'-c',`mcp_servers.kiln_workspace.args=${JSON.stringify([join(base,'package/scripts/evaluation/server.ts'),configPath])}`,'-c',`mcp_servers.kiln_workspace.env.KILN_PROGRAM_STORE=${JSON.stringify(join(workspace,'.kiln/programs'))}`,'-c','mcp_servers.kiln_workspace.env.KILN_RENDER="cpu"'];- const input=phase===1?prompt:followup;- let command,args,env={...process.env};- if(harness==='codex'){- command=node;- args=['C:/Program Files/nodejs/node_modules/@openai/codex/bin/codex.js','exec','--approve-for-me',...(phase===2?['resume']:[]),'--ignore-user-config','--json','--skip-git-repo-check','-m',model,...common,...(phase===1?['--ignore-rules','--cd',workspace]:[sessionId]),input];- }else{- command='C:/Program Files/nodejs/node_modules/opencode-ai/bin/opencode.exe';- args=['run','--pure','--auto','--dir',workspace,'--format','json','-m',model,'--variant','high',...(phase===2?['--session',sessionId]:[]),input];- env.XDG_CONFIG_HOME=join(workspace,'.config');env.OPENCODE_DISABLE_CLAUDE_CODE='true';+const base = process.argv[2] ? resolve(process.argv[2]) : '';+if (!base || process.argv[3] !== '--run-authorized-pilot')+ throw new Error(+ 'Usage: node scripts/evaluation/dispatch.mjs FROZEN_DIRECTORY --run-authorized-pilot. This dispatches up to 12 live model calls plus their same-session follow-ups; authorization must already be recorded.',+ );+const freeze = JSON.parse(await readFile(join(base, 'freeze.json'), 'utf8'));+const bun = 'C:/Users/Mattm/.bun/bin/bun.exe',+ node = 'C:/Program Files/nodejs/node.exe';+const sha = (x) => `sha256:${createHash('sha256').update(x).digest('hex')}`;+const followup =+ 'Use the saved revision. Read only the source section you need, increase `serviceOffset` by 0.15 metres, and render the edit by reference. Keep unrelated source unchanged. Show the named `ServiceAssembly` closely enough to check its attachment and in a wider view that establishes its location. Use the camera controls available in this condition. Sample the translation animation before, during and after its movement to check that attached pieces travel together. Export the revised source and GLB and report the final revision reference.';+const prompt =+ 'Read AGENTS.md, BRIEF.md and CONDITION.md. Build the brief using the configured Kiln MCP tools. Work only in this directory; do not read the engine installation, examples, other projects, previous runs, personal memories or global skills. Do not use web/network/provider tools or spawn agents. This is the first submission: save first.kiln.js and first.glb through node kiln.mjs, write first-result.json with programRef and honest image-review/remaining-issue notes, then stop for the follow-up. Keep at least 10 of the total 30 Kiln calls and some of the 15-minute total deadline for the subsequent edit. Do not bypass the experimental condition with direct engine imports or CLI authoring; the CLI is only for exporting saved source/GLB.';+await mkdir(join(base, 'runs'));+async function phase(run, phase, sessionId) {+ const { workspace, configPath, harness, model, deadline } = run;+ const common = [+ '-c',+ 'approval_policy="on-request"',+ '-c',+ 'approvals_reviewer="auto_review"',+ '-c',+ 'features.memories=false',+ '-c',+ 'features.apps=false',+ '-c',+ 'model_reasoning_effort="high"',+ '-c',+ `mcp_servers.kiln_workspace.command=${JSON.stringify(bun)}`,+ '-c',+ `mcp_servers.kiln_workspace.args=${JSON.stringify([join(base, 'package/scripts/evaluation/server.ts'), configPath])}`,+ '-c',+ `mcp_servers.kiln_workspace.env.KILN_PROGRAM_STORE=${JSON.stringify(join(workspace, '.kiln/programs'))}`,+ '-c',+ 'mcp_servers.kiln_workspace.env.KILN_RENDER="cpu"',+ ];+ const input = phase === 1 ? prompt : followup;+ let command,+ args,+ env = { ...process.env };+ if (harness === 'codex') {+ command = node;+ args = [+ 'C:/Program Files/nodejs/node_modules/@openai/codex/bin/codex.js',+ 'exec',+ '--approve-for-me',+ ...(phase === 2 ? ['resume'] : []),+ '--ignore-user-config',+ '--json',+ '--skip-git-repo-check',+ '-m',+ model,+ ...common,+ ...(phase === 1 ? ['--ignore-rules', '--cd', workspace] : [sessionId]),+ input,+ ];+ } else {+ command = 'C:/Program Files/nodejs/node_modules/opencode-ai/bin/opencode.exe';+ args = [+ 'run',+ '--pure',+ '--auto',+ '--dir',+ workspace,+ '--format',+ 'json',+ '-m',+ model,+ '--variant',+ 'high',+ ...(phase === 2 ? ['--session', sessionId] : []),+ input,+ ];+ env.XDG_CONFIG_HOME = join(workspace, '.config');+ env.OPENCODE_DISABLE_CLAUDE_CODE = 'true';}- await writeFile(join(run.directory,`invocation-${phase}.json`),JSON.stringify({command,args,cwd:workspace,environmentOverrides:harness==='opencode'?{XDG_CONFIG_HOME:env.XDG_CONFIG_HOME,OPENCODE_DISABLE_CLAUDE_CODE:'true'}:{}},null,2));- const started=Date.now();- return await new Promise(done=>{- const child=spawn(command,args,{cwd:workspace,env,stdio:['ignore','pipe','pipe'],windowsHide:true});- let stdout='',stderr='',timedOut=false;- child.stdout.on('data',data=>{stdout+=data;appendFileSync(join(run.directory,`harness-${phase}.jsonl`),data);});- child.stderr.on('data',data=>{stderr+=data;appendFileSync(join(run.directory,`stderr-${phase}.log`),data);});- const timer=setTimeout(()=>{timedOut=true;spawn('taskkill',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,stdio:'ignore'});},Math.max(1,deadline-Date.now()));- child.on('error',error=>{clearTimeout(timer);done({exitCode:-1,error:error.message,seconds:(Date.now()-started)/1000});});- child.on('close',exitCode=>{+ await writeFile(+ join(run.directory, `invocation-${phase}.json`),+ JSON.stringify(+ {+ command,+ args,+ cwd: workspace,+ environmentOverrides:+ harness === 'opencode'+ ? { XDG_CONFIG_HOME: env.XDG_CONFIG_HOME, OPENCODE_DISABLE_CLAUDE_CODE: 'true' }+ : {},+ },+ null,+ 2,+ ),+ );+ const started = Date.now();+ return await new Promise((done) => {+ const child = spawn(command, args, {+ cwd: workspace,+ env,+ stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true,+ });+ let stdout = '',+ stderr = '',+ timedOut = false;+ child.stdout.on('data', (data) => {+ stdout += data;+ appendFileSync(join(run.directory, `harness-${phase}.jsonl`), data);+ });+ child.stderr.on('data', (data) => {+ stderr += data;+ appendFileSync(join(run.directory, `stderr-${phase}.log`), data);+ });+ const timer = setTimeout(+ () => {+ timedOut = true;+ spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], {+ windowsHide: true,+ stdio: 'ignore',+ });+ },+ Math.max(1, deadline - Date.now()),+ );+ child.on('error', (error) => {+ clearTimeout(timer);+ done({ exitCode: -1, error: error.message, seconds: (Date.now() - started) / 1000 });+ });+ child.on('close', (exitCode) => {clearTimeout(timer);- const events=stdout.split('\n').flatMap(line=>{try{return[JSON.parse(line)];}catch{return[];}});- const id=events.find(e=>e.thread_id)?.thread_id ?? events.find(e=>e.sessionID)?.sessionID ?? sessionId;- done({exitCode,timedOut,sessionId:id,seconds:(Date.now()-started)/1000,eventCount:events.length,usage:events.filter(e=>e.usage||e.type==='step_finish').map(e=>e.usage??e.part),error:stderr.trim().slice(-1500)});+ const events = stdout.split('\n').flatMap((line) => {+ try {+ return [JSON.parse(line)];+ } catch {+ return [];+ }+ });+ const id =+ events.find((e) => e.thread_id)?.thread_id ??+ events.find((e) => e.sessionID)?.sessionID ??+ sessionId;+ done({+ exitCode,+ timedOut,+ sessionId: id,+ seconds: (Date.now() - started) / 1000,+ eventCount: events.length,+ usage: events+ .filter((e) => e.usage || e.type === 'step_finish')+ .map((e) => e.usage ?? e.part),+ error: stderr.trim().slice(-1500),+ });});});}-async function cell(harness,briefId,condition,index){- const runId=`e0-${harness}-${briefId}-${condition}`,directory=join(base,'runs',runId),workspace=join(directory,'workspace');- await mkdir(workspace,{recursive:true});- const model=harness==='codex'?'gpt-6-astra':'opencode/muse-spark-1.3-contributor-free';- const packet=(await readFile(join(base,'protocol/common-guide.md'),'utf8'))+'\n\nBudget: 30 total Kiln calls, 48 image cells, 512-pixel maximum cell side, 15 minutes total including follow-up. Export source using node kiln.mjs source sha256:FULL_HASH --out first.kiln.js; export GLB using node kiln.mjs render sha256:FULL_HASH --out first.glb. After the follow-up use final.kiln.js and final.glb. Do not read .kiln/programs directly.\n';- await writeFile(join(workspace,'AGENTS.md'),packet);- await cp(join(base,`protocol/briefs/${briefId}.md`),join(workspace,'BRIEF.md'));- await cp(join(base,`protocol/condition-${condition}.md`),join(workspace,'CONDITION.md'));- await writeFile(join(workspace,'kiln.mjs'),`import { main } from ${JSON.stringify(pathToFileURL(join(base,'package/dist/cli.mjs')).href)};process.env.KILN_PROGRAM_STORE=${JSON.stringify(join(workspace,'.kiln/programs'))};process.env.KILN_RENDER='cpu';process.exitCode=await main(process.argv.slice(2));\n`);- const configPath=join(directory,'host-config.json');- const config={runId,condition,outputDirectory:join(directory,'tools'),programStoreDirectory:join(workspace,'.kiln/programs'),authorization:freeze.authorization,allowResume:true,maxToolCalls:30,maxImageCells:48,maxCellSide:512,maxWallSeconds:900};- await writeFile(configPath,JSON.stringify(config,null,2));- if(harness==='opencode')await writeFile(join(workspace,'opencode.json'),JSON.stringify({$schema:'https://opencode.ai/config.json',mcp:{kiln_workspace:{type:'local',command:[bun,join(base,'package/scripts/evaluation/server.ts'),configPath],environment:{KILN_PROGRAM_STORE:config.programStoreDirectory,KILN_RENDER:'cpu'},enabled:true}},permission:{external_directory:'deny'}},null,2));- const suppliedFiles=[];for(const file of await readdir(workspace)) suppliedFiles.push({path:file,hash:sha(await readFile(join(workspace,file)))});- const run={runId,directory,workspace,configPath,harness,model,condition,briefId,index,deadline:Date.now()+900000,suppliedFiles,startedAt:new Date().toISOString()};- await writeFile(join(directory,'run.json'),JSON.stringify({...run,freeze},null,2));- console.log(JSON.stringify({runId,status:'started',workspace}));- const first=await phase(run,1);- await writeFile(join(directory,'phase-1.json'),JSON.stringify(first,null,2));- let firstSubmission=false;try{JSON.parse(await readFile(join(workspace,'first-result.json'),'utf8'));await readFile(join(workspace,'first.kiln.js'));firstSubmission=true;}catch{}- let second=null;- if(first.exitCode===0&&first.sessionId&&firstSubmission&&Date.now()<run.deadline)second=await phase(run,2,first.sessionId);- if(second)await writeFile(join(directory,'phase-2.json'),JSON.stringify(second,null,2));- const result={runId,first,second,firstSubmission,seconds:900-(run.deadline-Date.now())/1000,status:first.timedOut||second?.timedOut?'budget-exhausted':'pending-review'};- await writeFile(join(directory,'outcome.json'),JSON.stringify(result,null,2));- console.log(JSON.stringify(result));return result;+async function cell(harness, briefId, condition, index) {+ const runId = `e0-${harness}-${briefId}-${condition}`,+ directory = join(base, 'runs', runId),+ workspace = join(directory, 'workspace');+ await mkdir(workspace, { recursive: true });+ const model = harness === 'codex' ? 'gpt-6-astra' : 'opencode/muse-spark-1.3-contributor-free';+ const packet =+ (await readFile(join(base, 'protocol/common-guide.md'), 'utf8')) ++ '\n\nBudget: 30 total Kiln calls, 48 image cells, 512-pixel maximum cell side, 15 minutes total including follow-up. Export source using node kiln.mjs source sha256:FULL_HASH --out first.kiln.js; export GLB using node kiln.mjs render sha256:FULL_HASH --out first.glb. After the follow-up use final.kiln.js and final.glb. Do not read .kiln/programs directly.\n';+ await writeFile(join(workspace, 'AGENTS.md'), packet);+ await cp(join(base, `protocol/briefs/${briefId}.md`), join(workspace, 'BRIEF.md'));+ await cp(join(base, `protocol/condition-${condition}.md`), join(workspace, 'CONDITION.md'));+ await writeFile(+ join(workspace, 'kiln.mjs'),+ `import { main } from ${JSON.stringify(pathToFileURL(join(base, 'package/dist/cli.mjs')).href)};process.env.KILN_PROGRAM_STORE=${JSON.stringify(join(workspace, '.kiln/programs'))};process.env.KILN_RENDER='cpu';process.exitCode=await main(process.argv.slice(2));\n`,+ );+ const configPath = join(directory, 'host-config.json');+ const config = {+ runId,+ condition,+ outputDirectory: join(directory, 'tools'),+ programStoreDirectory: join(workspace, '.kiln/programs'),+ authorization: freeze.authorization,+ allowResume: true,+ maxToolCalls: 30,+ maxImageCells: 48,+ maxCellSide: 512,+ maxWallSeconds: 900,+ };+ await writeFile(configPath, JSON.stringify(config, null, 2));+ if (harness === 'opencode')+ await writeFile(+ join(workspace, 'opencode.json'),+ JSON.stringify(+ {+ $schema: 'https://opencode.ai/config.json',+ mcp: {+ kiln_workspace: {+ type: 'local',+ command: [bun, join(base, 'package/scripts/evaluation/server.ts'), configPath],+ environment: { KILN_PROGRAM_STORE: config.programStoreDirectory, KILN_RENDER: 'cpu' },+ enabled: true,+ },+ },+ permission: { external_directory: 'deny' },+ },+ null,+ 2,+ ),+ );+ const suppliedFiles = [];+ for (const file of await readdir(workspace))+ suppliedFiles.push({ path: file, hash: sha(await readFile(join(workspace, file))) });+ const run = {+ runId,+ directory,+ workspace,+ configPath,+ harness,+ model,+ condition,+ briefId,+ index,+ deadline: Date.now() + 900000,+ suppliedFiles,+ startedAt: new Date().toISOString(),+ };+ await writeFile(join(directory, 'run.json'), JSON.stringify({ ...run, freeze }, null, 2));+ console.log(JSON.stringify({ runId, status: 'started', workspace }));+ const first = await phase(run, 1);+ await writeFile(join(directory, 'phase-1.json'), JSON.stringify(first, null, 2));+ let firstSubmission = false;+ try {+ JSON.parse(await readFile(join(workspace, 'first-result.json'), 'utf8'));+ await readFile(join(workspace, 'first.kiln.js'));+ firstSubmission = true;+ } catch {}+ let second = null;+ if (first.exitCode === 0 && first.sessionId && firstSubmission && Date.now() < run.deadline)+ second = await phase(run, 2, first.sessionId);+ if (second) await writeFile(join(directory, 'phase-2.json'), JSON.stringify(second, null, 2));+ const result = {+ runId,+ first,+ second,+ firstSubmission,+ seconds: 900 - (run.deadline - Date.now()) / 1000,+ status: first.timedOut || second?.timedOut ? 'budget-exhausted' : 'pending-review',+ };+ await writeFile(join(directory, 'outcome.json'), JSON.stringify(result, null, 2));+ console.log(JSON.stringify(result));+ return result;}-const queue=async(harness)=>{const rows=harness==='codex'?[['variable-duct','A'],['variable-duct','B'],['variable-duct','C'],['optical-instrument','B'],['optical-instrument','C'],['optical-instrument','A']]:[['variable-duct','C'],['variable-duct','B'],['variable-duct','A'],['optical-instrument','A'],['optical-instrument','C'],['optical-instrument','B']];const results=[];for(let i=0;i<rows.length;i++)results.push(await cell(harness,...rows[i],i));return results;};-await writeFile(join(base,'results.json'),JSON.stringify((await Promise.all(['codex','opencode'].map(queue))).flat(),null,2));+const queue = async (harness) => {+ const rows =+ harness === 'codex'+ ? [+ ['variable-duct', 'A'],+ ['variable-duct', 'B'],+ ['variable-duct', 'C'],+ ['optical-instrument', 'B'],+ ['optical-instrument', 'C'],+ ['optical-instrument', 'A'],+ ]+ : [+ ['variable-duct', 'C'],+ ['variable-duct', 'B'],+ ['variable-duct', 'A'],+ ['optical-instrument', 'A'],+ ['optical-instrument', 'C'],+ ['optical-instrument', 'B'],+ ];+ const results = [];+ for (let i = 0; i < rows.length; i++) results.push(await cell(harness, ...rows[i], i));+ return results;+};+await writeFile(+ join(base, 'results.json'),+ JSON.stringify((await Promise.all(['codex', 'opencode'].map(queue))).flat(), null, 2),+);diff --git a/scripts/evaluation/observe-shipping.mjs b/scripts/evaluation/observe-shipping.mjsindex 59b0df06..719a8c20 100644--- a/scripts/evaluation/observe-shipping.mjs+++ b/scripts/evaluation/observe-shipping.mjs@@ -1,58 +1,242 @@// Evaluation-only transparent MCP recorder. Never installed with the runtime.-import {spawn} from 'node:child_process';-import {mkdirSync,appendFileSync,writeFileSync} from 'node:fs';-import {resolve,join} from 'node:path';-import {fileURLToPath} from 'node:url';-import {createInterface} from 'node:readline';-import {createHash} from 'node:crypto';-export function plannedCells(tool,args={}){- if(tool==='kiln_edit'&&args.render===false)return 0;- if(tool==='kiln_inspect')return 1;- if(!['kiln_render','kiln_edit','kiln_screenshot_animation','kiln_view_interior','kiln_screenshot'].includes(tool))return 0;- const capture=args.capture;- if(capture?.shots)return Math.min(9,Math.max(1,capture.shots.length));- if(capture?.cells?.length)return Math.min(9,capture.cells.length);- if(capture?.preset){const match=/^([1-3])x([1-3])$/.exec(capture.preset);return match?Number(match[1])*Number(match[2]):9;}- if(tool==='kiln_screenshot_animation')return Math.min(9,Math.max(1,args.frameTimes?.length??args.frames??6));- return tool==='kiln_view_interior'?3:6;+import { spawn } from 'node:child_process';+import { mkdirSync, appendFileSync, writeFileSync } from 'node:fs';+import { resolve, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createInterface } from 'node:readline';+import { createHash } from 'node:crypto';+export function plannedCells(tool, args = {}) {+ if (tool === 'kiln_edit' && args.render === false) return 0;+ if (tool === 'kiln_inspect') return 1;+ if (+ ![+ 'kiln_render',+ 'kiln_edit',+ 'kiln_screenshot_animation',+ 'kiln_view_interior',+ 'kiln_screenshot',+ ].includes(tool)+ )+ return 0;+ const capture = args.capture;+ if (capture?.shots) return Math.min(9, Math.max(1, capture.shots.length));+ if (capture?.cells?.length) return Math.min(9, capture.cells.length);+ if (capture?.preset) {+ const match = /^([1-3])x([1-3])$/.exec(capture.preset);+ return match ? Number(match[1]) * Number(match[2]) : 9;+ }+ if (tool === 'kiln_screenshot_animation')+ return Math.min(9, Math.max(1, args.frameTimes?.length ?? args.frames ?? 6));+ return tool === 'kiln_view_interior' ? 3 : 6;}-export class EvaluationBudget{- constructor({maxCalls=30,maxImages=48}={}){this.maxCalls=maxCalls;this.maxImages=maxImages;this.calls=0;this.images=0;this.pending=new Map();}- reserve(id,count){if(this.calls>=this.maxCalls)return 'Tool call budget exhausted';if(this.images+[...this.pending.values()].reduce((a,b)=>a+b,0)+count>this.maxImages)return 'Rendered image-cell budget exhausted';this.calls++;this.pending.set(id,count);return null;}- settle(id,count){this.pending.delete(id);this.images+=count;}- stats(){return {calls:this.calls,images:this.images,reserved:[...this.pending.values()].reduce((a,b)=>a+b,0),maxCalls:this.maxCalls,maxImages:this.maxImages};}+export class EvaluationBudget {+ constructor({ maxCalls = 30, maxImages = 48 } = {}) {+ this.maxCalls = maxCalls;+ this.maxImages = maxImages;+ this.calls = 0;+ this.images = 0;+ this.pending = new Map();+ }+ reserve(id, count) {+ if (this.calls >= this.maxCalls) return 'Tool call budget exhausted';+ if (+ this.images + [...this.pending.values()].reduce((a, b) => a + b, 0) + count >+ this.maxImages+ )+ return 'Rendered image-cell budget exhausted';+ this.calls++;+ this.pending.set(id, count);+ return null;+ }+ settle(id, count) {+ this.pending.delete(id);+ this.images += count;+ }+ stats() {+ return {+ calls: this.calls,+ images: this.images,+ reserved: [...this.pending.values()].reduce((a, b) => a + b, 0),+ maxCalls: this.maxCalls,+ maxImages: this.maxImages,+ };+ }}-export function observeShipping({server,out,maxCalls=30,maxImages=48,deadlineMs=900000}){- for(const value of [maxCalls,maxImages,deadlineMs])if(!Number.isSafeInteger(value)||value<1)throw Error('Positive observer limits required');- mkdirSync(out,{recursive:true});mkdirSync(join(out,'images'),{recursive:true});- const budget=new EvaluationBudget({maxCalls,maxImages});const pending=new Map();let timer,expired=false,sequence=0;- const record=entry=>appendFileSync(join(out,'transcript.jsonl'),JSON.stringify({...entry,time:new Date().toISOString()})+'\n');- const send=value=>process.stdout.write(JSON.stringify(value)+'\n');- const error=(id,message)=>send({jsonrpc:'2.0',id,result:{isError:true,content:[{type:'text',text:JSON.stringify({ok:false,code:'EVALUATION_BUDGET',error:message,budget:budget.stats()})}]}});- const child=spawn(process.execPath,[server],{stdio:['pipe','pipe','pipe'],windowsHide:true,env:{...process.env,...(process.env.RENDER_SERVICE_TOKEN&&!process.env.KILN_RENDER_TOKEN?{KILN_RENDER_TOKEN:process.env.RENDER_SERVICE_TOKEN}:{})}});- child.stderr.on('data',chunk=>appendFileSync(join(out,'server.stderr.log'),chunk));- createInterface({input:process.stdin}).on('line',line=>{let request;try{request=JSON.parse(line);}catch{child.stdin.write(line+'\n');return;}- if(request.method==='tools/call'){- if(!timer)timer=setTimeout(()=>{expired=true;record({direction:'budget',reason:'deadline',budget:budget.stats()});for(const id of pending.keys())error(id,'Session deadline exhausted');pending.clear();child.kill();},deadlineMs);- const tool=request.params?.name,args=request.params?.arguments??{},cells=plannedCells(tool,args);const reason=expired?'Session deadline exhausted':budget.reserve(request.id,cells);- record({direction:'request',id:request.id,tool,args,argumentBytes:Buffer.byteLength(JSON.stringify(args)),reservedCells:cells,denied:reason??undefined,budget:budget.stats()});- if(reason){error(request.id,reason);return;}- pending.set(request.id,{tool,cells,sequence:++sequence});+export function observeShipping({+ server,+ out,+ maxCalls = 30,+ maxImages = 48,+ deadlineMs = 900000,+}) {+ for (const value of [maxCalls, maxImages, deadlineMs])+ if (!Number.isSafeInteger(value) || value < 1) throw Error('Positive observer limits required');+ mkdirSync(out, { recursive: true });+ mkdirSync(join(out, 'images'), { recursive: true });+ const budget = new EvaluationBudget({ maxCalls, maxImages });+ const pending = new Map();+ let timer,+ expired = false,+ sequence = 0;+ const record = (entry) =>+ appendFileSync(+ join(out, 'transcript.jsonl'),+ `${JSON.stringify({ ...entry, time: new Date().toISOString() })}\n`,+ );+ const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);+ const error = (id, message) =>+ send({+ jsonrpc: '2.0',+ id,+ result: {+ isError: true,+ content: [+ {+ type: 'text',+ text: JSON.stringify({+ ok: false,+ code: 'EVALUATION_BUDGET',+ error: message,+ budget: budget.stats(),+ }),+ },+ ],+ },+ });+ const child = spawn(process.execPath, [server], {+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ env: {+ ...process.env,+ ...(process.env.RENDER_SERVICE_TOKEN && !process.env.KILN_RENDER_TOKEN+ ? { KILN_RENDER_TOKEN: process.env.RENDER_SERVICE_TOKEN }+ : {}),+ },+ });+ child.stderr.on('data', (chunk) => appendFileSync(join(out, 'server.stderr.log'), chunk));+ createInterface({ input: process.stdin })+ .on('line', (line) => {+ let request;+ try {+ request = JSON.parse(line);+ } catch {+ child.stdin.write(`${line}\n`);+ return;+ }+ if (request.method === 'tools/call') {+ if (!timer)+ timer = setTimeout(() => {+ expired = true;+ record({ direction: 'budget', reason: 'deadline', budget: budget.stats() });+ for (const id of pending.keys()) error(id, 'Session deadline exhausted');+ pending.clear();+ child.kill();+ }, deadlineMs);+ const tool = request.params?.name,+ args = request.params?.arguments ?? {},+ cells = plannedCells(tool, args);+ const reason = expired ? 'Session deadline exhausted' : budget.reserve(request.id, cells);+ record({+ direction: 'request',+ id: request.id,+ tool,+ args,+ argumentBytes: Buffer.byteLength(JSON.stringify(args)),+ reservedCells: cells,+ denied: reason ?? undefined,+ budget: budget.stats(),+ });+ if (reason) {+ error(request.id, reason);+ return;+ }+ pending.set(request.id, { tool, cells, sequence: ++sequence });+ }+ if (!expired) child.stdin.write(`${line}\n`);+ })+ .on('close', () => child.stdin.end());+ createInterface({ input: child.stdout }).on('line', (line) => {+ let response;+ try {+ response = JSON.parse(line);+ } catch {+ process.stdout.write(`${line}\n`);+ return;}- if(!expired)child.stdin.write(line+'\n');- }).on('close',()=>child.stdin.end());- createInterface({input:child.stdout}).on('line',line=>{let response;try{response=JSON.parse(line);}catch{process.stdout.write(line+'\n');return;}- const call=pending.get(response.id);if(call){const content=response.result?.content??[];const images=content.filter(item=>item.type==='image');const saved=[];for(let i=0;i<images.length;i++){const bytes=Buffer.from(images[i].data,'base64');const path=join(out,'images',`${String(call.sequence).padStart(3,'0')}-${i}.png`);writeFileSync(path,bytes);saved.push({path,bytes:bytes.length,sha256:createHash('sha256').update(bytes).digest('hex')});}- const delivered=images.length?Math.max(call.cells,images.length):0;budget.settle(response.id,delivered);pending.delete(response.id);- record({direction:'response',id:response.id,tool:call.tool,content:content.map(item=>item.type==='image'?{type:'image',mimeType:item.mimeType}:item),images:saved,chargedCells:delivered,isError:response.result?.isError??false,budget:budget.stats()});- if(images.length>call.cells){error(response.id,'Renderer returned more images than reserved');return;}+ const call = pending.get(response.id);+ if (call) {+ const content = response.result?.content ?? [];+ const images = content.filter((item) => item.type === 'image');+ const saved = [];+ for (let i = 0; i < images.length; i++) {+ const bytes = Buffer.from(images[i].data, 'base64');+ const path = join(out, 'images', `${String(call.sequence).padStart(3, '0')}-${i}.png`);+ writeFileSync(path, bytes);+ saved.push({+ path,+ bytes: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ });+ }+ const delivered = images.length ? Math.max(call.cells, images.length) : 0;+ budget.settle(response.id, delivered);+ pending.delete(response.id);+ record({+ direction: 'response',+ id: response.id,+ tool: call.tool,+ content: content.map((item) =>+ item.type === 'image' ? { type: 'image', mimeType: item.mimeType } : item,+ ),+ images: saved,+ chargedCells: delivered,+ isError: response.result?.isError ?? false,+ budget: budget.stats(),+ });+ if (images.length > call.cells) {+ error(response.id, 'Renderer returned more images than reserved');+ return;+ }}- process.stdout.write(line+'\n');+ process.stdout.write(`${line}\n`);+ });+ child.on('close', (code) => {+ if (timer) clearTimeout(timer);+ writeFileSync(+ join(out, 'budget.json'),+ JSON.stringify({ ...budget.stats(), expired, exitCode: code }, null, 2),+ );+ process.exitCode = code ?? 1;+ });+ child.on('error', (err) => {+ record({ direction: 'observer-error', message: err.message });+ process.exitCode = 1;});- child.on('close',code=>{if(timer)clearTimeout(timer);writeFileSync(join(out,'budget.json'),JSON.stringify({...budget.stats(),expired,exitCode:code},null,2));process.exitCode=code??1;});- child.on('error',err=>{record({direction:'observer-error',message:err.message});process.exitCode=1;});return child;}-if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){- const options={};const args=process.argv.slice(2);while(args.length){const flag=args.shift(),value=args.shift();if(!['--server','--out','--max-calls','--max-images','--deadline-ms'].includes(flag)||!value)throw Error('Expected --server PATH --out DIR [--max-calls 30 --max-images 48 --deadline-ms 900000]');options[{'--server':'server','--out':'out','--max-calls':'maxCalls','--max-images':'maxImages','--deadline-ms':'deadlineMs'}[flag]]=['--server','--out'].includes(flag)?resolve(value):Number(value);}if(!options.server||!options.out)throw Error('server and out required');observeShipping(options);+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const options = {};+ const args = process.argv.slice(2);+ while (args.length) {+ const flag = args.shift(),+ value = args.shift();+ if (+ !['--server', '--out', '--max-calls', '--max-images', '--deadline-ms'].includes(flag) ||+ !value+ )+ throw Error(+ 'Expected --server PATH --out DIR [--max-calls 30 --max-images 48 --deadline-ms 900000]',+ );+ options[+ {+ '--server': 'server',+ '--out': 'out',+ '--max-calls': 'maxCalls',+ '--max-images': 'maxImages',+ '--deadline-ms': 'deadlineMs',+ }[flag]+ ] = ['--server', '--out'].includes(flag) ? resolve(value) : Number(value);+ }+ if (!options.server || !options.out) throw Error('server and out required');+ observeShipping(options);}diff --git a/scripts/evaluation/server.test.ts b/scripts/evaluation/server.test.tsindex 745a1cdb..b2e36acf 100644--- a/scripts/evaluation/server.test.ts+++ b/scripts/evaluation/server.test.ts@@ -6,62 +6,155 @@ import { Client } from '@modelcontextprotocol/client';import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';test('pilot host advertises a condition, delivers a real image and enforces the call cap', async () => {- const directory=await mkdtemp(join(tmpdir(),'kiln-pilot-host-'));- const config=join(directory,'run.json');- await writeFile(config,JSON.stringify({runId:'offline-host-proof',condition:'A',outputDirectory:join(directory,'result'),programStoreDirectory:join(directory,'workspace/.kiln/programs'),authorization:'Offline test; no model calls',maxToolCalls:3,maxImageCells:6,maxCellSide:512,maxWallSeconds:60}));- const client=new Client({name:'pilot-host-proof',version:'1'});- const transport=new StdioClientTransport({command:process.execPath,args:[resolve('scripts/evaluation/server.ts'),config],stderr:'pipe'});+ const directory = await mkdtemp(join(tmpdir(), 'kiln-pilot-host-'));+ const config = join(directory, 'run.json');+ await writeFile(+ config,+ JSON.stringify({+ runId: 'offline-host-proof',+ condition: 'A',+ outputDirectory: join(directory, 'result'),+ programStoreDirectory: join(directory, 'workspace/.kiln/programs'),+ authorization: 'Offline test; no model calls',+ maxToolCalls: 3,+ maxImageCells: 6,+ maxCellSide: 512,+ maxWallSeconds: 60,+ }),+ );+ const client = new Client({ name: 'pilot-host-proof', version: '1' });+ const transport = new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/evaluation/server.ts'), config],+ stderr: 'pipe',+ });await client.connect(transport);try {- const listed=await client.listTools();+ const listed = await client.listTools();expect(listed.tools).toHaveLength(8);- const discovery=await client.callTool({name:'kiln_list_primitives',arguments:{category:'geometry'}});+ const discovery = await client.callTool({+ name: 'kiln_list_primitives',+ arguments: { category: 'geometry' },+ });expect(JSON.stringify(discovery)).not.toContain('parametricSurface');- const invalid=await client.callTool({name:'kiln_list_primitives',arguments:{query:'advanced lookup unavailable in A'}});+ const invalid = await client.callTool({+ name: 'kiln_list_primitives',+ arguments: { query: 'advanced lookup unavailable in A' },+ });expect(invalid.isError).toBe(true);- const rendered=await client.callTool({name:'kiln_render',arguments:{code:"const meta={name:'Box',category:'prop'};function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r,position:[0,0.5,0]});return r;}",capture:{preset:'1x1'}}});- expect((rendered.content as Array<{type:string}>).some((entry)=>entry.type==='image')).toBe(true);- const blocked=await client.callTool({name:'kiln_list_primitives',arguments:{}});+ const rendered = await client.callTool({+ name: 'kiln_render',+ arguments: {+ code: "const meta={name:'Box',category:'prop'};function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#887766'),{parent:r,position:[0,0.5,0]});return r;}",+ capture: { preset: '1x1' },+ },+ });+ expect(+ (rendered.content as Array<{ type: string }>).some((entry) => entry.type === 'image'),+ ).toBe(true);+ const blocked = await client.callTool({ name: 'kiln_list_primitives', arguments: {} });expect(blocked.isError).toBe(true);expect(JSON.stringify(blocked)).toContain('budget-exhausted');- const events=(await readFile(join(directory,'result/events.jsonl'),'utf8')).trim().split('\n').map((line)=>JSON.parse(line));+ const events = (await readFile(join(directory, 'result/events.jsonl'), 'utf8'))+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));expect(events[1].sequence).toBe(3);expect(events[1].images).toHaveLength(1);expect(events[1].images[0].hash).toMatch(/^sha256:/);- } finally { await client.close(); }-},30000);+ } finally {+ await client.close();+ }+}, 30000);test('explicit same-run restart retains consumed tool budget', async () => {- const directory=await mkdtemp(join(tmpdir(),'kiln-pilot-resume-'));- const config=join(directory,'run.json');- await writeFile(config,JSON.stringify({runId:'resume-proof',condition:'B',outputDirectory:join(directory,'result'),programStoreDirectory:join(directory,'workspace/.kiln/programs'),authorization:'Offline',allowResume:true,maxToolCalls:1,maxImageCells:6,maxCellSide:512,maxWallSeconds:60}));+ const directory = await mkdtemp(join(tmpdir(), 'kiln-pilot-resume-'));+ const config = join(directory, 'run.json');+ await writeFile(+ config,+ JSON.stringify({+ runId: 'resume-proof',+ condition: 'B',+ outputDirectory: join(directory, 'result'),+ programStoreDirectory: join(directory, 'workspace/.kiln/programs'),+ authorization: 'Offline',+ allowResume: true,+ maxToolCalls: 1,+ maxImageCells: 6,+ maxCellSide: 512,+ maxWallSeconds: 60,+ }),+ );async function connect() {- const client=new Client({name:'resume-proof',version:'1'});- await client.connect(new StdioClientTransport({command:process.execPath,args:[resolve('scripts/evaluation/server.ts'),config],stderr:'pipe'}));+ const client = new Client({ name: 'resume-proof', version: '1' });+ await client.connect(+ new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/evaluation/server.ts'), config],+ stderr: 'pipe',+ }),+ );return client;}- const first=await connect();- expect((await first.callTool({name:'kiln_list_primitives',arguments:{}})).isError).not.toBe(true);+ const first = await connect();+ expect((await first.callTool({ name: 'kiln_list_primitives', arguments: {} })).isError).not.toBe(+ true,+ );await first.close();- const second=await connect();- try { expect(JSON.stringify(await second.callTool({name:'kiln_list_primitives',arguments:{}}))).toContain('budget-exhausted'); }- finally { await second.close(); }-},30000);-+ const second = await connect();+ try {+ expect(+ JSON.stringify(await second.callTool({ name: 'kiln_list_primitives', arguments: {} })),+ ).toContain('budget-exhausted');+ } finally {+ await second.close();+ }+}, 30000);test('parallel requests consume one reservation each and preserve the cap', async () => {- const directory=await mkdtemp(join(tmpdir(),'kiln-pilot-parallel-'));- const config=join(directory,'run.json');- await writeFile(config,JSON.stringify({runId:'parallel-proof',condition:'B',outputDirectory:join(directory,'result'),programStoreDirectory:join(directory,'workspace/.kiln/programs'),authorization:'Offline',maxToolCalls:2,maxImageCells:6,maxCellSide:512,maxWallSeconds:60}));- const client=new Client({name:'parallel-proof',version:'1'});- await client.connect(new StdioClientTransport({command:process.execPath,args:[resolve('scripts/evaluation/server.ts'),config],stderr:'pipe'}));+ const directory = await mkdtemp(join(tmpdir(), 'kiln-pilot-parallel-'));+ const config = join(directory, 'run.json');+ await writeFile(+ config,+ JSON.stringify({+ runId: 'parallel-proof',+ condition: 'B',+ outputDirectory: join(directory, 'result'),+ programStoreDirectory: join(directory, 'workspace/.kiln/programs'),+ authorization: 'Offline',+ maxToolCalls: 2,+ maxImageCells: 6,+ maxCellSide: 512,+ maxWallSeconds: 60,+ }),+ );+ const client = new Client({ name: 'parallel-proof', version: '1' });+ await client.connect(+ new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/evaluation/server.ts'), config],+ stderr: 'pipe',+ }),+ );try {- const results=await Promise.all([0,1].map(()=>client.callTool({name:'kiln_list_primitives',arguments:{}})));- expect(results.every(result=>result.isError!==true)).toBe(true);- expect(JSON.stringify(await client.callTool({name:'kiln_list_primitives',arguments:{}}))).toContain('budget-exhausted');- const events=(await readFile(join(directory,'result/events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));- expect(events.map(event=>event.sequence).sort()).toEqual([1,2,3]);- const requests=(await readFile(join(directory,'result/requests.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));- expect(requests.map(event=>event.sequence)).toEqual([1,2,3]);- } finally { await client.close(); }-},30000);+ const results = await Promise.all(+ [0, 1].map(() => client.callTool({ name: 'kiln_list_primitives', arguments: {} })),+ );+ expect(results.every((result) => result.isError !== true)).toBe(true);+ expect(+ JSON.stringify(await client.callTool({ name: 'kiln_list_primitives', arguments: {} })),+ ).toContain('budget-exhausted');+ const events = (await readFile(join(directory, 'result/events.jsonl'), 'utf8'))+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ expect(events.map((event) => event.sequence).sort()).toEqual([1, 2, 3]);+ const requests = (await readFile(join(directory, 'result/requests.jsonl'), 'utf8'))+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ expect(requests.map((event) => event.sequence)).toEqual([1, 2, 3]);+ } finally {+ await client.close();+ }+}, 30000);diff --git a/scripts/evaluation/server.ts b/scripts/evaluation/server.tsindex 2b426e12..e379d1fb 100644--- a/scripts/evaluation/server.ts+++ b/scripts/evaluation/server.ts@@ -15,92 +15,235 @@ import { runTool } from '../../src/mcp-server';const configPath = process.argv[2];if (!configPath) throw new Error('Usage: bun scripts/evaluation/server.ts RUN_CONFIG.json');const config = JSON.parse(await readFile(resolve(configPath), 'utf8')) as {- runId:string; condition:Condition; outputDirectory:string; programStoreDirectory:string; authorization:string;- maxToolCalls:number; maxImageCells:number; maxCellSide:number; maxWallSeconds:number; allowResume?:boolean;+ runId: string;+ condition: Condition;+ outputDirectory: string;+ programStoreDirectory: string;+ authorization: string;+ maxToolCalls: number;+ maxImageCells: number;+ maxCellSide: number;+ maxWallSeconds: number;+ allowResume?: boolean;};-if (!['A','B','C'].includes(config.condition) || !config.runId || !config.authorization || !config.programStoreDirectory)+if (+ !['A', 'B', 'C'].includes(config.condition) ||+ !config.runId ||+ !config.authorization ||+ !config.programStoreDirectory+)throw new Error('runId, condition and a declared authorization record are required.');-for (const key of ['maxToolCalls','maxImageCells','maxCellSide','maxWallSeconds'] as const)- if (!Number.isInteger(config[key]) || config[key] <= 0) throw new Error(`${key} must be a positive integer.`);+for (const key of ['maxToolCalls', 'maxImageCells', 'maxCellSide', 'maxWallSeconds'] as const)+ if (!Number.isInteger(config[key]) || config[key] <= 0)+ throw new Error(`${key} must be a positive integer.`);if (config.maxCellSide > 512) throw new Error('Pilot cells are capped at 512 pixels per side.');const output = resolve(config.outputDirectory);// Nonrecursive final creation refuses accidental reuse of a completed or active run directory.-let previous: any;-try { await mkdir(output); await mkdir(join(output,'images')); }-catch(error) {- if (!config.allowResume || (error as NodeJS.ErrnoException).code!=='EEXIST') throw error;- previous=JSON.parse(await readFile(join(output,'host.json'),'utf8'));- if (!isDeepStrictEqual(previous.config,config)) throw new Error('Resume configuration differs from frozen run.');+/**+ * The arguments the image-cell estimator below reads, and only those. The real+ * schema is each tool's own `inputSchema`; this is the pilot's view of it, so a+ * field appearing here is a field the budget depends on.+ */+type PilotToolInput = {+ render?: boolean;+ frames?: number;+ frameTimes?: unknown[];+ capture?: { shots?: unknown[]; cells?: unknown[]; preset?: unknown; size?: number };+};++let previous: { config?: unknown; deadline?: number } | undefined;+try {+ await mkdir(output);+ await mkdir(join(output, 'images'));+} catch (error) {+ if (!config.allowResume || (error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;+ previous = JSON.parse(await readFile(join(output, 'host.json'), 'utf8'));+ if (!isDeepStrictEqual(previous.config, config))+ throw new Error('Resume configuration differs from frozen run.');}-const deadline = previous?.deadline ?? Date.now()+config.maxWallSeconds*1000;+const deadline = previous?.deadline ?? Date.now() + config.maxWallSeconds * 1000;const session = new AbortController();-const timer = setTimeout(()=>session.abort(new Error('budget-exhausted: wall-time limit')),Math.max(1,deadline-Date.now()));+const timer = setTimeout(+ () => session.abort(new Error('budget-exhausted: wall-time limit')),+ Math.max(1, deadline - Date.now()),+);const requestSignals = new AsyncLocalStorage<AbortSignal>();const context = createLocalToolContext({- programStore:new FileProgramStore(resolve(config.programStoreDirectory)),- evaluationControls:()=>({signal:AbortSignal.any([session.signal,...(requestSignals.getStore() ? [requestSignals.getStore()!] : [])]),deadlineMs:Math.max(1,Math.min(60000,deadline-Date.now()))}),+ programStore: new FileProgramStore(resolve(config.programStoreDirectory)),+ evaluationControls: () => ({+ signal: AbortSignal.any([+ session.signal,+ ...(requestSignals.getStore() ? [requestSignals.getStore()!] : []),+ ]),+ deadlineMs: Math.max(1, Math.min(60000, deadline - Date.now())),+ }),});-const definitions = createConditionRegistry(config.condition,context);-const sha = (bytes: string | Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;-if (!previous) await writeFile(join(output,'host.json'), JSON.stringify({config,deadline,disabledHelpers:config.condition==='C'?[]:disabledHelperNames,execution:{...context.localExecution,cacheScope:'disabled',cacheReason:'Experimental adapter does not declare an evaluator cache identity'},adapterHash:sha(await readFile(new URL('./conditions.ts',import.meta.url))),note:'CPU-only matched pilot host. Transport delivery is not proof of model image consumption.'},null,2));-let calls=0,cells=0,pixels=0;+const definitions = createConditionRegistry(config.condition, context);+const sha = (bytes: string | Uint8Array) =>+ `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+if (!previous)+ await writeFile(+ join(output, 'host.json'),+ JSON.stringify(+ {+ config,+ deadline,+ disabledHelpers: config.condition === 'C' ? [] : disabledHelperNames,+ execution: {+ ...context.localExecution,+ cacheScope: 'disabled',+ cacheReason: 'Experimental adapter does not declare an evaluator cache identity',+ },+ adapterHash: sha(await readFile(new URL('./conditions.ts', import.meta.url))),+ note: 'CPU-only matched pilot host. Transport delivery is not proof of model image consumption.',+ },+ null,+ 2,+ ),+ );+let calls = 0,+ cells = 0,+ pixels = 0;if (previous) {- const records=async(name:string)=>{try{return (await readFile(join(output,name),'utf8')).trim().split('\n').filter(Boolean).map(line=>JSON.parse(line));}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return [];throw error;}};- calls=Math.max(0,...(await records('requests.jsonl')).map(record=>record.sequence));- const counters=(await records('events.jsonl')).at(-1)?.counters;- cells=counters?.reservedOrDeliveredCells ?? 0; pixels=counters?.pixels ?? 0;+ const records = async (name: string) => {+ try {+ return (await readFile(join(output, name), 'utf8'))+ .trim()+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];+ throw error;+ }+ };+ calls = Math.max(0, ...(await records('requests.jsonl')).map((record) => record.sequence));+ const counters = (await records('events.jsonl')).at(-1)?.counters;+ cells = counters?.reservedOrDeliveredCells ?? 0;+ pixels = counters?.pixels ?? 0;}const requestSequences = new Map<string | number, number>();-const server = new McpServer({name:'kiln-evaluation',version:'1.0.0'});-for (const def of definitions) server.registerTool(def.name,{description:def.description,inputSchema:def.inputSchema},async(args,request)=>{- const sequence=requestSequences.get(request.mcpReq.id);- if(sequence===undefined)throw new Error('Missing reserved pilot request sequence.');- const started=Date.now();- const input=args as Record<string,any>;- const estimate = !['kiln_render','kiln_edit','kiln_inspect','kiln_screenshot_animation','kiln_view_interior'].includes(def.name) || (def.name==='kiln_edit' && input.render===false) ? 0- : input.capture?.shots?.length ?? input.capture?.cells?.length ?? (input.capture?.preset ? String(input.capture.preset).split('x').reduce((a,b)=>a*Number(b),1) : def.name==='kiln_inspect' ? 1 : def.name==='kiln_view_interior' ? 3 : input.frameTimes?.length ?? input.frames ?? 6);- let reserved=false;- try {- if (Date.now() >= deadline || sequence>config.maxToolCalls || cells+estimate>config.maxImageCells || (input.capture?.size ?? 384)>config.maxCellSide) throw new Error('budget-exhausted: declared pilot limit');- // Reserve before awaiting so parallel requests cannot exceed the image-cell allowance.- cells+=estimate; reserved=true;- const result = await requestSignals.run(request.mcpReq.signal,()=>runTool(def,args));- const images: Array<{path:string;hash:string;width:number;height:number}>=[];- for (const block of result.content) if (block.type==='image') {- const data=Buffer.from(block.data,'base64');- const width=data.readUInt32BE(16),height=data.readUInt32BE(20);- pixels+=width*height;- const path=`images/${sequence}-${images.length}.png`;- await writeFile(join(output,path),data);- images.push({path,hash:sha(data),width,height});- }- if (!images.length) cells-=estimate;- reserved=false;- if (pixels > config.maxImageCells*config.maxCellSide*config.maxCellSide) throw new Error('budget-exhausted: delivered pixel limit');- await appendFile(join(output,'events.jsonl'),JSON.stringify({sequence,tool:def.name,args,startedAt:new Date(started).toISOString(),wallMs:Date.now()-started,result:{...result,content:result.content.filter((block)=>block.type!=='image')},images,counters:{calls,reservedOrDeliveredCells:cells,pixels}})+'\n');- return result;- } catch(error) {- if (reserved) cells-=estimate;- const message=error instanceof Error?error.message:String(error);- await appendFile(join(output,'events.jsonl'),JSON.stringify({sequence,tool:def.name,args,wallMs:Date.now()-started,error:message,counters:{calls,reservedOrDeliveredCells:cells,pixels}})+'\n');- return {isError:true,content:[{type:'text' as const,text:message}]};- }-});-process.on('exit',()=>clearTimeout(timer));+const server = new McpServer({ name: 'kiln-evaluation', version: '1.0.0' });+for (const def of definitions)+ server.registerTool(+ def.name,+ { description: def.description, inputSchema: def.inputSchema },+ async (args, request) => {+ const sequence = requestSequences.get(request.mcpReq.id);+ if (sequence === undefined) throw new Error('Missing reserved pilot request sequence.');+ const started = Date.now();+ const input = args as PilotToolInput;+ const estimate =+ ![+ 'kiln_render',+ 'kiln_edit',+ 'kiln_inspect',+ 'kiln_screenshot_animation',+ 'kiln_view_interior',+ ].includes(def.name) ||+ (def.name === 'kiln_edit' && input.render === false)+ ? 0+ : (input.capture?.shots?.length ??+ input.capture?.cells?.length ??+ (input.capture?.preset+ ? String(input.capture.preset)+ .split('x')+ .reduce((a, b) => a * Number(b), 1)+ : def.name === 'kiln_inspect'+ ? 1+ : def.name === 'kiln_view_interior'+ ? 3+ : (input.frameTimes?.length ?? input.frames ?? 6)));+ let reserved = false;+ try {+ if (+ Date.now() >= deadline ||+ sequence > config.maxToolCalls ||+ cells + estimate > config.maxImageCells ||+ (input.capture?.size ?? 384) > config.maxCellSide+ )+ throw new Error('budget-exhausted: declared pilot limit');+ // Reserve before awaiting so parallel requests cannot exceed the image-cell allowance.+ cells += estimate;+ reserved = true;+ const result = await requestSignals.run(request.mcpReq.signal, () => runTool(def, args));+ const images: Array<{ path: string; hash: string; width: number; height: number }> = [];+ for (const block of result.content)+ if (block.type === 'image') {+ const data = Buffer.from(block.data, 'base64');+ const width = data.readUInt32BE(16),+ height = data.readUInt32BE(20);+ pixels += width * height;+ const path = `images/${sequence}-${images.length}.png`;+ await writeFile(join(output, path), data);+ images.push({ path, hash: sha(data), width, height });+ }+ if (!images.length) cells -= estimate;+ reserved = false;+ if (pixels > config.maxImageCells * config.maxCellSide * config.maxCellSide)+ throw new Error('budget-exhausted: delivered pixel limit');+ await appendFile(+ join(output, 'events.jsonl'),+ `${JSON.stringify({+ sequence,+ tool: def.name,+ args,+ startedAt: new Date(started).toISOString(),+ wallMs: Date.now() - started,+ result: {+ ...result,+ content: result.content.filter((block) => block.type !== 'image'),+ },+ images,+ counters: { calls, reservedOrDeliveredCells: cells, pixels },+ })}\n`,+ );+ return result;+ } catch (error) {+ if (reserved) cells -= estimate;+ const message = error instanceof Error ? error.message : String(error);+ await appendFile(+ join(output, 'events.jsonl'),+ `${JSON.stringify({+ sequence,+ tool: def.name,+ args,+ wallMs: Date.now() - started,+ error: message,+ counters: { calls, reservedOrDeliveredCells: cells, pixels },+ })}\n`,+ );+ return { isError: true, content: [{ type: 'text' as const, text: message }] };+ }+ },+ );+process.on('exit', () => clearTimeout(timer));timer.unref();-const underlying=new StdioServerTransport();-const transport:Transport={start:()=>underlying.start(),send:(message)=>{- if('id' in message)requestSequences.delete(message.id);- return underlying.send(message);-},close:()=>underlying.close()};-underlying.onmessage=(message)=>{- if ('method' in message && message.method==='tools/call') {- const sequence=++calls;- appendFileSync(join(output,'requests.jsonl'),JSON.stringify({sequence,method:message.method,paramsHash:sha(JSON.stringify(message.params ?? {})),receivedAt:new Date().toISOString()})+'\n');- if('id' in message)requestSequences.set(message.id,sequence);+const underlying = new StdioServerTransport();+const transport: Transport = {+ start: () => underlying.start(),+ send: (message) => {+ if ('id' in message) requestSequences.delete(message.id);+ return underlying.send(message);+ },+ close: () => underlying.close(),+};+underlying.onmessage = (message) => {+ if ('method' in message && message.method === 'tools/call') {+ const sequence = ++calls;+ appendFileSync(+ join(output, 'requests.jsonl'),+ `${JSON.stringify({+ sequence,+ method: message.method,+ paramsHash: sha(JSON.stringify(message.params ?? {})),+ receivedAt: new Date().toISOString(),+ })}\n`,+ );+ if ('id' in message) requestSequences.set(message.id, sequence);transport.onmessage?.(message);} else transport.onmessage?.(message);};-underlying.onerror=(error)=>transport.onerror?.(error);-underlying.onclose=()=>transport.onclose?.();-void serveStdio(() => server,{transport});+underlying.onerror = (error) => transport.onerror?.(error);+underlying.onclose = () => transport.onclose?.();+void serveStdio(() => server, { transport });diff --git a/scripts/experiment-program-aliases.ts b/scripts/experiment-program-aliases.tsindex df04dbc7..e833d349 100644--- a/scripts/experiment-program-aliases.ts+++ b/scripts/experiment-program-aliases.ts@@ -5,44 +5,85 @@ import { FileProgramStore } from '../src/program-store-node';import { ExperimentalProgramAliases } from '../src/experiments/program-aliases';if (process.argv[2] === '--child') {- const directory=process.argv[3]!, expected=process.argv[4]!, next=process.argv[5]!;- const aliases=new ExperimentalProgramAliases(join(directory,'aliases'),new FileProgramStore(join(directory,'programs')));- try { await aliases.compareAndSet('bridge',expected,next); console.log(JSON.stringify({status:'updated'})); }- catch(error) {- const message=(error as Error).message;+ const directory = process.argv[3]!,+ expected = process.argv[4]!,+ next = process.argv[5]!;+ const aliases = new ExperimentalProgramAliases(+ join(directory, 'aliases'),+ new FileProgramStore(join(directory, 'programs')),+ );+ try {+ await aliases.compareAndSet('bridge', expected, next);+ console.log(JSON.stringify({ status: 'updated' }));+ } catch (error) {+ const message = (error as Error).message;if (!message.includes('conflict') && !message.includes('busy')) throw error;- console.log(JSON.stringify({status:message.includes('conflict')?'conflict':'busy'}));+ console.log(JSON.stringify({ status: message.includes('conflict') ? 'conflict' : 'busy' }));}} else {- const directory=await mkdtemp(join(tmpdir(),'kiln-alias-concurrency-'));+ const directory = await mkdtemp(join(tmpdir(), 'kiln-alias-concurrency-'));try {- const store=new FileProgramStore(join(directory,'programs'));- const aliases=new ExperimentalProgramAliases(join(directory,'aliases'),store);- const refs=await Promise.all(['original','candidate-a','candidate-b'].map(code=>store.put(code)));- await aliases.compareAndSet('bridge',null,refs[0]!);- const children=Array.from({length:8},(_,i)=>{- const child=Bun.spawn([process.execPath,import.meta.path,'--child',directory,refs[0]!,refs[1+i%2]!],{stdout:'pipe',stderr:'pipe'});- const timer=setTimeout(()=>child.kill(),10000);- return (async()=>{+ const store = new FileProgramStore(join(directory, 'programs'));+ const aliases = new ExperimentalProgramAliases(join(directory, 'aliases'), store);+ const refs = await Promise.all(+ ['original', 'candidate-a', 'candidate-b'].map((code) => store.put(code)),+ );+ await aliases.compareAndSet('bridge', null, refs[0]!);+ const children = Array.from({ length: 8 }, (_, i) => {+ const child = Bun.spawn(+ [process.execPath, import.meta.path, '--child', directory, refs[0]!, refs[1 + (i % 2)]!],+ { stdout: 'pipe', stderr: 'pipe' },+ );+ const timer = setTimeout(() => child.kill(), 10000);+ return (async () => {try {- const [code,stdout,stderr]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);- if(code!==0) throw new Error(`Worker failed: ${stderr}`);- return JSON.parse(stdout) as {status:string};- } finally {clearTimeout(timer);}+ const [code, stdout, stderr] = await Promise.all([+ child.exited,+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ ]);+ if (code !== 0) throw new Error(`Worker failed: ${stderr}`);+ return JSON.parse(stdout) as { status: string };+ } finally {+ clearTimeout(timer);+ }})();});- const results=await Promise.all(children);- const updated=results.filter(result=>result.status==='updated').length;- if(updated!==1) throw new Error(`Expected one winner, received ${updated}`);- const finalRef=await aliases.resolve('bridge');- if(!refs.slice(1).includes(finalRef!)) throw new Error('Alias target is not a candidate');- const immutableSources=await Promise.all(refs.map(ref=>new FileProgramStore(store.directory).get(ref)));- if(JSON.stringify(immutableSources)!==JSON.stringify(['original','candidate-a','candidate-b'])) throw new Error('Immutable sources changed');- const receipt={experiment:'R0 project-local alias compare-and-set',processes:8,updated,rejected:7,- rejectionKinds:[...new Set(results.filter(result=>result.status!=='updated').map(result=>result.status))].sort(),- immutableReferencesResolved:refs.length,originalSourcePreserved:true,finalAliasIsCandidate:true,- usability:'Not evaluated; clean-room model pilot required before stable adoption'};- if(process.argv[2]!=='--check') await writeFile(resolve(import.meta.dir,'../docs/experiments/program-aliases-results.json'),JSON.stringify(receipt,null,2)+'\n');- console.log(JSON.stringify(receipt,null,2));- } finally { await rm(directory,{recursive:true,force:true}); }+ const results = await Promise.all(children);+ const updated = results.filter((result) => result.status === 'updated').length;+ if (updated !== 1) throw new Error(`Expected one winner, received ${updated}`);+ const finalRef = await aliases.resolve('bridge');+ if (!refs.slice(1).includes(finalRef!)) throw new Error('Alias target is not a candidate');+ const immutableSources = await Promise.all(+ refs.map((ref) => new FileProgramStore(store.directory).get(ref)),+ );+ if (+ JSON.stringify(immutableSources) !==+ JSON.stringify(['original', 'candidate-a', 'candidate-b'])+ )+ throw new Error('Immutable sources changed');+ const receipt = {+ experiment: 'R0 project-local alias compare-and-set',+ processes: 8,+ updated,+ rejected: 7,+ rejectionKinds: [+ ...new Set(+ results.filter((result) => result.status !== 'updated').map((result) => result.status),+ ),+ ].sort(),+ immutableReferencesResolved: refs.length,+ originalSourcePreserved: true,+ finalAliasIsCandidate: true,+ usability: 'Not evaluated; clean-room model pilot required before stable adoption',+ };+ if (process.argv[2] !== '--check')+ await writeFile(+ resolve(import.meta.dir, '../docs/experiments/program-aliases-results.json'),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ console.log(JSON.stringify(receipt, null, 2));+ } finally {+ await rm(directory, { recursive: true, force: true });+ }}diff --git a/scripts/experiment-reusable-parts.ts b/scripts/experiment-reusable-parts.tsindex e31a80f0..0c9ffe25 100644--- a/scripts/experiment-reusable-parts.ts+++ b/scripts/experiment-reusable-parts.ts@@ -6,13 +6,18 @@ import { executeKilnCode } from '../src/render';import { KilnDraftBuffer } from '../src/edit-buffer';import type * as THREE from 'three';-const recipe = readFileSync(resolve(import.meta.dir, '../skills/kiln-author-asset/references/reusable-frame.kiln.js'), 'utf8').replace(/\r\n/g, '\n');+const recipe = readFileSync(+ resolve(import.meta.dir, '../skills/kiln-author-asset/references/reusable-frame.kiln.js'),+ 'utf8',+).replace(/\r\n/g, '\n');const helper = recipe.slice(0, recipe.indexOf('const meta'));const body = helper.slice(helper.indexOf(' const { width'), helper.lastIndexOf('}'));function source(count: number, expanded: boolean): string {- const assemblies = Array.from({length: count}, (_, i) => {+ const assemblies = Array.from({ length: count }, (_, i) => {const args = `'Frame${i}', { width: 2.4, height: 2.6, depth: 0.18, post: 0.14 }, steel, root`;- const expression = expanded ? `((name, spec, material, parent) => {${body}})(${args})` : `makeFrame(${args})`;+ const expression = expanded+ ? `((name, spec, material, parent) => {${body}})(${args})`+ : `makeFrame(${args})`;return `const frame${i} = ${expression}; frame${i}.root.position.x = ${i * 1.5};`;}).join('\n');return `${expanded ? '' : helper}const meta={name:'Repeated frames',category:'architecture'};\nfunction build(){const root=createRoot('Frames');const steel=gameMaterial(0x3b7278);\n${assemblies}\nreturn root;}`;@@ -20,34 +25,57 @@ function source(count: number, expanded: boolean): string {function snapshot(root: THREE.Object3D) {root.updateMatrixWorld(true);const records: unknown[] = [];- root.traverse(node => {+ root.traverse((node) => {const mesh = node as THREE.Mesh;- records.push({name: node.name, matrix: node.matrixWorld.toArray(),- positions: mesh.isMesh ? Array.from(mesh.geometry.getAttribute('position').array) : undefined});+ records.push({+ name: node.name,+ matrix: node.matrixWorld.toArray(),+ positions: mesh.isMesh ? Array.from(mesh.geometry.getAttribute('position').array) : undefined,+ });});return JSON.stringify(records);}const trials = [];for (const count of [1, 3, 16]) {- const compact = source(count, false), expanded = source(count, true);- const a = await executeKilnCode(compact), b = await executeKilnCode(expanded);+ const compact = source(count, false),+ expanded = source(count, true);+ const a = await executeKilnCode(compact),+ b = await executeKilnCode(expanded);const equal = snapshot(a.root) === snapshot(b.root);if (!equal) throw new Error('Expanded and reusable assemblies differ');const oldString = "'Frame0', { width: 2.4, height: 2.6";const newString = "'Frame0', { width: 2.4, height: 3.1";const draft = new KilnDraftBuffer(compact);- if (!draft.apply({oldString, newString}).ok) throw new Error('Revision failed');+ if (!draft.apply({ oldString, newString }).ok) throw new Error('Revision failed');const edited = (await executeKilnCode(draft.code)).root;const target = edited.getObjectByName('Joint_Frame0')!;const anchorY = target.getObjectByName('Joint_TopAttachment')!.position.y;if (anchorY !== 3.1) throw new Error('Attachment did not follow parameter');- for (let i=1;i<count;i++) {- if (snapshot(a.root.getObjectByName(`Joint_Frame${i}`)!) !== snapshot(edited.getObjectByName(`Joint_Frame${i}`)!)) throw new Error('Unrelated assembly changed');+ for (let i = 1; i < count; i++) {+ if (+ snapshot(a.root.getObjectByName(`Joint_Frame${i}`)!) !==+ snapshot(edited.getObjectByName(`Joint_Frame${i}`)!)+ )+ throw new Error('Unrelated assembly changed');}- trials.push({count, reusableBytes: Buffer.byteLength(compact), expandedBytes: Buffer.byteLength(expanded), identicalGeometryAndTransforms: equal,- editArgumentBytes: Buffer.byteLength(JSON.stringify({oldString,newString})), revisedAnchorY: anchorY, unchangedSiblingAssemblies: count-1,- semanticsSha256: createHash('sha256').update(snapshot(a.root)).digest('hex')});+ trials.push({+ count,+ reusableBytes: Buffer.byteLength(compact),+ expandedBytes: Buffer.byteLength(expanded),+ identicalGeometryAndTransforms: equal,+ editArgumentBytes: Buffer.byteLength(JSON.stringify({ oldString, newString })),+ revisedAnchorY: anchorY,+ unchangedSiblingAssemblies: count - 1,+ semanticsSha256: createHash('sha256').update(snapshot(a.root)).digest('hex'),+ });}-const receipt = {experiment: 'X4 ordinary reusable parts', scope:'Offline deterministic assembly comparison; no model or visual-quality claim', trials};-writeFileSync(resolve(import.meta.dir, '../docs/experiments/reusable-parts-results.json'), JSON.stringify(receipt,null,2)+'\n');-console.log(JSON.stringify(receipt,null,2));+const receipt = {+ experiment: 'X4 ordinary reusable parts',+ scope: 'Offline deterministic assembly comparison; no model or visual-quality claim',+ trials,+};+writeFileSync(+ resolve(import.meta.dir, '../docs/experiments/reusable-parts-results.json'),+ `${JSON.stringify(receipt, null, 2)}\n`,+);+console.log(JSON.stringify(receipt, null, 2));diff --git a/scripts/gallery-history.test.ts b/scripts/gallery-history.test.tsindex c55fc8c5..8424dd03 100644--- a/scripts/gallery-history.test.ts+++ b/scripts/gallery-history.test.ts@@ -15,8 +15,18 @@ const record = () => ({currentSourceHash: hash(current),brief: { kind: 'summary', text: 'Make a workbench with a lower shelf.' },revisions: [- { title: 'First draft', description: 'Initial shelf position.', file: 'initial.kiln.js', sourceHash: hash(initial) },- { title: 'Raised shelf', description: 'Only the shelf height changed.', file: 'current.kiln.js', sourceHash: hash(current) },+ {+ title: 'First draft',+ description: 'Initial shelf position.',+ file: 'initial.kiln.js',+ sourceHash: hash(initial),+ },+ {+ title: 'Raised shelf',+ description: 'Only the shelf height changed.',+ file: 'current.kiln.js',+ sourceHash: hash(current),+ },],});@@ -42,25 +52,39 @@ describe('published example history', () => {const { input, output } = await fixture('valid', value);const result = await buildExampleHistory('workbench', current, input, output);expect(result?.brief).toEqual(value.brief);- expect(result?.revisions.map((entry: { current: boolean }) => entry.current)).toEqual([true, false]);+ expect(result?.revisions.map((entry: { current: boolean }) => entry.current)).toEqual([+ true,+ false,+ ]);expect(result?.revisions[1].source).toBe('assets/history/workbench/initial.kiln.js');expect(await readFile(join(output, 'history/workbench/initial.kiln.js'), 'utf8')).toBe(initial);expect(await readFile(join(output, 'history/workbench/current.kiln.js'), 'utf8')).toBe(current);});test('missing historical records stay unknown', async () => {- expect(await buildExampleHistory('workbench', current, join(workspace, 'missing'), join(workspace, 'unused'))).toBeUndefined();+ expect(+ await buildExampleHistory(+ 'workbench',+ current,+ join(workspace, 'missing'),+ join(workspace, 'unused'),+ ),+ ).toBeUndefined();});test('rejects attribution for a different displayed source', async () => {const { input, output } = await fixture('stale-current');- await expect(buildExampleHistory('workbench', 'changed source', input, output)).rejects.toThrow('displayed source');+ await expect(buildExampleHistory('workbench', 'changed source', input, output)).rejects.toThrow(+ 'displayed source',+ );});test('rejects changed snapshot bytes before publishing any history files', async () => {const { input, output } = await fixture('stale-revision');await writeFile(join(input, 'current.kiln.js'), 'changed source');- await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow('snapshot hash');+ await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow(+ 'snapshot hash',+ );await expect(readFile(join(output, 'history/workbench/initial.kiln.js'))).rejects.toThrow();});@@ -68,13 +92,17 @@ describe('published example history', () => {const value = record();value.revisions[0]!.file = '../private.kiln.js';const { input, output } = await fixture('unsafe', value);- await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow('snapshot filename');+ await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow(+ 'snapshot filename',+ );});test('requires the displayed revision to be represented', async () => {const value = record();value.revisions.pop();const { input, output } = await fixture('no-current', value);- await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow('displayed revision');+ await expect(buildExampleHistory('workbench', current, input, output)).rejects.toThrow(+ 'displayed revision',+ );});});diff --git a/scripts/generate-tool-reference.ts b/scripts/generate-tool-reference.tsindex 0f853dc7..c3b2b91f 100644--- a/scripts/generate-tool-reference.ts+++ b/scripts/generate-tool-reference.ts@@ -4,19 +4,24 @@ import { z } from 'zod';import { createKilnProgramToolRegistry } from '../src/tools/registry';const tools = createKilnProgramToolRegistry();-const content = [+const content = `${['# Tool reference','Generated from the public registry with `bun run docs:tools`. Change the registry to update names, descriptions or schemas; use `bun run docs:tools --check` to check for drift.','Use these tools through your connected agent. Supply `code` once, then pass the returned `programRef` to later calls. References identify exact source revisions. [Source workflow](programs.md) · [Camera recipes](cameras.md) · [Geometry guide](geometry.md).','Call `kiln_list_primitives({capabilities:true})` for the current host limits and export/camera support. The schema below describes inputs; actual image replies include fidelity and capture metadata. Source reads return exact text, edits return a new revision, and failed builds return their errors.',- ...tools.flatMap(tool => {+ ...tools.flatMap((tool) => {const schema = z.toJSONSchema(tool.inputSchema);- return [`## ${tool.name}`, tool.description, '<details>\n<summary>Input JSON Schema</summary>\n', '```json\n' + JSON.stringify(schema, null, 2) + '\n```\n\n</details>'];+ return [+ `## ${tool.name}`,+ tool.description,+ '<details>\n<summary>Input JSON Schema</summary>\n',+ `\`\`\`json\n${JSON.stringify(schema, null, 2)}\n\`\`\`\n\n</details>`,+ ];}),-].join('\n\n') + '\n';+].join('\n\n')}\n`;const path = fileURLToPath(new URL('../docs/tools.md', import.meta.url));if (process.argv.includes('--check')) {- if (await readFile(path, 'utf8').catch(() => '') !== content) {+ if ((await readFile(path, 'utf8').catch(() => '')) !== content) {console.error('Tool reference differs from the registry. Run bun run docs:tools.');process.exitCode = 1;}diff --git a/scripts/geometry-acceptance.mjs b/scripts/geometry-acceptance.mjsindex eea7e468..bd723ddf 100644--- a/scripts/geometry-acceptance.mjs+++ b/scripts/geometry-acceptance.mjs@@ -1,13 +1,57 @@import { spawnSync } from 'node:child_process';import { mkdirSync, writeFileSync } from 'node:fs';import { resolve } from 'node:path';-const cases=['bevel-concave-profile','bevel-concave','bevel-mixed','bevel-thin','shell-open-plane-in','shell-open-plane-out','shell-curved-in','shell-curved-out','shell-curved-collision','remesh-deformed','remesh-uneven','remesh-boolean'];-const results=[];-for(const id of cases){- const result=spawnSync('bun',[id==='bevel-concave-profile'?'scripts/geometry-profile-control.ts':'src/experiments/geometry-acceptance.ts',id],{cwd:resolve(import.meta.dirname,'..'),encoding:'utf8',timeout:20000,windowsHide:true,maxBuffer:1024*1024});- let record;- if(result.status===0){try{record=JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));}catch{record={id,status:'invalid-output',stdout:result.stdout};}}- else record={id,status:result.error?.code==='ETIMEDOUT'?'timeout':'failed',stderr:result.stderr.slice(-1500)};- results.push(record);console.log(JSON.stringify(record));+const cases = [+ 'bevel-concave-profile',+ 'bevel-concave',+ 'bevel-mixed',+ 'bevel-thin',+ 'shell-open-plane-in',+ 'shell-open-plane-out',+ 'shell-curved-in',+ 'shell-curved-out',+ 'shell-curved-collision',+ 'remesh-deformed',+ 'remesh-uneven',+ 'remesh-boolean',+];+const results = [];+for (const id of cases) {+ const result = spawnSync(+ 'bun',+ [+ id === 'bevel-concave-profile'+ ? 'scripts/geometry-profile-control.ts'+ : 'src/experiments/geometry-acceptance.ts',+ id,+ ],+ {+ cwd: resolve(import.meta.dirname, '..'),+ encoding: 'utf8',+ timeout: 20000,+ windowsHide: true,+ maxBuffer: 1024 * 1024,+ },+ );+ let record;+ if (result.status === 0) {+ try {+ record = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));+ } catch {+ record = { id, status: 'invalid-output', stdout: result.stdout };+ }+ } else+ record = {+ id,+ status: result.error?.code === 'ETIMEDOUT' ? 'timeout' : 'failed',+ stderr: result.stderr.slice(-1500),+ };+ results.push(record);+ console.log(JSON.stringify(record));}-const directory=resolve(import.meta.dirname,'../output/geometry-acceptance');mkdirSync(directory,{recursive:true});writeFileSync(resolve(directory,'results.json'),JSON.stringify({node:process.version,perCaseTimeoutMs:20000,results},null,2)+'\n');+const directory = resolve(import.meta.dirname, '../output/geometry-acceptance');+mkdirSync(directory, { recursive: true });+writeFileSync(+ resolve(directory, 'results.json'),+ `${JSON.stringify({ node: process.version, perCaseTimeoutMs: 20000, results }, null, 2)}\n`,+);diff --git a/scripts/geometry-experiments.mjs b/scripts/geometry-experiments.mjsindex f1b437a4..809bc29e 100644--- a/scripts/geometry-experiments.mjs+++ b/scripts/geometry-experiments.mjs@@ -1,14 +1,50 @@import { spawnSync } from 'node:child_process';import { mkdirSync, writeFileSync } from 'node:fs';import { resolve } from 'node:path';-const cases=['bevel-box-profile','bevel-box-minkowski','bevel-holed-profile','bevel-holed-minkowski','shell-sphere-normal-offset','shell-box-normal-offset','shell-thin-normal-offset','remesh-box-field','remesh-thin-field','sdf-sphere-coarse','sdf-sphere-fine','sdf-cellular'];-const results=[];-for(const id of cases){- const started=performance.now();- const result=spawnSync('bun',['src/experiments/geometry-frontier.ts',id],{cwd:resolve(import.meta.dirname,'..'),encoding:'utf8',timeout:20000,windowsHide:true,maxBuffer:1024*1024});- let record;- if(result.status===0){try{record=JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));}catch{record={id,status:'invalid-output',stdout:result.stdout};}}- else record={id,status:result.error?.code==='ETIMEDOUT'?'timeout':'failed',wallMs:performance.now()-started,stderr:result.stderr.slice(-1500)};- results.push(record);console.log(JSON.stringify(record));+const cases = [+ 'bevel-box-profile',+ 'bevel-box-minkowski',+ 'bevel-holed-profile',+ 'bevel-holed-minkowski',+ 'shell-sphere-normal-offset',+ 'shell-box-normal-offset',+ 'shell-thin-normal-offset',+ 'remesh-box-field',+ 'remesh-thin-field',+ 'sdf-sphere-coarse',+ 'sdf-sphere-fine',+ 'sdf-cellular',+];+const results = [];+for (const id of cases) {+ const started = performance.now();+ const result = spawnSync('bun', ['src/experiments/geometry-frontier.ts', id], {+ cwd: resolve(import.meta.dirname, '..'),+ encoding: 'utf8',+ timeout: 20000,+ windowsHide: true,+ maxBuffer: 1024 * 1024,+ });+ let record;+ if (result.status === 0) {+ try {+ record = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));+ } catch {+ record = { id, status: 'invalid-output', stdout: result.stdout };+ }+ } else+ record = {+ id,+ status: result.error?.code === 'ETIMEDOUT' ? 'timeout' : 'failed',+ wallMs: performance.now() - started,+ stderr: result.stderr.slice(-1500),+ };+ results.push(record);+ console.log(JSON.stringify(record));}-const directory=resolve(import.meta.dirname,'../output/geometry-experiments');mkdirSync(directory,{recursive:true});writeFileSync(resolve(directory,'results.json'),JSON.stringify({node:process.version,perCaseTimeoutMs:20000,results},null,2)+'\n');+const directory = resolve(import.meta.dirname, '../output/geometry-experiments');+mkdirSync(directory, { recursive: true });+writeFileSync(+ resolve(directory, 'results.json'),+ `${JSON.stringify({ node: process.version, perCaseTimeoutMs: 20000, results }, null, 2)}\n`,+);diff --git a/scripts/geometry-profile-control.ts b/scripts/geometry-profile-control.tsindex e3e384af..d90011d3 100644--- a/scripts/geometry-profile-control.ts+++ b/scripts/geometry-profile-control.ts@@ -2,7 +2,33 @@ import { extrudeProfile } from '../src/profile';import { getManifoldModule } from '../src/solids';import { geometryDiagnostics } from '../src/geometry';await getManifoldModule();-const start=performance.now();-const geometry=await extrudeProfile([[-1,-.35],[-.35,-.35],[-.35,-1],[.35,-1],[.35,-.35],[1,-.35],[1,.35],[.35,.35],[.35,1],[-.35,1],[-.35,.35],[-1,.35]],{depth:1,axis:'z',bevel:.1});+const start = performance.now();+const geometry = await extrudeProfile(+ [+ [-1, -0.35],+ [-0.35, -0.35],+ [-0.35, -1],+ [0.35, -1],+ [0.35, -0.35],+ [1, -0.35],+ [1, 0.35],+ [0.35, 0.35],+ [0.35, 1],+ [-0.35, 1],+ [-0.35, 0.35],+ [-1, 0.35],+ ],+ { depth: 1, axis: 'z', bevel: 0.1 },+);geometry.computeBoundingBox();-console.log(JSON.stringify({id:'bevel-concave-profile',elapsedMs:performance.now()-start,triangles:(geometry.index?.count??geometry.getAttribute('position').count)/3,bounds:{min:geometry.boundingBox!.min.toArray(),max:geometry.boundingBox!.max.toArray()},topology:geometryDiagnostics(geometry),capEdgesRounded:false,selectedEdgeControl:'sweep-axis edges only'}));+console.log(+ JSON.stringify({+ id: 'bevel-concave-profile',+ elapsedMs: performance.now() - start,+ triangles: (geometry.index?.count ?? geometry.getAttribute('position').count) / 3,+ bounds: { min: geometry.boundingBox!.min.toArray(), max: geometry.boundingBox!.max.toArray() },+ topology: geometryDiagnostics(geometry),+ capEdgesRounded: false,+ selectedEdgeControl: 'sweep-axis edges only',+ }),+);diff --git a/scripts/harness-smoke.mjs b/scripts/harness-smoke.mjsindex eb8dad81..7e1343fc 100644--- a/scripts/harness-smoke.mjs+++ b/scripts/harness-smoke.mjs@@ -87,19 +87,30 @@ async function smoke(name, harness, opts) {// but a report that names the model you requested is telling you your own// input back, and this script exists to stop doing that.const ran = harness.actualModel?.(r.out) ?? null;- const used = ran && ran !== String(model ?? '').split('/').pop() ? `${ran} (asked for ${model})` : model;+ const used =+ ran &&+ ran !==+ String(model ?? '')+ .split('/')+ .pop()+ ? `${ran} (asked for ${model})`+ : model;if (!existsSync(file)) {// The distinction that matters for a wiring bug: a child that never saw the// tools usually says so in as many words, and that reads very differently// from a model that tried and produced nothing.- const said = /no such tool|not available|don't have|do not have|unable to|no tools/i.test(r.out);+ const said = /no such tool|not available|don't have|do not have|unable to|no tools/i.test(+ r.out,+ );return {name,model: used,secs,ok: false,- why: said ? 'agent reported the Kiln tools were unavailable' : `no program written (exit ${r.code})`,+ why: said+ ? 'agent reported the Kiln tools were unavailable'+ : `no program written (exit ${r.code})`,out: r.out,};}@@ -141,12 +152,21 @@ async function main() {process.stdout.write(`${name.padEnd(9)} running...`);const r = await smoke(name, harness, opts);results.push(r);- console.log(`\r${name.padEnd(9)} ${r.ok ? 'ok ' : 'FAIL'} ${`${r.secs}s`.padStart(5)} ${r.model ?? '(configured default)'} ${r.why}`);+ console.log(+ `\r${name.padEnd(9)} ${r.ok ? 'ok ' : 'FAIL'} ${`${r.secs}s`.padStart(5)} ${r.model ?? '(configured default)'} ${r.why}`,+ );// On a failure the sandbox is the only copy of the evidence -- the brief the// child was given, its log, and whatever it did or did not write. It stays// on disk; `makeSandbox` clears it at the start of the next run anyway.if (!r.ok) {- console.log(r.out.trim().split('\n').slice(-12).map((l) => ` ${l}`).join('\n'));+ console.log(+ r.out+ .trim()+ .split('\n')+ .slice(-12)+ .map((l) => ` ${l}`)+ .join('\n'),+ );console.log(` sandbox: ${join(tmpdir(), 'kiln-dispatch', `smoke-${name}`)}`);}}@@ -156,7 +176,9 @@ async function main() {console.log('\nno harness CLIs installed; nothing was verified');process.exit(2);}- console.log(`\n${results.length - failed.length}/${results.length} harnesses reached the Kiln tools`);+ console.log(+ `\n${results.length - failed.length}/${results.length} harnesses reached the Kiln tools`,+ );process.exit(failed.length === 0 ? 0 : 1);}diff --git a/scripts/harness.mjs b/scripts/harness.mjsindex 9b0fb042..a43d5007 100644--- a/scripts/harness.mjs+++ b/scripts/harness.mjs@@ -47,7 +47,10 @@ function declaredOutputLimit(model) {}/** Colour codes are noise when you are trying to read a model name out of a log. */-const stripAnsi = (s) => String(s).replaceAll(/\[[0-9;]*m|\[0m/g, '');+// The rule is for control characters that arrived by accident. Stripping ANSI+// means matching ESC, so here it is the point of the expression.+// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ESC is deliberate+const stripAnsi = (s) => String(s).replaceAll(/\u001B\[[0-9;]*m|\[0m/gu, '');// One entry per harness. `argv` is a function so a harness that needs the// prompt attached to a flag (agy) and one that takes it positionally (claude,@@ -59,10 +62,14 @@ export const HARNESSES = {// --print takes its prompt ATTACHED. Passed separately, Go's flag package// reads the next flag as the prompt and silently ignores what you typed.argv: ({ model, prompt, timeout, logFile, sandbox }) => [- '--model', model,- '--print-timeout', timeout,- '--add-dir', sandbox,- '--log-file', logFile,+ '--model',+ model,+ '--print-timeout',+ timeout,+ '--add-dir',+ sandbox,+ '--log-file',+ logFile,`--print=${prompt}`,],// agy prints "Agent execution terminated due to error." to stdout and puts@@ -92,11 +99,16 @@ export const HARNESSES = {// belt-and-braces copy other harnesses can read. Both server names appear// because the tool prefix depends on how Kiln was installed.argv: ({ model, prompt, sandbox }) => [- '-p', prompt,- '--model', model,- '--permission-mode', 'acceptEdits',- '--allowedTools', 'mcp__plugin_kiln_kiln mcp__kiln Read Write Edit Glob Grep',- '--add-dir', sandbox,+ '-p',+ prompt,+ '--model',+ model,+ '--permission-mode',+ 'acceptEdits',+ '--allowedTools',+ 'mcp__plugin_kiln_kiln mcp__kiln Read Write Edit Glob Grep',+ '--add-dir',+ sandbox,],fallbackModels: [],},@@ -110,7 +122,12 @@ export const HARNESSES = {// exact contamination `makeSandbox` exists to prevent.codex: {bin: 'codex',- probe: (model) => ['exec', ...modelFlag(model), '--skip-git-repo-check', 'reply with the single word OK'],+ probe: (model) => [+ 'exec',+ ...modelFlag(model),+ '--skip-git-repo-check',+ 'reply with the single word OK',+ ],// No default model, deliberately. Codex rejects a model its account is not// entitled to -- `gpt-5.1-codex` came back "not supported when using Codex// with a ChatGPT account" -- and which ids an account can reach is not@@ -135,7 +152,8 @@ export const HARNESSES = {...modelFlag(model),'--approve-for-me','--skip-git-repo-check',- '--cd', sandbox,+ '--cd',+ sandbox,prompt,],fallbackModels: [],@@ -206,7 +224,6 @@ export const HARNESSES = {},};-// Windows: resolve the executable ourselves rather than asking for a shell.// `shell: true` concatenates argv into one command line, and the prompt is// multi-line -- so with a shell the child sees a mangled command and exits 2@@ -232,7 +249,10 @@ export function resolveBin(bin) {if (process.platform !== 'win32') return { cmd: bin, shell: false };if (!binCache.has(bin)) {const r = spawnSync('where', [bin], { encoding: 'utf8', shell: true });- const lines = (r.stdout ?? '').split('\n').map((l) => l.trim()).filter(Boolean);+ const lines = (r.stdout ?? '')+ .split('\n')+ .map((l) => l.trim())+ .filter(Boolean);const exe = lines.find((l) => l.toLowerCase().endsWith('.exe'));const shim = lines.find((l) => /\.(cmd|bat)$/i.test(l));binCache.set(bin, exe ? { cmd: exe, shell: false } : { cmd: shim ?? bin, shell: true });@@ -248,7 +268,8 @@ export function resolveBin(bin) {* containing a space -- a prompt, a Windows path under `Program Files` -- is* split at the space by the shell.*/-export const quoteArg = (a) => (/[\s"^&|<>]/.test(a) ? `"${String(a).replaceAll('"', '""')}"` : String(a));+export const quoteArg = (a) =>+ /[\s"^&|<>]/.test(a) ? `"${String(a).replaceAll('"', '""')}"` : String(a);/** '25m' / '90s' / '3600' -> milliseconds. */export function parseDuration(v) {@@ -298,7 +319,11 @@ export function killTree(child) {* output and no error. This kills it and reports the timeout as a normal failure* so the caller can move to the next model.*/-export function run(bin, args, { cwd = REPO, capture = true, logFile = null, timeoutMs = null, env = null } = {}) {+export function run(+ bin,+ args,+ { cwd = REPO, capture = true, logFile = null, timeoutMs = null, env = null } = {},+) {if (logFile) rmSync(logFile, { force: true });return new Promise((res) => {const resolved = resolveBin(bin);@@ -321,12 +346,22 @@ export function run(bin, args, { cwd = REPO, capture = true, logFile = null, timconst detached = process.platform !== 'win32';const childEnv = env ? { ...process.env, ...env } : process.env;const child = resolved.shell- ? spawn(quoteArg(resolved.cmd), args.map(quoteArg), { cwd, shell: true, stdio, detached, env: childEnv })+ ? spawn(quoteArg(resolved.cmd), args.map(quoteArg), {+ cwd,+ shell: true,+ stdio,+ detached,+ env: childEnv,+ }): spawn(resolved.cmd, args, { cwd, shell: false, stdio, detached, env: childEnv });let out = '';if (capture) {- child.stdout.on('data', (d) => { out += d; });- child.stderr.on('data', (d) => { out += d; });+ child.stdout.on('data', (d) => {+ out += d;+ });+ child.stderr.on('data', (d) => {+ out += d;+ });}let settled = false;let grace = null;@@ -338,7 +373,9 @@ export function run(bin, args, { cwd = REPO, capture = true, logFile = null, tim// Fold the harness's own log into the captured output, so the caller// sees the real cause rather than the one-line summary on stdout.if (logFile && existsSync(logFile)) {- try { out += readFileSync(logFile, 'utf8'); } catch {}+ try {+ out += readFileSync(logFile, 'utf8');+ } catch {}}res({ code, out });};@@ -404,7 +441,8 @@ export function makeSandbox(name) {rmSync(sandbox, { recursive: true, force: true });mkdirSync(sandbox, { recursive: true });const skillsSrc = join(REPO, 'skills');- if (existsSync(skillsSrc)) cpSync(skillsSrc, join(sandbox, '.claude', 'skills'), { recursive: true });+ if (existsSync(skillsSrc))+ cpSync(skillsSrc, join(sandbox, '.claude', 'skills'), { recursive: true });// Pre-approve the tools the brief asks the child to use.//@@ -423,15 +461,7 @@ export function makeSandbox(name) {// write its program. Nothing here grants the child the shell.const settings = {permissions: {- allow: [- 'mcp__kiln',- 'mcp__plugin_kiln_kiln',- 'Read',- 'Write',- 'Edit',- 'Glob',- 'Grep',- ],+ allow: ['mcp__kiln', 'mcp__plugin_kiln_kiln', 'Read', 'Write', 'Edit', 'Glob', 'Grep'],},};mkdirSync(join(sandbox, '.claude'), { recursive: true });diff --git a/scripts/implicit-acceptance-case.ts b/scripts/implicit-acceptance-case.tsindex 8123cd26..ab18c27d 100644--- a/scripts/implicit-acceptance-case.ts+++ b/scripts/implicit-acceptance-case.ts@@ -6,40 +6,93 @@ import type { BufferGeometry } from 'three';type Point = readonly [number, number, number];const [name, resolution] = process.argv.slice(2);const edgeLength = Number(resolution);-if (!['organic', 'mixed', 'cellular'].includes(name!) || ![0.2, 0.1].includes(edgeLength)) throw new Error('Choose organic|mixed|cellular and 0.2|0.1');-const sphere = ([x,y,z]: Point, center: number, radius: number) => radius-Math.hypot(x-center,y,z);-const box = ([x,y,z]: Point) => {- const q = [Math.abs(x)-0.6,Math.abs(y)-0.45,Math.abs(z)-0.5];- return -Math.hypot(...q.map(v=>Math.max(v,0)))-Math.min(Math.max(...q),0);+if (!['organic', 'mixed', 'cellular'].includes(name!) || ![0.2, 0.1].includes(edgeLength))+ throw new Error('Choose organic|mixed|cellular and 0.2|0.1');+const sphere = ([x, y, z]: Point, center: number, radius: number) =>+ radius - Math.hypot(x - center, y, z);+const box = ([x, y, z]: Point) => {+ const q = [Math.abs(x) - 0.6, Math.abs(y) - 0.45, Math.abs(z) - 0.5];+ return -Math.hypot(...q.map((v) => Math.max(v, 0))) - Math.min(Math.max(...q), 0);};const field = (p: Point) => {if (name === 'organic') {- const a=sphere(p,-0.4,0.65), b=sphere(p,0.4,0.65), k=0.3;- const h=Math.max(k-Math.abs(a-b),0)/k;- return Math.max(a,b)+h*h*k/4;+ const a = sphere(p, -0.4, 0.65),+ b = sphere(p, 0.4, 0.65),+ k = 0.3;+ const h = Math.max(k - Math.abs(a - b), 0) / k;+ return Math.max(a, b) + (h * h * k) / 4;}- if (name === 'mixed') return Math.max(box(p),sphere(p,0.65,0.65));- const [x,y,z]=p;- return Math.min(1-Math.hypot(x,y,z),0.15-Math.abs(Math.sin(x*6)*Math.cos(y*6)+Math.sin(y*6)*Math.cos(z*6)+Math.sin(z*6)*Math.cos(x*6)));+ if (name === 'mixed') return Math.max(box(p), sphere(p, 0.65, 0.65));+ const [x, y, z] = p;+ return Math.min(+ 1 - Math.hypot(x, y, z),+ 0.15 -+ Math.abs(+ Math.sin(x * 6) * Math.cos(y * 6) ++ Math.sin(y * 6) * Math.cos(z * 6) ++ Math.sin(z * 6) * Math.cos(x * 6),+ ),+ );};-const options = {bounds:{min:[-1.5,-1.2,-1.2] as Point,max:[1.5,1.2,1.2] as Point},edgeLength};-const started=performance.now();-const geometry=await implicitSurface(field,options);-const buildMs=performance.now()-started;-const repeated=await implicitSurface(field,options);+const options = {+ bounds: { min: [-1.5, -1.2, -1.2] as Point, max: [1.5, 1.2, 1.2] as Point },+ edgeLength,+};+const started = performance.now();+const geometry = await implicitSurface(field, options);+const buildMs = performance.now() - started;+const repeated = await implicitSurface(field, options);function digest(g: BufferGeometry) {- const h=createHash('sha256');- for(const attribute of [g.getAttribute('position'),g.getAttribute('normal'),g.index]) if(attribute) h.update(Buffer.from(attribute.array.buffer,attribute.array.byteOffset,attribute.array.byteLength));+ const h = createHash('sha256');+ for (const attribute of [g.getAttribute('position'), g.getAttribute('normal'), g.index])+ if (attribute)+ h.update(+ Buffer.from(attribute.array.buffer, attribute.array.byteOffset, attribute.array.byteLength),+ );return h.digest('hex');}-const p=geometry.getAttribute('position'), index=geometry.index;-const vertexResiduals:number[]=[],centroidResiduals:number[]=[];-for(let i=0;i<p.count;i++) vertexResiduals.push(Math.abs(field([p.getX(i),p.getY(i),p.getZ(i)])));-for(let i=0;i<(index?.count??p.count);i+=3) {- const ids=[0,1,2].map(k=>index?index.getX(i+k):i+k);- centroidResiduals.push(Math.abs(field([ids.reduce((s,j)=>s+p.getX(j),0)/3,ids.reduce((s,j)=>s+p.getY(j),0)/3,ids.reduce((s,j)=>s+p.getZ(j),0)/3])));+const p = geometry.getAttribute('position'),+ index = geometry.index;+const vertexResiduals: number[] = [],+ centroidResiduals: number[] = [];+for (let i = 0; i < p.count; i++)+ vertexResiduals.push(Math.abs(field([p.getX(i), p.getY(i), p.getZ(i)])));+for (let i = 0; i < (index?.count ?? p.count); i += 3) {+ const ids = [0, 1, 2].map((k) => (index ? index.getX(i + k) : i + k));+ centroidResiduals.push(+ Math.abs(+ field([+ ids.reduce((s, j) => s + p.getX(j), 0) / 3,+ ids.reduce((s, j) => s + p.getY(j), 0) / 3,+ ids.reduce((s, j) => s + p.getZ(j), 0) / 3,+ ]),+ ),+ );+}+function summary(values: number[]) {+ values.sort((a, b) => a - b);+ return {+ samples: values.length,+ max: values.at(-1),+ p95: values[Math.floor((values.length - 1) * 0.95)],+ };}-function summary(values:number[]) { values.sort((a,b)=>a-b);return {samples:values.length,max:values.at(-1),p95:values[Math.floor((values.length-1)*0.95)]}; }-const sha256=digest(geometry), repeatHash=digest(repeated);-if(sha256!==repeatHash) throw new Error('Repeated field output differs');-console.log(JSON.stringify({name,edgeLength,buildMs,triangles:(index?.count??p.count)/3,sha256,repeatIdentical:true,sampling:geometry.userData.kilnImplicit,vertexFieldResidual:summary(vertexResiduals),centroidFieldResidual:summary(centroidResiduals),topology:geometryDiagnostics(geometry),bounds:{min:geometry.boundingBox!.min.toArray(),max:geometry.boundingBox!.max.toArray()},uvPresent:!!geometry.getAttribute('uv')}));+const sha256 = digest(geometry),+ repeatHash = digest(repeated);+if (sha256 !== repeatHash) throw new Error('Repeated field output differs');+console.log(+ JSON.stringify({+ name,+ edgeLength,+ buildMs,+ triangles: (index?.count ?? p.count) / 3,+ sha256,+ repeatIdentical: true,+ sampling: geometry.userData.kilnImplicit,+ vertexFieldResidual: summary(vertexResiduals),+ centroidFieldResidual: summary(centroidResiduals),+ topology: geometryDiagnostics(geometry),+ bounds: { min: geometry.boundingBox!.min.toArray(), max: geometry.boundingBox!.max.toArray() },+ uvPresent: !!geometry.getAttribute('uv'),+ }),+);diff --git a/scripts/implicit-acceptance.mjs b/scripts/implicit-acceptance.mjsindex ffc897c3..70148a09 100644--- a/scripts/implicit-acceptance.mjs+++ b/scripts/implicit-acceptance.mjs@@ -1,12 +1,46 @@import { spawnSync } from 'node:child_process';import { mkdirSync, writeFileSync } from 'node:fs';import { resolve } from 'node:path';-const results=[];-for(const name of ['organic','mixed','cellular']) for(const edgeLength of [0.2,0.1]) {- const result=spawnSync('bun',['scripts/implicit-acceptance-case.ts',name,String(edgeLength)],{cwd:resolve(import.meta.dirname,'..'),encoding:'utf8',timeout:20000,windowsHide:true,maxBuffer:1024*1024});- let record;- if(result.status===0) record=JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));- else {record={name,edgeLength,status:result.error?.code==='ETIMEDOUT'?'timeout':'failed',stderr:result.stderr.slice(-1500)};process.exitCode=1;}- results.push(record);console.log(JSON.stringify(record));-}-const directory=resolve(import.meta.dirname,'../output/implicit-acceptance');mkdirSync(directory,{recursive:true});writeFileSync(resolve(directory,'results.json'),JSON.stringify({node:process.version,bun:spawnSync('bun',['--version'],{encoding:'utf8',windowsHide:true}).stdout.trim(),perCaseTimeoutMs:20000,results},null,2)+'\n');+const results = [];+for (const name of ['organic', 'mixed', 'cellular'])+ for (const edgeLength of [0.2, 0.1]) {+ const result = spawnSync(+ 'bun',+ ['scripts/implicit-acceptance-case.ts', name, String(edgeLength)],+ {+ cwd: resolve(import.meta.dirname, '..'),+ encoding: 'utf8',+ timeout: 20000,+ windowsHide: true,+ maxBuffer: 1024 * 1024,+ },+ );+ let record;+ if (result.status === 0) record = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1));+ else {+ record = {+ name,+ edgeLength,+ status: result.error?.code === 'ETIMEDOUT' ? 'timeout' : 'failed',+ stderr: result.stderr.slice(-1500),+ };+ process.exitCode = 1;+ }+ results.push(record);+ console.log(JSON.stringify(record));+ }+const directory = resolve(import.meta.dirname, '../output/implicit-acceptance');+mkdirSync(directory, { recursive: true });+writeFileSync(+ resolve(directory, 'results.json'),+ `${JSON.stringify(+ {+ node: process.version,+ bun: spawnSync('bun', ['--version'], { encoding: 'utf8', windowsHide: true }).stdout.trim(),+ perCaseTimeoutMs: 20000,+ results,+ },+ null,+ 2,+ )}\n`,+);diff --git a/scripts/observe-mcp.mjs b/scripts/observe-mcp.mjsindex 767acfc1..2c531dd4 100644--- a/scripts/observe-mcp.mjs+++ b/scripts/observe-mcp.mjs@@ -5,39 +5,69 @@ import { createInterface } from 'node:readline';const [server, trace] = process.argv.slice(2);if (!server || !trace) throw new Error('Expected server bundle path and trace path.');-const child = spawn(process.execPath, [server], { stdio: ['pipe', 'pipe', 'inherit'], windowsHide: true });+const child = spawn(process.execPath, [server], {+ stdio: ['pipe', 'pipe', 'inherit'],+ windowsHide: true,+});const pending = new Map();const record = (entry) => appendFileSync(trace, `${JSON.stringify(entry)}\n`);-createInterface({ input: process.stdin }).on('line', (line) => {- try {- const request = JSON.parse(line);- if (request.method === 'tools/call') {- const args = request.params?.arguments ?? {};- pending.set(request.id, request.params.name);- record({ direction: 'request', id: request.id, tool: request.params.name,- argumentBytes: Buffer.byteLength(JSON.stringify(args)), hasInlineCode: typeof args.code === 'string',- programRef: args.programRef, query: args.query, edits: args.edits });- }- } catch {}- child.stdin.write(`${line}\n`);-}).on('close', () => child.stdin.end());+createInterface({ input: process.stdin })+ .on('line', (line) => {+ try {+ const request = JSON.parse(line);+ if (request.method === 'tools/call') {+ const args = request.params?.arguments ?? {};+ pending.set(request.id, request.params.name);+ record({+ direction: 'request',+ id: request.id,+ tool: request.params.name,+ argumentBytes: Buffer.byteLength(JSON.stringify(args)),+ hasInlineCode: typeof args.code === 'string',+ programRef: args.programRef,+ query: args.query,+ edits: args.edits,+ });+ }+ } catch {}+ child.stdin.write(`${line}\n`);+ })+ .on('close', () => child.stdin.end());createInterface({ input: child.stdout }).on('line', (line) => {try {const response = JSON.parse(line);if (pending.has(response.id)) {const content = response.result?.content ?? [];- const text = content.filter((c) => c.type === 'text').map((c) => c.text).join('\n');+ const text = content+ .filter((c) => c.type === 'text')+ .map((c) => c.text)+ .join('\n');let data;- try { data = JSON.parse(text); } catch {}- record({ direction: 'response', id: response.id, tool: pending.get(response.id),- textBytes: Buffer.byteLength(text), images: content.filter((c) => c.type === 'image').length,- isError: response.result?.isError ?? false, ok: data?.ok,- programRef: data?.programRef, parentRef: data?.parentRef,- codeCharacters: data?.code?.length ?? 0, viewFidelity: data?.viewFidelity ?? data?.render?.viewFidelity });+ try {+ data = JSON.parse(text);+ } catch {}+ record({+ direction: 'response',+ id: response.id,+ tool: pending.get(response.id),+ textBytes: Buffer.byteLength(text),+ images: content.filter((c) => c.type === 'image').length,+ isError: response.result?.isError ?? false,+ ok: data?.ok,+ programRef: data?.programRef,+ parentRef: data?.parentRef,+ codeCharacters: data?.code?.length ?? 0,+ viewFidelity: data?.viewFidelity ?? data?.render?.viewFidelity,+ });pending.delete(response.id);}} catch {}process.stdout.write(`${line}\n`);});-child.on('close', (code) => { process.exitCode = code ?? 1; });-child.on('error', (error) => { console.error(error.message); process.exitCode = 1; });+child.on('close', (code) => {+ process.exitCode = code ?? 1;+});+child.on('error', (error) => {+ console.error(error.message);+ process.exitCode = 1;+});diff --git a/scripts/package-plugin.mjs b/scripts/package-plugin.mjsindex e96e3932..70548293 100644--- a/scripts/package-plugin.mjs+++ b/scripts/package-plugin.mjs@@ -12,7 +12,8 @@ export async function packagePlugin(destination, appId) {throw new Error('Expected a registered plugin_asdk_app connector ID');const directory = resolve(destination);const name = basename(directory);- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) throw new Error('Use a lowercase hyphenated plugin folder name');+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))+ throw new Error('Use a lowercase hyphenated plugin folder name');await mkdir(dirname(directory), { recursive: true });await mkdir(directory); // Deliberately refuses an existing output.const manifest = JSON.parse(await readFile(join(repo, '.codex-plugin/plugin.json'), 'utf8'));@@ -20,25 +21,47 @@ export async function packagePlugin(destination, appId) {delete manifest.mcpServers;if (appId) manifest.apps = './.app.json';await mkdir(join(directory, '.codex-plugin'));- await writeFile(join(directory, '.codex-plugin/plugin.json'), JSON.stringify(manifest, null, 2) + '\n');+ await writeFile(+ join(directory, '.codex-plugin/plugin.json'),+ `${JSON.stringify(manifest, null, 2)}\n`,+ );await cp(join(repo, 'skills'), join(directory, 'skills'), { recursive: true });await cp(join(repo, 'LICENSE'), join(directory, 'LICENSE'));- if (appId) await writeFile(join(directory, '.app.json'), JSON.stringify({ apps: { kiln: { id: appId } } }, null, 2) + '\n');+ if (appId)+ await writeFile(+ join(directory, '.app.json'),+ `${JSON.stringify({ apps: { kiln: { id: appId } } }, null, 2)}\n`,+ );const files = {};async function inventory(path, prefix = '') {- for (const entry of (await readdir(path, { withFileTypes: true })).sort((a,b) => a.name.localeCompare(b.name))) {+ for (const entry of (await readdir(path, { withFileTypes: true })).sort((a, b) =>+ a.name.localeCompare(b.name),+ )) {const relative = prefix + entry.name;- if (entry.isDirectory()) await inventory(join(path, entry.name), relative + '/');- else files[relative] = 'sha256:' + createHash('sha256').update(await readFile(join(path, entry.name))).digest('hex');+ if (entry.isDirectory()) await inventory(join(path, entry.name), `${relative}/`);+ else+ files[relative] =+ 'sha256:' ++ createHash('sha256')+ .update(await readFile(join(path, entry.name)))+ .digest('hex');}}await inventory(directory);- await writeFile(join(directory, 'package-provenance.json'), JSON.stringify({ version: 1, engineVersion: manifest.version, connectorBound: Boolean(appId), files }, null, 2) + '\n');+ await writeFile(+ join(directory, 'package-provenance.json'),+ `${JSON.stringify(+ { version: 1, engineVersion: manifest.version, connectorBound: Boolean(appId), files },+ null,+ 2,+ )}\n`,+ );return { directory, files: Object.keys(files).length, connectorBound: Boolean(appId) };}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {const [destination, appId] = process.argv.slice(2);- if (!destination) throw new Error('Usage: node scripts/package-plugin.mjs OUTPUT_DIRECTORY [plugin_asdk_app_ID]');+ if (!destination)+ throw new Error('Usage: node scripts/package-plugin.mjs OUTPUT_DIRECTORY [plugin_asdk_app_ID]');console.log(JSON.stringify(await packagePlugin(destination, appId), null, 2));}diff --git a/scripts/promote-asset.mjs b/scripts/promote-asset.mjsindex 48b8306a..d549ed70 100644--- a/scripts/promote-asset.mjs+++ b/scripts/promote-asset.mjs@@ -96,7 +96,8 @@ function promote(name) {});const out = `${r.stdout ?? ''}${r.stderr ?? ''}`;const tris = /(\d+) tris/.exec(out)?.[1];- if (r.status !== 0 || !tris) return { name, ok: false, why: `render failed: ${out.trim().slice(-200)}` };+ if (r.status !== 0 || !tris)+ return { name, ok: false, why: `render failed: ${out.trim().slice(-200)}` };return {name,diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjsindex 47d8bed6..f51cf023 100644--- a/scripts/reliability.test.mjs+++ b/scripts/reliability.test.mjs@@ -82,8 +82,8 @@ describe('repository reliability contracts', () => {// own path report "No files were processed". The surface is the gates and their// tests; the one-off tools beside them are a separate decision, recorded in// ledger 14.4 with what taking them costs.- expect(biome.files.includes).toContain('scripts/check-*.mjs');- expect(biome.files.includes).toContain('scripts/**/*.test.mjs');+ expect(biome.files.includes).toContain('scripts/**/*.mjs');+ expect(biome.files.includes).toContain('scripts/**/*.ts');// render-service joined the surface once its sources stopped being CRLF. It is// a shipped subsystem with 37 tests in CI, so it belongs here; what kept it out// was a `.gitattributes` `-text` line freezing an inconsistent line-ending mix.diff --git a/scripts/smoke-package-linux-bootstrap.mjs b/scripts/smoke-package-linux-bootstrap.mjsindex e3796760..e47b147f 100644--- a/scripts/smoke-package-linux-bootstrap.mjs+++ b/scripts/smoke-package-linux-bootstrap.mjs@@ -4,16 +4,34 @@ import { execFile } from 'node:child_process';import { promisify } from 'node:util';const exec = promisify(execFile);try {- await exec(process.execPath, ['/usr/local/lib/node_modules/npm/bin/npm-cli.js', 'install', '--prefix', '/tmp/kiln-npm', '[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { timeout:120000, maxBuffer:1024*1024 });- const result = await exec(process.execPath, ['/checks/smoke-package.mjs', '--tarball', '/input/candidate.tgz'], {- timeout:480000, maxBuffer:2*1024*1024,- env:{...process.env,npm_execpath:'/tmp/kiln-npm/node_modules/npm/bin/npm-cli.js'},- });+ await exec(+ process.execPath,+ [+ '/usr/local/lib/node_modules/npm/bin/npm-cli.js',+ 'install',+ '--prefix',+ '/tmp/kiln-npm',+ '[email protected]',+ '--ignore-scripts',+ '--no-audit',+ '--no-fund',+ ],+ { timeout: 120000, maxBuffer: 1024 * 1024 },+ );+ const result = await exec(+ process.execPath,+ ['/checks/smoke-package.mjs', '--tarball', '/input/candidate.tgz'],+ {+ timeout: 480000,+ maxBuffer: 2 * 1024 * 1024,+ env: { ...process.env, npm_execpath: '/tmp/kiln-npm/node_modules/npm/bin/npm-cli.js' },+ },+ );process.stdout.write(result.stdout);if (result.stderr) process.stderr.write(result.stderr);} catch (error) {- if(error.stdout) process.stdout.write(error.stdout);- if(error.stderr) process.stderr.write(error.stderr);+ if (error.stdout) process.stdout.write(error.stdout);+ if (error.stderr) process.stderr.write(error.stderr);else process.stderr.write(String(error));- process.exitCode=1;+ process.exitCode = 1;}diff --git a/scripts/smoke-package-linux.mjs b/scripts/smoke-package-linux.mjsindex 0beb31d0..c54e1768 100644--- a/scripts/smoke-package-linux.mjs+++ b/scripts/smoke-package-linux.mjs@@ -7,45 +7,90 @@ import { readFile, stat, writeFile } from 'node:fs/promises';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-const image = 'node:22.23.1-bookworm-slim@sha256:6c74791e557ce11fc957704f6d4fe134a7bc8d6f5ca4403205b2966bd488f6b3';+const image =+ 'node:22.23.1-bookworm-slim@sha256:6c74791e557ce11fc957704f6d4fe134a7bc8d6f5ca4403205b2966bd488f6b3';const [tarballArg, receiptArg, ...extra] = process.argv.slice(2);-assert(tarballArg && receiptArg && extra.length === 0, 'Usage: node scripts/smoke-package-linux.mjs <package.tgz> <receipt.json>');-const tarball = resolve(tarballArg), output = resolve(receiptArg);+assert(+ tarballArg && receiptArg && extra.length === 0,+ 'Usage: node scripts/smoke-package-linux.mjs <package.tgz> <receipt.json>',+);+const tarball = resolve(tarballArg),+ output = resolve(receiptArg);assert((await stat(tarball)).isFile(), 'Tarball must be a file.');const scripts = dirname(fileURLToPath(import.meta.url));const name = `kiln-package-smoke-${randomUUID()}`;-const args = ['run', '--rm', '--name', name, '--memory', '2g', '--cpus', '2',- '--mount', `type=bind,source=${tarball},target=/input/candidate.tgz,readonly`,- '--mount', `type=bind,source=${scripts},target=/checks,readonly`,- image, 'node', '/checks/smoke-package-linux-bootstrap.mjs'];+const args = [+ 'run',+ '--rm',+ '--name',+ name,+ '--memory',+ '2g',+ '--cpus',+ '2',+ '--mount',+ `type=bind,source=${tarball},target=/input/candidate.tgz,readonly`,+ '--mount',+ `type=bind,source=${scripts},target=/checks,readonly`,+ image,+ 'node',+ '/checks/smoke-package-linux-bootstrap.mjs',+];const child = spawn('docker', args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });-let stdout = '', stderr = '';-child.stdout.on('data', data => { stdout += data; });-child.stderr.on('data', data => { stderr = (stderr + data).slice(-16000); });+let stdout = '',+ stderr = '';+child.stdout.on('data', (data) => {+ stdout += data;+});+child.stderr.on('data', (data) => {+ stderr = (stderr + data).slice(-16000);+});let timedOut = false;const timer = setTimeout(() => {timedOut = true;spawn('docker', ['rm', '--force', name], { windowsHide: true, stdio: 'ignore' });}, 600000);try {- const code = await new Promise((done, fail) => { child.on('error', fail); child.on('exit', done); });- const tarballSha256 = createHash('sha256').update(await readFile(tarball)).digest('hex');+ const code = await new Promise((done, fail) => {+ child.on('error', fail);+ child.on('exit', done);+ });+ const tarballSha256 = createHash('sha256')+ .update(await readFile(tarball))+ .digest('hex');let smoke;- try { smoke = JSON.parse(stdout); } catch { smoke = {status:'failed', error:stderr || stdout || 'No smoke receipt'}; }+ try {+ smoke = JSON.parse(stdout);+ } catch {+ smoke = { status: 'failed', error: stderr || stdout || 'No smoke receipt' };+ }let validationError;try {- assert.equal(code,0,stderr);- assert.equal(timedOut,false);- assert.equal(smoke.status,'passed');- assert.equal(smoke.platform,'linux');- assert.equal(smoke.node,'v22.23.1');- assert.equal(smoke.npm,'12.0.1');- assert.equal(smoke.tarballSha256,tarballSha256);- } catch (error) { validationError = error; }- const receipt = { status:validationError?'failed':'passed', image, tarball, tarballSha256,- containerMemoryBytes:2147483648, containerCpus:2, timedOut, exitCode:code, smoke,- ...(validationError ? {error:validationError.message} : {}) };- await writeFile(output, JSON.stringify(receipt,null,2)+'\n');- console.log(JSON.stringify(receipt,null,2));- if(validationError) throw validationError;-} finally { clearTimeout(timer); }+ assert.equal(code, 0, stderr);+ assert.equal(timedOut, false);+ assert.equal(smoke.status, 'passed');+ assert.equal(smoke.platform, 'linux');+ assert.equal(smoke.node, 'v22.23.1');+ assert.equal(smoke.npm, '12.0.1');+ assert.equal(smoke.tarballSha256, tarballSha256);+ } catch (error) {+ validationError = error;+ }+ const receipt = {+ status: validationError ? 'failed' : 'passed',+ image,+ tarball,+ tarballSha256,+ containerMemoryBytes: 2147483648,+ containerCpus: 2,+ timedOut,+ exitCode: code,+ smoke,+ ...(validationError ? { error: validationError.message } : {}),+ };+ await writeFile(output, `${JSON.stringify(receipt, null, 2)}\n`);+ console.log(JSON.stringify(receipt, null, 2));+ if (validationError) throw validationError;+} finally {+ clearTimeout(timer);+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 1c2b18bf..1072baa3 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -11,56 +11,137 @@ import { fileURLToPath, pathToFileURL } from 'node:url';const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');const root = await mkdtemp(join(tmpdir(), 'kiln-package-café-'));-const receipt = { root, platform: process.platform, arch: process.arch, node: process.version, checks: [], status: 'running' };+const receipt = {+ root,+ platform: process.platform,+ arch: process.arch,+ node: process.version,+ checks: [],+ status: 'running',+};const sha = (value) => createHash('sha256').update(value).digest('hex');async function command(args, cwd, env = {}) {return new Promise((done, fail) => {- const child = spawn(process.execPath, args, { cwd, windowsHide: true, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });- let stdout = '', stderr = '';- child.stdout.on('data', (data) => { stdout += data; });- child.stderr.on('data', (data) => { stderr += data; });- const timer = setTimeout(() => { child.kill(); fail(new Error(`Command exceeded five minutes: ${args[0]}`)); }, 300000);- child.on('error', (error) => { clearTimeout(timer); fail(error); });- child.on('exit', (code) => { clearTimeout(timer); if (code === 0) done(stdout); else fail(new Error(`Command exited ${code}: ${args.slice(0, 3).join(' ')}\n${stderr.slice(-6000)}`)); });+ const child = spawn(process.execPath, args, {+ cwd,+ windowsHide: true,+ env: { ...process.env, ...env },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '',+ stderr = '';+ child.stdout.on('data', (data) => {+ stdout += data;+ });+ child.stderr.on('data', (data) => {+ stderr += data;+ });+ const timer = setTimeout(() => {+ child.kill();+ fail(new Error(`Command exceeded five minutes: ${args[0]}`));+ }, 300000);+ child.on('error', (error) => {+ clearTimeout(timer);+ fail(error);+ });+ child.on('exit', (code) => {+ clearTimeout(timer);+ if (code === 0) done(stdout);+ else+ fail(+ new Error(+ `Command exited ${code}: ${args.slice(0, 3).join(' ')}\n${stderr.slice(-6000)}`,+ ),+ );+ });});}async function npmCli() {- const candidates = [process.env.npm_execpath, join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'), resolve(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js')].filter(Boolean);- for (const candidate of candidates) if (candidate.endsWith('npm-cli.js')) { try { await stat(candidate); return candidate; } catch {} }+ const candidates = [+ process.env.npm_execpath,+ join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),+ resolve(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js'),+ ].filter(Boolean);+ for (const candidate of candidates)+ if (candidate.endsWith('npm-cli.js')) {+ try {+ await stat(candidate);+ return candidate;+ } catch {}+ }throw new Error('Run this check with npm run test:package so npm can locate its CLI.');}async function connect(server, cwd, store) {- const child = spawn(process.execPath, [server], { cwd, windowsHide: true, env: { ...process.env, KILN_RENDER: 'cpu', KILN_PROGRAM_STORE: store }, stdio: ['pipe', 'pipe', 'pipe'] });- let next = 0, buffer = '', stderr = '';+ const child = spawn(process.execPath, [server], {+ cwd,+ windowsHide: true,+ env: { ...process.env, KILN_RENDER: 'cpu', KILN_PROGRAM_STORE: store },+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ let next = 0,+ buffer = '',+ stderr = '';const pending = new Map();- child.stderr.on('data', (data) => { stderr = (stderr + data).slice(-4000); });+ child.stderr.on('data', (data) => {+ stderr = (stderr + data).slice(-4000);+ });child.stdout.on('data', (data) => {buffer += data;- let end;- while ((end = buffer.indexOf('\n')) >= 0) {- const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);+ for (let end = buffer.indexOf('\n'); end >= 0; end = buffer.indexOf('\n')) {+ const line = buffer.slice(0, end);+ buffer = buffer.slice(end + 1);if (!line.trim()) continue;- let message; try { message = JSON.parse(line); } catch { continue; }+ let message;+ try {+ message = JSON.parse(line);+ } catch {+ continue;+ }const resolve = pending.get(message.id);- if (resolve) { pending.delete(message.id); resolve(message); }+ if (resolve) {+ pending.delete(message.id);+ resolve(message);+ }}});- const call = (method, params) => new Promise((done, fail) => {- const id = ++next;- const timer = setTimeout(() => { pending.delete(id); fail(new Error(`MCP ${method} timed out. ${stderr}`)); }, 60000);- pending.set(id, (message) => { clearTimeout(timer); if (message.error) fail(new Error(JSON.stringify(message.error))); else done(message.result); });- child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ const call = (method, params) =>+ new Promise((done, fail) => {+ const id = ++next;+ const timer = setTimeout(() => {+ pending.delete(id);+ fail(new Error(`MCP ${method} timed out. ${stderr}`));+ }, 60000);+ pending.set(id, (message) => {+ clearTimeout(timer);+ if (message.error) fail(new Error(JSON.stringify(message.error)));+ else done(message.result);+ });+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);+ });+ const close = () => {+ child.kill();+ };+ child.on('error', (error) => {+ for (const resolve of pending.values()) resolve({ error: { message: error.message } });+ pending.clear();});- const close = () => { child.kill(); };- child.on('error', (error) => { for (const resolve of pending.values()) resolve({ error: { message: error.message } }); pending.clear(); });try {- await call('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'kiln-package-smoke', version: '1' } });- child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ await call('initialize', {+ protocolVersion: '2025-11-25',+ capabilities: {},+ clientInfo: { name: 'kiln-package-smoke', version: '1' },+ });+ child.stdin.write(+ `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`,+ );return { call, close };- } catch (error) { close(); throw error; }+ } catch (error) {+ close();+ throw error;+ }}const textResult = (result) => {@@ -78,7 +159,9 @@ try {receipt.tarball = resolve(args[1]);assert((await stat(receipt.tarball)).isFile(), 'Tarball must be a file.');} else {- const packed = JSON.parse(await command([npm, 'pack', '--json', '--ignore-scripts', '--pack-destination', root], repo));+ const packed = JSON.parse(+ await command([npm, 'pack', '--json', '--ignore-scripts', '--pack-destination', root], repo),+ );const pack = Array.isArray(packed) ? packed[0] : Object.values(packed)[0];receipt.tarball = join(root, pack.filename);receipt.integrity = pack.integrity;@@ -91,33 +174,79 @@ try {// until this line existed, and the on-demand start has nothing to start without it.assert(pack.files.some((entry) => entry.path === 'render-service/src/server.mjs'));assert(!pack.files.some((entry) => entry.path.startsWith('render-service/test/')));- assert(!pack.files.some((entry) => entry.path.includes('__tests__') || entry.path.endsWith('.test.ts')));+ assert(+ !pack.files.some(+ (entry) => entry.path.includes('__tests__') || entry.path.endsWith('.test.ts'),+ ),+ );}receipt.tarballSha256 = sha(await readFile(receipt.tarball));const install = join(root, 'fresh installation');await mkdir(install);- await writeFile(join(install, 'package.json'), JSON.stringify({ private: true, name: 'kiln-package-check', version: '1.0.0' }));- await command([npm, 'install', receipt.tarball, '--omit=dev', '--no-audit', '--no-fund'], install);+ await writeFile(+ join(install, 'package.json'),+ JSON.stringify({ private: true, name: 'kiln-package-check', version: '1.0.0' }),+ );+ await command(+ [npm, 'install', receipt.tarball, '--omit=dev', '--no-audit', '--no-fund'],+ install,+ );const runtime = join(install, 'node_modules/@kiln/engine');const pkg = JSON.parse(await readFile(join(runtime, 'package.json'), 'utf8'));receipt.engineVersion = pkg.version;- for (const required of ['dist/cli.mjs', 'dist/mcp-server.mjs', 'dist/evaluator-worker.mjs', 'scripts/create-workspace.mjs', 'plugin.json', '.claude-plugin/plugin.json', 'render-service/src/server.mjs', 'render-service/src/register-hooks.mjs', 'render-service/package.json'])- assert((await stat(join(runtime, required))).isFile(), `Missing installed package file: ${required}`);+ for (const required of [+ 'dist/cli.mjs',+ 'dist/mcp-server.mjs',+ 'dist/evaluator-worker.mjs',+ 'scripts/create-workspace.mjs',+ 'plugin.json',+ '.claude-plugin/plugin.json',+ 'render-service/src/server.mjs',+ 'render-service/src/register-hooks.mjs',+ 'render-service/package.json',+ ])+ assert(+ (await stat(join(runtime, required))).isFile(),+ `Missing installed package file: ${required}`,+ );// `renderServiceDir()` is `new URL('../render-service', import.meta.url)` from the// bundle. Walk that exact arithmetic against the real installation rather than// trusting that the three paths above happen to sit where the server will look.assert(- (await stat(fileURLToPath(new URL('../render-service/src/server.mjs', pathToFileURL(join(runtime, 'dist/mcp-server.mjs')))))).isFile(),+ (+ await stat(+ fileURLToPath(+ new URL(+ '../render-service/src/server.mjs',+ pathToFileURL(join(runtime, 'dist/mcp-server.mjs')),+ ),+ ),+ )+ ).isFile(),'render-service is not where the MCP bundle resolves it',);- receipt.bundleHashes = { cli: sha(await readFile(join(runtime, 'dist/cli.mjs'))), mcp: sha(await readFile(join(runtime, 'dist/mcp-server.mjs'))) };+ receipt.bundleHashes = {+ cli: sha(await readFile(join(runtime, 'dist/cli.mjs'))),+ mcp: sha(await readFile(join(runtime, 'dist/mcp-server.mjs'))),+ };assert((await readFile(join(runtime, 'dist/cli.mjs'), 'utf8')).startsWith('#!/usr/bin/env node'));- assert.match(await command([join(runtime, 'dist/cli.mjs'), '--help'], root), /kiln render/, 'Direct Node CLI must print help');+ assert.match(+ await command([join(runtime, 'dist/cli.mjs'), '--help'], root),+ /kiln render/,+ 'Direct Node CLI must print help',+ );receipt.checks.push('direct-node-cli-help');- assert.match(await command([npm, 'exec', '--offline', '--', 'kiln', '--help'], install), /kiln render/, 'npm bin entry must print help (including Linux symlinks)');+ assert.match(+ await command([npm, 'exec', '--offline', '--', 'kiln', '--help'], install),+ /kiln render/,+ 'npm bin entry must print help (including Linux symlinks)',+ );receipt.checks.push('tarball-install-without-dev-dependencies', 'node-cli-entry');const workspace = join(root, 'asset workspace café');- await command([npm, 'exec', '--offline', '--', 'kiln-init', workspace, '--harness', 'codex'], install);+ await command(+ [npm, 'exec', '--offline', '--', 'kiln-init', workspace, '--harness', 'codex'],+ install,+ );assert((await stat(workspace)).isDirectory(), 'npm kiln-init must create its workspace');receipt.checks.push('npm-init-workspace');const cli = join(workspace, 'kiln.mjs');@@ -127,51 +256,165 @@ try {assert.match(ref, /^p_[a-f0-9]{12}$/);assert.equal(await command([cli, 'source', `sha256:${sha(source)}`], root), source);receipt.checks.push('short-reference-full-hash-compatibility');- await command([cli, 'render', ref, '--render', 'cpu', '--out', join(workspace, 'asset.glb'), '--views', join(workspace, 'sheet.png')], root);+ await command(+ [+ cli,+ 'render',+ ref,+ '--render',+ 'cpu',+ '--out',+ join(workspace, 'asset.glb'),+ '--views',+ join(workspace, 'sheet.png'),+ ],+ root,+ );const png = await readFile(join(workspace, 'sheet.png'));assert.equal(png.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');const require = createRequire(join(runtime, 'package.json'));const { NodeIO } = await import(pathToFileURL(require.resolve('@gltf-transform/core')).href);const doc = await new NodeIO().readBinary(await readFile(join(workspace, 'asset.glb')));- assert(doc.getRoot().listMeshes().some((mesh) => mesh.listPrimitives().some((primitive) => primitive.getAttribute('TEXCOORD_0')?.getCount() > 0)));+ assert(+ doc+ .getRoot()+ .listMeshes()+ .some((mesh) =>+ mesh+ .listPrimitives()+ .some((primitive) => primitive.getAttribute('TEXCOORD_0')?.getCount() > 0),+ ),+ );receipt.checks.push('csg-wasm', 'uv-wasm', 'cpu-png', 'cross-cwd-cli-source-store');- const capture = { version: 'kiln.capture.v1', output: 'grid', cols: 2, size: 160, shots: [- { name: 'Part side', subject: { name: 'Mesh_Body' }, visibility: 'isolate', camera: { type: 'orbit', relativeTo: 'part', azimuthDeg: 25, elevationDeg: 0 } },- { name: 'Part above', subject: { name: 'Mesh_Body' }, visibility: 'context', camera: { type: 'orbit', relativeTo: 'part', azimuthDeg: 90, elevationDeg: 70 } },- ] };+ const capture = {+ version: 'kiln.capture.v1',+ output: 'grid',+ cols: 2,+ size: 160,+ shots: [+ {+ name: 'Part side',+ subject: { name: 'Mesh_Body' },+ visibility: 'isolate',+ camera: { type: 'orbit', relativeTo: 'part', azimuthDeg: 25, elevationDeg: 0 },+ },+ {+ name: 'Part above',+ subject: { name: 'Mesh_Body' },+ visibility: 'context',+ camera: { type: 'orbit', relativeTo: 'part', azimuthDeg: 90, elevationDeg: 70 },+ },+ ],+ };const recipe = join(workspace, 'capture.json');await writeFile(recipe, JSON.stringify(capture));- const captureLog = await command([cli, 'render', ref, '--render', 'cpu', '--capture', recipe, '--views', join(workspace, 'chosen.png'), '--out', join(workspace, 'chosen.glb')], root);+ const captureLog = await command(+ [+ cli,+ 'render',+ ref,+ '--render',+ 'cpu',+ '--capture',+ recipe,+ '--views',+ join(workspace, 'chosen.png'),+ '--out',+ join(workspace, 'chosen.glb'),+ ],+ root,+ );const chosen = await readFile(join(workspace, 'chosen.png'));assert.deepEqual([chosen.readUInt32BE(16), chosen.readUInt32BE(20)], [332, 168]);assert.match(captureLog, /build reused/, 'Camera-only export must reuse the evaluated build');- assert.equal(sha(await readFile(join(workspace, 'chosen.glb'))), sha(await readFile(join(workspace, 'asset.glb'))));+ assert.equal(+ sha(await readFile(join(workspace, 'chosen.glb'))),+ sha(await readFile(join(workspace, 'asset.glb'))),+ );capture.shots[0].camera.elevationDeg = 75;await writeFile(recipe, JSON.stringify(capture));- await command([cli, 'render', ref, '--render', 'cpu', '--capture', recipe, '--views', join(workspace, 'changed-view.png')], root);+ await command(+ [+ cli,+ 'render',+ ref,+ '--render',+ 'cpu',+ '--capture',+ recipe,+ '--views',+ join(workspace, 'changed-view.png'),+ ],+ root,+ );assert.notEqual(sha(chosen), sha(await readFile(join(workspace, 'changed-view.png'))));const badCapture = { ...capture, shots: [{ ...capture.shots[0], subject: { name: 'Body' } }] };await writeFile(recipe, JSON.stringify(badCapture));- await assert.rejects(command([cli, 'render', ref, '--render', 'cpu', '--capture', recipe, '--views', join(workspace, 'missing-subject.png')], root), /missing camera subject; choose an exact path/);+ await assert.rejects(+ command(+ [+ cli,+ 'render',+ ref,+ '--render',+ 'cpu',+ '--capture',+ recipe,+ '--views',+ join(workspace, 'missing-subject.png'),+ ],+ root,+ ),+ /missing camera subject; choose an exact path/,+ );badCapture.shots[0].subject = { path: '/PackedEnclosure[0]/PackedEnclosure[0]/Mesh_Body[0]' };await writeFile(recipe, JSON.stringify(badCapture));- await command([cli, 'render', ref, '--render', 'cpu', '--capture', recipe, '--views', join(workspace, 'exact-subject.png')], root);+ await command(+ [+ cli,+ 'render',+ ref,+ '--render',+ 'cpu',+ '--capture',+ recipe,+ '--views',+ join(workspace, 'exact-subject.png'),+ ],+ root,+ );assert((await stat(join(workspace, 'exact-subject.png'))).size > 0);receipt.checks.push('capture-file-part-relative-grid', 'capture-file-build-reuse');- await command([cli, 'render', ref, '--render', 'cpu', '--out', join(workspace, 'worker.glb')], root, { KILN_EVALUATOR_MODE: 'subprocess' });- assert.equal(sha(await readFile(join(workspace, 'worker.glb'))), sha(await readFile(join(workspace, 'asset.glb'))));+ await command(+ [cli, 'render', ref, '--render', 'cpu', '--out', join(workspace, 'worker.glb')],+ root,+ { KILN_EVALUATOR_MODE: 'subprocess' },+ );+ assert.equal(+ sha(await readFile(join(workspace, 'worker.glb'))),+ sha(await readFile(join(workspace, 'asset.glb'))),+ );receipt.checks.push('packaged-node-worker');- const server = join(runtime, 'dist/mcp-server.mjs'), store = join(workspace, '.kiln/programs');+ const server = join(runtime, 'dist/mcp-server.mjs'),+ store = join(workspace, '.kiln/programs');const session = await connect(server, root, store);let changed;try {const listed = await session.call('tools/list', {});assert(listed.tools.some((tool) => tool.name === 'kiln_source'));assert(listed.tools.some((tool) => tool.name === 'kiln_render'));- const read = textResult(await session.call('tools/call', { name: 'kiln_source', arguments: { programRef: ref, query: 'gameMaterial' } }));+ const read = textResult(+ await session.call('tools/call', {+ name: 'kiln_source',+ arguments: { programRef: ref, query: 'gameMaterial' },+ }),+ );assert.match(read.code, /0x4488aa/);- const result = await session.call('tools/call', { name: 'kiln_edit', arguments: { programRef: ref, edits: [{ oldString: '0x4488aa', newString: '0xaa8844' }] } });+ const result = await session.call('tools/call', {+ name: 'kiln_edit',+ arguments: { programRef: ref, edits: [{ oldString: '0x4488aa', newString: '0xaa8844' }] },+ });changed = textResult(result);assert.equal(changed.ok, true);assert.equal(changed.parentRef, ref);@@ -180,15 +423,35 @@ try {assert.equal(changed.code, undefined);assert(result.content.some((item) => item.type === 'image' && item.data.length > 100));receipt.editResult = { programRef: changed.programRef, parentRef: changed.parentRef };- } finally { session.close(); }+ } finally {+ session.close();+ }const restarted = await connect(server, install, store);try {- const after = textResult(await restarted.call('tools/call', { name: 'kiln_source', arguments: { programRef: changed.programRef, query: 'gameMaterial' } }));+ const after = textResult(+ await restarted.call('tools/call', {+ name: 'kiln_source',+ arguments: { programRef: changed.programRef, query: 'gameMaterial' },+ }),+ );assert.match(after.code, /0xaa8844/);- } finally { restarted.close(); }- await command([cli, 'source', changed.programRef, '--out', join(workspace, 'revised.kiln.js')], root);- assert.equal(await readFile(join(workspace, 'revised.kiln.js'), 'utf8'), source.replace('0x4488aa', '0xaa8844'));- receipt.checks.push('mcp-discovery', 'source-reference-edit-images', 'server-restart-persistence', 'exact-source-export');+ } finally {+ restarted.close();+ }+ await command(+ [cli, 'source', changed.programRef, '--out', join(workspace, 'revised.kiln.js')],+ root,+ );+ assert.equal(+ await readFile(join(workspace, 'revised.kiln.js'), 'utf8'),+ source.replace('0x4488aa', '0xaa8844'),+ );+ receipt.checks.push(+ 'mcp-discovery',+ 'source-reference-edit-images',+ 'server-restart-persistence',+ 'exact-source-export',+ );receipt.status = 'passed';} catch (error) {receipt.status = 'failed';diff --git a/scripts/test-plugin-package.mjs b/scripts/test-plugin-package.mjsindex 6051dbf0..932354d7 100644--- a/scripts/test-plugin-package.mjs+++ b/scripts/test-plugin-package.mjs@@ -13,11 +13,19 @@ try {assert.equal(manifest.name, 'kiln-chatgpt');const mapping = JSON.parse(await readFile(join(result.directory, '.app.json')));assert.equal(mapping.apps.kiln.id, 'plugin_asdk_app_test');- assert.match(await readFile(join(result.directory, 'skills/kiln-author-asset/references/program-contract.md'), 'utf8'), /build/);+ assert.match(+ await readFile(+ join(result.directory, 'skills/kiln-author-asset/references/program-contract.md'),+ 'utf8',+ ),+ /build/,+ );await assert.rejects(packagePlugin(result.directory, 'plugin_asdk_app_test'), /exist/i);await assert.rejects(packagePlugin(join(root, 'invalid'), 'https://example.com'), /connector ID/);assert.ok(result.files > 5);- console.error('Plugin packaging passed: complete skill references, exact connector binding, no overwrite.');+ console.error(+ 'Plugin packaging passed: complete skill references, exact connector binding, no overwrite.',+ );} finally {await rm(root, { recursive: true, force: true });}diff --git a/scripts/thinking-ab.ts b/scripts/thinking-ab.tsindex 6c60a1d4..6c9cd89a 100644--- a/scripts/thinking-ab.ts+++ b/scripts/thinking-ab.ts@@ -17,14 +17,43 @@ import { assessProgramGrade } from '../src/agent/grade-refine';import { createAssetIntentV1, type AssetCategory } from '../src/contracts';const PROMPTS: Array<{ key: string; category: AssetCategory; prompt: string }> = [- { key: 'chest', category: 'prop', prompt: 'a weathered pirate treasure chest with iron bands, lid slightly open, gold coins spilling out' },+ {+ key: 'chest',+ category: 'prop',+ prompt:+ 'a weathered pirate treasure chest with iron bands, lid slightly open, gold coins spilling out',+ },{ key: 'wrxwagon', category: 'vehicle', prompt: 'a 2002 Subaru WRX wagon with a spoiler' },- { key: 'ranger', category: 'character', prompt: 'a hooded desert ranger with a walking staff, satchel, and layered cloth wraps' },- { key: 'lighthouse', category: 'architecture', prompt: 'a small cliffside lighthouse with a spiral exterior stair and a glowing lantern room' },- { key: 'archway', category: 'environment', prompt: 'an ancient mossy stone archway wrapped in flowering vines, cracked but standing' },- { key: 'stall', category: 'prop', prompt: 'a wooden market stall with a striped awning and crates of vegetables' },- { key: 'well', category: 'prop', prompt: 'a round stone well with a wooden crank, rope, and hanging bucket' },- { key: 'lamp', category: 'prop', prompt: 'a cast-iron street lamp with a hexagonal glass lantern head' },+ {+ key: 'ranger',+ category: 'character',+ prompt: 'a hooded desert ranger with a walking staff, satchel, and layered cloth wraps',+ },+ {+ key: 'lighthouse',+ category: 'architecture',+ prompt: 'a small cliffside lighthouse with a spiral exterior stair and a glowing lantern room',+ },+ {+ key: 'archway',+ category: 'environment',+ prompt: 'an ancient mossy stone archway wrapped in flowering vines, cracked but standing',+ },+ {+ key: 'stall',+ category: 'prop',+ prompt: 'a wooden market stall with a striped awning and crates of vegetables',+ },+ {+ key: 'well',+ category: 'prop',+ prompt: 'a round stone well with a wooden crank, rope, and hanging bucket',+ },+ {+ key: 'lamp',+ category: 'prop',+ prompt: 'a cast-iron street lamp with a hexagonal glass lantern head',+ },];type Arm = 'default' | 'high';@@ -129,7 +158,9 @@ async function main(): Promise<void> {await Promise.all(Array.from({ length: Math.max(1, conc) }, worker));console.log('\n## H-43 thinking A/B — gemini-3.5-flash, unified surface, n=8/arm\n');- console.log('| arm | key | ok | grade | tris | mats | steps | latency s | in tok | out tok | note |');+ console.log(+ '| arm | key | ok | grade | tris | mats | steps | latency s | in tok | out tok | note |',+ );console.log('|---|---|---|---|---|---|---|---|---|---|---|');for (const r of rows.sort((a, b) => a.key.localeCompare(b.key) || a.arm.localeCompare(b.arm))) {console.log(@@ -137,7 +168,9 @@ async function main(): Promise<void> {);}- console.log('\n| arm | ok | grades | steps p50 | latency p50 s | latency p95 s | out-tok p50 | out-tok total |');+ console.log(+ '\n| arm | ok | grades | steps p50 | latency p50 s | latency p95 s | out-tok p50 | out-tok total |',+ );console.log('|---|---|---|---|---|---|---|---|');for (const arm of ARMS) {const a = rows.filter((r) => r.arm === arm);diff --git a/scripts/upload-posters.mjs b/scripts/upload-posters.mjsindex cfe29d7a..b81155bd 100644--- a/scripts/upload-posters.mjs+++ b/scripts/upload-posters.mjs@@ -27,14 +27,17 @@ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');const wrangler = (args) => {const run = spawnSync('wrangler', args, { encoding: 'utf8', windowsHide: true });- if (run.status !== 0) throw new Error(`wrangler ${args[0]} ${args[1]} failed:\n${run.stderr || run.stdout}`);+ if (run.status !== 0)+ throw new Error(`wrangler ${args[0]} ${args[1]} failed:\n${run.stderr || run.stdout}`);return run.stdout;};/** A receipt exists only for attested posters; GIFs and previews have none. */async function recordedImageHash(name) {try {- const side = JSON.parse(await readFile(join(REPO, 'examples', `${name}.provenance.json`), 'utf8'));+ const side = JSON.parse(+ await readFile(join(REPO, 'examples', `${name}.provenance.json`), 'utf8'),+ );return side.provenance?.posterReceipt?.imageHash ?? null;} catch {return null;@@ -43,9 +46,13 @@ async function recordedImageHash(name) {let files;try {- files = (await readdir(SOURCE)).filter((f) => Object.keys(TYPES).some((e) => f.endsWith(e))).sort();+ files = (await readdir(SOURCE))+ .filter((f) => Object.keys(TYPES).some((e) => f.endsWith(e)))+ .sort();} catch {- console.log(`Nothing to publish: ${SOURCE} does not exist. Render first with scripts/hero-shots.ts or scripts/anim-gifs.ts.`);+ console.log(+ `Nothing to publish: ${SOURCE} does not exist. Render first with scripts/hero-shots.ts or scripts/anim-gifs.ts.`,+ );process.exit(0);}if (files.length === 0) {@@ -70,13 +77,24 @@ try {);const key = `${BUCKET}/${PREFIX}/${file}`;- wrangler(['r2', 'object', 'put', key, '--file', join(SOURCE, file), '--content-type', TYPES[extension], '--remote']);+ wrangler([+ 'r2',+ 'object',+ 'put',+ key,+ '--file',+ join(SOURCE, file),+ '--content-type',+ TYPES[extension],+ '--remote',+ ]);// Read it back rather than trusting the upload: these bytes are the artifact.const roundTrip = join(staging, file);wrangler(['r2', 'object', 'get', key, '--remote', '--file', roundTrip]);const stored = sha(await readFile(roundTrip));- if (stored !== digest) throw new Error(`${file} changed in transit.\n local: ${digest}\n stored: ${stored}`);+ if (stored !== digest)+ throw new Error(`${file} changed in transit.\n local: ${digest}\n stored: ${stored}`);published += 1;console.log(`${file} ${digest}${recorded ? ' (matches receipt)' : ''}`);@@ -84,4 +102,6 @@ try {} finally {await rm(staging, { recursive: true, force: true });}-console.log(`Published ${published} image${published === 1 ? '' : 's'} to ${BUCKET}/${PREFIX}, each verified byte-for-byte after upload.`);+console.log(+ `Published ${published} image${published === 1 ? '' : 's'} to ${BUCKET}/${PREFIX}, each verified byte-for-byte after upload.`,+);diff --git a/scripts/verify-posters.mjs b/scripts/verify-posters.mjsindex 5f2db104..80216526 100644--- a/scripts/verify-posters.mjs+++ b/scripts/verify-posters.mjs@@ -33,7 +33,13 @@ const BASE = process.env.KILN_POSTER_BASE ?? 'https://assets.kilnstudio.tools/reconst sha = (bytes) => createHash('sha256').update(bytes).digest('hex');/** Images published without a receipt, named individually so the gap is visible. */-const UNATTESTED = ['tidal-observatory.png', 'carousel.gif', 'orrery.gif', 'radio-telescope.gif', 'robot-arm.gif'];+const UNATTESTED = [+ 'tidal-observatory.png',+ 'carousel.gif',+ 'orrery.gif',+ 'radio-telescope.gif',+ 'robot-arm.gif',+];const entries = await readdir(RECEIPTS);const attested = entries.filter((f) => f.endsWith('.json')).sort();@@ -65,14 +71,18 @@ for (const file of [...attested.map((f) => f.replace(/\.json$/, '.png')), ...UNAfailures.push(`${file}: served as ${type || 'no content-type'}`);if (UNATTESTED.includes(file)) continue;- const receipt = JSON.parse(await readFile(join(RECEIPTS, file.replace(/\.png$/, '.json')), 'utf8'));+ const receipt = JSON.parse(+ await readFile(join(RECEIPTS, file.replace(/\.png$/, '.json')), 'utf8'),+ );if (!receipt.imageHash) {failures.push(`${file}: receipt records no imageHash`);continue;}const digest = sha(bytes);if (digest !== receipt.imageHash) {- failures.push(`${file}: published bytes differ from the receipt.\n receipt: ${receipt.imageHash}\n served: ${digest}`);+ failures.push(+ `${file}: published bytes differ from the receipt.\n receipt: ${receipt.imageHash}\n served: ${digest}`,+ );continue;}hashed += 1;