Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

feat: complete next development cycle (#3)

Matthew Kissingerfd9c2303754f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5d545bc2..61de8b19 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,12 +18,23 @@ jobs:
name: typecheck · lint · test
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- name: Setup Bun
- uses: oven-sh/setup-bun@v2
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
- bun-version: 1.3.9
+ bun-version: 1.3.14
+
+ - name: Setup Node
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 22.23.1
+
+ - name: Setup npm
+ run: npm install --global [email protected]
+
+ - name: Check toolchain metadata
+ run: bun run check:toolchain
- name: Install
run: bun install --frozen-lockfile
@@ -34,7 +45,17 @@ jobs:
- name: Lint (Biome)
run: bun run lint
- # KILN_SPIKE_LIVE=0 (the `test` script default) keeps tests offline — no model
+ # KILN_SPIKE_LIVE=0 (the `test:coverage` script default) keeps tests offline — no model
# calls, no provider key. `test:live` is the opt-in live path, not run in CI.
- - name: Unit tests
- run: bun test
+ # bunfig.toml reports text + LCOV and enforces the checked-in coverage ratchet.
+ - name: Unit tests and coverage gate
+ run: bun run test:coverage
+
+ - name: Upload coverage report
+ if: ${{ always() && hashFiles('coverage/lcov.info') != '' }}
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: engine-coverage
+ path: coverage/lcov.info
+ if-no-files-found: error
+ retention-days: 14
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..e9b13d0d
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,69 @@
+# Kiln Engine Agent Guide
+
+## Scope
+
+This repository is the private `@kiln/engine` source of truth. It turns model-authored TypeScript into
+GLB assets and includes deterministic rendering, validation/QA, primitives, agent tools, arena
+ranking, and scene composition. Product UI, API, auth, storage, AgentCore runtime, SDK, realtime, and
+IaC belong in the sibling `../kiln-studio/` repository; do not implement those here.
+
+Read [README.md](./README.md) before changing exports or package contents. Runtime code is under
+`src/`; tests are colocated as `*.test.ts` or under `__tests__/`. Repository-only checks live under
+`scripts/`. The package intentionally ships TypeScript source through the explicit `files` and
+`exports` lists in `package.json`.
+
+## Toolchain and validation
+
+Supported CI toolchain: Bun `1.3.14`; Node `22.23.1`; npm `12.0.1`. Do not use a Bun canary or implicit latest for a
+release gate.
+
+```bash
+bun install --frozen-lockfile
+bun run check:toolchain
+bun run typecheck
+bun run lint
+bun run test
+bun run test:coverage
+```
+
+Fast change loop: run the nearest test file first, then `bun run typecheck && bun run lint && bun run
+test`. Full offline gate: also run `bun run test:coverage`; it emits text plus `coverage/lcov.info`
+and enforces the checked-in line/function ratchet in `bunfig.toml`. Raise thresholds when practical;
+do not lower them without an explicit measured rationale. Live model tests are opt-in only via
+`bun run test:live` and may spend money.
+
+Use strict test-driven development for behavior changes: add a focused failing test, observe the
+expected failure, implement the smallest fix, and rerun both the focused and full gates. Preserve
+determinism and do not add `Date.now()` or `Math.random()` to render/rasterizer compute paths.
+
+## Engine consumption and package boundary
+
+Studio consumes a committed tarball, never a path link. After an approved engine change, refresh it
+from Studio—not from this repository:
+
+```bash
+cd ../kiln-studio
+bun run sync:engine
+bun install
+```
+
+Do not hand-edit `../kiln-studio/agent-runtime/vendor/kiln-engine.tgz`. Before handing off, inspect a
+package dry run and ensure tests, repository scripts, coverage output, and `AGENTS.md` have not entered
+the tarball.
+
+Container-manifest trap: Studio's local root `node_modules` can hide missing production dependencies.
+The API image installs its own manifest with Bun; the Agent image installs
+`agent-runtime/package.json` with `npm --legacy-peer-deps`. Engine optional provider peers must be
+explicit in every consuming image manifest that needs them. Follow `../kiln-studio/CLAUDE.md` and its
+current container boot-validation runbook before any deployment.
+
+## Safety
+
+- Keep the raw engine/tool surface private; Studio `/v1` is the approved external product boundary.
+- Never print, read unnecessarily, or commit provider keys, AWS credentials, `.env*`, or secrets.
+- Keep normal validation offline. Do not invoke live providers unless explicitly requested.
+- Do not deploy, commit, push, force-push, create remotes/releases, mutate AWS, or publish packages
+ without explicit user approval. Production changes belong to Studio's guarded deploy flow.
+- Do not edit the historical `pixel-forge` repository or use it as a build dependency.
+- Do not edit the workspace root or sibling Studio while performing an engine-only task, except when
+ the user explicitly expands scope or requests the documented tarball synchronization.
diff --git a/README.md b/README.md
index 62048fe9..eb72895b 100644
--- a/README.md
+++ b/README.md
@@ -38,8 +38,13 @@ For current access and distribution decisions, see
bun install
bun run typecheck # tsc --noEmit
bun run test # bun test (offline; live agent tests gated behind KILN_SPIKE_LIVE=1)
+bun run test:coverage # LCOV report plus the checked coverage ratchet
```
+The reliability baseline is **95.38% functions / 91.80% lines**. CI enforces
+non-regression ratchets of 92% functions and 91% lines and uploads `coverage/lcov.info`.
+Threshold decreases require an explicit measured rationale.
+
## Subpath exports
The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by subpath:
diff --git a/bun.lock b/bun.lock
index 5d505c6f..b0f4103e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -26,7 +26,7 @@
"@aws-sdk/client-bedrock-runtime": "^3.1083.0",
"@biomejs/biome": "^2.5.3",
"@google/genai": "^2.10.0",
- "@strands-agents/sdk": "^1.8.0",
+ "@strands-agents/sdk": "1.10.0",
"@types/bun": "^1.3.14",
"ai": "^6.0.222",
"openai": "^6.46.0",
@@ -230,7 +230,7 @@
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
- "@strands-agents/sdk": ["@strands-agents/[email protected]", "", { "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.1069.0", "@types/json-schema": "^7.0.15", "uuid": "^14.0.1", "yaml": "^2.8.3" }, "peerDependencies": { "@a2a-js/sdk": "^0.3.10", "@ai-sdk/provider": "^3.0.0", "@anthropic-ai/sdk": "^0.106.0", "@aws-sdk/client-bedrock-agent": "^3.1075.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.1075.0", "@aws-sdk/client-s3": "^3.1069.0", "@aws/bedrock-token-generator": "^1.1.0", "@cedar-policy/cedar-wasm": "^4.0.0", "@cedar-policy/mcp-schema-generator-wasm": "^0.6.0", "@google/genai": "^2.6.0", "@modelcontextprotocol/sdk": "^1.25.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.219.0", "@opentelemetry/exporter-trace-otlp-http": "^0.219.0", "@opentelemetry/resources": "^2.8.0", "@opentelemetry/sdk-metrics": "^2.6.1", "@opentelemetry/sdk-trace-base": "^2.6.1", "@opentelemetry/sdk-trace-node": "^2.6.1", "@smithy/types": "^4.15.1", "express": "^5.1.0", "openai": "^6.45.0", "zod": "^4.1.12" }, "optionalPeers": ["@a2a-js/sdk", "@ai-sdk/provider", "@anthropic-ai/sdk", "@aws-sdk/client-bedrock-agent", "@aws-sdk/client-bedrock-agent-runtime", "@aws-sdk/client-s3", "@aws/bedrock-token-generator", "@cedar-policy/cedar-wasm", "@cedar-policy/mcp-schema-generator-wasm", "@google/genai", "@opentelemetry/exporter-metrics-otlp-http", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@smithy/types", "express", "openai"] }, "sha512-JYRWJPlWKHwIHY8ksXNPeyqD1+kRDYgS2RglYWEm/Wz48ZdlF3Fw40vrTqL1huIIB9P6+VR5lQlkyTrYmZvnbA=="],
+ "@strands-agents/sdk": ["@strands-agents/[email protected]", "", { "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.1078.0", "@types/json-schema": "^7.0.15", "uuid": "^14.0.1", "yaml": "^2.8.3" }, "peerDependencies": { "@a2a-js/sdk": "^0.3.10", "@ai-sdk/provider": "^3.0.0", "@anthropic-ai/sdk": "^0.109.1", "@aws-sdk/client-bedrock-agent": "^3.1078.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.1078.0", "@aws-sdk/client-s3": "^3.1078.0", "@aws/bedrock-token-generator": "^1.1.0", "@cedar-policy/cedar-wasm": "^4.0.0", "@cedar-policy/mcp-schema-generator-wasm": "^0.6.0", "@google/genai": "^2.6.0", "@modelcontextprotocol/sdk": "^1.25.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.219.0", "@opentelemetry/exporter-trace-otlp-http": "^0.219.0", "@opentelemetry/resources": "^2.8.0", "@opentelemetry/sdk-metrics": "^2.6.1", "@opentelemetry/sdk-trace-base": "^2.6.1", "@opentelemetry/sdk-trace-node": "^2.6.1", "@smithy/types": "^4.15.1", "express": "^5.1.0", "openai": "^6.45.0", "zod": "^4.1.12" }, "optionalPeers": ["@a2a-js/sdk", "@ai-sdk/provider", "@anthropic-ai/sdk", "@aws-sdk/client-bedrock-agent", "@aws-sdk/client-bedrock-agent-runtime", "@aws-sdk/client-s3", "@aws/bedrock-token-generator", "@cedar-policy/cedar-wasm", "@cedar-policy/mcp-schema-generator-wasm", "@google/genai", "@opentelemetry/exporter-metrics-otlp-http", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@smithy/types", "express", "openai"] }, "sha512-7KIGM+6cCgN/RbIcXFRTtLkLkdtXB57zprUvy2bZL+BO8WkhHh4Fv8DpRwTAZXZQUq37KqwmQ/DyX70Y2xTvog=="],
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
diff --git a/bunfig.toml b/bunfig.toml
new file mode 100644
index 00000000..9e579b75
--- /dev/null
+++ b/bunfig.toml
@@ -0,0 +1,18 @@
+[test]
+coverageSkipTestFiles = true
+coverageReporter = ["text", "lcov"]
+coverageDir = "coverage"
+coveragePathIgnorePatterns = [
+ "**/*.test.ts",
+ "**/*.test.mjs",
+ "**/__tests__/**",
+ "**/__snapshots__/**",
+ "**/fixtures/**",
+ "**/fixtures.ts",
+ "**/*.d.ts",
+ "**/generated/**",
+ "**/*.generated.ts",
+ "dist/**",
+ "coverage/**",
+ "vendor/**",
+]
diff --git a/coverage-thresholds.json b/coverage-thresholds.json
new file mode 100644
index 00000000..cd249cb4
--- /dev/null
+++ b/coverage-thresholds.json
@@ -0,0 +1,10 @@
+{
+ "measuredBaseline": {
+ "functions": 95.38,
+ "lines": 91.80
+ },
+ "thresholds": {
+ "functions": 92,
+ "lines": 91
+ }
+}
diff --git a/package.json b/package.json
index f05fd0fa..cc10ea78 100644
--- a/package.json
+++ b/package.json
@@ -6,6 +6,12 @@
"license": "MIT",
"author": "Matthew Kissinger",
"type": "module",
+ "packageManager": "[email protected]",
+ "engines": {
+ "bun": "1.3.14",
+ "node": "22.23.1",
+ "npm": "12.0.1"
+ },
"exports": {
"./agent": "./src/agent/index.ts",
"./arena": "./src/arena/index.ts",
@@ -41,9 +47,11 @@
"CHANGELOG.md"
],
"scripts": {
+ "check:toolchain": "bun scripts/check-toolchain.mjs",
"typecheck": "tsc --noEmit",
"build": "tsc --noEmit",
"test": "KILN_SPIKE_LIVE=0 bun test",
+ "test:coverage": "KILN_SPIKE_LIVE=0 bun test --coverage && bun scripts/check-coverage.mjs",
"test:live": "KILN_SPIKE_LIVE=1 bun test",
"lint": "biome check ."
},
@@ -84,7 +92,7 @@
"@aws-sdk/client-bedrock-runtime": "^3.1083.0",
"@biomejs/biome": "^2.5.3",
"@google/genai": "^2.10.0",
- "@strands-agents/sdk": "^1.8.0",
+ "@strands-agents/sdk": "1.10.0",
"@types/bun": "^1.3.14",
"ai": "^6.0.222",
"openai": "^6.46.0",
diff --git a/scripts/check-coverage.mjs b/scripts/check-coverage.mjs
new file mode 100644
index 00000000..98e91a0b
--- /dev/null
+++ b/scripts/check-coverage.mjs
@@ -0,0 +1,48 @@
+import { readFile } from 'node:fs/promises';
+
+const lcovPath = process.argv[2] ?? 'coverage/lcov.info';
+const thresholdsPath = process.argv[3] ?? 'coverage-thresholds.json';
+
+function totalField(lcov, field) {
+ return [...lcov.matchAll(new RegExp(`^${field}:(\\d+)$`, 'gmu'))].reduce(
+ (sum, match) => sum + Number(match[1]),
+ 0,
+ );
+}
+
+function percentage(hit, found, label) {
+ if (found === 0) throw new Error(`LCOV report contains no ${label}`);
+ return (hit / found) * 100;
+}
+
+const [lcov, configurationText] = await Promise.all([
+ readFile(lcovPath, 'utf8'),
+ readFile(thresholdsPath, 'utf8'),
+]);
+const configuration = JSON.parse(configurationText);
+const thresholds = configuration.thresholds;
+
+if (
+ typeof thresholds?.functions !== 'number' ||
+ typeof thresholds?.lines !== 'number' ||
+ thresholds.functions < 0 ||
+ thresholds.lines < 0
+) {
+ throw new Error('coverage thresholds must contain non-negative functions and lines percentages');
+}
+
+const actual = {
+ functions: percentage(totalField(lcov, 'FNH'), totalField(lcov, 'FNF'), 'functions'),
+ lines: percentage(totalField(lcov, 'LH'), totalField(lcov, 'LF'), 'lines'),
+};
+const failures = Object.entries(thresholds).filter(
+ ([metric, threshold]) => actual[metric] < threshold,
+);
+const summary = `functions ${actual.functions.toFixed(2)}% (minimum ${thresholds.functions.toFixed(2)}%), lines ${actual.lines.toFixed(2)}% (minimum ${thresholds.lines.toFixed(2)}%)`;
+
+if (failures.length > 0) {
+ console.error(`Coverage gate failed: ${summary}`);
+ process.exit(1);
+}
+
+console.log(`Coverage gate passed: ${summary}`);
diff --git a/scripts/check-coverage.test.mjs b/scripts/check-coverage.test.mjs
new file mode 100644
index 00000000..92828397
--- /dev/null
+++ b/scripts/check-coverage.test.mjs
@@ -0,0 +1,68 @@
+import { expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const checker = new URL('./check-coverage.mjs', import.meta.url).pathname;
+
+async function fixture(thresholds) {
+ const directory = await mkdtemp(join(tmpdir(), 'kiln-coverage-'));
+ await writeFile(
+ join(directory, 'lcov.info'),
+ [
+ 'TN:',
+ 'SF:src/example.ts',
+ 'FN:1,covered',
+ 'FNDA:1,covered',
+ 'FN:2,uncovered',
+ 'FNDA:0,uncovered',
+ 'FNF:2',
+ 'FNH:1',
+ 'DA:1,1',
+ 'DA:2,0',
+ 'LF:2',
+ 'LH:1',
+ 'end_of_record',
+ '',
+ ].join('\n'),
+ );
+ await writeFile(join(directory, 'thresholds.json'), JSON.stringify({ thresholds }));
+ return directory;
+}
+
+test('aggregate coverage checker accepts coverage at the ratchet', async () => {
+ const directory = await fixture({ functions: 50, lines: 50 });
+ try {
+ const result = spawnSync(
+ process.execPath,
+ [checker, join(directory, 'lcov.info'), join(directory, 'thresholds.json')],
+ { encoding: 'utf8' },
+ );
+
+ expect(result.status, result.stderr || result.stdout).toBe(0);
+ expect(result.stdout.trim()).toBe(
+ 'Coverage gate passed: functions 50.00% (minimum 50.00%), lines 50.00% (minimum 50.00%)',
+ );
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test('aggregate coverage checker rejects coverage below either ratchet', async () => {
+ const directory = await fixture({ functions: 50.01, lines: 50.01 });
+ try {
+ const result = spawnSync(
+ process.execPath,
+ [checker, join(directory, 'lcov.info'), join(directory, 'thresholds.json')],
+ { encoding: 'utf8' },
+ );
+
+ expect(result.status).toBe(1);
+ expect(result.stderr.trim()).toBe(
+ 'Coverage gate failed: functions 50.00% (minimum 50.01%), lines 50.00% (minimum 50.01%)',
+ );
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/check-toolchain.mjs b/scripts/check-toolchain.mjs
new file mode 100644
index 00000000..fa811b35
--- /dev/null
+++ b/scripts/check-toolchain.mjs
@@ -0,0 +1,55 @@
+import { spawnSync } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+
+const filesOnly = process.argv.includes('--files-only');
+const packageJson = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
+const workflow = await readFile(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8');
+
+const expectedPackageManager = '[email protected]';
+const expectedEngines = { bun: '1.3.14', node: '22.23.1', npm: '12.0.1' };
+const errors = [];
+
+if (packageJson.packageManager !== expectedPackageManager) {
+ errors.push(`packageManager must be ${expectedPackageManager}`);
+}
+if (packageJson.engines?.bun !== expectedEngines.bun) {
+ errors.push(`engines.bun must be ${expectedEngines.bun}`);
+}
+if (packageJson.engines?.node !== expectedEngines.node) {
+ errors.push(`engines.node must be ${expectedEngines.node}`);
+}
+if (packageJson.engines?.npm !== expectedEngines.npm) {
+ errors.push(`engines.npm must be ${expectedEngines.npm}`);
+}
+if (!/^\s*bun-version:\s*1\.3\.14\s*$/mu.test(workflow)) {
+ errors.push('CI bun-version must be 1.3.14');
+}
+if (!/^\s*node-version:\s*22\.23\.1\s*$/mu.test(workflow)) {
+ errors.push('CI node-version must be 22.23.1');
+}
+if (!workflow.includes('npm install --global [email protected]')) {
+ errors.push('CI npm version must be 12.0.1');
+}
+if (!workflow.includes('run: bun run check:toolchain')) {
+ errors.push('CI must run the toolchain metadata check');
+}
+for (const ref of workflow.matchAll(/uses:\s*([^\s#]+)/g)) {
+ if (!ref[1].startsWith('./') && !/@[0-9a-f]{40}$/i.test(ref[1])) errors.push(`CI Action ref must use an immutable commit SHA: ${ref[1]}`);
+}
+if (!filesOnly && process.versions.bun !== expectedEngines.bun) {
+ errors.push(`runtime Bun must be ${expectedEngines.bun} (found ${process.versions.bun ?? 'Node'})`);
+}
+if (!filesOnly) {
+ const revision = spawnSync('bun', ['--revision'], { encoding: 'utf8', shell: false });
+ const value = String(revision.stdout || revision.stderr || '').trim();
+ if (revision.status !== 0 || !/^1\.3\.14\+[0-9a-f]+$/i.test(value)) {
+ errors.push(`runtime Bun must be stable 1.3.14 (found ${value || 'missing'})`);
+ }
+}
+
+if (errors.length > 0) {
+ for (const error of errors) console.error(`- ${error}`);
+ process.exit(1);
+}
+
+console.log(`Toolchain metadata: Bun ${expectedEngines.bun}, Node ${expectedEngines.node}, npm ${expectedEngines.npm}`);
diff --git a/scripts/reliability.test.mjs b/scripts/reliability.test.mjs
new file mode 100644
index 00000000..d362454e
--- /dev/null
+++ b/scripts/reliability.test.mjs
@@ -0,0 +1,71 @@
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+
+const root = new URL('../', import.meta.url);
+const rootPath = fileURLToPath(root);
+
+async function readJson(path) {
+ return JSON.parse(await readFile(new URL(path, root), 'utf8'));
+}
+
+async function readText(path) {
+ return readFile(new URL(path, root), 'utf8').catch(() => '');
+}
+
+describe('repository reliability contracts', () => {
+ test('package metadata declares the CI-supported runtimes', async () => {
+ const pkg = await readJson('package.json');
+
+ expect(pkg.packageManager).toBe('[email protected]');
+ expect(pkg.engines).toEqual({ bun: '1.3.14', node: '22.23.1', npm: '12.0.1' });
+ });
+
+ test('the toolchain checker verifies package and workflow metadata', async () => {
+ const pkg = await readJson('package.json');
+ const result = spawnSync(process.execPath, ['scripts/check-toolchain.mjs', '--files-only'], {
+ cwd: rootPath,
+ encoding: 'utf8',
+ });
+
+ expect(pkg.scripts['check:toolchain']).toBe('bun scripts/check-toolchain.mjs');
+ expect(result.status, result.stderr || result.stdout).toBe(0);
+ expect(result.stdout.trim()).toBe('Toolchain metadata: Bun 1.3.14, Node 22.23.1, npm 12.0.1');
+ });
+
+ test('coverage is measured, ratcheted, and retained by CI', async () => {
+ const pkg = await readJson('package.json');
+ const bunfig = await readText('bunfig.toml');
+ const thresholds = JSON.parse((await readText('coverage-thresholds.json')) || '{}');
+ const readme = await readText('README.md');
+ const workflow = await readText('.github/workflows/ci.yml');
+
+ expect(pkg.scripts['test:coverage']).toBe(
+ 'KILN_SPIKE_LIVE=0 bun test --coverage && bun scripts/check-coverage.mjs',
+ );
+ expect(bunfig).toContain('coverageReporter = ["text", "lcov"]');
+ expect(bunfig).not.toContain('coverageThreshold =');
+ expect(bunfig).toContain('coveragePathIgnorePatterns = [');
+ expect(thresholds).toEqual({
+ measuredBaseline: { functions: 95.38, lines: 91.8 },
+ thresholds: { functions: 92, lines: 91 },
+ });
+ expect(readme).toContain('95.38% functions / 91.80% lines');
+ expect(readme).toContain('Threshold decreases require an explicit measured rationale.');
+ expect(workflow).toContain('run: bun run test:coverage');
+ expect(workflow).toContain('uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02');
+ expect(workflow).toContain('path: coverage/lcov.info');
+ });
+
+ test('standalone agent context stays concise and names the safety-critical paths', async () => {
+ const agents = await readText('AGENTS.md');
+
+ expect(Buffer.byteLength(agents)).toBeGreaterThan(0);
+ expect(Buffer.byteLength(agents)).toBeLessThan(12 * 1024);
+ expect(agents).toContain('bun run test:coverage');
+ expect(agents).toContain('bun run sync:engine');
+ expect(agents).toContain('npm --legacy-peer-deps');
+ expect(agents).toContain('Do not deploy, commit, push');
+ });
+});
diff --git a/src/contracts/asset.test.ts b/src/contracts/asset.test.ts
index be352e1c..2ce2afa0 100644
--- a/src/contracts/asset.test.ts
+++ b/src/contracts/asset.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, test } from 'bun:test';
import {
+ ARCHITECTURE_INTERIOR_MODES,
+ ARCHITECTURE_ROOF_MODES,
+ ARCHITECTURE_ROOF_TYPES,
ASSET_CATEGORIES,
KILN_ASSET_FRAME,
createAssetIntentV1,
@@ -249,6 +252,93 @@ describe('asset contracts', () => {
);
});
+ test('normalizes the architecture lifecycle contract while preserving legacy enterable input', () => {
+ expect(ARCHITECTURE_INTERIOR_MODES).toEqual(['none', 'shell', 'navigable']);
+ expect(ARCHITECTURE_ROOF_MODES).toEqual(['auto', 'fixed', 'removable', 'none']);
+ expect(ARCHITECTURE_ROOF_TYPES).toContain('dome');
+
+ const legacy = createAssetIntentV1({
+ category: 'architecture',
+ architecture: { enterable: true },
+ });
+ expect(legacy.architecture).toMatchObject({
+ enterable: true,
+ storeyCount: 1,
+ interiorMode: 'navigable',
+ roofMode: 'auto',
+ });
+ expect(legacy.capabilities).toEqual(expect.arrayContaining(['enterable', 'navigable']));
+
+ const shell = createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ storeyCount: 5,
+ interiorMode: 'shell',
+ roofMode: 'removable',
+ },
+ });
+ expect(shell.architecture).toMatchObject({
+ enterable: false,
+ storeyCount: 5,
+ interiorMode: 'shell',
+ roofMode: 'removable',
+ });
+ expect(shell.capabilities).not.toContain('enterable');
+ expect(shell.capabilities).not.toContain('navigable');
+ expect(validateAssetIntentV1(shell).valid).toBe(true);
+ });
+
+ test('normalizes dome/rotunda intent and rejects invalid architecture lifecycle values', () => {
+ const rotunda = createAssetIntentV1({
+ category: 'architecture',
+ subtype: 'rotunda',
+ architecture: {
+ storeyCount: 1,
+ interiorMode: 'navigable',
+ roofMode: 'fixed',
+ roof: { type: 'dome', rise: 5.5, pitchDegrees: 0, closedEnds: false },
+ },
+ });
+ expect(rotunda.architecture).toMatchObject({
+ subtype: 'rotunda',
+ storeyCount: 1,
+ interiorMode: 'navigable',
+ roofMode: 'fixed',
+ roof: { type: 'dome', rise: 5.5, pitchDegrees: 0 },
+ });
+ expect(validateAssetIntentV1(rotunda).valid).toBe(true);
+
+ for (const architecture of [
+ { ...rotunda.architecture!, storeyCount: 0 },
+ { ...rotunda.architecture!, storeyCount: 6 },
+ { ...rotunda.architecture!, storeyCount: 1.5 },
+ { ...rotunda.architecture!, interiorMode: 'decorative' },
+ { ...rotunda.architecture!, roofMode: 'hinged' },
+ { ...rotunda.architecture!, enterable: false },
+ {
+ ...rotunda.architecture!,
+ roofMode: 'none',
+ roof: { ...rotunda.architecture!.roof, type: 'dome' },
+ },
+ ]) {
+ expect(validateAssetIntentV1({ ...rotunda, architecture }).valid).toBe(false);
+ }
+ });
+
+ test('continues to validate pre-lifecycle architecture v1 payloads using legacy semantics', () => {
+ const current = createAssetIntentV1({
+ category: 'architecture',
+ architecture: { enterable: false, roof: { type: 'none' } },
+ });
+ const {
+ storeyCount: _storeys,
+ interiorMode: _interior,
+ roofMode: _roofMode,
+ ...legacy
+ } = current.architecture!;
+ expect(validateAssetIntentV1({ ...current, architecture: legacy }).valid).toBe(true);
+ });
+
test('normalizes a complete architecture intent with consistent pitch, rise, and portal clearance', () => {
const intent = createAssetIntentV1({
category: 'architecture',
diff --git a/src/contracts/asset.ts b/src/contracts/asset.ts
index bd955c2d..f9953b71 100644
--- a/src/contracts/asset.ts
+++ b/src/contracts/asset.ts
@@ -206,9 +206,23 @@ export interface VehicleIntentV1Input {
animationAssemblies?: readonly string[];
}
-export const ARCHITECTURE_ROOF_TYPES = ['gable', 'shed', 'hip', 'flat', 'none', 'custom'] as const;
+export const ARCHITECTURE_ROOF_TYPES = [
+ 'gable',
+ 'shed',
+ 'hip',
+ 'dome',
+ 'flat',
+ 'none',
+ 'custom',
+] as const;
export type ArchitectureRoofType = (typeof ARCHITECTURE_ROOF_TYPES)[number];
+export const ARCHITECTURE_INTERIOR_MODES = ['none', 'shell', 'navigable'] as const;
+export type ArchitectureInteriorMode = (typeof ARCHITECTURE_INTERIOR_MODES)[number];
+
+export const ARCHITECTURE_ROOF_MODES = ['auto', 'fixed', 'removable', 'none'] as const;
+export type ArchitectureRoofMode = (typeof ARCHITECTURE_ROOF_MODES)[number];
+
export const ARCHITECTURE_SCALE_MODES = ['realistic', 'stylized'] as const;
export type ArchitectureScaleMode = (typeof ARCHITECTURE_SCALE_MODES)[number];
@@ -243,7 +257,14 @@ export interface ArchitectureRoofIntentV1 {
/** Trusted, category-specific architecture requirements. */
export interface ArchitectureIntentV1 {
subtype: string;
+ /** Legacy compatibility projection; true exactly for navigable interiors. */
enterable: boolean;
+ /** Requested above-ground storeys. Deterministic architecture QA supports one through five. */
+ storeyCount: number;
+ /** Whether the asset has no interior, a visible shell, or a traversable interior. */
+ interiorMode: ArchitectureInteriorMode;
+ /** Roof ownership/removal policy, independent from the geometric roof profile. */
+ roofMode: ArchitectureRoofMode;
footprint: ArchitectureFootprintV1;
wallHeight: number;
scaleMode: ArchitectureScaleMode;
@@ -254,7 +275,11 @@ export interface ArchitectureIntentV1 {
export interface ArchitectureIntentV1Input {
subtype?: string;
+ /** @deprecated Prefer interiorMode; retained for persisted/request compatibility. */
enterable?: boolean;
+ storeyCount?: number;
+ interiorMode?: ArchitectureInteriorMode;
+ roofMode?: ArchitectureRoofMode;
footprint?: Partial<Omit<ArchitectureFootprintV1, 'units'>> & { units?: 'm' };
wallHeight?: number;
scaleMode?: ArchitectureScaleMode;
@@ -974,6 +999,54 @@ function validateArchitecture(
});
valid = false;
}
+ // These fields were added to schema v1 after the original architecture
+ // contract shipped. Missing values retain legacy semantics at read time;
+ // newly normalized intents always emit all three fields.
+ if (
+ value.storeyCount !== undefined &&
+ (typeof value.storeyCount !== 'number' ||
+ !Number.isInteger(value.storeyCount) ||
+ value.storeyCount < 1 ||
+ value.storeyCount > 5)
+ ) {
+ issues.push({
+ code: 'INVALID_ARCHITECTURE_STOREY_COUNT',
+ path: 'architecture.storeyCount',
+ message: 'architecture.storeyCount must be an integer from 1 through 5.',
+ });
+ valid = false;
+ }
+ if (
+ value.interiorMode !== undefined &&
+ !isEnumValue(ARCHITECTURE_INTERIOR_MODES, value.interiorMode)
+ ) {
+ issues.push({
+ code: 'INVALID_ARCHITECTURE_INTERIOR_MODE',
+ path: 'architecture.interiorMode',
+ message: `architecture.interiorMode must be one of ${ARCHITECTURE_INTERIOR_MODES.join(', ')}.`,
+ });
+ valid = false;
+ }
+ if (value.roofMode !== undefined && !isEnumValue(ARCHITECTURE_ROOF_MODES, value.roofMode)) {
+ issues.push({
+ code: 'INVALID_ARCHITECTURE_ROOF_MODE',
+ path: 'architecture.roofMode',
+ message: `architecture.roofMode must be one of ${ARCHITECTURE_ROOF_MODES.join(', ')}.`,
+ });
+ valid = false;
+ }
+ if (
+ isEnumValue(ARCHITECTURE_INTERIOR_MODES, value.interiorMode) &&
+ typeof value.enterable === 'boolean' &&
+ value.enterable !== (value.interiorMode === 'navigable')
+ ) {
+ issues.push({
+ code: 'ARCHITECTURE_INTERIOR_ENTERABLE_MISMATCH',
+ path: 'architecture.enterable',
+ message: 'architecture.enterable must be true exactly when interiorMode is "navigable".',
+ });
+ valid = false;
+ }
if (!isEnumValue(ARCHITECTURE_SCALE_MODES, value.scaleMode)) {
issues.push({
code: 'INVALID_ARCHITECTURE_SCALE_MODE',
@@ -1032,6 +1105,7 @@ function validateArchitecture(
valid = false;
}
const flat = roof.type === 'flat' || roof.type === 'none';
+ const dome = roof.type === 'dome';
if (
typeof roof.rise !== 'number' ||
!Number.isFinite(roof.rise) ||
@@ -1049,14 +1123,15 @@ function validateArchitecture(
if (
typeof roof.pitchDegrees !== 'number' ||
!Number.isFinite(roof.pitchDegrees) ||
- (flat ? roof.pitchDegrees !== 0 : roof.pitchDegrees <= 0 || roof.pitchDegrees >= 89)
+ (flat || dome ? roof.pitchDegrees !== 0 : roof.pitchDegrees <= 0 || roof.pitchDegrees >= 89)
) {
issues.push({
code: 'INVALID_ARCHITECTURE_ROOF_PITCH',
path: 'architecture.roof.pitchDegrees',
- message: flat
- ? 'Flat or absent roofs must have zero pitch.'
- : 'Pitched roofs must have a pitch greater than 0 and less than 89 degrees.',
+ message:
+ flat || dome
+ ? 'Flat, absent, or dome roofs must have zero planar pitch.'
+ : 'Pitched roofs must have a pitch greater than 0 and less than 89 degrees.',
});
valid = false;
}
@@ -1079,6 +1154,7 @@ function validateArchitecture(
if (
!flat &&
+ !dome &&
isRecord(value.footprint) &&
typeof value.footprint.spanX === 'number' &&
typeof value.footprint.spanZ === 'number' &&
@@ -1099,6 +1175,17 @@ function validateArchitecture(
valid = false;
}
}
+ if (
+ isEnumValue(ARCHITECTURE_ROOF_MODES, value.roofMode) &&
+ (value.roofMode === 'none') !== (roof.type === 'none')
+ ) {
+ issues.push({
+ code: 'ARCHITECTURE_ROOF_MODE_TYPE_MISMATCH',
+ path: 'architecture.roofMode',
+ message: 'roofMode and roof.type must both be "none", or both describe a present roof.',
+ });
+ valid = false;
+ }
}
if (value.portal !== undefined) {
@@ -1241,6 +1328,18 @@ export function validateAssetIntentV1(value: unknown): ContractValidationResult<
message: 'The enterable capability must exactly match architecture.enterable.',
});
}
+ if (
+ isRecord(value.architecture) &&
+ isEnumValue(ARCHITECTURE_INTERIOR_MODES, value.architecture.interiorMode) &&
+ Array.isArray(value.capabilities) &&
+ value.capabilities.includes('navigable') !== (value.architecture.interiorMode === 'navigable')
+ ) {
+ issues.push({
+ code: 'ARCHITECTURE_NAVIGABLE_CAPABILITY_MISMATCH',
+ path: 'capabilities',
+ message: 'The navigable capability must exactly match architecture.interiorMode.',
+ });
+ }
} else if (value.architecture !== undefined) {
issues.push({
code: 'ARCHITECTURE_INTENT_CATEGORY_MISMATCH',
@@ -1457,23 +1556,33 @@ function normalizeArchitectureIntent(input: AssetIntentV1Input): ArchitectureInt
const ridgeAxis = architecture.roof?.ridgeAxis ?? 'x';
const roofType = architecture.roof?.type ?? 'gable';
const flat = roofType === 'flat' || roofType === 'none';
+ const dome = roofType === 'dome';
const halfRun = (ridgeAxis === 'x' ? spanZ : spanX) / 2;
const suppliedRise = architecture.roof?.rise;
const suppliedPitch = architecture.roof?.pitchDegrees;
- const pitchDegrees = flat
- ? (suppliedPitch ?? 0)
- : (suppliedPitch ??
- (suppliedRise !== undefined && halfRun > 0
- ? Math.atan2(suppliedRise, halfRun) / THREE_DEGREES
- : 30));
+ const pitchDegrees =
+ flat || dome
+ ? (suppliedPitch ?? 0)
+ : (suppliedPitch ??
+ (suppliedRise !== undefined && halfRun > 0
+ ? Math.atan2(suppliedRise, halfRun) / THREE_DEGREES
+ : 30));
const rise = flat
? (suppliedRise ?? 0)
- : (suppliedRise ?? Math.tan(pitchDegrees * THREE_DEGREES) * halfRun);
- const enterable = architecture.enterable ?? true;
+ : dome
+ ? (suppliedRise ?? Math.min(spanX, spanZ) / 2)
+ : (suppliedRise ?? Math.tan(pitchDegrees * THREE_DEGREES) * halfRun);
+ const interiorMode =
+ architecture.interiorMode ?? (architecture.enterable === false ? 'none' : 'navigable');
+ const enterable = architecture.enterable ?? interiorMode === 'navigable';
+ const roofMode = architecture.roofMode ?? (roofType === 'none' ? 'none' : 'auto');
return {
subtype: architecture.subtype ?? input.subtype ?? 'building',
enterable,
+ storeyCount: architecture.storeyCount ?? 1,
+ interiorMode,
+ roofMode,
footprint: { spanX, spanZ, units: 'm' },
wallHeight: architecture.wallHeight ?? input.bounds?.y ?? 2.8,
scaleMode: architecture.scaleMode ?? 'realistic',
@@ -1835,6 +1944,8 @@ export function createAssetIntentV1(input: AssetIntentV1Input): AssetIntentV1 {
const capabilities = [...(input.capabilities ?? [])];
if (architecture?.enterable && !capabilities.includes('enterable'))
capabilities.push('enterable');
+ if (architecture?.interiorMode === 'navigable' && !capabilities.includes('navigable'))
+ capabilities.push('navigable');
if (character?.grounded && !capabilities.includes('grounded')) capabilities.push('grounded');
if (vehicle?.supportPolicy === 'grounded' && !capabilities.includes('grounded')) {
capabilities.push('grounded');
diff --git a/src/qa/architecture-corpus.ts b/src/qa/architecture-corpus.ts
index 329fbcb3..05a99b99 100644
--- a/src/qa/architecture-corpus.ts
+++ b/src/qa/architecture-corpus.ts
@@ -44,6 +44,10 @@ const CANONICAL_ARCHITECTURE_CODES = Object.freeze([
'ARCH_RIDGE_GAP',
'ARCH_ENVELOPE_GAP',
'ARCH_BLOCKED_PORTAL',
+ 'ARCH_STOREY_COUNT',
+ 'ARCH_INTERIOR_MODE',
+ 'ARCH_ROOF_MODE',
+ 'ARCH_DOME_PROFILE',
]);
function semantic<T extends THREE.Object3D>(node: T, role: string): T {
@@ -413,6 +417,180 @@ function buildPorchIntersectionControl(): ArchitectureCorpusPayload {
return payload;
}
+function buildStoreyControl(builtStoreys: 1 | 2): ArchitectureCorpusPayload {
+ const root = new THREE.Group();
+ root.name = `ArchitectureStoreys_${builtStoreys}`;
+ const material = new THREE.MeshStandardMaterial({ color: 0xb9a17d });
+ for (let index = 1; index <= builtStoreys; index++) {
+ part(
+ root,
+ `Floor_${index}`,
+ new THREE.BoxGeometry(6, 0.12, 4),
+ material,
+ `floor.storey.${index}`,
+ [0, (index - 1) * 3, 0],
+ );
+ }
+ root.updateMatrixWorld(true);
+ return {
+ intent: createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ storeyCount: 2,
+ interiorMode: 'none',
+ roofMode: 'none',
+ roof: { type: 'none' },
+ },
+ }),
+ scene: root,
+ };
+}
+
+function buildInteriorShellControl(hasShell: boolean): ArchitectureCorpusPayload {
+ const root = new THREE.Group();
+ root.name = hasShell ? 'ArchitectureInteriorShellControl' : 'ArchitectureInteriorShellMissing';
+ part(
+ root,
+ 'WallFront',
+ new THREE.BoxGeometry(0.15, 3, 4),
+ new THREE.MeshStandardMaterial({ color: 0xb9a17d }),
+ 'wall.front',
+ [3, 1.5, 0],
+ );
+ if (hasShell) {
+ const interior = semantic(new THREE.Group(), 'architecture.interior.shell');
+ interior.name = 'InteriorShell';
+ interior.scale.set(5.7, 2.8, 3.7);
+ interior.position.y = 1.5;
+ root.add(interior);
+ }
+ root.updateMatrixWorld(true);
+ return {
+ intent: createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ interiorMode: 'shell',
+ roofMode: 'none',
+ roof: { type: 'none' },
+ },
+ }),
+ scene: root,
+ };
+}
+
+function buildRemovableRoofControl(separable: boolean): ArchitectureCorpusPayload {
+ const root = new THREE.Group();
+ root.name = separable ? 'ArchitectureRemovableRoofControl' : 'ArchitectureRemovableRoofFixed';
+ const roof = new THREE.Mesh(
+ new THREE.BoxGeometry(6.4, 0.15, 4.4),
+ new THREE.MeshStandardMaterial({ color: 0x59616d }),
+ );
+ roof.name = 'Roof';
+ roof.position.y = 3;
+ stampSemanticMetadataV1(roof, {
+ roles: ['roof.assembly'],
+ ...(separable
+ ? {
+ relationships: [
+ {
+ kind: 'separable-from',
+ target: 'architecture.shell',
+ targetType: 'role' as const,
+ },
+ ],
+ }
+ : {}),
+ });
+ root.add(roof);
+ root.updateMatrixWorld(true);
+ return {
+ intent: createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ interiorMode: 'none',
+ roofMode: 'removable',
+ roof: { type: 'flat' },
+ },
+ }),
+ scene: root,
+ };
+}
+
+function buildRotundaControl(radiusScale: 0.5 | 1): ArchitectureCorpusPayload {
+ const radius = 4;
+ const wallHeight = 4;
+ const root = semantic(new THREE.Group(), 'architecture.shell.rotunda');
+ root.name = radiusScale === 1 ? 'RotundaDomeControl' : 'UndersizedRotundaDome';
+ part(
+ root,
+ 'RotundaDrum',
+ new THREE.CylinderGeometry(radius, radius, wallHeight, 24, 1, true),
+ new THREE.MeshStandardMaterial({ color: 0xb9a17d, side: THREE.DoubleSide }),
+ 'wall.rotunda',
+ [0, wallHeight / 2, 0],
+ );
+ const dome = part(
+ root,
+ 'Dome',
+ new THREE.SphereGeometry(radius, 24, 12, 0, Math.PI * 2, 0, Math.PI / 2),
+ new THREE.MeshStandardMaterial({ color: 0x8d8a82 }),
+ 'roof.dome',
+ [0, wallHeight, 0],
+ );
+ dome.scale.set(radiusScale, 1, radiusScale);
+ root.updateMatrixWorld(true);
+ return {
+ intent: createAssetIntentV1({
+ category: 'architecture',
+ subtype: 'rotunda',
+ architecture: {
+ storeyCount: 1,
+ interiorMode: 'none',
+ roofMode: 'fixed',
+ footprint: { spanX: radius * 2, spanZ: radius * 2 },
+ wallHeight,
+ roof: {
+ type: 'dome',
+ rise: radius,
+ pitchDegrees: 0,
+ overhang: 0,
+ closedEnds: false,
+ },
+ },
+ }),
+ scene: root,
+ };
+}
+
+function reciprocal(
+ failureId: string,
+ controlId: string,
+ description: string,
+ code: string,
+ failureBuild: () => ArchitectureCorpusPayload,
+ controlBuild: () => ArchitectureCorpusPayload,
+): readonly [ArchitectureCorpusDescriptor, ArchitectureCorpusDescriptor] {
+ return [
+ {
+ id: failureId,
+ kind: 'failure',
+ pairId: controlId,
+ description,
+ expectedPrimaryCode: code,
+ forbiddenCodes: [],
+ build: failureBuild,
+ },
+ {
+ id: controlId,
+ kind: 'control',
+ pairId: failureId,
+ description: `Known-good reciprocal control for ${description}`,
+ forbiddenCodes: CANONICAL_ARCHITECTURE_CODES,
+ build: controlBuild,
+ },
+ ];
+}
+
const failure = (
id: string,
pairId: string,
@@ -541,6 +719,38 @@ export const ARCHITECTURE_REGRESSION_CORPUS = Object.freeze([
'sealed-enterable-box',
'Equivalent architecture has a real exterior-to-interior clearance prism.',
),
+ ...reciprocal(
+ 'storey-count-mismatch',
+ 'storey-count-control',
+ 'A two-storey request exposes only one portable floor.storey role.',
+ 'ARCH_STOREY_COUNT',
+ () => buildStoreyControl(1),
+ () => buildStoreyControl(2),
+ ),
+ ...reciprocal(
+ 'interior-shell-missing',
+ 'interior-shell-control',
+ 'interiorMode=shell has no portable semantic interior shell volume.',
+ 'ARCH_INTERIOR_MODE',
+ () => buildInteriorShellControl(false),
+ () => buildInteriorShellControl(true),
+ ),
+ ...reciprocal(
+ 'removable-roof-fixed',
+ 'removable-roof-control',
+ 'A removable roof request exposes a roof assembly without separable-from semantics.',
+ 'ARCH_ROOF_MODE',
+ () => buildRemovableRoofControl(false),
+ () => buildRemovableRoofControl(true),
+ ),
+ ...reciprocal(
+ 'undersized-rotunda-dome',
+ 'rotunda-dome-control',
+ 'A declared rotunda dome covers only half of its requested circular footprint.',
+ 'ARCH_DOME_PROFILE',
+ () => buildRotundaControl(0.5),
+ () => buildRotundaControl(1),
+ ),
{
id: 'valid-large-overhang',
kind: 'false-positive',
diff --git a/src/qa/architecture.test.ts b/src/qa/architecture.test.ts
index c3007f06..a8d6f649 100644
--- a/src/qa/architecture.test.ts
+++ b/src/qa/architecture.test.ts
@@ -28,6 +28,10 @@ const canonicalCodes = new Set([
'ARCH_RIDGE_GAP',
'ARCH_ENVELOPE_GAP',
'ARCH_BLOCKED_PORTAL',
+ 'ARCH_STOREY_COUNT',
+ 'ARCH_INTERIOR_MODE',
+ 'ARCH_ROOF_MODE',
+ 'ARCH_DOME_PROFILE',
]);
function canonicalHelperShell(ridgeAxis: 'x' | 'z' = 'x') {
@@ -99,6 +103,22 @@ describe('ARCH-019 executable reciprocal architecture corpus', () => {
});
}
+ test('freezes lifecycle and rotunda adversaries with reciprocal controls', () => {
+ const ids = ARCHITECTURE_REGRESSION_CORPUS.map((fixture) => fixture.id);
+ expect(ids).toEqual(
+ expect.arrayContaining([
+ 'storey-count-mismatch',
+ 'storey-count-control',
+ 'interior-shell-missing',
+ 'interior-shell-control',
+ 'removable-roof-fixed',
+ 'removable-roof-control',
+ 'undersized-rotunda-dome',
+ 'rotunda-dome-control',
+ ]),
+ );
+ });
+
test('covers every observed architecture failure with a reciprocal control', () => {
const byId = new Map(ARCHITECTURE_REGRESSION_CORPUS.map((fixture) => [fixture.id, fixture]));
for (const fixture of ARCHITECTURE_REGRESSION_CORPUS) {
@@ -265,6 +285,146 @@ describe('ARCH-010–016 validator policy', () => {
expect(findings.every((finding) => finding.disposition !== 'block')).toBe(true);
});
+ test('enforces requested multi-storey count from portable floor.storey roles', () => {
+ const scene = new THREE.Group();
+ scene.name = 'TwoStoreyFixture';
+ const material = new THREE.MeshStandardMaterial();
+ for (const [index, y] of [
+ [1, 0],
+ [2, 3],
+ ] as const) {
+ const floor = stampSemanticMetadataV1(
+ new THREE.Mesh(new THREE.BoxGeometry(5, 0.12, 4), material),
+ { roles: [`floor.storey.${index}`] },
+ );
+ floor.name = `Floor_${index}`;
+ floor.position.y = y;
+ scene.add(floor);
+ }
+ const intent = createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ storeyCount: 2,
+ interiorMode: 'none',
+ roofMode: 'none',
+ roof: { type: 'none' },
+ },
+ });
+ expect(evaluateArchitectureQa({ intent, scene }).map((finding) => finding.code)).not.toContain(
+ 'ARCH_STOREY_COUNT',
+ );
+ scene.remove(scene.getObjectByName('Floor_2')!);
+ const finding = evaluateArchitectureQa({ intent, scene }).find(
+ (candidate) => candidate.code === 'ARCH_STOREY_COUNT',
+ );
+ expect(finding).toMatchObject({
+ disposition: 'block',
+ measurement: { actual: 1, expected: 2, threshold: 2 },
+ });
+ });
+
+ test('requires measurable shell evidence exactly when interiorMode is shell', () => {
+ const scene = new THREE.Group();
+ scene.name = 'InteriorShellFixture';
+ const intent = createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ interiorMode: 'shell',
+ roofMode: 'none',
+ roof: { type: 'none' },
+ },
+ });
+ expect(evaluateArchitectureQa({ intent, scene }).map((finding) => finding.code)).toContain(
+ 'ARCH_INTERIOR_MODE',
+ );
+ const shell = stampSemanticMetadataV1(new THREE.Group(), {
+ roles: ['architecture.interior.shell'],
+ });
+ shell.name = 'InteriorShell';
+ scene.add(shell);
+ expect(evaluateArchitectureQa({ intent, scene }).map((finding) => finding.code)).not.toContain(
+ 'ARCH_INTERIOR_MODE',
+ );
+ });
+
+ test('requires removable roofs to own a portable separable-from relationship', () => {
+ const scene = new THREE.Group();
+ scene.name = 'RemovableRoofFixture';
+ const roof = stampSemanticMetadataV1(
+ new THREE.Mesh(new THREE.BoxGeometry(5, 0.15, 4), new THREE.MeshStandardMaterial()),
+ {
+ roles: ['roof.assembly'],
+ relationships: [
+ { kind: 'separable-from', target: 'architecture.shell', targetType: 'role' },
+ ],
+ },
+ );
+ roof.name = 'Roof';
+ roof.position.y = 3;
+ scene.add(roof);
+ const intent = createAssetIntentV1({
+ category: 'architecture',
+ architecture: {
+ interiorMode: 'none',
+ roofMode: 'removable',
+ roof: { type: 'flat' },
+ },
+ });
+ expect(evaluateArchitectureQa({ intent, scene }).map((finding) => finding.code)).not.toContain(
+ 'ARCH_ROOF_MODE',
+ );
+ stampSemanticMetadataV1(roof, { roles: ['roof.assembly'] });
+ const finding = evaluateArchitectureQa({ intent, scene }).find(
+ (candidate) => candidate.code === 'ARCH_ROOF_MODE',
+ );
+ expect(finding?.measurement).toMatchObject({
+ name: 'removableRoofRelationshipCount',
+ actual: 0,
+ threshold: 1,
+ });
+ });
+
+ test('supports a Pantheon-like rotunda dome and rejects undersized dome coverage', () => {
+ const scene = stampSemanticMetadataV1(new THREE.Group(), {
+ roles: ['architecture.shell.rotunda'],
+ });
+ scene.name = 'RotundaFixture';
+ const dome = stampSemanticMetadataV1(
+ new THREE.Mesh(
+ new THREE.SphereGeometry(4, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2),
+ new THREE.MeshStandardMaterial(),
+ ),
+ { roles: ['roof.dome'] },
+ );
+ dome.name = 'Dome';
+ dome.position.y = 4;
+ scene.add(dome);
+ const intent = createAssetIntentV1({
+ category: 'architecture',
+ subtype: 'rotunda',
+ architecture: {
+ interiorMode: 'none',
+ roofMode: 'fixed',
+ footprint: { spanX: 8, spanZ: 8 },
+ wallHeight: 4,
+ roof: { type: 'dome', rise: 4, pitchDegrees: 0, overhang: 0, closedEnds: false },
+ },
+ });
+ expect(evaluateArchitectureQa({ intent, scene }).map((finding) => finding.code)).not.toContain(
+ 'ARCH_DOME_PROFILE',
+ );
+ dome.scale.set(0.5, 1, 0.5);
+ scene.updateMatrixWorld(true);
+ const finding = evaluateArchitectureQa({ intent, scene }).find(
+ (candidate) => candidate.code === 'ARCH_DOME_PROFILE',
+ );
+ expect(finding?.measurement).toMatchObject({
+ name: 'minimumDomeCoverageRatio',
+ actual: 0.5,
+ threshold: 0.9,
+ });
+ });
+
test('explicit stylized scale suppresses every realistic scale-band warning', () => {
const payload = buildArchitectureCorpusFixture({ stylized: true });
const findings = evaluateArchitectureQa({ intent: payload.intent, scene: payload.scene });
diff --git a/src/qa/architecture.ts b/src/qa/architecture.ts
index 0d31dc8f..a32462de 100644
--- a/src/qa/architecture.ts
+++ b/src/qa/architecture.ts
@@ -1,6 +1,10 @@
import * as THREE from 'three';
-import { readSemanticMetadataV1FromExtras, type ArchitectureIntentV1 } from '../contracts';
+import {
+ readSemanticMetadataV1FromExtras,
+ type ArchitectureIntentV1,
+ type SemanticRelationshipV1,
+} from '../contracts';
import { withArchitectureRepair } from './architecture-repairs';
import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';
import type { QaContext, QaFinding } from './types';
@@ -24,6 +28,7 @@ interface ArchitecturePart {
nodeName: string;
nodePath: string;
directRoles: readonly string[];
+ directRelationships: readonly SemanticRelationshipV1[];
roles: readonly string[];
isMesh: boolean;
bounds: Bounds3;
@@ -74,8 +79,8 @@ const boundsFinite = (bounds: Bounds3): boolean => Number.isFinite(bounds.min.x)
const extent = (bounds: Bounds3, axis: Axis): number => bounds.max[axis] - bounds.min[axis];
-function semanticRoles(node: THREE.Object3D): readonly string[] {
- return readSemanticMetadataV1FromExtras(node.userData)?.roles ?? [];
+function semanticMetadata(node: THREE.Object3D) {
+ return readSemanticMetadataV1FromExtras(node.userData);
}
function markerBounds(matrix: THREE.Matrix4): Bounds3 {
@@ -178,7 +183,9 @@ function collectArchitectureEvidence(scene: unknown): ArchitectureSceneEvidence
siblingIndex: number,
inheritedRoles: readonly string[],
): void => {
- const directRoles = semanticRoles(node);
+ const metadata = semanticMetadata(node);
+ const directRoles = metadata?.roles ?? [];
+ const directRelationships = metadata?.relationships ?? [];
directRoles.forEach((role) => {
allRoles.add(role);
});
@@ -202,6 +209,7 @@ function collectArchitectureEvidence(scene: unknown): ArchitectureSceneEvidence
nodeName: node.name || node.type,
nodePath,
directRoles,
+ directRelationships,
roles,
isMesh,
...evidence,
@@ -950,6 +958,175 @@ function portalFindings(
];
}
+function storeyFindings(
+ context: QaContext,
+ architecture: ArchitectureIntentV1,
+ evidence: ArchitectureSceneEvidence,
+): QaFinding[] {
+ const requested = architecture.storeyCount ?? 1;
+ const indexes = new Set<number>();
+ for (const role of evidence.semanticRoles) {
+ const match = /^(?:architecture\.)?floor\.storey\.(\d+)$/.exec(role);
+ if (match) indexes.add(Number(match[1]));
+ }
+ // A single legacy floor remains a valid one-storey control. Exact counting is
+ // required once a multi-storey request is made or indexed floor evidence is claimed.
+ if (requested === 1 && indexes.size === 0) return [];
+ const actual = indexes.size;
+ if (actual === requested) return [];
+ return [
+ architectureFinding(context, {
+ code: 'ARCH_STOREY_COUNT',
+ disposition: 'block',
+ message: `Requested ${requested} storeys but found ${actual} distinct portable floor.storey.<index> roles.`,
+ affected: { node: evidence.root.name || 'architecture-root' },
+ measurement: {
+ name: 'semanticStoreyCount',
+ actual,
+ expected: requested,
+ threshold: requested,
+ },
+ viewHints: ['architecture.cutaway.dollhouse', 'generic.top.semantic-overlay'],
+ repairText:
+ 'Add or remove only the requested floor levels, stamp each level once as floor.storey.<1-5>, and keep stairs and clearances aligned between consecutive levels.',
+ }),
+ ];
+}
+
+function interiorModeFindings(
+ context: QaContext,
+ architecture: ArchitectureIntentV1,
+ evidence: ArchitectureSceneEvidence,
+): QaFinding[] {
+ const mode = architecture.interiorMode ?? (architecture.enterable ? 'navigable' : 'none');
+ const interiorEvidence = evidence.parts.filter((part) =>
+ part.roles.some(
+ (role) => role === 'architecture.interior.shell' || role.startsWith('interior.'),
+ ),
+ );
+ const valid =
+ mode === 'shell'
+ ? interiorEvidence.length > 0
+ : mode !== 'none' || interiorEvidence.length === 0;
+ if (valid) return [];
+ return [
+ architectureFinding(context, {
+ code: 'ARCH_INTERIOR_MODE',
+ disposition: 'block',
+ message:
+ mode === 'shell'
+ ? 'interiorMode=shell requires a portable architecture.interior.shell semantic volume.'
+ : 'interiorMode=none conflicts with semantic interior geometry.',
+ affected: {
+ node: interiorEvidence[0]?.nodeName ?? evidence.root.name ?? 'architecture-root',
+ nodePath: interiorEvidence[0]?.nodePath,
+ },
+ measurement: {
+ name: 'semanticInteriorShellCount',
+ actual: interiorEvidence.length,
+ expected: mode === 'shell' ? '>= 1' : 0,
+ threshold: mode === 'shell' ? 1 : 0,
+ },
+ viewHints: ['architecture.cutaway.dollhouse', 'architecture.floor-plan'],
+ repairText:
+ mode === 'shell'
+ ? 'Add one non-rendering architecture.interior.shell volume matching the usable inner envelope; do not fake the interior with a painted exterior face.'
+ : 'Remove the unrequested interior semantic volume or change trusted intent to shell/navigable before generation.',
+ }),
+ ];
+}
+
+function roofModeFindings(
+ context: QaContext,
+ architecture: ArchitectureIntentV1,
+ evidence: ArchitectureSceneEvidence,
+): QaFinding[] {
+ const mode = architecture.roofMode ?? (architecture.roof.type === 'none' ? 'none' : 'auto');
+ if (mode === 'auto') return [];
+ const roofParts = evidence.parts.filter((part) => hasRolePrefix(part, 'roof.'));
+ const removableRelationships = roofParts.flatMap((part) =>
+ part.directRelationships.filter((relationship) => relationship.kind === 'separable-from'),
+ );
+ const present = roofParts.length > 0;
+ const valid =
+ mode === 'none'
+ ? !present
+ : mode === 'fixed'
+ ? present && removableRelationships.length === 0
+ : present && removableRelationships.length > 0;
+ if (valid) return [];
+ const measurement =
+ mode === 'removable'
+ ? {
+ name: 'removableRoofRelationshipCount',
+ actual: removableRelationships.length,
+ expected: '>= 1',
+ threshold: 1,
+ }
+ : {
+ name: 'semanticRoofPartCount',
+ actual: roofParts.length,
+ expected: mode === 'none' ? 0 : '>= 1',
+ threshold: mode === 'none' ? 0 : 1,
+ };
+ return [
+ architectureFinding(context, {
+ code: 'ARCH_ROOF_MODE',
+ disposition: 'block',
+ message: `roofMode=${mode} conflicts with ${roofParts.length} semantic roof parts and ${removableRelationships.length} separable-from relationships.`,
+ affected: {
+ node: roofParts[0]?.nodeName ?? evidence.root.name ?? 'architecture-root',
+ nodePath: roofParts[0]?.nodePath,
+ },
+ measurement,
+ viewHints: ['generic.top.semantic-overlay', 'architecture.cutaway.dollhouse'],
+ repairText:
+ 'Match trusted roofMode exactly: omit all roof.* roles for none, keep fixed roofs attached, or stamp one roof assembly with a separable-from relationship for removable.',
+ }),
+ ];
+}
+
+function domeFindings(
+ context: QaContext,
+ architecture: ArchitectureIntentV1,
+ evidence: ArchitectureSceneEvidence,
+): QaFinding[] {
+ const requested =
+ architecture.roof.type === 'dome' ||
+ /(?:^|[. _-])rotunda(?:$|[. _-])/i.test(architecture.subtype);
+ if (!requested) return [];
+ const dome = aggregate(
+ evidence.parts.filter(
+ (part) => part.isMesh && (hasRole(part, 'roof.dome') || hasRole(part, 'roof.surface.dome')),
+ ),
+ );
+ const spanXCoverage = dome ? extent(dome.bounds, 'x') / architecture.footprint.spanX : 0;
+ const spanZCoverage = dome ? extent(dome.bounds, 'z') / architecture.footprint.spanZ : 0;
+ const riseCoverage = dome ? extent(dome.bounds, 'y') / architecture.roof.rise : 0;
+ const minimumCoverage = Math.min(spanXCoverage, spanZCoverage, riseCoverage);
+ if (minimumCoverage >= 0.9) return [];
+ return [
+ architectureFinding(context, {
+ code: 'ARCH_DOME_PROFILE',
+ disposition: 'block',
+ message: `The semantic rotunda dome covers ${(spanXCoverage * 100).toFixed(1)}% X, ${(spanZCoverage * 100).toFixed(1)}% Z, and ${(riseCoverage * 100).toFixed(1)}% of declared rise.`,
+ affected: {
+ node: dome?.parts[0]?.nodeName ?? evidence.root.name ?? 'architecture-root',
+ nodePath: dome?.parts[0]?.nodePath,
+ },
+ measurement: {
+ name: 'minimumDomeCoverageRatio',
+ actual: minimumCoverage,
+ expected: '>= 0.9',
+ threshold: 0.9,
+ },
+ viewHints: ['generic.top.semantic-overlay', 'architecture.cutaway.dollhouse'],
+ repairText:
+ 'Rebuild the roof.dome hemisphere to cover the declared circular rotunda footprint and rise; preserve any intentional oculus as a bounded opening rather than shrinking the whole dome.',
+ }),
+ ];
+}
+
interface ScaleBand {
code: string;
label: string;
@@ -1099,6 +1276,10 @@ export function evaluateArchitectureQa(context: QaContext): readonly QaFinding[]
const evidence = collectArchitectureEvidence(context.scene);
if (!evidence) return [];
return [
+ ...storeyFindings(context, architecture, evidence),
+ ...interiorModeFindings(context, architecture, evidence),
+ ...roofModeFindings(context, architecture, evidence),
+ ...domeFindings(context, architecture, evidence),
...roofFindings(context, architecture, evidence),
...endFindings(context, architecture, evidence),
...envelopeFindings(context, architecture, evidence),
@@ -1116,7 +1297,7 @@ export const ARCHITECTURE_QA_RULE: QaRule = {
promotion: conformancePromotionAuthorization(
'architecture-qa-v1',
'src/qa/architecture.test.ts',
- 'd83b6f3696455bb8c14bb4d36fa61e9470314af75959cb20b6da8da76c83e3da',
+ 'e5ad1245240f1244c592849df2977c74d26e535dffebc9ad5a2adf6db743d573',
),
defaultMode: 'enforce',
evaluate: (context) =>
diff --git a/src/qa/benchmark-fixtures.test.ts b/src/qa/benchmark-fixtures.test.ts
new file mode 100644
index 00000000..8a5e298a
--- /dev/null
+++ b/src/qa/benchmark-fixtures.test.ts
@@ -0,0 +1,138 @@
+import { createHash } from 'node:crypto';
+
+import { describe, expect, test } from 'bun:test';
+
+import { validateAssetIntentV1 } from '../contracts';
+import * as qaExports from './index';
+import {
+ ASSET_BENCHMARK_FIXTURES_CANONICAL_SHA256,
+ ASSET_BENCHMARK_FIXTURES_V1,
+ PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1,
+ RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1,
+ STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1,
+ WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1,
+} from './benchmark-fixtures';
+
+function expectDeepFrozen(value: unknown, path = 'root', seen = new Set<object>()): void {
+ if (typeof value !== 'object' || value === null || seen.has(value)) return;
+ seen.add(value);
+ expect(Object.isFrozen(value), path).toBe(true);
+ for (const [key, child] of Object.entries(value)) {
+ expectDeepFrozen(child, `${path}.${key}`, seen);
+ }
+}
+
+describe('next-cycle deterministic benchmark fixtures', () => {
+ test('exports the exact four model-independent fixture identities', () => {
+ expect(ASSET_BENCHMARK_FIXTURES_V1.map((fixture) => fixture.id)).toEqual([
+ 'retro-futurist-rally-coupe',
+ 'windswept-japanese-maple',
+ 'static-ornate-energy-crossbow',
+ 'pantheon-inspired-rotunda',
+ ]);
+ expect(ASSET_BENCHMARK_FIXTURES_V1).toEqual([
+ RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1,
+ WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1,
+ STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1,
+ PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1,
+ ]);
+ expect(qaExports.ASSET_BENCHMARK_FIXTURES_V1).toBe(ASSET_BENCHMARK_FIXTURES_V1);
+ });
+
+ test('freezes prompts, canonical intent/config, expected semantics, and adversaries deeply', () => {
+ expectDeepFrozen(ASSET_BENCHMARK_FIXTURES_V1, 'fixtures');
+ for (const fixture of ASSET_BENCHMARK_FIXTURES_V1) {
+ expect(validateAssetIntentV1(fixture.intent), fixture.id).toMatchObject({
+ valid: true,
+ issues: [],
+ });
+ expect(fixture.prompt.trim().length, fixture.id).toBeGreaterThan(80);
+ expect(fixture.config).toEqual({
+ schemaVersion: 1,
+ mode: 'glb',
+ style: 'detailed',
+ includeAnimation: false,
+ captureViews: true,
+ toolSurface: 'unified',
+ });
+ expect(fixture.expectedSemantics.length, fixture.id).toBeGreaterThanOrEqual(4);
+ expect(fixture.adversaries.length, fixture.id).toBeGreaterThanOrEqual(3);
+ }
+ expect(JSON.stringify(ASSET_BENCHMARK_FIXTURES_V1)).not.toMatch(
+ /modelId|providerId|judgeModel|juryModel|modelRoster|juryRoster/,
+ );
+ });
+
+ test('pins exact category intent and benchmark semantics without trademark or animation drift', () => {
+ expect(RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1.intent).toMatchObject({
+ category: 'vehicle',
+ subtype: 'wheeled',
+ vehicle: {
+ subtype: 'wheeled',
+ wheelCount: 4,
+ axleCount: 2,
+ steering: 'front',
+ supportPolicy: 'grounded',
+ },
+ });
+ expect(
+ RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1.intent.capabilities.includes('driveable'),
+ ).toBe(true);
+ expect(
+ RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1.intent.capabilities.includes('grounded'),
+ ).toBe(true);
+ expect(RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1.prompt).toContain(
+ 'no manufacturer badges',
+ );
+
+ expect(WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1.intent).toMatchObject({
+ category: 'vegetation',
+ subtype: 'tree',
+ vegetation: {
+ subtype: 'tree',
+ growthState: 'lush',
+ canopyProfile: 'broadleaf',
+ standalone: true,
+ grounded: true,
+ },
+ });
+ expect(WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1.intent.forbiddenExtras).toEqual([
+ 'soil disk',
+ 'planter',
+ 'display base',
+ 'unrelated rocks',
+ 'floating leaves',
+ ]);
+
+ expect(STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1.intent).toMatchObject({
+ category: 'prop',
+ subtype: 'energy-crossbow',
+ capabilities: [],
+ forbiddenExtras: ['display pedestal'],
+ });
+ expect('animation' in STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1.intent).toBe(false);
+ expect(STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1.config.includeAnimation).toBe(false);
+
+ expect(PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1.intent).toMatchObject({
+ category: 'architecture',
+ subtype: 'rotunda',
+ architecture: {
+ subtype: 'rotunda',
+ storeyCount: 1,
+ interiorMode: 'navigable',
+ roofMode: 'fixed',
+ roof: { type: 'dome', pitchDegrees: 0, closedEnds: false },
+ },
+ });
+ expect(PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1.prompt).toContain('Pantheon-inspired');
+ expect(PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1.prompt).not.toContain('faithful replica');
+ });
+
+ test('pins the canonical JSON digest and reproduces it byte-for-byte', () => {
+ const json = JSON.stringify(ASSET_BENCHMARK_FIXTURES_V1);
+ expect(JSON.stringify(ASSET_BENCHMARK_FIXTURES_V1)).toBe(json);
+ expect(createHash('sha256').update(json).digest('hex')).toBe(
+ ASSET_BENCHMARK_FIXTURES_CANONICAL_SHA256,
+ );
+ });
+});
diff --git a/src/qa/benchmark-fixtures.ts b/src/qa/benchmark-fixtures.ts
new file mode 100644
index 00000000..a60b5986
--- /dev/null
+++ b/src/qa/benchmark-fixtures.ts
@@ -0,0 +1,441 @@
+import { createAssetIntentV1, type AssetCategory, type AssetIntentV1 } from '../contracts';
+
+export const ASSET_BENCHMARK_FIXTURE_SCHEMA_VERSION = 1 as const;
+export const ASSET_BENCHMARK_FIXTURE_SET_VERSION = 'kiln.asset-benchmark-fixtures.v1' as const;
+
+export interface AssetBenchmarkExecutionConfigV1 {
+ schemaVersion: 1;
+ mode: 'glb';
+ style: 'detailed';
+ includeAnimation: false;
+ captureViews: true;
+ toolSurface: 'unified';
+}
+
+export type AssetBenchmarkSemanticEvidence = 'deterministic' | 'visual' | 'deterministic+visual';
+
+export interface AssetBenchmarkExpectedSemanticV1 {
+ id: string;
+ description: string;
+ evidence: AssetBenchmarkSemanticEvidence;
+ requiredRoles: readonly string[];
+ viewIds: readonly string[];
+}
+
+export interface AssetBenchmarkAdversaryV1 {
+ id: string;
+ description: string;
+ violatedSemantics: readonly string[];
+}
+
+export interface AssetBenchmarkFixtureV1 {
+ schemaVersion: 1;
+ setVersion: typeof ASSET_BENCHMARK_FIXTURE_SET_VERSION;
+ id: string;
+ category: AssetCategory;
+ prompt: string;
+ intent: AssetIntentV1;
+ config: AssetBenchmarkExecutionConfigV1;
+ expectedSemantics: readonly AssetBenchmarkExpectedSemanticV1[];
+ adversaries: readonly AssetBenchmarkAdversaryV1[];
+}
+
+function deepFreeze<T>(value: T, seen = new Set<object>()): T {
+ if (typeof value !== 'object' || value === null || seen.has(value)) return value;
+ seen.add(value);
+ for (const child of Object.values(value)) deepFreeze(child, seen);
+ return Object.freeze(value);
+}
+
+const STATIC_DETAILED_CONFIG: AssetBenchmarkExecutionConfigV1 = deepFreeze({
+ schemaVersion: 1,
+ mode: 'glb',
+ style: 'detailed',
+ includeAnimation: false,
+ captureViews: true,
+ toolSurface: 'unified',
+});
+
+const semantic = (
+ id: string,
+ description: string,
+ evidence: AssetBenchmarkSemanticEvidence,
+ requiredRoles: readonly string[],
+ viewIds: readonly string[],
+): AssetBenchmarkExpectedSemanticV1 =>
+ deepFreeze({
+ id,
+ description,
+ evidence,
+ requiredRoles: [...requiredRoles],
+ viewIds: [...viewIds],
+ });
+
+const adversary = (
+ id: string,
+ description: string,
+ violatedSemantics: readonly string[],
+): AssetBenchmarkAdversaryV1 =>
+ deepFreeze({ id, description, violatedSemantics: [...violatedSemantics] });
+
+function fixture(
+ value: Omit<AssetBenchmarkFixtureV1, 'schemaVersion' | 'setVersion' | 'config'>,
+): AssetBenchmarkFixtureV1 {
+ return deepFreeze({
+ schemaVersion: ASSET_BENCHMARK_FIXTURE_SCHEMA_VERSION,
+ setVersion: ASSET_BENCHMARK_FIXTURE_SET_VERSION,
+ ...value,
+ config: STATIC_DETAILED_CONFIG,
+ });
+}
+
+export const RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1 = fixture({
+ id: 'retro-futurist-rally-coupe',
+ category: 'vehicle',
+ prompt:
+ 'A generic retro-futurist rally coupe facing +X, with a compact readable cabin, four load-bearing wheels under pronounced arches, two aligned axles, front steering, generous suspension travel, and a planted rally stance. Use original bodywork with no manufacturer badges or copied production-car identity.',
+ intent: createAssetIntentV1({
+ category: 'vehicle',
+ subtype: 'wheeled',
+ capabilities: ['driveable'],
+ requiredParts: [
+ 'cabin',
+ 'wheel.front.left',
+ 'wheel.front.right',
+ 'wheel.rear.left',
+ 'wheel.rear.right',
+ 'wheel arches',
+ ],
+ forbiddenExtras: ['manufacturer badge', 'trademarked bodywork'],
+ material: { mode: 'pbrRecipe' },
+ vehicle: {
+ subtype: 'wheeled',
+ supportAssemblies: ['wheel'],
+ propulsionAssemblies: ['wheel'],
+ wheelCount: 4,
+ axleCount: 2,
+ steering: 'front',
+ supportPolicy: 'grounded',
+ animationAssemblies: [],
+ },
+ }),
+ expectedSemantics: [
+ semantic(
+ 'vehicle-forward-orientation',
+ 'The coupe has one unambiguous nose and longitudinal body axis facing trusted +X.',
+ 'deterministic+visual',
+ ['vehicle.frame', 'vehicle.chassis'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'vehicle-cabin-readability',
+ 'The cabin reads as an attached occupied volume rather than decorative roof clutter.',
+ 'visual',
+ ['vehicle.cabin'],
+ ['front', 'three-quarter', 'right'],
+ ),
+ semantic(
+ 'vehicle-four-wheel-support',
+ 'Exactly four load-bearing wheel assemblies occupy unique front/rear and left/right corners.',
+ 'deterministic',
+ ['wheel.front.left', 'wheel.front.right', 'wheel.rear.left', 'wheel.rear.right'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'vehicle-rally-stance',
+ 'Wheel arches clear the tires and the chassis presents a planted wide-track rally stance.',
+ 'deterministic+visual',
+ ['vehicle.chassis', 'vehicle.fender.front.left', 'vehicle.fender.front.right'],
+ ['front', 'three-quarter'],
+ ),
+ semantic(
+ 'vehicle-front-steering',
+ 'Only the front axle owns steering pivots and every wheel spins around vehicle-local +Z.',
+ 'deterministic',
+ ['steering.pivot.front.left', 'steering.pivot.front.right'],
+ ['top', 'front'],
+ ),
+ ],
+ adversaries: [
+ adversary(
+ 'coupe-floating-decorative-wheels',
+ 'Four wheel-shaped decorations are present, but one or more do not carry support semantics or touch the ground plane.',
+ ['vehicle-four-wheel-support', 'vehicle-rally-stance'],
+ ),
+ adversary(
+ 'coupe-bad-axles',
+ 'Wheel centers do not form two coherent front/rear axle pairs or their spin axes are not local +Z.',
+ ['vehicle-four-wheel-support', 'vehicle-front-steering'],
+ ),
+ adversary(
+ 'coupe-rear-only-steering',
+ 'Steering pivots are attached to the rear axle while trusted intent requires front steering.',
+ ['vehicle-front-steering'],
+ ),
+ ],
+});
+
+export const WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1 = fixture({
+ id: 'windswept-japanese-maple',
+ category: 'vegetation',
+ prompt:
+ 'A standalone lush Japanese maple rooted at Y=0, shaped by persistent wind into a strongly asymmetric but balanced silhouette. Build a tapered trunk, a readable primary-to-secondary branching hierarchy, and several attached broadleaf foliage clusters; include no soil disk, planter, display base, unrelated rocks, or floating leaves.',
+ intent: createAssetIntentV1({
+ category: 'vegetation',
+ subtype: 'tree',
+ requiredParts: [
+ 'tapered trunk',
+ 'primary branches',
+ 'secondary branches',
+ 'attached foliage clusters',
+ ],
+ forbiddenExtras: ['soil disk', 'planter', 'display base', 'unrelated rocks', 'floating leaves'],
+ material: { mode: 'pbrRecipe' },
+ vegetation: {
+ subtype: 'tree',
+ growthState: 'lush',
+ canopyProfile: 'broadleaf',
+ standalone: true,
+ grounded: true,
+ },
+ }),
+ expectedSemantics: [
+ semantic(
+ 'maple-grounded-tapered-trunk',
+ 'One tapered trunk owns the single standalone ground contact and narrows toward its crown.',
+ 'deterministic+visual',
+ ['vegetation.contact.ground', 'vegetation.trunk'],
+ ['front', 'right'],
+ ),
+ semantic(
+ 'maple-branch-hierarchy',
+ 'Primary branches attach to the trunk and secondary branches attach to a primary branch.',
+ 'deterministic',
+ ['vegetation.branch.primary', 'vegetation.branch.secondary'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'maple-windswept-canopy',
+ 'The canopy is intentionally asymmetric and directionally windswept without becoming disconnected.',
+ 'visual',
+ ['vegetation.canopy'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'maple-attached-foliage',
+ 'Every foliage cluster is attached to the declared branch graph and none floats independently.',
+ 'deterministic+visual',
+ ['vegetation.foliage', 'vegetation.canopy.cluster'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'maple-standalone-scope',
+ 'The asset contains the tree only, with no fake grounding base or unrelated scene dressing.',
+ 'deterministic',
+ ['vegetation.contact.ground'],
+ ['front', 'top'],
+ ),
+ ],
+ adversaries: [
+ adversary(
+ 'maple-sparse-canopy',
+ 'A lush-tree request contains too few or too-small foliage clusters to occupy its branch envelope.',
+ ['maple-windswept-canopy', 'maple-attached-foliage'],
+ ),
+ adversary(
+ 'maple-repetitive-canopy',
+ 'Identical foliage blobs repeat on a radial grid and erase the requested windswept asymmetry.',
+ ['maple-windswept-canopy'],
+ ),
+ adversary(
+ 'maple-disconnected-foliage',
+ 'One or more canopy clusters have no contact or semantic relationship to the branch graph.',
+ ['maple-attached-foliage'],
+ ),
+ adversary(
+ 'maple-fake-grounding-base',
+ 'A soil disk, planter, display plinth, or unrelated rock is added to fake ground contact.',
+ ['maple-standalone-scope', 'maple-grounded-tapered-trunk'],
+ ),
+ ],
+});
+
+export const STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1 = fixture({
+ id: 'static-ornate-energy-crossbow',
+ category: 'prop',
+ prompt:
+ 'A static ornate energy crossbow pointing along +X, with an attached stock and grip, mirrored bow limbs, a centered rail, and one taut luminous string or energy arc connecting both limb tips. Keep every assembly connected and readable, and add no display pedestal or implied firing animation.',
+ intent: createAssetIntentV1({
+ category: 'prop',
+ subtype: 'energy-crossbow',
+ requiredParts: ['stock', 'grip', 'limb.left', 'limb.right', 'energy string', 'rail'],
+ forbiddenExtras: ['display pedestal'],
+ material: { mode: 'pbrRecipe' },
+ }),
+ expectedSemantics: [
+ semantic(
+ 'crossbow-forward-orientation',
+ 'The rail and firing direction point along trusted +X with the grip below and bow width along Z.',
+ 'deterministic+visual',
+ ['prop.forward', 'weapon.rail'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'crossbow-stock-grip-attachment',
+ 'Stock, grip, and rail form one connected central assembly.',
+ 'deterministic+visual',
+ ['weapon.stock', 'weapon.grip', 'weapon.rail'],
+ ['front', 'right'],
+ ),
+ semantic(
+ 'crossbow-limb-symmetry',
+ 'Left and right bow limbs are mirrored around the center rail and remain attached at the prod.',
+ 'deterministic+visual',
+ ['weapon.limb.left', 'weapon.limb.right'],
+ ['front', 'top'],
+ ),
+ semantic(
+ 'crossbow-energy-string-attachment',
+ 'One string or energy arc spans both limb tips and is centered on the rail.',
+ 'deterministic+visual',
+ ['weapon.string.energy'],
+ ['front', 'top'],
+ ),
+ semantic(
+ 'crossbow-static-contract',
+ 'The initial fixture contains no clips, animated pivots, or implied firing motion.',
+ 'deterministic',
+ [],
+ ['front'],
+ ),
+ ],
+ adversaries: [
+ adversary(
+ 'crossbow-asymmetric-limbs',
+ 'One bow limb differs materially in length, attachment, or tip placement from its reciprocal limb.',
+ ['crossbow-limb-symmetry'],
+ ),
+ adversary(
+ 'crossbow-detached-energy-string',
+ 'The luminous string or energy arc floats near the bow without terminating at both limb tips.',
+ ['crossbow-energy-string-attachment'],
+ ),
+ adversary(
+ 'crossbow-detached-central-assembly',
+ 'The grip, stock, or rail is visibly disconnected from the central body.',
+ ['crossbow-stock-grip-attachment', 'crossbow-forward-orientation'],
+ ),
+ adversary(
+ 'crossbow-unrequested-pedestal-or-animation',
+ 'The result adds a display pedestal or animation despite the explicitly static single-prop contract.',
+ ['crossbow-static-contract'],
+ ),
+ ],
+});
+
+export const PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1 = fixture({
+ id: 'pantheon-inspired-rotunda',
+ category: 'architecture',
+ prompt:
+ 'A Pantheon-inspired original rotunda facing +X: one primary storey, a circular drum and navigable floor, a fixed hemispherical dome with a real bounded oculus, and an attached columned portico framing a clear exterior-to-interior entry. Preserve inspiration without claiming exact historical reproduction.',
+ intent: createAssetIntentV1({
+ category: 'architecture',
+ subtype: 'rotunda',
+ requiredParts: ['rotunda drum', 'navigable floor', 'dome', 'oculus', 'portico', 'clear entry'],
+ forbiddenExtras: ['gable roof'],
+ material: { mode: 'pbrRecipe' },
+ architecture: {
+ subtype: 'rotunda',
+ storeyCount: 1,
+ interiorMode: 'navigable',
+ roofMode: 'fixed',
+ footprint: { spanX: 12, spanZ: 12 },
+ wallHeight: 6,
+ scaleMode: 'realistic',
+ roof: {
+ type: 'dome',
+ ridgeAxis: 'x',
+ rise: 6,
+ pitchDegrees: 0,
+ overhang: 0,
+ closedEnds: false,
+ },
+ portal: { width: 2.4, height: 3.6, depth: 0.5 },
+ },
+ }),
+ expectedSemantics: [
+ semantic(
+ 'rotunda-primary-volume',
+ 'One circular rotunda drum owns the single primary storey and a continuous navigable floor.',
+ 'deterministic+visual',
+ ['architecture.shell.rotunda', 'floor.storey.1'],
+ ['front', 'right', 'top', 'architecture.cutaway.dollhouse'],
+ ),
+ semantic(
+ 'rotunda-fixed-dome',
+ 'A fixed hemispherical dome covers the declared circular footprint and rise without gable fallback.',
+ 'deterministic+visual',
+ ['roof.dome'],
+ ['front', 'right', 'top'],
+ ),
+ semantic(
+ 'rotunda-real-oculus',
+ 'The oculus is a bounded opening through the dome rather than a decal or dark disk.',
+ 'deterministic+visual',
+ ['opening.roof.oculus'],
+ ['top', 'architecture.cutaway.dollhouse'],
+ ),
+ semantic(
+ 'rotunda-portico-clearance',
+ 'The attached portico frames the entry without columns, pediment, or steps blocking its clearance.',
+ 'deterministic+visual',
+ ['architecture.portico', 'opening.front.door'],
+ ['front', 'architecture.portal.eye'],
+ ),
+ semantic(
+ 'rotunda-navigable-entry',
+ 'A correctly sized exterior-to-interior portal reaches the navigable floor of the rotunda.',
+ 'deterministic',
+ ['opening.front.door', 'architecture.interior.shell'],
+ ['architecture.portal.eye', 'architecture.cutaway.dollhouse'],
+ ),
+ ],
+ adversaries: [
+ adversary(
+ 'rotunda-decal-oculus',
+ 'A dark circular decal is placed on an otherwise sealed dome instead of cutting a bounded opening.',
+ ['rotunda-real-oculus'],
+ ),
+ adversary(
+ 'rotunda-sealed-entry',
+ 'A painted or decorative door occupies the claimed exterior-to-interior clearance.',
+ ['rotunda-navigable-entry'],
+ ),
+ adversary(
+ 'rotunda-blocked-portico',
+ 'A portico column, stair, or pediment intersects the required entry clearance.',
+ ['rotunda-portico-clearance', 'rotunda-navigable-entry'],
+ ),
+ adversary(
+ 'rotunda-missing-floor',
+ 'The drum and dome are present but the requested primary floor role is absent.',
+ ['rotunda-primary-volume'],
+ ),
+ adversary(
+ 'rotunda-gable-fallback',
+ 'The requested dome is replaced with a generic gable roof.',
+ ['rotunda-fixed-dome', 'rotunda-real-oculus'],
+ ),
+ ],
+});
+
+export const ASSET_BENCHMARK_FIXTURES_V1: readonly AssetBenchmarkFixtureV1[] = deepFreeze([
+ RETRO_FUTURIST_RALLY_COUPE_BENCHMARK_FIXTURE_V1,
+ WINDSWEPT_JAPANESE_MAPLE_BENCHMARK_FIXTURE_V1,
+ STATIC_ORNATE_ENERGY_CROSSBOW_BENCHMARK_FIXTURE_V1,
+ PANTHEON_INSPIRED_ROTUNDA_BENCHMARK_FIXTURE_V1,
+]);
+
+/** SHA-256 of JSON.stringify(ASSET_BENCHMARK_FIXTURES_V1), updated only with reviewed fixture changes. */
+export const ASSET_BENCHMARK_FIXTURES_CANONICAL_SHA256 =
+ '4b81caa8779fb6c2a4ff4abc2d7aa6bf2cd557c0c43bfcdb7a6dd8c81751ab4d' as const;
diff --git a/src/qa/index.ts b/src/qa/index.ts
index b8576289..1eb3e2ef 100644
--- a/src/qa/index.ts
+++ b/src/qa/index.ts
@@ -24,4 +24,5 @@ export * from './breadth';
export * from './breadth-evidence';
export * from './breadth-final';
export * from './breadth-corpus';
+export * from './benchmark-fixtures';
export * from './run';