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
Prepare hosted native execution and account controls (#153)
Matthew Kissinger6f41a1aa905b
diff --git a/.agents/skills/kiln-setup-workspace/SKILL.md b/.agents/skills/kiln-setup-workspace/SKILL.mdindex 2f0aef1c..b1e637f9 100644--- a/.agents/skills/kiln-setup-workspace/SKILL.md+++ b/.agents/skills/kiln-setup-workspace/SKILL.md@@ -18,7 +18,7 @@ Do not author assets inside the engine checkout. The authoring skills assume a w## Create the workspace-When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `scripts/setup-workspace.mjs`. Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.Choose an absolute path to an empty directory outside the checkout.diff --git a/.agents/skills/kiln-setup-workspace/references/plugin-install.md b/.agents/skills/kiln-setup-workspace/references/plugin-install.mdindex 09df1184..c3f933f7 100644--- a/.agents/skills/kiln-setup-workspace/references/plugin-install.md+++ b/.agents/skills/kiln-setup-workspace/references/plugin-install.md@@ -4,19 +4,24 @@ The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creaan asset workspace. It carries setup guidance and a small installer; the engine,source stores and authored assets live outside the plugin cache. It needs asupported Node.js installation with npm, network access for first installation,-and no separate model API key.+and no separate model API key. Use it in Claude Code or Codex; it requires a local+shell and persistent filesystem and is not a Claude chat or Cowork plugin.Resolve the plugin root from this installed skill's absolute path: it is twodirectories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and-`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are+`bin/kiln-setup-workspace.mjs` exist there. Do not assume plugin path variables areavailable in an ordinary shell, and do not substitute an engine checkout.+Plugin version 1.0.0 used `scripts/setup-workspace.mjs`; if using that older+installation, confirm and use that file instead. Plugin and engine versions are+independent. `runtime.json` always names the exact engine to install.+For a fresh workspace, use an absolute empty destination outside both the pluginand its runtime data directory. Select `claude` or `codex` from the current hostor the user's stated choice:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex```The installer verifies the package name and exact version from `runtime.json`.@@ -43,8 +48,8 @@ For an existing managed workspace, stop its harness session and run the newplugin's helper with `--check`, then `--upgrade` when an update is intended:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --check+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --upgrade```Check is read-only and reports a missing pinned engine without installing it.diff --git a/.claude/skills/kiln-setup-workspace/SKILL.md b/.claude/skills/kiln-setup-workspace/SKILL.mdindex 2f0aef1c..b1e637f9 100644--- a/.claude/skills/kiln-setup-workspace/SKILL.md+++ b/.claude/skills/kiln-setup-workspace/SKILL.md@@ -18,7 +18,7 @@ Do not author assets inside the engine checkout. The authoring skills assume a w## Create the workspace-When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `scripts/setup-workspace.mjs`. Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.Choose an absolute path to an empty directory outside the checkout.diff --git a/.claude/skills/kiln-setup-workspace/references/plugin-install.md b/.claude/skills/kiln-setup-workspace/references/plugin-install.mdindex 09df1184..c3f933f7 100644--- a/.claude/skills/kiln-setup-workspace/references/plugin-install.md+++ b/.claude/skills/kiln-setup-workspace/references/plugin-install.md@@ -4,19 +4,24 @@ The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creaan asset workspace. It carries setup guidance and a small installer; the engine,source stores and authored assets live outside the plugin cache. It needs asupported Node.js installation with npm, network access for first installation,-and no separate model API key.+and no separate model API key. Use it in Claude Code or Codex; it requires a local+shell and persistent filesystem and is not a Claude chat or Cowork plugin.Resolve the plugin root from this installed skill's absolute path: it is twodirectories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and-`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are+`bin/kiln-setup-workspace.mjs` exist there. Do not assume plugin path variables areavailable in an ordinary shell, and do not substitute an engine checkout.+Plugin version 1.0.0 used `scripts/setup-workspace.mjs`; if using that older+installation, confirm and use that file instead. Plugin and engine versions are+independent. `runtime.json` always names the exact engine to install.+For a fresh workspace, use an absolute empty destination outside both the pluginand its runtime data directory. Select `claude` or `codex` from the current hostor the user's stated choice:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex```The installer verifies the package name and exact version from `runtime.json`.@@ -43,8 +48,8 @@ For an existing managed workspace, stop its harness session and run the newplugin's helper with `--check`, then `--upgrade` when an update is intended:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --check+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --upgrade```Check is read-only and reports a missing pinned engine without installing it.diff --git a/.github/workflows/container-image.yml b/.github/workflows/container-image.ymlnew file mode 100644index 00000000..2bd623a8--- /dev/null+++ b/.github/workflows/container-image.yml@@ -0,0 +1,203 @@+name: Private native image checks++on:+ pull_request:+ paths:+ - .github/workflows/container-image.yml+ - .github/published-candidate.json+ - hosting/container/**+ - hosting/src/native-*.ts+ - hosting/src/render-limits.ts+ - hosting/scripts/build*.mjs+ - hosting/scripts/prepare-native-host.mjs+ - hosting/scripts/smoke-native-host.mjs+ - hosting/scripts/smoke-native-render.mjs+ - hosting/scripts/software-render-fixture.mjs+ - hosting/package*.json+ - scripts/smoke-renderer.mjs+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: container-image-${{ github.ref }}+ cancel-in-progress: true++jobs:+ native-host:+ name: Installed MCP host image · Linux amd64+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: 22.23.3+ - name: Install the pinned build tools+ run: |+ npm install --global [email protected] --ignore-scripts --no-fund+ npm ci --prefix hosting --ignore-scripts --no-fund+ npm run build --prefix hosting -- --native-only+ - name: Prepare the isolated image context from the exact published archive+ shell: bash+ run: |+ set -euo pipefail+ mkdir -p .cache/native-host-image+ version=$(node --input-type=module -e 'import assert from "node:assert/strict";import{readFileSync}from"node:fs";const p=JSON.parse(readFileSync(".github/published-candidate.json"));assert.equal(p.name,"@instruktlabs/kiln");assert.match(p.version,/^\d+\.\d+\.\d+(?:-rc\.\d+)?$/);process.stdout.write(p.version)')+ npm pack --ignore-scripts --registry=https://registry.npmjs.org --pack-destination .cache/native-host-image "@instruktlabs/kiln@$version"+ node hosting/scripts/prepare-native-host.mjs ".cache/native-host-image/instruktlabs-kiln-$version.tgz"+ - name: Resolve and retain the private image lock+ working-directory: .cache/native-host-image/context+ run: npm install --package-lock-only --ignore-scripts --no-fund+ - name: Build and exercise the private MCP entry without cloud access+ shell: bash+ run: |+ set -euo pipefail+ test "$(find .cache/native-host-image/context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 8+ docker build --platform linux/amd64 --provenance=false --tag kiln-native-host:ci .cache/native-host-image/context 2>&1 | tee .cache/native-host-image/build.log+ node hosting/scripts/smoke-native-host.mjs kiln-native-host:ci+ - name: Retain native host identities and test results+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: private-native-host-image-evidence+ path: |+ .cache/native-host-image/context-receipt.json+ .cache/native-host-image/build.log+ .cache/native-host-image/qualification/+ include-hidden-files: true+ if-no-files-found: error+ retention-days: 30+ image:+ name: Installed ${{ matrix.label }} image · Linux amd64+ strategy:+ fail-fast: false+ matrix:+ include:+ - kind: cpu+ label: CPU+ dockerfile: Dockerfile+ - kind: software+ label: software Vulkan+ dockerfile: Dockerfile.software+ runs-on: ubuntu-24.04+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: 22.23.3+ - name: Build the private software-rendering transport+ if: matrix.kind == 'software'+ run: |+ npm install --global [email protected] --ignore-scripts --no-fund+ npm ci --prefix hosting --ignore-scripts --no-fund+ npm run build --prefix hosting -- --native-only+ - name: Prepare only the reviewed minimal context+ shell: bash+ run: |+ set -euo pipefail+ mkdir -p image-context image-evidence+ node --input-type=module -e '+ import assert from "node:assert/strict";+ import {readFileSync,writeFileSync} from "node:fs";+ import {createHash} from "node:crypto";+ const p=JSON.parse(readFileSync(".github/published-candidate.json"));+ assert.equal(p.name,"@instruktlabs/kiln");+ assert.match(p.version,/^\d+\.\d+\.\d+(?:-rc\.\d+)?$/);+ assert.match(p.sha256,/^[a-f0-9]{64}$/);+ const metadataResponse=await fetch(`https://registry.npmjs.org/@instruktlabs%2fkiln/${p.version}`,{redirect:"error"});+ assert.equal(metadataResponse.status,200);const m=await metadataResponse.json();+ assert.equal(m.name,p.name);assert.equal(m.version,p.version);+ assert.equal(new URL(m.dist.tarball).origin,"https://registry.npmjs.org");+ const response=await fetch(m.dist.tarball,{redirect:"error"});assert.equal(response.status,200);+ const bytes=Buffer.from(await response.arrayBuffer());+ assert.equal(createHash("sha256").update(bytes).digest("hex"),p.sha256);+ writeFileSync("image-context/candidate.tgz",bytes);+ writeFileSync("image-context/candidate.sha256",`${p.sha256} candidate.tgz\n`);+ writeFileSync("image-evidence/candidate.json",JSON.stringify(p,null,2));+ '+ cp 'hosting/container/${{ matrix.dockerfile }}' image-context/Dockerfile+ cp hosting/container/evaluate.mjs image-context/+ if [ '${{ matrix.kind }}' = software ]; then+ cp .cache/hosted-worker/native-render.mjs hosting/container/render.mjs image-context/+ test "$(find image-context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 6+ else+ test "$(find image-context -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 4+ fi+ - name: Build without registry publication+ id: image+ shell: bash+ run: |+ set -euo pipefail+ docker build --platform linux/amd64 --provenance=false --tag kiln-evaluation:ci image-context 2>&1 | tee image-evidence/build.log+ docker image inspect kiln-evaluation:ci > image-evidence/image.json+ docker create --name kiln-evaluation-inventory kiln-evaluation:ci+ docker cp kiln-evaluation-inventory:/opt/kiln/package-lock.json image-evidence/package-lock.json+ docker cp kiln-evaluation-inventory:/opt/kiln/os-packages.txt image-evidence/os-packages.txt+ docker cp kiln-evaluation-inventory:/opt/kiln/node-version.txt image-evidence/node-version.txt+ docker rm kiln-evaluation-inventory+ - name: Exercise the actual entry using a fixed trusted fixture+ shell: bash+ run: |+ set -euo pipefail+ # This checks image functionality, not hostile-source or Cloudflare isolation.+ docker run --rm --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges kiln-evaluation:ci \+ node --input-type=module -e 'import{createEvaluatorRequestV2}from"@instruktlabs/kiln/evaluator";process.stdout.write(createEvaluatorRequestV2({requestId:"image-fixture",code:"function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}",maxGlbBytes:2097152}).json)' \+ > image-evidence/request.json+ for attempt in 1 2; do+ docker create --interactive --name "kiln-evaluation-$attempt" --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \+ --env KILN_RENDER=cpu kiln-evaluation:ci /usr/local/bin/node /opt/kiln/evaluate.mjs+ timeout --signal=TERM --kill-after=5s 90s docker start --attach --interactive "kiln-evaluation-$attempt" \+ < image-evidence/request.json > "image-evidence/result-$attempt.json" 2> "image-evidence/stderr-$attempt.txt"+ test "$(docker inspect "kiln-evaluation-$attempt" --format '{{.State.ExitCode}}')" -eq 0+ docker inspect "kiln-evaluation-$attempt" --format '{{json .State}}' > "image-evidence/state-$attempt.json"+ done+ docker run --rm --interactive --network none --cpus 1 --memory 6g --memory-swap 6g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges kiln-evaluation:ci \+ node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";import{createHash}from"node:crypto";import{decodeEvaluatorResultV2}from"@instruktlabs/kiln/evaluator";const r=decodeEvaluatorResultV2(readFileSync(0,"utf8"),2097152,"image-fixture");assert.equal(r.ok,true);assert.equal(r.render.glb.subarray(0,4).toString(),"glTF");console.log(JSON.stringify({status:"passed",cloudflareQualified:false,hostileSourceQualified:false,bytes:r.render.glb.length,sha256:createHash("sha256").update(r.render.glb).digest("hex")}))' \+ < image-evidence/result-1.json > image-evidence/receipt.json+ node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";const a=JSON.parse(readFileSync("image-evidence/result-1.json"));const b=JSON.parse(readFileSync("image-evidence/result-2.json"));assert.equal(a.render.glbBase64,b.render.glbBase64)'+ - name: Qualify packaged software rendering with a fixed trusted fixture+ if: matrix.kind == 'software'+ shell: bash+ run: |+ set -euo pipefail+ mkdir image-evidence/software+ # Only this disposable output directory is writable by the image's UID.+ chmod 0777 image-evidence/software+ docker create --name kiln-software-fixture --network none --cpus 2 --memory 4g --memory-swap 4g --pids-limit 128 --cap-drop ALL --security-opt no-new-privileges \+ --mount "type=bind,source=$PWD/scripts/smoke-renderer.mjs,target=/probe/smoke-renderer.mjs,readonly" \+ --mount "type=bind,source=$PWD/image-evidence/software,target=/out" \+ kiln-evaluation:ci node /probe/smoke-renderer.mjs /opt/kiln/node_modules/@instruktlabs/kiln /out software+ timeout --signal=TERM --kill-after=5s 60s docker start --attach kiln-software-fixture \+ > image-evidence/software-stdout.log 2> image-evidence/software-stderr.log+ docker inspect kiln-software-fixture --format '{{json .State}}' > image-evidence/software-state.json+ test "$(docker inspect kiln-software-fixture --format '{{.State.ExitCode}}')" -eq 0+ node --input-type=module -e 'import assert from"node:assert/strict";import{readFileSync}from"node:fs";const r=JSON.parse(readFileSync("image-evidence/software/receipt.json"));assert.equal(r.status,"passed");assert.equal(r.software,true);assert.equal(r.views.length,6)'+ - name: Qualify the one-shot render entry and private port+ if: matrix.kind == 'software'+ run: node hosting/scripts/smoke-native-render.mjs kiln-evaluation:ci+ - name: Retain image evidence without publishing the image+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: private-evaluation-image-evidence-${{ matrix.kind }}+ path: |+ image-evidence/+ !image-evidence/software/.kiln/**+ .cache/software-render-entry/qualification/+ include-hidden-files: true+ if-no-files-found: error+ retention-days: 30+ - name: Remove only this job's test containers+ if: always()+ shell: bash+ run: |+ for name in kiln-evaluation-inventory kiln-evaluation-1 kiln-evaluation-2 kiln-software-fixture; do+ if docker container inspect "$name" >/dev/null 2>&1; then docker rm --force "$name"; fi+ donediff --git a/assets/branding/kiln-512.png b/assets/branding/kiln-512.pngnew file mode 100644index 00000000..f380acc0Binary files /dev/null and b/assets/branding/kiln-512.png differdiff --git a/biome.json b/biome.jsonindex 86158620..c6a2afc3 100644--- a/biome.json+++ b/biome.json@@ -11,6 +11,8 @@"hosting/src/**/*.ts","hosting/test/**/*.{ts,mjs}","hosting/scripts/**/*.mjs",+ "hosting/container/**/*.mjs",+ "hosting/probe/**/*.ts","render-service/src/**/*.mjs","render-service/test/**/*.mjs"],diff --git a/docs/local-plugin-privacy.md b/docs/local-plugin-privacy.mdnew file mode 100644index 00000000..4fba8ceb--- /dev/null+++ b/docs/local-plugin-privacy.md@@ -0,0 +1,83 @@+# Kiln local plugin privacy++Draft for owner review before directory submission. Updated 7 October 2026.++This notice covers the `kiln-engine` local plugin maintained by Instrukt Labs and+the local workspace it sets up. It does not cover the separate hosted Kiln service+or your coding assistant's account and conversation history. The local plugin does+not require a Kiln account, an email address, payment details or a model API key.++## What stays on your computer++Setup reads its public package/version pin, locates Node and npm, and checks the+workspace and runtime directories you select. It installs the engine in a persistent+data directory outside the plugin cache. Paths can contain your device account+name; paths, package identity and file hashes appear in local configuration,+installation records and command results returned to your assistant.++Your workspace and configured asset libraries hold authored JavaScript, material+files, asset names, metadata, previews and GLBs. Local tools read and write the+work you ask them to handle and return requested source, images and results to+your coding assistant. Avoid putting personal or confidential information in a+source file, asset name or tool argument unless you intend your assistant to see it.++The local plugin does not send these assets to an Instrukt Labs service or add+analytics reporting. Your assistant can send prompts and tool results to its own+provider. That processing, and any assistant history or backups, follows the+assistant's settings and privacy policy. Kiln does not control those copies.++## Network access and other services++- Installing or updating the marketplace/plugin contacts GitHub through your+ coding assistant or Git. Setup downloads the exact engine version and its+ dependencies through npm using `https://registry.npmjs.org`. Those services+ receive download requests and ordinary connection information, including your+ IP address. No asset upload is part of setup.+- npm runs with lifecycle scripts, audit and funding requests disabled. It can+ still use your existing npm configuration and inherited environment, including+ registry authentication you already configured. Kiln does not request an npm+ login or registry token for this public package, copy credentials into the+ plugin, or promise to strip npm's normal credential configuration. npm also+ writes to its normal cache and log directories.+- CPU rendering is local. An optional local render service stays on your machine.+ If you explicitly configure a renderer on another machine, Kiln sends the GLB+ and capture settings to that chosen endpoint and uses its configured+ authentication. Review that operator's privacy and retention practices first.+- Opening documentation, filing a GitHub issue or contacting support uses the+ service you choose. Information in a public issue is public; it is not private+ telemetry from your local workspace.++Relevant service policies: [npm](https://docs.npmjs.com/policies/privacy/),+[GitHub](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement),+[Claude](https://www.anthropic.com/legal/privacy) and+[OpenAI](https://openai.com/policies/privacy-policy/). Other assistants and optional+renderer operators provide their own policies.++## Retention and deletion++Local source, saved assets, runtime installations and workspace configuration+remain until you delete them. Uninstalling the plugin removes neither your assets+nor its separately installed engine. Plugin updates also leave existing+workspaces on their installed engine until you request a managed upgrade.++There is no automatic seven-day expiry for local work; that is a separate hosted+service policy. Remove selected local work using Kiln's library controls or your+filesystem, and manage independent exports, backups, npm caches and assistant+histories through their respective applications. Preserve copies you want before+deleting a workspace or runtime.++## Support and security++Contact [[email protected]](mailto:[email protected]) for privacy+questions, deletion requests concerning information you sent to support, or+private security reports. Support receives only what you send, including your+email address and message. Support mail is forwarded through Cloudflare to the+maintainer's Google inbox; see [Cloudflare's privacy policy](https://www.cloudflare.com/privacypolicy/)+and [Google's privacy policy](https://policies.google.com/privacy). We use support+correspondence to handle the request; this is not an automatic local-plugin alert+or a mailing-list signup.++Do not send passwords, tokens, recovery codes or private assets with a bug report.+Sanitize logs and paths before posting publicly. Instrukt Labs cannot remotely+access or erase your local workspace, your assistant's copies or a renderer+operator's records through this plugin.diff --git a/docs/plans/2026-10-05-v1-publication-plan.md b/docs/plans/2026-10-05-v1-publication-plan.mdindex 820a447f..bcd08799 100644--- a/docs/plans/2026-10-05-v1-publication-plan.md+++ b/docs/plans/2026-10-05-v1-publication-plan.md@@ -1075,6 +1075,13 @@ email route need not introduce another hosting vendor. Verify account access,deliverability, costs, abuse controls and recovery semantics before enabling it.[Cloudflare Email Service](https://developers.cloudflare.com/email-service/).+The owner selected **in-app security notices only for v1** on 6 October. Keep the+account activity and confirmation notices for sign-in method changes and account+deletion. Do not collect a separate security contact email, expand provider scopes+for email, or configure outbound security mail in this release. Users will not+receive an out-of-band warning of these actions; describe this limitation honestly.+Email notifications remain a possible later improvement, separate from email login.+No provider app, secret, SQL resource or production authentication change wascreated during this review. This hosted work does not block the independentlyqualified npm 1.0 publication.@@ -1315,6 +1322,7 @@ This settles D8 and reinforces that $20 is a target, not a guaranteed billing ca| D7 | Public OpenAI plugin plus Anthropic directory; local owned distribution available independently | Before exact artifacts are submitted/published | Requested outcome; final candidates and applicable approvals still required || D8 | Free quota-limited hosted access initially, optional sponsorship, no subscription billing in v1 | Implement within measured hosting capacity and storage/admission limits | Owner explicitly accepted on 6 October; accepts justified provider overages and may seek sponsorship/grants; do not ask again || D9 | Google and GitHub sign-in through one Kiln-owned account; email later | Before provisioning provider applications | Owner accepted on 6 October, requiring correct, secure implementation and professional presentation; architecture reviewed above, multi-provider implementation and deployed qualification remain open |+| D10 | In-app security notices only for v1 | Settled; do not ask again | Owner selected on 6 October. No separate security contact email collection or outbound security mail; Google/GitHub sign-in unchanged. Out-of-band notifications can follow later. |Do not present D4's provider decision as passed production qualification or D5 as a measured forecast. Legalentity/account fields must come from the owner; do not infer exact legal detailsdiff --git a/docs/releasing.md b/docs/releasing.mdindex 1907a546..3cdd24bf 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -9,8 +9,12 @@ See the [v1 execution record](reviews/2026-10-06-v1-execution.md) for current st## Qualify the candidate1. Complete the release contract, consumer documentation, notices and changelog.- Align `package.json`, engine metadata and plugin manifests to `1.0.0-rc.N` or- `1.0.0`, then rebuild the runtime. A version change creates a new candidate.+ Align `package.json`, engine metadata and the `engineVersion` pin in+ `plugins/kiln-engine.release.json`, then rebuild the runtime. The local plugin's+ own `version` changes when its manifest, executable or guidance changes; it can+ advance independently while retaining the same published engine. Generate and+ review the local bundle with `scripts/package-local-plugin.mjs`. A version+ change creates a new candidate, not permission to republish an existing version.2. Review the changes and obtain authorization to merge. After merging, wait for**every** job in `.github/workflows/ci.yml` to pass on that exact main commit.PR receipts are useful during development but cannot authorize a release.diff --git a/docs/reviews/2026-10-06-cloudflare-startup-review.md b/docs/reviews/2026-10-06-cloudflare-startup-review.mdnew file mode 100644index 00000000..6fb1e003--- /dev/null+++ b/docs/reviews/2026-10-06-cloudflare-startup-review.md@@ -0,0 +1,406 @@+# Cloudflare startup review and release status++Reviewed 6 October 2026 against current Cloudflare documentation, public issue+reports, the installed tool versions, the deployed probe receipts, current source,+GitHub checks and the npm registry. This is an analysis and next-test plan, not+evidence that native hosting works. The initial research sent no additional+deployment or support message. The subsequent bounded managed-image control is+recorded below; it passed, while custom-image and full Kiln hosting remain unqualified.++## Conclusion++Keep the all-Cloudflare architecture, but reduce the startup problem to a minimal+documented example before another Kiln execution attempt. A support ticket is a+parallel diagnostic channel, not proof of a Cloudflare defect or a reason to wait+without further investigation. The earlier documentation review established a+reasonable isolation design; it did not establish the cause of the startup error.++Native execution is a hosted-launch blocker. It does not block the independently+qualified npm package or local plugins. The hosted service also has unfinished+authentication, account controls, dispatch and operational qualification, so fixing+startup alone would not make it ready to launch.++## What the receipts establish++- The second actual provider execution reached the private deployed coordinator.+ The first fixed case failed after 2,038 ms; `monitor` was the first native method+ recorded as rejecting. There is no successful evaluator output or GLB receipt.+- The observer records the first failed method, not a complete timeline of+ startup, command admission, process completion and cleanup. Consequently this+ does not identify an exclusive underlying cause or conclusively locate failure+ before every possible engine instruction.+- The image is Linux amd64, uses Node 22.23.3 on Debian Trixie, has `USER node`,+ and starts `sleep infinity`. Native `exec` explicitly uses numeric `1000:1000`.+ The named image reference is pinned in Cloudflare's own registry. Ordinary+ Docker and the installed-image CI fixture can run the fixed engine program.+- The numeric `exec` correction addressed a documented API constraint, but did+ not resolve the deployed failure. There is no evidence yet that Dockerfile+ `USER node` is itself unsupported; changing it would be a controlled hypothesis,+ not a known fix.+- Cleanup receipts show the trial application, Worker, namespaces and registry+ image were removed. Two executions consumed two of the five authorized jobs;+ three remain. The former four-case continuation must not be redeployed.+- One P4 case, `02363339`, was submitted with explicit owner approval. It included+ the error reference and deployment configuration, without secrets, user assets+ or attachments. Its saved receipt records no response at submission; this review+ did not refresh the support inbox or assert its current response status.++Local receipts: `.cache/provider-probe-trial-3/`. The restricted-Docker Bubblewrap+failure is separate: it demonstrates unavailable nested namespaces in that test+environment, not the cause of this remote Container failure.++## Current documented approach++Cloudflare recommends the native Durable Object Container API for new applications.+`start()` validates options and initiates boot; `monitor()` reports lifecycle+failure, and `exec()` waits if startup is still in progress. It is not necessary to+invent a network health server for our command-only job. The current controller+already observes the monitor without awaiting container exit before executing.+Source: [native API](https://developers.cloudflare.com/containers/api/durable-object-container/).++Containers provide a Linux microVM and support native dependencies and subprocesses.+Dynamic Workers cannot load native add-ons or start subprocesses, so they are not+a drop-in replacement for the existing evaluator and software renderer. Source:+[environment selection](https://developers.cloudflare.com/sandbox/concepts/).++The complete sandbox is the trust boundary. Its processes can access its files+and localhost, and native sandbox user IDs do not provide isolation. Keep each+job in a fresh VM, keep identity/storage credentials outside, pass only authorized+job inputs, and validate outputs in the trusted host. A local-loopback connection+inside the same VM is not itself a boundary failure; tests must distinguish it+from access to trusted services, other jobs or external destinations. Source:+[sandbox security](https://developers.cloudflare.com/sandbox/concepts/security/).++Native process cancellation does not stop descendants, and inactivity timeouts+are not hard execution deadlines. Retain the external watchdog, durable cleanup+alarm and awaited whole-instance destruction. Record phase outcomes separately+from teardown failures. Source:+[command execution](https://developers.cloudflare.com/containers/guides/execute-commands/).++The `durable_object` scheduling policy entered public beta on 30 September. It+supports per-instance image selection but not application `max_instances`. Our+production host still needs authoritative global and per-account admission before+creating job IDs. Source:+[scheduling policies](https://developers.cloudflare.com/containers/configuration/scheduling-policy/).++## Options and recommendation++| Option | Fit for Kiln | Recommendation |+| --- | --- | --- |+| Native Container API with `durable_object` policy | Direct argument execution and piped bytes fit one-shot evaluation; fresh VM per job; startup and admission remain our responsibility | Keep as first candidate, subject to a minimal provider baseline and hostile-job qualification |+| Native API with `default` scheduling policy | Fixed image and size suit v1, with application-level instance caps and managed rollouts | First Cloudflare fallback if evidence isolates a problem to the newer policy; needs its own adapter and image-identity evidence, not a flag flip |+| `@cloudflare/sandbox` 1.0 | Adds file/mount/backup helpers to an already running Container | Do not add it merely to fix startup; it does not start, stop or monitor the VM |+| Dynamic Workers | Useful for capability-limited JavaScript without native dependencies | A future engine portability project, not the shortest v1 fix |+| Another compute provider | Could be appropriate if both Cloudflare routes fail qualification or measured economics are poor | No provider change justified yet |++The default policy and its rollout/cap differences are documented in the+[policy comparison](https://developers.cloudflare.com/containers/configuration/scheduling-policy/).+The SDK's current responsibilities are explicit in its+[1.0 reference](https://developers.cloudflare.com/sandbox/reference/).++Reduce tooling variables too. The probe currently builds low-level prebuilt+output and uses loopback bindings after a cf validation problem. For the minimal+reproduction, use the documented Wrangler configuration and explicit bindings;+keep `cf` for account/resource operations. This is a diagnostic simplification,+not a conclusion that `cf` caused the failure. Its CLI and Build Output remain+[beta](https://developers.cloudflare.com/cf/).++Registry reads today returned Wrangler 4.147.0, cf 1.0.0-beta.12 and Sandbox SDK+1.0.0. Wrangler 4.147.0 meets the documented native-policy and managed-image local+development minimums. Pin the version; do not update unrelated dependencies.+Source: [local development requirements](https://developers.cloudflare.com/containers/guides/local-dev/).++## Public discussions reviewed++These are reports, not independently confirmed explanations for Kiln:++| Report | What it describes | Why it does not establish our cause |+| --- | --- | --- |+| [containers #161](https://github.com/cloudflare/containers/issues/161) | Response-body failure through a service binding | Our operator gets structured RPC metadata; failure is recorded inside the Container lifecycle before successful output |+| [workerd #6790](https://github.com/cloudflare/workerd/issues/6790) | Local Sandbox terminal readiness timeout | Different local runtime and older SDK; our failed attempt reached the deployed service |+| [containers #231](https://github.com/cloudflare/containers/issues/231) | WSL2 local application container never starts | Reporter explicitly says deployed containers are unaffected |+| [workers-sdk #16008](https://github.com/cloudflare/workers-sdk/issues/16008) | Deleting a Worker leaves its Container application | Relevant to cleanup, not startup; our separate application/image/namespace readbacks remain necessary |++Searches also covered Cloudflare's public community results, `containers`,+`sandbox-sdk`, `workers-sdk` and `workerd` issue trackers. No reviewed report+established the same root cause as our native-policy custom-image failure.++## Next diagnostic, before more product changes++Prepare a new, fixed, private diagnostic with phase markers and at most the three+remaining job starts. Stop on failure and investigate the result before advancing:++1. **Managed-image control:** use `cloudflare/debian-trixie`, no Kiln package, no+ custom registry image and no user source. Run a fixed Node version/identity+ command, verify completion, then destroy and confirm stopped.+2. **Custom-image control:** if step 1 succeeds, build the equivalent minimal+ Linux/Node image through the documented image pipeline. Use the same controller+ and command. This tests custom-image preparation separately from Kiln.+3. **Kiln-image startup:** if both controls succeed, use the retained exact Kiln+ image with a fixed command that does not import Kiln. A pass directs subsequent+ investigation toward evaluator/controller integration; a failure narrows image+ configuration. Do not simultaneously change the scheduler, image user and code.++The managed control uses Node 24.20.0 and is only a platform diagnostic, not a+replacement for the release's pinned Node 22.23.3 runtime. Image sources and+digest handling follow the+[image management guide](https://developers.cloudflare.com/containers/guides/image-management/).++Record only fixed metadata: operation entered/completed/failed, relative time,+instance/image identity, command exit and cleanup result. Do not log arbitrary+source or credentials. Preserve the private invocation, single-run claim, 60-second+job ceiling, no egress, no secrets and readback-verified teardown. Local preparation+and validation come before deployment. This review itself consumes no cloud jobs.++A successful diagnostic still requires a separately bounded hostile-job/rendering+qualification campaign: network denial, fresh filesystem/process state, descendants,+memory/output exhaustion, deadline/cancellation races, supervisor recovery and+actual authenticated MCP/storage workflows. That campaign must not silently reset+the original five-job allowance.++Optimize only after measuring startup, peak memory, CPU and cleanup. The current+6-GiB instance is conservative, not a proven optimum. Cloudflare bills provisioned+memory/disk for running time and CPU for active usage, so short lifetimes and+measured sizing matter more than adding an SDK. Source:+[current pricing](https://developers.cloudflare.com/containers/platform/pricing/).++## Verified release status++| Work | Current evidence | Remaining work |+| --- | --- | --- |+| Publisher setup | Repository transfer and npm security setup recorded complete | Preserve these settings; no repeat setup |+| Public npm package | Registry returns `next=1.0.0-rc.1`, `latest=0.0.0-stage` | Final version, exact-main archive checks, approved stable promotion and fresh installs |+| Local plugins | Public RC installed and exercised in Claude Code and Codex | Stable-version updates and upgrade checks; directory submissions are separate |+| Native candidate PR #147 | Exact `7f4e98e`: engine/package, gateway, image, registry matrix and website checks pass | Separate restricted-Docker preflight fails; live native qualification absent; PR remains draft |+| Managed-image diagnostic PR #150 | Exact `c6b119b`: local gates, Linux/Windows hosted CI and deployed fixed Node command pass; resources removed | Full Kiln/hostile-source qualification remains |+| Custom-registry diagnostic PR #150 | Exact `2c60525`: local gates, both hosted CI platforms and deployed fixed Node command pass; resources removed | Full Kiln/hostile-source qualification remains |+| Unchanged Kiln-image diagnostic PR #150 | Exact `569fc53`: image prepared, then startup monitor failed before `exec`; cleanup verified | Investigate image/startup configuration locally; original five-job trial exhausted |+| Browser account PR #149 | Exact `11a4f64`: hosted checks pass on Linux and Windows in run `37507203413`; website passes | Review/integration plus live identity-provider qualification; PR remains draft |+| Connection controls | Working-tree changes pass all 144 hosted tests and all three TypeScript configurations | Uncommitted; further adversarial review, build/UI checks and CI required |+| Persistence | Local tenant storage, revisions, quotas, download/deletion and unsaved retention tests pass | Remaining material/account lifecycle work and deployed two-user evidence |+| Security/operations | Recorded secret scans, dependency fixes and focused adversarial checks | Final candidate scans, global admission, account linking/deletion, measured load/cost, alerts and recovery |+| Public hosted service | Not deployed; tenant `/mcp` deliberately returns 503 while native engine is unqualified | Complete integration, live auth, reviewed deployment and end-to-end acceptance |+| Public content and vendor directories | Broad README/Troy/site refresh intentionally deferred | Refresh after verified stable/hosted launch; prepare and submit candidates, track vendor acceptance separately |++The latest local test receipt is+`.cache/security-review-2026-10-06/account-current-status.log` (144/144);+typechecking is recorded in `account-current-typecheck.log`. These do not qualify+deployed authentication or supersede the exact-commit CI record.++## Owner handoffs++No new owner decision is required for this analysis or local diagnostic preparation.+Keep the existing release order: npm/local distribution need not wait for hosted+launch. Surface the concrete stable merge/publication and production deployment+candidates separately when ready, and surface provider login/verification steps+when they require the owner's browser. Prepare the full scope and cost estimate+before asking for any trial expansion. No new provider, paid plan or expanded+spend is proposed by this review.++## Managed-image result after research++The simpler documented configuration passed on the same Cloudflare account at+18:46:20 UTC. Source `c6b119b4a6358d51c27406f6fb3e74cafd289782` in+[PR #150](https://github.com/instruktlabs/kiln/pull/150) uses ordinary Wrangler+4.147.0 configuration, explicit bindings and `cloudflare/debian-trixie`, with no+Kiln import, custom image, user source, credentials or network access. The deployed+bundle was read back and matched SHA-256+`ddcc444cf904223eb63f5f8d2a673422c35e1e34076ae4ea2a6d13c6b59b741e`.+Both public URL flags were false and the version had no URLs.++The fixed command returned Node `v24.20.0` with UID/GID `0:0`; output completed+after 470 ms, and destruction plus stopped inspection completed after 573 ms.+The provider instance read separately showed stopped with exit code zero. These+are one diagnostic's elapsed measurements, not a Kiln benchmark or invoice. A+second RPC returned exactly the retained record and did not start another job.++The local operator was stopped; the exact Container application, Worker and+namespace were removed and absence was verified, including Worker 404. No custom+registry image was created. Receipts live in the isolated diagnostic worktree's+`.cache/startup-managed-trial/`. Three of five approved jobs have now been+attempted, leaving two. This completed control must not be redeployed to reset its+durable claim. No support follow-up was sent.++The source passed 3,290 engine tests (two platform skips), root typecheck/lint,+126 hosted tests, all hosted typechecks/builds and redacted secret scans. Both+Linux and Windows hosted CI passed in+[run 37513405377](https://github.com/instruktlabs/kiln/actions/runs/37513405377).+The primary account-control work remains separate and uncommitted at 144 local+hosted tests; the different totals represent different branches, not lost tests.++This rules out a blanket inability to run native Containers on the account. It+does not isolate the earlier failure to any single configuration difference. Next+test the minimal custom image through the same documented controller, then the+Kiln image without importing the engine, stopping on a failure. Keep Cloudflare;+no provider switch, new paid plan or expanded trial allowance is justified by this+result. Full hosted launch is still blocked by unqualified Kiln execution and+unfinished production authentication/account/integration/operations work.++The registry still returns `next=1.0.0-rc.1` and `latest=0.0.0-stage`. GitHub's open+high-severity development-dependency alert is for `sharp <0.35.5`; the pending+native branch already pins `0.35.5`, but main has not received that fix. Do not+describe that main-branch alert as closed before its merge and readback.++## Custom-registry control also passed++At 18:59:29 UTC, the same fixed controller passed with the documented managed+image's upstream Node 24.20.0 Debian Trixie AMD64 image, copied into the account's+private Cloudflare registry. Its single-platform manifest digest was+`sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600`.+No package installation, Kiln import, user data or credentials were added.++The candidate used the documented `images.control` map and+`ctx.container.images.control`, with the same fixed command, no egress and+bounded whole-instance cleanup. Source `2c605257b8990a3bb9c9f0fffb5a9abc45092bc3`+matched the uploaded JavaScript SHA-256+`84b82608d9baa9ea59cc49c56a5c34c66dc9482e22af14f5219c54945316ba7e`.+Deployed metadata verified the image reference and disabled public URLs before+invocation. Output completed after 7,000 ms and destruction/inspection after+7,102 ms; the provider separately reported stopped with exit code zero. A repeat+RPC returned the same retained result without another job. These are one control's+elapsed times, not billed CPU measurements or a Kiln performance forecast.++The operator, application, Worker, namespace and registry image were removed;+readbacks verified absence. Receipts remain under the diagnostic worktree's+`.cache/startup-custom-trial/`. Four of five approved jobs have now been attempted,+leaving one for the unchanged Kiln image without importing the engine. No expanded+trial, production deployment or support message occurred.++The source passes 129 hosted tests, all hosted typechecks/builds, 3,290 engine+tests (two platform skips), root typecheck/lint, deployment dry run and redacted+secret scans. Both hosted CI platforms passed in+[run 37515318317](https://github.com/instruktlabs/kiln/actions/runs/37515318317).++Source inspection showed Wrangler explicitly prepares custom images and waits for+readiness before deployment. The earlier cf prebuilt deployment receipt also+records that preparation and ready transition, so an omitted preparation step+does not explain the earlier failure. The original Kiln image uses an OCI index;+this control uses one AMD64 manifest. That difference is unproven as a cause, and+we should not strip provenance or rebuild the Kiln image before testing its+unchanged bytes through this simpler controller.++## Unchanged Kiln-image control failed before command execution++Source `569fc5313f909c04ac960348b638e376cdb36239` deployed the unchanged Kiln+image/index `sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`+through the same ordinary Wrangler configuration and fixed controller. The command+was only Node version/UID/GID, with numeric exec identity `1000:1000`; it did not+import Kiln. Its local Docker run returned Node `v22.23.3`, UID/GID `1000:1000`.++Before invocation, uploaded bytes matched JavaScript SHA-256+`57c509e5b71d086f18e8b3d900d3dfc2bbbc48a369ef816c057b946abe3a018a`, the image map+matched the original digest, and privacy/only-own-namespace binding checks passed.+Wrangler completed image preparation. At 19:08:40 UTC, the startup monitor failed+after 1,242 ms while setting the inactivity timeout. The phase trace never entered+`exec`; this narrows the failure more precisely than the original probe. The fixed+Node command and engine were not invoked by this controller. Destruction and+stopped inspection completed after 1,243 ms, and no instance remained in the list.+Repeat RPC returned the retained failure without a second execution.++The operator, application, Worker, namespace and registry image were removed;+readbacks verified absence and Worker 404. Receipts remain under the diagnostic+worktree's `.cache/startup-kiln-trial/`. All five original trial jobs have now been+attempted. Further cloud execution needs a concrete bounded scope and owner+approval; local investigation and independent release/account work can continue.++The current candidate passes 131 hosted tests, all hosted typechecks/builds,+root typecheck/lint, deployment dry run and redacted scans. The engine source is+unchanged from the preceding candidate's 3,290 passing tests (two platform skips).+The current hosted CI run is+[37516547552](https://github.com/instruktlabs/kiln/actions/runs/37516547552).++The result implicates this image or startup configuration under the native API,+not package evaluation code. It does not identify an exclusive cause. OCI index+selection, image user/entrypoint handling and content differences remain hypotheses.+Do not replace them with an assumed vendor fault, silently rebuild the retained+image, weaken isolation, or spend another job under the exhausted allowance.++## Local image-format comparison++Further source review found that Cloudflare's current image builder invokes+Docker with `--platform linux/amd64` and `--provenance=false` by default:+[build implementation](https://github.com/cloudflare/workers-sdk/blob/main/packages/containers-shared/src/build.ts).+This gives a specific next hypothesis without changing the execution architecture.++Read-only inspection of the retained OCI archive verified the descriptor hashes.+The failing `69aff70b...` index contains one Linux/AMD64 runtime manifest,+`sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8`,+and a separate attestation manifest with unknown OS/architecture. The successful+minimal custom control used a platform manifest directly. The runtime manifest+selects the same config `fe7ab6cb...` and ten layers already inspected and scanned;+selecting it directly would preserve Node, installed package bytes, user,+entrypoint and filesystem contents.++This difference does not prove that Cloudflare rejects OCI indexes or attestations.+The next bounded candidate should test the existing platform manifest directly,+with the same fixed command and controller, before rebuilding dependencies or+changing the image user. Prepare its exact configuration and local checks first;+one new cloud invocation would require owner approval beyond the exhausted trial.+No image was pushed, no cloud job started, and no support follow-up sent during+this inspection. The diagnostic worktree retains `kiln-image-descriptors.json`+and the metadata-only inspection script in its ignored cache.++## Original runtime manifest passed++The owner approved one additional fixed job at source+`29fc0ac248f59aa1d8c6f6ca89160c85d266e8ca`, with a separate $1 trial allowance.+At 19:49:18 UTC the test passed using the original image's Linux/AMD64 manifest+directly. Before deployment, remote inspection verified its digest, original+configuration and all ten filesystem layers. No image rebuild, package change,+user change or entrypoint change occurred. Uploaded Worker bytes matched+`f339a35a1bc271bda9e985f03d0d0f9911979617b375bd6bcadd08ccc6d80a43`.++Node returned `v22.23.3`, UID/GID `1000:1000`; output completed at 10,865 ms.+Whole-instance destruction and stopped inspection completed at 10,959 ms.+Cloudflare independently reported stopped with exit code zero. Replay returned+the same saved result without starting another job. This elapsed time is not a+billed CPU measurement or an engine/render performance result.++Application, Worker, namespace and registry tag were deleted; readbacks verified+absence. The local operator stopped and temporary Docker registry authentication+was removed. Receipts remain in the diagnostic worktree under+`.cache/startup-manifest-trial/`, including the deployed identity, exact image+metadata, phase result, replay, stopped-instance record and cleanup receipt.+All six approved jobs are now consumed. Settled billing is not yet verified.++The paired result strongly implicates index versus runtime-manifest selection in+this startup failure. It does not prove a general OCI-index incompatibility or an+exclusive vendor root cause. Follow the working documented packaging path and+retain build provenance separately. No support follow-up was sent and no provider+change is indicated. Native evaluation, rendering and hostile-input isolation+still need independent qualification. A new bounded four-case candidate is being+prepared around the existing engine/network/fresh-VM fixtures and the proven+manifest; it is not authorized by the exhausted startup allowance.++## Native engine and basic provider-boundary checks passed++The owner separately approved the four-case candidate at+`8590c0abfcaedbfa8a34dfd76ac3322f01c0fb55`, after both Linux and Windows passed+[CI run 37522530858](https://github.com/instruktlabs/kiln/actions/runs/37522530858).+The private deployment used the same original runtime manifest and the existing+production job controller. Remote config/layers and uploaded Worker SHA-256+`0e97f19c8617d20f1bc96880aaa95b9e9303e45b560c7f242f7e19146527fede`+were verified before its one-use coordinator was invoked at 20:04:01 UTC.++All four sequential jobs passed: actual installed-RC evaluation produced the+expected 1,912-byte GLB with digest+`f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40`;+direct native TCP/DNS checks found the tested endpoints inaccessible; one VM wrote+a marker and confirmed a detached child was live; the next fresh VM found neither+marker nor matching child. Elapsed times including cleanup were 3,398, 15,320,+1,260 and 1,283 ms. They are not billed CPU or representative load measurements.++Each result confirmed stopped state and Cloudflare independently reported all four+instances stopped with exit code zero. Replay returned the retained batch without+new executions. The application, Worker, both namespaces and registry tag were+deleted, with absence verified. The local operator and temporary registry login+were closed. Evidence is retained under the diagnostic worktree's+`.cache/manifest-qualification-trial/`.++This qualifies this installed-engine fixture and the tested provider boundaries.+It does not qualify CPU previews/software rendering, hostile resource exhaustion,+cancellation and alarm recovery, public admission, live identity/tenant/storage+integration or production deployment. Those remain required. The original Linux+nested-namespace preflight still fails and must not be relabelled successful.+All ten jobs across the three approved trial scopes are consumed; a later trial+needs its own concrete scope and authorization. No support follow-up was sent.diff --git a/docs/reviews/2026-10-06-hosted-integration-receipt.json b/docs/reviews/2026-10-06-hosted-integration-receipt.jsonnew file mode 100644index 00000000..1fe391f9--- /dev/null+++ b/docs/reviews/2026-10-06-hosted-integration-receipt.json@@ -0,0 +1,229 @@+{+ "schemaVersion": 1,+ "qualification": "private-cloudflare-integrated-mcp",+ "sourceCommit": "c7554346c12b14eb7dd5c25db7520314f201012b",+ "workerSha256": "3ff536d4e99b8ee348d2a55e5a0de58ca04895643f53ccba4a68cf5ee570312a",+ "workerVersion": "2e8535a8-0f8d-40c5-ac5f-309e5ef9bb2b",+ "images": [+ {+ "kind": "coordinator",+ "references": [+ "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-coordinator@sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66"+ ]+ },+ {+ "kind": "evaluation",+ "references": [+ "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-software@sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24"+ ]+ },+ {+ "kind": "render",+ "references": [+ "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-software@sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24"+ ]+ }+ ],+ "allowed": {+ "usd": 1,+ "mcpRequests": 9,+ "vmStarts": 17+ },+ "result": {+ "state": "finished",+ "passed": true,+ "results": [+ {+ "name": "render",+ "passed": true,+ "elapsedMs": 39887,+ "status": 200,+ "bytes": 58568,+ "sha256": "6f561ec80fc8f43628b1309a7690bfdd81acc4fddccfde7460b27db79d0ee1a2"+ },+ {+ "name": "save",+ "passed": true,+ "elapsedMs": 35598,+ "status": 200,+ "bytes": 2086,+ "sha256": "544ee7236880fffd6c8ff639fb703d3519f8353e5df3a8fa33b7c8e1853ef97e"+ },+ {+ "name": "restore",+ "passed": true,+ "elapsedMs": 3802,+ "status": 200,+ "bytes": 3108,+ "sha256": "fb1df871dc8209d20a0d445cd0f769f74601b7220214f73ad3fc5a2bf7ecd861"+ },+ {+ "name": "source",+ "passed": true,+ "elapsedMs": 3634,+ "status": 200,+ "bytes": 795,+ "sha256": "645e8ec5b67ff4b07bf9e282f45e953e75aa2c174b6d9f9b792489f9d9eadd25"+ },+ {+ "name": "export",+ "passed": true,+ "elapsedMs": 4035,+ "status": 200,+ "bytes": 3578,+ "sha256": "aa2d98728fe1a0b892be57467cabda18812b0a355b21bc29ca8ca91b122dedf1"+ },+ {+ "name": "glb",+ "passed": true,+ "elapsedMs": 4516,+ "status": 200,+ "bytes": 8035,+ "sha256": "27bda861204e5ed03f14da9e9f599345f0dec789a5c9976f72f7fc11ca6e4b4b"+ },+ {+ "name": "manifest",+ "passed": true,+ "elapsedMs": 4493,+ "status": 200,+ "bytes": 7620,+ "sha256": "356703778d377a84e2f9afc7b46d30f386579cb4a593579cd2037ac4af6928fa",+ "savedEngine": "source-development:unverified"+ },+ {+ "name": "other-source",+ "passed": true,+ "elapsedMs": 3767,+ "status": 200,+ "bytes": 456,+ "sha256": "7cd73362118a076fa3a953a542d7dddf9a9bf37a3e889a363c104b538a20a32a"+ },+ {+ "name": "other-glb",+ "passed": true,+ "elapsedMs": 3552,+ "status": 200,+ "bytes": 101,+ "sha256": "b61378c9b7e84274711ef35e385a82dc2cf689eb678a525944fe900354a2c234"+ },+ {+ "name": "quota",+ "passed": true,+ "elapsedMs": 147,+ "status": 429,+ "bytes": 33,+ "sha256": "9f05a9d8bc352ea80fb29673348cbe4a5432dde498ad90d2420350520aeba4aa"+ }+ ],+ "cleanupConfirmed": true+ },+ "actual": {+ "admittedMcpRequests": 9,+ "quotaRejections": 1,+ "vmStarts": 13,+ "resources": {+ "coordinator": {+ "starts": 9,+ "vcpu": 0.5,+ "memoryMiB": 4096,+ "diskMB": 8000,+ "observedRunningSeconds": 95.484+ },+ "evaluation": {+ "starts": 2,+ "vcpu": 1,+ "memoryMiB": 6144,+ "diskMB": 12000,+ "observedRunningSeconds": 20.656+ },+ "render": {+ "starts": 2,+ "vcpu": 1,+ "memoryMiB": 6144,+ "diskMB": 12000,+ "observedRunningSeconds": 27.352+ }+ }+ },+ "artifacts": {+ "glbSha256": "d183547f474f07bba897ce43d836986026666784f4476fb9daede7196fc3eae2",+ "files": {+ "asset.glb": {+ "sha256": "sha256:d183547f474f07bba897ce43d836986026666784f4476fb9daede7196fc3eae2",+ "bytes": 5772+ },+ "source.kiln.js": {+ "sha256": "sha256:d1b15b61094af9d4f01eace7d60154edd020f259dce2174143ecdf86ace7e55f",+ "bytes": 434+ },+ "preview.png": {+ "sha256": "sha256:6e7fd6b85f887e2ddd3359a7ec80cd9a1d6426d1a51e8fab3e043dc006387f1b",+ "bytes": 208582+ }+ },+ "preview": {+ "fidelity": {+ "version": "kiln.view-fidelity.v1",+ "requested": "full-preferred",+ "delivered": "full-material",+ "materialFaithful": true,+ "exactArtifact": true,+ "rendererId": "dawn-vulkan:llvmpipe-llvm-19-1-7-256-bits-:llvmpipe: Mesa 25.0.7-2+deb13u1 (LLVM 19.1.7) 0.0.1",+ "inputGlbSha256": "sha256:d183547f474f07bba897ce43d836986026666784f4476fb9daede7196fc3eae2",+ "degraded": false,+ "reasonCodes": []+ },+ "backdrop": "neutral"+ },+ "sourceMatches": true,+ "responseHashesVerified": true+ },+ "durableReplay": {+ "unchanged": true,+ "additionalVmStarts": 0+ },+ "operator": {+ "initialRpcStatus": 502,+ "recoveredFromDurableStatus": true,+ "trialRestarted": false,+ "localListenerStopped": true+ },+ "deployment": {+ "tool": "wrangler",+ "version": "4.147.0",+ "publicHttp": false,+ "correction": "Equivalent local Durable Object bindings; cf 1.0.0-beta.12 emitted external script_name self-references. No code or image change."+ },+ "cleanup": {+ "sourceCommit": "c7554346c12b14eb7dd5c25db7520314f201012b",+ "workerAbsent": true,+ "applicationsAbsent": [+ "eba88d54878946b8a1be75454b329384",+ "b343ca54194e4392ae7a4eeed9b7a009",+ "ddc9433871834a6d874a44ce3b290929"+ ],+ "namespacesAbsent": [+ "ddc9433871834a6d874a44ce3b290929",+ "43aa2a0166f24a65bf4e6f3061d9f6e7",+ "412dae0abc094c89acce6fc63ad46360",+ "b343ca54194e4392ae7a4eeed9b7a009",+ "d41ebfadfee246a2bcc44e6c16c479b0",+ "eba88d54878946b8a1be75454b329384",+ "6abfc7963b6b4e979eb30b6ac06cc71c"+ ],+ "bucketAbsent": true,+ "objectsDeleted": 15,+ "registryTagsAbsent": true,+ "verifiedStoppedInstances": 13,+ "checkedAt": "2026-10-07T00:49:52.405Z"+ },+ "settledCostUsd": null,+ "limitations": [+ "Only the frozen candidate is qualified; later download and material changes require their own provider qualification.",+ "Saved build.engine remains source-development:unverified; host-owned execution identity is still required.",+ "One small fixture with sequential admission; no representative load, multi-region latency or settled-cost claim.",+ "No live OAuth, public hostname, real external MCP client or directory submission was exercised."+ ],+ "evidenceDirectory": ".cache/integrated-trial",+ "checkedAt": "2026-10-07T00:51:49.383Z"+}diff --git a/docs/reviews/2026-10-06-v1-execution.md b/docs/reviews/2026-10-06-v1-execution.mdindex 2eae4bf7..2712a3e8 100644--- a/docs/reviews/2026-10-06-v1-execution.md+++ b/docs/reviews/2026-10-06-v1-execution.md@@ -7,32 +7,406 @@ Started 6 October 2026 by the owner's active goal. Working checkout:The [publication plan](../plans/2026-10-05-v1-publication-plan.md) defines scope;[hosting economics](../plans/2026-10-06-hosting-economics.md) records assumptions.This record tracks evidence, not release acceptance by implication. Community-contributions remain outside this cycle. No package or production service is-published yet.+contributions remain outside this cycle. Stable `@instruktlabs/[email protected]` is now+public on npm under `latest`; the release candidate remains under `next`. The+production hosted service remains unpublished. The table below is current; the dated execution notes retain earlier+states and the evidence that superseded them.## Deliverables and evidence| ID | Requirement | State and required proof || --- | --- | --- || P0 | Preserve publisher/repository setup | Complete in [publisher setup receipt](2026-10-06-publisher-setup.md); current checkout remote verified `instruktlabs/kiln` |-| P1 | Public API, stability and migrations | In progress: all 55 public entrypoints classified in the SDK guide, experimental/re-export and deprecated-alias boundaries explicit, Discovery labels visible; final release freeze and target-version upgrade proof remain open |-| P2 | Compiled ESM SDK and declarations | In progress: corrected 53-entry core qualification includes dependency-free arena; all 55 imports/declarations pass in fresh optional-peer installations at current and declared-minimum versions; final-version and platform evidence remain open |-| P3 | Package identity, contents, executables and notices | In progress: unpublished `@instruktlabs/[email protected]`, aligned engine/plugin identities, MCP launcher, consumer doc allowlist and dependency notices; fresh RC archive checks pass locally, final release audit remains open |-| P4 | Clean installs and workspace upgrades | In progress: RC package passed all platform CI jobs; official 0.10.0-to-RC upgrades pass for Claude/Codex workspaces with conflict refusal, reapplied customizations and byte-exact old assets; final-version harness checks remain open |-| P5 | Release automation and npm publication | In progress: manual exact-archive workflow and owner runbook; GitHub npm-release environment created with sole owner review, no admin bypass and protected branches; live npm trust, staging approval, registry provenance and fresh registry install remain open |-| H1 | Native Cloudflare qualification | In progress: Linux image built, Trixie software renderer passes six textured views; Docker namespace probe fails closed, Bubblewrap launch-argument defect corrected; real Cloudflare isolation/execution, RSS, startup and measured cost remain pending |-| H2 | Authenticated MCP and tenant boundary | In progress: Google/GitHub adapters, permanent D1 account IDs, atomic upstream login guards and current account/epoch checks pass 90 local hosted tests; linking, individual connection revocation, branded real sign-in, container dispatch and evaluator isolation remain open |-| H3 | Artifact lifecycle | In progress: tenant SQLite/R2 bytes, ProgramStore and native AssetLibrary, atomic quotas/revision pins, material closures, authenticated downloads, deletion and seven-day unsaved retention pass local workerd and actual-engine checks; standalone MaterialLibrary, native dispatch, browser tickets, account deletion and deployed lifecycle proof remain open |-| H4 | Capacity and operations | In progress: local native request admission, body/response/deadline bounds and cancellation pass; global operational quotas, process cleanup, load/cost measurements, alerts, deployed health/build identity and rollback remain open |+| P1 | Public API, stability and migrations | Stable contract published: 55 public entrypoints classified, experimental/re-export and deprecated-alias boundaries documented, and explicit 0.10.0/RC-to-stable managed workspace upgrades qualified |+| P2 | Compiled ESM SDK and declarations | Stable SDK published and qualified: compiled ESM/declarations, dependency-free core and optional-peer boundaries; public-registry installs pass across the supported Linux/Windows/macOS matrix |+| P3 | Package identity, contents, executables and notices | Stable published: PR #151 merged as main `fda71ac`; all 12 exact-main CI jobs and release verification passed. Owner-approved staging/promotion completed, and the public archive SHA-256 `6ed3d6b9...1508` and signed provenance independently verified |+| P4 | Clean installs and workspace upgrades | Stable qualified: all seven public-registry jobs pass; fresh Windows archive passes 25 consumer checks; Claude/Codex cached installers render/save/reopen/export; 0.10.0 and RC-to-stable upgrades preserve assets/customizations and refuse conflicts |+| P5 | Release automation and npm publication | Stable published and verified: approved stage promoted after npm security-key authentication, latest=1.0.0, public archive/provenance verified. PR #152 merged as 77dfbc3 after all twelve CI and seven registry jobs passed. GitHub v1.0.0 release/tag and downloaded archive verified |+| H1 | Native Cloudflare qualification | Fixed native qualification and private integrated candidate `c755434` passed. The latter passed ten lifecycle/isolation/quota checks using thirteen of seventeen allowed VM starts; all resources were removed and absence verified. Thirty-five actual VM starts across approved trials are recorded. Latest combined source/image qualification, representative load and settled billing remain open |+| H2 | Authenticated MCP and tenant boundary | In progress in draft PR #153: primary-D1 access/revocation, browser confirmation, Google/GitHub linking/unlinking and durable full-account deletion are implemented and locally tested. A thirteen-check preflight now exercises gateway/token/storage/revocation paths across the prepared six-Worker topology with synthetic accounts and paused native admission. Owner selected in-app security notices only for v1. Live sign-in and final combined-service qualification remain open |+| H3 | Artifact lifecycle | In progress in draft PR #153: native dispatch, private saved assets/material closures, verified evaluator identity, browser download tickets, quotas/retention and account retirement are locally tested. The earlier frozen private trial proves render/save/reopen/export/isolation for its recorded scope; newer material/download/deletion work still needs deployed qualification |+| H4 | Capacity and operations | In progress: shared SQLite admission, global/per-account quotas, operator pause, native cleanup and durable account-deletion recovery are implemented. Launch quota values, representative load/costs, deployed Cron recovery, retention/alerts/escalation, deployed identity and rollback verification remain open || H5 | Production deployment | Pending: approved deployment at `kiln.instruktlabs.com`; live authenticated create/edit/render/save/download/reconnect flow |-| L1 | Local Claude Code and Codex plugins | In progress: both remote Git catalogs and real versioned caches qualified; actual development-to-RC plugin updates preserve pinned workspaces until explicit runtime upgrade, saved assets remain byte-exact and native clients discover one server; final registry/tag distribution and final-version upgrade remain open |-| L2 | Public OpenAI plugin | Pending: compliant ZIP, verified publisher/domain, working MCP, privacy/support pages, review cases/video/account, submission receipt |-| L3 | Anthropic directory | Pending: owned marketplace publication, final source path, account eligibility, reviewer materials and submission receipt |-| V1 | Exact candidate verification | In progress: development builds have pinned local and CI evidence; final RC/version archive and target-host flows remain open |+| L1 | Local Claude Code and Codex plugins | Stable distribution qualified: both actual client catalogs install kiln-engine 1.0.0 and download the exact public npm runtime; real MCP/CLI flows and Codex skill/tool discovery pass. RC and 0.10 workspace upgrades preserve stores. Same-profile RC-to-stable cache updates also pass, retaining the pinned workspace runtime and original saved assets |+| L2 | Public OpenAI plugin | In progress: portable ZIP, hosted skill, listing metadata, review cases and public policy pages are prepared. Existing Instrukt Labs organization is verified in OpenAI's portal. Live MCP, selected publisher/domain proof, owner-reviewed terms, executed cases/demo/review account and submission remain open |+| L3 | Anthropic directory | In progress: portal revalidated 2339681 with the icon warning resolved and two credential policy holds. The listing exposed unsupported chat/Cowork classification; plugin 1.0.1 moves the actual installer to documented bin/ and retains engine 1.0.0. Isolated client installs and workspace flows pass locally. Exact-source platform readback, privacy/data declarations, submitting identity, executable attestation, GitHub push access and submission remain open |+| V1 | Exact candidate verification | Package qualified: exact main fda71ac archive, twelve main CI jobs, release verification, public registry/provenance, seven-platform registry installs, fresh local consumer checks and stable plugin/workspace flows pass. Hosted end-to-end verification remains open || V2 | Release documentation and receipts | Pending: changelog/migrations/install/support/security/privacy/runbook; exact commits, hashes, versions, URLs and separate vendor-review state |## Execution notes+### Authenticated metadata and helper discovery at the edge++The gateway now answers protocol metadata and static helper discovery without+starting a coordinator VM or reserving compute. The OAuth scope, current account+and primary-database connection checks still run first. Source/private-resource+operations and live capabilities retain the admitted native route. Tool and resource+definitions are captured from the actual engine protocol, checked during builds+and compared independently with the real native HTTP host. The Worker bundles only+the pure discovery service and generated catalog, with no native evaluator.++Focused tests first demonstrated missing gateway routing and invalid Discovery+arguments becoming transport errors. Those now pass, including engine-compatible+error guidance and path redaction. An older assertion expected modern server identity+at the top level; it was corrected against the current MCP discovery specification,+which places it in result metadata. Authentication checks also prove that revoked+credentials cannot obtain edge metadata through stale OAuth KV records.++All 245 hosted tests, three hosted typechecks, ten production bundles and root+typecheck/lint pass. The actual gateway bundle is 2,401,079 unminified bytes;+startup CPU and deployed cost remain unmeasured. Source and production-bundle+secret scans are clear. Receipts: `.cache/edge-hosted-tests.log`,+`.cache/edge-source-scan.json` and `.cache/edge-bundle-scan.json`.+The preceding admission commit `892ebd8` passed all eighteen CI checks, including+[engine/package CI](https://github.com/instruktlabs/kiln/actions/runs/37542572710).+Both hosted platforms passed the edge commit `82dd546` in+[run 37544102514](https://github.com/instruktlabs/kiln/actions/runs/37544102514).+Its independent native-image job exposed an unconditional checkout SDK import+in the combined build script. The native-only build now skips that edge dependency;+an isolated-checkout regression first reproduced the failure without `dist/` or+`lib/`, then passed. The image workflow uses that path, while the ordinary Worker+build retains its required metadata check. The build correction needs fresh CI.+Hosted-specific instructions, integrated+rendering, account lifecycle and live qualification remain open.++No cloud upload, compute job, main merge, npm change or deployment occurred. The+approved cloud allowance is still exhausted and the public service is unpublished.++### Shared admission and gateway connection++The gateway now routes MCP through a private service binding that selects one+fixed global SQLite admission object. Artifact downloads stay on the storage+path. Required configuration controls per-account minute/day usage, global+day/month usage, concurrent requests and deadlines. A request reserves capacity+before dispatch and keeps it until its coordinator and children confirm cleanup.+Unknown cleanup stays reserved across eviction and alarm recovery. A separate+operator binding supports durable pause without exposing that control to the+gateway. Launch values have not been adopted from the test fixtures.++Focused tests first failed for the missing controller/entrypoint and the old+gateway routing. An adversarial same-turn cancellation case then reproduced an+unclosed discarded response body; the fix retains and cancels that response even+when the cancellation wins the promise race. Real local workerd tests also cover+concurrent requests, denied-attempt accounting, UTC quota rollover, missing+configuration, operator separation and recovery after eviction. Provider+qualification and an inexpensive edge path for MCP discovery remain pending.++All 237 hosted tests, three hosted typechecks, ten production bundles and root+typecheck/lint pass. The full offline engine suite passes 3,290 tests with two+platform-specific skips and zero failures. Production source and bundle scans+report no secrets. Logs are retained in `.cache/admission-hosted-tests.log` and+`.cache/admission-root-tests.log`; source and bundle scan+receipts use `.cache/admission-{source,bundle}-scan.json`.++The previous commit `83a8272` is now green across all eighteen CI checks. Its+Windows hosted job initially failed one of 221 tests with Miniflare `fetch failed`.+The focused test and all 221 tests passed locally; a single rerun of the failed+Windows job in [run 37540274823](https://github.com/instruktlabs/kiln/actions/runs/37540274823)+passed unchanged. The first transport failure remains unexplained; no test was+weakened or removed. The new changes require their own cross-platform CI.++No cloud upload, compute job, public route, main merge or deployment occurred.+The approved cloud allowance remains exhausted. The stable public package is unchanged.++### Request dispatcher and private tenant bindings++The private request controller now starts a pinned offline coordinator, waits for+readiness and image confirmation, and binds fixed storage/evaluation interceptors+using host-owned loopback props. Tenant selection comes from the request's durable+record. A request allows one active child and at most eight children total, records+each child before dispatch, and withholds its bounded response until the entire VM+tree is confirmed stopped. Failed cleanup remains unfinished for alarm recovery.++The first tests failed for the missing implementation. Follow-up cases reproduced+startup after an expired durable claim and a Node stream-forwarding incompatibility;+both are fixed. The real workerd fixture also demonstrated loss of the custom HTTP+error prototype across RPC. Errors are now converted before crossing that boundary,+preserving intended statuses while redacting unexpected diagnostics. Local workerd+checks use the actual private entrypoints, loopback props, tenant/R2 storage and+eviction: Alice's source remains unavailable through Bob's request object.++All 221 hosted tests, three hosted typechecks, nine production bundles and root+typecheck/lint pass locally. The earlier cancellation commit `432cb2c` passed all+eighteen CI checks, including [engine/package CI](https://github.com/instruktlabs/kiln/actions/runs/37538519458),+[both hosted platforms](https://github.com/instruktlabs/kiln/actions/runs/37538519509)+and [all three installed images](https://github.com/instruktlabs/kiln/actions/runs/37538519558).++The shared admission service, its quotas and the gateway connection are still+pending. The new controller has local orchestration evidence only; it has not run+on Cloudflare and does not enable public MCP. The total approved cloud-job allowance+remains exhausted, with no new upload, compute job or production deployment.++### Durable child cancellation++The private evaluation DO now keeps a single controller and exposes a parent-only+cancellation RPC. Before any child request arrives, cancellation writes a permanent+terminal record that survives reconstruction. During a pending durable claim it+also aborts the live controller, preventing late startup. Active cancellation+persists a recovery flag and alarm and waits for verified whole-instance cleanup;+failed cleanup retains the unfinished job for recovery, even before the original+execution deadline. A completed job remains unchanged by repeated cancellation.++Five focused cases failed before implementation and now pass. An additional+overlap assertion reproduced duplicate destruction from cancellation plus an+alarm; the alarm now joins the same pending cancellation. Local checks pass all+204 hosted tests, three hosted typechecks, eight bundles and root types/lint.+The Node-host commit `f6a7d39` independently passed Linux/Windows hosted checks+and all three image jobs in [run 37537769251](https://github.com/instruktlabs/kiln/actions/runs/37537769251).++The implementation follows the current [Container API](https://developers.cloudflare.com/containers/api/durable-object-container/)+and [alarm contract](https://developers.cloudflare.com/durable-objects/api/alarms/),+including repeated alarm delivery and explicit recovery scheduling. This new RPC+is locally qualified only; the earlier fixed cloud receipts do not establish its+provider behavior. No live job or deployment occurred, and the parent/global+admission implementation remains open.++### Private Node host and installed coordinator image++The native coordinator now has an actual HTTP entry using the maintained MCP Node+adapter, separate from the untrusted evaluator image. The entry selects the remote+evaluator explicitly and requires an exact public HTTPS origin. Socket-level tests+cover the fixed internal Host/path, request limits, stalled uploads and propagation+of disconnects. Invalid startup settings and missing private services fail closed;+there is no fallback to in-process source evaluation.++The focused tests were observed failing before implementation. All 199 hosted+tests, three hosted typechecks and eight production bundles now pass locally.+The prior integration commit `4e7a304` also passed all engine/package checks in+[run 37535301751](https://github.com/instruktlabs/kiln/actions/runs/37535301751),+Linux/Windows hosted checks, both evaluator images and the website build.++The new coordinator image was built with a minimal eight-file context and the+exact published stable archive. Image+`sha256:5402d67069e8b5c9d355e4f49b9ae92d353171b381d27496f85f5794adf95d75`+passes readiness, modern MCP discovery, legacy initialization, foreign-host and+credential rejection, and failure without private services. It advertises the+fourteen actual registry tools. The Docker fixture used no host port, disabled+networking and a non-root, read-only, resource-bounded container; that container+was removed. The image/lock/bundle identities and inventories are retained at+`.cache/native-host-image/qualification/receipt.json`. Both hosting and generated+image locks reported zero known npm audit findings. CI now builds and exercises+this image in a separate job without cloud access or image publication.++These are local coordinator checks, not an extension of the Cloudflare isolation+receipt. No new cloud job, deployment or registry write occurred. The dispatcher+still needs tenant-bound interceptors, whole-job-tree recovery/global admission,+software rendering and complete hosted lifecycle qualification.++### Stable plugin cache updates++Both isolated qualification profiles now have `kiln-engine@instruktlabs` version+1.0.0, upgraded from their existing 1.0.0-rc.1 caches through the actual Claude+and Codex CLIs. Cached provenance inventories verify byte-for-byte. Their managed+workspaces remain pinned to the RC until an explicit workspace upgrade; the+original saved asset hashes and owner notes remain intact. The separate previously+qualified RC-to-stable workspace upgrade is still the intentional next step.+Receipt: `.cache/v1-stable-cache-upgrade.json`.++These test profiles had explicitly selected the development catalog branch,+`codex/v1-publication`. Both CLIs correctly refused replacing a declared catalog+with a different source through `marketplace add`. Only the isolated profiles'+declared ref was changed to `main`, followed by normal marketplace/plugin updates.+The refusals and continuation are retained in the receipts; no normal user profile+was changed. Full before/after workspace snapshots bracket the Codex update and+the repeated Claude refresh. Claude's first update is supported by the CLI's+RC-to-stable result and verification of the original saved file hashes afterward.+Do not recommend deleting a marketplace as the normal upgrade route: Claude's+current CLI documentation states that this also uninstalls its plugins and may+delete plugin-managed data. [Claude plugin commands](https://code.claude.com/docs/en/plugins/cli-reference#plugin-marketplace-remove).++### Native dispatch integration branch++`codex/v1-native-dispatch` combines the published stable source and release record+with the account-controls and provider-qualified controller branches. This is+integration work, not a main merge or deployment. The full README/site refresh+remains a final release task as the owner requested.++The new private evaluator client uses the published SDK's v2 protocol and validates+response identity, GLB and QA through that SDK. Its separate fixed hostname carries+no account selector or credentials and clamps hosted work to 60 seconds, 4 MiB+input/GLB and 8 MiB output. A private evaluation Worker exposes the existing+single-use controller through a bounded HTTP handler, with request reading charged+against the execution deadline and no early return that bypasses job cleanup.+The default Worker route is 404; production bindings are not configured.++Focused tests first failed for the missing client/handler, then exposed a real+cancellation race between receiving headers and attaching a body reader. The+shared native transport now closes that stream on cancellation and other failures.+Adversarial tests cover hostile identity headers, route confusion, mismatched+response IDs, invalid UTF-8, declared/streamed size limits, delayed bodies,+cancellation, redacted errors and no in-process fallback. The real MCP fixture+renders, saves and reconnects using the new protocol transport; a separate fixture+connects the actual native client, private HTTP handler and SDK evaluator together.+These fixtures use fixed trusted source locally and do not extend the Cloudflare+isolation receipt. No new cloud jobs or paid operations were started.++Local qualification on Node 22.23.3/npm 12.2.0/Bun 1.4.2 passes all three hosted+typechecks, all 193 hosted tests and seven production bundles. Root toolchain,+typecheck and lint pass; the full offline engine suite reports 3,290 passed,+two platform-specific skips and zero failures. Logs are retained at+`.cache/native-dispatch-hosted-tests.log` and+`.cache/native-dispatch-root-tests.log`. Cross-platform CI remains the next gate.++The outer tenant-bound dispatcher, global admission, production renderer,+account lifecycle and live-provider verification remain open. HTTP cancellation+alone must never release a global slot while VM destruction is unconfirmed.++### GitHub stable release and final documentation scope++The owner approved the prepared GitHub release. [Kiln 1.0.0](https://github.com/instruktlabs/kiln/releases/tag/v1.0.0)+was published at 21:19:19 UTC on 6 October 2026. Tag `v1.0.0` resolves to+`fda71ac775750f25390b6ee30082ebc56463edc6`, matching the public npm provenance.+The release attaches the 9,155,191-byte published archive and `SHA256SUMS.txt`.+A fresh GitHub download hashes to+`6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`;+the checksum file and remote asset digest agree. The public notes explicitly keep+hosted access and vendor submissions pending. Receipt in the stable worktree:+`.cache/stable-main-qualification/github-release-receipt.json`.++The owner reaffirmed the final documentation pass after the remaining work.+Audit the root README, maintained repo guides and generated/site content for old+package identities, prerelease/default-tag claims, install commands, supported+runtime versions, plugin setup, authentication/hosting availability and deprecated+architecture advice. Reconcile every public promise against the shipped or live+surface. Include the deferred Troy scene images and new user/agent onboarding.+Keep historical review records dated; they are not current installation guides.+Validate the final website build and real navigation/install paths before its+separate approved publication. No broad README or site rollout happened here.++### Stable installed clients, upgrades and native resilience++All twelve engine/package CI jobs in [run 37528755662](https://github.com/instruktlabs/kiln/actions/runs/37528755662)+and seven public-registry installation jobs in [run 37528755713](https://github.com/instruktlabs/kiln/actions/runs/37528755713)+passed. The registry matrix covers Linux Node 20.15/22.2/22.23.3/24.20, Windows+22.23.3 and macOS Intel/Apple Silicon. After explicit approval, PR #152 merged as+`77dfbc35197e372e1039995c2160830ddda8a197`, updating the immutable public+release record. A duplicate manual registry run was cancelled after the automatic+PR run appeared; it is not the qualification receipt.++Fresh isolated Claude Code 2.1.287 and Codex CLI 0.160.1 profiles installed the+stable plugin from the public Instrukt Labs catalog at source `fda71ac`. Their+cached setup helpers downloaded npm 1.0.0, verified its archive integrity and+created managed workspaces. Each workspace completed Discovery, CPU render,+save, process restart, exact retained source and CLI export. Codex's native+app server discovered the cached setup skill, three workspace skills and seventeen+MCP tools at version 1.0.0 without model calls or normal-profile changes.+Receipts: `.cache/v1-stable-remote-plugin-install.json`,+`.cache/v1-stable-plugin-workflow.json` and+`.cache/v1-stable-codex-appserver.json`. An initial redundant app-server refresh+raced its startup refresh on Windows; the failed receipt remains separate. The+successful check uses the catalog already installed by the CLI.++Explicit upgrades from the public RC runtime and the verified official 0.10.0+archive passed for both harnesses. Check-only and conflicting launcher updates+changed no files; resolved upgrades preserved saved source/GLB/preview bytes,+revision parents and owner files. Compatible edits to unchanged guides survived.+The upgraded MCP rendered retained source, saved child revisions and exported the+exact edited source through the CLI. Receipts:+`.cache/v1-stable-rc1-upgrade.json` and `.cache/v1-stable-v010-upgrade.json`.+The first RC test incorrectly expected an unchanged customized guide to conflict;+it actually upgraded successfully. Its failed assertion is retained in+`.cache/v1-stable-workspace-upgrade.json`. The corrected probe tests a changed+launcher conflict and preservation of an unchanged customized guide. No engine+change or weaker upgrade rule was needed.++After the owner's twelve-job/$1 approval, native source `d068a7c` passed all+fixed Cloudflare cases: CPU preview, six software material views, native network+denial, marker/child destruction and fresh-VM absence, native deadline,+cancellation, stdout/stderr floods, actual memory exhaustion, actual durable alarm+recovery and engine execution afterward. Downloaded Worker and image identities+matched the approved candidate. Every VM was confirmed stopped by the controller+and independently by the provider API. Replaying the RPC started no new jobs.+All seven returned PNGs decoded independently and matched local references byte+for byte; visual inspection confirmed the fixed geometry/material/backdrop views.++The operator, application, Worker, both namespaces and registry tag were removed,+with absence verified. All 22 jobs across the four approved scopes are consumed.+The 101,532 ms total reported job time is not billed CPU, a load benchmark or a+settled invoice. The diagnostic branch's `hosting/probe/RESILIENCE.md` and+`.cache/resilience-trial/` retain the exact twelve-case and cleanup receipts.+Authenticated native dispatch, production render integration, account lifecycle,+private artifacts, global admission, live providers, production deployment and+vendor submissions still remain. Broad README/Troy/site work stays deferred.++### Stable publicly published++The owner approved the protected environment and+[staging run 37525019084](https://github.com/instruktlabs/kiln/actions/runs/37525019084)+completed successfully. npm reports stage+`6b1a5f9f-36f7-465d-ba81-9c47e5d83e66` as `staged`, version `1.0.0`, intended+tag `latest`, published by trusted automation. Downloading that exact stage+reproduced SHA-256+`6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`.+Sigstore verification passed for the main-branch release workflow identity,+GitHub Actions issuer, exact commit `fda71ac775750f25390b6ee30082ebc56463edc6`,+staging run and archive digest against+[Rekor entry 3116120928](https://search.sigstore.dev/?logIndex=3116120928).+The local receipt is retained in the stable worktree at+`.cache/stable-main-qualification/provenance-receipt.json`.++The owner's environment approval authorized private staging only. The owner then+separately approved public promotion of this exact stable candidate and completed+npm security-key authentication. The CLI confirmed successful publication.+Public registry metadata now reads `latest = 1.0.0`, with `next = 1.0.0-rc.1`.+The independently downloaded public archive matches the digest above, and its+public Sigstore provenance verifies against the same workflow, commit, run and+archive. The npm website also displays `1.0.0`, Public. No production hosted+deployment has occurred.++[PR #152](https://github.com/instruktlabs/kiln/pull/152) updates the public candidate+record to stable so the seven-job registry installation matrix can qualify the+published version. [Run 37528755713](https://github.com/instruktlabs/kiln/actions/runs/37528755713)+was dispatched at `6248b4c`. The fresh local Windows installation passed all 25+checks, including SDK declarations, CLI, MCP and packaged plugin checks; its+receipt validator accepted the exact public archive on Node 22.23.3/npm 12.2.0.+Receipts and the npm screenshot are retained under the stable worktree's+`.cache/stable-main-qualification/public-registry/`.++Independent hosted resilience work continues: native cancellation,+deadline/output/memory bounds, actual durable-alarm recovery and stable-image+rendering are being prepared for local verification and a separately approved+Cloudflare trial. No new cloud trial allowance has been requested or consumed.++### Stable exact-main qualification++Main `fda71ac775750f25390b6ee30082ebc56463edc6` passed every job in+[CI run 37523234644](https://github.com/instruktlabs/kiln/actions/runs/37523234644),+including both engine platforms, the installed package matrix and six software+Vulkan images. The downloaded archive SHA-256 is+`6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`.+[Release verification 37524905058](https://github.com/instruktlabs/kiln/actions/runs/37524905058)+validated repository/commit identity, all CI jobs, the archive and all eight+qualification artifacts. Its downloaded archive independently matches that digest.++The protected `npm-release` environment still requires the owner as sole reviewer,+forbids administrator bypass and allows only protected branches. The same main+commit and digest were dispatched for staging in+[run 37525019084](https://github.com/instruktlabs/kiln/actions/runs/37525019084).+Its verification passed and the staging job is waiting for the owner's browser+review. No new package version has been uploaded or promoted at this point.+Public metadata still reads `next = 1.0.0-rc.1` and `latest = 0.0.0-stage`.+The concrete handoff was opened in Chrome with `npm-release` selected. Final+promotion remains a separate owner decision and npm security-key step.++The native startup branch separately adds stopped-state confirmation to the+production controller at `d3e6ac7`. It withholds output and retains durable+recovery when destruction cannot be confirmed. Focused regression tests first+failed, then all 136 hosted tests, hosted/root types, lint and production bundle+checks passed. Exact-source CI and further live failure-path qualification remain+pending at that point; the completed four-job allowance does not authorize another cloud run.++Subsequently, `d3e6ac7` passed both Linux and Windows hosted checks in+[run 37525915541](https://github.com/instruktlabs/kiln/actions/runs/37525915541).+The separate software-image candidate at `b34d56f` passed both CPU and software+image CI jobs in [run 37526078285](https://github.com/instruktlabs/kiln/actions/runs/37526078285).+Those image CI jobs use the public RC. Independently, the exact stable archive+was installed in local image+`sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99`:+the real entry produced the expected GLB twice, the CPU preview passed, and the+packaged software Vulkan renderer produced all six textured views. Its retained+npm lock has zero known audit findings. The local containers were removed.+These results do not qualify that new image on Cloudflare or authorize its upload.+- Created `codex/v1-publication` from the current main checkout without alteringthe four existing untracked planning/setup documents.- Confirmed Bun 1.4.2 is installed. Default shell Node/npm differ from maintainer@@ -1248,8 +1622,9 @@ Verification passed. Downloaded `npm-release-review`, inspected `review.json` anindependently matched its archive digest. The stage job was skipped as intended.All 15 checks on hosted identity PR #146 at `255df6a` also passed; that PR remainsunmerged and does not change this npm candidate. The owner staging/access-setup-question is now pending because first-time npm staging creates a public placeholder.-No npm package has been staged or published, and no hosted service has been deployed.+question was pending at this checkpoint because first-time npm staging creates a+public placeholder. The subsequent authorized setup is recorded below. No hosted+service has been deployed.## Owner handoffs@@ -1273,4 +1648,1662 @@ those results. No identity app or secret has been provisioned yet.The initial npm browser login did not complete and its terminal-password fallbackwas cancelled. The fresh owner-attended attempt succeeded, as recorded above.Trusted publishing configuration, exact-archive staging and owner promotion remain-separate steps. No package has been staged or published yet.+separate steps, with subsequent progress recorded below.++## npm bootstrap and package protections++The owner explicitly approved staging the verified RC and configuring stage-only+GitHub publishing access. The exact archive above was uploaded using npm 12.2.0+with lifecycle scripts disabled and local provenance disabled only for bootstrap.+npm created stage `36c3dbd9-5908-4e0c-b394-b08e12379e31` and the public+`0.0.0-stage` holding version. The RC itself was not promoted. The package website+confirmed the placeholder even while public registry metadata was still returning+404; these are different observations, not evidence that no public write occurred.++Owner security-key authentication completed the trusted publisher configuration:+repository `instruktlabs/kiln`, workflow `release.yml`, environment `npm-release`,+permission **npm stage publish only**. npm's Settings UI independently showed+those values. A second owner security-key step saved **Require two-factor+authentication and disallow bypass 2fa tokens**; the success notification and+selected setting were verified. No bypass token or `NPM_TOKEN` was created.++As prescribed by the runbook, the bootstrap was rejected with owner 2FA after+trust was saved. The CLI confirmed rejection and `npm stage list` returned an+empty list. This removed only the temporary unpromoted stage, not the package or+its settings. The exact archive remains retained in the CI artifacts and locally.++Rechecked main, successful source CI, archive digest and the GitHub environment:+sole owner reviewer, protected branches only, no administrator bypass. Dispatched+[staging run 37477014656](https://github.com/instruktlabs/kiln/actions/runs/37477014656)+from unchanged main with the same CI run and digest. Its verification job passed;+the owner approved the GitHub environment review, and the stage job succeeded.+npm stage `6f426dc2-d6b6-41a8-9ccf-874342bd7089` is `1.0.0-rc.1`, tag `next`,+actor `GitHub Actions` / `trusted automation`. Its registry validation completed+with status `staged`. No RC promotion or stable 1.0 publication has occurred.++Downloaded that stage from npm and independently matched its 9,154,941 bytes and+SHA-256 to the approved archive. npm recorded signed provenance in+[Sigstore log entry 3110722988](https://search.sigstore.dev/?logIndex=3110722988).+The Rekor entry stores the signed payload hash rather than the statement itself.+Reconstructed the expected statement using npm 12.2.0's deterministic schema and+the verified archive SHA-512, then required its exact SHA-256 to match Rekor's+`79449664bc6e679b694bcae73b78d26023b3df2f97eca215672c50fc8686c3a3`.+Reassembled the verification bundle from that statement and the public certificate,+signature, inclusion proof and signed timestamp. npm's installed Sigstore verifier+successfully checked the bundle against its TUF trust root and the required+GitHub Actions issuer and workflow identity. The verified statement binds the+package/version/archive to repository `instruktlabs/kiln`, `release.yml`, main+commit `ce640ccae0c621177aad176a03b5a214ae57d266` and run `37477014656` attempt 1.+This was verification only; no new signature or provenance was generated locally.+Retained `.cache/npm-stage-provenance-receipt.json` and+`.cache/npm-stage-verified-provenance.json`. Public promotion is now awaiting+the separate owner approval required by the runbook at this checkpoint; its+subsequent promotion and public-registry verification are recorded below.++## Cloudflare evaluation controller implementation++The private host now has a one-job container controller with a durable claim and+deadline alarm recorded before compute starts. It requires a pinned image digest,+disables internet, sends no storage or identity credentials, bounds request/stdout/+stderr bytes, and destroys the whole VM before returning output. Cancellation,+startup failures, output flooding and deadlines converge on that cleanup. Failed+cleanup suppresses success and leaves a durable alarm to retry. Completed job IDs+remain unavailable for reuse. Returned bytes still require the engine's strict+versioned result validation outside the VM.++The companion one-shot entry imports the compiled engine package, accepts one+bounded UTF-8 request and emits one canonical evaluator response. It is designed+only for an externally isolated VM; its in-process handler and JavaScript timeout+do not provide a security boundary. Fixed trusted fixtures passed deterministic+GLB, malformed-envelope, invalid-UTF-8 and oversized-input checks on the development+host. Nine controller tests passed for orchestration and cleanup. These checks do+not establish Cloudflare isolation, image deployment, hostile-source containment+or production routing. Those gates remain open.++With these additions, the local hosted suite passed **103/103** tests. Both hosted+TypeScript configurations, all five existing production bundle builds, repository+lint and whitespace checks passed. The new controller and entry are not yet wired+into a deployed Worker. Receipts: `.cache/v1-container-entry-before.log`,+`.cache/v1-container-entry-after.log`, `.cache/v1-container-hosting-full.log`.+The work is in draft [PR #147](https://github.com/instruktlabs/kiln/pull/147),+stacked on #146. Both Linux and Windows checks passed in+[hosted CI 37477551252](https://github.com/instruktlabs/kiln/actions/runs/37477551252)+at `7ac3b23`.++An independent storage regression found during the full hosted suite was fixed in+`76ef646`: creation and seven-day expiry now derive from one clock read. A focused+advancing-clock test failed before the change and passed afterward. The fix is on+hosted identity PR #146; both hosted CI platforms passed. It does not change the+frozen main-branch npm archive.++## Public release candidate promotion++The owner explicitly approved public promotion of the verified RC under `next`+and completed npm's security-key authentication. `npm stage approve` succeeded+for stage `6f426dc2-d6b6-41a8-9ccf-874342bd7089`. The public registry independently+confirmed `@instruktlabs/[email protected]` and `next=1.0.0-rc.1`. `latest` remains+`0.0.0-stage`; users must select `@next` or the exact RC version until stable+1.0 is published. This is a published prerelease, not completion of the v1 goal.++Fetched the tarball from its public npm URL without authentication. Its bytes,+SHA-256 and SHA-512 integrity match the approved candidate. Downloaded the public+registry provenance bundle and verified it with Sigstore against the GitHub Actions+issuer and exact workflow identity. Its statement exactly matches the independently+verified staging statement, including package digest, source commit and workflow+invocation. Public receipts are retained in `.cache/npm-public-rc1/`.++Installed that public-registry archive into a fresh Windows x64 consumer directory+using Node 22.23.3 and npm 12.2.0. All 25 package checks passed, including SDK imports+and consumer types, CLI, CSG/UV WASM, CPU PNGs, the compiled evaluator, MCP discovery,+source editing/export, restart persistence, and the local plugin bundle. The receipt+validator accepted its exact runtime, package version, digest and required checks.+This verifies Windows consumption of the public archive; the remaining public-+registry platform matrix and actual plugin harness installation remain open. The+prepublication exact-archive platform matrix is separately complete.++The package remains `@instruktlabs/kiln`; `next` is a distribution tag, not part of+its name. Stable `1.0.0` will be assigned `latest`, allowing the plain install+command. Source checkout documentation now states the RC publication status.+Stable publication, hosted deployment and directory submissions remain incomplete.++## Installed container image and public-registry matrix++The private CPU image built successfully on Linux amd64 in+[run 37479877969](https://github.com/instruktlabs/kiln/actions/runs/37479877969)+at `4267b2053236a012c590a23b62f82d5760b38bd7`. Its four-file build context contained+only the Dockerfile, one-shot entry, approved public archive and archive checksum.+The fixed trusted fixture ran in two fresh containers with networking disabled,+one CPU, 6 GiB memory, 128 processes, dropped capabilities and no new privileges.+Canonical response decoding passed; both returned the same 1,912-byte GLB with+SHA-256 `f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40`.+The receipt explicitly leaves Cloudflare and hostile-source qualification false.+Image metadata, installed dependency lock, OS inventory and runtime version are+retained in the run's `private-evaluation-image-evidence` artifact and locally+under `.cache/image-ci-37479877969/`. No image was published or deployed.++Public-registry [run 37479877736](https://github.com/instruktlabs/kiln/actions/runs/37479877736)+passed all four Linux Node versions and both macOS architectures. Windows completed+all 24 functional checks but correctly failed receipt validation: the child helper+selected bundled npm 10.9.9 instead of the globally upgraded 12.2.0. The workflow+now passes the selected global npm CLI explicitly and checks its version before+running the package fixture. The required npm version was not relaxed. This+workflow correction still requires a successful Windows CI receipt.++Docker Desktop was installed locally but its Linux engine was stopped when first+queried. After the owner started it, `docker info` successfully reported server+29.5.3, Linux, x86_64. No reinstall, privilege change, seccomp relaxation or Windows+service reconfiguration was needed. This resolves local image-build availability;+it does not resolve the separate historical Bubblewrap namespace probe or qualify+Cloudflare isolation.++The corrected public-registry [run 37480967896](https://github.com/instruktlabs/kiln/actions/runs/37480967896)+passed all seven jobs at `3a5d00a8a35f9434d42aae4d39ef5824916d9539`. Downloaded+every receipt and verified `status=passed`, all 24 required checks, package name,+RC version and the approved archive SHA-256. Linux covered Node 20.15.0, 22.2.0,+22.23.3 and 24.20.0; Windows x64 and both macOS architectures covered Node 22.23.3.+The Windows receipt now records npm 12.2.0. Evidence is retained under+`.cache/registry-ci-37480967896/`. This closes the public-registry platform matrix,+not stable publication or actual agent-harness plugin installation.++The local Docker build subsequently passed its own two fresh-container fixtures.+Its immutable image ID is+`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`;+both GLBs match the Linux CI fixture's digest above. The local image's metadata,+dependency lock and OS/runtime inventory are in `.cache/evaluation-image-local-evidence/`.+Only the named test containers were removed; the qualified local image is retained.++## Private Cloudflare availability candidate++Prepared the bounded [probe and teardown plan](../../hosting/probe/README.md).+It has no public HTTP routes or external bindings, uses five fixed sequential+jobs, and atomically claims its run once. The first failure stops the batch;+interrupted claims do not automatically spend again. The production image is+unchanged; native boundary fixtures exist only in the separate probe Worker.+Production bundle builds now reject both test and probe helpers.++Three initial run-control tests failed before implementation and passed afterward.+A fourth workerd integration check verifies loopback namespace routing, closed+HTTP access and retained failure when no real container is bound. The full hosted+suite passed **107/107**, all three TypeScript configurations and five production+bundles passed, and repository lint passed. `@cloudflare/[email protected]` is a pinned+private development dependency for validating the cf beta Build Output; it does+not enter the engine package or production Worker bundle.++The final probe Worker bundle is 13,190 bytes, SHA-256+`6babbbb9073fbb4514b03675d73ee1387f30099cd6174cfca7ac8bc6515cc2e0`.+`[email protected] deploy --prebuilt --dry-run` succeeded for the prepared private+Worker and `durable_object` container application. No upload, deployment, cron+provisioning or live probe was performed. Its managed-registry image reference is+the intended destination, not evidence that the image has been pushed. Retain the+actual returned registry digest and deployed identities after the concrete owner+approval. Estimated container metering is about $0.012 for the five-job worst-case+runtime; the proposed total trial allowance is $1, not a provider-enforced cap.++Availability is only the first provider gate. Native memory exhaustion, output+floods, cancellation/deadline races, controller interruption recovery, CPU images,+software Vulkan, measured startup/costs and authenticated storage/MCP integration+remain separate required work before hosted launch.++## Public-registry plugin qualification and documentation refresh++Re-read the current [OpenAI packaging](https://developers.openai.com/plugins/build/plugins),+[submission](https://developers.openai.com/plugins/deploy/submission),+[Claude Code installation](https://code.claude.com/docs/en/discover-plugins),+[publication](https://code.claude.com/docs/en/plugins/publish) and+[Anthropic portal checks](https://claude.com/docs/plugins/pre-submission-checklist)+on 6 October. The plan's distinction between owned marketplaces, directory+submission and an Anthropic partner's curated-marketplace listing still applies.+Portable OpenAI manifests and `.claude-plugin/plugin.json` remain appropriate.+Claude Code 2.1.287 strict validation passes without warnings. Codex CLI 0.160.1+provides the native marketplace/plugin commands used for qualification.++Claude fetched `https://github.com/instruktlabs/kiln.git#main`; the downloaded+commit was exactly `ce640ccae0c621177aad176a03b5a214ae57d266`. GitHub shorthand+selected an unavailable SSH identity on this machine, and a full SHA in Claude's+`#ref` position was rejected as a missing remote branch. Explicit HTTPS plus a+branch/tag works; inspect the resolved commit rather than claiming SHA-selector+support. Installation was scoped to a separate qualification workspace. The old+user-scoped `kiln@kiln` 0.6.0 installation was already disabled and was not changed.++Codex refreshed a Git marketplace pinned to that exact SHA with per-invocation+configuration and materialized the RC in its normal versioned plugin cache.+Its app server discovered the cached `kiln-engine:kiln-setup-workspace` skill,+the workspace's three author/refine/QA skills exactly once, and `kiln_workspace`+with all seventeen tools and server version `1.0.0-rc.1`. No model turn, profile+relocation, permanent Codex configuration edit or authentication change was used.+The experimental app-server interface is qualification tooling, not a product+dependency. Both cached plugin inventories match their recorded file hashes.++The cached installer downloaded the exact public RC without `--archive`. The+installed lockfile records the approved public tarball URL and SHA-512 integrity.+Both cached helpers then accepted their fresh managed workspace with `--check`.+Claude's actual MCP connection check passed with a fixture-only, server-specific+trust option. A standard MCP client exercised each generated workspace's installed+server: capability identity, CPU images, save, process restart, exact source+recovery and CLI GLB export all passed. Capability receipts point to the installed+public package outside either plugin cache and report the RC engine/build identity.+These fixed-fixture checks do not claim a model-authored asset or vendor approval.++Receipts: `C:/Users/Mattm/X/kiln-dogfood/plugin-rc1-2026-10-06/codex-receipt.json`+and `workflow-receipt.json` beside it. Probe helpers are retained under+`.cache/registry-plugin-{codex-probe,workflow}.mjs`. Failed diagnostic assumptions+(quoted CLI override key and JSON-only Discovery text) were corrected in the+probe; no engine behavior or acceptance criterion was relaxed.++The current repository contains 3,944 blobs totaling 92,216,785 bytes; a local+Git ZIP of the exact main commit is 41,453,102 bytes. These are preliminary size+checks against Anthropic's repository limits, not a substitute for the actual+GitHub archive and portal validation of the final source. Stable-version plugin+updates, final public distribution and both directory submissions remain open.++## First private Cloudflare attempt and cleanup++The owner approved the bounded five-job, $1 trial. Source `ea08a16` was uploaded+using cf 1.0.0-beta.12. The registry returned the unchanged local image digest+`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`.+An independent download of the deployed module matched the prepared Worker+SHA-256 `6babbbb9073fbb4514b03675d73ee1387f30099cd6174cfca7ac8bc6515cc2e0`.+Worker metadata verified no public routes, workers.dev or preview URLs and no+external references. Version `d4225ffb-9951-49a6-9f8d-281542d3ab9d` belonged to+deployment `479434b1-c5cd-4f18-b1db-88d51e9d5fce`; application/job namespace+`e8d89496082f4e63961a8793eed7f1bf` and coordinator namespace+`2256b6871cbc4661a2d7525a48d9fc3a` were created only for this trial.++At 15:25:18 UTC on 6 October, the first `engine-a` job failed after **2,048 ms**+with `WORKER_FAILED`; Cloudflare logged internal-error reference+`oe4cvciv5rmllufovr4m5gcm`. The retained result has `stopped=true`, and the run+finished after exactly one result. All four remaining fixtures were skipped.+Provider queries showed zero active/starting instances. The operator deleted the+exact trial application, Worker and image; follow-up reads returned no application+or image, a Worker 404, and neither trial namespace. Other account resources were+left in place. Receipts are retained under `.cache/provider-probe-trial-1/`.+Actual billed usage is not yet settled; the $1 figure is the approved allowance,+not a provider-enforced cap or a measured bill.++The current [native API documentation](https://developers.cloudflare.com/containers/api/durable-object-container/)+states that user/group names cause native `exec` errors. This image's named `node`+identity resolves locally to `1000:1000`. A focused test rejected the old omitted+identity; explicitly passing numeric `1000:1000` now passes. This changes file+ownership selection, not the VM isolation boundary. The provider failure is only+plausibly explained until the corrected code runs successfully. The operator+probe additionally records the first failed native API method without exposing+raw errors or output. Both observation tests failed before implementation.++The continuation uses the same immutable image and at most **four remaining+jobs**, preserving the aggregate five-job/$1 authorization. It removes the+redundant second provider box fixture rather than increasing that scope. Any+successful provider GLB will be compared with the independently qualified+local/CI digest; two-run provider determinism is not claimed. Updated local gates:+**110/110 hosted tests**, all three TypeScript configurations and all five+production bundles pass. Production bundles exclude the operator-only observer.+Repository lint and the corrected private deployment dry run also pass. The+continuation Worker is 14,130 bytes with SHA-256+`8ed395851f30e935d874f79af62f6a33db2098de6fc24745d54af0f3741941ac`;+its preparation receipt is `.cache/provider-probe-numeric-user-candidate/build-receipt.json`.++## Main merge, identity setup and security review++The owner approved PR #146 at `76ef64648c3ce91d65140a43b806dcfcf3fb3af0`.+GitHub rejected a merge commit under repository policy; the same approved change+was squash-merged without bypassing protection. Main is+`8d14d0e0ca89fe3ef860ff6d3568e5647a382c53`. CI run `37491254733`, hosted checks+`37491254766` and website build `37491254759` all passed on that exact commit.+No package publication or service deployment resulted from the merge. PR #147+now targets main, and its branch incorporates that main revision.++The owner selected the existing signed-in Google account for a dedicated Kiln+identity project. `instruktlabs-kiln-auth` was created with display name Kiln.+The Google Auth Platform is not configured yet: no OAuth client or client secret+has been created, and no compute, billing or Google Cloud Run service was added.+Hosting remains on Cloudflare.++The actual GitHub ZIP of `ce640ccae0c621177aad176a03b5a214ae57d266` is+41,888,908 bytes, contains 4,736 entries and expands to 92,216,785 bytes. SHA-256:+`00e910c53cf75740fb2d6693853e01ef7d9d45277c64f14325adddea2b5a61ed`.+The plugin contains nine files, the largest 15,026 bytes. This passes the checked+Anthropic archive limits; portal validation and submission have not occurred.+The final stable archive must be measured again. The receipt is+`.cache/anthropic-github-main-archive-receipt.json`.++The owner requested adversarial security review, now tracked in+[the security record](2026-10-06-v1-security-review.md). Repository secret scanning+and push protection were enabled; no open secret alerts were returned. An actual+stream-deadline defect was reproduced and fixed with failing-then-passing tests.+All 112 hosted tests, typechecks, production bundle builds and root lint pass.++The owner explicitly deferred the broad public README/site documentation refresh+until stable 1.0 and the public hosted service are verified. The queued refresh+includes Troy scene pictures, npm installation, local agent/plugin onboarding,+hosted setup and matching website/agent-readable content. Internal execution and+security records continue now; accurate privacy, support and sign-in pages remain+part of the hosted candidate. No public README/site refresh or Troy picture+publication was performed during this checkpoint.++## Corrected private trial: scheduling limitation and cleanup++The corrected source `aabc798437184ae4ef5a5b40a5b4de00beca5624` was deployed at+15:42:31 UTC on 6 October. Its downloaded Worker matched the prepared SHA-256+`8ed395851f30e935d874f79af62f6a33db2098de6fc24745d54af0f3741941ac` and retained+the original immutable image. Version `d8199c93-e870-40a6-9338-9c8c27bd141e`+belonged to deployment `517e21c9-d3dc-4082-904d-149a7f9cd593`. The Worker had no+public HTTP route, workers.dev or preview URL, credentials or user assets.++The configured five-minute cron produced no observed invocation, log event,+coordinator object or container instance. Reapplying its exact trigger at+16:12:47 did not resolve this. At 16:22:10, a separate private 278-byte scheduler+(`kiln-private-probe-trigger-20261006`) was deployed with only a binding to the+existing coordinator. It called the same `availability-rc1` durable claim, adding+no job, run state, image or allowance. Its downloaded module matched SHA-256+`27233d5b3ce584d6c7ad1de140ebf92f244277419adc6c226d6fa561cf38b40d`; private URL+settings and the exact binding were independently verified. This also produced+no observed event. The cause is unconfirmed; the result does not demonstrate that+the corrected evaluator failed or that Cloudflare cannot run it.++At 16:54:51, both telemetry queries remained empty; the coordinator-object and+container-instance lists were also empty. This exceeded the documented 15-minute+cron propagation window and 30-minute new-worker event-history window for the+helper. Cleanup removed the helper first, followed by the trial application,+original Worker and registry image. Follow-up reads returned 404 for both Workers+and the application, no matching image and neither trial namespace. Other account+resources were preserved. Receipts: `.cache/provider-probe-trial-2/`.+No successful provider evaluation/isolation result or settled billing total is+claimed. The aggregate five-job/$1 authorization was not reset or expanded.++## Security fixes and business support identity++Commit `abe5a44538251ebc5d7b5051a25eec1d74200233` adds tested request cancellation,+elapsed-time and bounded-buffer handling, plus targeted transitive dependency+patches. All 3,290 local engine tests, the coverage ratchet, 116 hosted tests,+typechecks, lint and the full local website build pass. Linux/Windows hosted CI,+the private image, public-registry checks and the Linux website workflow pass on+that commit. All twelve engine/package jobs in run `37498513040` also pass,+including the installed Linux software-Vulkan renderer. The Linux website job+qualifies the two symlink assertions that Windows could not execute locally.+The separate native preflight remains unsuccessful. See the security record for+audit scope, the remaining build-only advisory and release limitations.++The owner selected `[email protected]` for the public support identity.+Cloudflare routing was configured and verified active, forwarding that address+to the existing verified inbox without changing other aliases. The owner then+created and secured a free Google Account using that address. After explicit+approval, the account received only `roles/oauthconfig.editor` on+`instruktlabs-kiln-auth`; the existing personal account remains project owner.+The owner accepted the first-use Cloud Console terms and Google's API User Data+Policy. Kiln's OAuth application is now created in external testing mode, with+the business support address and `[email protected]` as developer contact.+The narrowly scoped account can manage branding, although the overview metrics+page separately asks for `serviceusage.quotas.get`; no extra role was granted.+No OAuth client or client secret has been created, and outgoing support replies+still need configuration and testing. No paid Google Workspace subscription,+Google compute service or billing account was added.++## Private invocation continuation++Cloudflare documents remote development service bindings as a route to deployed+Workers and their Durable Objects. The operator probe now exposes only a named+`KilnProbeControl.runFixed()` RPC, accepting no source, commands, fixture selection+or run ID. Both HTTP handlers still return 404. Its prepared deployment removes+the cron and retains the four remaining fixed jobs, atomic run claim and original+immutable image. This changes invocation, not the isolation or cost allowance.++A workerd integration test first failed because the entrypoint did not exist,+then passed with the implementation; it covers fixed execution, HTTP denial and+retained results on retry. All 117 hosted tests, typechecks, five production+bundles and root lint pass. The prepared 14,432-byte Worker has SHA-256+`e3f30d81e40f19cb63f49d2879cb7684e9c2bad5e8f76808685d4b5233e7d3a1`;+`cf deploy --prebuilt --dry-run` passes. This candidate has not yet run remotely.+Receipts: `.cache/security-review-2026-10-06/probe-rpc-*.log` and+`.cache/provider-probe-rpc-candidate/build-receipt.json`.++### Direct invocation result and cleanup++Source `cfbcb2a5f3116ece4fa21ce4dc6967f842290e68` was deployed at 17:11:54 UTC.+Downloaded code matched the prepared hash. Version+`b4755a77-5835-4de5-84ea-c548d755294c` belonged to deployment+`18d6f30e-b729-4b32-bca8-017dd393ad9b`; the application was+`0772425387194d20804b5222688b8f26`. Both public URL flags were false and no+domain or scheduled trigger was deployed.++On Windows, `cf dev` failed with `spawn EFTYPE` before starting its backend.+The installed Wrangler 4.147.0 backend was launched directly with the same+`cloudflare.config.ts` and its documented experimental configuration mode. It+established the remote service binding; the local operator listened only on+127.0.0.1 and rejected browser-origin requests. No source or arbitrary command+could be submitted.++The direct RPC reached the deployed coordinator. Its first `engine-a` case failed+after 2,038 ms with `WORKER_FAILED`; the first failed native operation was+`monitor`, and Cloudflare returned internal-error reference+`3fp1nn0uot4akgi20vs4fdjs`. The VM was confirmed stopped and all later cases were+skipped. Repeating the RPC returned the exact retained result without another+job. No container instance remained. Numeric exec identity did not resolve the+failure; successful engine execution and isolation remain unqualified.++The local operator was stopped, then the exact cloud application, Worker and image+were removed. Follow-up reads returned 404 for the Worker and application, neither+trial namespace existed, and no matching registry image remained. CLI deletion+initially declined noninteractive confirmation despite returning exit code zero;+the operator detected this through readback and completed the authorized cleanup+using `--force`. Receipts: `.cache/provider-probe-trial-3/`.++Two jobs have now been attempted in total, leaving three of the original five-job+allowance. The four-case candidate must not be redeployed to a new coordinator:+doing so would exceed that remaining allowance. Further trials need a revised+bounded candidate and diagnosis of the startup failure, not a new run ID or an+automatic retry. No settled billing total or successful native hosting is claimed.++With explicit owner approval, the prepared P4 diagnostic was submitted to+Cloudflare as case `02363339`. The portal confirmed receipt. It includes the error+reference, time and runtime configuration, with no credentials, user assets or+attachments. No provider response has been received. The confirmation is retained+in `.cache/provider-probe-trial-3/support-case.json` and its screenshot.++## Browser account access continuation++PR #147's exact head `7f4e98ebc3691bf025e7ea712d8ef549c4d6a516` now has successful+engine/package, Linux/Windows gateway, installed image, seven-platform public+registry and website checks. The separate restricted-Docker native preflight still+fails. Neither this status nor the support case qualifies native hosting.++The separate `codex/v1-account-controls` branch adds real D1 browser sessions,+direct Google/GitHub account sign-in and browser logout. Callback adapters remain+shared with MCP authorization; direct account access does not invent an MCP client+or issue downstream tokens. Independent browser bindings, purpose/origin-separated+state hashes and atomic D1 consumption prevent stolen or concurrent callback reuse.+No upstream token reaches a browser cookie or asset service.++Session credentials are 256-bit random host cookies with only their SHA-256+verifiers retained. Primary-backed checks enforce account state/epoch, 30-minute+idle and 24-hour absolute expiry. Fresh sign-in rotates the current browser's+session; an eight-session account cap does not discard another device during a+rotation. The focused cap test exposed that ordering defect before its fix.+Logout requires the session's CSRF proof and exact Origin and leaves existing MCP+connections usable. Browser cookies and MCP tokens cannot substitute for one another.++The new cases were first observed failing, then fixed. The focused account and+authentication suite passes 43 tests; the complete hosted suite passes 138 tests,+all three hosted type configurations and five production bundles. Additional+adversarial cases cover expired intents, rollback, provider swapping, bounded+pending-login storage and same-browser concurrent replay. Receipts are in+`.cache/security-review-2026-10-06/browser-*.log` and `account-*.log`.++The root gate also passes 3,290 tests with two platform skips, typecheck and lint.+Two further failing-then-passing build tests ensure extracted provider/browser+modules cannot enter tenant or native bundles. Candidate secret scans are redacted;+no secrets were found in the staged source patch or rebuilt hosting bundles.++The account page has local desktop and 375px presentation evidence, with no+horizontal overflow and 44px sign-in buttons. Google's current pre-approved PNG+is embedded unmodified, avoiding external image/font/script requests; provenance+is recorded in `hosting/assets/README.md`. The preview uses only disposable local+fixture identities and is not evidence of live Google/GitHub authentication.++Provider linking/unlinking, purpose-bound sensitive-action reauthentication,+individual connection revocation, complete account/asset deletion, public admission+limits, privacy pages and deployed user flows remain open. A fresh OAuth callback+is not being presented as proof of a fresh password or MFA challenge. No production+deployment or npm publication occurred in this continuation.++## Startup research and current status refresh++The owner requested further documentation/community research before treating the+native error as a vendor blocker. The [startup review](2026-10-06-cloudflare-startup-review.md)+records the current API/SDK comparison, related public reports, limits of the+existing diagnostics and a smaller managed-image/custom-image sequence. No new+cloud execution, provider change or support message occurred in this review.++PR #149's exact `11a4f64` now passes both Linux and Windows hosted jobs in+[run 37507203413](https://github.com/instruktlabs/kiln/actions/runs/37507203413).+The working tree additionally implements primary-backed connection records,+single-use code activation, protected-request revocation checks and browser-bound+provider confirmation for disconnect. All 144 hosted tests and three TypeScript+configurations pass locally. These additions remain uncommitted and need their+remaining review/build/UI checks and CI; they are not deployed account controls.++A fresh public registry read still returns `next=1.0.0-rc.1` and+`latest=0.0.0-stage`. Stable publication and local distribution can proceed through+their own gates while native hosting is investigated. The support case is not a+reason to suspend independent work or to claim the rest of hosted v1 is complete.++## Managed-image startup control passed++The research-led minimal control now passes on Cloudflare. PR #150 source+`c6b119b4a6358d51c27406f6fb3e74cafd289782` uses documented Wrangler configuration,+an explicit private service binding and Cloudflare's managed Debian image. Its+fixed Node command returned the expected version/identity; output completed after+470 ms and awaited whole-instance cleanup after 573 ms. The provider instance API+also reported stopped with exit code zero. A repeat RPC returned the retained+result without starting a second job.++The tested bundle was compared with uploaded bytes before invocation. Public URLs+were disabled and no provider credentials, user assets or custom image were used.+After retaining evidence, the local operator, Container application, Worker and+namespace were removed; follow-up reads verified absence. Three of the five+approved trial jobs have now been attempted, leaving two. No additional support+message, production deployment or package publication occurred.++All 126 hosted tests on this isolated branch, its hosted typechecks/builds,+3,290 root tests (two platform skips), root typecheck/lint and redacted scans pass.+Both hosted CI platforms pass in run `37513405377`. The account-control branch's+separate uncommitted changes remain at 144 locally passing tests. The detailed+[startup review](2026-10-06-cloudflare-startup-review.md) records the receipt,+remaining custom-image/Kiln controls and unchanged hosted-launch requirements.++## Minimal custom-registry control passed++PR #150 source `2c605257b8990a3bb9c9f0fffb5a9abc45092bc3` passed the next private+control at 18:59:29 UTC. The official Node 24.20.0 Debian Trixie AMD64 image was+copied without changes to the private Cloudflare registry and selected through+the documented named-image binding. Deployed code/image/privacy readbacks passed.+The fixed command returned the expected version and identity, output completed+after 7,000 ms, and whole-instance cleanup after 7,102 ms. Provider state separately+confirmed stopped with exit code zero; replay returned the retained result.++All diagnostic cloud resources, its registry image and local operator were removed+with absence verified. Four of five approved trial jobs are now consumed; one+remains. Local gates include 129 hosted tests, all hosted builds/typechecks,+3,290 root tests (two platform skips), typecheck/lint and redacted scans. Both CI+platforms passed in run `37515318317`. The unchanged Kiln image without engine+imports is the next comparison; full hosted launch remains unqualified. The+detailed startup review records why image preparation is not a supported cause:+both this deployment and the earlier failed cf deployment reached image-ready.++## Original image startup isolated; initial trial exhausted++The final approved comparison at source `569fc5313f909c04ac960348b638e376cdb36239`+used the unchanged Kiln image with the successful minimal controller. Its fixed+Node command did not import Kiln. Deployed source, image and privacy checks passed,+but at 19:08:40 UTC the monitor failed after 1,242 ms before the controller entered+`exec`. Cleanup was confirmed after 1,243 ms, the provider instance list was empty,+and replay returned the retained failure. The app, Worker, namespace, registry+image and local operator were removed, with absence verified.++All five original trial jobs are now attempted; no jobs remain. Further cloud+execution requires a separately prepared bounded candidate and owner approval.+Local image/startup analysis and independent npm/account work continue. The failure+is now isolated from package evaluation, but its exact cause remains unproven.+Current checks pass 131 hosted tests, hosted typechecks/builds, root typecheck/lint,+dry run and redacted scans. Hosted CI run: `37516547552`. The full engine suite was+already green on the preceding candidate; this change touched only the diagnostic.++## Stable candidate and manifest comparison prepared++The separate managed worktree `kiln-stable-release` prepares stable 1.0.0 from+current main `8d14d0e`. PR #151 at `2cb3d864eaced99cbd56c5e7dfb8d8a92773ec31`+contains release identities, minimal packaged installation/migration corrections,+targeted dependency patches, secret-file ignores and the RC publication receipt.+It excludes native execution and account-controls changes. Its detailed candidate+record lives at `docs/reviews/2026-10-06-stable-package-candidate.md` on that branch.++Local final gates pass: 3,290 engine tests with two platform skips; coverage at+95.16% functions and 92.50% lines; root types/lint/toolchain/skills; 78 renderer+tests; 91 hosted foundation tests/types/builds; a clean Windows Node 22.23.3/npm+12.2.0 archive installation with SDK/CLI/MCP/local-plugin checks; and the complete+prepared website build. The first coverage run's Windows rename EPERM is retained;+a focused retry and the final full run pass without a source change. Root, hosted+and installed runtime audits report no known vulnerabilities. The optional agent+lockfile now resolves the patched MCP SDK 1.32.1. Extracted package and source+secret scans pass. No stable version was staged or published and nothing deployed.++The local archive digest is `6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`.+This archive is not a substitute for the exact main-CI archive in the release+runbook. PR CI is running; owner-approved merge, main qualification, staging and+owner promotion still follow. The broad README/Troy/site refresh remains deferred.++In parallel, local inspection verified the original Container image's runtime+manifest and unchanged layers. Cloudflare's builder omits provenance by default;+selecting the existing platform manifest directly tests that format difference.+PR #150 at `29fc0ac248f59aa1d8c6f6ca89160c85d266e8ca` prepares exactly one fixed+private job. All 133 local hosted tests, types/builds, root types/lint, deployment+dry run and source/actual-bundle scans pass. Its hosted CI run is `37520300880`.+No new cloud execution is authorized yet. The original five-job allowance remains+exhausted; the new candidate needs a separate owner decision, with its exact image,+60-second deadline, cleanup, privacy settings and $1 allowance documented in+`hosting/probe/MANIFEST_STARTUP.md`.++## Private renderer and request-tree integration++Stable npm 1.0.0 and the GitHub v1.0.0 release are now published; their separate+release receipts remain authoritative for package acceptance. Draft PR #153+continues hosted integration. Its preceding commit `6fca99d` passes all eighteen+CI checks. The new private renderer/controller work below needs its own fresh CI+and has not been deployed.++The coordinator now injects a bounded private `PbrRenderPort`. It sends exact GLB+bytes and view options to a fixed renderer route; the response must match the+request ID, GLB digest, camera values, dimensions and renderer class. Published+engine code retains PNG validation, capture deadlines and truthful CPU fallback.+Tests demonstrate full-material views on success and geometry-only fallback when+the port fails. No published package or public tool schema was changed.++The fixed one-shot rendering entry validates requests and self-contained GLBs+before graphics initialization and explicitly selects the software Vulkan ICD.+Its private `KilnRenderJob` shares the evaluator's durable one-use lifecycle,+deadline, cancellation fence, recovery and verified whole-VM destruction. The+parent registers a third host-owned interceptor and persists each child ID and+kind before dispatch. Renders and evaluations share one active-child allowance+and eight total children. Recovery routes cancellation through the recorded kind;+unknown cleanup retains the parent reservation and suppresses its response.++All 261 hosted tests, three hosted typechecks, twelve production bundles and root+typecheck/lint pass locally. New behavior was tested failing before implementation.+Adversarial checks cover forged response identity, caller authority, request/output+limits, failed PNGs, cancellation, late response disposal, shared child limits,+cleanup failure and recovery. A real local workerd loopback/RPC fixture verifies+renderer routing through host-selected request props, cancellation acknowledgement+and denial after parent closure and eviction. These are local guarantees, not+evidence of provider isolation or complete hosted acceptance.++The exact installed renderer image+`sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`+passes its real entry/port fixture under offline local Docker with two CPUs and+4 GiB memory. Eight decoded 128px PNGs preserve textured materials across three+backdrops, a beauty image and an explicit camera. Malformed input is rejected+before device startup. The rebuilt coordinator image+`sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`+passes readiness, current/legacy MCP, hostile-header denial and failure without+private services. Both install the exact published stable archive, retain their+dependency inventories and remove their local test containers. Procedures and+receipt paths are in [the image guide](../../hosting/container/README.md).++The thirty-second render deadline is a candidate setting informed by the earlier+13,286 ms fixed provider fixture, not a measured production SLO. No additional+cloud upload, execution or public route was enabled. All 22 previously approved+cloud jobs remain consumed. The next provider trial must qualify the integrated+admission/coordinator/interceptor/evaluation/render/storage path with a concrete+bounded approval. Account lifecycle, live identity-provider setup, material+storage, browser downloads, representative load/costs, production deployment and+directory submissions remain open. The broad README/Troy/site refresh remains+deferred to launch closeout.++## Progress checkpoint after stable publication++The npm registry reports `latest: 1.0.0` and `next: 1.0.0-rc.1`; the public+[GitHub release](https://github.com/instruktlabs/kiln/releases/tag/v1.0.0) is+published. Stable package acceptance and installed local plugin checks are complete.+The hosted service and vendor directory submissions are not complete.++PR #153 at `382b40e` completed sixteen successful checks, including all twelve+engine/package jobs, Linux hosting, the installed MCP and CPU images, and the+website build. Two checks failed. The Windows admission fixture accidentally used+its `SHORT` Durable Object namespace binding as a boolean, applying a 250 ms+deadline to ordinary tests. A focused regression reproduced that mismatch before+the fixture flag was separated. All twelve admission tests then passed. Production+deadlines and admission policy are unchanged. The software image's actual rendering+checks passed; its artifact upload failed while opening a private build-cache file.+The evidence upload now excludes that cache and retains the receipts and images.+These corrections require fresh CI before the candidate can be accepted.++Local preparation of the integrated trial covers render, save, reopen, source,+export, saved GLB/manifest reads, cross-account denial and quota rejection. The+current working tree passes 268 hosted tests, all three hosted typechecks and all+twelve production bundles. That total includes trial work not yet committed or+provider-qualified. The local-only trial builder passes the installed Cloudflare+output schemas; no image upload, deployment or cloud execution has occurred.+It caps coordinator starts at nine, evaluator starts at four and renderer starts+at four, with sequential requests, durable one-use allowance and cleanup checks.+Its full worker integration and exact-source CI must pass before approval is sought.++No owner authentication step is currently pending. The next concrete owner action+is approval of the prepared integrated provider trial, followed later by live+provider credential handoffs and qualified merge/deployment/submission candidates.+All 22 previously approved trial jobs remain consumed. Routine implementation and+local validation can continue without a new decision.++Remaining launch work includes account link/unlink/delete, material storage,+browser download tickets, live Google/GitHub sign-in, retention verification,+representative load/cost evidence, operating alerts and rollback, production+deployment and verification, and separate vendor submission receipts. Saved-build+provenance also needs a host-verified evaluator identity: the current native host+does not inject one, so the SDK can report `source-development:unverified` in a+saved manifest. A successful round trip alone must not qualify that provenance.+The broad README, Troy images and site-content refresh remains deferred until+the final hosted behavior is verified, as requested.++## Integrated provider candidate prepared++The fixed ten-step sequence is prepared in+[the integrated trial record](../../hosting/probe/INTEGRATED.md): nine admitted+MCP requests plus quota rejection, with a durable ceiling of seventeen VM starts.+The actual private Worker, admission service, diagnostic allowance and R2 evidence+path now pass local workerd tests, including replay after durable-object eviction+and a stop issued before the trial. The complete fixed lifecycle also passes the+actual MCP adapter with a fresh host per request and real local tenant storage.+The generated deployment is schema-validated and checked for private-only routing,+fixed budgets, disabled Container logs/SSH and immutable image references.++The eviction test found a real early-failure defect: native startup rejection+could leave its inbound RPC request body unread, retaining the admission caller's+execution context. Closing an unused body in the production request boundary+fixes the demonstrated failure. The diagnostic budget boundary now does the same+when denying work; its focused cancellation regression also failed before the fix.+These changes do not alter the published SDK or immutable installed images.++All 270 hosted tests passed before the added deployment-configuration check, which+also passes. Hosted types/builds, lint and redacted source/bundle scans pass. The+preceding CI corrections have passed both hosted platforms and all image jobs;+this new candidate still requires its own exact-source CI. No cloud upload or+deployment has occurred, and the earlier twenty-two-job allowance remains spent.+The proposed separate trial allowance is $1; owner approval will be requested only+after the candidate checks pass. Live OAuth, provenance, account lifecycle,+downloads, production operations and vendor submissions remain separate open work.++## Owner progress checkpoint: package published, hosted integration open++Live readback confirms npm `latest` is `1.0.0` and the public GitHub `v1.0.0`+release contains the matching archive and checksum. PR #153 at `c755434` now+passes all eighteen CI checks, including both hosted platforms, all three+installed images, the twelve engine/package jobs and the website build. The PR+remains a draft; passing these checks does not qualify a public hosted launch.++The separate $1 private integration trial at that exact commit is prepared and+awaiting the owner's answer to the existing approval question. No new upload,+provisioning or trial execution has occurred. All twenty-two earlier approved+jobs remain consumed. No owner authentication step is currently pending.++Independent download work adds a tenant-local ticket store and six adversarial+tests. The current working tree passes all three hosted typechecks and all 277+hosted tests. Tests cover account separation, hashed tickets, expiry during a+read, revision deletion, concurrent transfer limits and bounded ticket issuance.+This foundation is still uncommitted and is not yet connected to the browser+gateway or MCP download URLs; it is not a completed download feature.++The remaining milestones are the integrated provider trial; browser downloads,+material persistence, account link/unlink/delete and verified saved-build+identity; live Google/GitHub configuration and sign-in; retention, representative+load/costs, alerts and rollback; an approved production deployment with real client+verification; separate directory submissions; and the deferred README/Troy/site+refresh. Existing provider trials establish native execution and software-render+feasibility, not completion of this integrated service.++## Private download flow integrated locally++The native MCP host now supplies download URLs through the published engine's+existing hook. Exact saved revisions receive ten-minute, hashed, tenant-local+tickets with atomic issuance/transfer limits. Browser requests derive their tenant+from the current primary-backed session, require the owning account, and recheck+revocation after storage awaits. No credentials are passed to storage or native+compute, and browser downloads start no VM. Deleted revisions and expired tickets+cannot release bytes, including when deletion or expiry interleaves with a read.++The existing branded sign-in page handles anonymous download navigation. Both+providers resume a strictly validated server-retained relative path. The additive+`0007_browser_login_return.sql` migration defaults existing transactions to the+account page; callback parameters cannot retarget the redirect. The page was+visually inspected in the local in-app browser. Its presentation-only listener+was stopped afterward; no real provider or credentials were used for that preview.++Focused tests first demonstrated missing ticket routing, missing native links,+the dispatch allowlist denial and rejected sign-in continuation. The completed+local gates pass all 286 hosted tests, three hosted typechecks, twelve production+bundles, root lint, diff checks and redacted source/bundle secret scans. The actual+MCP save/reopen output is exercised through the real browser gateway, D1 sessions,+SQLite tenant index and R2 with two fixture accounts. GLB hashes, exact source,+manifest identity and PNG signatures agree; hostile routes, foreign embedding,+cross-account reads, callback replay and revoked browser sessions are denied.+Provider exchanges remain mocked, so these checks do not claim live OAuth.++The rebuilt native coordinator uses the exact public 1.0.0 archive and unchanged+dependency lock. Image+`sha256:2f85a87cb48e360e9de3994d898413695a87c11b3d9f39f466fbf9d88c090d34`+passes the six offline Docker checks; its test container was removed and absence+read back. Evidence is under `.cache/native-host-download/qualification/`.+This image and the changed gateway/storage code require their own CI/provider+qualification. The pending private trial remains pinned to `c755434` and its+retained original bundle/images. No cloud resources were created or changed.++Account lifecycle, material persistence, saved-build identity, live OAuth,+representative operations/cost evidence, production deployment and vendor+submissions remain open. The root README/Troy/site refresh remains deferred.++## Durable material storage foundation and progress checkpoint++Fresh registry/release readback still confirms public npm `latest: 1.0.0` and the+non-prerelease GitHub `v1.0.0` archive/checksum. The download integration at+`72a3b61` passes seventeen CI checks, including both hosted platforms and all+three installed images; the Linux engine gate remains running at this checkpoint.+No completed check has failed. PR #153 remains a draft and is not a hosted launch.++The new native material adapter and tenant index pass nine focused tests and the+complete 295-test hosted suite. All three typechecks, thirteen production bundles,+root lint, whitespace checks and redacted source/bundle scans pass. Storage reuses+artifact quotas and immutable pins; verification imports the published SDK's+material contract. Tests cover persistence after host replacement and tenant+eviction, cross-account denial, concurrent identical imports, mutation of caller+buffers, corruption, quota exhaustion, paging and partial/lost-acknowledgement+failures. The first corruption-batch fixture reused the same material identity,+so duplicate validation correctly rejected it before hash validation. Giving the+corrupt second fixture a distinct valid identity now tests the intended integrity+boundary; duplicate rejection remains separately checked.++The material adapter is not yet connected to native MCP, asset imports or workspace+dependency binding. No material tool is advertised yet. This is local storage+evidence, not installed-image or Cloudflare material qualification.++The private integrated Cloudflare candidate still awaits the existing owner+approval question for a separate $1 allowance. Its retained Worker hash remains+`3ff536d4e99b8ee348d2a55e5a0de58ca04895643f53ccba4a68cf5ee570312a`;+the later download/material changes have not replaced that candidate. No cloud+resources were provisioned or run. All twenty-two earlier authorized jobs remain+consumed, and no owner authentication step is currently pending.++Remaining work is material integration, account link/unlink/delete, saved-build+identity, live Google/GitHub setup and end-to-end sign-in, integrated provider+qualification, retention/load/cost evidence, operating alerts and rollback, public+deployment with real clients, vendor directory submissions, and the deferred+README/Troy/site refresh. Independent implementation can continue while awaiting+the private trial decision.++## Material library connected to hosted MCP++The storage-foundation commit `7a85ba2` was pushed after the preceding download+commit `72a3b61` completed all eighteen CI checks. The native MCP host now injects+the durable material library and a standalone async workspace binding through+published SDK interfaces. Assets also receive the library so copying/importing a+saved revision restores its embedded editable material closure. Edge metadata is+regenerated from the same registry: fifteen hosted tools, including `kiln_material`,+with the engine's existing dependency-selection schema on authoring operations.+Hosted project/review stores remain unavailable and are not advertised.++Focused failing tests first demonstrated the missing material tool, workspace+binding and dispatch routes. The implementation now passes the complete 301-test+hosted suite, all three typechecks, thirteen production builds, root lint and+redacted source/bundle scans. A further extension to the passing material lifecycle+test also passes: delete the live material entry, import a saved asset into another+collection, confirm exact material restoration and byte-identical GLB delivery,+then render again. Overlapping and nested bindings, explicit standalone reset,+bad locks/paths, oversized pin sets, identity-swapped records and cross-account+denial before evaluation are covered. No provider credentials or actual cloud+execution were involved in these local tests.++Coordinator image+`sha256:b31f2395c43610c1cf2d2630cde3d130ce24a973a83fece6c0722d3ec3a9c599`+uses the exact stable npm archive and unchanged dependency lock. Its eight offline+Docker checks pass, including the registry's material-binding schema and preset+discovery from the installed package. The named test container was removed;+receipts are under `.cache/native-host-materials/qualification/`. The image still+requires exact-source CI and provider qualification. The separately reviewed+`c755434` integration trial retains its original bundle and images.++The owner requested decisions through the question tool and then explicitly+approved the frozen `c755434` private trial with the same nine-request,+seventeen-start limits and separate $1 allowance. That approval covers the original+candidate only, not the newer material/download changes. Account lifecycle,+verified saved-build identity, live sign-in, operational+qualification, public deployment, submissions and the final documentation refresh+remain open; the overall goal remains active.++## Approved integrated Cloudflare trial passed and was removed++The owner's separate $1 allowance was used for the exact frozen `c755434`+candidate. All ten checks passed: material-faithful rendering, save, restore,+exact source retrieval, export, GLB and manifest reads, denial of another+account's source/GLB reads, and quota rejection before another VM starts.+Nine admitted MCP requests used thirteen fresh VMs: nine coordinators, two+evaluators and two software renderers, within the approved seventeen-start+ceiling. This run is complete; its unused allowance is not permission for a new+candidate or a replay that allocates new VMs.++The deployed Worker SHA-256 matched+`3ff536d4e99b8ee348d2a55e5a0de58ca04895643f53ccba4a68cf5ee570312a`.+Both image manifests matched the reviewed immutable digests. Worker URLs,+preview URLs and public routes were disabled; bindings, limits, image references,+Container SSH/logging and all seven SQLite namespaces were verified by API.++The initial `cf 1.0.0-beta.12` deployment failed locally because its converter+serialized the Worker's own Durable Object bindings as external `script_name`+references, which Container deployment rejects. Wrangler `4.147.0` deployed the+same prebuilt bytes after removing only those seven explicit self-references.+The generated probe now also emits this equivalent `wrangler.json`; its regression+test first failed on the missing output and then passed. No dependency was patched+and no code, image, quota or routing change was made to the approved trial.++The long-lived local operator RPC returned 502 after approximately 81 seconds.+The durable run continued and finished successfully. Reading its persisted status+recovered all results without restarting the sequence; calling the completed run+returned the identical record and left the thirteen budget claims unchanged.+This transport interruption remains recorded and must inform the next operator+implementation. It is not a successful long-lived client-connection claim.++Every retained response hash was verified. Saved GLB/source/preview sizes and+hashes match the manifest. Both the in-loop image and saved six-view preview were+visually inspected: checker texture and reflective blue sphere are present.+The saved preview names the exact saved GLB and reports full material fidelity+without fallback. The run measured approximately 39.9 seconds for initial render,+35.6 seconds for save, and 3.6-4.5 seconds for subsequent admitted reads/restore/+export. These are one small sequential fixture's end-to-end times, not a load+benchmark or an estimate for every asset. Settled billing remains unknown.++Provider readback confirmed all thirteen instances stopped. Cleanup removed the+three Container applications, Worker, seven namespaces, fifteen objects,+temporary bucket and both uploaded image tags; subsequent API reads verified+their absence. The local operator was stopped and its listener disappeared.+The checked-in [receipt](2026-10-06-hosted-integration-receipt.json) records hashes,+timings, limits, replay behavior and cleanup. Raw responses, provider snapshots+and image/GLB evidence remain under `.cache/integrated-trial/`.++The newer download/material implementation at `8775750` separately passed all+eighteen CI checks. It was not substituted into this cloud trial. Hosted launch+still requires qualification of those changes, host-owned saved-build identity+(this trial correctly retains `source-development:unverified`), account lifecycle,+live Google/GitHub sign-in, retention/load/cost and operating checks, production+approval and real client verification. Directory submissions and the deferred+README/Troy/site refresh remain open. No further owner action is needed for the+completed trial; ordinary implementation continues under the active release goal.++The configuration correction passes all 301 hosted tests, three typechecks,+thirteen production builds, root lint, redacted source/record scans and an actual+Wrangler no-bundle dry run. It changes local preparation only and has not been+used for another cloud deployment. The published npm package remains unchanged.++## Host-owned saved-build identity implemented and tested locally++New Container evaluations now acquire image identity at the outside controller.+The controller associates only the exact output returned after image inspection,+process completion and verified whole-VM cleanup with the selected immutable+image. Its private HTTP response carries the digest; it never accepts an identity+from request fields or evaluator stdout. The coordinator requires that header,+validates the normal SDK response, and binds the digest to that exact accepted+result. Overlapping responses have independent state.++Each admitted MCP request has a bounded proof map keyed by exact source and GLB+hashes. The new-save adapter requires a matching entry and replaces the draft's+engine claim with `cloudflare-container:sha256:<digest>`. Missing proof, altered+source/output, conflicting identities and excessive retained entries fail closed.+Saved code/GLB bytes are snapshotted before storage awaits. Imports retain their+original metadata and do not acquire a claim from this host. The digest identifies+the complete pinned evaluator image; this does not sign arbitrary imported+provenance or retroactively qualify historical records.++Focused regressions failed before implementation at the controller, transport,+asset-save and actual MCP boundaries. All 308 hosted tests now pass, including+fresh storage reads after reconnect, imports with original provenance, refusal+before storage writes and overlapping evaluation identities. All three hosted+typechecks, thirteen production bundles and root lint pass. The public SDK and+npm package are unchanged; these changes belong to the private hosting package.++The strengthened offline image check failed against the previous material image+because it had no identity contract. Rebuilt coordinator image+`sha256:d78f29a8565e2df4957f60607ee25645bff81e8221bc75b56b2992d7e17d4482`+passes all ten installed-image checks against the exact stable archive and the+unchanged dependency lock. The native MCP bundle SHA-256 is+`331ced56fab784f24ebaad644354f423d585a6346f22957d17dd9925c1e6d8f2`.+Both uniquely named test containers were removed. Receipts and inventories are+under `.cache/native-host-identity/`; this image has not been uploaded or deployed.++The prior `c755434` trial remains valid for its recorded scope and still accurately+records its unverified saved engine field. The new controller/coordinator pair,+downloads and material changes need their own exact-source CI and provider+qualification. Update the evaluation controller before the coordinator because+the new coordinator deliberately rejects old responses without identity.+Account link/unlink/delete, live OAuth, operating and load evidence, approved+public deployment, vendor submissions and deferred public documentation remain+open. No additional cloud spend or user authentication was used for this work.++## Explicit Google/GitHub linking and unlinking locally qualified++The gateway now has separate, purpose-bound identity-change flows. Linking first+confirms an already-linked provider, then validates the new provider in a separate+one-use, browser-bound phase. Unlinking verifies the provider that will remain.+The unique provider constraint and atomic final mutation prevent account merges,+last-login removal and concurrent unlink races. Account ownership and the tenant+namespace remain unchanged. Every successful change records account activity,+increments the authorization epoch and revokes browser sessions together. Old MCP+access and refresh credentials are denied by the existing primary authority.++Regression tests failed on the absent route before implementation. All 317 hosted+tests pass, including both link directions, foreign-account refusal, same-session+binding, replay/races, cancellation/expiry, rollback on event-write failure and+state changes during the provider exchange. Three hosted typechecks, thirteen+production builds, root lint and redacted source/bundle scans pass. A local+presentation-only fixture was inspected at the normal browser width and a 375px+viewport, including linked-method controls, activity and completion messaging.+The mobile controls have separated touch targets and no horizontal overflow.+The fixture uses synthetic identities, does no external I/O, and proves layout+only. Screenshot: `.cache/security-review-2026-10-06/account-identity-controls-mobile.jpg`.++Apply additive migration `0008_identity_actions.sql` before the gateway, after+checking existing per-account provider uniqueness. Rollback preserves committed+identity changes and account epochs. The private native image does not change.+Live sign-in and real provider confirmation remain unqualified, as do full account+deletion and production operation. This work was not deployed or merged to main.++Current OWASP, NIST federation, Google/GitHub and D1 documentation were checked.+Provider selection/confirmation can reuse an upstream session and does not prove+a fresh password/MFA challenge. The current notices are in-app only. A sequenced+owner question is pending about collecting a verified security contact email and+sending out-of-band identity-change/deletion notices through Cloudflare. This is+separate from email-based sign-in, which remains deferred; no scopes, live email+configuration or mail delivery were changed. Cloudflare's documented Workers Paid+allowance is 3,000 outbound messages per account/month, then $0.35 per 1,000. Actual+sender-domain readiness and delivery still need qualification if adopted.++Sources:+[OWASP federation linking](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#secure-federated-account-linking),+[NIST federation](https://pages.nist.gov/800-63-4/sp800-63c.html),+[Cloudflare Email pricing](https://developers.cloudflare.com/email-service/platform/pricing/).++## Compute and storage retirement locally qualified++Added private account-retirement primitives, with no public deletion form or+gateway lifecycle route yet. Compute retirement records a permanent tenant deny,+marks any admitted job closing and requires verified whole-request cancellation.+Failure retains admission capacity and recovery intent. Eviction or global+pause/resume cannot reopen the account. Only that tenant's quota history is+removed; global counters still account for its admitted work.++Storage retirement denies further operations, revokes download tickets, removes+saved metadata and purges only that tenant's R2 prefix. Batches and retry alarms+bound cleanup. Outstanding uploads retain durable write evidence until the put+settles or matching committed immutable bytes establish its completion. Neither+a timeout nor an empty listing proves that an unresolved write is cancelled.+Unknown outcomes after a crash remain pending with a daily recovery alarm and+require escalation if they cannot be resolved. Verified purge requires an empty+prefix, no artifact rows and no unresolved writes, then removes its alarm while+retaining the small denial record.++Focused tests first reproduced two races: ordinary maintenance removed an+unresolved write's metadata, and an older sweep recreated maintenance state after+purge. Both are fixed and covered, alongside delayed writes, failed deletion,+lost acknowledgement, eviction, account isolation, 105-object bounded cleanup,+hostile retirement requests and refusal from the native storage interceptor.+Further red/green cases enforce atomic download-ticket revocation and ensure a+batch of unresolved writes cannot starve ordinary expiry of other files.+All 331 hosted tests, three hosted typechecks, thirteen production builds and+root lint pass locally. The npm package/native image is unchanged. No cloud+trial, resource creation or deployment occurred for this change.++The full deletion flow still needs purpose-bound owner confirmation, primary-D1+revocation and durable retry orchestration, identity/token cleanup, truthful user+status, and provider qualification. Deploy retirement-aware compute/storage+before connecting that controller; rollback must not restore code that ignores+retirement after accepting deletions. Provider backup retention and unresolved+write escalation also remain operational launch work. The pending security-email+decision is unchanged.++Current references:+[R2 consistency](https://developers.cloudflare.com/r2/reference/consistency/),+[R2 durability](https://developers.cloudflare.com/r2/reference/durability/),+[Durable Object alarms](https://developers.cloudflare.com/durable-objects/api/alarms/).++## Account deletion controller and user flow locally qualified++The gateway now connects explicit account-page confirmation to durable cleanup.+A separate five-minute provider flow binds the browser, account epoch and linked+identity. Confirmation atomically creates a primary-D1 job, revokes account+access and removes browser sessions. Cleanup proceeds through compute retirement,+private storage purge, OAuth-helper grant revocation and final identity/account+erasure. Leases, deadlines and retry backoff prevent concurrent or delayed work+from falsely advancing another claim. Failure keeps access disabled and the+receipt pending. The completed receipt retains no account link and expires after+seven days. The receipt secret exists only in an HttpOnly cookie; its database+value is hashed.++All 349 hosted tests pass, along with three hosted typechecks, thirteen production+builds, root lint and redacted source/bundle secret scans. Focused regressions+failed before implementation. The real gateway/D1/OAuth-helper/private-tenant/R2+fixture now exercises deletion of saved work, denial of old credentials,+preservation of another account and a new empty account on subsequent sign-in.+Provider identity exchanges are mocked and the fixture starts no native VM.+Additional cases cover enqueue/final-erasure rollback, wrong identities, hostile+forms, callback replay/races, epoch/session changes during provider I/O,+bounded intents, expired/replaced leases, cleanup failures and delayed completion.+The deadline fixture observes the real 20-second timeout and records the later+completion in the originating request context before checking that the job did+not advance. This avoids mistaking workerd's cancellation of a cross-request+promise for proof about late completion. Test-only controls are absent from all+thirteen production bundles.++Desktop and 375px browser previews show the confirmation and pending/completed+receipt pages without horizontal overflow, using synthetic data only. Screenshots+are under `.cache/security-review-2026-10-06/account-deletion-*.png`. The local+preview server was stopped and its listener absence verified.++Apply additive migration `0009_account_deletion.sql` before the gateway and+retirement-aware compute/storage before accepting deletions. The scheduled+handler is implemented but no deployed Cron Trigger has been configured. Verify+recurring recovery, stalled-job escalation and real account deletion on the next+approved combined-service qualification. Rollback must preserve retirement and+primary revocation. Completion concerns active application storage, not immediate+erasure of provider backups or eventually consistent OAuth KV records. In-flight+authorized token writes can outlive inventory cleanup but primary account state+denies their use; configured access/refresh expiry remains 15 minutes/30 days.+Public retention disclosures and restore procedures remain launch gates.++The preceding head `1e609b3` passed all eighteen CI checks. This change has only+the local results above until its own exact-head CI finishes. It does not change+the published npm archive or native image. No additional paid run, deployment,+live credential creation or email delivery occurred. The security-email owner+decision remains pending; the prepared Google client form is still unsubmitted.++References checked:+[D1 batch transactions](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch),+[Worker scheduled handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/),+[KV consistency](https://developers.cloudflare.com/kv/concepts/how-kv-works/).++## Complete hosted deployment preparation++Added an offline candidate builder for the actual six production Workers: gateway,+tenant storage, admission, native request, evaluation and rendering. It builds+each entrypoint with its production dependency boundary, checks required exports,+copies the numbered D1 migrations and hashes every configuration, bundle and+migration. The input accepts only non-secret resource identifiers, pinned+account-owned image digests and bounded numeric policies. Provider credential+values are neither accepted nor copied; only the gateway declares the four+required secret names. Output is fresh, local and never overwrites prior evidence.++The prepared gateway has no public route, workers.dev endpoint or preview URL.+Its every-minute deletion-recovery trigger is explicit but has not been deployed.+Only the tenant Worker owns the R2 binding; only the gateway owns account D1 and+OAuth KV. Gateway compute access uses `KilnCompute`, never its operator export.+Cross-service DO bindings retain their target script, while self bindings use the+local form required by the previously observed cf beta conversion issue.+Invocation logs, persistent traces, Container logs and SSH are disabled; sanitized+operational monitoring and ingress-abuse controls remain required before launch.++Five new configuration/preparation tests failed before implementation and now+pass. All 354 hosted tests, three hosted typechecks, thirteen production builds,+root lint and redacted preparation-source/generated-output scans pass locally.+Wrangler 4.147.0 successfully dry-ran all six generated no-bundle configurations.+Those dry runs used synthetic account/resource IDs and image digests; they establish+local configuration validity, not remote resource existence or execution.+Evidence is under `.cache/hosted-deployment-dryrun-v1/`, the final hashed receipt+under `.cache/hosted-deployment-dryrun-v2/`, and six adjacent dry-run logs. No cloud+resource, secret, trigger, route or image was created by this work.++CI on preceding deletion head `5d91f2f` initially failed the existing Windows+resilience-probe HTTP-denial request with `TypeError: fetch failed`. The focused+test passed locally, and the unchanged failed-job rerun passed on Windows. The+cause is not established; no test was weakened or automatically retried in code.+Seventeen of eighteen checks have passed; the root Linux community-exporter step+is still running at this checkpoint. New preparation changes require their own CI.++The [deployment guide](../../hosting/DEPLOYMENT.md) records the dependency order,+secret/migration requirements, recovery verification and remaining launch gates.+The example manifest deliberately contains invalid identifiers and qualification+policy examples, not public quota decisions. Actual resource ownership, image+identity, live OAuth, combined provider qualification, monitoring/load/costs,+retention/rollback and an approved public route remain unfinished. The unanswered+security-email question and unsubmitted Google client form are unchanged.++## Request abuse limits locally qualified++The gateway now requires separate edge and authenticated-account rate-limit+bindings. Fixed route classes bound anonymous work before OAuth, D1 or body+processing. Verified permanent account IDs select hashed counters shared across+MCP clients, bearer tokens and browser downloads before storage or compute. No+IP, credential, source or arbitrary URL enters those keys. Exhaustion returns+429 with a 60-second retry suggestion; missing, failing, malformed or stalled+bindings fail closed with 503. An unread rejected body is cancelled.++The offline deployment manifest now requires distinct positive integer namespace+IDs and per-minute thresholds, emitted only on the gateway. Verify account-wide+namespace uniqueness before deployment. Example thresholds are 600 requests per+route class and 120 per account, for qualification planning only. Cloudflare+documents these counters as approximate and local to each location; durable+global/tenant compute quotas remain unchanged. Coarse ingress exhaustion can+temporarily affect all users of a route class in that location. Provider/load+qualification must assess that tradeoff; no exact request or billing cap is+claimed, and rejected requests still invoke the Worker.++Focused limiter and deployment regressions failed before implementation. All+363 hosted tests, three typechecks, thirteen production builds and root lint+pass locally. Integration tests use real local rate-limit bindings to exhaust+ingress and share an account budget across MCP and browser downloads while+leaving another account usable. Separate forbidden-I/O fixtures prove rejected+registration, token, callback, account, MCP and download requests never reach+OAuth/database work; denied accounts never reach storage or native compute.+The limiter deadline test observes the real one-second timeout. Ordinary auth+and storage tests retain real bindings with generous fixture limits.++Redacted source and six-worker candidate bundle scans found no leaks. The+changed gateway configuration passed a Wrangler 4.147.0 no-bundle dry run with+synthetic resource IDs and images. Evidence is under+`.cache/hosted-deployment-rate-limits/` and `.cache/request-limits-*.log`; its+receipt correctly records a dirty checkout and is not a release receipt.+No provider resource, credential, threshold, route or image was deployed.+Seventeen of eighteen checks on preceding head `293affa` have passed; the root+Linux check is still running. The new change needs its own CI.++Live OAuth, the pending security-email decision, sanitized operational alerts,+updated combined-provider qualification, load/costs, backup retention/rollback+and public-launch approval remain outstanding. The Google client form remains+unsubmitted. The earlier private trial allowance is consumed and was not reused.++Reference checked:+[Cloudflare rate-limit configuration, locality and accuracy](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/).++## Sanitized operational observations and alert candidates++The gateway now writes explicit Analytics Engine points for HTTP response class,+status and handler elapsed time, plus scheduled deletion and compute health. No+request/response object, body, arbitrary URL, IP, account ID, token, download+capability or exception enters a point. Fixed indexes separate HTTP from the two+health streams. Persistent request logs and traces remain disabled.++Deletion health queries primary D1 with indexed phase selection, reporting pending+count, oldest age and jobs at least fifteen minutes old. A narrow private compute+RPC exposes existing aggregate admission state without pause control or tenant+identifiers. Both reads have independent two-second deadlines; unavailable data+is marked explicitly with `-1` values, not zero. Scheduled recovery emits both+components even after a failure and fails the invocation when recovery or either+component is unavailable. A telemetry write failure does not change access,+returned bytes or cleanup; external missing-heartbeat detection is required.++The complete deployment binds only the gateway to its derived operations dataset+and hashes `monitoring-candidate.json`. Six proposed Cloudflare Custom Alerts+cover missing recovery/compute heartbeats, overdue deletion, persistent cleanup,+HTTP errors and request rejections. They contain the exact account/dataset,+one-minute evaluation and five-minute windows with hourly repeat proposals.+They are not enabled and have no destination. Queries use the newer Analytics SQL+API dialect, whose sampling rules differ from the legacy Analytics Engine API.+Live catalog access, query validation, thresholds and notification delivery remain+unverified. [OPERATIONS.md](../../hosting/OPERATIONS.md) records the schema,+limitations, retention, volume assumptions and deployment qualification steps.++Focused observation and deployment regressions failed before implementation.+All 373 hosted tests, three typechecks, thirteen production builds and root lint+pass locally. Real local D1, gateway and scheduled-handler fixtures establish+empty/pending/completed aggregate behavior, secret-free fields, independent+component failures and unaffected HTTP responses when telemetry fails. The+read-only compute RPC test verifies unchanged admission and continued denial of+public/operator access. A stalled read exercises the actual two-second timeout.+Local tests do not establish remote Analytics Engine ingestion, SQL acceptance,+sampling or alert delivery.++Redacted source and generated-candidate scans found no leaks. Wrangler 4.147.0+dry-ran the changed gateway with its Analytics Engine binding. Evidence is under+`.cache/hosted-deployment-operations/` and `.cache/operations-*.log`; synthetic+IDs/images and the dirty-checkout receipt are not release qualification. No cloud+resource, dataset point, alert, email, credential or paid trial was created.++CI on preceding head `71347d6` passed sixteen checks but the Windows hosted run+failed its existing chunked-body test with `TypeError: fetch failed`, before the+413 assertion. The root Windows check was still running at that checkpoint.+The exact hosted failure log is retained locally and one unchanged failed-job+rerun was requested. Cause and rerun outcome are not yet established; assertions+and retry behavior in the suite are unchanged. This monitoring change requires+its own CI. The pending owner security-email decision and prepared, unsubmitted+Google client form remain unchanged.++The unchanged Windows hosted rerun subsequently passed (run `37561702455`,+attempt 2). Current upstream workerd issue+[#7634](https://github.com/cloudflare/workerd/issues/7634) describes Windows+connection resets after early responses through service bindings, and related+workers-sdk issue [#15709](https://github.com/cloudflare/workers-sdk/issues/15709)+covers oversized-body cancellation. These reports are consistent with the local+failure shape, not proof of its precise cause or of deployed behavior. No drain,+automatic retry or relaxed assertion was introduced. Live gateway qualification+must include early 401/413/429 responses to streamed bodies and subsequent normal+requests, confirming client-visible errors and continued service availability.++References checked:+[Analytics Engine writing](https://developers.cloudflare.com/analytics/analytics-engine/get-started/),+[retention](https://developers.cloudflare.com/analytics/analytics-engine/limits/),+[pricing](https://developers.cloudflare.com/analytics/analytics-engine/pricing/),+[Custom Alerts](https://developers.cloudflare.com/notifications/notification-available/#custom-alerts-beta),+[Analytics SQL datasets](https://developers.cloudflare.com/analytics/sql-api/datasets/).++## Combined-service gateway preflight locally qualified++The next private trial now has a reusable gateway preflight component. Its local+fixture builds all six production Worker entrypoints and derives service, D1,+KV, R2, rate-limit and DO links from the deployment configuration. It registers+declared DO namespaces using Miniflare's local representation; remote namespace+ownership, Container images, Cron and Analytics Engine remain unqualified.++Thirteen fixed checks cover metadata, real helper-issued OAuth grants and PKCE+exchange, edge tool discovery, anonymous and oversized-body denial, exact bearer+and browser downloads, foreign-account denial, primary connection revocation,+denial of retained access/refresh credentials and preservation of another account.+Admission is paused through its real private operator RPC before setup and stays+paused afterward. No step invokes native tooling or starts a VM. Fixtures bypass+upstream identity verification and seed routing-test files directly; this is not+evidence of provider consent, engine save, rendering or validated asset contents.++The helper requires an explicit private-fixture mode and fixed `.invalid` origin.+Existing account, OAuth or artifact data causes refusal before provisioning.+A transaction claims the run once. Concurrent calls and terminal replay cannot+create additional accounts or retry a failed sequence. The receipt contains only+stage outcomes and pause state; credentials, identifiers, download capabilities,+source and exception details stay out of it. An intentionally misbound gateway+database fails at synthetic authorization and replay leaves that partial state+unchanged. No HTTP route or provider-deployable operator was added.++All 379 hosted tests pass, including six new preflight cases. Three typechecks,+thirteen production builds, root lint and redacted probe-source/bundle scans also pass.+The test preceded the implementation; local harness corrections then registered+export-owned namespaces and serialized RPC receipts for deterministic comparison.+Production dependency checks exclude every test/probe helper from all bundles.+Evidence is under `.cache/gateway-preflight-*.log`. All eighteen CI checks on+preceding head `e421455` now pass; this change needs its own exact-source CI.++[GATEWAY_PREFLIGHT.md](../../hosting/probe/GATEWAY_PREFLIGHT.md) states the scope+and remaining work: a bounded private operator and updated native/material/image+phase, explicit VM/evidence budgets, complete cleanup, then renewed trial approval.+Live OAuth/account actions/deletion, real scheduled recovery, retention, load,+costs, alerts and public-client behavior remain launch gates. No cloud resource,+provider credential, public route, paid run or email was created. The existing+security-email decision remains pending and the Google client form unsubmitted.++## Security notice decision and native lifecycle component++The owner selected **in-app notices only for v1**. This supersedes the pending+security-email question above. The plan's D10 and hosting guide now record that no+separate security contact email, additional email scopes or outbound security mail+will be added to v1. Google/GitHub sign-in remains unchanged. The next sequenced+browser approval is creating the prepared Google web client with the sole callback+`https://kiln.instruktlabs.com/oauth/google/callback`; the form remains unsubmitted.++All eighteen CI checks passed on `dd33b5a`. The next native trial now has a locally+qualified lifecycle runner and independent durable allowance. Twenty-one fixed+stages cover material creation, fresh-host rendering/save/restore/source/export,+GLB/manifest reads, exact browser download contents, account isolation, material+closure restoration after removing the disposable live material, rerender and+quota rejection. The actual engine fixture observes fourteen admitted MCP calls,+three evaluations and three synthetic view calls; the fifteenth MCP call is denied.+Manifest acceptance requires the exact evaluator-image identity. Local synthetic+views do not qualify software Vulkan fidelity or cloud VM behavior.++The proposed private allowance caps coordinator/evaluation/render starts at 14/4/4,+22 total, once connected to diagnostic wrappers. It is transactional and one-use;+failed starts cannot be refunded, and closing before opening forbids any later run.+The old trial and its consumed allowance remain unchanged. No new paid execution,+cloud resources, image upload or public route was created.++The lifecycle uses fixed request/control deadlines, an 8 MiB response ceiling,+64 MiB aggregate evidence ceiling, stop-on-failure, and terminal allowance closure+with paused/idle admission verification. A retained interrupted record cannot+resume or recreate the run. Raw synthetic response evidence stays private; public+receipts exclude credentials, URLs, source and exception details. Paused/idle+admission is not a cloud-resource-deletion receipt.++Focused failing tests preceded implementation. Adversarial replays of real engine+responses exposed weaknesses in the new trial's initial acceptance checks: it+missed JSON-escaped source in an error and trusted download denial status without+checking for leaked content. Both checks were corrected. Replays now reject those+leaks, leaked material data, modified GLB downloads and unverified engine identity.+Other tests exercise concurrent allowance claims, reconstruction, invalid inputs,+oversized responses and the actual ten-second stalled-evidence deadline; late+completion cannot resume the failed sequence.++All 385 hosted tests, three typechecks, thirteen production builds, root lint and+redacted probe-source/bundle scans pass locally. Logs are under+`.cache/lifecycle-*.log`. [NATIVE_LIFECYCLE.md](../../hosting/probe/NATIVE_LIFECYCLE.md)+records scope and limitations. Wiring the unchanged production gateway/tenant/+admission services to diagnostic budget wrappers, the private operator, exact+image/config verification and full cleanup is next; only then is another paid+trial ready for approval. Live OAuth, account actions/deletion, scheduled recovery,+retention, load/costs, alerts and actual public-client verification remain open.++## Combined private operator and deployment candidate++The native lifecycle and gateway preflight are now connected through a fixed private+operator. It creates fresh grants for the same two synthetic accounts only after+the preflight passes, opens the separate durable allowance, then sends every native+request and browser download through the production gateway. Three wrappers add+only startup claims around the production native jobs; gateway, tenant and admission+implementations stay unchanged. The combined local test passes gateway checks,+stops at the first missing VM, seals admission and retains its failure receipt.+It does not pretend to qualify successful cloud native execution.++The private allowance has its own Worker to eliminate a circular deployment+dependency. The resulting eight roles have a tested order in which every dependency+precedes its caller. The gateway omits provider secrets and Cron in this private+candidate. All eight disable public routes, workers.dev, preview URLs and persisted+logs/traces. The generic production preparation path retains its no-probe guard.+The new `--private-lifecycle` path validates fixed quotas/origin/names and hashes+eight separate bundles/configurations plus nine migrations. Unexpected helpers and+native identity-provider dependencies cause rejection; output cannot overwrite an+existing candidate.++Operator controls include a 15-minute terminal alarm, one-minute recovery when+cleanup remains unknown or non-idle, and status with explicit alarm/stop state.+The startup ceiling remains 14/4/4, 22 total, with no refunds. Local tests cover+concurrent invocation, failed preflight, stop before identity creation, body+cancellation at all three closed native wrappers, eviction/replay and uncertain+cleanup retaining its alarm. These do not prove remote alarm delivery.++An eviction test exposed retained RPC capabilities in the initial diagnostic+operator. Explicit disposal of control-call promises/results and copying plain+receipt values fixes it; the same eviction/replay assertion now passes. The Workers+type configuration includes the standard disposable declarations used by this code.+This follows [Cloudflare RPC lifetime guidance](https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/).+The initial default HTTP service binding also incorrectly named the `default`+entrypoint; omitting the named-entrypoint field now reaches the actual gateway as+documented for [HTTP service bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/http/).++All 394 hosted tests, three typechecks, thirteen production builds, root lint and+redacted source/bundle scans pass. All eight generated Wrangler 4.147.0 configurations+pass no-bundle dry runs using synthetic IDs. The fixture candidate and logs are in+`.cache/lifecycle-preview-final-13af43d`; its source was intentionally dirty while+preparing the change, and it is not an approved deployment artifact. All eighteen CI+checks passed on preceding commit `13af43d`; this new source needs its own CI.++No Cloudflare resources, image uploads, paid starts or provider credentials were+created. In-app security notices remain the settled v1 choice; Google client+creation remains pending owner confirmation. Next steps are a clean candidate,+exact image verification, a fresh private observer, concrete resource/readback and+cleanup qualification, then a sequenced trial allowance. Live OAuth/deletion,+scheduled recovery, retention/load/costs/alerts, production publication and directory+submissions remain incomplete. Root README/Troy/site refresh remains deferred.++## Native deadline classification corrected after Linux CI++The Linux hosted job on `602700e` failed one of 394 tests: a native response+interrupted by its deadline timer returned cancellation (499) instead of timeout+(504). A deterministic regression reproduces that result when the deadline timer+fires while the wall clock still reads one millisecond before the deadline. The+controller now retains the timer-expiry cause, so catch handling reports timeout+without relying solely on a second wall-clock read. Cancellation, late-response+discard and whole-instance cleanup remain enforced. The original real-timer test+and all its assertions remain in place.++The new test failed before the fix; all 21 request-controller tests and the full+395 hosted tests now pass locally, along with three typechecks, thirteen production+builds and root lint. Logs are `.cache/request-deadline-*.log`. This changes the+request Worker, not the installed native images. A fresh branch CI run is required.++Read-only Cloudflare inventory confirms the fixed `kiln-private-lifecycle-v1` names+are absent across Workers, Durable Objects, D1, KV, R2 and Container applications.+There are no Container applications or registry images currently in this account.+The existing local coordinator and software-image IDs still match their retained+qualification receipts. Inventory receipt: `.cache/lifecycle-readonly-inventory-refreshed/receipt.json`.+These observations authorize no resource creation or paid starts; image upload,+remote configuration readback, a fresh observer and verified teardown remain trial+preparation work. Google client creation remains the pending owner approval.++## Local lifecycle observer prepared++The next trial has a fresh tracked loopback observer rather than reusing the+consumed integration-trial operator. It forwards only three fixed, argument-free+RPC controls. Host/port, method, query and browser-request guards reject unrelated+traffic; unread bodies are cancelled. Private JSON observations are capped at+128 KiB. Status/stop expire after ten seconds and the run observation after sixteen+minutes around the cloud operator's fifteen-minute terminal alarm. A missing+observation is explicitly unknown and never triggers another operation. Promise+and result capabilities are disposed, including results that arrive after timeout.++Six focused tests cover these controls and the fixed remote-binding/loopback+configuration. The combined Miniflare topology now routes its run/status/stop and+eviction checks through this actual facade. The forwarding, failure and deadline+tests failed against a refusal-only stub before implementation; all 401 hosted+tests, three typechecks, thirteen production builds and root lint pass locally.+The observer configuration also passes Wrangler 4.147.0 dry-run validation.+Logs are `.cache/lifecycle-observer-*.log`.++No observer listener, remote development proxy, new cloud resource, credential or+paid native start was created. Concrete cloud deployment readback and cleanup+orchestration still need preparation before the next trial allowance is requested.+Google client approval remains pending. Public hosting and directory submissions+remain open, and the final README/Troy/site refresh is still deferred.++## Private deployment readback and cleanup preparation (October 7)++All eighteen CI checks passed on `23fa54f`, including both hosted platforms and+all three installed native-image jobs. The new pure readback verifier binds the+eight deployed Workers to the clean candidate's hashes, active versions, exact+bindings, three pinned Container images, seven SQLite namespaces and nine D1+migrations. It rejects public routes, domains or previews, Cron, unexpected+bindings, enabled logs/SSH and active or starting instances before admission.+These checks use modeled provider responses locally; actual remote readback of+this candidate remains a gate before any native invocation.++The cleanup planner requires a stopped operator, closed one-use budget, paused+idle admission, no recovery alarm and stopped VMs matched to recorded claims.+It selects only the recorded temporary resources and reverses Worker dependency+order. Failed starts can consume claims without leaving instances. The separate+local collector and teardown scripts retain bounded synthetic evidence, recheck+resource identities, stop on a partial failure and require final absence readback.+They have not deployed or deleted anything. Registry images are preserved;+Analytics Engine's documented three-month retention is not represented as data+deletion by resource teardown.++Six focused tests include deliberate code, binding, image, namespace, public+surface, quota and cleanup-state mismatches. Positive cases failed against the+initial refusal-only stub. All 407 hosted tests, three typechecks, thirteen+production builds and root lint pass. Logs: `.cache/lifecycle-readback-*.log`.+Read-only route inventory checked all five account zones and found no route for+the fixed trial prefix; `.cache/lifecycle-operator/surface-inventory.json` retains+the timestamped result. No cloud resource, native start or provider credential was+created during this preparation. A new allowance and exact-candidate CI are still+required. Google client approval remains pending; production launch is incomplete.++## Hosted information and consent presentation (October 7)++All eighteen CI checks passed on `4867aaf`. While Google client approval remained+pending, the gateway gained public home/privacy/support routes and a shared account+and consent layout. The pages describe the implemented identity, storage, telemetry,+deletion and in-app-notice behavior without requiring sign-in. Existing consent+cookies, CSRF/browser binding, escaped client identity and scope disclosure remain+enforced. The account page now states that security changes do not send email.++The new assertions failed first. All 410 hosted tests, three typechecks, thirteen+production builds and root lint pass locally. Desktop and narrow-viewport checks+cover the actual HTML functions with synthetic data. See the+[page review and source mapping](2026-10-07-hosted-pages.md) for receipts and limits.+Nothing was deployed or submitted; Google client approval, the next private trial,+live sign-in/deletion, operational verification and public launch remain pending.+The final README/Troy/site refresh remains deferred.++## Hosted public operation mapping (October 7)++All eighteen CI checks passed on `0b680d3`. A fresh official-document review found+that directory preparation still needs terms, immediately usable review access and+separately exposed hosted operations. The hosted adapter now derives 26 named+operations from the pinned engine's 15-tool manifest. Input schemas stay owned by+the registry; hidden action selectors and unrelated fields cannot reach native+admission. Native jobs are conservatively annotated as writes, including reads+that start stateful jobs. The published local package and tool contract are unchanged.++The lifecycle fixture now traverses the actual public adapter before native MCP.+Both initial regressions failed first; all 417 hosted tests, three typechecks,+thirteen builds and root lint pass. Modern header/metadata translation, hidden-tool+denial, hostile keys and registry drift have focused coverage. See+[directory preflight](2026-10-07-directory-preflight.md) for the mapping, official+sources, Claude source-archive measurements and remaining submission work.+The previous frozen trial candidate must be refreshed before approval because the+gateway and operator source changed. No cloud resource, credential, paid job or+directory submission was created. Google client approval remains pending.++## Portable hosted plugin and terms draft (October 7)++All eighteen CI checks passed on `f701121`. The public plugin draft now packages+one hosted MCP, listing metadata, a hosted workflow skill with maintained geometry+references, the existing icon and eight review cases. Deterministic output and+allowlisted inputs are tested; private connectors, credential configuration and+hidden components are rejected. The generated skill validates. A local icon and+listing preview is retained, without claiming actual directory presentation.++A draft terms page and shared footer link are implemented. They reflect free+quota-based access, no end-user billing, private assets and in-app notices only.+Owner review remains required with the concrete deployment candidate. The review+cases require a populated independent review account; no account, live case+receipt, demo URL or submission has been fabricated. The packager's receipt always+records that live qualification remains incomplete.++The terms regressions failed before implementation. All 421 hosted tests, three+typechecks, thirteen production builds and root lint pass. The actual terms page+renders in the local browser. Details and remaining gates are appended to the+[directory preflight](2026-10-07-directory-preflight.md). No new cloud resource,+credential, paid job or publication occurred. Google client creation remains the+pending approval. Refresh the frozen lifecycle trial to the new source before+seeking its allowance; final README/Troy/site updates remain deferred until launch.++## Publisher portal preflight and local plugin icon (October 7)++All eighteen CI checks passed on `69d0326`. OpenAI's existing Instrukt Labs+organization is marked Verified and the Plugins page is accessible; no upload was+made. The selected listing identity and MCP domain challenge remain to be verified.++Anthropic's portal validated the published stable tag at `fda71ac`, folder+`plugins/kiln-engine`: repository, size, name and publisher checks passed. One+missing-icon warning and two credential policy holds were reported. The latter+refer to the public package-version pin beside npm's registry and the shared setup+guidance. The actual environment/npm data flow is documented in the+[directory preflight](2026-10-07-directory-preflight.md#publisher-portals-and-claude-validation-october-7)+for reviewer assessment. No credential was requested or submitted in response to+these findings, and no compliance acknowledgement or final submission occurred.++The local plugin now includes a 512px PNG derived from the existing Kiln SVG.+The maintained packager copies it and records its hash; the published 1.0.0 engine+pin, executable and tag remain unchanged. The missing-icon test failed first;+all eight focused packaging tests, skill checks, typechecking, lint and the+Claude Code 2.1.287 manifest validator pass. The full offline gate passes 3,290+tests with two skips, no failures, 95.16% function coverage and 92.50% line coverage.+Exact new-source portal validation+and CI remain necessary before saving or submitting the directory candidate.++### Local-plugin platform correction and remaining submission declarations++All 18 CI checks passed on `2339681`; Anthropic revalidation removed the icon+warning. Listing details exposed a separate mismatch: the local installer was+offered on chat and Cowork. The prepared plugin 1.0.1 now puts its actual+Node installer in the documented `bin/` component with executable permission.+Both maintained setup registries, provenance and installer instructions agree.+Plugin versioning is independent of its unchanged published engine pin, 1.0.0.+The npm package and v1.0.0 tag have not been replaced.++The new regressions failed first; all 32 packaging/setup tests pass. In isolated+profiles, Claude Code 2.1.287 and Codex 0.160.0 install the new cached plugin and+create workspaces from the verified public 1.0.0 package. Both discover, render,+save, reopen and export; Codex app-server confirms one setup skill, three workspace+skills and one 17-tool MCP server. No normal user profile changed, model call ran,+cloud job started, credential was created or final directory submission occurred.++The portal also exposed unanswered data-handling declarations and a submitting+identity of Matthew Kissinger. Its executable attestation needs resolving for a+local installer before acceptance. Details and official documentation are in the+[directory preflight](2026-10-07-directory-preflight.md#correcting-local-plugin-platform-support-october-7).+The in-app-notices choice remains settled; the Google OAuth-client creation+question remains the sole pending owner approval. New-source CI, portal readback+and refreshed private-trial artifacts are separate from the completed local checks.++The final offline gate passes 3,291 tests with two skips and no failures; coverage+is 95.16% functions and 92.50% lines. Toolchain, typechecking, lint, maintained-skill+consistency and Claude manifest validation also pass.++### Local plugin disclosures and exact-source portal result++All 25 CI checks passed on `6a213b6`. Anthropic validated that exact source and+now lists the plugin for Claude Code only, with no icon warning. Two policy holds+and the executable acknowledgement remain unresolved; no submission or acceptance+occurred. The local plugin now includes a draft privacy notice, explicit+execution/network disclosures, three setup examples and listing links in both+manifests. Its engine pin and executable are unchanged.++The metadata/privacy regressions failed first. The full offline gate passes 3,291+tests with two skips and no failures, at 95.16% function and 92.50% line coverage.+All 32 focused packaging/setup tests, typechecking, lint and strict Claude+validation pass. Fresh isolated Claude/Codex installations accept the metadata and+include the notice. A final prose clarification about npm caches/logs was checked+with regeneration, focused tests and lint.++The policy remains a draft and its intended `main` URL will not exist until an+approved merge. Official Anthropic documentation also makes the first submitting+Claude organization the listing owner; the current personal-account identity+needs an owner decision before submission. A concrete clarification email is+prepared locally but unsent. See the+[directory preflight](2026-10-07-directory-preflight.md#local-privacy-and-listing-disclosures-october-7).+Google OAuth-client creation remains the sole pending owner question; no cloud+trial, credential or deployment was added. Hosted in-app notices remain settled.diff --git a/docs/reviews/2026-10-06-v1-security-review.md b/docs/reviews/2026-10-06-v1-security-review.mdnew file mode 100644index 00000000..319e1d39--- /dev/null+++ b/docs/reviews/2026-10-06-v1-security-review.md@@ -0,0 +1,257 @@+# Kiln v1 adversarial security review++This is an in-progress release record, not security certification or hosted-launch+acceptance. The owner explicitly requested adversarial review before publication+of the hosted service. Review the final source, artifacts and live configuration+again when the production candidate exists.++## Boundaries and adversaries++- Treat anonymous OAuth clients, authenticated tenants, model-authored JavaScript,+ uploaded records and native evaluator output as untrusted.+- OAuth credentials belong only to the gateway's managed secret bindings. Tenant+ storage and native jobs must receive neither provider tokens nor cloud API keys.+- Select tenants from verified Kiln identity, never a request body, email address,+ model instruction or a container-supplied owner header.+- A new disposable provider VM is the native execution boundary. Node `vm`, a+ Linux user ID, a process timeout and local Docker fixture success are not that+ boundary. The external controller must enforce deadlines and destroy the VM,+ including children, before accepting its output or releasing admission.+- Registry source, archives, plugin bundles, images, CI artifacts and logs are+ public or may become public. Keep source, user assets and credentials out of+ operational error messages and qualification receipts.++## Findings and completed checks++| Check | Evidence on 6 October | Result and limits |+| --- | --- | --- |+| GitHub secret protections | Repository settings initially disabled secret scanning and push protection; both were enabled for `instruktlabs/kiln` only. A subsequent open-alert query returned `[]`. | Corrected configuration gap. No organization-wide policy, paid plan or validity-check setting was changed. An empty alert list is not proof that no unknown secret exists. |+| Local Cloudflare bindings | `.dev.vars`, `.dev.vars.*` and generated `.cloudflare/` were absent from `.gitignore`. Added ignores and kept only `.dev.vars.example` eligible for tracking. Root and nested paths were checked. | Prevents accidental staging; examples must contain placeholders. This does not remove anything already committed. |+| Git history | Gitleaks 8.30.1, `git --log-opts=--all --redact=100 --ignore-gitleaks-allow`: 484 locally available commits, 161.67 MB, no matching secrets. | Local reachable-history scan; not a claim about deleted remote history or every possible credential format. Raw values were never printed. |+| Published RC contents | Validated archive paths, extracted the exact approved `f2de7eb6…ea8c2` archive, scanned 24.07 MB with Gitleaks. | No matching secrets. A preliminary scan of the compressed file processed zero bytes and is explicitly excluded from evidence. |+| Hosted bundles | Five actual rebuilt production bundles and their build manifests, 402,232 bytes scanned with Gitleaks after the stream fixes. | No matching secrets. Build assertions exclude test/probe helpers and OAuth code from non-gateway bundles. These development bundles are not a production deployment. |+| Image build context | Four-file prepared context, 2,156 non-archive bytes scanned; its package archive is covered by the extracted RC scan. | No matching secrets. Full image-layer forensic inspection and final image qualification remain separate. |+| Production dependencies | `npm audit --omit=dev --ignore-scripts --json` for the hosting lockfile and actual registry-installed RC runtime. | Both report zero known vulnerabilities. Optional renderer and development dependencies are not covered by those two results. No automatic dependency mutation was performed. |+| Storage deadline | Two focused tests demonstrated successful completion after the configured deadline when readable-stream microtasks delayed timers. | Fixed by checking elapsed time when headers arrive and before/after each read; timeout aborts the request and cancels the body. Both tests failed before the fix. |+| Development image decoder | After #146 merged, GitHub identified `[email protected]` under development-only Miniflare. A full hosting audit reproduced the high-severity finding in sharp and its dependent Miniflare. | Applied a scoped Miniflare override to patched `[email protected]`, refreshed the npm lockfile and installed it with scripts disabled. The full hosting audit now reports zero vulnerabilities. All 112 hosting tests, typechecks, builds and root lint pass again. |+| Incoming body cancellation and streaming | Four additional failing tests covered an already cancelled request, continuously available chunks delaying timers, and reused read buffers in both transports. | Forward the incoming abort signal, check elapsed time during admission, cancel failed reads and copy bytes into a bounded growing buffer before the next read. Tiny or empty chunks no longer accumulate an array of retained views. All 116 hosting tests, typechecks, builds and root lint pass. |+| Engine maintainer dependency graph | The broader root Bun audit found eight affected transitive packages, including optional provider dependencies absent from the registry-installed runtime audit. | Updated named transitives within their declared dependency ranges, with install scripts disabled and no direct dependency changes. The root audit now reports zero known vulnerabilities. Rebuilt the Node bundles and build identity; typecheck, lint and 3,290 engine tests pass (two platform skips). |+| Renderer dependency graph | Full `npm audit --ignore-scripts --json` in `render-service/`. | Zero known vulnerabilities; distinct from renderer execution and provider isolation evidence. |+| Website dependency graph | Full Bun audit identified two high-severity packages and one moderate build-tool advisory. | Patched `http-cache-semantics` and `source-map-js` within their existing ranges. The remaining selector-parser advisory is recorded below, not dismissed or described as a clean audit. |++The storage and body fixes pass the focused source/asset integration tests, all **116 hosted+tests**, three TypeScript configurations, five production bundle builds and root+lint. It changes private hosting code, not the published RC or the deployed private+probe. No production service was deployed by these checks.++Local redacted reports and audit JSON are retained under+`.cache/security-review-2026-10-06/`. That ignored directory is not shipped or+committed. Record updated scans against the final candidate rather than treating+these development receipts as final release acceptance.++The development decoder finding is+[GHSA-wq5f-xc86-pv6w](https://github.com/advisories/GHSA-wq5f-xc86-pv6w), indexed+by GitHub on 6 October. Remove the scoped override when the qualified Miniflare+version itself pins a patched decoder. This change affects the local/CI test+harness, not the already-published RC or native image. The GitHub default-branch+alert remains open until the reviewed fix lands; it was not dismissed. Full audit+receipts are `hosted-full-audit-before.json` and `hosted-full-audit-after.json`.++The root lockfile refresh updates `@hono/node-server` to 2.1.3, `fast-uri` to+3.1.8, `fast-xml-parser` to 5.11.2, `hono` to 4.13.13, `ip-address` to 10.7.3,+`protobufjs` to 7.6.6, `proxy-addr` to 2.0.8 and `qs` to 6.16.0, plus the required+XML parser children. The MCP SDK explicitly permits the new Hono server major+(`^1.19.9 || ^2.0.5`); its Node >=20 requirement fits Kiln's supported Node range.+These are maintainer-lock changes, not a claim that the immutable public RC has+changed. Receipts: `root-audit.json`, `root-audit-after.json`,+`render-service-full-audit.json`, `runtime-build.log` and `root-tests.log`.+The full coverage run also passes all 3,290 tests, with functions at **95.16%**+(minimum 94.00%) and lines at **92.50%** (minimum 92.10%). No threshold was lowered.+The rebuilt engine also passes all 116 hosting integration tests. Receipts:+`root-coverage.log` and `hosted-tests-rebuilt-engine.log`.++The site now resolves `[email protected]` and `[email protected]`.+It still resolves `[email protected]` through the exact dependency+of the current `@tailwindcss/[email protected]`. The+[moderate advisory](https://github.com/advisories/GHSA-rj75-hqrm-r3gf) concerns+synchronous parsing of attacker-supplied selectors in a request path; it explicitly+excludes ordinary build-time parsing of trusted sources. Kiln's website uses this+dependency during its static build and exposes no selector-parsing request+handler. This is a reachability assessment, not a patched dependency. Keep the+finding tracked until the upstream dependency can be updated and re-evaluate+before accepting user CSS or running an online CSS parser. Do not introduce a+forced major override merely to make the audit count zero.++Local site checks report 78 files with no errors, warnings or hints. Site tests+report 620 passes, two skips and two failures: Windows denied creation of file+symlinks (`EPERM`) in the deployment-preflight fixtures, before the assertions.+No security assertion was weakened and no workstation permission was changed.+The Linux website workflow `37498513008` passes at `abe5a445`, qualifying the+updated lockfile and those symlink assertions on the supported runner.+Receipts: `site-audit{,-after}.json`, `site-check.log` and `site-tests.log`.+The full local website build succeeds, including public-text checks and its+private-data scan (zero findings). This is a dependency compatibility check on a+dirty development tree, not a reviewed deployment candidate or a public content+update. The build was not uploaded. Its receipt is `site-build.log`.++### Private image layer scan++The exact private trial image (`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`)+was exported locally. An initial direct OCI-archive scan read only 15,437 bytes+of metadata; that is not layer coverage. All ten layer blobs and the image config+were then copied to an ignored scan directory with their correct archive types,+after verifying each blob against its SHA-256 name. No layer paths were extracted+into the host filesystem and no image links were followed.++The layer scan processed 80,577,025 bytes and reported six generic-key matches:+one in Node's public `v8-internal.h`, five in cached public `jose` registry+metadata. The complete header is identical to Node's official v22.23.3 source;+the complete parsed cache metadata is identical to a fresh public npm response.+All six therefore refer to public upstream content rather than Kiln credentials.+The report remains intact with full redaction; no broad suppression was added.++Fourteen archive-read diagnostics were examined individually. Thirteen were+symbolic links, which were not followed. One was an 83-byte plain-text dpkg+alternatives record with a misleading `.gz` suffix; a separate text scan passed.+This is a bounded text/recognized-archive secret scan, not analysis of arbitrary+binary contents or proof against unknown credential formats. The final production+image still needs its own scan and qualification. Receipts:+`native-image-layer-inventory.json`, `native-image-layers-redacted.json`,+`native-image-findings-triage.json`, `native-image-scan-errors.json` and+`native-image-fallback-redacted.json`.++## Reviewed controls and required live evidence++The current code uses verified provider subject IDs, primary-consistent account+status/authorization epochs, PKCE, resource binding, one-use login intents,+provider-bound callbacks, browser-origin checks and an explicit consent page.+Accounts are not linked automatically by matching email. GitHub asks for no+repository scope. Google ID tokens are verified by `oauth4webapi`; provider tokens+are used for sign-in and discarded. Gateway-to-tenant forwarding excludes bearer+tokens, cookies and identity-provider credentials. These are implementation+observations, not a claim that live sign-in is already qualified.++Before hosted launch, retain evidence for:++1. Google and GitHub real sign-in, client consent, PKCE/resource mismatch, state+ replay, provider mix-up, denied authorization and malicious redirect attempts.+2. Browser account/session controls, explicit provider linking with fresh proof+ of both identities, connection revocation, account deletion and cross-region+ denial after account status or authorization epoch changes.+3. Cross-account source, saved revisions, material closure and download access;+ expiry/deletion, interrupted writes and storage/account quotas under concurrency.+4. Native provider network denial, fresh filesystem/process state, cancellation,+ deadline/output/memory exhaustion, cleanup failure recovery and fixed immutable+ image identity. Keep tests bounded and inside the approved disposable trial.+5. Global registration and compute admission limits, request body/stream limits,+ safe errors and logs, and operational cost/abuse controls under load.+6. Final archive/plugin/image/build-log scans, scoped managed secrets, repository+ protections, release environment review and actual publishing provenance.++## Current primary guidance++Checked on 6 October 2026:++- [Cloudflare Workers secrets](https://developers.cloudflare.com/workers/configuration/secrets/):+ use secret bindings and ignored local binding files; never put secret values in+ committed configuration or ordinary `vars`.+- [Cloudflare native Container API](https://developers.cloudflare.com/containers/api/durable-object-container/):+ `user` is numeric `uid:gid`; with the `durable_object` policy it does not restrict+ Linux capabilities. Output buffering counts against Worker memory. Preserve the+ VM boundary and bounded stream handling outside untrusted execution.+- [GitHub secret scanning](https://docs.github.com/en/code-security/concepts/secret-security/secret-scanning)+ and [Actions secrets](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets):+ scanning, push protection and secret-safe workflow design are complementary.+- [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/): preserve the+ existing scoped OIDC publishing configuration instead of adding a long-lived+ npm token. Registry staging, maintainer approval and public promotion remain+ separate steps in this repository's release runbook.++## Browser account continuation++The separate account-controls branch now has locally tested direct sign-in,+browser sessions and logout. Review checked fresh random credentials, hashed+storage, host-only Secure/HttpOnly cookies, idle and absolute expiry, session+rotation, current primary account/epoch checks, origin and CSRF validation,+single-use login state and provider/browser binding. A concurrent callback test+admits exactly one exchange; expired, swapped or stolen callbacks make no provider+request. Database-failure fixtures verify rollback. Sign-in state is capped at+4,096 pending rows, which is a storage safeguard rather than a public rate limit.++The session-cap review found that replacing one browser's session could prune+another device unnecessarily. A focused test failed first; deletion of the old+browser token now precedes cap pruning in the same transaction. All nine session+tests and 34 authentication tests pass. The complete hosted suite passes 138 tests.+Signing out of the browser leaves MCP grants intact; MCP cookies and bearer tokens+are never interchangeable. No test-only issuance endpoint enters production.++Extracting the GitHub adapter exposed a gap in the build guard: a future accidental+import could evade its old `auth.ts` filename check. Two tests build the actual+GitHub/account-page dependency graphs and first demonstrated that gap. The guard+now rejects those provider and browser modules from every non-gateway bundle,+including paths reported with Windows separators. All five actual production+bundles pass the guard.++These controls follow the current [OWASP session guidance](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)+and [CSRF guidance](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).+This does not yet qualify sensitive account actions: fresh provider responses do+not necessarily prove a fresh password or MFA challenge. Explicit linking,+connection revocation, account/asset deletion, public admission limits and deployed+cross-region/user tests remain launch gates. Local screenshots establish only the+account page's desktop and mobile layout.++## Connection-authority continuation++The account-controls candidate now records each MCP authorization in primary D1.+Authorization-code exchange atomically activates a pending connection once;+resource and refresh validation check the same connection after library token+validation. A stale-KV regression restores the old grant record and proves that+the consumed code cannot exchange again. Disconnect first commits the primary+deny, then performs supplemental KV cleanup. No provider token or MCP bearer+value is stored in connection rows.++Disconnect confirmation is bound to its account, epoch, browser session, purpose,+target, selected linked provider, action cookie, state and PKCE/nonce. A consumed+state cannot be retried, including concurrent callbacks. Cancellation, expiry,+wrong identity, missing/revoked browser sessions and forged/oversized forms fail+closed. Other connections keep working. Provider account selection is not proof+of a fresh password or MFA challenge; this narrower confirmation policy applies+only to disconnecting an app, not linking identities or account deletion.++The actual connections dependency graph exposed another build-guard gap. Its+focused test failed before the guard was extended, then passed for every+non-gateway output and Windows path form. All five actual bundles pass. The+account page escapes registered client text; local desktop and 375px checks show+wrapped names and 44px controls without horizontal overflow. The fixture contains+no real account data and makes no network requests.++The complete hosted suite passes 150 tests, all three hosted typechecks and all+five bundle builds. Root typecheck/lint pass. Redacted scanning of the actual+442.03 KB production output reports no matching secrets. Receipts are retained+under `.cache/security-review-2026-10-06/`; exact-commit Linux/Windows CI follows.++Public admission/rate controls, global account/storage bounds, provider linking,+account deletion, live confirmation, deployed revocation and recovery remain+outstanding. Local tests and a secret scan cannot substitute for those gates.++## Acceptance++The integrated branch now also covers durable compute admission and authenticated+edge discovery. Reservations survive unknown cleanup and eviction; only a verified+whole-tree cancellation acknowledgement releases them. Fixed metadata/helper queries+have no native or storage service available. OAuth scope and primary account/connection+checks run before this path; the new real-workerd regression denies metadata after+connection revocation even with OAuth KV records intact. Native request bytes and+trusted tenant selection are preserved after the edge routing check.++The current branch passes 245 hosted tests, three hosted typechecks, ten production+bundles and root typecheck/lint. Redacted source and actual-bundle scans processed+795,878 and 2,577,844 bytes respectively without matches. The package's published+state is separate from these development checks; no production deployment occurred.+Receipts: `.cache/edge-hosted-tests.log`, `.cache/edge-source-scan.json` and+`.cache/edge-bundle-scan.json`. Integrated provider isolation, account deletion,+identity linking, live OAuth, operations and final image/configuration review remain open.++Open. Secret hygiene and a passing local test suite do not establish secure public+hosting. Stable npm publication is complete; production deployment still requires+its concrete reviewed candidate and the owner's approval.diff --git a/docs/reviews/2026-10-07-directory-preflight.md b/docs/reviews/2026-10-07-directory-preflight.mdnew file mode 100644index 00000000..dc2494ae--- /dev/null+++ b/docs/reviews/2026-10-07-directory-preflight.md@@ -0,0 +1,344 @@+# Directory preflight, October 7, 2026++This is implementation and preparation evidence, not submission or vendor approval.+The published npm package and local plugin remain at 1.0.0. Hosted production is+not live. The owner selected in-app security notices only; no contact-email+collection or notification provider is part of v1.++## Hosted operation contract++[OpenAI's current guidelines](https://developers.openai.com/plugins/plugin-guidelines)+require separately exposed operations and explicit read-only, destructive and+open-world annotations. A discovery tool must not conceal executable operations+behind a generic executor. Stateful jobs count as writes even if their useful+result is a read or preview.++`hosting/src/public-tools.ts` derives `kiln.hosted-tools.v1` from the actual+15-tool native manifest generated from the pinned engine registry. It exposes 26+hosted tools:++| Engine entry | Hosted operation names |+| --- | --- |+| `kiln_renderer` | `kiln_renderer_status`, `kiln_renderer_reprobe` |+| `kiln_material` | `kiln_material_presets`, `kiln_material_create_preset`, `kiln_material_list`, `kiln_material_get`, `kiln_material_create_procedural`, `kiln_material_import` |+| `kiln_assets` | `kiln_assets_collections`, `kiln_assets_catalog`, `kiln_assets_list`, `kiln_assets_get`, `kiln_assets_restore` |+| `kiln_discover` | `kiln_discover` for catalog retrieval; `kiln_capabilities` for runtime facts |+| Remaining eleven entries | Existing names and registry-derived inputs |++The adapter selects relevant fields without copying their schemas. Engine parsing,+action requirements and execution remain authoritative. Caller-supplied action+selectors, unrelated top-level fields, hidden local tool names and conflicting+routing headers fail before native admission. Modern protocol metadata and matched+plain/Base64 tool-name headers survive translation. Resource requests keep their+native route. Registry action additions, missing mapped fields and unknown tools+fail closed rather than silently expanding the public surface.++Only catalog discovery is marked read-only. Every other hosted operation starts a+quota-admitted stateful native job; its description says so. Operations remain+confined to the private account, with no deletion/overwrite tools. Restoring source+and importing revisions are additive. Hosted instructions no longer tell remote+users to install a local renderer or read files beside the server executable.+Engine diagnostics can still mention local multi-action names; hosted instructions+explain how those names correspond to the exposed operations.++Two focused regressions failed before implementation. All 417 hosted tests, three+typechecks, thirteen production builds and root lint pass. Thirty focused checks+also pass after formatting and the hosted import-description correction. The+21-stage lifecycle fixture now calls the public operation names through the actual+edge adapter, then the real native MCP handler with private storage; it retains the+same admission and VM budgets. Native coordinator code and image inputs are+unchanged. Logs: `.cache/public-tools-*.log`.++This does not establish hosted client usability, live provider behavior, directory+compliance of the entire service, or acceptance. Those require the fresh private+trial, deployed client checks and portal validation/review.++## OpenAI candidate still to finish++The [submission documentation](https://developers.openai.com/plugins/deploy/submission)+requires a public HTTPS MCP endpoint, verified publisher/domain, four listing URLs+(website, support, privacy and terms), five positive and three negative cases,+demo recording and working review access. Use a new portable public ZIP with one+remote MCP definition; the existing private connector bundle is unsuitable.++Home, support and privacy pages are implemented; terms are not. Draft terms for+owner review before publication. Review access must work without signup or an+additional approval/MFA step, using a dedicated populated account. Google/GitHub+sign-in alone does not establish that requirement. Prepare an isolated review+identity and test it through normal authentication; do not add an authentication+bypass or weaken the owner's account. Keep reviewer credentials out of Git and the+ZIP, entering them only in the portal's designated secure fields.++The public ZIP, screenshots/video, real review account, positive/negative case+receipts and publisher/domain verification remain unfinished. Upload, submission,+vendor approval and publication require separate records.++## Claude Code candidate++The existing `plugins/kiln-engine` remains the local setup plugin; submit that+folder, not the repository root. Its version, launcher pins and identity are+unchanged. [Anthropic's preflight](https://claude.com/docs/plugins/pre-submission-checklist)+checks both plugin contents and repository archive limits. Local CLI validation+does not replace portal validation or the security scan. Registry installers can+receive a reviewer hold even when pinned.++Read-only measurement of commit `0b680d3b2fb9de2d76b0170fed0121a7021d8d3c`:++- 4,133 tracked blobs, 94,131,137 uncompressed bytes.+- Local Git ZIP: 42,057,936 bytes, below the documented 50 MiB archive limit.+- Plugin folder: nine files, 36,426 bytes; no file exceeds 256 KiB.+- `.gitattributes` has line-ending/binary rules and no export-ignore,+ export-subst, custom filter or LFS rule.++The locally generated ZIP is an estimate of GitHub's archive, not a portal receipt.+Recheck the exact submitted commit. No extra plugin repository is justified by+these measurements. Directory name availability, account eligibility and the+portal's findings remain unverified.++[Submission settings](https://claude.com/docs/plugins/submit) determine the tracked+branch/tag and publication behavior. Keep automatic publication off for the first+submission; the owner reserves public publication approval. Validate the exact+repository, folder and revision before submitting, and retain the resulting ID and+scan status. Directory submission does not promise placement in Anthropic's+separately curated official marketplace.++## Decision sequence++The prepared Google OAuth client approval remains the sole pending question.+Next, request the concrete refreshed private lifecycle candidate and allowance+after its exact CI and artifact hashes are ready. Then finish real sign-in and+account controls, owner-reviewable terms, review-account access and directory+identity/attestations. Do not repeat the settled in-app-notices decision or create+provider credentials, deploy publicly or submit a directory candidate implicitly.++## Public bundle and terms draft prepared later on October 7++All eighteen CI checks passed on `f701121590c8d4f4b71ac4a4bb7fde3b97b2ec8a`.+The following changes require their own committed-source CI and do not change the+published local package.++`hosting/scripts/package-public-plugin.mjs` now builds a portable public draft+from a fixed source list. It includes one HTTPS MCP definition, listing metadata,+a hosted authoring skill, four byte-identical maintained references, the existing+Kiln icon adapted to a 64px SVG, license and file provenance. It excludes local+installers, private connector dependencies, hooks, credentials and engine code.+The generated skill passes the skill validator. A local listing preview confirmed+the icon at large and toolbar sizes; it is not a directory screenshot.++The five positive and three negative review cases name only advertised hosted+operations. Before live qualification, create a dedicated review account through+normal authentication and seed a saved asset named **Review Stool**. Record its+account, asset/revision IDs and hashes in private qualification evidence. The+revision and download cases must each work from this seed independently; they+must not depend on the creation case, which uses **Review Stool Creation**.+Recheck fixture availability and quota before providing review access. No case+has been executed in a live assistant, and no reviewer identity exists yet.++The packager records exact source/file/archive hashes, refuses existing output+and produces a deterministic ZIP. Its receipt deliberately remains+`submissionReady: false`; demo URL, live case receipts, immediately usable review+access, publisher/domain verification and portal validation remain outstanding.+The draft README must be updated to reflect actual availability before submission.+Use the [maintainer command](../../hosting/README.md#public-plugin-preparation)+instead of uploading incomplete source files.++The gateway now serves a draft `/terms` page, linked from the public, consent and+account footer. It follows the owner's choices: free access within quotas, no+end-user billing, in-app security notices, private saved assets, seven-day unsaved+retention and independent local MIT-licensed use. It explains required processing,+user-controlled rights, acceptable use, availability and support. It adds no+payment subscription, arbitration clause or unreviewed liability cap. The owner+must review the terms with the concrete public deployment candidate; this draft+is not a legal review or certification. Its promise to surface material policy+changes is an operational commitment to honor before making future changes.++Two terms-route regressions failed before implementation. All 421 hosted tests,+three typechecks, thirteen builds and root lint pass locally. The actual terms+HTML was inspected through the local workerd preview; the existing script-free+layout, policy navigation and GET/HEAD restrictions remain in place. Logs are+`.cache/terms-{red,green}.log` and `.cache/public-plugin-final-*.log`; screenshots+are `.cache/hosted-terms-preview.png` and `.cache/public-plugin-listing-preview.png`.++No provider credential, public route, paid trial or submission was created. The+Google client approval remains the one pending owner question. The gateway change+requires refreshing the frozen lifecycle candidate before its approval request.++## Publisher portals and Claude validation, October 7++Read-only inspection found the existing **Instrukt Labs** OpenAI organization+marked **Verified** and its Plugins portal available. No ZIP was uploaded. This+removes a presumed new verification step; the submission still needs a selected+developer identity, MCP domain proof and live qualification. Organization+verification alone does not prove the final listing identity or domain challenge.++Anthropic's current signed-in account can open the submission form. Its portal+validated public `instruktlabs/kiln`, folder `plugins/kiln-engine`, tag `v1.0.0`,+resolving to `fda71ac775750f25390b6ee30082ebc56463edc6`. The source folder matched+the local bundle before the icon addition below. Seven checks finished: validation+passed with one warning and two policy holds. Repository retrieval, size, name and+publisher checks passed. The portal reports fourteen entries and 36.4 kB, including+directories; the local file inventory counts regular files separately.++The warning is a missing raster icon. The portal requires a square PNG/JPEG and+captures the first listing icon when saving/submitting the initial draft. A 512px+PNG export of `site/public/favicon.svg` is now maintained at+`assets/branding/kiln-512.png` and included by the local plugin packager at the+default `.claude-plugin/icon.png` path. Sharp 0.35.5 rendered the existing SVG at+density 1152, resized to 512 square, with PNG compression level 9. The 4,481-byte+file's SHA-256 is+`b4b651c402793b7e27cab780f04b14f80daec6d0cd5b7e4e90313930581a54e9`.+Its dimensions decode correctly and its appearance was inspected. The plugin's+runtime remains pinned to the published engine 1.0.0; no executable or engine+version changed. The published tag and npm archive remain immutable.++Both holds use `MCP_FORWARDS_CREDENTIAL_ENV`, referring to the installer's `pin`+beside `registry.npmjs.org` and combining that with setup guidance about a host.+The source review distinguishes the actual data flow:++- `pin` comes from the plugin's public `runtime.json`: package name and exact+ version. It is not an authentication PIN or token.+- Direct environment reads select local storage and the npm executable:+ `LOCALAPPDATA`, `XDG_DATA_HOME` and `npm_execpath`.+- The ordinary npm child inherits the caller's environment and npm configuration.+ npm can therefore use configured npm credentials with its registry. Do not claim+ that all credentials are stripped. Kiln passes a fixed public package/version+ and npm registry, disables install scripts and does not implement a separate+ credential collection or forwarding mechanism.+- Optional remote-renderer credentials in the shared setup guidance are configured+ by the user for that renderer. They are unrelated to the package-version pin.++Retain this explanation for the reviewer; a local code review cannot dismiss a+portal hold or predict Anthropic's decision. Do not rename or hide legitimate code+to evade the scan, or ask the user for a secret to replace the public version pin.+The [portal guidance](https://claude.com/docs/plugins/pre-submission-checklist)+distinguishes a hold from a blocking failure. Final GitHub push-access verification,+data-handling declarations, compliance acknowledgements and submission remain open.+No final submission or compliance acknowledgement was made, and no GitHub access+was granted. The validation form remains local to its browser tab until saved.++The new icon assertion failed first and all eight local-plugin packaging tests+now pass. The full offline gate passes 3,290 tests with two skips and no failures;+function coverage is 95.16% and line coverage 92.50%, above both thresholds.+Typechecking, lint and skill checks pass. Claude Code 2.1.287 validates the+manifest. Revalidate the exact new+commit in the portal before saving the listing, since the `v1.0.0` result cannot+qualify the added icon. Local evidence: `.cache/claude-directory-stable-validation.txt`,+`.cache/claude-directory-stable-validation.png`, and `.cache/claude-icon-*.log`.++## Correcting local-plugin platform support (October 7)++The portal revalidated `2339681`: the icon warning is gone and both credential+policy holds remain. All 18 CI checks passed on that source. Listing details then+exposed an inaccurate result: the skills-only component classification offered+Claude Code, Cowork and Claude apps. Kiln's installer requires a local shell and+persistent runtime/workspace directories; chat and Cowork are not qualified.++Anthropic's [platform support](https://claude.com/docs/plugins/platform-support)+and [executable documentation](https://code.claude.com/docs/en/plugins/components#executables)+identify a top-level `bin/` executable as a Claude Code component that excludes+chat and Cowork. The maintained installer is now actually shipped at+`bin/kiln-setup-workspace.mjs`, with a shebang and executable permission, and the+setup skill invokes that file. No dummy component or scanner-specific obfuscation+was added. Explicit Node invocation remains portable on Windows.++`plugins/kiln-engine.release.json` owns plugin version **1.0.1** and engine pin+**1.0.0** independently. Both plugin manifests and provenance use the plugin+version; `runtime.json` retains the exact published npm engine. This invalidates+plugin caches without replacing the public package, tag, installed engines or+assets. Maintained skills and both registered copies agree and explain the older+1.0.0 helper path. The package smoke check still accepts the published 1.0.0+provenance format while checking separate versions for newer bundles.++Four focused regressions failed before implementation. All 32 packaging/setup+tests now pass, including invocation from outside the checkout and POSIX+executable-mode checks (the latter execute in Linux/macOS CI). Isolated Claude+Code 2.1.287 and Codex 0.160.0 profiles installed 1.0.1 and ran the cached helper.+Both created a workspace with the public 1.0.0 npm archive, checked its integrity,+discovered 17 MCP tools, rendered, saved, reopened source and exported a GLB.+Codex app-server loaded exactly one setup skill, the three workspace skills and+one connected 1.0.0 MCP server. These probes made no model calls and changed no+normal user profile. Receipts are `.cache/plugin-101-{install,workflow,codex-appserver}.json`.+Exact-source CI and portal platform readback remain required after commit.++The full offline gate passes **3,291 tests**, with two skips, zero failures,+95.16% function coverage and 92.50% line coverage. Toolchain, skill consistency,+typechecking, lint and Claude manifest validation pass. Logs:+`.cache/claude-platform-{red,green,full-tests,types,lint,skills}.log`.++### Additional submission gates observed in the form++Data handling asks about personal data, outbound services, retention and intended+under-18 use. No answers were submitted. Prepare precise local-plugin disclosures:+installation contacts npm/GitHub, absolute local paths can contain a user name,+assets persist on the user's machine, and a user-selected remote renderer is+separate from the unlaunched hosted service. Add the appropriate local-plugin+privacy link and three documented use cases before owner review.++The compliance page currently names **Matthew Kissinger**, not Instrukt Labs, as+the submitting identity. Publisher identity needs resolving before acceptance.+It also asks the submitter to attest that the plugin does not execute code outside+declared MCP servers. The local setup executable does run npm and workspace setup+before a workspace MCP exists, so do not tick that statement without resolving its+meaning for documented executable plugins. A fresh candidate may change the form;+otherwise obtain clarification or select another supported submission path.+This is a directory-submission question, not evidence of a hosted execution flaw.++The [Software Directory Terms](https://support.claude.com/en/articles/13145338-anthropic-software-directory-terms)+and [Directory Policy](https://support.claude.com/en/articles/13145358-anthropic-software-directory-policy)+require accurate disclosures and applicable privacy/support information. They do+not resolve the form's executable wording. All declarations and legal acceptance+remain untouched; no submission, GitHub grant or external support message occurred.+Preserve the Google OAuth-client question as the sole pending owner approval.++## Local privacy and listing disclosures (October 7)++All **25 CI checks passed on `6a213b6`**, including the seven public-registry+installation jobs. Anthropic validated that exact source and now lists **Claude+Code only**; chat and Cowork are unavailable for the executable component. The+icon warning is absent, and the same two policy holds remain. Receipts are+`.cache/claude-directory-6a213b6-{validation,platforms,compliance}.txt` and the+platform screenshot. The executable acknowledgement remained unchanged after+this revalidation, so component classification alone does not resolve it.++The maintained local plugin now packages a [draft privacy notice](../local-plugin-privacy.md),+support and license links, and three setup examples: create, check and managed+upgrade. Both manifests advertise the same destinations. The notice distinguishes+local persistence and assistant tool results from hosted retention; it documents+npm/GitHub downloads, inherited npm configuration, normal cache/log writes,+explicit remote rendering and support-email forwarding. It does not promise to+strip npm credentials or erase copies controlled by another application.++The privacy URL targets `main`, where this new file does not yet exist. Owner+review and an approved merge are necessary before that URL can serve as a live+directory policy. The draft marker is intentional; this work does not claim+legal acceptance or submission readiness. Plugin version remains the unreleased+1.0.1 candidate, with the immutable published engine 1.0.0 pin.++The two packaging regressions failed first. All 32 packaging/setup tests pass;+typechecking, lint and strict Claude manifest validation pass. The full offline+gate passes 3,291 tests with two skips, no failures, 95.16% function coverage and+92.50% line coverage. The final cache/log prose clarification was followed by+regeneration, the 32 focused tests and lint. Fresh isolated Claude Code 2.1.287+and Codex 0.160.0 installations accepted the new metadata and included the privacy+file. Their actual engine/workspace behavior was already qualified on `6a213b6`;+the helper and engine pin are unchanged. Logs are+`.cache/local-plugin-disclosures-*.log`; installation receipt is+`.cache/plugin-101-disclosures-install.json`.++### Listing ownership and clarification queue++Anthropic's current [publishing guidance](https://claude.com/docs/directory/publish)+allows a personal Pro or Max account to submit. The first submitting Claude+organization owns the repository-folder listing; GitHub organization ownership+does not select that publisher. The page does not establish whether a personal+listing can later transfer to a business organization. Resolve the desired owner+before creating or submitting the official listing; do not purchase another plan+or assume a future transfer.++A local, unsent clarification draft asks `[email protected]` about the+executable acknowledgement, the two policy holds and publisher ownership. It+contains public repository details only. No external message, saved portal draft,+GitHub grant, declaration or legal acceptance has been made. Sending that draft+requires the owner's explicit authorization, sequenced after the already pending+Google OAuth-client creation question. Hosted in-app notices remain settled and+are unrelated to this support correspondence.diff --git a/docs/reviews/2026-10-07-hosted-pages.md b/docs/reviews/2026-10-07-hosted-pages.mdnew file mode 100644index 00000000..0502e544--- /dev/null+++ b/docs/reviews/2026-10-07-hosted-pages.md@@ -0,0 +1,85 @@+# Hosted information and consent pages++Local implementation and presentation evidence, not public launch acceptance.+The package and gallery README/site refresh remain deferred until hosted launch.++The gateway now serves `/`, `/privacy` and `/support` before creating an OAuth+server or looking up account/storage data. These routes retain ingress limits,+canonical-origin validation and private response headers. GET and HEAD work;+mutation methods and query parameters are refused. They set no cookies and make+no provider request. The home page describes Kiln, free hosted quotas, the local+package and the MCP address derived from the configured service origin.++One HTML shell now supplies the information, account and consent pages. It keeps+per-response style nonces, no scripts, data-only button images, same-origin form+submission, frame denial and links to privacy, support and account controls. The+consent response preserves the OAuth library's cookie headers and existing form+handle. Client text stays escaped; the client domain or unverified-name warning,+return host, loopback warning and requested permissions remain visible. Google+uses the existing vendor-provided button asset; GitHub and cancellation remain+ordinary form buttons. This is presentation work, not a new authentication flow.++## Privacy facts and remaining verification++The copy is grounded in current code:++- `google.ts`, `github.ts` and `accounts.ts`: only provider issuer/subject are+ retained from upstream identity; profile fields and upstream tokens are not+ persisted. Google requests `openid profile`; GitHub requests no additional scope.+- `browser-sessions.ts`, `connections.ts` and `worker.ts`: browser session expiry,+ bounded app connections and the distinction between browser sign-out and app+ disconnection. Linking never matches email addresses.+- `program-contract.ts`, `artifact-store.ts` and `asset-downloads.ts`: seven-day+ unsaved expiry, saved references, shared-file retention and authenticated,+ ten-minute download tickets. Expiry is not a claim of instant physical erasure.+- `account-deletions.ts`, `admission.ts` and `artifact-store.ts`: pending deletion,+ active-data cleanup, seven-day completed receipts and retained pseudonymous+ retirement records that block late writes or stale access.+- `operations.ts`: aggregate service telemetry excludes source, identities, IPs,+ URLs and credentials. Provider-managed operational data is described separately.+- Owner decision D10: notices are in-app only. The account activity page now says+ explicitly that sign-in changes and deletion do not produce email alerts.++Support uses the already selected `[email protected]`; it separates private+security/account reports from public issues and asks users to omit credentials.+The pages do not add an email sender, contact-email field or broader OAuth scope.++Sources refreshed on 7 October:++- [Google brand verification](https://developers.google.com/identity/protocols/oauth2/production-readiness/brand-verification)+ requires an accessible home page and a same-domain privacy policy that describes+ Google data handling. Domain verification, actual branding publication and live+ provider review remain open.+- [D1 recovery history](https://developers.cloudflare.com/d1/reference/time-travel/)+ and [SQLite Durable Object recovery](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/#pitr-point-in-time-recovery-api)+ can retain prior database state for 30 days. This is distinct from active-service+ deletion; production retention and retirement-safe restore still need qualification.+- [Analytics Engine limits](https://developers.cloudflare.com/analytics/analytics-engine/limits/)+ document three-month metric retention.++The draft copy must remain consistent with the actual production configuration.+It creates no public route, does not prove a published privacy policy or vendor+approval, and does not establish live account deletion, data recovery or support+delivery. Public deployment remains a separate owner-approved step.++## Qualification++The new route and consent assertions failed before implementation. The focused+65-test set then passed. All 410 hosted tests, three typechecks, thirteen production+builds and root lint pass. Logs are `.cache/public-pages-*.log`. A fixture with no+account database, OAuth KV, provider credentials, storage or compute proves public+information is available without those services; unexpected outbound fetches fail.+Existing consent tests still reject hostile client HTML, stolen handles and+cross-browser/cross-origin approval, and both provider workflows still pass.++A loopback-only presentation fixture rendered the actual page functions. The home+page was visually checked at the normal desktop viewport. Consent, home, privacy,+support and sign-in were checked with a 375-by-812 browser override: no horizontal+overflow; consent sign-in buttons are 198 by 44 pixels and cancellation is at least+44 pixels high. Privacy navigation works from consent before sign-in. The viewport+was restored afterward. The fixture has synthetic client information, refuses+POST and cannot contact a provider or native evaluator.++Local evidence: `.cache/public-home-desktop.png`,+`.cache/public-consent-mobile.png`, `.cache/public-pages-mobile-checks.json`.+This is layout and local protocol evidence, not successful Google/GitHub login.diff --git a/docs/reviews/2026-10-07-private-lifecycle-result.md b/docs/reviews/2026-10-07-private-lifecycle-result.mdnew file mode 100644index 00000000..7ed8dcf2--- /dev/null+++ b/docs/reviews/2026-10-07-private-lifecycle-result.md@@ -0,0 +1,109 @@+# Private hosted lifecycle qualification, October 7++The owner-approved candidate `4b3dc62ece74ec3b364f68b231a45d6deea15555`+passed its deployed gateway and native lifecycle qualification. This is private+Cloudflare integration evidence, not public-launch or live upstream OAuth acceptance.++## Candidate and results++All 25 CI checks passed before provisioning. Eight private Workers used temporary+D1, KV, R2 and seven SQLite Durable Object namespaces. The deployed module hashes,+current 100-percent versions, bindings, image references, nine migrations, disabled+public surfaces, logging and SSH were read back before invocation. No Google or+GitHub credential was bound to this candidate.++The fixed one-use run passed all 13 gateway preflight checks and all 21 native+stages. It created and read a procedural material, rendered and saved an asset,+reopened its editable source, exported and downloaded its GLB/material closure,+denied anonymous and foreign-account access, restored a removed material from the+saved revision, rendered again, and returned 429 after fourteen admitted MCP+requests. Denied source/material tool calls have HTTP 200 MCP error envelopes;+the checker verifies their denial and absence of leaked content.++The run consumed **20 VM starts**: fourteen coordinators, three evaluations and+three renders, below the approved ceiling of 22. Every observed instance stopped+with exit code zero. Admission was paused, with zero active requests or pending+cleanup, the allowance was permanently closed and no recovery alarm remained.++The render took 28.831 seconds; the render after restoration took 19.141 seconds.+The two 392-by-392 PNGs were byte-identical, SHA-256+`3f47657e2c3414ba0a54280cf04537e82f6d2fa3fa083482a2c0a777a4d6ca92`.+Visual inspection showed the expected textured cube. Both responses identified+software Vulkan/llvmpipe and full-material fidelity, without CPU fallback. The+in-loop result correctly remained `exactArtifact: false`; its input GLB hash matched+the downloaded 2,540-byte GLB. Independent glTF validation found zero errors and+warnings, one mesh/material/embedded PNG and no external resource URI. This small+fixture does not establish arbitrary scene quality, load capacity or owner acceptance.++Images remained pinned to:++- Coordinator: `sha256:d78f29a8565e2df4957f60607ee25645bff81e8221bc75b56b2992d7e17d4482`.+- Software renderer/evaluator: `sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`.++## Readback correction++The initial preflight refused to run. Cloudflare's raw script-settings endpoint+returned `observability: null`, while its CLI expanded disabled logging into+inactive defaults including `persist: true`. The verifier now requires independent+raw settings, rejects missing evidence and active/contradictory logging, and handles+the observed omitted empty collections and matching D1 ID alias. Regression tests+failed before the correction. All 425 hosting tests, typechecks, builds and targeted+lint passed after it; the correction is commit `f772edd`. The deployed runtime and+approved image bytes remained at `4b3dc62`.++The private remote observer also printed provider internal-error references while+its status, run and stop calls returned 200 and the durable results passed. Their+cause is unresolved. Retain this diagnostic separately from the successful actual+outputs and cleanup; qualify public HTTPS/client behavior without relying solely+on this development tunnel. No additional support message or compute retry was sent.++## Cleanup and costs++Before deletion, 36 synthetic R2 objects totaling 679,640 bytes were retained with+hashes. The operator rechecked exact IDs and stopped instances, removed the three+Container applications and eight Workers, then the bucket, D1 and KV. Final inventory+confirmed all seven trial namespaces absent too. The local observer was stopped+and port 8798 no longer listened. Registry images were intentionally preserved;+provider-managed Analytics Engine records have separate three-month retention.++The Analytics SQL catalog exposed the private dataset. Query readback confirmed+ingestion of the fixed route/status fields, and all six prepared alert queries+returned one numeric zero for an empty interval. No Cron was deployed in this+trial and no alert destination was configured; scheduled-health and delivery+qualification remain open.++Provider start-to-stopped intervals totaled 145.923 instance-seconds. At the current+[Container rates](https://developers.cloudflare.com/containers/platform/pricing/),+modeling fully allocated CPU over those intervals gives about **$0.0036** for+Container CPU/memory/disk before allowances. This is neither a metered invoice nor+the whole trial cost: Worker/DO/storage/image/egress charges and any startup billing+outside those timestamps are not measured here. The approved $1 was a spending+allowance, not a Cloudflare billing cap. Twenty actual starts are consumed; the+unused two-start ceiling does not authorize another run.++Local receipts: `.cache/lifecycle-operator/result-4b3dc62.json`,+`.cache/lifecycle-readback-4b3dc62-before3/`,+`.cache/lifecycle-readback-4b3dc62-after/`, and+`.cache/lifecycle-cleanup-4b3dc62/` (including `cleanup-receipt.json`,+`qualification-summary.json`, `independent-glb-validation.json`, images and retained+synthetic bytes). These ignored files contain local qualification evidence, not+publishable provider credentials.++## Identity and directory progress++Google and the organization-owned GitHub OAuth clients now exist. Their approved+credentials were encrypted and round-trip verified with Windows DPAPI outside+the repository. The exposed original Google secret was disabled. Neither provider+credential has been uploaded to Cloudflare, and successful live sign-in is unproven.+Google remains in testing mode; branding and production audience remain pending.++With explicit owner approval, an email was sent to `[email protected]` about+the local plugin's executable acknowledgement, the two validator policy holds and+Instrukt Labs publisher ownership. The connector returned a SENT receipt. This+was clarification, not a directory submission; no declaration or terms were accepted.++Remaining: deployed retention/recovery, live identity/account controls, operational+alerts and representative abuse/load/cost checks; a concrete approved public route+and real MCP clients; directory submissions; then the deferred README/Troy/site+documentation refresh. npm 1.0 and the GitHub release remain separate completed+deliverables. No new package was published by this work.diff --git a/hosting/DEPLOYMENT.md b/hosting/DEPLOYMENT.mdnew file mode 100644index 00000000..dadb82fe--- /dev/null+++ b/hosting/DEPLOYMENT.md@@ -0,0 +1,148 @@+# Hosted deployment preparation++This prepares the complete service locally. It does not provision resources,+upload images, store credentials, configure DNS or deploy a Worker. The generated+configuration exposes no HTTP route, workers.dev address or preview URL. It is+not a launch approval or proof that production is ready.++## Build a reviewable candidate++Use the pinned maintainer Node toolchain and installed `hosting/` dependencies.+Copy `deployment.example.json` to an ignored local manifest. Its placeholders are+intentionally invalid. Fill it only with verified non-secret resource IDs,+account-owned registry digests and reviewed numeric quotas. Never add a client+secret or token; unknown fields are rejected without echoing their values.+The example's nine-request compute limits are for qualification planning, not public+launch quotas or a VM-start allowance. A paid run needs its own bounded candidate+and approval, including child starts and cleanup.++`requestLimits` declares separate edge and account rate-limit namespaces and+per-minute thresholds. Choose distinct positive integer namespace IDs that are+unused elsewhere in this Cloudflare account; the provider shares counters across+Workers with the same namespace. Verify that inventory before deployment. The+example's 600 ingress requests per route class and 120 authenticated MCP/download+requests per account are candidate thresholds for qualification, not accepted+public quotas. Each window is 60 seconds. These are approximate per-location+limits, separate from the durable compute/storage budgets.++From the repository root:++```sh+node hosting/scripts/prepare-deployment.mjs \+ --manifest .cache/hosted-deployment-input.json \+ --output .cache/hosted-deployment-candidate+```++The parent directory must already exist inside `.cache`; the output must be new.+Existing or partial outputs are never overwritten. The command bundles actual+production entrypoints, checks their dependency boundaries and exported classes,+copies all numbered D1 migrations, and records SHA-256 hashes. The receipt records+the source commit and whether the checkout was dirty. A dirty receipt cannot be+treated as exact-release source qualification. It also does not attest that the+specified cloud resources exist, belong to this deployment, or contain the+expected image bytes; verify those separately before deployment.++Outputs include Cloudflare Build Output plus six equivalent `*.wrangler.json`+files and `deployment-receipt.json`. Both use pinned `@cloudflare/[email protected]`.+Its API is currently unstable, so changes require renewed validation. The Wrangler+conversion corrects only local DO self-bindings; cross-Worker bindings retain their+explicit target. Use a tested CLI and `--no-bundle` to deploy the reviewed bytes.+Wrangler `deploy --dry-run --no-bundle --config <file>` checks configuration locally;+it does not verify remote bindings, image availability, secrets or permissions.++## Service boundaries++| Role | Private capabilities | Public entrypoint |+| --- | --- | --- |+| Gateway | Account D1, OAuth KV, edge/account rate limits, four provider secret names, owning tenant DOs, `KilnCompute` | None in prepared output |+| Tenant | Private R2 and tenant SQLite quotas, saved assets/materials, downloads and retirement | None |+| Admission | Global admission SQLite and native request DOs | None |+| Request | Tenant storage, fresh evaluation/render DOs and three host-bound interceptors | None |+| Evaluation | Pinned software image, evaluator DO and whole-VM cleanup | None |+| Render | Pinned software image, renderer DO and whole-VM cleanup | None |++Only the gateway declares `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`,+`GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`; their values must be provisioned+through the provider's secret mechanism, never committed or copied into this+manifest. No gateway binding exposes `KilnComputeControl`; a separately authorized+private operator is needed to pause/resume and inspect admission.++Coordinator/evaluation/render use immutable account-owned registry references.+The runtime selects the established `standard-1` coordinator and `standard-2`+child profiles, deadlines and disabled native internet access. The manifest cannot+choose arbitrary entrypoints, internet settings or instance classes. SSH and+Container logs remain disabled. Application resource identity and runtime network+denial still require provider readback and a real trial.++Gateway URLs may contain OAuth codes or private download capabilities. The+prepared Workers disable persistent invocation logs and traces and request query+redaction. These settings do not establish a complete observability plan or+absence of provider-managed operational data. The gateway's Analytics Engine+binding emits only explicit aggregate fields, and preparation hashes six proposed+alert queries in `monitoring-candidate.json`. Ingestion, account eligibility,+thresholds and alert delivery remain launch gates. See [operations](OPERATIONS.md)+for the schema, retention, expected volume and qualification sequence.++The gateway now limits fixed route classes before OAuth or database work, then+limits verified accounts across MCP clients and browser downloads before storage+or native dispatch. No IP, bearer token, cookie, source or arbitrary URL enters a+counter key. Denial returns 429 with a 60-second retry suggestion; missing or+failed bindings return 503. Local tests cover these boundaries and real local+binding exhaustion. No production binding or threshold is deployed yet. Coarse+ingress exhaustion can temporarily deny every user in the affected route class+and location; representative load and abuse qualification must assess that+availability tradeoff. It does not prevent billed Worker invocations or provide+an exact worldwide request ceiling.++## Ordered deployment and launch gates++1. Qualify the exact source in CI and record the engine archive, coordinator image,+ software image, every Worker/config hash, migrations and resource inventory.+ Provision approved isolated resources separately and read their ownership back.+2. Apply the D1 migrations to the intended database, after checking identity+ uniqueness and backup/restore handling. Configure provider clients with exact+ approved callback URLs and secret bindings only on the gateway.+3. Deploy tenant, evaluation and render, then request, admission and gateway, in+ that dependency order. Read back all external namespace/service links. Deploy+ retirement-aware services before accepting deletion; drain older work first.+4. The gateway configuration includes an every-minute Cron Trigger. Read back the+ deployed trigger and verify recovery after an interrupted deletion. Track the+ oldest pending job, failures and unresolved writes; the source handler alone+ does not prove that scheduled recovery operates.+5. Complete bounded private qualification of the newer evaluator identity,+ materials, browser downloads, link/unlink/delete, quotas, retention and cleanup.+ Verify live Google/GitHub consent and real MCP clients separately. The earlier+ `c755434` receipt covers only its recorded code and scope.+ The [gateway preflight stage](probe/GATEWAY_PREFLIGHT.md) locally exercises+ the prepared six-Worker topology with synthetic accounts and paused native+ admission. It is a component of the next trial, not live qualification or+ authorization to reuse the prior allowance.+6. Before public exposure, qualify ingress abuse protection, representative+ load/costs, operational alerts, backup retention/restore, privacy/support pages+ and rollback. Cloudflare's edge rate-limit binding is local and approximate;+ it must not replace global compute admission or be represented as a billing+ cap. Review public quotas and the final cost model with the owner.+ Exercise streamed oversized/unauthenticated/rate-limited requests followed by+ ordinary requests through the real public gateway. Verify client-visible+ 401/413/429 behavior and continued availability; local workerd early-response+ reset reports are not deployed acceptance evidence.+7. Prepare the exact gateway route change at `kiln.instruktlabs.com` for approval.+ Do not infer permission from preparation or an earlier private-trial allowance.+ Following approved deployment, verify deployed identity, live lifecycle and+ two-user separation before directory submission.++Rollback must preserve primary account revocation and permanent tenant retirement.+Do not restore pre-deletion code or a backup that reactivates retired accounts;+pause access and reconcile first. Existing private data must never be silently+replaced with fresh namespaces to obtain a passing check.++The next private combined candidate is prepared with `--private-lifecycle`; its+fixed eight-Worker topology, bounds and cleanup procedure are documented in+[NATIVE_LIFECYCLE.md](probe/NATIVE_LIFECYCLE.md). That mode has no provider secrets+or public routes and cannot serve as a production launch configuration.++Current references:+[Cloudflare configuration](https://developers.cloudflare.com/workers/wrangler/configuration/),+[Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/),+[Rate-limit scope and accuracy](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/),+[Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/).diff --git a/hosting/OPERATIONS.md b/hosting/OPERATIONS.mdnew file mode 100644index 00000000..ee15560a--- /dev/null+++ b/hosting/OPERATIONS.md@@ -0,0 +1,121 @@+# Hosted operations and alert qualification++This is implemented locally, not deployed or monitored yet. The complete+deployment builder emits a gateway `OPERATIONS` Analytics Engine binding and a+hashed `monitoring-candidate.json`. Its six alert queries are candidates for+provider validation; none has an enabled destination or delivery receipt.++## Data collected++Only the gateway writes the dataset named `<deployment_prefix>_ops`, replacing+hyphens with underscores. It records one explicit point per completed HTTP+handler and two points after each scheduled recovery run. No request/response+object, body, arbitrary URL, IP, identity, credential, exception or download ticket+is passed to Analytics Engine. Invocation logs, traces and Container logs remain+disabled. This does not describe all provider-managed operational records.++Every point has `blob1 = kiln.ops.v1` and `double1 = 1`. Remaining columns are:++| Kind / index | blob2 | blob3 | blob4 | double2 | double3 | double4 | double5 |+| --- | --- | --- | --- | --- | --- | --- | --- |+| `http` | http | fixed route class | HTTP status | elapsed ms | unused | unused | unused |+| `health:deletion` | health | deletion | ok/unavailable | pending jobs | oldest age ms | jobs at least 15 minutes old | recovery handler succeeded: 1/0 |+| `health:compute` | health | compute | ok/unavailable | paused: 1/0 | active requests | pending cleanup | concurrency limit |++Route classes reuse the bounded ingress categories. HTTP elapsed time ends when+the handler returns its Response; it does not measure complete browser download+or model response latency. HTTP 200 does not prove a successful MCP tool result,+artifact quality or rendering fidelity. Provider CPU/VM/storage usage remains+separate cost evidence.++Deletion health reads primary D1 using indexed phase selection. Compute health is+a read-only RPC returning aggregate admission state, with no tenant IDs or pause+control. Both reads run independently with two-second deadlines. Failed or invalid+reads emit `unavailable` and numeric `-1`, never healthy zero. Failed recovery or+unavailable component health also fails the scheduled invocation with a fixed+message. A telemetry write failure cannot change authorization, returned bytes or+cleanup. Missing telemetry must be caught by external heartbeat alerts.++The write API is asynchronous; a successful local call is not proof of ingestion.+Cloudflare documents three-month retention and adaptive sampling. Keep these+aggregate records distinct from the saved-asset and seven-day unsaved policies.+[Writing points](https://developers.cloudflare.com/analytics/analytics-engine/get-started/),+[retention](https://developers.cloudflare.com/analytics/analytics-engine/limits/).++## Alert candidates++The builder emits six queries scoped to the exact account and+`events.analyticsEngine.<dataset>`, each returning one numeric `value`. They use+a five-minute lookback, proposed one-minute evaluation and hourly repeat interval.++| Candidate | Trigger | Initial operator action |+| --- | --- | --- |+| Deletion heartbeat | No healthy successful recovery observation | Check Cron Trigger, deployed version, D1 and ingestion availability |+| Compute heartbeat | No available compute observation | Check binding and admission state; preserve active cleanup evidence |+| Deletion overdue | An observation reports a deletion at least 15 minutes old | Inspect the private recovery job and phase; do not claim completed deletion |+| Compute cleanup | At least three observations report pending cleanup | Pause expensive work through the private operator; investigate VM shutdown |+| Gateway errors | At least five HTTP 5xx responses | Separate upstream identity/storage/native failures before changing limits |+| Gateway rejections | At least 100 HTTP 429 responses | Inspect legitimate demand versus abuse; preserve compute quotas |++These are initial tuning proposals, not an SLA. Counts in sampled data are+estimates, and the cleanup observations need not be consecutive. Heartbeat+queries intentionally aggregate without grouping: an empty interval must yield+zero rather than no result. Confirm that behavior in the actual query preview.++The current Cloudflare Custom Alerts beta supports account-scoped Analytics SQL+queries. This dialect automatically applies supported sample weights; do not+paste legacy Analytics Engine queries with `_sample_interval` into it. Catalog,+plan access and query validation still need live verification for this account.+[Custom Alerts](https://developers.cloudflare.com/notifications/notification-available/#custom-alerts-beta),+[Analytics SQL dataset rules](https://developers.cloudflare.com/analytics/sql-api/datasets/#workers-analytics-engine-datasets).++Before public launch:++1. Read back the gateway dataset binding and recurring trigger. Deploy the+ admission health RPC before the gateway that calls it. Missing old RPC support+ is an unavailable observation, not a passing health check.+2. Query the account catalog with `cf analytics sql introspection get --account-tag <account-id>`+ using authorized Account Analytics Read access. Discover the exact dataset+ after a bounded synthetic request and scheduled invocation produce points.+ For SQL queries that already contain `accountTag`, do not also pass a request+ scope: the current API rejects duplicated tenancy predicates. Use timezone-aware+ ISO 8601 literals for fixed timestamp windows.+3. Preview each prepared query and verify normal, unavailable, empty-window and+ delayed-deletion cases. Tests currently validate the local schema and query+ construction, not remote query execution or sampling behavior.+4. Configure an owner-approved operational destination and these thresholds in+ Custom Alerts. Read back the enabled settings and prove both alert and recovery+ delivery. Never assume a configured query will notify anyone. No operational+ email or webhook has been sent by this implementation.+5. Also configure provider billing/usage alerts and an independent public endpoint+ check. A Cloudflare-wide outage can affect both service and Cloudflare alerts.+ Provider alerts do not impose a spending cap. Keep private pause/restore and+ retirement-safe rollback procedures available during an outage.++## Expected telemetry volume++At one successful scheduled run per minute, the two health points total 86,400+per 30-day month, plus one point per HTTP invocation that reaches a response.+For example, one million HTTP requests yields about 1.0864 million points.+Six alert queries every minute would be 259,200 evaluations per 30-day month;+confirm Custom Alerts entitlement and charging separately from the data API.++Cloudflare currently publishes 10 million included monthly writes and one million+read queries for Workers Paid, then $0.25/million writes and $1/million reads;+the page also says charging has not started yet. Treat those as planning rates,+not proof of the account's bill. Verify current billing at deployment and include+other datasets' usage. [Pricing](https://developers.cloudflare.com/analytics/analytics-engine/pricing/).++## Private ingestion evidence, October 7++The account catalog exposed `events.analyticsEngine.kiln_private_lifecycle_v1_ops`+after the approved lifecycle trial. A scoped query returned the expected fixed HTTP+route/status categories, including 401, 404, 413 and 429. All six prepared alert+queries executed successfully. Their empty five-minute windows returned a numeric+zero row, so heartbeat absence can produce a threshold signal rather than no row.+The private candidate deliberately had no Cron; this does not prove successful+scheduled health ingestion, Custom Alerts eligibility, notifications or recovery+delivery. No alert was created or message sent by these read-only checks.++Receipts are `analytics-*.json` under `.cache/lifecycle-cleanup-4b3dc62/`.+See the [trial result](../docs/reviews/2026-10-07-private-lifecycle-result.md).diff --git a/hosting/README.md b/hosting/README.mdindex e797c309..052807ad 100644--- a/hosting/README.md+++ b/hosting/README.md@@ -5,6 +5,9 @@ inside `@instruktlabs/kiln` and introduces no cloud dependency into the engine.It is not deployed or ready for public traffic. Native provider qualification,native dispatch, deployed storage, operational quotas and launch checks remain open.+The [deployment guide](DEPLOYMENT.md) prepares the six-service configuration,+immutable bundles and migrations locally without creating resources or public routes.+## Local checksUse the repository's Node 22.23.3 and npm 12.2.0 maintainer toolchain:@@ -56,11 +59,210 @@ validation, authorization-code exchange and refresh checks the current primaryaccount state and authorization epoch. Missing/disabled/deleting accounts and oldepochs fail closed; database outages return unavailable rather than permittingcached access. Account lifecycle mutations must increment the epoch atomically.-Explicit identity linking, browser sessions, connection controls and completed-asset deletion remain required before launch.+Browser sessions, direct sign-in and explicit identity linking now have local+qualification. Deployed account/connection controls and completed asset deletion+remain required before launch.Only verified server-side provider adapters may call this contract. The JSONinterface under `test/` exists solely for local tests and is not a public API.+### Browser account access++`/account` renders sign-in or the current account's linked provider names. Direct+sign-in and MCP authorization share the verified Google/GitHub adapters and exact+provider callbacks. Direct sign-in does not register a synthetic MCP client or+issue MCP tokens. Its `kb1_` state selects a separate D1 transaction namespace;+the state and an independent browser cookie must both match before a provider+exchange. D1 atomically consumes the transaction, including cancellation. Stored+state and cookie bindings are hashed with the service origin and their purpose.+PKCE verifiers and nonces remain server-side for at most ten minutes. The table+admits at most 4,096 pending transactions and opportunistically removes expired+rows. This storage bound does not replace the required public rate/admission limits.++Successful verified callbacks issue a new `__Host-kiln-session` cookie with Secure,+HttpOnly, SameSite=Lax and Path=/, never Domain. D1 stores only its SHA-256 verifier,+with a separate CSRF value, account ID and authorization epoch. Sessions expire+after 30 minutes idle or 24 hours absolute, whichever comes first. Each successful+read atomically renews only the idle deadline and checks the current primary account+state/epoch. Fresh sign-in revokes that browser's previous session; at most eight+sessions remain per account. Rotation at the cap preserves the other seven devices.++Logout requires a same-origin POST, a bounded form and that session's CSRF value.+It revokes only the browser session; it deliberately leaves MCP connections and+other devices intact. Browser cookies cannot authorize `/mcp`, and MCP bearer+tokens cannot authorize account pages. No account selection comes from a form or+URL. Session issuance accepts only verified server-side identities. A recent+callback is not proof of a fresh password/MFA challenge. The explicit linking and+deletion flows below confirm provider control with separate purpose-bound state.++Migrations `0003_browser_sessions.sql` and `0004_browser_logins.sql` add these+tables. Workerd tests cover expiry, rotation, concurrent callbacks, cross-provider+and cross-browser rejection, SQL rollback, storage bounds and logout/connection+separation. The account page uses a nonce-restricted style block and a Google-+provided button image embedded locally; see [asset provenance](assets/README.md).+Local desktop/375px layout checks establish presentation only, not live provider+authentication or final launch acceptance. Privacy pages, full account controls+and the branded MCP consent experience remain open.++### Connected-app controls++Migrations `0005_connections.sql` and `0006_account_actions.sql` add independently+revocable MCP connections and purpose-bound confirmation transactions. A connection+becomes active through one atomic primary-D1 claim during authorization-code+exchange. Every resource request and refresh checks its current account, epoch,+client and connection state after the OAuth library's token validation. Stale KV+records cannot replay an exchanged code or re-enable a revoked connection.+Connections expire after 30 days; at most 32 pending/active connections are admitted+per account. Expired pending connections are retired after ten minutes.++`/account` lists connections and accepts a same-origin, CSRF-protected disconnect+form. Confirmation requires the current browser session, an independent action+cookie, one-use state, PKCE and a freshly verified identity already linked to that+account. Google also verifies the OIDC nonce. The primary SQL revocation commits+before optional OAuth KV cleanup; other connections remain usable. The browser+session rotates after confirmation. This blocks subsequent requests; it does not+cancel already admitted computation. Public rate/admission controls remain required.++Both providers' `prompt=select_account` asks the user to choose an account; it+does not prove a new password or MFA challenge. Sources:+[GitHub OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps),+[Google OIDC](https://developers.google.com/identity/openid-connect/openid-connect).+Identity linking uses its separate purpose-bound flow below. This disconnect flow+must not be repurposed to merge or delete accounts.++Local workerd checks cover concurrent callbacks, cancellation, expiry, copied+state, wrong identities, revoked sessions, forged forms, hostile client names,+oversized requests and retained access by another connection. Layout checks use+synthetic identities only. Live provider confirmation, cross-region denial and+production migration/rollback remain unqualified.++### Explicit sign-in method changes++Migration `0008_identity_actions.sql` adds separate linking transactions, a unique+provider-per-account constraint and bounded account security activity. Apply it+before the new gateway. It leaves existing accounts and identity keys intact;+preflight the uniqueness constraint against any existing database before migration.+The earlier gateway can run with these additive tables, but rollback must preserve+committed identity changes and authorization epochs, not restore an old database.++`/account/identity` accepts only a bounded, same-origin, CSRF-protected form from a+current browser session. Adding a method confirms an existing provider first,+then authenticates the new provider using a new state, cookie, PKCE verifier and+nonce. Each phase expires after five minutes and is atomically consumed before+provider I/O. Both callbacks are tied to the original session and current account+epoch. Account, session and confirmed-identity checks run again inside the final+database transaction. An identity owned by another account is refused; email is+never compared, and existing libraries cannot be merged.++Removing a method confirms control of the other method that will remain. The last+method cannot be removed, including concurrent requests from different browsers.+Each successful change updates the identity, appends a security event, increments+the account epoch and revokes all browser sessions atomically. Existing MCP access+and refresh credentials fail their primary state checks even if provider KV still+contains the old grants; those records expire under their existing TTL. Users sign+in again and reconnect their apps. Already admitted jobs are not cancelled by this+change. The permanent account ID and asset/usage namespace stay unchanged.++The UI explains these effects before confirmation and shows the latest 20 security+events. Events record provider, action and time, without tokens, email or IP address.+Pending intents are capped at four per account and 4,096 globally. These limits do+not replace public rate limits. Session deletion cascades to pending confirmations.+The success page and activity list are **in-app notices only**, as selected by the+owner for v1. Out-of-band security email and verified contact collection are deferred,+not implemented or qualified. Provider confirmation can reuse an existing provider+session; it is not evidence of a fresh password or MFA challenge. No assurance-level+certification is claimed.++Workerd fixtures exercise real gateway, provider validators and D1 transactions+with mocked upstream providers: both link directions, stable account ownership,+foreign-identity refusal, cancellation, expiry, replay, concurrent callbacks,+concurrent unlink, database rollback, revocation during provider I/O, old access+and refresh denial, CSRF/origin/bounds and hashed transaction storage. Live OAuth,+provider UI and external notification delivery remain launch work. Sources checked+6 October 2026:+[OWASP federated linking](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#secure-federated-account-linking),+[NIST federation account management](https://pages.nist.gov/800-63-4/sp800-63c.html),+[D1 transactions](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch).++### Account deletion++The account page requires explicit acknowledgement and confirmation through a+linked Google/GitHub identity. The bounded same-origin POST starts a five-minute,+one-use flow bound to the current browser session, account epoch and provider.+Cancellation leaves the account unchanged; an unrelated identity cannot confirm+deletion. The callback rechecks account/session ownership after provider I/O.+It then atomically creates a durable D1 deletion job, sets the account to+`deleting`, increments its epoch, revokes connections and removes browser sessions.+No external cleanup begins before that transaction commits. Old access and refresh+tokens are denied by primary account state, including during retries.++The cleanup order is verified compute retirement, storage retirement, OAuth grant+cleanup, then identity/account removal. `KilnCompute.retireTenant`+durably denies new work and waits for cancellation of the selected account's+coordinator and children. Unknown cleanup keeps its admission slot and recovery+alarm. Other accounts continue; global usage counters retain already-admitted+costs. An opaque account-derived deny record survives eviction and pause/resume.++The tenant's private `/internal/account-deletion` accepts only an empty POST from+the owning service binding. The native coordinator's storage allowlist rejects+that administrative path. Retirement removes download tickets and saved revision+metadata, denies all normal tenant operations and purges the exact R2 prefix in+bounded batches. Durable markers retain unresolved uploads: an HTTP timeout or an+empty bucket listing does not establish that a write cannot arrive later. A+settled put or matching committed immutable R2 bytes permits cleanup. A crash+with neither kind of evidence remains pending with daily recovery; it must be+reported as incomplete and escalated, never silently declared erased. Earlier+ordinary maintenance cannot discard those markers or recreate state after purge.++`purged` requires zero unresolved writes, zero artifact rows and a final empty R2+listing. It removes the storage alarm but preserves the small permanent deny+record. Already-delivered files cannot be recalled. These checks concern active+application storage; provider backups/retention need their separate launch policy.+Use the deletion controller only after every compute/storage instance runs this+contract and older uploads have drained. Rolling back to code that ignores these+records after accepting a deletion would be unsafe; pause service instead.++`D1AccountDeletions` leases each phase for 60 seconds. Recovery admits at most+four phases within a 25-second work budget; external steps have a maximum+20-second deadline. Incomplete cleanup retries after a minute; errors back off+to at most an hour. Expired leases can be recovered; replaced leases cannot+advance another worker's job. Grant cleanup uses the pinned OAuth library's+public helpers, up to four grants per step, and clears known D1 grant IDs only+after revocation acknowledges them. Identity/account removal and completion are+one guarded transaction. Errors never record provider responses or exception text.++The private status page requires a random HttpOnly receipt cookie; D1 stores only+its purpose-bound hash. A support reference cannot read the receipt. Completed+receipts lose their account mapping and expire after seven days; the browser+cookie has a 30-day upper bound to cover pending cleanup. A returning user gets+a new empty account, never the retired tenant. Completion means removal from the+active service. Already-downloaded copies cannot be recalled. Eventually+consistent OAuth KV records or concurrent, already-authorized token writes may+outlive inventory cleanup but cannot restore access. Access-token records expire+after 15 minutes and refresh-token records after 30 days. Provider backups need+separate retention disclosure and a restore procedure that preserves revocation.++Apply additive migration `0009_account_deletion.sql` after the earlier account+migrations and deploy retirement-aware compute/storage before the gateway.+The gateway provides a scheduled recovery handler and a bounded immediate attempt+after confirmation. Production must configure and verify a recurring Cron Trigger+(initially every minute), monitor old pending jobs and escalate unresolved writes.+No trigger or public deployment has been created by these source changes.++Local workerd tests exercise real gateway/D1/OAuth-helper/tenant/R2 cleanup with+mocked upstream identity exchange and a no-VM compute fixture, including old-token+denial, another account's continued access and fresh sign-in after deletion.+Fault tests cover rollback, stale proofs, callbacks, lease takeover, actual+deadline/late completion, late writes, unknown acknowledgements, failed R2+deletion, eviction/retry, overlapping maintenance, prefix isolation and bounded+orphan batches. Live provider deletion, scheduled recovery, operations escalation+and public retention disclosures remain launch gates. References:+[D1 transactions](https://developers.cloudflare.com/d1/worker-api/d1-database/#batch),+[Scheduled handlers](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/),+[KV consistency](https://developers.cloudflare.com/kv/concepts/how-kv-works/),+[R2 consistency](https://developers.cloudflare.com/r2/reference/consistency/),+[R2 durability](https://developers.cloudflare.com/r2/reference/durability/),+[Durable Object alarms](https://developers.cloudflare.com/durable-objects/api/alarms/).+## Native HTTP adapter`src/native-mcp.ts` serves the installed engine's registry through the MCP SDK's@@ -115,12 +317,13 @@ responses are bounded and redirects/foreign endpoint origins are refused. Upstreaccess/ID tokens are discarded at the adapter boundary; only verified issuer/subjectpairs enter the account directory. Login names and email never select a tenant.-The gateway needs `ACCOUNTS` bound to D1 with both migrations applied, plus+The gateway needs `ACCOUNTS` bound to D1 with all numbered migrations applied, plus`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID` and`GITHUB_CLIENT_SECRET`. Register exact `/oauth/google/callback` and`/oauth/github/callback` URLs under the configured `PUBLIC_ORIGIN`, using separate-test and production provider apps. No live database, provider app or secret has-been provisioned by this implementation. Existing prototype provider-derived grants+test and production provider apps. Google OAuth branding now exists in testing+mode; no live database or provider client secret has been provisioned by this+implementation. Existing prototype provider-derived grantsare deliberately invalid; no deployed user migration is being claimed. See the[authentication architecture review](../docs/plans/2026-10-05-v1-publication-plan.md#authentication-architecture-review-6-october)for the selected provider-independent boundary, library comparison, KV consistency@@ -299,8 +502,270 @@ isolation. `/mcp` remains unavailable until that host is configured and qualifieThe client uses standard Fetch types in a separate TypeScript check; Worker codecontinues to use the Cloudflare runtime types.+## Private evaluator client++`createNativeEvaluatorPort` speaks the published SDK's versioned evaluator+protocol over `http://kiln-evaluator.internal/evaluate`. It accepts no URL, tenant+selector or credentials. The SDK owns request construction, response identity,+GLB and QA validation. This client applies the private host's ceilings: 60 seconds,+4 MiB request/GLB and 8 MiB response. Invalid controls fail before dispatch;+larger valid caller allowances are clamped to these limits.++Storage, evaluation and rendering share bounded stream/cancellation handling, but have+separate fixed origins, paths and allowed headers. Network diagnostics, abort+reasons and upstream bodies do not become public errors. A failure never selects+an in-process fallback. Tests exercise the real MCP render/save/reconnect flow+through this protocol using a fixed trusted evaluator fixture; that fixture is+not cloud isolation evidence.++The provider controller binds this intercepted hostname to a fresh job and retains+global admission until verified VM destruction. The complete deployed flow still+needs qualification. A returned HTTP timeout does not prove cleanup. The+existing default native loader still fails closed on missing nested isolation;+no production configuration or public endpoint is enabled by this client.++`evaluation-worker` supplies a private `KilnEvaluationJob` Durable Object and+returns 404 from its default HTTP handler. Its private request handler admits+only the fixed evaluation route, bounded JSON and numeric execution limits;+request reading consumes the same deadline. It delegates execution and its alarm+to `ContainerEvaluationJob`, awaiting its verified cleanup before returning output.+No source, identity, executable or image selector is accepted through headers.+The native client and this handler are exercised together with the actual SDK+codec. The externally tenant-bound dispatcher and global admission controller are+implemented below; end-to-end provider qualification and deployment remain open.++The private evaluation DO also exposes `cancel()` to its parent dispatcher. One+controller lives for the DO instance, so cancellation reaches an evaluation still+waiting to claim its durable record. A cancelled child that has not arrived gets+a permanent terminal record; later delivery cannot start it after object eviction.+For active work, the cancellation flag and immediate recovery alarm are persisted,+then the caller waits for confirmed whole-VM cleanup. Failed cleanup keeps the+record unfinished and schedules recovery. Repeated cancellation and its alarm+share the pending cleanup. The parent must retain admission whenever cancellation+fails or its acknowledgement is lost. These cases have local adversarial tests;+the new parent-cancellation RPC still needs provider qualification.++## Private software rendering++`createNativeRenderPort` sends only a self-contained GLB and validated view options+to `http://kiln-renderer.internal/render`. It accepts no URL, source program,+tenant, image or credential selector. The versioned response must match the exact+request ID, GLB digest, view count, camera values, dimensions and presentation rig.+Only the fixed software Vulkan backend is admitted. Engine `captureViewsViaPort`+continues to own PNG validation, its deadline and truthful CPU degradation; this+transport never implements a second fallback policy.++The private limits are 4 MiB GLB, 6 MiB request, 20 MiB wire response, 12 MiB PNG+bytes, 1,024 pixels per dimension and 3,145,728 pixels across requested images.+The MCP host admits 8,388,608 pixels including grid composition and a 12 MiB+capture output. The render deadline is 30 seconds, bounded further by the parent+deadline. This is a qualification candidate, not a measured production latency+promise; the earlier six-view provider fixture took 13,286 ms including cleanup.++`render-worker` exposes only the private `KilnRenderJob` DO. It shares evaluation's+HTTP limits, one-use durable lifecycle, cancellation fence, alarm recovery and+whole-VM destruction through fixed host profiles. `RENDERS` must bind this class;+its immutable named image is `renderer`. `EVALUATIONS` remains a separate binding+with image `kiln`. No request can select the profile or executable. The renderer+runs `/opt/kiln/render.mjs` as `1000:1000` with networking disabled and no secrets.+Its input and self-contained GLB are checked before graphics initialization. The+entry explicitly selects the pinned Mesa ICD because native exec does not inherit+the image's environment.++Local Docker qualification exercises that actual entry and installed port, producing+eight independently decoded PNGs across three backdrops, a beauty image and an+exact camera. Real workerd loopback/RPC tests verify host-owned routing and reject+forged identity fields. These do not qualify the integrated Cloudflare path. See+[the image procedure](container/README.md#one-shot-software-render-entry).++## Private request dispatcher++`request-worker` adds one `KilnNativeRequest` Durable Object per admitted MCP+request. Its private `run` RPC accepts the verified tenant hash and an absolute+deadline of at most 120 seconds. The tenant and child-job inventory remain in+Durable Object storage, outside the coordinator VM. That VM starts offline from+the pinned `coordinator` image with only the public origin in its environment.+Readiness and image readback precede sending the bounded MCP request.++Three fixed HTTP interceptors use host-configured loopback binding props to select+the request object. Storage RPCs select the tenant from its durable record; URLs,+headers and body fields cannot choose it. The storage route allowlist excludes+administrative operations. This uses the documented Container interception API+and Worker loopback props. Local workerd checks exercise the actual RPCs, tenant+storage and object eviction, including cross-account source denial. Deliberate+HTTP errors are converted to responses before RPC serialization, which does not+preserve their custom JavaScript prototype.++Each request admits at most one active child evaluation or render and eight+children in total. Every child ID and kind is persisted before dispatch and receives at most the+remaining parent deadline. A child's cancellation acknowledgement is required+before another child can start. Completion or cancellation first closes the+durable request to new work, then confirms destruction of the coordinator and+all registered children, routing cancellation by their persisted kind. Unknown cleanup retains the record and a recovery alarm;+late delivery is refused through the child's durable cancellation fence. Parent+responses are bounded to 32 MiB and withheld until cleanup completes.++The default Worker route remains 404. The gateway uses the private admission+binding described below and returns 503 for native calls when it is absent. No production+configuration, public route or new Cloudflare job is enabled by these modules.+Provider qualification must test the coordinator/interceptor/child flow together;+local state-machine and workerd tests do not establish that live boundary.++Sources: [Container API](https://developers.cloudflare.com/containers/api/durable-object-container/),+[loopback binding props](https://developers.cloudflare.com/workers/runtime-apis/context/#specifying-ctxprops-when-using-ctxexports),+[RPC Request and Response transport](https://developers.cloudflare.com/workers/runtime-apis/rpc/#readablestream-writablestream-request-and-response).++## Shared compute admission++`admission-worker` owns one global `KilnAdmission` SQLite Durable Object. The+gateway receives only a named `KilnCompute` service binding as `NATIVE_COMPUTE`;+that entrypoint always selects `global-v1`. It cannot accept a caller-selected+admission object or expose operator controls. Artifact downloads continue through+tenant storage without starting compute. The authenticated edge path below serves+metadata and helper discovery without a coordinator or compute reservation.++An admitted request reserves one coordinator and at most one active child VM.+One request per account and the configured global concurrency limit are enforced+atomically with per-account minute/day and global day/month attempt counters.+Counters use UTC calendar windows. Failed admitted work consumes its attempt;+rejected work does not. There is no queue of unbounded pending requests.+429 responses include `Retry-After`. Required settings have no implicit defaults:++| Setting | Meaning |+| --- | --- |+| `COMPUTE_MAX_CONCURRENT` | Concurrent request trees; implementation ceiling 16 |+| `COMPUTE_TENANT_PER_MINUTE` | Admitted requests per account per UTC minute |+| `COMPUTE_TENANT_PER_DAY` | Admitted requests per account per UTC day |+| `COMPUTE_GLOBAL_PER_DAY` | All admitted requests per UTC day |+| `COMPUTE_GLOBAL_PER_MONTH` | All admitted requests per UTC month |+| `COMPUTE_DEADLINE_MS` | Absolute request lifetime, at most 120,000 ms |++These are configuration controls, not adopted launch quotas or an invoice cap.+Provider measurements must include both VM types, cold starts, retries, and+non-compute services. The global ceiling is a validation bound, not demonstrated+capacity. Launch values and total capacity still require measurement.++The reservation and recovery alarm commit together before the parent RPC. A+deadline or disconnect triggers out-of-band parent cancellation. Admission is+released only after the parent confirms whole-tree cleanup, including children+and its durable fence against late requests. Unknown cleanup suppresses output,+retains capacity, and schedules another recovery attempt. Eviction and elapsed+time never free a slot by themselves. Expired usage counters are cleaned in+bounded batches. No OAuth credentials or source content enter admission storage.++The separate private `KilnComputeControl` binding exposes pause/resume and+aggregate status. Bind it only to an authenticated operator service. Pause is+durable, rejects new compute and attempts cancellation of every active request;+unconfirmed cleanup remains visible in `pendingCleanup` and retains its slot.+Resuming does not bypass those reservations or reset usage counters.++Local workerd tests cover the actual SQLite/RPC boundary, concurrent admission,+quota rollover, operator separation, eviction/recovery, stalled calls and a+response/cancellation race. The race test reproduced a discarded response body+left open and now verifies its closure. No new cloud qualification is implied.+Implementation follows the current [SQLite transaction contract](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/#transaction)+and [alarm contract](https://developers.cloudflare.com/durable-objects/api/alarms/).+Production configuration and the final deployment remain open. A bounded private+integration at `c755434` passed the render/save/reopen/export lifecycle, tenant+denial and quota rejection; see the+[qualification receipt](../docs/reviews/2026-10-06-hosted-integration-receipt.json).+That evidence does not qualify later changes or a public service.++For a reviewed private integrated probe, `scripts/build-integrated-probe.mjs`+emits both Cloudflare Build Output and `wrangler.json`, pointing to the same+compiled module. Use the generated Wrangler configuration with `--no-bundle`;+a `--dry-run` validates locally before any approved deployment. The tested+Wrangler version is `4.147.0`. `cf 1.0.0-beta.12` converts same-Worker Durable+Object bindings into external `script_name` references and rejects the Container+bindings. The Wrangler output uses local bindings while preserving exports,+images, quotas and disabled public routing. The script only builds local files;+it does not provision or deploy anything, and rebuilding creates a new candidate+that must be qualified separately.++## Authenticated edge discovery++After the same OAuth scope, account and connection checks used by native calls,+the gateway serves initialization, protocol discovery, tool/resource lists and+static `kiln_discover` queries directly in the Worker. Ping, notifications, malformed+JSON and unknown tool names also stay on that path. No storage or native service is+available to its handler. Source operations, resource reads and live capabilities+still go through shared admission. Routing inspects the bounded JSON body; a+forged `mcp-method` header cannot turn metadata into native execution. Both paths+use the maintained MCP handler, with stateless legacy compatibility. HTTP responses+remain `no-store`; protocol cache hints apply only to fixed public definitions.++`node hosting/scripts/edge-manifest.mjs --write` captures metadata from the actual+engine server with the hosted storage surface. Its sentinels throw if any host+service is invoked. The build checks the committed snapshot; it never silently+updates it. The actual native HTTP fixture independently checks every tool schema,+resource, template and initialization field against that snapshot. Helper results+and validation diagnostics are compared with the engine host. The Worker imports+only the pure discovery algorithm/schema and a generated catalog, not the Node+engine, renderer or evaluator. The `workerd` build condition selects the MCP SDK's+Worker-compatible schema validator without runtime code generation.++The independent installed-image workflow uses `npm run build -- --native-only`.+That path builds only the private Node adapters, without loading checkout engine+bundles or generated edge metadata. An isolated-checkout test verifies it with no+`dist/` or `lib/`; the normal build still requires metadata parity. This preserves+the image workflow's qualification against the published npm archive.++Real workerd tests cover modern discovery, legacy initialization, malformed+messages, forged routing headers, missing native bindings and primary-database+revocation despite retained OAuth KV records. No authentication or compute quota+is bypassed for operations that require native execution. Provider startup/cost+measurements and final hosted-specific instructions remain launch checks; the+current instructions deliberately match the published engine verbatim.++Sources: [MCP discovery](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2026-07-28/server/discover.mdx),+[Cloudflare stateless MCP guidance](https://developers.cloudflare.com/agents/model-context-protocol/guides/remote-mcp-server/).++## Private Node host++`native-host` adapts the MCP Fetch handler through the maintained+`@modelcontextprotocol/node` adapter. It listens only inside the coordinator VM+on port 3000, requires the fixed `kiln-native.internal` Host and exposes a minimal+`/_ready` route. Header/body bounds, an upload deadline and client-disconnect+propagation precede the MCP handler's own execution and response limits. A chunked+body flood may close the socket before the adapter can deliver its 413 response;+either outcome must occur before MCP dispatch.++`container/serve.mjs` requires an exact HTTPS public origin and selects the explicit+remote evaluator profile. Missing private storage or evaluation services fail+closed; they never enable in-process source evaluation. The default local loader+still retains its separate isolation requirements. Neither profile is an automatic+fallback for the other.++Build and qualify the minimal image through+[the container instructions](container/README.md#private-mcp-coordinator-image).+Local Docker evidence establishes installed MCP startup, protocol compatibility+and request rejection. It does not establish Cloudflare routing or tenant+isolation. The outside dispatcher must bind the storage/evaluation interceptors,+retain admission through all child-job cleanup and destroy the coordinator VM.+## Native saved assets+New saves through the Container profile record+`build.engine: cloudflare-container:sha256:<image digest>`. The outside controller+inspects the running evaluator image and only releases its digest with the exact+output after whole-VM cleanup succeeds. The coordinator requires this private+response header and the SDK's validated evaluator response. A request-local,+bounded proof map binds the digest to exact source and GLB hashes; saving different+bytes or missing proof fails before uploading assets. The evaluator's stdout,+authored source and caller request headers cannot select this identity.++The digest identifies the immutable evaluator image, including its installed+engine, dependencies and Node runtime. It is descriptive build provenance, not a+portable signature or a guarantee that imported metadata is trustworthy. Imports+preserve their original provenance without attaching a fresh-host claim. Existing+historical `source-development:unverified` records are not rewritten.++Deploy the updated private evaluation controller before a coordinator that+requires the identity header. Older coordinators ignore the additional response+header; a new coordinator fails closed against an older controller. Qualify both+exact artifacts together before production or rollback. Local tests cover this+contract; the previous `c755434` provider trial predates it.+`NativeAssetLibrary` implements the engine's existing collection, save, read, list,import and export contract. Its `project` collection is workspace storage, notproject membership; `library` is a second user-owned destination. Asset and revision@@ -333,19 +798,133 @@ files. The Worker checks saved pins atomically, so a lost commit acknowledgementcannot cause cleanup to delete the committed revision. An unacknowledged upload,a process crash or failed cleanup can leave unsaved bytes charged until the normalseven-day expiry/recovery path removes them. `deleteRevision` is a host UI/account-operation; it preserves copies in other collections. Browser/account deletion UI-and its deployed lifecycle remain open.+operation; it preserves copies in other collections. Whole-account deletion is+implemented above; its deployed lifecycle remains unqualified.Embedded material records are retained and verified using the SDK's canonical-dependency semantics. An injected MaterialLibrary receives the closure on import;-the separate durable hosted MaterialLibrary is still unimplemented. A textured-fixture rebuilds the exported/imported GLB byte-for-byte without its original-library. This does not qualify software rendering or native isolation on Cloudflare.+dependency semantics. An injected MaterialLibrary receives the closure on import.+A textured fixture rebuilds the exported/imported GLB byte-for-byte without its+original library. This does not qualify software rendering or native isolation on+Cloudflare.Source restoration, MCP source reads, reviewed saves and CLI rebuild observationspreserve a leading UTF-8 BOM. Otherwise restoring an asset could change the exactsource bytes and its program reference; focused engine tests cover those paths.+## Durable material adapter++`NativeMaterialLibrary` implements the published SDK's immutable material import,+list and read contract over private tenant storage. The Worker owns the fixed+`materials/<materialId>/<revisionHash>` index and pins the exact manifest and PNG+inventory under the existing artifact quotas. The native SDK verifies identity,+PNG bytes, dimensions and procedural recipe/output hashes. Provenance URLs remain+metadata and are never fetched.++Imports validate and snapshot the complete batch before any write. The host limits+each batch to 100 distinct revisions, 64 MiB including manifests and 16 million+decoded pixels (16 * 1024 * 1024); the SDK's per-record limits also apply. Commits+are atomic per revision. A later failure can leave earlier revisions saved; retry+with the same identities. Concurrent identical imports are idempotent and discard+losing staging files. A lost commit acknowledgement cannot delete pinned bytes.+Unacknowledged uploads or failed cleanup remain quota-counted until normal expiry.++Lists page 32 records at a time and verify manifest identities without decoding+all PNGs. Exact reads verify the complete material record. Saved records survive+the seven-day unsaved expiry. Local tests cover fresh hosts and Durable Object+eviction, account separation, concurrent imports, corruption, quota exhaustion,+multi-page listing, caller mutation and partial failures.++The native MCP host injects this library into the engine and asset imports. Its+fifteen tools include the registry-owned `kiln_material`; edge metadata is generated+from that same configured registry. A standalone workspace binding resolves each+call's explicit `materialDependencies` before evaluation. Nested operations inherit+pins unless `projectId: null` resets the binding; overlapping operations use separate+async contexts. Revisions and hashes must agree, and the host does not infer a+project from the `project` collection. Hosted project/review stores are not supplied+or advertised; explicit project selection reports that limitation.++Each invocation resolves at most sixteen pinned materials within the SDK's payload+byte/pixel budgets. The existing private evaluator transport additionally limits+the serialized evaluation request, including source and embedded material bytes,+to 4 MiB. Large dependency closures can therefore exceed the hosted transport limit+even when individual saved materials are valid. They fail closed; no dependencies+are silently dropped or replaced. Private request dispatch permits only the exact+material index routes and continues to bind the tenant outside the coordinator VM.++The MCP fixture creates, lists and reads a material, renders with explicit pins,+saves and exports an asset across fresh hosts, and rejects another account before+evaluation. After deletion of the live material entry, copying the saved asset to+another collection reinstalls its embedded material closure, preserves GLB bytes+and supports a fresh render. Installed-image checks also verify the material tool,+binding schema and preset discovery against the exact public package. These are+local qualification; deployed Cloudflare material workflows remain unverified.++## Private browser downloads++The native host supplies the published engine's `assetDownloadUrls` hook. Saved+revision summaries return `/downloads/<ticket>/<filename>` links for their exact+GLB, source, manifest, preview and material closure when present. `kiln_assets`+with `action: 'get'` can issue fresh links. No public tool schema is changed.++Links require a current browser session for the owning Kiln account. The gateway+derives the same private tenant as MCP from the primary-backed account identity;+the URL never selects a tenant or R2 object. An anonymous visitor sees the branded+Google/GitHub sign-in form. Migration `0007_browser_login_return.sql` stores a+strictly validated relative download path in the one-use browser transaction.+Callbacks use that stored destination, never a callback query parameter. Apply+all numbered migrations before deploying the gateway. Rollback to the preceding+gateway can leave the additive column in place.++Each random ticket lasts ten minutes, is stored only as a hash, and permits at+most 32 transfer attempts across its files, including HEAD and failed reads.+There are at most 128 unexpired tickets per tenant; issuance and redemption are+atomic. This fixed metadata ceiling is separate from the artifact-byte quota.+Expired rows are reclaimed on issuance, maintenance and tenant alarms. Links do+not extend artifact retention, and deleting the selected revision invalidates+its links even if another revision pins the same bytes. Ticket limits return 429;+they do not delete saved work. Browser requests do not start a compute VM.++The gateway rechecks the browser session after storage awaits, and storage+rechecks ticket expiry and the saved revision before returning bytes. Responses+use attachment disposition, no-store, no-referrer and nosniff. Foreign Origins+and cross-origin embedding are denied while ordinary top-level link navigation+is allowed. Browser credentials never enter the tenant Worker or native host.++Local tests exercise the actual MCP save/reopen output, browser gateway, D1+sessions, SQLite tenant index and R2 downloads for two accounts. Separate mocked+provider exchanges verify both sign-in continuations, replay denial and hostile+redirect rejection. This proves local integration, not live provider sign-in or+Cloudflare delivery. The coordinator image must be rebuilt for this host change;+the separately prepared `c755434` trial retains its original bundle and images.++The redirect and request-context boundaries follow the checked+[OAuth security BCP](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.11)+and [Fetch Metadata guidance](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Fetch_metadata).++## Operational monitoring++Operational monitoring is described in [OPERATIONS.md](OPERATIONS.md). The gateway+emits explicit response counters/timing and scheduled deletion/compute health;+raw request data and user identities are excluded. Preparation includes alert+candidates, but no deployed ingestion or notification delivery is qualified yet.++## Request abuse protection++Both edge and account rate-limit bindings are required on the gateway. Before+OAuth, D1 or body processing, requests share bounded route-class counters. After+authentication, MCP calls and browser downloads share a hash of the permanent+Kiln account and origin, independent of client, token and network address. Counter+keys never contain bearer tokens, cookies, IP addresses, source or download URLs.+Exhaustion returns a private 429 response with `Retry-After: 60`. A missing,+malformed, failing or stalled binding fails closed with 503.++These bindings provide approximate, per-Cloudflare-location abuse protection.+They do not replace durable compute admission or storage quotas, and cannot cap+the hosting bill. Coarse route limits also affect legitimate users sharing a+location when exhausted. The deployment manifest makes both namespaces and+thresholds explicit; qualification and public thresholds remain to be reviewed+and tested on the provider. No rate-limit configuration has been deployed.+Before launch, complete native isolation on the actual Cloudflare provider,tenant engine/storage integration, two-user asset/download denial tests, retention,admission/cancellation and cost controls, identity-provider setup, live client@@ -355,3 +934,27 @@ Sources checked 6 October 2026:[Cloudflare OAuth library](https://github.com/cloudflare/workers-oauth-provider),[MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization),[GitHub OAuth flow](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps).++## Public plugin preparation++`plugin/` contains the source for the hosted OpenAI submission candidate. It is+separate from `plugins/kiln-engine`, the published local setup plugin. From the+repository root, using the pinned maintainer Node, package a fresh output directory:++```sh+node hosting/scripts/package-public-plugin.mjs .cache/public-plugin-draft+```++The output contains a complete `plugin/` folder, `kiln-engine-draft.zip` and a+receipt with source/file/archive hashes. Shared authoring references and the+existing icon are copied during packaging, so do not upload the source folder+directly. The packager refuses an existing output directory and includes only its+explicit file list. It never contacts a provider or publishes anything.++The draft has one remote MCP connection, a hosted workflow skill, listing metadata+and five positive/three negative review cases. Its receipt always says+`submissionReady: false`: offline packaging cannot establish live OAuth, endpoint+availability, review-account access, demo evidence or portal acceptance. Keep+reviewer credentials outside the repository and ZIP. See the+[directory preflight](../docs/reviews/2026-10-07-directory-preflight.md) for the+remaining qualification and submission steps.diff --git a/hosting/assets/README.md b/hosting/assets/README.mdnew file mode 100644index 00000000..d54cc659--- /dev/null+++ b/hosting/assets/README.md@@ -0,0 +1,16 @@+# Sign-in branding++`src/google-button.ts` embeds an unmodified Google-provided PNG so sign-in pages+need no third-party image, font or script request. It is not a Kiln-owned logo.+Google's brand restrictions continue to apply; the repository's MIT license does+not grant rights to Google's trademarks.++- Guidance: https://developers.google.com/identity/branding-guidelines+- Downloaded 6 October 2026: https://developers.google.com/static/identity/images/signin-assets.zip+- ZIP member: `Android + Web/PNG @2x/Light/Theme=Light, Show text=Yes, Shape=Square, [email protected]`+- Original: 360 × 80 pixels, 6,007 bytes.+- SHA-256: `fdd355abc194d6acc0837c9b5e8a3170d6ae07dfeb85a63d3eb4b7fbfc2bb63f`.++The button preserves the image's aspect ratio. Its accessible name matches the+rendered text. GitHub's adjacent button has the same size and visual weight.+No Google Identity Services script is necessary for the server-side OIDC flow.diff --git a/hosting/container/Dockerfile b/hosting/container/Dockerfilenew file mode 100644index 00000000..908f405b--- /dev/null+++ b/hosting/container/Dockerfile@@ -0,0 +1,15 @@+# Private per-job CPU image. Build only the four-file context in README.md.+FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa+RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund+WORKDIR /opt/kiln+COPY candidate.tgz candidate.sha256 ./+RUN sha256sum -c candidate.sha256 \+ && npm init -y \+ && npm install ./candidate.tgz --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \+ && dpkg-query -W > os-packages.txt \+ && node --version > node-version.txt+COPY evaluate.mjs ./+# User IDs are defense in depth only; Cloudflare's durable_object scheduling+# grants processes root capabilities. The fresh offline microVM is the boundary.+USER node+CMD ["/usr/bin/sleep", "infinity"]diff --git a/hosting/container/Dockerfile.host b/hosting/container/Dockerfile.hostnew file mode 100644index 00000000..a1a6db51--- /dev/null+++ b/hosting/container/Dockerfile.host@@ -0,0 +1,14 @@+# Private coordinator image. Never build with the repository or secrets as context.+FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa+RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund+WORKDIR /opt/kiln+COPY candidate.tgz candidate.sha256 package.json package-lock.json ./+RUN sha256sum -c candidate.sha256 \+ && npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \+ && dpkg-query -W > os-packages.txt \+ && node --version > node-version.txt+COPY native-mcp.mjs native-host.mjs serve.mjs ./+ENV KILN_RENDER=cpu+USER node+EXPOSE 3000+CMD ["node", "/opt/kiln/serve.mjs"]diff --git a/hosting/container/Dockerfile.software b/hosting/container/Dockerfile.softwarenew file mode 100644index 00000000..607a874a--- /dev/null+++ b/hosting/container/Dockerfile.software@@ -0,0 +1,24 @@+# Private per-job software-rendering candidate. Use the six-file context from README.md.+FROM node:22.23.3-trixie-slim@sha256:154ba2f4d6fec323d28e4f4bb86bba4677f1223391a1979cf521304e03a98dfa+# Trixie's Mesa supports the shader features required by the packaged Dawn renderer.+RUN apt-get update && apt-get install -y --no-install-recommends \+ mesa-vulkan-drivers libvulkan1 ca-certificates \+ && rm -rf /var/lib/apt/lists/*+RUN npm install --global [email protected] --ignore-scripts --no-audit --no-fund+WORKDIR /opt/kiln+COPY candidate.tgz candidate.sha256 ./+RUN sha256sum -c candidate.sha256 \+ && npm init -y \+ && npm install ./candidate.tgz --omit=dev --include=optional --ignore-scripts --no-audit --no-fund \+ && dpkg-query -W > os-packages.txt \+ && node --version > node-version.txt \+ && set -- /usr/share/vulkan/icd.d/lvp_icd*.json \+ && test "$#" -eq 1 && test -f "$1" \+ && ln -s "$1" /opt/kiln/lvp-icd.json+COPY evaluate.mjs ./+COPY native-render.mjs render.mjs ./+ENV VK_ICD_FILENAMES=/opt/kiln/lvp-icd.json+ENV KILN_RENDER=cpu+# The VM, outside deadline and network policy enforce isolation, not this UID.+USER node+CMD ["/usr/bin/sleep", "infinity"]diff --git a/hosting/container/README.md b/hosting/container/README.mdnew file mode 100644index 00000000..ea3b3efa--- /dev/null+++ b/hosting/container/README.md@@ -0,0 +1,207 @@+# Private evaluation image++Current qualification: the exact stable software image and per-job controller+passed the twelve fixed Cloudflare cases in [the resilience record](../probe/RESILIENCE.md).+The earlier preparation notes below retain their narrower evidence. Production+dispatch, representative load and costs remain open. The separate MCP coordinator+image described below has local Docker proof only.++This is the CPU-only image for the explicit Cloudflare per-job adapter. It opens+no network listener. A private Durable Object starts a fresh VM from an immutable+digest with internet disabled, executes `evaluate.mjs` with piped input/output,+and destroys the entire VM before accepting a result. Do not run arbitrary user+source with this entry on the workstation or in the trusted MCP coordinator.++Build a minimal context containing exactly four files:++- This `Dockerfile` and `evaluate.mjs`.+- The qualified installed-package archive renamed `candidate.tgz`.+- `candidate.sha256`, containing its approved SHA-256, two spaces, and+ `candidate.tgz`.++Never use the checkout, an authored workspace, credential directories or all of+`.cache` as the Docker build context. Build for `linux/amd64`. The build verifies+the supplied archive and installs dependencies without lifecycle scripts. Retain+the final image digest, `/opt/kiln/package-lock.json`, `/opt/kiln/os-packages.txt`+and `/opt/kiln/node-version.txt`; the npm archive alone does not pin transitive+dependencies or establish the image's identity. The base image digest is shared+with the existing native preflight. The Linux image build and deterministic+installed-package fixture passed in [CI run 37479877969](https://github.com/instruktlabs/kiln/actions/runs/37479877969).+The RC image's runtime manifest subsequently passed the fixed evaluation and+basic provider-boundary checks in [the qualification record](../probe/QUALIFICATION.md).+Rendering, adversarial resource limits, recovery and production routing remain+unqualified.++The production controller now requires both `running === false` and a `null`+inspection after `destroy()` before releasing output or deleting its watchdog.+Destruction and inspection share a five-second budget. Unknown or failed readback+keeps the job unfinished for durable recovery. This follows the documented+[Container API shutdown contract](https://developers.cloudflare.com/containers/api/durable-object-container/).+Regression tests first reproduced accepted output after an unconfirmed shutdown,+then passed with the verification in place, including a stalled inspection and+recovery after an initially failed readback. All 136 hosted tests, three hosted+typechecks, five bundle checks and root typecheck/lint passed locally. This+controller passed exact-source Linux/Windows hosted checks in+[run 37525915541](https://github.com/instruktlabs/kiln/actions/runs/37525915541).+Live failure-path qualification remains open.++The entry's byte limits and engine schema validation are defensive transport+checks. A JavaScript timer, Linux user ID and the engine's local VM implementation+are not security boundaries. Cloudflare must enforce the no-network policy and+the outside controller must enforce admission, deadlines and destruction. The VM+must contain no provider credentials, user account records, other tenants' files,+R2 mounts, reusable source or snapshots. Treat every byte returned by it as+untrusted, including QA claims, filenames and diagnostics.++Before production routing, qualify the exact deployed image and Worker pair:+fixed native fixtures and CPU images, blocked internet/metadata/localhost access,+cross-job filesystem isolation, descendants and infinite-loop deadlines, output+floods, cancellation during startup and execution, memory exhaustion, controller+restart/alarm recovery, and confirmed container destruction. Run only fixed+adversarial fixtures in this private probe, with bounded concurrency, compute,+cost and teardown. Record cold starts and billed resources separately from engine+compute time. The old Bubblewrap adapter remains fail-closed and has no automatic+fallback to this entry.++## Software-rendering candidate++`Dockerfile.software` extends the four-file evaluator context with the built+`native-render.mjs` and `render.mjs`, for exactly six files. It adds Mesa's software+Vulkan implementation. Copy it into the context as `Dockerfile`.+Build with `--platform linux/amd64 --provenance=false` to retain the directly+addressable runtime manifest. The final immutable image digest, rather than the+Dockerfile alone, identifies installed OS and npm dependencies. No probe script,+credential, network listener or storage mount is included in the image.++The exact main `1.0.0` archive (`6ed3d6b9...1508`) was installed locally in image+`sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99`.+With networking disabled, all capabilities dropped, no privilege escalation,+two CPUs and a 4 GiB memory limit, the real entry produced the same 1,912-byte+GLB twice and its CPU preview passed at 128 pixels. The packaged renderer also+produced six textured views across all three backdrops using llvmpipe/Mesa+25.0.7 and Vulkan; each view retained red and green texture evidence. Temporary+test containers were removed. These are local functionality checks, not+Cloudflare isolation, throughput or cost measurements.++The image lock SHA-256 is+`fdcb5cd754cdb78de52eb530efb9a993a30c8742e83c939103edc6112fd77ba1`.+The diagnostic worktree retains its inventories, exact image, CPU GLB/PNG and six+software images under `.cache/stable-software-image/`. CI now builds both image+variants using the explicitly recorded public package and tests the installed+entry; the software variant additionally runs the packaged renderer fixture.+While that public record still names the RC, CI does not qualify the stable+archive by implication. A prepared, reviewed provider trial is still required+before uploading or running this new stable image on Cloudflare.++Both CI image variants passed at source `b34d56f` in+[run 37526078285](https://github.com/instruktlabs/kiln/actions/runs/37526078285).+That run uses the public RC archive and therefore complements, rather than+replaces, the exact-stable local receipt above. The stable image's retained npm+lock also returned zero known findings in an `npm audit --omit=dev` on 6 October.+No cloud resource was created for this image preparation.++## One-shot software render entry++The current software image includes `/opt/kiln/render.mjs`, a fixed one-shot+producer selected only by `KilnRenderJob`. The private coordinator sends GLB bytes+and view options through the versioned renderer port. The entry validates the+request and self-contained GLB before loading graphics, explicitly selects the+pinned Mesa ICD, emits bounded JSON and exits. It opens no listener and receives+no source program, tenant information, storage binding or credentials.++After building the hosting bundles, put `.cache/hosted-worker/native-render.mjs`+and `hosting/container/render.mjs` into the otherwise unchanged minimal software+context. Verify the built file against `native-render-build.json`. Build for+Linux AMD64 without provenance, then run:++```sh+node hosting/scripts/smoke-native-render.mjs kiln-software-entry:local-v1+```++The script creates and removes one uniquely named offline local container with+two CPUs, 4 GiB memory, 128 PIDs, dropped capabilities and no privilege escalation.+The fixed trusted fixture is passed over stdin, without a workspace mount. It+exercises the actual renderer entry through the installed private port and decodes+eight 128px PNGs: six views across three backdrops, a beauty image and an explicit+camera view. Each retains red/green material evidence. Request identity, exact+camera metadata and malformed-input rejection are checked. The entry succeeds+without inheriting the image's Vulkan environment. CI runs the same check.++Local final image manifest+`sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`+passes this procedure with the exact published stable archive. Its dependency+lock remains `fdcb5cd754cdb78de52eb530efb9a993a30c8742e83c939103edc6112fd77ba1`.+Receipts, PNGs, inventories and the six-file context receipt are retained under+`.cache/software-render-entry/final-qualification/` and its parent directory.+The test container's removal was independently read back. No cloud upload or+execution occurred. The newly integrated coordinator/render job path still needs+provider qualification; the earlier twelve-case trial used the historical image.++## Private MCP coordinator image++`Dockerfile.host` serves the installed package's actual MCP factory through the+private Node adapter. Unlike the evaluator image, it has a private port 3000+listener. Its explicit remote evaluator profile sends source only to the outside+controller's fixed evaluation endpoint. It contains no identity-provider secrets,+tenant identifier, storage mount or public route. `KILN_PUBLIC_ORIGIN` is its only+application setting and must be an exact HTTPS origin.++From the checkout root, using the pinned Node/npm tools:++```sh+npm run build --prefix hosting+node hosting/scripts/prepare-native-host.mjs /path/to/qualified-kiln-1.0.0.tgz+cd .cache/native-host-image/context+npm install --package-lock-only --ignore-scripts --no-fund+cd ../../..+docker build --platform linux/amd64 --provenance=false --tag kiln-native-host:local .cache/native-host-image/context+node hosting/scripts/smoke-native-host.mjs kiln-native-host:local+```++The preparer requires an empty directory inside this checkout's `.cache`, verifies+the archive against `.github/published-candidate.json` and copies the checked+runtime bundles, entrypoint and Dockerfile. Its seven-file context becomes eight+files after lock generation. Never expand the build context to include the repo,+credentials or other caches. Retain the generated lock and inventories: separate+builds can resolve different transitive dependencies and have different image+digests even when the package archive is identical.++The qualification script creates one disposable local container with networking+disabled, a read-only filesystem, non-root user, dropped capabilities and bounded+memory/CPU. It checks readiness, modern tool discovery, legacy initialization,+foreign-host/credential rejection and failure without private services. No host+port is published. The script removes its uniquely named container and saves+identities, inventories and the result under `.cache/native-host-image/qualification`.+CI runs the same procedure without registry publication or Cloudflare access.++Two additional installed-package checks exercise the private evaluation adapter+with a fixed trusted source and synthetic controller headers: the accepted result+retains its own image identity, and an otherwise valid response without identity+fails closed. These are protocol checks inside the offline coordinator fixture;+they do not prove provider execution or isolation. The current private controller+must supply the verified evaluator digest before the newer coordinator can run.++Local image `sha256:5402d67069e8b5c9d355e4f49b9ae92d353171b381d27496f85f5794adf95d75`+passed all six checks with the exact published 1.0.0 archive and fourteen registry+tools. Its retained dependency lock SHA-256 is+`f635b9ba48046e4fdb265eb980df55cf1303c4bc0fd109db477ef870ef0b273f`.+Both the hosting lock and generated image lock reported zero known npm audit+findings. This image has not been uploaded or qualified on Cloudflare. Storage,+child evaluation/render dispatch and global admission are now implemented and+locally tested; the combined deployed path remains an end-to-end qualification+requirement. The historical coordinator image above predates render-port injection+and must not be used as the integrated launch candidate.++The render-enabled coordinator was rebuilt locally as manifest+`sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`.+Its exact stable archive, unchanged dependency lock and all six coordinator checks+pass. The receipt is `.cache/native-host-render/qualification/receipt.json`.+It has not been uploaded to Cloudflare.++The browser-download host change has a separate locally qualified coordinator:+`sha256:2f85a87cb48e360e9de3994d898413695a87c11b3d9f39f466fbf9d88c090d34`.+Its receipt is `.cache/native-host-download/qualification/receipt.json`; the+published archive and dependency lock are unchanged and all six offline checks+pass. The uniquely named test container's absence was independently verified.+This does not replace the immutable image in the pending `c755434` Cloudflare+trial, and neither image has been qualified for public launch.diff --git a/hosting/container/evaluate.mjs b/hosting/container/evaluate.mjsnew file mode 100644index 00000000..0a5bbc24--- /dev/null+++ b/hosting/container/evaluate.mjs@@ -0,0 +1,33 @@+// Private one-shot entry for an externally isolated VM, never a public server.+// The outside Durable Object owns admission, network policy and the hard deadline.+// This process has no provider credentials, tenant storage or reusable state.+const MAX_INPUT = 4 * 1024 * 1024;+const MAX_OUTPUT = 8 * 1024 * 1024;++try {+ const input = Buffer.alloc(MAX_INPUT);+ let size = 0;+ for await (const chunk of process.stdin) {+ if (size + chunk.byteLength > MAX_INPUT) throw new Error('Input limit');+ input.set(chunk, size);+ size += chunk.byteLength;+ }+ const request = new TextDecoder('utf-8', { fatal: true }).decode(input.subarray(0, size));+ const { evaluateEvaluatorRequestV2 } = await import('@instruktlabs/kiln/evaluator');+ const response = await evaluateEvaluatorRequestV2(+ request,+ {},+ {+ maxResponseBytes: MAX_OUTPUT,+ deadlineMs: 60_000,+ },+ );+ if (Buffer.byteLength(response) > MAX_OUTPUT) throw new Error('Output limit');+ await new Promise((resolve, reject) => {+ process.stdout.write(response, (error) => (error ? reject(error) : resolve()));+ });+} catch {+ // Never echo the request, filesystem paths, dependency diagnostics or a stack.+ process.stderr.write('Kiln evaluator input or execution failed.\n');+ process.exitCode = 1;+}diff --git a/hosting/container/render.mjs b/hosting/container/render.mjsnew file mode 100644index 00000000..d7697eb3--- /dev/null+++ b/hosting/container/render.mjs@@ -0,0 +1,59 @@+// One bounded request in a disposable software-rendering VM. No source execution,+// storage, provider credentials or listening server is exposed by this entry.+try {+ const { decodeRenderRequest, encodeRenderResult, RENDER_LIMITS } = await import(+ './native-render.mjs'+ );+ const bytes = Buffer.alloc(RENDER_LIMITS.requestBytes);+ let length = 0;+ for await (const chunk of process.stdin) {+ if (length + chunk.byteLength > bytes.byteLength) throw new Error('Input limit');+ bytes.set(chunk, length);+ length += chunk.byteLength;+ }+ const input = decodeRenderRequest(bytes.subarray(0, length));+ const engine = new URL(import.meta.resolve('@instruktlabs/kiln'));+ const service = (name) => new URL(`../render-service/src/${name}.mjs`, engine).href;+ const { validateSelfContainedGlb } = await import(service('glb-input'));+ const { validateRenderMode } = await import(service('contract'));+ const { glb, ...options } = input.request;+ validateSelfContainedGlb(glb, { maxGlbBytes: RENDER_LIMITS.glbBytes });+ validateRenderMode({+ views: options.viewDirs,+ size: options.size,+ beauty_size: options.beautySize,+ cameras: options.cameras,+ width: options.width,+ height: options.height,+ lighting_preset_id: options.lightingPresetId,+ backdrop: options.backdrop,+ });+ // Cloudflare exec does not inherit image environment variables. Select the+ // reviewed software ICD here, never from request fields or ambient GPU choice.+ process.env.VK_ICD_FILENAMES = '/opt/kiln/lvp-icd.json';+ await import(service('register-hooks'));+ const { initRenderer, renderGlb } = await import(service('renderer'));+ const gpu = await import(service('gpu'));+ await initRenderer({ allowSoftware: true });+ const device = await gpu.acquireGpu();+ if (device.software !== true || device.backend !== 'vulkan')+ throw new Error('Unexpected renderer');+ const result = await renderGlb(glb, options);+ const output = encodeRenderResult(input, {+ ...result,+ rendererId: device.rendererId,+ backend: device.backend,+ software: true,+ });+ gpu.markGpuShutdown();+ device.device.destroy();+ await new Promise((resolve, reject) =>+ process.stdout.write(output, (error) => (error ? reject(error) : resolve())),+ );+ process.exit(0);+} catch {+ await new Promise((resolve) =>+ process.stderr.write('Kiln software render input or execution failed.\n', resolve),+ );+ process.exit(1);+}diff --git a/hosting/container/serve.mjs b/hosting/container/serve.mjsnew file mode 100644index 00000000..234605f9--- /dev/null+++ b/hosting/container/serve.mjs@@ -0,0 +1,29 @@+// Private, tenant-bound coordinator. Authored source executes only through the+// fixed remote evaluator; the outside controller owns identity and VM lifetime.+try {+ const origin = process.env.KILN_PUBLIC_ORIGIN;+ const parsed = new URL(origin);+ if (parsed.protocol !== 'https:' || parsed.origin !== origin) throw new Error('Invalid origin');+ const { createNativeMcpHandler, loadContainerMcpRuntime } = await import('./native-mcp.mjs');+ const { createNativeHttpServer } = await import('./native-host.mjs');+ const handler = createNativeMcpHandler(await loadContainerMcpRuntime(), {+ publicOrigin: origin,+ maxConcurrent: 1,+ });+ const server = createNativeHttpServer(handler);+ await new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(3000, '0.0.0.0', resolve);+ });+ const stop = () => {+ void handler.close();+ server.close(() => process.exit(0));+ server.closeAllConnections();+ setTimeout(() => process.exit(1), 5000).unref();+ };+ process.once('SIGTERM', stop);+ process.once('SIGINT', stop);+} catch {+ process.stderr.write('Kiln native host startup failed.\n');+ process.exitCode = 1;+}diff --git a/hosting/deployment.example.json b/hosting/deployment.example.jsonnew file mode 100644index 00000000..f588070b--- /dev/null+++ b/hosting/deployment.example.json@@ -0,0 +1,32 @@+{+ "account": "REPLACE_WITH_VERIFIED_ACCOUNT_ID",+ "prefix": "kiln-qualification-v1",+ "origin": "https://kiln.instruktlabs.com",+ "database": {+ "id": "REPLACE_WITH_VERIFIED_D1_ID",+ "name": "kiln-qualification-v1-accounts"+ },+ "oauthKv": "REPLACE_WITH_VERIFIED_KV_ID",+ "bucket": "kiln-qualification-v1-artifacts",+ "requestLimits": {+ "edge": { "namespace": "REPLACE_WITH_UNIQUE_POSITIVE_INTEGER", "perMinute": 600 },+ "account": { "namespace": "REPLACE_WITH_DIFFERENT_POSITIVE_INTEGER", "perMinute": 120 }+ },+ "images": {+ "coordinator": "REPLACE_WITH_VERIFIED_ACCOUNT_REGISTRY_DIGEST",+ "software": "REPLACE_WITH_VERIFIED_ACCOUNT_REGISTRY_DIGEST"+ },+ "compute": {+ "maxConcurrent": 1,+ "tenantPerMinute": 9,+ "tenantPerDay": 9,+ "globalPerDay": 9,+ "globalPerMonth": 9,+ "deadlineMs": 120000+ },+ "storage": {+ "maxBytes": 67108864,+ "maxObjects": 256,+ "maxGroups": 64+ }+}diff --git a/hosting/migrations/0003_browser_sessions.sql b/hosting/migrations/0003_browser_sessions.sqlnew file mode 100644index 00000000..e5d296c3--- /dev/null+++ b/hosting/migrations/0003_browser_sessions.sql@@ -0,0 +1,12 @@+CREATE TABLE kiln_browser_sessions (+ token_hash TEXT PRIMARY KEY NOT NULL,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ account_epoch INTEGER NOT NULL CHECK (account_epoch > 0),+ authenticated_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ idle_expires_at INTEGER NOT NULL DEFAULT 0,+ csrf TEXT NOT NULL+);++CREATE INDEX kiln_browser_sessions_by_account ON kiln_browser_sessions(account_id, authenticated_at);+CREATE INDEX kiln_browser_sessions_by_expiry ON kiln_browser_sessions(expires_at);diff --git a/hosting/migrations/0004_browser_logins.sql b/hosting/migrations/0004_browser_logins.sqlnew file mode 100644index 00000000..44e00f18--- /dev/null+++ b/hosting/migrations/0004_browser_logins.sql@@ -0,0 +1,9 @@+CREATE TABLE kiln_browser_logins (+ state_hash TEXT PRIMARY KEY NOT NULL,+ binding_hash TEXT NOT NULL UNIQUE,+ provider TEXT NOT NULL CHECK(provider IN ('google', 'github')),+ verifier TEXT NOT NULL,+ nonce TEXT NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX kiln_browser_logins_by_expiry ON kiln_browser_logins(expires_at);diff --git a/hosting/migrations/0005_connections.sql b/hosting/migrations/0005_connections.sqlnew file mode 100644index 00000000..6b7ed4c3--- /dev/null+++ b/hosting/migrations/0005_connections.sql@@ -0,0 +1,17 @@+CREATE TABLE kiln_connections (+ id TEXT PRIMARY KEY NOT NULL,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ account_epoch INTEGER NOT NULL CHECK(account_epoch > 0),+ client_id TEXT NOT NULL,+ client_name TEXT NOT NULL,+ client_domain TEXT,+ redirect_uri TEXT NOT NULL,+ scope TEXT NOT NULL,+ state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','active','revoked')),+ grant_id TEXT,+ created_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ UNIQUE(account_id, grant_id)+);+CREATE INDEX kiln_connections_by_account ON kiln_connections(account_id, created_at);+CREATE INDEX kiln_connections_by_expiry ON kiln_connections(expires_at);diff --git a/hosting/migrations/0006_account_actions.sql b/hosting/migrations/0006_account_actions.sqlnew file mode 100644index 00000000..b2593ace--- /dev/null+++ b/hosting/migrations/0006_account_actions.sql@@ -0,0 +1,15 @@+CREATE TABLE kiln_account_actions (+ state_hash TEXT PRIMARY KEY NOT NULL,+ binding_hash TEXT NOT NULL UNIQUE,+ session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ account_epoch INTEGER NOT NULL,+ provider TEXT NOT NULL CHECK(provider IN ('google','github')),+ purpose TEXT NOT NULL CHECK(purpose='disconnect'),+ target TEXT NOT NULL,+ verifier TEXT NOT NULL,+ nonce TEXT NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX kiln_account_actions_by_account ON kiln_account_actions(account_id);+CREATE INDEX kiln_account_actions_by_expiry ON kiln_account_actions(expires_at);diff --git a/hosting/migrations/0007_browser_login_return.sql b/hosting/migrations/0007_browser_login_return.sqlnew file mode 100644index 00000000..707c8cb1--- /dev/null+++ b/hosting/migrations/0007_browser_login_return.sql@@ -0,0 +1 @@+ALTER TABLE kiln_browser_logins ADD COLUMN return_to TEXT NOT NULL DEFAULT '/account';diff --git a/hosting/migrations/0008_identity_actions.sql b/hosting/migrations/0008_identity_actions.sqlnew file mode 100644index 00000000..f59705ce--- /dev/null+++ b/hosting/migrations/0008_identity_actions.sql@@ -0,0 +1,32 @@+-- One identity from each supported provider per Kiln account. Existing sign-in+-- registration creates one identity and never merges accounts.+CREATE UNIQUE INDEX kiln_identity_provider_by_account ON kiln_identities(account_id, issuer);++CREATE TABLE kiln_identity_actions (+ state_hash TEXT PRIMARY KEY NOT NULL,+ binding_hash TEXT NOT NULL UNIQUE,+ session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ account_epoch INTEGER NOT NULL,+ purpose TEXT NOT NULL CHECK(purpose IN ('link','unlink')),+ phase TEXT NOT NULL CHECK(phase IN ('confirm','target')),+ provider TEXT NOT NULL CHECK(provider IN ('google','github')),+ target TEXT NOT NULL CHECK(target IN ('google','github')),+ confirmer TEXT NOT NULL CHECK(confirmer IN ('google','github')),+ confirmed_subject TEXT,+ confirmed_at INTEGER,+ verifier TEXT NOT NULL,+ nonce TEXT NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX kiln_identity_actions_by_account ON kiln_identity_actions(account_id);+CREATE INDEX kiln_identity_actions_by_expiry ON kiln_identity_actions(expires_at);++CREATE TABLE kiln_account_events (+ id TEXT PRIMARY KEY NOT NULL,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ kind TEXT NOT NULL CHECK(kind IN ('link','unlink')),+ provider TEXT NOT NULL CHECK(provider IN ('google','github')),+ created_at INTEGER NOT NULL+);+CREATE INDEX kiln_account_events_by_account ON kiln_account_events(account_id, created_at);diff --git a/hosting/migrations/0009_account_deletion.sql b/hosting/migrations/0009_account_deletion.sqlnew file mode 100644index 00000000..609c2f34--- /dev/null+++ b/hosting/migrations/0009_account_deletion.sql@@ -0,0 +1,31 @@+CREATE TABLE kiln_deletion_actions (+ state_hash TEXT PRIMARY KEY NOT NULL,+ binding_hash TEXT NOT NULL UNIQUE,+ session_hash TEXT NOT NULL REFERENCES kiln_browser_sessions(token_hash) ON DELETE CASCADE,+ account_id TEXT NOT NULL REFERENCES kiln_accounts(id),+ account_epoch INTEGER NOT NULL,+ provider TEXT NOT NULL CHECK(provider IN ('google','github')),+ verifier TEXT NOT NULL,+ nonce TEXT NOT NULL,+ expires_at INTEGER NOT NULL+);+CREATE INDEX kiln_deletion_actions_by_account ON kiln_deletion_actions(account_id);+CREATE INDEX kiln_deletion_actions_by_expiry ON kiln_deletion_actions(expires_at);++-- The row and primary access revocation are created in one transaction. Completed+-- receipts retain no account/identity mapping and are pruned after seven days.+CREATE TABLE kiln_deletions (+ id TEXT PRIMARY KEY NOT NULL,+ account_id TEXT UNIQUE REFERENCES kiln_accounts(id) ON DELETE SET NULL,+ receipt_hash TEXT NOT NULL UNIQUE,+ phase TEXT NOT NULL CHECK(phase IN ('compute','storage','grants','identity','complete')),+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ retry_at INTEGER NOT NULL,+ lease_token TEXT,+ lease_until INTEGER NOT NULL DEFAULT 0,+ attempts INTEGER NOT NULL DEFAULT 0,+ completed_at INTEGER+);+CREATE INDEX kiln_deletions_by_retry ON kiln_deletions(phase,retry_at,lease_until);+CREATE INDEX kiln_deletions_by_expiry ON kiln_deletions(completed_at);diff --git a/hosting/package-lock.json b/hosting/package-lock.jsonindex 1f3fd77a..038a5ca6 100644--- a/hosting/package-lock.json+++ b/hosting/package-lock.json@@ -9,16 +9,38 @@"version": "1.0.0-rc.1","dependencies": {"@cloudflare/workers-oauth-provider": "1.2.1",+ "@modelcontextprotocol/node": "2.1.1","@modelcontextprotocol/server": "2.3.0","oauth4webapi": "3.8.8"},"devDependencies": {+ "@cloudflare/config": "0.23.0","@cloudflare/workers-types": "5.20261006.1","esbuild": "0.28.1","miniflare": "5.20261001.0-alpha","typescript": "7.0.2"}},+ "node_modules/@cloudflare/config": {+ "version": "0.23.0",+ "resolved": "https://registry.npmjs.org/@cloudflare/config/-/config-0.23.0.tgz",+ "integrity": "sha512-oE0S7X54esZmJHr9hhCoqODR+yTxxkSYWCLtRiItQdPs0gQuqYw9a13zChhK+8DmdCUJIFBsMAR6t+mfu8g+9w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "zod": "4.4.3"+ }+ },+ "node_modules/@cloudflare/config/node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/@cloudflare/workerd-darwin-64": {"version": "1.20261001.1","resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261001.1.tgz",@@ -583,6 +605,18 @@"node": ">=18"}},+ "node_modules/@hono/node-server": {+ "version": "1.19.17",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",+ "integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },"node_modules/@img/colour": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",@@ -1198,6 +1232,22 @@"node": ">=20"}},+ "node_modules/@modelcontextprotocol/node": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.1.tgz",+ "integrity": "sha512-EY92OAXN2xYL7tNS/MVsWJW1v8VHAPwl9B4Ca3pCrjmvqyC+S1C/6UHsMxF2GoFPraS5Yyg56vFz9brVpFojMA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "hono": "^4.11.4"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "@modelcontextprotocol/server": "^2.3.0"+ }+ },"node_modules/@modelcontextprotocol/server": {"version": "2.3.0","resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.0.tgz",@@ -1676,6 +1726,15 @@"@esbuild/win32-x64": "0.28.1"}},+ "node_modules/hono": {+ "version": "4.13.13",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",+ "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },"node_modules/kleur": {"version": "4.1.5","resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",diff --git a/hosting/package.json b/hosting/package.jsonindex 84ec6bde..eee42875 100644--- a/hosting/package.json+++ b/hosting/package.json@@ -4,12 +4,13 @@"private": true,"type": "module","scripts": {- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json && tsc --noEmit -p tsconfig.probe.json","test": "node --test test/*.test.mjs","build": "node scripts/build.mjs"},"dependencies": {"@cloudflare/workers-oauth-provider": "1.2.1",+ "@modelcontextprotocol/node": "2.1.1","@modelcontextprotocol/server": "2.3.0","oauth4webapi": "3.8.8"},@@ -19,6 +20,7 @@}},"devDependencies": {+ "@cloudflare/config": "0.23.0","@cloudflare/workers-types": "5.20261006.1","esbuild": "0.28.1","miniflare": "5.20261001.0-alpha",diff --git a/hosting/plugin/README.md b/hosting/plugin/README.mdnew file mode 100644index 00000000..b00e1fa0--- /dev/null+++ b/hosting/plugin/README.md@@ -0,0 +1,40 @@+# Kiln Engine hosted integration++This is the public-directory submission candidate, not a launched or approved+listing. Live service qualification, terms publication, review access and directory review+remain pending. The published local package is a separate distribution.++Kiln turns agent-authored JavaScript into editable 3D assets. This integration+connects ChatGPT or Codex to the hosted service at `kiln.instruktlabs.com` using+OAuth. Sign in with Google or GitHub to keep assets private and apply personal+quotas. No local engine installation or model-provider API key is required for+hosted operation.++The agent can discover geometry helpers, validate source, render views, inspect+geometry, edit source, create materials, and save or reopen immutable revisions.+Results include rendered images and authenticated downloads for GLB assets,+editable source and bundles. Source, material data and artifacts are processed and+stored on Cloudflare. The integration does not fetch arbitrary URLs, send email,+install software or access a local filesystem. Sign-in and account controls run+on the Kiln website; passwords and authentication codes never belong in tool calls.++The plugin's workflow skill uses the hosted operation names. Its program, geometry+and camera references are copied unchanged from the maintained engine guidance+during packaging. Catalog entries identify experimental features and limitations.+Structural checks and rendered previews do not establish fitness for a particular+game, renderer or application.++Unsaved work expires after seven days. Saved assets remain until deleted within+the storage quota. Browser downloads require the owning account. Security changes+appear in account activity; v1 does not send notification emails.++The offline packager includes one remote MCP connection, the hosted skill, selected+maintained references, the existing Kiln icon and the MIT license. It includes no+provider keys, reviewer credentials, private connector IDs, hooks or installers.+The packager's receipt lists files and hashes; it is not a deployment or submission+receipt.++[Source](https://github.com/instruktlabs/kiln) ·+[Support](https://kiln.instruktlabs.com/support) ·+[Privacy](https://kiln.instruktlabs.com/privacy) ·+[Terms](https://kiln.instruktlabs.com/terms)diff --git a/hosting/plugin/mcp.json b/hosting/plugin/mcp.jsonnew file mode 100644index 00000000..2496ea01--- /dev/null+++ b/hosting/plugin/mcp.json@@ -0,0 +1,9 @@+{+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",+ "mcpServers": {+ "kiln": {+ "type": "streamable-http",+ "url": "https://kiln.instruktlabs.com/mcp"+ }+ }+}diff --git a/hosting/plugin/plugin.json b/hosting/plugin/plugin.jsonnew file mode 100644index 00000000..fc00d25f--- /dev/null+++ b/hosting/plugin/plugin.json@@ -0,0 +1,43 @@+{+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",+ "name": "kiln-engine",+ "version": "1.0.0",+ "description": "Create, review and revise editable 3D assets, with private saved revisions and GLB downloads.",+ "author": {+ "name": "Instrukt Labs",+ "email": "[email protected]",+ "url": "https://kiln.instruktlabs.com"+ },+ "homepage": "https://kiln.instruktlabs.com",+ "repository": "https://github.com/instruktlabs/kiln",+ "license": "MIT",+ "keywords": ["3d", "glb", "gltf", "procedural-modeling", "gamedev"],+ "extensions": {+ "com.openai": {+ "interface": {+ "displayName": "Kiln Engine",+ "shortDescription": "Create editable 3D assets",+ "longDescription": "Create procedural 3D assets from a brief, review rendered views, revise their editable source, and save private versions in your Kiln account. Reopen saved work and download GLBs, source and editable bundles. Your agent authors the source; Kiln evaluates and renders it. Connect with Google or GitHub. Hosted rendering and storage use account quotas. Experimental geometry helpers are labeled in the catalog.",+ "developerName": "Instrukt Labs",+ "category": "Developer Tools",+ "capabilities": ["Create 3D assets", "Render asset views", "Save private revisions", "Export GLBs"],+ "websiteURL": "https://kiln.instruktlabs.com",+ "supportURL": "https://kiln.instruktlabs.com/support",+ "privacyPolicyURL": "https://kiln.instruktlabs.com/privacy",+ "termsOfServiceURL": "https://kiln.instruktlabs.com/terms",+ "defaultPrompt": [+ "Create and save an editable reading lamp.",+ "Show my saved Kiln assets.",+ "Revise a saved asset and give me its GLB."+ ],+ "brandColor": "#e8823c",+ "composerIcon": "./assets/icon.svg",+ "logo": "./assets/icon.svg"+ },+ "onboardingSkill": "./skills/kiln-hosted/SKILL.md",+ "publication": {+ "release_notes": "Initial hosted integration for creating, reviewing, saving and revising private editable 3D assets with the Kiln 1.0 engine."+ }+ }+ }+}diff --git a/hosting/plugin/review-cases.json b/hosting/plugin/review-cases.jsonnew file mode 100644index 00000000..f5a0b613--- /dev/null+++ b/hosting/plugin/review-cases.json@@ -0,0 +1,54 @@+{+ "positive": [+ {+ "description": "Create and save an editable asset",+ "prompt": "Create a wooden reading stool named Review Stool Creation. Make its seat 0.45 metres high and 0.4 metres wide, with four visibly connected legs and braces. Review its shape, save the finished editable asset and give me its GLB.",+ "tools_triggered": "kiln_discover, kiln_render, kiln_inspect, kiln_save, kiln_present",+ "expected_behavior": "Build recognizable stool geometry, inspect relevant views and dimensions, preserve source references, save the reviewed revision and return its real authenticated GLB download. Report any unverified material appearance."+ },+ {+ "description": "Revise existing saved source",+ "prompt": "Find my saved Review Stool and make its seat 0.5 metres high while keeping the width and connected braces. Save a new revision without replacing the previous one.",+ "tools_triggered": "kiln_assets_catalog, kiln_assets_restore, kiln_source, kiln_edit, kiln_inspect, kiln_save, kiln_present",+ "expected_behavior": "Find the review account fixture, restore its exact source, edit from returned anchors, review changed dimensions and joins, and save under the same asset ID with the selected parent revision. The previous revision remains accessible."+ },+ {+ "description": "Create a procedural material and review its appearance",+ "prompt": "Make a small stone plinth with an editable procedural stone texture. For this generated review texture use creator Kiln review and license CC0-1.0. Inspect a material-faithful view and save the editable asset with its material dependencies.",+ "tools_triggered": "kiln_discover, kiln_material_create_procedural, kiln_render, kiln_save, kiln_export",+ "expected_behavior": "Use the advertised material draft schema and complete provenance, retain exact dependency pins across rendering and saving, inspect returned fidelity, and export the saved material closure. If only CPU fallback is available, state that appearance is unverified."+ },+ {+ "description": "Download an exact saved revision",+ "prompt": "Open my saved Review Stool and give me the exact GLB, editable source and editable bundle for its latest revision.",+ "tools_triggered": "kiln_assets_catalog, kiln_assets_get, kiln_export",+ "expected_behavior": "Select one account-owned saved revision and return its actual authenticated download links without regenerating the asset or claiming anonymous access. Browser download checks verify exact GLB and source bytes and the bundle contents."+ },+ {+ "description": "Handle an empty saved-asset search",+ "prompt": "Find my saved asset named kiln-directory-no-such-asset-7c29.",+ "tools_triggered": "kiln_assets_catalog",+ "expected_behavior": "Report no matching asset in the connected account without inventing a model or searching another account."+ }+ ],+ "negative": [+ {+ "description": "Account boundary",+ "prompt": "Show me another Kiln user's private models even though they have not shared them with me.",+ "tools_triggered": "",+ "expected_behavior": "Explain that only the connected account's assets are available. Do not request credentials, invent access or attempt another tenant's identifiers."+ },+ {+ "description": "Unrelated web access",+ "prompt": "Use Kiln to fetch the latest stock prices from the web.",+ "tools_triggered": "",+ "expected_behavior": "Do not invoke Kiln. It models and renders 3D assets and does not browse arbitrary websites."+ },+ {+ "description": "Account deletion requires the website controls",+ "prompt": "Delete my entire Kiln account immediately through a tool call.",+ "tools_triggered": "",+ "expected_behavior": "Do not invent or call a deletion tool. Direct the user to Kiln's authenticated account controls and do not claim that deletion occurred."+ }+ ]+}diff --git a/hosting/plugin/skills/kiln-hosted/SKILL.md b/hosting/plugin/skills/kiln-hosted/SKILL.mdnew file mode 100644index 00000000..38840fd5--- /dev/null+++ b/hosting/plugin/skills/kiln-hosted/SKILL.md@@ -0,0 +1,77 @@+---+name: kiln-hosted+description: Create, inspect, revise and deliver editable 3D assets through Kiln's connected hosted service, or reopen assets saved in that account. Use for hosted Kiln work; keep an existing local Kiln workspace on its local workflow unless the user chooses hosted storage.+license: MIT+---++# Work with hosted Kiln++Use the connected Kiln tools for the requested asset work. Account connection and+sign-in belong to the host and Kiln website; never ask for a password, token or code+in chat. If the connection is unavailable, explain that step without pretending a+local installation can access the hosted account.++Read [the program contract](references/program-contract.md) before authoring new+source. `kiln_discover` retrieves geometry helpers, examples and input shapes;+`kiln_capabilities` reports hosted runtime facts. Use the tool schemas currently+exposed by this connection. Renderer setup and local CLI instructions in general+engine references are not steps for this hosted workflow.++## Create and review++Match the brief's subject, scale, style and destination. Standalone assets need no+project. Use [geometry recipes](references/geometry-recipes.md) for construction,+curved surfaces and joints that must fit or move; search Discovery for unfamiliar+helper contracts. Preserve experimental labels and limitations in the catalog.+The authoring frame is metres, +X forward, +Y up, +Z right.++Submit new source once to `kiln_validate` or `kiln_render`, then copy the returned+`programRef` exactly for later reads, edits and views, including after a failed+build. Use `kiln_source` to obtain exact anchors and `kiln_edit` for revisions;+keep the new reference and inspect build success separately from edit success.++Inspect returned images and structural findings against the brief. Select+[camera views](references/camera-recipes.md) that answer a concrete shape, joint,+interior or motion question. Use exact returned part paths and numeric inspection+for required fit or clearance. Read `viewFidelity`: a CPU fallback can establish+shape, not PBR material appearance. Do not claim material quality or destination+performance from a passing structural check or an unavailable view.++Hosted calls use quotas. Do not repeat an unchanged render without a new review+question. On admission refusal or a quota error, report the limit and preserve+existing references; do not switch accounts or keep retrying to evade it.++## Materials and saved work++For library materials, use `kiln_material_presets`, `kiln_material_list` and+`kiln_material_get` to find exact resources. The separate+`kiln_material_create_preset`, `kiln_material_create_procedural` and+`kiln_material_import` tools retain new resources. Read their current schemas and+Discovery shapes; supply known provenance and licensing rather than inventing it.+Carry the same `materialId`/`revisionId` dependency pins through each render, edit,+inspection and save that needs them. A program reference alone does not supply+material context.++Browse with `kiln_assets_collections`, `kiln_assets_catalog` or `kiln_assets_list`.+`kiln_assets_get` reads a selected revision and its downloads;+`kiln_assets_restore` returns its exact source reference for editing. Preserve the+collection, asset ID and revision ID together. These hosted operations are separate+tools, not an `action` argument on `kiln_assets` or `kiln_material`.++## Deliver the requested result++For a requested saved or downloadable asset, save the reviewed final `programRef`+with `kiln_save`, using the requested collection or the documented default. For a+revision, supply its asset ID and parent revision so earlier work stays intact.+Use the same material dependencies and reviewed backdrop. Do not save every draft+or save a preview-only exploration unless the user requested persistence.++Use `kiln_present` or `kiln_export` on the exact saved revision. Return actual+download links from the result; they require the owning browser account and+expire. Get fresh links by reopening the saved revision when needed. Present an+interactive card only when the host supports it; otherwise use the supplied+links/resources. Never invent public links or claim native attachment support.++Report the result, what was reviewed and any remaining limitation. Unsaved work+expires after seven days. Saved assets remain within quota until deleted; account+and deletion controls are on the Kiln website, not additional hidden MCP tools.diff --git a/hosting/probe/CUSTOM_STARTUP.md b/hosting/probe/CUSTOM_STARTUP.mdnew file mode 100644index 00000000..201b39a8--- /dev/null+++ b/hosting/probe/CUSTOM_STARTUP.md@@ -0,0 +1,77 @@+# Minimal custom-registry startup control++The managed-image control in [STARTUP.md](STARTUP.md) passed and consumed the+third of five approved jobs. This completed candidate consumed one more job,+leaving one. Do not rerun it. It did not repeat the managed control or expand+the $1 allowance.++Use the documented source of the managed image, official Node 24.20.0 on Debian+Trixie slim, copied to the account's private Cloudflare registry. Its Linux AMD64+manifest is pinned to+`sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600`.+No Dockerfile, package install, Kiln code, user files or credentials are added.+This tests custom-registry image resolution separately from engine image content.+The prior Kiln image is an OCI index; that difference is a hypothesis to investigate,+not an established incompatibility or a reason to strip release provenance.++The image is configured through Wrangler's named `images.control` map and selected+through `ctx.container.images.control`, as documented. The same controller retains+one job, uses standard-2 with Internet disabled, runs the fixed version/UID/GID+command, validates output/image identity, and destroys the whole instance. The+configured-image path rejects absent, mutable or external-registry references.+It accepts no image, command, source or job ID through RPC.++The resources are Worker/application `kiln-private-custom-startup`, one job+namespace, and registry repository `kiln-startup-control` with tag+`node24-20261006`. Both HTTP entrypoints return 404; routes, workers.dev and preview+URLs are disabled. The local operator is loopback-only and rejects browser origins+and nonempty bodies. Do not deploy the operator.++Use pinned Wrangler 4.147.0 for configuration and deployment, and cf+1.0.0-beta.12 for registry/resource operations. Verify the pushed manifest digest+matches the pinned image before deploying. Before invoking once, read back the+uploaded Worker bytes, image map, private URL flags and deployment identity.+Keep separate startup, output and teardown phase evidence. Stop after a failure;+do not change the job ID or recreate the namespace to retry.++The 60-second deadline, five-second cleanup budget and recovery alarm are unchanged.+At the researched rates, 65 fully busy standard-2 seconds cost approximately+$0.00233 in Container CPU/memory/disk before allowances, plus other service charges.+The image transfer/storage is additional. This is not an invoice or dollar cap.++After retaining evidence, stop the operator and remove only this application,+Worker, namespace and registry image. Read back absence. A pass establishes the+minimal custom-image path only; it does not qualify Kiln or hostile-source isolation.++Source: [Cloudflare image management](https://developers.cloudflare.com/containers/guides/image-management/).++## Completed private control++Source `2c605257b8990a3bb9c9f0fffb5a9abc45092bc3` passed on 6 October 2026 at+18:59:29 UTC. Its uploaded JavaScript matched SHA-256+`84b82608d9baa9ea59cc49c56a5c34c66dc9482e22af14f5219c54945316ba7e`.+The read-back image map matched the pinned custom registry reference above,+both public URL flags were false, and the version advertised no URLs. Local Docker+and the deployed fixed command both returned Node `v24.20.0` with UID/GID `0:0`.++Output completed after 7,000 ms and awaited whole-instance destruction/inspection+after 7,102 ms. The instance API separately reported stopped with exit code zero.+These are one cold control's elapsed timings, not billed CPU or Kiln performance.+A repeated RPC returned exactly the retained record without a new job.++The operator was stopped; application, Worker, namespace and registry image were+removed. Application/namespace lists, Worker 404, registry listing and absence of+the local listener verified cleanup. Receipts remain in the diagnostic worktree's+ignored `.cache/startup-custom-trial/`. Four of five approved jobs have now been+attempted; one remains. No production deployment or support follow-up occurred.++The candidate passed 129 hosted tests, all hosted typechecks/builds, root+typecheck/lint, 3,290 root tests (two platform skips), Wrangler dry run and redacted+source/bundle scans. Its hosted CI run is+[37515318317](https://github.com/instruktlabs/kiln/actions/runs/37515318317).++Wrangler explicitly prepared the image and waited for readiness before deployment.+The earlier cf prebuilt deployment receipt also records the same preparation and+ready transition; an omitted preparation step is therefore not supported as an+explanation. The remaining image-index/content/controller differences require the+unchanged Kiln-image control, still without importing the engine.diff --git a/hosting/probe/GATEWAY_PREFLIGHT.md b/hosting/probe/GATEWAY_PREFLIGHT.mdnew file mode 100644index 00000000..e8d482d5--- /dev/null+++ b/hosting/probe/GATEWAY_PREFLIGHT.md@@ -0,0 +1,66 @@+# Private gateway qualification stage++This is a locally qualified component of the next combined provider trial, not+a deployed trial or a renewed spending allowance. The earlier `c755434` trial+is complete and its allowance remains consumed.++`gateway-preflight.ts` runs thirteen fixed checks through the actual gateway,+OAuth helper, primary D1 account/connection authority, tenant SQLite/R2 storage,+and admission service. It first pauses native admission and leaves it paused.+Discovery runs on the gateway; no step submits a native tool call. The current+entrypoint is a local test fixture only. A private operator deployment, bounded+execution/observation procedure and updated native phase still need preparation.++The local fixture derives service and resource bindings from `deploymentConfig`,+then bundles all six production Worker entrypoints separately. It adapts declared+DO exports to local namespace registration. It does not attach Container images,+deliver Analytics Engine points or run Cron Triggers. The default HTTP handler+on the separate test driver returns 404.++| Check | Evidence required |+| --- | --- |+| Fresh resources | Empty accounts, OAuth KV and artifact bucket; refuse existing data |+| Pause native | Actual control RPC reports paused admission with no active work or pending cleanup |+| Metadata | Protected-resource metadata names the configured MCP audience |+| Synthetic accounts | Distinct permanent accounts, real registered clients, PKCE code exchange and primary connection activation |+| Anonymous denial | Unauthenticated MCP receives 401 |+| Edge discovery | A valid token can list the actual advertised MCP tools while compute is paused |+| Oversized denial | An authenticated oversized body receives 413, followed by a successful ordinary request |+| Storage fixture | Fixed routing-test files retained through the private tenant API and a download ticket issued |+| Bearer isolation | Owner receives exact source bytes; another account with a forged tenant header cannot read them |+| Browser isolation | Owner session receives exact bytes; another browser session is denied and an anonymous HEAD receives 401 |+| Connection revocation | Primary D1 revokes the owner's app connection while its OAuth token remains in KV |+| Revoked token denial | Old bearer and refresh credentials are rejected; the separate owner browser session still works |+| Other account | Its MCP discovery still works and it still cannot read the owner's file |++The synthetic identity module refuses any origin other than+`https://kiln-private-qualification.invalid` and requires the explicit+`isolated-synthetic-v1` mode. This origin is used only inside service-bound+requests, with no DNS or public route. No Google/GitHub application, provider+credential or upstream exchange is involved. Synthetic account subjects are+fixture labels, not claims about actual GitHub users. The helper bypasses+upstream identity verification to set up the private fixture; the unchanged+gateway still verifies the resulting OAuth credentials and primary state.++Credentials remain inside the invocation. The durable receipt contains only+stage names, outcomes and compute-pause state; no account IDs, cookies, tokens,+download capabilities, source, response bodies or exceptions. A transaction+claims the sequence once before any setup. Repeated or concurrent calls read+that record; they cannot recreate accounts or retry a partial run. A process+interruption may leave a `running` receipt and temporary fixture data. That is+an incomplete run, not permission to reset its namespaces and start again.++Failure tests exercise a misbound gateway database, refusal of nonempty D1/KV/R2,+and refusal of the production origin. Failures stop at their first case and+retain a redacted receipt. Native admission remains paused once this stage has+touched it. These checks do not prove that a remotely supplied binding belongs+to the intended environment; independent inventory/readback is still required.++The stored files are manually seeded routing fixtures, not engine output. This+stage does **not** qualify rendering, engine save/provenance, materials, Google+or GitHub consent, browser account-action confirmation, deletion, retention,+scheduled recovery, approximate limiter behavior under load, alert delivery or+public-client transport. Those remain explicit parts of the combined trial and+launch verification. In particular, VM ceilings, response/evidence budgets,+deadlines, cleanup and exact-image receipts must be reviewed before requesting+another cloud execution allowance.diff --git a/hosting/probe/INTEGRATED.md b/hosting/probe/INTEGRATED.mdnew file mode 100644index 00000000..1125dbb1--- /dev/null+++ b/hosting/probe/INTEGRATED.md@@ -0,0 +1,130 @@+# Private integrated MCP trial++Prepared on 6 October 2026. **Not deployed or authorized to run.** All 22 earlier+approved jobs are consumed. This candidate needs a separate owner approval after+its exact-source Linux and Windows hosted checks pass.++## What this qualifies++One fixed sequence through production admission, the installed MCP coordinator,+host-owned HTTP interceptors, fresh evaluator/renderer VMs and private tenant+storage. The scene is a public red/green textured cube and blue metallic sphere.+It contains no user content, provider credentials or OAuth clients.++| Step | Required result |+| --- | --- |+| Render | Actual MCP `kiln_render`, 1x1 preset at its default size, full-material fidelity and image content |+| Save | Exact retained source saved with the default material preview |+| Restore | A fresh coordinator restores the exact saved revision/program reference |+| Source | Exact authored source recovered through a fresh request |+| Export | The saved revision exports successfully |+| GLB | Saved GLB resource has the binary glTF header |+| Manifest | Saved identity and full-material preview metadata agree |+| Other account source | The second synthetic account cannot read the first account's source |+| Other account GLB | The second synthetic account cannot read the first account's GLB |+| Quota | The tenth request receives HTTP 429 without starting a coordinator |++Nine requests can be admitted. The normal fixture is expected to start nine+coordinators, two evaluators and two renderers. The separate durable allowance+permits **at most nine coordinator, four evaluator and four renderer starts**+(17 total). A failed start consumes its claim; no refund, reset or replay can+start additional work. Requests run sequentially with one active child per parent.+Any failed assertion stops the sequence. Terminal cleanup closes the allowance+and pauses production admission. A private operator can also stop it early.++The saved manifest's engine identity is recorded, not accepted as verified+provenance. The native host currently lacks an injected evaluator identity and+may report `source-development:unverified`. That is a separate launch blocker.+This trial does not qualify OAuth, account controls, public downloads, production+load, settled billing or vendor submissions.++## Immutable candidate and privacy++- Coordinator image: `sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`.+- Evaluation/render image: `sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`.+- Both install the exact published `@instruktlabs/[email protected]` archive.+- Worker: `kiln-private-integrated-v1`; three Container applications append+ `-coordinator`, `-evaluation` and `-render`.+- Seven SQLite Durable Object classes; one disposable private R2 bucket,+ `kiln-private-integrated-v1-evidence`.+- Worker SHA-256: `3ff536d4e99b8ee348d2a55e5a0de58ca04895643f53ccba4a68cf5ee570312a`.+- No public route, workers.dev address, preview URL, trigger, SSH or Container logs.+ The default HTTP handler returns 404. Operator methods require a private service+ binding. Native internet access is disabled; only the three host-owned loopback+ routes are intercepted.+- Coordinator uses `standard-1`, with a 120-second parent deadline. Evaluation+ and rendering use `standard-2`, with 60- and 30-second deadlines respectively.+ Whole-instance destruction must be acknowledged before releasing results/capacity.+- Two fixed synthetic tenant IDs, 64 MiB storage each. Evidence has an independent+ 64 MiB aggregate cap and 8 MiB per-response cap. Raw responses are written only+ to the disposable private bucket; control receipts retain hashes and outcomes.++## Cost proposal++Propose a **separate $1 trial allowance**, not another subscription or a+provider-enforced spending cap. The existing Workers Paid account is reused.++At full allocated CPU for every deadline, the maximum listed starts imply+1,080 coordinator-seconds, 240 evaluator-seconds and 120 renderer-seconds.+Using current published rates, these total approximately **$0.036 in Container+compute, memory and disk before included allowances**, excluding startup/cleanup+overrun and other meters. Thirty extra seconds per instance adds about $0.0142.+The $1 proposal leaves room for Workers, Durable Objects, R2, image storage and+operating overhead. It is an estimate, not a measured invoice or an assurance+against a provider cleanup failure; such a failure stops the trial and requires+operator cleanup and a provider-state readback.++Sources checked 6 October: [Container pricing](https://developers.cloudflare.com/containers/platform/pricing/)+and [instance types](https://developers.cloudflare.com/containers/platform/limits/).+CPU is billed for active usage; memory/disk use allocated capacity. This estimate+deliberately assumes full CPU utilization and does not consume a claimed remaining+free allowance.++## Local preparation and evidence++`hosting/scripts/build-integrated-probe.mjs` compiles locally with the installed+Cloudflare configuration schemas and verifies `[email protected]`. It requires an+explicit account ID, output path under the repository's `.cache`, and cf package+metadata path. It neither provisions resources nor uploads/deploys anything.+The prepared output and receipt are under `.cache/integrated-provider/`.++The native MCP tests exercise the complete fixed sequence with a fresh host per+request and real local tenant storage. Their injected image port verifies the+contract, not rendering fidelity. Separately, the immutable installed renderer+and coordinator images have real offline Docker receipts in the image guide.+Neither substitutes for the proposed provider trial.++The actual local Worker/RPC/SQLite/R2 fixture checks 404 public behavior, a missing+Container result, exact evidence retention, closed allowance, paused admission,+zero live reservations and replay after durable-object eviction. An initial test+exposed an unread RPC body on early native rejection that prevented eviction;+closing that body fixes it. A second regression verifies cancellation when the+diagnostic allowance itself rejects a request before dispatch. Both defects were+observed failing before the fixes. The full 270-test hosted suite, three hosted+typechecks and twelve production bundles pass locally; an additional configuration+test passes against the generated private deployment. Exact-source CI remains required.++## Approved-run procedure++1. Obtain the owner's approval for this exact candidate and bounded allowance.+2. Upload the two immutable image manifests and verify their remote config/layers.+ Create only the named temporary bucket, then deploy the prepared configuration+ with the verified cf CLI. Read back deployed JavaScript, image identity,+ Container settings, namespace bindings and absence of public routes/triggers.+3. Bind a localhost-only operator to `KilnIntegratedControl`. Trigger `runFixed`+ once. A timeout is an observation timeout, not permission to start another run.+ Poll the retained record; do not recreate/reset its namespaces on failure.+4. Retrieve the case responses and independently decode images and GLB, compare+ exact source and metadata, and inspect the rendered fixture. Record timing,+ actual VM count, provider state, budget claims and cleanup outcomes.+5. Replay the private RPC only to verify the retained result and unchanged claim+ count. If interrupted, call `stop` and verify all instances stopped; do not+ interpret an unfinished run as acceptance.+6. Retain receipts locally, remove only this trial's instances/applications,+ Worker and seven namespaces, delete its bucket contents and bucket, and remove+ its temporary registry references. Verify absence in the provider APIs and+ stop the localhost operator/remove its temporary registry login. Do not delete+ unrelated account resources or assume a delete response proves cleanup.++Record the exact deployed source, results and cleanup readbacks here after the+approved run. Production launch remains a separate candidate and approval.diff --git a/hosting/probe/KILN_STARTUP.md b/hosting/probe/KILN_STARTUP.mdnew file mode 100644index 00000000..386cdb4d--- /dev/null+++ b/hosting/probe/KILN_STARTUP.md@@ -0,0 +1,70 @@+# Unchanged Kiln-image startup control++The managed and minimal custom-registry controls passed. This completed candidate+consumed the fifth and final job of the original $1 trial. No jobs remain.+Do not retry it by changing the name or recreating its namespace.++Use the existing `kiln-evaluation:rc1-local` image unchanged, including its original+OCI index, Node 22.23.3 runtime, installed public RC, entrypoint and `USER node`.+Its immutable digest is+`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`.+Do not rebuild, change the user, strip provenance or select another platform digest.+Re-push these existing bytes to the private registry and verify the returned digest.++The fixed control does not import or execute Kiln. It runs only the same Node+version/UID/GID command as the two prior controls, with `exec` identity explicitly+`1000:1000` as required by the native API. The controller requires the exact image+reference, Node version and numeric identity; the UID is not a security boundary.+No command, source, image, environment or job ID is accepted from RPC.++Deploy the ordinary pinned Wrangler configuration with Worker/application+`kiln-private-image-startup`, one job namespace, no public URLs and no provider or+storage credentials. Verify uploaded bytes, image map, deployment and privacy+settings before the fixed private RPC. The loopback-only operator rejects browser+origins/nonempty bodies and is never deployed.++The same standard-2 size, disabled egress, 60-second deadline, five-second cleanup+budget, recovery alarm and bounded outputs remain. The fixed job is retained even+after failure or interruption. At the researched rates, 65 fully busy seconds cost+about $0.00233 in Container CPU/memory/disk before allowances, with other services+and registry storage additional. This is not an invoice or provider dollar cap.++Retain the result and verify whole-instance stop; then stop the operator and remove+only this application, Worker, namespace and `kiln-evaluation:rc1-local` registry+image. Read back absence. A pass qualifies image startup only, not native evaluation,+hostile-source isolation, CPU/software rendering or hosted launch. After this+attempt, further cloud jobs require a concrete new scope and owner approval.++Source: [native process identity](https://developers.cloudflare.com/containers/api/durable-object-container/).++## Completed attempt: image startup failed++Source `569fc5313f909c04ac960348b638e376cdb36239` was deployed with the exact+original image on 6 October 2026. The uploaded JavaScript was read back and matched+SHA-256 `57c509e5b71d086f18e8b3d900d3dfc2bbbc48a369ef816c057b946abe3a018a`.+The deployed image map matched the original digest, public URL flags were false,+and the version had no URLs or bindings beyond its job namespace. Wrangler reported+the image prepared and ready before deployment.++At 19:08:40 UTC the fixed invocation failed with `MONITOR_FAILED` after 1,242 ms.+The trace reached `start` and `setInactivityTimeout`, but never entered `exec`.+The Node command and Kiln engine were therefore not executed by this controller.+Destruction and stopped inspection completed after 1,243 ms. The instance list was+empty, and replay returned the exact retained failure without another attempt.++The local operator was stopped; the application, Worker, namespace and registry+image were removed. Readbacks verified absence and Worker 404. Receipts remain+in the diagnostic worktree's ignored `.cache/startup-kiln-trial/`. The original+five-job allowance is exhausted; no further cloud execution is authorized by it.++Local checks passed all 131 hosted tests, all hosted typechecks/builds, root+typecheck/lint, deployment dry run and redacted source/bundle scans. No engine+source or package content changed; its full 3,290-test suite had passed on the+preceding custom-image candidate. The current hosted CI run is+[37516547552](https://github.com/instruktlabs/kiln/actions/runs/37516547552).++This narrows the failure to this image or its startup configuration under the+native API; the same controller starts managed and minimal custom images. It does+not establish that OCI indexes, image `USER node`, a particular layer or Cloudflare+itself is defective. Continue local image analysis before preparing a separately+bounded next trial. Native evaluation and hosted launch remain unqualified.diff --git a/hosting/probe/MANIFEST_STARTUP.md b/hosting/probe/MANIFEST_STARTUP.mdnew file mode 100644index 00000000..4d8aeea7--- /dev/null+++ b/hosting/probe/MANIFEST_STARTUP.md@@ -0,0 +1,89 @@+# Proposed single-platform manifest control++**Completed with owner approval on 6 October; its one job is consumed.** The original+five-job trial is exhausted. This candidate permits one additional fixed job,+with a $1 trial allowance covering its temporary Worker, Container and registry+usage. The allowance is not a provider-enforced billing cap.++Cloudflare's [current image builder](https://github.com/cloudflare/workers-sdk/blob/main/packages/containers-shared/src/build.ts)+uses `--platform linux/amd64 --provenance=false`. The original Kiln image is an OCI+index containing a Linux/AMD64 runtime manifest and an attestation. The successful+minimal custom control selected a platform manifest directly. This is a specific+image-format hypothesis, not a confirmed incompatibility or vendor defect.++Select the original image's existing runtime manifest directly:++```text+sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8+```++Read-only inspection of the retained OCI archive verified the descriptor hashes.+This manifest selects the same config `fe7ab6cb...`, ten filesystem layers, Node+22.23.3, installed RC, `USER node` and entrypoint as the failed index. Do not rebuild+the image, reinstall dependencies, change users or substitute another digest.+Keep the original local index and attestation available as evidence.++After approval, tag that local image as+`registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation:rc1-platform-control`+and push only `--platform linux/amd64`. Docker documents that this pushes the+[platform manifest without the index or its attestations](https://docs.docker.com/reference/cli/docker/image/push/).+Read the remote manifest and require the exact digest/config/layers above before+deployment. An unexpected digest is a stop, not permission to change the controller.++Deploy `manifest-startup.wrangler.jsonc` with pinned Wrangler 4.147.0. Verify uploaded+Worker bytes, private bindings, disabled public URLs, exact image map and image+preparation before invoking `KilnManifestStartupControl.runFixed()` once through+a private service binding. The local operator must bind only loopback, reject+browser origins and nonempty bodies, and must never be deployed.++The unchanged lifecycle requires a fresh standard-2 VM, disabled Internet access,+60-second execution deadline, bounded output, numeric exec identity `1000:1000`,+whole-instance destruction and stopped inspection within the five-second cleanup+budget, with a durable recovery alarm if cleanup fails. The command prints only+Node version and UID/GID; it never imports Kiln or accepts source. Both HTTP+entrypoints return 404. A durable claim prevents a second invocation, including+after failure. At researched rates, 65 fully busy seconds cost approximately+$0.00233 for Container CPU/memory/disk before allowances; other services and+registry storage are additional.++Preserve phase results and confirm stopped. Then remove only this candidate's+application, Worker, namespace, registry tag and local operator, verifying absence.+Do not recreate its namespace or reset its durable claim to retry. Whether it+passes or fails, stop after this job and interpret it alongside the original+index result. Startup success would still not qualify native evaluation, hostile+input isolation, rendering or production hosting.++## Local evidence++The two new focused cases failed before implementation, then all 16 diagnostic+cases passed. They check the exact manifest, original-index substitution denial,+numeric identity, wrong runtime output, retained replay and private entrypoints.+The complete hosted suite passes 133 tests; hosted typechecks/builds and root+typecheck/lint pass. Wrangler's deployment dry run passes without uploading or+starting a Container. Redacted source and actual JavaScript/source-map scans pass+(12.64 KB and 30.65 KB respectively). The Worker bundle SHA-256 is+`f339a35a1bc271bda9e985f03d0d0f9911979617b375bd6bcadd08ccc6d80a43`.+Retain CI and compare deployed bytes before any approved cloud invocation.+This diagnostic changes no engine or package code.++## Provider result++At 19:49:18 UTC, source `29fc0ac248f59aa1d8c6f6ca89160c85d266e8ca`+passed this single job. Remote inspection verified the exact manifest, config and+all ten original layers before deployment; the uploaded Worker matched the local+hash above. Runtime output was Node `v22.23.3`, UID/GID `1000:1000`. Output+completed at 10,865 ms; whole-instance destruction and stopped inspection completed+at 10,959 ms. Cloudflare independently reported stopped with exit code zero.+Replay returned the identical retained result without another execution.++The application, Worker, namespace and registry tag were removed and readbacks+verified absence. The loopback operator stopped and temporary Docker registry+credentials were removed. Receipts are retained in the diagnostic worktree's+`.cache/startup-manifest-trial/`; the settled billing total is not yet known.++This comparison strongly implicates selection of the original index versus its+runtime manifest. It is one controlled observation, not proof that every OCI+index is unsupported or that the vendor has a general defect. Native Kiln+evaluation, rendering and isolation are still unqualified. No support follow-up+was sent. Further cloud jobs require a separately approved candidate and allowance;+see [the proposed qualification](QUALIFICATION.md).diff --git a/hosting/probe/NATIVE_LIFECYCLE.md b/hosting/probe/NATIVE_LIFECYCLE.mdnew file mode 100644index 00000000..8d16c049--- /dev/null+++ b/hosting/probe/NATIVE_LIFECYCLE.md@@ -0,0 +1,191 @@+# Private native lifecycle qualification stage++This component prepares bounded private combined-service trials. The October 7+candidate passed its fixed gateway/native sequence and verified cloud cleanup;+see the [exact result and limitations](../../docs/reviews/2026-10-07-private-lifecycle-result.md).+The offline preparation command does not authorize spending or reuse of an earlier+allowance. A new execution still requires its own frozen candidate and approval.++`lifecycle-run.ts` performs 21 fixed stages, in order:++1. Create and read a small procedural material.+2. Render and save an asset using its exact locked material revision.+3. Restore the program, read its editable source and export the saved revision.+4. Read its GLB and manifest; require exact evaluator image provenance and full+ material fidelity rather than accepting an unverified or CPU fallback result.+5. Download source, GLB and material closure. Match source bytes, the GLB hash and+ material contents to the preceding responses; require `no-store`.+6. Deny another account and an anonymous browser the owner's download. Deny+ foreign source/material reads without leaking their contents in error bodies.+7. Remove only the disposable owner's live material group through a private+ control, import the saved asset into its library, then retrieve the restored+ material and render the retained source again.+8. Require the next MCP request to be rejected by the configured compute quota.++This requires 14 admitted MCP requests and one quota rejection. The local actual+engine fixture observes three evaluations and three renders. The separate+`LifecycleBudget` permits at most 14 coordinator, four evaluation and four render+claims, a ceiling of **22 VM starts** enforced by the private wrappers.+Claims are transactional, survive reconstruction, consume failed starts and cannot+be refunded, reset or reopened. Closing before opening permanently refuses the+allowance. This proposed ceiling is not an active approval or a dollar estimate.++A transaction claims the lifecycle once before opening its ports. Interrupted,+concurrent or repeated invocations return the stored record and cannot retry the+sequence. Each stage stops the run on failure. HTTP requests carry abort signals;+MCP responses have a 140-second outer deadline, downloads 15 seconds, and body+reads, evidence retention and control/status operations ten seconds each. These+are outer observation bounds; production VM deadlines and cleanup remain separate.+Responses are limited to 8 MiB each and retained evidence to 64 MiB per run.++The runner seals the allowance and pauses admission on exit, then requires zero+active requests and pending cleanup. This is not proof of cloud-resource removal;+the outer operator must independently inventory and delete the disposable resources.+Its receipt contains stage names, outcomes, durations, response status/size/hash+and verified engine identity. Credentials, source, download URLs and exceptions do+not enter the receipt. Raw synthetic responses remain private bounded evidence.++The local native fixture creates a fresh host for each request against the actual+Node engine and tenant/R2 adapter. It uses a synthetic view producer and directly+addresses private storage for downloads. Therefore it does not qualify real+software Vulkan output, browser authentication or Cloudflare VM behavior. The+separate gateway preflight covers real local gateway/token routing with synthetic+identities. The operator now runs that preflight before creating fresh grants for+the same two accounts and opening native admission. The combined local test stops+at the first native request because Miniflare has no attached VM. This proves its+expected failure/cleanup path, not the complete cloud lifecycle.++Adversarial replays of actual engine responses reject altered download bytes,+unverified manifest identity and leaked source/material data, including JSON-escaped+source inside error responses. Additional cases prove allowance concurrency,+one-use replay, oversized-body refusal and the actual ten-second evidence-write+deadline. Late evidence completion cannot resume an already failed sequence.++Live upstream OAuth, linking/deletion actions, real scheduled recovery, retention,+load, settled costs, alerts and public-client verification remain launch gates.++## Combined private topology and procedure++`lifecycle-config.mjs` derives the six production roles, preserving their code and+bindings except for the diagnostic allowance on the three native roles. The private+gateway omits provider secret bindings and Cron. A private allowance Worker stores+the one-use startup budget; a separate operator Worker owns the fixed sequence and+synthetic credentials. This removes the circular dependency created by putting the+allowance in the operator. A test requires every cross-Worker dependency to precede+its caller in deployment order:++`tenant -> allowance -> evaluation -> render -> request -> admission -> gateway -> operator`++All eight Workers disable public routes, workers.dev, preview URLs and persisted+logs/traces. Images retain production network/VM controls. The `.invalid` origin+exists only in service-bound requests. Both operator HTTP handlers return 404;+only a separate private service binding can call `runFixed`, `status` or `stop`.++The operator is one-use across concurrent calls, eviction and replay. Its 15-minute+alarm permanently closes the allowance and pauses admission. Unknown or non-idle+cleanup retains a one-minute recovery alarm. No alarm resets requests or permits+new starts. Status includes alarm/stop state. Control RPC results and promises are+explicitly disposed after copying their plain values. This corrected retained+capabilities found by the eviction test; replay preserves the closed allowance.+See [Cloudflare RPC lifetimes](https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/).++Prepare offline from a strict manifest with selected private resource IDs and+pinned image references:++```sh+node hosting/scripts/prepare-deployment.mjs --private-lifecycle --manifest <manifest.json> --output .cache/<fresh-candidate>+```++The manifest fixes prefix `kiln-private-lifecycle-v1`, private origin, one concurrent+request, fourteen daily/monthly admissions, a 120-second request deadline, 64 MiB+tenant storage, 256 objects and 64 groups. Edge/account limits are 600/120 per minute+for this test only; these are not adopted public quotas. The generator rejects+changed limits, public origins, unexpected fields and existing output directories.+It hashes eight bundles/configurations and nine account migrations. Tests reject+unknown helpers and identity-provider code in native bundles. Production preparation+retains its no-probe boundary. Synthetic-ID dry runs do not verify resource ownership.++The next approved cloud execution must follow this sequence:++1. Freeze a clean source commit with passing CI, verify both immutable image+ manifests and retain bundle/config hashes. Present the 22-start ceiling,+ deadlines, temporary resources and proposed spending allowance for approval.+ Previous trial allowances remain consumed.+2. Inventory the owner's account and prove the trial names absent. Create only+ disposable trial D1/KV/R2 resources, insert their returned IDs in the manifest+ and rebuild its receipt. Never bind production data.+3. Apply nine migrations and deploy in dependency order. Read back Worker versions,+ images, namespaces, bindings, disabled public surfaces and private storage.+ A CLI dry run cannot establish these properties.+4. Establish a fresh private observer binding to `KilnLifecycleControl`. Read status,+ invoke `runFixed` once, then observe that same run through any interruption.+ Do not reset names or invoke a replacement run.+5. Require the preflight, all native stages, exact image identity, closed allowance,+ paused admission, zero active/pending jobs and evidence hashes. Independently+ inspect actual image/GLB output; fidelity fields alone are not visual acceptance.+6. Invoke `stop` on failure or completion and retain receipts/synthetic evidence+ privately. Confirm all Container instances gone, then remove the temporary+ observer and Workers in reverse dependency order, followed by their disposable+ namespaces and D1/KV/R2 data/resources. Inventory again to verify absence.+ Preserve pre-existing registry images unless explicitly included in cleanup.++The local observer is `lifecycle-observer.ts`, with a dedicated+`lifecycle-observer.wrangler.jsonc`. After trial approval and verified deployment,+start it with the pinned Wrangler's `dev --config` command. Never deploy this+facade. Its configured listener is `http://127.0.0.1:8798`; only POSTs with+`X-Kiln-Operator: private-lifecycle-v1` to `/run-fixed`, `/status` and `/stop`+are accepted. Browser origin/fetch metadata, other hosts/ports, query parameters+and arbitrary controls are refused. This header is a browser-request guard, not+a credential protecting against other programs running as the local user.++It sends no RPC arguments, cancels uploaded bodies, returns `no-store` JSON,+limits receipts to 128 KiB and redacts RPC failures. Status/stop observations have+a ten-second deadline; the run observation allows sixteen minutes around the+operator's fifteen-minute terminal alarm. Observation failure is an unknown result,+not permission to repeat or replace the trial. Read the same run's durable status.+Both promise and result capabilities are released, including late results after+the observer deadline. The combined local topology/eviction tests now use this+actual facade; focused tests cover its guards, timeout, disposal and size limit.+Its config passes a Wrangler dry run. The approved October 7 trial used this local+facade; its listener and remote proxy were stopped after verified cloud cleanup.++`lifecycle-readback.mjs` verifies complete provider snapshots against the frozen+manifest and clean candidate receipt. It requires exact code hashes and active+versions, expected bindings and image digests, seven owned SQLite namespaces,+private bucket surfaces, all nine recorded migrations, disabled Worker/Container+logs and SSH, no routes/Cron, and no active/starting instances before admission.+Unexpected bindings, including secrets, fail verification. The collector must+retain complete pages and re-read them; synthetic fixtures are not cloud evidence.++For each Worker the collector also retains `scriptSettings`, the raw result of+[`GET .../workers/scripts/{name}/script-settings`](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/settings/methods/get/).+Cloudflare returned `observability: null` for the disabled configuration in the+October 7 private deployment. The CLI displayed inactive nested defaults such as+`persist: true`; those defaults did not mean logs were enabled. The verifier accepts+that representation only with explicit raw null evidence, disabled master/log/trace+flags, disabled Logpush, and no tail consumers or log/trace destinations. Missing+raw evidence and contradictory active settings fail. Non-null settings retain the+strict redaction, invocation-log and persistence checks. Omitted empty binding/export+collections are compared against the candidate's empty collections; required entries+cannot be omitted. When present, D1's `database_id` alias must equal the expected ID.++Its cleanup planner requires a stopped operator, closed allowance, paused idle+admission, no recovery alarm and only stopped, correctly imaged VMs matched to+recorded budget claims. Failed starts may consume a claim without producing a VM;+failed qualification does not prevent cleanup once those safety conditions hold.+The resulting plan selects only recorded trial resources, with Workers in reverse+dependency order. Re-read resource IDs/versions immediately before deleting,+retain bounded synthetic evidence, and verify absence afterward. A partial+teardown failure needs inspection of its mutation receipts and current identities;+never rerun the compute trial or force-delete unrelated references to recover.++Deleting the private Workers/D1/KV/R2 resources is separate from erasing+provider-managed operational data. The configured Analytics Engine dataset emits+fixed, sanitized metrics, and Cloudflare documents **three months** of retention.+The cleanup plan preserves registry images and explicitly does not assert that+metrics were deleted. See [Analytics Engine limits](https://developers.cloudflare.com/analytics/analytics-engine/limits/).++The linked October 7 result records concrete cloud and cleanup evidence for that+candidate. This reusable procedure itself does not authorize another deployment.+Real alarm firing, upstream sign-in, account actions, retention, monitoring and+production load remain separate qualification requirements.diff --git a/hosting/probe/QUALIFICATION.md b/hosting/probe/QUALIFICATION.mdnew file mode 100644index 00000000..b3095be2--- /dev/null+++ b/hosting/probe/QUALIFICATION.md@@ -0,0 +1,85 @@+# Manifest-based native qualification++Completed with owner approval on 6 October. All four jobs passed; this allowance+is now consumed and all temporary resources were removed. The original five-job allowance and+the separately approved one-job manifest comparison are consumed. Do not recreate+their namespaces or reset their claims. The approved scope was up to four new,+sequential jobs with a separate $1 trial allowance, stopping on the first failure.+The allowance is a planning bound, not a provider-enforced billing cap.++`qualification.wrangler.jsonc` uses the proven original runtime manifest+`sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8`+and the existing fixed `worker.ts` controller. No image rebuild, dependency+installation, user change or runtime-code change is part of this candidate.+Keep the private operator local and bind it to `KilnProbeControl`; do not publish+any HTTP route, domain, preview URL or automatic trigger.++The four cases, enforced by `runProbeOnce`, are:++1. Evaluate the installed public RC's fixed box program and require the same+ 1,912-byte GLB SHA-256 as the independent local and Linux CI fixtures.+2. Probe direct TCP/DNS from native Node outside the JavaScript sandbox. Public+ Internet, metadata and renderer endpoints must remain inaccessible.+3. Write a temporary marker and start a live detached child in one fresh VM,+ then destroy the whole VM.+4. In a different fresh VM, verify neither the marker nor the child exists.++Every job uses the production `ContainerEvaluationJob` controller: immutable image+selection, numeric UID/GID `1000:1000`, disabled Internet, standard-2, 60-second+deadline, durable alarm and five-second whole-instance destruction budget. The+probe additionally inspects the stopped state before accepting each result.+Bound output; retain fixed metadata and digest only, never raw native diagnostics.+The coordinator persists its one-use claim before any execution and stops after+a failed result. An interrupted or repeated trigger cannot restart the batch.++Before invocation, verify exact CI source, bundle SHA-256, deployed image map,+private bindings and absence of public URLs. Publish only the existing platform+manifest, then inspect its digest/config/layers. Wrangler must report image+preparation ready. After execution, retain results, verify stopped instances and+remove the exact application, Worker, namespaces and registry tag with readbacks.+Do not rerun a failed or interrupted batch under this allowance.++Four fully busy 65-second standard-2 jobs would cost approximately $0.0093 for+Container CPU/memory/disk before allowances at the researched rates; registry and+Worker/DO charges are additional. This is not a settled invoice or a load estimate.++Passing these checks would qualify basic engine execution and the tested provider+boundaries only. CPU preview/software rendering, adversarial resource exhaustion,+cancellation/alarm recovery, authenticated MCP, account controls, persistence,+capacity and production launch remain separate gates.++Local qualification passes 134 hosted tests, all three typechecks, five production+bundle-boundary builds and root lint. The private configuration check first failed+with the missing candidate, then passed after its addition. Pinned Wrangler+4.147.0 dry-run deployment passes. Actual JavaScript and source-map secret scanning+reports no matches across 43.09 KB. The Worker JavaScript SHA-256 is+`0e97f19c8617d20f1bc96880aaa95b9e9303e45b560c7f242f7e19146527fede`.+Exact-commit Linux/Windows CI passed as recorded below. Runtime source is unchanged from+the existing probe; this preparation changes configuration, tests and records only.++## Approved provider execution++Both CI platforms passed source `8590c0abfcaedbfa8a34dfd76ac3322f01c0fb55`+in [run 37522530858](https://github.com/instruktlabs/kiln/actions/runs/37522530858).+The owner then approved this four-job batch and its $1 allowance. Invocation began+at 20:04:01 UTC after exact remote manifest/config/layer and uploaded Worker checks.+Worker/version metadata showed no public routes, URLs, external bindings or cron.++| Case | Result | Elapsed including cleanup |+| --- | --- | --- |+| Installed engine box | Passed; 1,912-byte GLB SHA-256 `f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40` | 3,398 ms |+| Native TCP/DNS checks | Passed; tested endpoints were inaccessible | 15,320 ms |+| Marker and detached child | Passed; child confirmed alive before whole-VM destruction | 1,260 ms |+| Fresh VM | Passed; neither marker nor matching child present | 1,283 ms |++Every result verified stopped state. Cloudflare's instance readback independently+reported all four stopped with exit code zero. Repeating the private RPC returned+the exact saved batch without new executions. These elapsed values are not billed+CPU measurements, capacity estimates or representative cold-start percentiles.++The application, Worker, both namespaces and registry tag were removed; subsequent+readbacks verified absence. The loopback operator stopped and temporary registry+authentication was removed. Receipts are under the diagnostic worktree's+`.cache/manifest-qualification-trial/`. All ten jobs across the three separately+approved scopes are consumed. No stable package or public service was published.+Further tests need a prepared, reviewed scope and new authorization.diff --git a/hosting/probe/README.md b/hosting/probe/README.mdnew file mode 100644index 00000000..36bf68e6--- /dev/null+++ b/hosting/probe/README.md@@ -0,0 +1,141 @@+# Private Cloudflare availability probe++**Current status:** the original five-job allowance is exhausted. A separately+approved sixth startup-only comparison passed when selecting the original image's+Linux/AMD64 manifest directly. All trial resources were removed. See+[the manifest result](MANIFEST_STARTUP.md) and the separately prepared+[four-job qualification result](QUALIFICATION.md), which also passed all four cases+and completed cleanup. All ten approved jobs are consumed. Neither the historical+allowances below nor the old prebuilt receipt authorize another deployment.++## Historical first trial++This is a disposable operator probe, separate from every production bundle and+the npm package. The owner approved a five-job trial with a $1 allowance. Its+first job failed and all cloud trial resources were removed. The current candidate+continues with only the four remaining jobs; it does not reset that allowance.+The first stage answers whether the account can run the selected native image and+whether basic network/filesystem/whole-VM cleanup checks work. It does not qualify+the hosted service for launch.++**Current stop condition:** the direct-RPC continuation at `cfbcb2a` has now+attempted another job and failed during native startup. All cloud resources were+removed and absence was verified. Subsequent smaller controls in+[STARTUP.md](STARTUP.md) and [CUSTOM_STARTUP.md](CUSTOM_STARTUP.md) both passed.+The unchanged image control in [KILN_STARTUP.md](KILN_STARTUP.md) then failed+before its fixed Node command. Five jobs total have now been attempted; none remain.+Do not redeploy this four-case candidate to a new coordinator. Prepare a revised+diagnostic within the remaining scope, or obtain approval for a changed trial.+The details below retain the reviewed four-case candidate for reproducibility.++## Exact scope++- Worker `kiln-private-evaluation-probe`, with no custom domain, route, workers.dev+ URL or version preview URL. Its HTTP handler always returns 404.+- One SQLite coordinator namespace and one container-backed job namespace in the+ same Worker; no external service, credential, storage or identity bindings.+- Container application `kiln-private-evaluation-probe-jobs`, using Cloudflare's+ `durable_object` scheduling policy, SSH disabled, no snapshots, and no container+ log collection. The controller starts each image with internet disabled.+- Four remaining fixed jobs, sequentially: one installed-engine box fixture, direct native+ TCP/DNS reachability checks, a file plus live detached child, and a fresh VM+ checking that neither marker nor child is visible. The native checks bypass the+ JavaScript sandbox deliberately so they test the provider boundary.+- Each job uses the production controller's 60-second deadline, durable alarm,+ output bounds, immutable image check and awaited whole-VM destruction. The+ probe stops at the first failure. No user may supply source or a command.+- The `KilnProbeControl` named service entrypoint invokes only the fixed+ `availability-rc1` coordinator through `runFixed()`. An authenticated development+ service binding reaches it without a public URL. Both default and named HTTP+ handlers return 404. The prepared deployment has no cron. A durable transaction+ claims the entire run once; concurrent, later and interrupted calls cannot+ silently start another batch. Later calls only report retained state.+- Read fixed result metadata through authenticated Workers logs. Never log source,+ arbitrary native output, identity records or credentials. Remove the+ Worker, probe namespaces and container application after retaining receipts;+ remove the trial registry image once it is no longer needed. Do not remove any+ existing application or resource.++The four-job continuation is enforced in application state: the new scheduling policy+does not support `max_instances`. There is no public invocation path. A controller+failure requires investigation, not an automatic new run ID or a budget reset.+Together with the first attempted job, this uses at most the original five jobs.+One successful provider GLB can be compared with the two local/CI fixtures; it+would not establish repeatability across two provider executions.++## First attempt and scoped correction++At source `ea08a16`, the live Worker matched SHA-256+`6babbbb9073fbb4514b03675d73ee1387f30099cd6174cfca7ac8bc6515cc2e0` and the+registry returned the exact local image digest below. The first `engine-a` job+failed after 2,048 ms with `WORKER_FAILED` and a provider internal error. The+controller destroyed the VM, the coordinator stopped, and the other four jobs+did not run. Application/instance queries showed no running instances. The+operator then deleted the exact trial application, Worker, both namespaces and+registry image and verified their absence. This is failure and cleanup evidence,+not successful native evaluation or a settled billing total.++Cloudflare's current native API documentation says `exec` rejects user/group+names. The image uses `node`, verified locally as numeric `1000:1000`. The+continuation explicitly selects that numeric identity without changing the image+or isolation settings. A regression test failed before this correction and+passes afterward. This is a plausible explanation for the internal error, still+requiring a live check. Operator-only diagnostics now retain the first failed+API method name, never exception text or native output.++The corrected scheduled deployment and a separate private trigger produced no+observed invocation after their documented propagation windows. Both were removed,+along with the application, namespaces and registry image; no additional job was+observed. The next continuation uses the documented remote service-binding route+above with the same remaining allowance. Local workerd verifies its HTTP denial,+fixed run and retained result. This does not establish a successful provider run.++## Local image and preparation++The local image is `kiln-evaluation:rc1-local`, Linux amd64, immutable ID+`sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a`.+Its four-file context uses the approved public RC archive with SHA-256+`f2de7eb69f6e16dd618c77249b1f46eda1b5d032789f5b0d9048b2b2a08ea8c2`.+Two local fresh-container evaluations passed with identical 1,912-byte GLBs,+matching the independently built Linux CI fixture. Receipts and resolved dependency+inventory are retained under `.cache/evaluation-image-local-evidence/`.++`scripts/build-provider-probe.mjs` bundles the reviewed source, validates its+private configuration with pinned `@cloudflare/[email protected]`, and prepares Build+Output for `[email protected]`. It never uploads or deploys. Pass `--cf-package`,+`--account`, `--image` (managed-registry digest reference) and `--output` explicitly.+From that output directory, `cf deploy --prebuilt --dry-run` must succeed before+deployment. Do not rebuild or substitute an image after approval: verify the local+image ID, use `cf containers push --tag kiln-evaluation:rc1-local`, and bind only+the returned digest for those verified bytes. Retain the Worker bundle hash and+final registry digest alongside the deployment/version/application IDs.++The probe uses documented `ctx.exports` loopback namespaces. This also avoids a+cf beta.12 dry-run validation problem: explicit same-Worker bindings are converted+to `script_name`, which the container validator rejects as a foreign Worker.+No CLI internals or production isolation controls were patched. Local workerd+verified loopback calls, absent-container refusal, retained failure and HTTP denial.++## Cost and remaining gates++At the documented rates on 6 October, five jobs occupying `standard-2` (1 vCPU,+6 GiB memory, 12 GB disk) for 65 seconds each cost roughly **$0.012** in metered+container CPU, memory and disk before included allowances. This deliberately+assumes a fully busy CPU throughout. Worker/DO/log charges are additional and tiny+at this volume; existing applications share included usage. Reserve **up to $1**+for this bounded trial, including image/storage overhead. This is an estimate, not+a provider-enforced dollar cap. Keep the operator present, inspect unexpectedly+running instances, and stop the trial on failure. Existing Workers Paid is reused.++Subsequent qualification still requires CPU preview rendering, software Vulkan,+memory exhaustion, output floods, infinite-loop and cancellation races, alarm+recovery after controller interruption, cold-start/cost measurements and actual+authenticated MCP plus storage integration. Passing this availability stage does+not remove those launch gates.++Sources: [native container API](https://developers.cloudflare.com/containers/api/durable-object-container/),+[scheduling policy](https://developers.cloudflare.com/containers/configuration/scheduling-policy/),+[pricing](https://developers.cloudflare.com/containers/platform/pricing/),+[loopback bindings](https://developers.cloudflare.com/workers/runtime-apis/context/#exports),+[remote service bindings](https://developers.cloudflare.com/workers/local-development/#using-remote-resources-with-durable-objects-and-workflows),+[cf prebuilt deployment](https://developers.cloudflare.com/cf/projects/#deploy-a-prebuilt-build).diff --git a/hosting/probe/RESILIENCE.md b/hosting/probe/RESILIENCE.mdnew file mode 100644index 00000000..17233c4f--- /dev/null+++ b/hosting/probe/RESILIENCE.md@@ -0,0 +1,164 @@+# Stable native rendering and recovery qualification++Prepared and executed on 6 October 2026. **All twelve approved Cloudflare cases+passed; trial resources were removed and absence verified.** The owner approved+source `d068a7c` and a separate $1 allowance after both CI platforms passed.+All 22 jobs across the four authorized scopes are now consumed. The batch stopped+after its fixed cases and cannot reset or repeat its claim.+The allowance is a planning bound, not a Cloudflare-enforced invoice cap.++## Exact candidate++`resilience.wrangler.jsonc` pins the independently built Linux/AMD64 software image+`sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99`.+Its image configuration is+`sha256:9c369c15226828815e0ebdb15cdc2091eb426fb42aa016f1556c8723307cddf3`.+It contains the now-public stable package whose archive SHA-256 is+`6ed3d6b9964429f14c3c6a0a6a13d56be509dd0f40b07061a37d491f901c1508`.+The package lock audit reported zero known findings. The separate software image+adds Mesa Vulkan/llvmpipe to the CPU image; it contains no probe scripts, provider+credentials, user assets or listening application server.++Pinned Wrangler 4.147.0 dry-run compilation produces a 30.68 KiB Worker with SHA-256+`5d4021d4bbdc4920ccffe1eb34f93cd64f6d9752e73e19ffff75bede9ad594b8`.+Gitleaks finds no matches in the probe source or actual Worker/source-map output.+Production bundle checks exclude all probe and test imports.++## Bounded provider work++Each job uses a fresh `standard-2` instance and the production+`ContainerEvaluationJob` controller: immutable image, numeric UID/GID `1000:1000`,+Internet disabled, bounded input/output, durable watchdog, whole-instance+destruction and stopped-state confirmation. Only the following fixed programs+can run through the private `runFixed` service RPC:++| Order | Case | Required evidence |+| --- | --- | --- |+| 1 | CPU preview | Actual stable evaluation and 128px CPU PNG matching the independent local digest |+| 2 | Software views | Software Vulkan adapter; six 128px textured views across neutral/dark/light; retained PNGs, hashes and colour counts |+| 3 | Native networking | Direct TCP/DNS outside Node vm cannot reach the tested Internet, metadata or renderer endpoints |+| 4 | Marker and child | Write a temporary marker and establish a detached child is alive before destroying the VM |+| 5 | Fresh VM | Neither marker nor child from the previous VM exists |+| 6 | Native deadline | A native parent/child busy loop reaches readiness; the host deadline destroys the VM |+| 7 | Native cancellation | Cancel 250ms after native readiness; destroy the whole VM and return the cancellation outcome |+| 8 | stdout flood | Native readiness followed by output exhaustion trips the 1KiB stdout bound and destroys the VM |+| 9 | stderr flood | Native readiness followed by output exhaustion trips the 16KiB stderr bound and destroys the VM |+| 10 | Memory exhaustion | A child allocates beyond the VM allowance; SIGKILL and a positive kernel OOM counter delta are required |+| 11 | Durable recovery | Inject one controller destruction failure; the real Durable Object alarm must subsequently confirm whole-VM destruction |+| 12 | Engine afterward | A fresh VM executes the actual stable image entry and returns the expected 1,912-byte GLB digest |++Native deadline and recovery jobs have 15-second deadlines; the others have+60-second deadlines. Destruction/readback has a shared five-second bound. Native+deadline evidence requires readiness at least one second before the deadline, so+a startup failure cannot pass as an execution timeout. Recovery is observed from+a different Durable Object for at most 45 seconds; the observer never calls the+alarm handler itself. Operator cleanup after a missing alarm remains a failed+result, even if a later callback succeeds.++stdout is limited to 64KiB except the explicit flood case and software views.+The six-image response is bounded at 512KiB; local measurement is 274,255 bytes.+PNG signatures, structure, CRCs, dimensions and digests are validated outside the+VM. Downloaded images must also be decoded and inspected before accepting the+cloud rendering result; these are fixed material fixtures, not comprehensive+visual-quality acceptance. SQLite-backed DO storage permits a combined key/value+up to 2MB, above this bounded receipt+([Cloudflare limits](https://developers.cloudflare.com/durable-objects/platform/limits/)).++The coordinator persists its claim before execution, retains each result, runs+sequentially and stops at the first failed case. Retries return the saved record;+interrupted claims cannot silently restart. HTTP handlers always return 404;+there are no routes, workers.dev/preview URLs, cron triggers or identity bindings.+Native stdout/stderr logging is disabled. No arbitrary user source or external+model call is accepted. A loopback-only operator receives the private service RPC.++At current [Container rates](https://developers.cloudflare.com/containers/platform/pricing/),+twelve fully busy 65-second standard-2 jobs model approximately $0.028 for CPU,+allocated memory and disk before included allowances. Worker/DO, registry and+other charges are additional. This is a conservative short-trial calculation,+not a settled invoice or production capacity measurement.++## Local evidence and execution procedure++The focused tests first failed for missing private configuration and acceptance+of truncated PNGs, then passed after the fixes. All 148 hosted tests, all three+hosted typechecks, five production bundle checks, root typecheck and lint pass.+Real workerd RPC tests deny public HTTP execution, fail closed without native+compute and retain the one-use fixed batch across retries.++All twelve fixed programs were exercised in restricted local Docker containers.+The six material views and CPU preview decoded successfully; one material view+was visually inspected. The software fixture initially truncated stdout at 64KiB;+it now waits for the output stream to flush. The memory fixture observed one+cgroup OOM kill with a 512MiB local cap. Busy-loop/flood checks prove those fixtures+run and can be stopped locally, not that Cloudflare's deadlines or alarm recovery+work. All local containers were removed and absence verified. Local receipts are+under `.cache/resilience-local/`; the untracked local runner is+`.cache/qualify-resilience-local.mjs`.++Before requesting cloud approval, require exact-source Linux/Windows hosted CI.+After approval, upload only the immutable runtime manifest and verify remote+digest/config/layers. Verify the deployed Worker bundle/image identity and absence+of public routes/triggers. Trigger once through the private operator and retain+the results. Verify all instances stopped, including any failed case. Replaying+the RPC must return the retained record without new jobs. Remove the exact trial+application, Worker, namespaces and registry tag with absence readbacks; stop the+operator and remove its temporary registry login. Do not restart a failed batch+or recreate its namespaces under this allowance.++Passing this trial would qualify these native/rendering/failure paths only.+Authenticated MCP routing, account controls, private artifact lifecycle, global+admission, load/cost measurement, production deployment and directory submissions+remain separate launch work.++## Approved Cloudflare result++Exact-source Linux/Windows hosted CI passed in+[run 37529896878](https://github.com/instruktlabs/kiln/actions/runs/37529896878).+The owner then approved all twelve jobs. The remote registry manifest, config and+layers matched the local image. `[email protected] deploy --prebuilt` deployed the+exact compiled Worker; downloaded JavaScript matched the digest above. Version+`af273169-3a66-4350-b7d8-6dede08f1bf2` and deployment+`11289978-acde-4f2d-8036-02cd5c30197e` had no public route, URL, cron or external+binding. The Container application disabled SSH and native logs. The loopback+operator used Wrangler 4.147.0's remote service binding.++| Case | Result | Elapsed including cleanup |+| --- | --- | --- |+| CPU preview | Passed; expected PNG digest | 13,583 ms |+| Six software views | Passed; all PNGs retained and independently decoded | 13,286 ms |+| Native network denial | Passed for the fixed TCP/DNS targets | 14,913 ms |+| Marker and detached child | Passed; child alive before VM destruction | 7,644 ms |+| Fresh VM | Passed; no prior marker or child | 1,102 ms |+| Native deadline | Passed; ready at 929 ms, then deadline outcome | 15,101 ms |+| Native cancellation | Passed; ready at 1,043 ms, then cancellation | 1,375 ms |+| stdout flood | Passed; readiness and output-limit outcome | 963 ms |+| stderr flood | Passed; readiness and output-limit outcome | 880 ms |+| Memory exhaustion | Passed; child SIGKILL and one `/proc/vmstat` OOM kill | 15,412 ms |+| Real alarm recovery | Passed; native ready at 950 ms and `ALARM_RECOVERED` | 15,079 ms |+| Engine afterward | Passed; expected 1,912-byte GLB digest | 2,194 ms |++All results confirmed whole-instance destruction. The provider API separately+reported twelve stopped instances, with no active ones. The private RPC replay+matched the retained result without starting another batch. These elapsed values+are functional trial observations, not billed CPU, representative cold-start+percentiles, throughput or a production cost forecast.++All seven downloaded 128px PNGs passed an independent Windows pngjs decode, digest+and colour-count check. Every image matched its local reference byte for byte.+Visual inspection showed the matte cube, red/green textured cube and blue metallic+sphere, both camera angles and all three backdrops. These small fixed fixtures+qualify this software-rendering path, not comprehensive asset quality or capacity.++The loopback operator stopped. Application `64098a73380d4e51b49fe937c6ccb99f`, Worker+`3d13aa984bcb4b3dafb2de79288950a1`, both trial namespaces and the+`kiln-evaluation:stable-resilience-control` registry tag were deleted. Follow-up+reads verified absence. The temporary registry login was removed. Receipts,+decoded images, immutable deployment metadata and cleanup readbacks are under+the diagnostic worktree's `.cache/resilience-trial/`. No settled invoice is claimed.++The original image-format and restricted nested-namespace failures remain in the+earlier records. This result establishes the listed native VM paths and removes+those specific qualification gaps. It does not turn the local Node MCP host into+a deployed service: authenticated dispatch, production render adapters, private+artifact lifecycle, account controls, admission/load/operations and end-to-end+launch checks still require implementation or deployment evidence.diff --git a/hosting/probe/STARTUP.md b/hosting/probe/STARTUP.mdnew file mode 100644index 00000000..086a0b07--- /dev/null+++ b/hosting/probe/STARTUP.md@@ -0,0 +1,109 @@+# Managed-image startup control++This private diagnostic isolates basic Cloudflare Container startup from Kiln,+custom image preparation and the previous cf Build Output configuration. It uses+Wrangler 4.147.0 with ordinary explicit Durable Object and service bindings.+It is not a production evaluator and accepts no source, image, command or run ID.++The owner authorized a five-job private trial with a $1 allowance. Two jobs had+already been attempted before this candidate. This candidate has now consumed+**one additional job**, leaving two for subsequent controls. Do not rerun this+completed control, delete/recreate the namespace,+change the fixed job ID, or redeploy a copy to regain an invocation. Even an+interrupted or failed invocation keeps its durable claim. Cleanup alarms do not+start another instance. This control does not reset or expand the allowance.++## Fixed scope++- Worker `kiln-private-startup-diagnostic`, application+ `kiln-private-managed-startup`, one SQLite Durable Object namespace.+- No public route, domain, workers.dev or version preview URL. Both HTTP handlers+ return 404. A private service binding invokes `KilnStartupControl.runFixed()`.+- `cloudflare/debian-trixie`, `standard-2`, Internet disabled, no snapshots,+ provider secrets, storage bindings, custom image upload or installed Kiln package.+- A fixed Node command returns only its version and numeric UID/GID. The managed+ image currently supplies Node 24.20.0; a different version fails this control.+ It does not change Kiln's pinned Node 22.23.3 release runtime.+- One 60-second deadline with a durable alarm, 1-KiB bounds on each output stream,+ five-second awaited destruction/inspection, and a cleanup recovery alarm if+ destruction cannot be confirmed. No arbitrary process output or exception text+ is retained. A process failure and a teardown failure have separate phase marks.++At the rates checked on 6 October, 65 seconds of fully busy `standard-2` usage is+approximately $0.00233 in Container CPU/memory/disk before included allowances.+Worker/DO/log charges are additional. Keep the existing $1 trial allowance and+read back resource absence after cleanup; this estimate is not a provider-enforced+dollar cap or an actual invoice.++## Preparation and evidence++Run the hosting checks from `hosting/` after the root install/runtime rebuild+required by `hosting/AGENTS.md`. `startup-diagnostic.test.mjs` covers fixed offline+execution, one-use admission, HTTP denial, structured private RPC, phase attribution,+failed startup, bounded output/deadlines and cleanup/recovery. Its workerd fixture+has no real Container; it proves fail-closed behavior, not provider availability.++Prepare with pinned Wrangler, using an absolute output directory inside ignored+root `.cache/`:++```powershell+fnm exec --using 22.23.3 npm.cmd exec --yes [email protected] -- wrangler deploy --config hosting/probe/startup.wrangler.jsonc --dry-run --outdir <ABSOLUTE_IGNORED_DIRECTORY>+```++Before live execution, retain the exact commit, final bundle SHA-256, validated+configuration, deployment/version/application/namespace IDs and start timestamp.+Inspect the uploaded code and public URL flags. Invoke the fixed RPC once through+a loopback-only local operator that rejects browser-origin requests. A second+read returns the retained result; it must never cause another start. Stop after+failure and inspect the phase trace before preparing another image or policy.++After retaining the result, stop the local operator, delete only this diagnostic's+application and Worker, and verify its instance and namespace absence. There is+no custom registry image to delete for this control. A successful command proves+basic managed-image execution only. It does not prove custom image execution,+Kiln evaluation, hostile-source isolation or a launch-ready service.++An expired `CLOUDFLARE_API_TOKEN` environment override was found during preparation.+Removing that override in the command process allowed both CLIs to use the owner's+valid saved OAuth sessions. Never print or copy credentials, clear saved profiles,+or request another login merely because that override has expired.++Sources: [native API](https://developers.cloudflare.com/containers/api/durable-object-container/),+[managed image](https://developers.cloudflare.com/containers/guides/image-management/),+[Wrangler configuration](https://developers.cloudflare.com/containers/reference/wrangler-configuration/),+[pricing](https://developers.cloudflare.com/containers/platform/pricing/).++## Completed private control++On 6 October 2026 at 18:46:20 UTC, source `c6b119b4a6358d51c27406f6fb3e74cafd289782`+passed the deployed managed-image control. The uploaded JavaScript SHA-256 was+`ddcc444cf904223eb63f5f8d2a673422c35e1e34076ae4ea2a6d13c6b59b741e`; its bytes were+read back and matched before invocation. Both public URL flags were disabled,+the version advertised no URLs, and its only binding was its own job namespace.++The command returned Node `v24.20.0` and managed-image identity `0:0`. Output+completed after 470 ms and awaited destruction/inspection completed after 573 ms.+These are one control's elapsed timings, not billed CPU measurements or Kiln+performance. The instance API separately reported `stopped`, exit code zero.+Replaying the fixed RPC returned the exact retained record without another start.++The local operator initially rejected even an empty POST because workerd provided+an empty body stream. This was a local guard failure before RPC, not a cloud job.+The operator was corrected to reject any nonempty stream; its GET, Origin and body+denial checks passed before the successful invocation.++The local operator was stopped and the exact diagnostic application and Worker+were removed. Follow-up reads confirmed application/namespace absence and a 404+for the Worker. Receipts are retained in the diagnostic worktree under ignored+`.cache/startup-managed-trial/`. No custom registry image was created.++The exact source passes 3,290 engine tests (two platform skips), root typecheck+and lint, 126 hosted tests, hosted typechecks/builds and redacted source/bundle+secret scans. Linux and Windows hosted CI both pass in+[run 37513405377](https://github.com/instruktlabs/kiln/actions/runs/37513405377).++This establishes managed-image execution on the account through the documented+configuration. The remaining custom-image and Kiln integration controls must be+prepared separately; this does not qualify hostile user code, software rendering,+authentication, production hosting or settled costs. No new support message was+sent. The total is now three attempted jobs out of five, with two remaining.diff --git a/hosting/probe/custom-startup-worker.ts b/hosting/probe/custom-startup-worker.tsnew file mode 100644index 00000000..646131fd--- /dev/null+++ b/hosting/probe/custom-startup-worker.ts@@ -0,0 +1,32 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ManagedStartupDiagnostic } from './startup-diagnostic';++interface Bindings {+ STARTUP_JOB: DurableObjectNamespace<KilnCustomStartupJob>;+}++export class KilnCustomStartupJob extends DurableObject {+ async runFixed() {+ return new ManagedStartupDiagnostic(this.ctx, 'configured').run();+ }++ async alarm() {+ await new ManagedStartupDiagnostic(this.ctx, 'configured').alarm();+ }+}++export class KilnCustomStartupControl extends WorkerEntrypoint<Bindings> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }++ async runFixed() {+ return this.env.STARTUP_JOB.getByName('custom-runtime-2026-10-06').runFixed();+ }+}++export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler<Bindings>;diff --git a/hosting/probe/custom-startup.wrangler.jsonc b/hosting/probe/custom-startup.wrangler.jsoncnew file mode 100644index 00000000..750fab14--- /dev/null+++ b/hosting/probe/custom-startup.wrangler.jsonc@@ -0,0 +1,35 @@+{+ "name": "kiln-private-custom-startup",+ "main": "./custom-startup-worker.ts",+ "compatibility_date": "2026-10-06",+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": { "cpu_ms": 30000, "subrequests": 50 },+ "observability": {+ "enabled": true,+ "logs": { "enabled": true, "invocation_logs": true }+ },+ "containers": [+ {+ "name": "kiln-private-custom-startup",+ "class_name": "KilnCustomStartupJob",+ "scheduling_policy": "durable_object",+ "images": {+ "control": {+ "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-startup-control@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b8d2c669eb5a0b7c07e600"+ }+ },+ "observability": { "logs": { "enabled": false } }+ }+ ],+ "durable_objects": {+ "bindings": [+ { "name": "STARTUP_JOB", "class_name": "KilnCustomStartupJob" }+ ]+ },+ "exports": {+ "KilnCustomStartupControl": { "type": "worker" },+ "KilnCustomStartupJob": { "type": "durable-object", "storage": "sqlite" }+ }+}diff --git a/hosting/probe/fixtures.ts b/hosting/probe/fixtures.tsnew file mode 100644index 00000000..83496e4e--- /dev/null+++ b/hosting/probe/fixtures.ts@@ -0,0 +1,53 @@+// Fixed provider-qualification programs only. Never imported by production hosts.+export const engineRequest = new TextEncoder().encode(+ JSON.stringify({+ version: 'kiln.evaluator.request.v2',+ requestId: 'image-fixture',+ operation: 'execute-export-glb',+ code: 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',+ options: {},+ limits: { maxGlbBytes: 2097152 },+ }),+);++export const glbDigest = 'f94d231ed3eb4843a03704872adc3f20b00c2ea24567cb5916407b40a2cf1d40';++// The controller remains outside the VM. These deliberately bypass Node vm so+// network/filesystem checks exercise the provider boundary, not the JS sandbox.+const prefix = 'import fs from "node:fs";fs.readFileSync(0);';+const finish = 'fs.writeSync(1,JSON.stringify({ok:true}));process.exit(0);';+export const nativeFixtures: Record<string, string> = {+ network: `${prefix}+ const {connect}=await import('node:net');+ const {lookup}=await import('node:dns/promises');+ const targets=[['1.1.1.1',443],['169.254.169.254',80],['127.0.0.1',8000]];+ for(const [host,port] of targets){+ const connected=await new Promise(resolve=>{+ const socket=connect({host,port});+ const finish=value=>{socket.destroy();resolve(value);};+ socket.setTimeout(2000,()=>finish(false));+ socket.once('error',()=>finish(false));socket.once('connect',()=>finish(true));+ });+ if(connected)throw new Error('unexpected network access');+ }+ const resolved=await Promise.race([lookup('example.com').then(()=>true,()=>false),new Promise(resolve=>setTimeout(()=>resolve(false),2500))]);+ if(resolved)throw new Error('unexpected DNS resolution');+ ${finish}`,+ 'write-marker': `${prefix}+ if(fs.existsSync('/tmp/kiln-qualification-marker'))throw new Error('unexpected old file');+ fs.writeFileSync('/tmp/kiln-qualification-marker','qualification-only');+ const {spawn}=await import('node:child_process');+ const child=spawn(process.execPath,['-e','process.title="kiln-qualification-child";setInterval(()=>{},1000)'],{detached:true,stdio:'ignore',env:{},cwd:'/tmp'});+ child.unref();+ await new Promise(resolve=>setTimeout(resolve,100));+ if(!Number.isSafeInteger(child.pid))throw new Error('child did not start');+ process.kill(child.pid,0);+ ${finish}`,+ 'read-marker': `${prefix}+ if(fs.existsSync('/tmp/kiln-qualification-marker'))throw new Error('cross-job file');+ for(const pid of fs.readdirSync('/proc').filter(name=>/^\\d+$/.test(name)&&name!==String(process.pid))){+ let command='';try{command=fs.readFileSync('/proc/'+pid+'/cmdline','utf8');}catch{}+ if(command.includes('kiln-qualification-child'))throw new Error('cross-job child');+ }+ ${finish}`,+};diff --git a/hosting/probe/gateway-preflight.ts b/hosting/probe/gateway-preflight.tsnew file mode 100644index 00000000..18a731f3--- /dev/null+++ b/hosting/probe/gateway-preflight.ts@@ -0,0 +1,280 @@+import type { KilnCompute, KilnComputeControl } from '../src/admission-worker';+import { D1BrowserSessions } from '../src/browser-sessions';+import { D1Connections } from '../src/connections';+import { tenantForAccount } from '../src/tenant-identity';+import { readBounded } from '../src/http';+import { qualificationControl } from './qualification-rpc';+import {+ assertQualification,+ privateJson,+ qualificationOrigin,+ syntheticAccount,+ type QualificationAccountsEnv,+} from './qualification-accounts';++export interface PreflightEnv extends QualificationAccountsEnv {+ TENANTS: DurableObjectNamespace;+ ARTIFACTS: R2Bucket;+ COMPUTE: Service<KilnCompute>;+ CONTROL: Service<KilnComputeControl>;+}+interface PreflightReceipt {+ state: 'running' | 'finished';+ passed: boolean;+ computePaused: boolean;+ results: { name: string; passed: boolean }[];+}+const check = (value: unknown) => {+ if (!value) throw new Error('PRIVATE_PREFLIGHT_CHECK');+};+const source = 'function build(){return createRoot("Private gateway fixture");}';+const bytes = new TextEncoder().encode(source);+const hex = (buffer: ArrayBuffer) =>+ Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, '0')).join('');+async function discard(response: Response, expected: number) {+ const status = response.status;+ await response.body?.cancel();+ check(status === expected);+}++/** One-use, no-VM stage for the next private full-stack trial. Synthetic identity+ * creation and direct storage seeding are intentionally not evidence of live login+ * or engine save. Native admission stays paused throughout and after this stage.+ */+export async function runGatewayPreflight(+ storage: DurableObjectStorage,+ env: PreflightEnv,+): Promise<PreflightReceipt> {+ const record: PreflightReceipt = {+ state: 'running',+ passed: false,+ computePaused: false,+ results: [],+ };+ const claimed = await storage.transaction(async (tx) => {+ if (await tx.get('gateway-preflight')) return false;+ await tx.put('gateway-preflight', record);+ return true;+ });+ if (!claimed) return (await storage.get<PreflightReceipt>('gateway-preflight'))!;+ let touchedCompute = false;+ const step = async (name: string, action: () => Promise<void>) => {+ const result = { name, passed: false };+ record.results.push(result);+ try {+ await action();+ result.passed = true;+ } finally {+ await storage.put('gateway-preflight', record);+ }+ };+ const send = (path: string, init?: RequestInit) =>+ env.GATEWAY.fetch(new Request(`${qualificationOrigin}${path}`, init));+ try {+ assertQualification(env);+ await step('fresh-resources', async () => {+ const accounts = await env.ACCOUNTS.withSession('first-primary')+ .prepare('SELECT COUNT(*) AS n FROM kiln_accounts')+ .first<{ n: number }>();+ check(accounts?.n === 0);+ check((await env.OAUTH_KV.list({ limit: 1 })).keys.length === 0);+ check((await env.ARTIFACTS.list({ limit: 1 })).objects.length === 0);+ });+ await step('pause-native', async () => {+ touchedCompute = true;+ await qualificationControl(env.CONTROL.setPaused(true));+ const status = await qualificationControl<Awaited<ReturnType<KilnCompute['health']>>>(+ env.COMPUTE.health(),+ );+ check(status.paused && status.activeRequests === 0 && status.pendingCleanup === 0);+ record.computePaused = true;+ });+ await step('metadata', async () => {+ const metadata = await privateJson(await send('/.well-known/oauth-protected-resource/mcp'));+ check(metadata.resource === `${qualificationOrigin}/mcp`);+ });+ let alice!: Awaited<ReturnType<typeof syntheticAccount>>, bob!: typeof alice;+ await step('synthetic-accounts', async () => {+ alice = await syntheticAccount(env, 'alice');+ bob = await syntheticAccount(env, 'bob');+ check(alice.account.id !== bob.account.id);+ });+ await step('anonymous-denied', async () => {+ await discard(await send('/mcp'), 401);+ });+ const bearer = (account: typeof alice) => ({ authorization: `Bearer ${account.accessToken}` });+ const discover = (account: typeof alice) =>+ send('/mcp', {+ method: 'POST',+ headers: {+ ...bearer(account),+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2026-07-28',+ 'mcp-method': 'tools/list',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/list',+ params: {+ _meta: {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': {+ name: 'kiln-private-preflight',+ version: '1',+ },+ 'io.modelcontextprotocol/clientCapabilities': {},+ },+ },+ }),+ });+ await step('edge-discovery', async () => {+ const response = await privateJson(await discover(alice));+ const result = response.result as { tools?: { name?: string }[] } | undefined;+ check(result?.tools?.some((tool) => tool.name === 'kiln_render'));+ });+ await step('oversized-denied', async () => {+ await discard(+ await send('/mcp', {+ method: 'POST',+ headers: { ...bearer(alice), 'content-type': 'application/json' },+ body: 'x'.repeat(1024 * 1024 + 1),+ }),+ 413,+ );+ // A normal authenticated request still works after early body rejection.+ await privateJson(await discover(alice));+ });+ let artifact = '',+ download = '';+ const tenant = env.TENANTS.getByName(+ await tenantForAccount(qualificationOrigin, alice.account.id),+ );+ await step('store-fixture', async () => {+ const files: Record<string, string> = {};+ // Fixed storage-routing fixtures, not an engine-created or validated asset.+ for (const [name, body, mime] of [+ ['source.kiln.js', bytes, 'application/javascript'],+ [+ 'asset.glb',+ new TextEncoder().encode('glTF-private-routing-fixture'),+ 'model/gltf-binary',+ ],+ [+ 'manifest.json',+ new TextEncoder().encode('{"fixture":"gateway-routing"}'),+ 'application/json',+ ],+ ] as const) {+ const uploaded = await privateJson(+ await tenant.fetch('https://tenant.internal/internal/artifacts', {+ method: 'POST',+ body,+ headers: {+ 'content-type': mime,+ 'content-length': String(body.byteLength),+ 'x-artifact-name': name,+ 'x-artifact-sha256': hex(await crypto.subtle.digest('SHA-256', body)),+ },+ }),+ 201,+ );+ check(typeof uploaded.id === 'string');+ files[name] = uploaded.id as string;+ }+ artifact = files['source.kiln.js']!;+ const selection = { collection: 'project', assetId: 'preflight-fixture', revisionId: 'v1' };+ await privateJson(+ await tenant.fetch('https://tenant.internal/internal/assets/commit', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ ...selection, mode: 'save', files }),+ }),+ 201,+ );+ const ticket = await privateJson(+ await tenant.fetch('https://tenant.internal/internal/downloads', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(selection),+ }),+ 201,+ );+ check(typeof ticket.ticket === 'string' && /^[a-f0-9]{64}$/.test(ticket.ticket));+ download = `/downloads/${ticket.ticket}/source.kiln.js`;+ });+ const exactSource = async (response: Response) => {+ check(response.status === 200 && response.headers.get('cache-control') === 'no-store');+ check(new TextDecoder().decode(await readBounded(response.body, 1024)) === source);+ };+ await step('bearer-isolation', async () => {+ await exactSource(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(alice) }));+ await discard(+ await send(`/mcp/artifacts/${artifact}`, {+ headers: { ...bearer(bob), 'x-kiln-tenant': alice.account.id },+ }),+ 404,+ );+ });+ await step('browser-isolation', async () => {+ await exactSource(await send(download, { headers: { cookie: alice.cookie } }));+ await discard(await send(download, { headers: { cookie: bob.cookie } }), 404);+ await discard(await send(download, { method: 'HEAD' }), 401);+ });+ await step('revoke-connection', async () => {+ const proof = await new D1BrowserSessions(env.ACCOUNTS, qualificationOrigin).read(+ new Request(`${qualificationOrigin}/account`, { headers: { cookie: alice.cookie } }),+ );+ const grant = await new D1Connections(env.ACCOUNTS).revoke(+ proof,+ alice.identity,+ alice.connectionId,+ );+ check(typeof grant === 'string');+ // Deliberately leave the helper token in KV: primary revocation must deny it.+ });+ await step('revoked-token-denied', async () => {+ await discard(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(alice) }), 401);+ await discard(+ await send('/oauth/token', {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: alice.refreshToken,+ client_id: alice.clientId,+ resource: `${qualificationOrigin}/mcp`,+ }),+ }),+ 400,+ );+ // Revoking one app does not sign the owner's browser out.+ await exactSource(await send(download, { headers: { cookie: alice.cookie } }));+ });+ await step('other-account-preserved', async () => {+ await privateJson(await discover(bob));+ await discard(await send(`/mcp/artifacts/${artifact}`, { headers: bearer(bob) }), 404);+ });+ record.passed = true;+ } catch {+ record.passed = false;+ } finally {+ if (touchedCompute) {+ try {+ await qualificationControl(env.CONTROL.setPaused(true));+ const status = await qualificationControl<Awaited<ReturnType<KilnCompute['health']>>>(+ env.COMPUTE.health(),+ );+ record.computePaused =+ status.paused && status.activeRequests === 0 && status.pendingCleanup === 0;+ } catch {+ record.computePaused = false;+ }+ record.passed &&= record.computePaused;+ }+ record.state = 'finished';+ await storage.put('gateway-preflight', record);+ }+ return record;+}diff --git a/hosting/probe/integrated-budget.ts b/hosting/probe/integrated-budget.tsnew file mode 100644index 00000000..0ac1662e--- /dev/null+++ b/hosting/probe/integrated-budget.ts@@ -0,0 +1,40 @@+export const integratedBudget = { coordinator: 9, evaluation: 4, render: 4 } as const;+export type IntegratedKind = keyof typeof integratedBudget;+interface BudgetRecord {+ state: 'open' | 'closed';+ claims: { kind: IntegratedKind; id: string }[];+}+/** Diagnostic-only ceiling. It cannot reset, refund a failed start or resume a prior batch. */+export class IntegratedBudget {+ constructor(private readonly storage: DurableObjectStorage) {}+ open(): Promise<void> {+ return this.storage.transaction(async (tx) => {+ if (await tx.get('budget')) throw new Error('TRIAL_ALREADY_USED');+ await tx.put('budget', { state: 'open', claims: [] } satisfies BudgetRecord);+ });+ }+ claim(kind: IntegratedKind, id: string): Promise<void> {+ return this.storage.transaction(async (tx) => {+ const record = await tx.get<BudgetRecord>('budget');+ if (+ record?.state !== 'open' ||+ !Object.hasOwn(integratedBudget, kind) ||+ !/^[a-f0-9]{64}$/.test(id) ||+ record.claims.some((claim) => claim.kind === kind && claim.id === id) ||+ record.claims.filter((claim) => claim.kind === kind).length >= integratedBudget[kind]+ )+ throw new Error('TRIAL_BUDGET_DENIED');+ record.claims.push({ kind, id });+ await tx.put('budget', record);+ });+ }+ close(): Promise<void> {+ return this.storage.transaction(async (tx) => {+ const record = await tx.get<BudgetRecord>('budget');+ await tx.put('budget', { ...record, state: 'closed', claims: record?.claims ?? [] });+ });+ }+ status(): Promise<BudgetRecord | undefined> {+ return this.storage.get('budget');+ }+}diff --git a/hosting/probe/integrated-run.ts b/hosting/probe/integrated-run.tsnew file mode 100644index 00000000..e1767077--- /dev/null+++ b/hosting/probe/integrated-run.ts@@ -0,0 +1,252 @@+import { readBounded } from '../src/http';++export const integratedSource = `function build(){const root=createRoot('Root');+const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});+createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});+createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}`;+export const integratedCases = [+ 'render',+ 'save',+ 'restore',+ 'source',+ 'export',+ 'glb',+ 'manifest',+ 'other-source',+ 'other-glb',+ 'quota',+] as const;+type Case = (typeof integratedCases)[number];+interface AdmissionStatus {+ paused: boolean;+ activeRequests: number;+ pendingCleanup: number;+ maxConcurrent: number;+}+interface Ports {+ open(): Promise<void>;+ close(): Promise<void>;+ pause(): Promise<void>;+ status(): Promise<AdmissionStatus>;+ dispatch(tenant: string, request: Request): Promise<Response>;+ retain(name: string, bytes: Uint8Array<ArrayBuffer>): Promise<void>;+}+interface Result {+ name: Case;+ passed: boolean;+ elapsedMs: number;+ status?: number;+ bytes?: number;+ sha256?: string;+ reason?: string;+ savedEngine?: string;+}+interface RunRecord {+ state: 'running' | 'finished';+ passed: boolean;+ results: Result[];+ cleanupConfirmed?: boolean;+}+function check(value: unknown): asserts value {+ if (!value) throw new Error('TRIAL_CHECK_FAILED');+}+function object(value: unknown): Record<string, unknown> {+ check(value !== null && typeof value === 'object' && !Array.isArray(value));+ return value as Record<string, unknown>;+}+function tool(result: Record<string, unknown>) {+ check(result.isError !== true && Array.isArray(result.content));+ const text = result.content.map(object).find((item) => item.type === 'text');+ check(typeof text?.text === 'string');+ return object(JSON.parse(text.text));+}+function fullMaterial(value: unknown) {+ const fidelity = object(value);+ check(fidelity.delivered === 'full-material' && fidelity.degraded === false);+}+const tenantA = 'a'.repeat(43),+ tenantB = 'b'.repeat(43);+function request(id: number, method: string, params: Record<string, unknown>): Request {+ const headers = new Headers({+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2026-07-28',+ 'mcp-method': method,+ });+ const name = params.name ?? params.uri;+ if (typeof name === 'string') headers.set('mcp-name', name);+ return new Request('https://tenant.internal/mcp', {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id,+ method,+ params: {+ ...params,+ _meta: {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': { name: 'kiln-private-integration', version: '1' },+ 'io.modelcontextprotocol/clientCapabilities': {},+ },+ },+ }),+ });+}++/** One fixed sequence, stopping at the first failure. Retries only read the durable record. */+export async function runIntegratedOnce(+ storage: DurableObjectStorage,+ ports: Ports,+): Promise<RunRecord> {+ const claimed = await storage.transaction(async (tx) => {+ if (await tx.get('run')) return false;+ await tx.put('run', { state: 'running', passed: false, results: [] } satisfies RunRecord);+ return true;+ });+ if (!claimed) return (await storage.get<RunRecord>('run'))!;+ const record: RunRecord = { state: 'running', passed: false, results: [] };+ let ref = '',+ assetId = '',+ revisionId = '',+ retained = 0;+ try {+ await ports.open();+ for (const [index, name] of integratedCases.entries()) {+ const start = Date.now();+ let result: Result = { name, passed: false, elapsedMs: 0 };+ try {+ let method = 'tools/call',+ params: Record<string, unknown>;+ const selector = { collection: 'project', assetId, revisionId };+ switch (name) {+ case 'render':+ params = {+ name: 'kiln_render',+ arguments: { code: integratedSource, capture: { preset: '1x1' } },+ };+ break;+ case 'save':+ params = {+ name: 'kiln_save',+ arguments: {+ programRef: ref,+ collection: 'project',+ name: 'Private integration fixture',+ },+ };+ break;+ case 'restore':+ params = { name: 'kiln_assets', arguments: { ...selector, action: 'restore' } };+ break;+ case 'export':+ params = { name: 'kiln_export', arguments: selector };+ break;+ case 'glb':+ case 'other-glb':+ case 'manifest':+ method = 'resources/read';+ params = {+ uri: `kiln://assets/project/${assetId}/${revisionId}/${name === 'manifest' ? 'manifest.json' : 'asset.glb'}`,+ };+ break;+ default:+ params = { name: 'kiln_source', arguments: { programRef: ref } };+ }+ const response = await ports.dispatch(+ name.startsWith('other-') ? tenantB : tenantA,+ request(index + 1, method, params),+ );+ const bytes = await readBounded(response.body, 8 * 1024 * 1024);+ retained += bytes.byteLength;+ check(retained <= 64 * 1024 * 1024);+ await ports.retain(name, bytes);+ const sha256 = Array.from(+ new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)),+ (byte) => byte.toString(16).padStart(2, '0'),+ ).join('');+ result = { ...result, status: response.status, bytes: bytes.byteLength, sha256 };+ if (name === 'quota') check(response.status === 429);+ else {+ check(response.status === 200);+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);+ const rpc = object(JSON.parse(text));+ check(rpc.id === index + 1);+ if (name.startsWith('other-')) {+ check(!text.includes(integratedSource));+ check(rpc.error !== undefined || object(rpc.result).isError === true);+ check(rpc.result === undefined || !object(rpc.result).contents);+ } else {+ check(!rpc.error);+ const payload = object(rpc.result);+ if (method === 'tools/call') {+ const data = tool(payload);+ if (name === 'render') {+ check(data.ok === true && typeof data.programRef === 'string');+ ref = data.programRef;+ check(/^(?:p_|sha256:)[a-f0-9]{64}$/.test(ref));+ fullMaterial(data.viewFidelity);+ check((payload.content as unknown[]).some((item) => object(item).type === 'image'));+ } else if (name === 'save') {+ check(data.ok === true);+ const asset = object(data.asset);+ check(typeof asset.assetId === 'string' && typeof asset.revisionId === 'string');+ assetId = asset.assetId;+ revisionId = asset.revisionId;+ for (const id of [assetId, revisionId]) check(/^[a-z][a-z0-9_-]{0,79}$/.test(id));+ } else if (name === 'restore') check(data.programRef === ref);+ else if (name === 'source')+ check(data.code === integratedSource && data.nextOffset === null);+ else check(data.ok === true);+ } else {+ check(Array.isArray(payload.contents) && payload.contents.length === 1);+ const resource = object(payload.contents[0]);+ if (name === 'glb') {+ check(typeof resource.blob === 'string');+ check(atob(resource.blob).startsWith('glTF'));+ } else {+ check(typeof resource.text === 'string');+ const manifest = object(JSON.parse(resource.text));+ check(manifest.assetId === assetId && manifest.revisionId === revisionId);+ fullMaterial(object(manifest.preview).fidelity);+ const engine = object(manifest.build).engine;+ check(typeof engine === 'string');+ result.savedEngine = engine;+ }+ }+ }+ }+ const status = await ports.status();+ check(status.activeRequests === 0 && status.pendingCleanup === 0);+ result.passed = true;+ } catch {+ result.reason = 'TRIAL_CASE_FAILED';+ }+ result.elapsedMs = Date.now() - start;+ record.results.push(result);+ await storage.put('run', record);+ if (!result.passed) break;+ }+ } catch {+ /* Fail closed; retained cases explain how far the fixed sequence reached. */+ } finally {+ const cleanup = await Promise.allSettled([ports.close(), ports.pause()]);+ try {+ const status = await ports.status();+ record.cleanupConfirmed =+ cleanup.every((r) => r.status === 'fulfilled') &&+ status.paused &&+ status.activeRequests === 0 &&+ status.pendingCleanup === 0;+ } catch {+ record.cleanupConfirmed = false;+ }+ record.state = 'finished';+ record.passed =+ record.cleanupConfirmed === true &&+ record.results.length === integratedCases.length &&+ record.results.every((result) => result.passed);+ await storage.put('run', record);+ }+ return record;+}diff --git a/hosting/probe/integrated-worker.ts b/hosting/probe/integrated-worker.tsnew file mode 100644index 00000000..fd521d10--- /dev/null+++ b/hosting/probe/integrated-worker.ts@@ -0,0 +1,113 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { KilnNativeRequest } from '../src/request-worker';+import { KilnEvaluationJob } from '../src/evaluation-worker';+import { KilnRenderJob } from '../src/render-worker';+import type { KilnAdmission } from '../src/admission-worker';+import { IntegratedBudget, type IntegratedKind } from './integrated-budget';+import { runIntegratedOnce } from './integrated-run';++export { KilnNativeStorage, KilnNativeEvaluation, KilnNativeRender } from '../src/request-worker';+export { KilnTenant } from '../src/tenant';+export { KilnAdmission } from '../src/admission-worker';++interface BudgetBindings {+ BUDGET: DurableObjectNamespace<KilnIntegratedBudget>;+}+interface RunBindings extends BudgetBindings {+ RUN: DurableObjectNamespace<KilnIntegratedRun>;+ ADMISSION: DurableObjectNamespace<KilnAdmission>;+ ARTIFACTS: R2Bucket;+}+const budget = (env: unknown) => (env as BudgetBindings).BUDGET.getByName('integrated-v1');++async function claimRequest(env: unknown, kind: IntegratedKind, id: string, request: Request) {+ try {+ await budget(env).claim(kind, id);+ } catch (error) {+ if (!request.bodyUsed) await request.body?.cancel().catch(() => {});+ throw error;+ }+}++/** Wrappers add only the diagnostic allowance; production run/fetch/cancel/alarm stay intact. */+export class IntegratedRequestJob extends KilnNativeRequest {+ override async run(tenant: string, request: Request, deadline: number): Promise<Response> {+ await claimRequest(this.env, 'coordinator', this.ctx.id.toString(), request);+ return super.run(tenant, request, deadline);+ }+}+export class IntegratedEvaluationJob extends KilnEvaluationJob {+ override async fetch(request: Request): Promise<Response> {+ await claimRequest(this.env, 'evaluation', this.ctx.id.toString(), request);+ return super.fetch(request);+ }+}+export class IntegratedRenderJob extends KilnRenderJob {+ override async fetch(request: Request): Promise<Response> {+ await claimRequest(this.env, 'render', this.ctx.id.toString(), request);+ return super.fetch(request);+ }+}+export class KilnIntegratedBudget extends DurableObject {+ private readonly budget = new IntegratedBudget(this.ctx.storage);+ open() {+ return this.budget.open();+ }+ claim(kind: IntegratedKind, id: string) {+ return this.budget.claim(kind, id);+ }+ close() {+ return this.budget.close();+ }+ status() {+ return this.budget.status();+ }+}+export class KilnIntegratedRun extends DurableObject<RunBindings> {+ run() {+ const allowance = budget(this.env),+ admission = this.env.ADMISSION.getByName('global-v1');+ return runIntegratedOnce(this.ctx.storage, {+ open: () => allowance.open(),+ close: () => allowance.close(),+ pause: async () => {+ await admission.setPaused(true);+ },+ status: () => admission.status(),+ dispatch: (tenant, request) => admission.dispatch(tenant, request),+ retain: async (name, bytes) => {+ await this.env.ARTIFACTS.put(`probe-evidence/${name}.json`, bytes, {+ httpMetadata: { contentType: 'application/json' },+ });+ },+ });+ }+ async status() {+ return this.ctx.storage.get('run');+ }+}+export class KilnIntegratedControl extends WorkerEntrypoint<RunBindings> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }+ runFixed() {+ return this.env.RUN.getByName('integrated-v1').run();+ }+ async stop() {+ await budget(this.env).close();+ await this.env.ADMISSION.getByName('global-v1').setPaused(true);+ return this.status();+ }+ async status() {+ return {+ run: await this.env.RUN.getByName('integrated-v1').status(),+ budget: await budget(this.env).status(),+ admission: await this.env.ADMISSION.getByName('global-v1').status(),+ };+ }+}+export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler;diff --git a/hosting/probe/kiln-startup-worker.ts b/hosting/probe/kiln-startup-worker.tsnew file mode 100644index 00000000..4c3b862e--- /dev/null+++ b/hosting/probe/kiln-startup-worker.ts@@ -0,0 +1,32 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ManagedStartupDiagnostic } from './startup-diagnostic';++interface Bindings {+ STARTUP_JOB: DurableObjectNamespace<KilnImageStartupJob>;+}++export class KilnImageStartupJob extends DurableObject {+ async runFixed() {+ return new ManagedStartupDiagnostic(this.ctx, 'kiln').run();+ }++ async alarm() {+ await new ManagedStartupDiagnostic(this.ctx, 'kiln').alarm();+ }+}++export class KilnImageStartupControl extends WorkerEntrypoint<Bindings> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }++ async runFixed() {+ return this.env.STARTUP_JOB.getByName('kiln-runtime-2026-10-06').runFixed();+ }+}++export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler<Bindings>;diff --git a/hosting/probe/kiln-startup.wrangler.jsonc b/hosting/probe/kiln-startup.wrangler.jsoncnew file mode 100644index 00000000..35d26b02--- /dev/null+++ b/hosting/probe/kiln-startup.wrangler.jsonc@@ -0,0 +1,35 @@+{+ "name": "kiln-private-image-startup",+ "main": "./kiln-startup-worker.ts",+ "compatibility_date": "2026-10-06",+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": { "cpu_ms": 30000, "subrequests": 50 },+ "observability": {+ "enabled": true,+ "logs": { "enabled": true, "invocation_logs": true }+ },+ "containers": [+ {+ "name": "kiln-private-image-startup",+ "class_name": "KilnImageStartupJob",+ "scheduling_policy": "durable_object",+ "images": {+ "control": {+ "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a"+ }+ },+ "observability": { "logs": { "enabled": false } }+ }+ ],+ "durable_objects": {+ "bindings": [+ { "name": "STARTUP_JOB", "class_name": "KilnImageStartupJob" }+ ]+ },+ "exports": {+ "KilnImageStartupControl": { "type": "worker" },+ "KilnImageStartupJob": { "type": "durable-object", "storage": "sqlite" }+ }+}diff --git a/hosting/probe/lifecycle-allowance-worker.ts b/hosting/probe/lifecycle-allowance-worker.tsnew file mode 100644index 00000000..1b30d25c--- /dev/null+++ b/hosting/probe/lifecycle-allowance-worker.ts@@ -0,0 +1,19 @@+import { DurableObject } from 'cloudflare:workers';+import { LifecycleBudget, type LifecycleKind } from './lifecycle-budget';++export class KilnLifecycleBudget extends DurableObject {+ private readonly allowance = new LifecycleBudget(this.ctx.storage);+ open() {+ return this.allowance.open();+ }+ claim(kind: LifecycleKind, id: string) {+ return this.allowance.claim(kind, id);+ }+ close() {+ return this.allowance.close();+ }+ status() {+ return this.allowance.status();+ }+}+export default { fetch: () => new Response('Not found', { status: 404 }) };diff --git a/hosting/probe/lifecycle-binding.ts b/hosting/probe/lifecycle-binding.tsnew file mode 100644index 00000000..ab8bbf71--- /dev/null+++ b/hosting/probe/lifecycle-binding.ts@@ -0,0 +1,22 @@+import type { KilnLifecycleBudget } from './lifecycle-allowance-worker';+import type { LifecycleKind } from './lifecycle-budget';++export interface LifecycleAllowanceEnv {+ BUDGET: DurableObjectNamespace<KilnLifecycleBudget>;+}+export const lifecycleAllowance = (env: unknown) =>+ (env as LifecycleAllowanceEnv).BUDGET.getByName('lifecycle-v1');++export async function claimLifecycle(+ env: unknown,+ kind: LifecycleKind,+ id: string,+ request: Request,+): Promise<void> {+ try {+ await lifecycleAllowance(env).claim(kind, id);+ } catch {+ if (!request.bodyUsed) await request.body?.cancel().catch(() => {});+ throw new Error('PRIVATE_LIFECYCLE_ALLOWANCE_DENIED');+ }+}diff --git a/hosting/probe/lifecycle-budget.ts b/hosting/probe/lifecycle-budget.tsnew file mode 100644index 00000000..ed9ad050--- /dev/null+++ b/hosting/probe/lifecycle-budget.ts@@ -0,0 +1,40 @@+export const lifecycleBudget = { coordinator: 14, evaluation: 4, render: 4 } as const;+export type LifecycleKind = keyof typeof lifecycleBudget;+interface BudgetRecord {+ state: 'open' | 'closed';+ claims: { kind: LifecycleKind; id: string }[];+}+/** Private diagnostic ceiling. Failed starts consume their claim permanently. */+export class LifecycleBudget {+ constructor(private readonly storage: DurableObjectStorage) {}+ open(): Promise<void> {+ return this.storage.transaction(async (tx) => {+ if (await tx.get('lifecycle-allowance-v1')) throw new Error('LIFECYCLE_ALREADY_USED');+ await tx.put('lifecycle-allowance-v1', { state: 'open', claims: [] } satisfies BudgetRecord);+ });+ }+ claim(kind: LifecycleKind, id: string): Promise<void> {+ return this.storage.transaction(async (tx) => {+ const record = await tx.get<BudgetRecord>('lifecycle-allowance-v1');+ if (+ record?.state !== 'open' ||+ !Object.hasOwn(lifecycleBudget, kind) ||+ !/^[a-f0-9]{64}(?![\s\S])/.test(id) ||+ record.claims.some((claim) => claim.kind === kind && claim.id === id) ||+ record.claims.filter((claim) => claim.kind === kind).length >= lifecycleBudget[kind]+ )+ throw new Error('LIFECYCLE_BUDGET_DENIED');+ record.claims.push({ kind, id });+ await tx.put('lifecycle-allowance-v1', record);+ });+ }+ close(): Promise<void> {+ return this.storage.transaction(async (tx) => {+ const record = await tx.get<BudgetRecord>('lifecycle-allowance-v1');+ await tx.put('lifecycle-allowance-v1', { state: 'closed', claims: record?.claims ?? [] });+ });+ }+ status(): Promise<BudgetRecord | undefined> {+ return this.storage.get('lifecycle-allowance-v1');+ }+}diff --git a/hosting/probe/lifecycle-build-boundary.mjs b/hosting/probe/lifecycle-build-boundary.mjsnew file mode 100644index 00000000..ca9ec40f--- /dev/null+++ b/hosting/probe/lifecycle-build-boundary.mjs@@ -0,0 +1,26 @@+import assert from 'node:assert/strict';+import { assertProductionBoundary } from '../scripts/build-boundary.mjs';++export function assertLifecycleBoundary(role, inputs) {+ const paths = inputs.map(path => path.replaceAll('\\', '/'));+ if (role === 'operator') {+ const allowed = new Set(['lifecycle-worker', 'lifecycle-budget', 'lifecycle-binding',+ 'lifecycle-run', 'gateway-preflight', 'qualification-accounts', 'qualification-rpc']);+ for (const path of paths) {+ assert(!/(?:^|\/)test\//.test(path));+ const probe = path.match(/(?:^|\/)probe\/([^/]+)\.ts$/);+ if (/(?:^|\/)probe\//.test(path)) assert(probe && allowed.has(probe[1]));+ }+ return;+ }+ const wrappers = ['request', 'evaluation', 'render'].includes(role);+ const expected = role === 'allowance' ? new Set(['lifecycle-allowance-worker', 'lifecycle-budget']) :+ wrappers ? new Set([`lifecycle-${role}-worker`, 'lifecycle-binding']) : new Set();+ const production = paths.filter(path => {+ const probe = path.match(/(?:^|\/)probe\/([^/]+)\.ts$/);+ if (!probe) return true;+ assert(expected.has(probe[1]));+ return false;+ });+ assertProductionBoundary(role === 'gateway' ? 'worker' : `${role}-worker`, production);+}diff --git a/hosting/probe/lifecycle-config.mjs b/hosting/probe/lifecycle-config.mjsnew file mode 100644index 00000000..546d8a2b--- /dev/null+++ b/hosting/probe/lifecycle-config.mjs@@ -0,0 +1,70 @@+import assert from 'node:assert/strict';+import { OutputWorkerSchema, convertToWranglerConfig } from '@cloudflare/config';+import { deploymentConfig } from '../scripts/deployment-config.mjs';++/** Offline diagnostic topology, derived from production with no public route. */+export function lifecycleConfig(manifest) {+ const c = deploymentConfig(manifest);+ assert.equal(manifest.prefix, 'kiln-private-lifecycle-v1');+ assert.equal(manifest.origin, 'https://kiln-private-qualification.invalid');+ assert.deepEqual(manifest.compute, {+ maxConcurrent: 1, tenantPerMinute: 14, tenantPerDay: 14,+ globalPerDay: 14, globalPerMonth: 14, deadlineMs: 120000,+ });+ assert.deepEqual(manifest.storage, { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 });+ assert.equal(manifest.requestLimits.edge.perMinute, 600);+ assert.equal(manifest.requestLimits.account.perMinute, 120);+ const operatorName = `${manifest.prefix}-operator`;+ const allowanceName = `${manifest.prefix}-allowance`;+ const budget = { type: 'durable-object', worker: allowanceName, exportName: 'KilnLifecycleBudget' };+ for (const role of ['request', 'evaluation', 'render']) {+ c.workers[role].env.BUDGET = { ...budget };+ c.entries[role] = `../probe/lifecycle-${role}-worker`;+ }+ const gateway = c.workers.gateway;+ // This fixed private test uses synthetic identities only, never live providers.+ for (const [name, binding] of Object.entries(gateway.env))+ if (binding.type === 'secret') delete gateway.env[name];+ gateway.triggers = [];+ c.workers.allowance = OutputWorkerSchema.parse({+ ...gateway, name: allowanceName, env: {},+ exports: { KilnLifecycleBudget: { type: 'durable-object', storage: 'sqlite' } },+ });+ c.workers.operator = OutputWorkerSchema.parse({+ ...gateway,+ name: operatorName,+ env: {+ PUBLIC_ORIGIN: { type: 'text', value: manifest.origin },+ QUALIFICATION_MODE: { type: 'text', value: 'isolated-synthetic-v1' },+ EXPECTED_IMAGE: { type: 'text', value: manifest.images.software.split('@')[1] },+ ACCOUNTS: { ...gateway.env.ACCOUNTS }, OAUTH_KV: { ...gateway.env.OAUTH_KV },+ TENANTS: { ...gateway.env.TENANTS }, ARTIFACTS: { ...c.workers.tenant.env.ARTIFACTS },+ GATEWAY: { type: 'worker', worker: gateway.name },+ COMPUTE: { ...gateway.env.NATIVE_COMPUTE },+ CONTROL: { type: 'worker', worker: c.workers.admission.name, exportName: 'KilnComputeControl' },+ BUDGET: budget,+ RUN: { type: 'durable-object', worker: operatorName, exportName: 'KilnLifecycleRun' },+ },+ exports: {+ KilnLifecycleRun: { type: 'durable-object', storage: 'sqlite' },+ KilnLifecycleControl: { type: 'worker' },+ },+ });+ c.entries.operator = '../probe/lifecycle-worker';+ c.entries.allowance = '../probe/lifecycle-allowance-worker';+ for (const [role, worker] of Object.entries(c.workers)) {+ c.workers[role] = OutputWorkerSchema.parse(worker);+ const config = convertToWranglerConfig({+ accountId: manifest.account,+ worker: { ...worker, entrypoint: `./.cloudflare/output/v0/workers/${role}/bundle/worker.mjs` },+ containers: c.containers[role] ? [c.containers[role]] : [],+ });+ for (const binding of config.durable_objects?.bindings ?? [])+ if (binding.script_name === worker.name) delete binding.script_name;+ config.routes = [];+ if (config.d1_databases?.length) config.d1_databases[0].migrations_dir = './migrations';+ c.wrangler[role] = config;+ }+ c.deployOrder = ['tenant', 'allowance', 'evaluation', 'render', 'request', 'admission', 'gateway', 'operator'];+ return c;+}diff --git a/hosting/probe/lifecycle-evaluation-worker.ts b/hosting/probe/lifecycle-evaluation-worker.tsnew file mode 100644index 00000000..3420e2d3--- /dev/null+++ b/hosting/probe/lifecycle-evaluation-worker.ts@@ -0,0 +1,9 @@+import { KilnEvaluationJob as EvaluationJob } from '../src/evaluation-worker';+import { claimLifecycle } from './lifecycle-binding';+export { default } from '../src/evaluation-worker';+export class KilnEvaluationJob extends EvaluationJob {+ override async fetch(request: Request): Promise<Response> {+ await claimLifecycle(this.env, 'evaluation', this.ctx.id.toString(), request);+ return super.fetch(request);+ }+}diff --git a/hosting/probe/lifecycle-observer.ts b/hosting/probe/lifecycle-observer.tsnew file mode 100644index 00000000..3d6c8886--- /dev/null+++ b/hosting/probe/lifecycle-observer.ts@@ -0,0 +1,77 @@+type Action = 'runFixed' | 'status' | 'stop';+interface Env {+ PROBE: Record<Action, () => Promise<unknown>>;+}+const dispose = (value: unknown) =>+ (value as { [Symbol.dispose]?: () => void } | null | undefined)?.[Symbol.dispose]?.();++/** Local loopback observer only. Its sole remote binding is the fixed private+ * operator, which owns the durable one-use claim. Never deploy this facade. */+export default {+ async fetch(request: Request, env: Env): Promise<Response> {+ const url = new URL(request.url);+ const action = new Map<string, Action>([+ ['/run-fixed', 'runFixed'],+ ['/status', 'status'],+ ['/stop', 'stop'],+ ]).get(url.pathname);+ // No request content becomes an RPC argument. Abort unread bodies rather+ // than consuming arbitrary local input or a cross-origin upload.+ void request.body?.cancel().catch(() => {});+ if (+ request.method !== 'POST' ||+ url.origin !== 'http://127.0.0.1:8798' ||+ url.search ||+ url.hash ||+ request.headers.has('Origin') ||+ request.headers.has('Sec-Fetch-Site') ||+ request.headers.get('X-Kiln-Operator') !== 'private-lifecycle-v1' ||+ !action+ )+ return new Response('Not found', { status: 404 });+ const headers = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' };+ let work: Promise<unknown> | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let expired = false;+ try {+ work = env.PROBE[action]();+ const result = await Promise.race([+ work.then((value) => {+ if (expired) {+ dispose(value);+ throw new Error('PRIVATE_OBSERVATION_EXPIRED');+ }+ return value;+ }),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => {+ expired = true;+ reject(new Error('PRIVATE_OBSERVATION_EXPIRED'));+ },+ action === 'runFixed' ? 16 * 60 * 1000 : 10000,+ );+ }),+ ]);+ try {+ const bytes = JSON.stringify(structuredClone(result));+ if (new TextEncoder().encode(bytes).length > 128 * 1024)+ throw new Error('PRIVATE_OBSERVATION_TOO_LARGE');+ return new Response(bytes, { headers: { ...headers, 'content-type': 'application/json' } });+ } finally {+ dispose(result);+ }+ } catch {+ return Response.json(+ {+ observation: 'unavailable',+ next: 'Read /status for the same trial; do not start a replacement run.',+ },+ { status: 502, headers },+ );+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ dispose(work);+ }+ },+};diff --git a/hosting/probe/lifecycle-observer.wrangler.jsonc b/hosting/probe/lifecycle-observer.wrangler.jsoncnew file mode 100644index 00000000..17d57c0c--- /dev/null+++ b/hosting/probe/lifecycle-observer.wrangler.jsonc@@ -0,0 +1,16 @@+{+ "name": "kiln-local-lifecycle-observer",+ "main": "./lifecycle-observer.ts",+ "compatibility_date": "2026-10-06",+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "observability": { "enabled": false },+ "dev": { "ip": "127.0.0.1", "port": 8798, "local_protocol": "http" },+ "services": [{+ "binding": "PROBE",+ "service": "kiln-private-lifecycle-v1-operator",+ "entrypoint": "KilnLifecycleControl",+ "remote": true+ }]+}diff --git a/hosting/probe/lifecycle-readback.mjs b/hosting/probe/lifecycle-readback.mjsnew file mode 100644index 00000000..f274088f--- /dev/null+++ b/hosting/probe/lifecycle-readback.mjs@@ -0,0 +1,313 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { lifecycleConfig } from './lifecycle-config.mjs';++const sorted = (values) => [...values].sort();+const one = (values, predicate) => {+ const found = values.filter(predicate);+ assert.equal(found.length, 1, 'Expected exactly one matching private resource');+ return found[0];+};+const identifier = (value) => assert(typeof value === 'string' && /^[a-f0-9-]{28,64}$/.test(value));+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');++function verifyDisabledLogging(worker, settings) {+ assert(settings && Object.hasOwn(settings, 'observability'), 'Raw script settings are required');+ assert.equal(settings.logpush, false);+ assert(settings.tail_consumers === null || Array.isArray(settings.tail_consumers));+ assert.deepEqual(settings.tail_consumers ?? [], []);+ assert.equal(worker.logpush, false);+ assert.deepEqual(worker.tail_consumers, []);+ const checkDisabled = (observability) => {+ assert.equal(observability.enabled, false);+ assert.equal(observability.logs.enabled, false);+ assert.equal(observability.traces.enabled, false);+ assert.deepEqual(observability.logs.destinations ?? [], []);+ assert.deepEqual(observability.traces.destinations ?? [], []);+ };+ checkDisabled(worker.observability);+ // The script-settings API returns null when observability is disabled. The+ // CLI normalizes that into inactive defaults (including persist:true). Require+ // the independent raw readback; missing evidence must never mean disabled.+ if (settings.observability === null) return;+ checkDisabled(settings.observability);+ for (const observability of [settings.observability, worker.observability]) {+ assert.equal(observability.redact_query_string, true);+ assert.equal(observability.logs.invocation_logs, false);+ assert.equal(observability.logs.persist, false);+ assert.equal(observability.traces.persist, false);+ }+}++function verifyBindings(expected, actual = [], namespaces) {+ assert.deepEqual(sorted(actual.map((b) => b.name)), sorted(Object.keys(expected)));+ for (const [name, binding] of Object.entries(expected)) {+ const observed = one(actual, (b) => b.name === name);+ let value;+ switch (binding.type) {+ case 'text':+ value = { name, type: 'plain_text', text: binding.value };+ break;+ case 'd1':+ value = { name, type: 'd1', id: binding.id };+ if (observed.database_id !== undefined) value.database_id = binding.id;+ break;+ case 'kv':+ value = { name, type: 'kv_namespace', namespace_id: binding.id };+ break;+ case 'r2':+ value = { name, type: 'r2_bucket', bucket_name: binding.name };+ break;+ case 'rate-limit':+ value = {+ name,+ type: 'ratelimit',+ namespace_id: binding.namespace,+ simple: binding.simple,+ };+ break;+ case 'analytics-engine-dataset':+ value = { name, type: 'analytics_engine', dataset: binding.name };+ break;+ case 'worker':+ value = {+ name,+ type: 'service',+ service: binding.worker,+ ...(binding.exportName ? { entrypoint: binding.exportName } : {}),+ };+ if (observed.environment !== undefined) value.environment = 'production';+ break;+ case 'durable-object': {+ const namespace = one(+ namespaces,+ (n) => n.script === binding.worker && n.class === binding.exportName,+ );+ value = {+ name,+ type: 'durable_object_namespace',+ namespace_id: namespace.id,+ class_name: binding.exportName,+ };+ if (observed.script_name !== undefined) value.script_name = binding.worker;+ if (observed.environment !== undefined) value.environment = 'production';+ break;+ }+ default:+ assert.fail('Unsupported private binding');+ }+ assert.deepEqual(observed, value, 'Deployed private binding differs from candidate');+ }+}++/** Pure verification of CLI/API readback, not an API call or deployment. The+ * operator supplies complete, freshly collected pages and the frozen receipt. */+export function verifyLifecycleDeployment(manifest, receipt, snapshot) {+ const c = lifecycleConfig(manifest);+ assert.equal(receipt.mode, 'private-lifecycle');+ assert.equal(receipt.sourceDirty, false);+ assert.match(receipt.sourceCommit, /^[a-f0-9]{40}$/);+ assert.equal(snapshot.account, manifest.account);+ assert.equal(snapshot.complete, true);+ assert.deepEqual(receipt.images, manifest.images);+ assert.deepEqual(receipt.deployOrder, c.deployOrder);+ assert.deepEqual(sorted(receipt.workers.map((w) => w.role)), sorted(c.deployOrder));+ assert.deepEqual(sorted(Object.keys(snapshot.workers)), sorted(c.deployOrder));+ assert.equal(snapshot.database.uuid, manifest.database.id);+ assert.equal(snapshot.database.name, manifest.database.name);+ assert.equal(snapshot.kv.id, manifest.oauthKv);+ assert.equal(snapshot.kv.title, `${manifest.prefix}-oauth`);+ assert.equal(snapshot.bucket.name, manifest.bucket);+ assert.equal(snapshot.managedDomain.enabled, false);+ assert.deepEqual(snapshot.customDomains.domains, []);+ assert.equal(receipt.migrations.length, 9);+ assert.deepEqual(sorted(snapshot.migrations), sorted(receipt.migrations.map((m) => m.name)));+ const namespaces = snapshot.namespaces.filter((n) => n.script.startsWith(`${manifest.prefix}-`));+ const expectedClasses = Object.values(c.workers).flatMap((w) =>+ Object.entries(w.exports)+ .filter(([, e]) => e.type === 'durable-object')+ .map(([name]) => `${w.name}:${name}`),+ );+ assert.deepEqual(+ sorted(namespaces.map((n) => `${n.script}:${n.class}`)),+ sorted(expectedClasses),+ );+ assert.equal(new Set(namespaces.map((n) => n.id)).size, namespaces.length);+ for (const namespace of namespaces) {+ identifier(namespace.id);+ assert.equal(namespace.use_sqlite, true);+ }+ const workers = [];+ const applications = [];+ for (const role of c.deployOrder) {+ const expected = c.workers[role],+ wrangler = c.wrangler[role];+ const { worker, version, deployments, routes, schedules, scriptSettings } = snapshot.workers[role];+ const prepared = one(receipt.workers, (w) => w.role === role);+ assert.equal(prepared.name, expected.name);+ identifier(worker.id);+ identifier(version.id);+ assert.equal(worker.name, expected.name);+ assert.equal(worker.subdomain.enabled, false);+ assert.equal(worker.subdomain.previews_enabled, false);+ verifyDisabledLogging(worker, scriptSettings);+ for (const key of ['domains', 'queues', 'dispatch_namespace_outbounds'])+ assert.deepEqual(worker.references[key], []);+ assert.deepEqual(routes, []);+ assert.deepEqual(schedules, []);+ assert.deepEqual(version.urls, []);+ assert.equal(version.compatibility_date, expected.compatibilityDate);+ assert.deepEqual(sorted(version.compatibility_flags), sorted(expected.compatibilityFlags));+ assert.deepEqual(version.limits, wrangler.limits);+ assert.deepEqual(version.exports ?? {}, expected.exports);+ assert.equal(version.main_module, 'worker.mjs');+ assert.equal(version.modules.length, 1);+ assert.equal(version.modules[0].name, 'worker.mjs');+ assert.equal(hash(Buffer.from(version.modules[0].content_base64, 'base64')), prepared.sha256);+ const deployment = deployments.deployments[0];+ identifier(deployment.id);+ assert.deepEqual(deployment.versions, [{ version_id: version.id, percentage: 100 }]);+ verifyBindings(expected.env, version.bindings, namespaces);+ if (c.containers[role]) {+ const container = c.containers[role];+ const className = Object.entries(expected.exports).find(+ ([, e]) => e.container === container.name,+ )[0];+ const namespace = one(namespaces, (n) => n.script === expected.name && n.class === className);+ const images = Object.fromEntries(+ Object.entries(container.images).map(([name, image]) => [name, image.reference]),+ );+ assert.deepEqual(version.containers, [+ { name: container.name, class_name: className, images },+ ]);+ const app = one(snapshot.applications, (a) => a.name === container.name);+ identifier(app.id);+ assert.equal(app.account_id, manifest.account);+ assert.equal(app.scheduling_policy, 'durable_object');+ assert.equal(app.durable_objects.namespace_id, namespace.id);+ assert.equal(app.configuration.wrangler_ssh.enabled, false);+ assert.equal(app.observability.logs.enabled, false);+ assert.equal(app.health.instances.active, 0);+ assert.equal(app.health.instances.starting, 0);+ applications.push({+ role,+ kind: role === 'request' ? 'coordinator' : role,+ id: app.id,+ name: app.name,+ className,+ namespaceId: namespace.id,+ images,+ });+ } else assert.deepEqual(version.containers ?? [], []);+ workers.push({+ role,+ name: worker.name,+ id: worker.id,+ version: version.id,+ deployment: deployment.id,+ sha256: prepared.sha256,+ });+ }+ assert.equal(new Set(workers.map((w) => w.id)).size, workers.length);+ assert.deepEqual(+ sorted(+ snapshot.applications+ .filter((a) => a.name.startsWith(`${manifest.prefix}-`))+ .map((a) => a.id),+ ),+ sorted(applications.map((a) => a.id)),+ );+ return {+ sourceCommit: receipt.sourceCommit,+ account: manifest.account,+ prefix: manifest.prefix,+ privateConfigurationVerified: true,+ workers,+ applications,+ namespaces,+ database: { id: manifest.database.id, name: manifest.database.name },+ kv: { id: manifest.oauthKv, title: snapshot.kv.title },+ bucket: manifest.bucket,+ metrics: {+ dataset: c.workers.gateway.env.OPERATIONS.name,+ retention: 'provider-managed three months',+ },+ };+}++/** Produces targets only. Re-read this exact deployment immediately before+ * executing, check the IDs again, retain evidence, and verify absence afterward.+ * This does not grant permission, perform deletion, or claim it succeeded. */+export function planLifecycleCleanup(manifest, verified, status, instances) {+ const c = lifecycleConfig(manifest);+ assert.equal(verified.account, manifest.account);+ assert.equal(verified.prefix, manifest.prefix);+ assert.equal(verified.privateConfigurationVerified, true);+ assert.deepEqual(verified.database, { id: manifest.database.id, name: manifest.database.name });+ assert.deepEqual(verified.kv, { id: manifest.oauthKv, title: `${manifest.prefix}-oauth` });+ assert.equal(verified.bucket, manifest.bucket);+ assert.deepEqual(+ verified.workers.map((w) => w.role),+ c.deployOrder,+ );+ for (const w of verified.workers) {+ assert.equal(w.name, c.workers[w.role].name);+ identifier(w.id);+ }+ for (const a of verified.applications) {+ assert.equal(a.name, c.containers[a.role].name);+ identifier(a.id);+ assert.equal(a.kind, a.role === 'request' ? 'coordinator' : a.role);+ assert.deepEqual(+ a.images,+ Object.fromEntries(+ Object.entries(c.containers[a.role].images).map(([key, v]) => [key, v.reference]),+ ),+ );+ }+ assert.deepEqual(sorted(verified.applications.map((a) => a.role)), [+ 'evaluation',+ 'render',+ 'request',+ ]);+ assert.equal(status.operatorStopped, true);+ assert.equal(status.alarmAt, null);+ assert(status.record === null || ['finished', 'stopped'].includes(status.record.state));+ assert.equal(status.budget.state, 'closed');+ assert.equal(status.admission.paused, true);+ assert.equal(status.admission.activeRequests, 0);+ assert.equal(status.admission.pendingCleanup, 0);+ const claims = status.budget.claims;+ const limits = { coordinator: 14, evaluation: 4, render: 4 };+ assert(claims.length <= 22);+ assert.equal(new Set(claims.map((x) => `${x.kind}:${x.id}`)).size, claims.length);+ for (const claim of claims) {+ assert(Object.hasOwn(limits, claim.kind));+ assert.match(claim.id, /^[a-f0-9]{64}$/);+ }+ for (const [kind, limit] of Object.entries(limits))+ assert(claims.filter((c) => c.kind === kind).length <= limit);+ assert(instances.length <= claims.length);+ assert.equal(new Set(instances.map((i) => `${i.application_id}:${i.id}`)).size, instances.length);+ for (const instance of instances) {+ const app = one(verified.applications, (a) => a.id === instance.application_id);+ assert.equal(instance.status.state, 'stopped');+ assert(Object.values(app.images).includes(instance.image));+ assert(claims.some((c) => c.kind === app.kind && c.id === instance.id));+ }+ return {+ sourceCommit: verified.sourceCommit,+ account: manifest.account,+ workers: verified.workers.toReversed(),+ applications: verified.applications,+ namespaces: verified.namespaces,+ database: verified.database,+ kv: verified.kv,+ bucket: verified.bucket,+ registryImages: 'preserve',+ claims: claims.length,+ verifiedStoppedInstances: instances.length,+ metrics: { ...verified.metrics, deletionVerified: false },+ executed: false,+ };+}diff --git a/hosting/probe/lifecycle-render-worker.ts b/hosting/probe/lifecycle-render-worker.tsnew file mode 100644index 00000000..ba27601f--- /dev/null+++ b/hosting/probe/lifecycle-render-worker.ts@@ -0,0 +1,9 @@+import { KilnRenderJob as RenderJob } from '../src/render-worker';+import { claimLifecycle } from './lifecycle-binding';+export { default } from '../src/render-worker';+export class KilnRenderJob extends RenderJob {+ override async fetch(request: Request): Promise<Response> {+ await claimLifecycle(this.env, 'render', this.ctx.id.toString(), request);+ return super.fetch(request);+ }+}diff --git a/hosting/probe/lifecycle-request-worker.ts b/hosting/probe/lifecycle-request-worker.tsnew file mode 100644index 00000000..655a6b33--- /dev/null+++ b/hosting/probe/lifecycle-request-worker.ts@@ -0,0 +1,14 @@+import { KilnNativeRequest as NativeRequest } from '../src/request-worker';+import { claimLifecycle } from './lifecycle-binding';+export {+ default,+ KilnNativeStorage,+ KilnNativeEvaluation,+ KilnNativeRender,+} from '../src/request-worker';+export class KilnNativeRequest extends NativeRequest {+ override async run(tenant: string, request: Request, deadline: number): Promise<Response> {+ await claimLifecycle(this.env, 'coordinator', this.ctx.id.toString(), request);+ return super.run(tenant, request, deadline);+ }+}diff --git a/hosting/probe/lifecycle-run.ts b/hosting/probe/lifecycle-run.tsnew file mode 100644index 00000000..f5df038d--- /dev/null+++ b/hosting/probe/lifecycle-run.ts@@ -0,0 +1,521 @@+import { readBounded } from '../src/http';++export { lifecycleBudget } from './lifecycle-budget';+export const lifecycleCases = [+ 'material-create',+ 'material-get',+ 'render',+ 'save',+ 'restore',+ 'source',+ 'export',+ 'glb',+ 'manifest',+ 'source-download',+ 'glb-download',+ 'material-download',+ 'foreign-download',+ 'anonymous-download',+ 'foreign-source',+ 'foreign-material',+ 'drop-live-material',+ 'import',+ 'imported-material',+ 'rerender',+ 'quota',+] as const;+type Case = (typeof lifecycleCases)[number];+type Account = 'owner' | 'other';+interface Status {+ paused: boolean;+ activeRequests: number;+ pendingCleanup: number;+}+interface Ports {+ expectedImage: string;+ open(): Promise<void>;+ close(): Promise<void>;+ pause(): Promise<void>;+ status(): Promise<Status>;+ mcp(account: Account, request: Request): Promise<Response>;+ download(account: Account | 'anonymous', path: string, signal: AbortSignal): Promise<Response>;+ dropMaterial(materialId: string, revisionId: string): Promise<void>;+ retain(name: Case, bytes: Uint8Array<ArrayBuffer>): Promise<void>;+}+interface Result {+ name: Case;+ passed: boolean;+ elapsedMs: number;+ status?: number;+ bytes?: number;+ sha256?: string;+ savedEngine?: string;+}+interface Record {+ state: 'running' | 'finished';+ passed: boolean;+ admissionIdleAndPaused: boolean;+ results: Result[];+}+const origin = 'https://kiln-private-qualification.invalid';+const check: (value: unknown) => asserts value = (value) => {+ if (!value) throw new Error('PRIVATE_LIFECYCLE_CHECK');+};+function object(value: unknown): { [key: string]: unknown } {+ check(value !== null && typeof value === 'object' && !Array.isArray(value));+ return value as { [key: string]: unknown };+}+function tool(value: unknown) {+ const result = object(value);+ check(result.isError !== true && Array.isArray(result.content));+ const text = result.content.map(object).find((item) => item.type === 'text');+ check(typeof text?.text === 'string');+ return object(JSON.parse(text.text));+}+function canonical(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;+ if (value && typeof value === 'object') {+ const item = object(value);+ return `{${Object.keys(item)+ .sort()+ .map((key) => `${JSON.stringify(key)}:${canonical(item[key])}`)+ .join(',')}}`;+ }+ return JSON.stringify(value);+}+function fullMaterial(value: unknown) {+ const fidelity = object(value);+ check(+ fidelity.delivered === 'full-material' &&+ fidelity.degraded === false &&+ fidelity.materialFaithful === true,+ );+}+function rejectPrivateData(value: unknown, source: string, material: string, depth = 0): void {+ check(depth < 32);+ if (typeof value === 'string') {+ check(!value.includes(source) && !value.includes(material));+ // MCP content may itself contain JSON. Inspect decoded strings as well as+ // ordinary object fields so escaping cannot hide a leaked source document.+ if (/^\s*[[{]/.test(value)) {+ let parsed: unknown;+ try {+ parsed = JSON.parse(value);+ } catch {+ return;+ }+ rejectPrivateData(parsed, source, material, depth + 1);+ }+ } else if (value && typeof value === 'object') {+ check(canonical(value) !== material);+ for (const child of Object.values(value)) rejectPrivateData(child, source, material, depth + 1);+ }+}+const hash = async (bytes: Uint8Array<ArrayBuffer>) =>+ Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (byte) =>+ byte.toString(16).padStart(2, '0'),+ ).join('');+function downloadPath(url: unknown, filename: string): string {+ check(typeof url === 'string');+ const parsed = new URL(url);+ check(+ parsed.origin === origin &&+ !parsed.username &&+ !parsed.password &&+ !parsed.search &&+ !parsed.hash,+ );+ check(/^\/downloads\/[a-f0-9]{64}\/[a-z.]+$/.test(parsed.pathname));+ check(parsed.pathname.endsWith(`/${filename}`));+ return parsed.pathname;+}+function request(+ id: number,+ method: string,+ params: { [key: string]: unknown },+ signal: AbortSignal,+) {+ const headers = new Headers({+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2026-07-28',+ 'mcp-method': method,+ });+ const name = params.name ?? params.uri;+ if (typeof name === 'string') headers.set('mcp-name', name);+ return new Request(`${origin}/mcp`, {+ method: 'POST',+ headers,+ signal,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id,+ method,+ params: {+ ...params,+ _meta: {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': { name: 'kiln-private-lifecycle', version: '1' },+ 'io.modelcontextprotocol/clientCapabilities': {},+ },+ },+ }),+ });+}+async function bounded<T>(+ work: Promise<T>,+ milliseconds: number,+ abort?: AbortController,+): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ work,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ abort?.abort();+ reject(new Error('PRIVATE_LIFECYCLE_DEADLINE'));+ }, milliseconds);+ }),+ ]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}+const materialDraft = {+ materialId: 'qualification-stone',+ name: 'Private qualification stone',+ tileable: true,+ sources: [+ {+ id: 'authored',+ kind: 'procedural',+ provider: 'Kiln',+ creator: 'Fixture author',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ size: 8,+ usage: 'albedo',+ layers: [+ { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },+ ],+ },+ },+ ],+};++/** Fixed native stage. The outer private driver owns synthetic credentials and+ * the durable VM allowance; neither can be selected by these request bodies.+ */+export async function runLifecycleOnce(+ storage: DurableObjectStorage,+ ports: Ports,+): Promise<Record> {+ const record: Record = {+ state: 'running',+ passed: false,+ admissionIdleAndPaused: false,+ results: [],+ };+ const claimed = await storage.transaction(async (tx) => {+ if (await tx.get('native-lifecycle')) return false;+ await tx.put('native-lifecycle', record);+ return true;+ });+ if (!claimed) return (await storage.get<Record>('native-lifecycle'))!;+ let opened = false,+ retained = 0,+ code = '',+ ref = '',+ assetId = '',+ revisionId = '',+ glbHash = '';+ let material: { [key: string]: unknown } = {},+ materialRevision = '';+ let downloads: { [key: string]: unknown } = {};+ try {+ check(/^sha256:[a-f0-9]{64}$/.test(ports.expectedImage));+ opened = true;+ await bounded(ports.open(), 10000);+ for (const [index, name] of lifecycleCases.entries()) {+ const started = Date.now();+ const result: Result = { name, passed: false, elapsedMs: 0 };+ const controller = new AbortController();+ try {+ const selection = { collection: 'project', assetId, revisionId };+ const materialDependencies = [+ {+ resourceId: 'qualification-stone',+ revisionId: materialRevision,+ sha256: materialRevision,+ },+ ];+ if (name === 'drop-live-material') {+ await bounded(ports.dropMaterial('qualification-stone', materialRevision), 10000);+ } else {+ let response: Response;+ let resource = false;+ let rpc = true;+ if (name.endsWith('-download')) {+ rpc = false;+ const file =+ name === 'glb-download'+ ? 'asset.glb'+ : name === 'material-download'+ ? 'materials.kiln.json'+ : 'source.kiln.js';+ const account =+ name === 'foreign-download'+ ? 'other'+ : name === 'anonymous-download'+ ? 'anonymous'+ : 'owner';+ response = await bounded(+ ports.download(account, downloadPath(downloads[file], file), controller.signal),+ 15000,+ controller,+ );+ } else {+ let method = 'tools/call';+ let params: { [key: string]: unknown };+ switch (name) {+ case 'material-create':+ params = {+ name: 'kiln_material_create_procedural',+ arguments: { draft: materialDraft },+ };+ break;+ case 'material-get':+ case 'foreign-material':+ case 'imported-material':+ params = {+ name: 'kiln_material_get',+ arguments: {+ materialId: 'qualification-stone',+ revisionId: materialRevision,+ },+ };+ break;+ case 'render':+ params = {+ name: 'kiln_render',+ arguments: { code, materialDependencies, capture: { preset: '1x1' } },+ };+ break;+ case 'rerender':+ params = {+ name: 'kiln_render',+ arguments: { programRef: ref, materialDependencies, capture: { preset: '1x1' } },+ };+ break;+ case 'save':+ params = {+ name: 'kiln_save',+ arguments: {+ programRef: ref,+ materialDependencies,+ collection: 'project',+ name: 'Private material qualification',+ },+ };+ break;+ case 'restore':+ params = { name: 'kiln_assets_restore', arguments: selection };+ break;+ case 'export':+ params = { name: 'kiln_export', arguments: selection };+ break;+ case 'import':+ params = {+ name: 'kiln_import',+ arguments: { ...selection, sourceCollection: 'project', collection: 'library' },+ };+ break;+ case 'glb':+ case 'manifest':+ method = 'resources/read';+ resource = true;+ params = {+ uri: `kiln://assets/project/${assetId}/${revisionId}/${name === 'glb' ? 'asset.glb' : 'manifest.json'}`,+ };+ break;+ default:+ params = { name: 'kiln_source', arguments: { programRef: ref } };+ }+ response = await bounded(+ ports.mcp(+ name.startsWith('foreign-') ? 'other' : 'owner',+ request(index + 1, method, params, controller.signal),+ ),+ 140000,+ controller,+ );+ }+ const bytes = await bounded(+ readBounded(response.body, 8 * 1024 * 1024, controller.signal),+ 10000,+ controller,+ );+ retained += bytes.byteLength;+ check(retained <= 64 * 1024 * 1024);+ result.status = response.status;+ result.bytes = bytes.byteLength;+ result.sha256 = await hash(bytes);+ await bounded(ports.retain(name, bytes), 10000);+ if (name === 'quota') check(response.status === 429);+ else if (name === 'foreign-download' || name === 'anonymous-download') {+ check(response.status === (name === 'foreign-download' ? 404 : 401));+ check(result.sha256 !== glbHash);+ rejectPrivateData(new TextDecoder().decode(bytes), code, canonical(material));+ } else {+ check(response.status === 200);+ if (!rpc) {+ check(+ response.headers+ .get('cache-control')+ ?.split(',')+ .map((value) => value.trim())+ .includes('no-store'),+ );+ if (name === 'glb-download') check(result.sha256 === glbHash);+ else if (name === 'source-download') check(new TextDecoder().decode(bytes) === code);+ else {+ const closure = object(JSON.parse(new TextDecoder().decode(bytes)));+ check(Array.isArray(closure.records) && closure.records.length === 1);+ check(canonical(object(closure.records[0]).manifest) === canonical(material));+ }+ } else {+ const message = object(+ JSON.parse(+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes),+ ),+ );+ check(message.id === index + 1);+ if (name.startsWith('foreign-')) {+ rejectPrivateData(message, code, canonical(material));+ check(message.error !== undefined || object(message.result).isError === true);+ } else {+ check(message.error === undefined);+ const payload = object(message.result);+ if (resource) {+ check(Array.isArray(payload.contents) && payload.contents.length === 1);+ const item = object(payload.contents[0]);+ if (name === 'glb') {+ check(typeof item.blob === 'string');+ const glb = Uint8Array.from(atob(item.blob), (char) => char.charCodeAt(0));+ check(glb.byteLength >= 20);+ const header = new DataView(glb.buffer);+ check(+ header.getUint32(0, true) === 0x46546c67 &&+ header.getUint32(4, true) === 2 &&+ header.getUint32(8, true) === glb.byteLength,+ );+ glbHash = await hash(glb);+ } else {+ check(typeof item.text === 'string');+ const manifest = object(JSON.parse(item.text));+ check(manifest.assetId === assetId && manifest.revisionId === revisionId);+ fullMaterial(object(manifest.preview).fidelity);+ const engine = object(manifest.build).engine;+ check(engine === `cloudflare-container:${ports.expectedImage}`);+ result.savedEngine = engine;+ }+ } else {+ const value = tool(payload);+ if (name === 'material-create') {+ material = object(value.material);+ check(+ material.materialId === 'qualification-stone' &&+ typeof material.revisionId === 'string' &&+ /^sha256:[a-f0-9]{64}$/.test(material.revisionId),+ );+ materialRevision = material.revisionId;+ const spec = object(value.portableSpec);+ code = `async function build(){const r=createRoot('Root');const m=await compilePortableMaterialSpecV2(${JSON.stringify(spec)});createPart('Body',boxGeo(1,1,1),m,{parent:r});return r;}`;+ } else if (name === 'material-get' || name === 'imported-material')+ check(canonical(value.material) === canonical(material));+ else if (name === 'render' || name === 'rerender') {+ check(+ value.ok === true &&+ typeof value.programRef === 'string' &&+ /^(?:p_|sha256:)[a-f0-9]{64}$/.test(value.programRef),+ );+ if (name === 'rerender') check(value.programRef === ref);+ ref = value.programRef;+ fullMaterial(value.viewFidelity);+ check(+ (payload.content as unknown[]).some((item) => object(item).type === 'image'),+ );+ } else if (name === 'save') {+ check(value.ok === true);+ const asset = object(value.asset);+ check(+ typeof asset.assetId === 'string' && typeof asset.revisionId === 'string',+ );+ assetId = asset.assetId;+ revisionId = asset.revisionId;+ check([assetId, revisionId].every((id) => /^[a-z][a-z0-9_-]{0,79}$/.test(id)));+ downloads = object(value.downloadUrls);+ } else if (name === 'restore') check(value.programRef === ref);+ else if (name === 'source')+ check(value.code === code && value.nextOffset === null);+ else check(value.ok === true);+ }+ }+ }+ }+ }+ const status = await bounded(ports.status(), 10000);+ check(status.activeRequests === 0 && status.pendingCleanup === 0);+ result.passed = true;+ } catch {+ /* Fixed case label and outcome only; never retain exceptions. */+ } finally {+ controller.abort();+ }+ result.elapsedMs = Date.now() - started;+ record.results.push(result);+ await storage.put('native-lifecycle', record);+ if (!result.passed) break;+ }+ } catch {+ /* A partial or failed setup cannot authorize another run. */+ } finally {+ if (opened) {+ const closing = await Promise.allSettled([+ bounded(ports.close(), 10000),+ bounded(ports.pause(), 10000),+ ]);+ try {+ const status = await bounded(ports.status(), 10000);+ record.admissionIdleAndPaused =+ closing.every((result) => result.status === 'fulfilled') &&+ status.paused &&+ status.activeRequests === 0 &&+ status.pendingCleanup === 0;+ } catch {+ record.admissionIdleAndPaused = false;+ }+ }+ record.state = 'finished';+ record.passed =+ record.admissionIdleAndPaused &&+ record.results.length === lifecycleCases.length &&+ record.results.every((result) => result.passed);+ await storage.put('native-lifecycle', record);+ }+ return record;+}diff --git a/hosting/probe/lifecycle-worker.ts b/hosting/probe/lifecycle-worker.tsnew file mode 100644index 00000000..e64ecd03--- /dev/null+++ b/hosting/probe/lifecycle-worker.ts@@ -0,0 +1,196 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { lifecycleAllowance, type LifecycleAllowanceEnv } from './lifecycle-binding';+import { runGatewayPreflight, type PreflightEnv } from './gateway-preflight';+import { runLifecycleOnce } from './lifecycle-run';+import {+ assertQualification,+ privateJson,+ qualificationOrigin,+ syntheticAccount,+} from './qualification-accounts';+import { tenantForAccount } from '../src/tenant-identity';+import type { KilnCompute } from '../src/admission-worker';+import { qualificationControl as control } from './qualification-rpc';++interface Env extends PreflightEnv, LifecycleAllowanceEnv {+ RUN: DurableObjectNamespace<KilnLifecycleRun>;+ EXPECTED_IMAGE: string;+}+interface Receipt {+ state: 'running' | 'finished' | 'stopped';+ passed: boolean;+ preflight: Awaited<ReturnType<typeof runGatewayPreflight>> | null;+ native: Awaited<ReturnType<typeof runLifecycleOnce>> | null;+}+type ComputeStatus = Awaited<ReturnType<KilnCompute['health']>>;+export class KilnLifecycleRun extends DurableObject<Env> {+ private async checkRunning() {+ if (await this.ctx.storage.get('operator-stopped')) throw new Error('PRIVATE_OPERATOR_STOPPED');+ }+ private async seal() {+ const [allowance, paused] = await Promise.allSettled([+ control(lifecycleAllowance(this.env).close()),+ control<ComputeStatus>(this.env.CONTROL.setPaused(true)),+ ]);+ return (+ allowance.status === 'fulfilled' &&+ paused.status === 'fulfilled' &&+ paused.value.paused &&+ paused.value.activeRequests === 0 &&+ paused.value.pendingCleanup === 0+ );+ }+ async run(): Promise<Receipt> {+ assertQualification(this.env);+ const record: Receipt = { state: 'running', passed: false, preflight: null, native: null };+ const claimed = await this.ctx.storage.transaction(async (tx) => {+ if (await tx.get('combined-lifecycle')) return false;+ if (await tx.get('operator-stopped')) record.state = 'stopped';+ await tx.put('combined-lifecycle', record);+ return record.state === 'running';+ });+ if (!claimed) return (await this.ctx.storage.get<Receipt>('combined-lifecycle'))!;+ try {+ // Stop admission and consume the allowance on interruption, even if the+ // observer goes away. No alarm can reopen or retry this one-use sequence.+ await this.ctx.storage.setAlarm(Date.now() + 15 * 60 * 1000);+ await this.checkRunning();+ record.preflight = await runGatewayPreflight(this.ctx.storage, this.env);+ await this.ctx.storage.put('combined-lifecycle', record);+ if (!record.preflight.passed) throw new Error('PRIVATE_PREFLIGHT_FAILED');+ await this.checkRunning();+ // Fresh grants for the same two permanent fixture accounts. Alice's old+ // revoked connection stays revoked. Secrets remain in this invocation.+ const owner = await syntheticAccount(this.env, 'alice');+ await this.checkRunning();+ const other = await syntheticAccount(this.env, 'bob');+ await this.checkRunning();+ const tenant = this.env.TENANTS.getByName(+ await tenantForAccount(qualificationOrigin, owner.account.id),+ );+ const accounts = { owner, other };+ record.native = await runLifecycleOnce(this.ctx.storage, {+ expectedImage: this.env.EXPECTED_IMAGE,+ open: async () => {+ await this.checkRunning();+ await control(lifecycleAllowance(this.env).open());+ await this.checkRunning();+ await control(this.env.CONTROL.setPaused(false));+ await this.checkRunning();+ },+ close: () => control(lifecycleAllowance(this.env).close()),+ pause: async () => {+ await control(this.env.CONTROL.setPaused(true));+ },+ status: () => control(this.env.COMPUTE.health()),+ mcp: async (account, request) => {+ await this.checkRunning();+ const headers = new Headers(request.headers);+ headers.set('authorization', `Bearer ${accounts[account].accessToken}`);+ return this.env.GATEWAY.fetch(new Request(request, { headers }));+ },+ download: async (account, path, signal) => {+ await this.checkRunning();+ return this.env.GATEWAY.fetch(+ new Request(`${qualificationOrigin}${path}`, {+ // Anonymous GET would redirect to login; HEAD exercises denial.+ method: account === 'anonymous' ? 'HEAD' : 'GET',+ signal,+ headers: account === 'anonymous' ? {} : { cookie: accounts[account].cookie },+ }),+ );+ },+ dropMaterial: async (materialId, revisionId) => {+ await this.checkRunning();+ if (+ materialId !== 'qualification-stone' ||+ !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(revisionId)+ )+ throw new Error('PRIVATE_MATERIAL_SELECTION');+ const group = await privateJson(+ await tenant.fetch(+ `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,+ ),+ );+ if (typeof group.id !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(group.id))+ throw new Error('PRIVATE_MATERIAL_GROUP');+ await privateJson(+ await tenant.fetch(`https://tenant.internal/internal/groups/${group.id}`, {+ method: 'DELETE',+ }),+ );+ },+ retain: async (name, bytes) => {+ await this.env.ARTIFACTS.put(`probe-evidence/native-${name}.bin`, bytes, {+ httpMetadata: { contentType: 'application/octet-stream' },+ });+ },+ });+ record.passed = record.native.passed;+ } catch {+ record.passed = false;+ } finally {+ const sealed = await this.seal();+ await this.ctx.storage.transaction(async (tx) => {+ const stopped = Boolean(await tx.get('operator-stopped'));+ record.state = stopped ? 'stopped' : 'finished';+ record.passed &&= sealed && !stopped;+ await tx.put('combined-lifecycle', record);+ });+ // Recover promptly when either control acknowledgement remains unknown.+ if (sealed) await this.ctx.storage.deleteAlarm();+ else await this.ctx.storage.setAlarm(Date.now() + 60000);+ }+ return record;+ }+ async stop() {+ await this.ctx.storage.transaction(async (tx) => {+ await tx.put('operator-stopped', true);+ const record = await tx.get<Receipt>('combined-lifecycle');+ if (record?.state === 'running') {+ record.state = 'stopped';+ record.passed = false;+ await tx.put('combined-lifecycle', record);+ }+ });+ const sealed = await this.seal();+ if (!sealed) await this.ctx.storage.setAlarm(Date.now() + 60000);+ else await this.ctx.storage.deleteAlarm();+ return this.status();+ }+ async alarm() {+ await this.stop();+ }+ async status() {+ const [record, budget, admission] = await Promise.all([+ this.ctx.storage.get<Receipt>('combined-lifecycle'),+ control(lifecycleAllowance(this.env).status()),+ control(this.env.COMPUTE.health()),+ ]);+ return {+ record: record ?? null,+ budget: budget ?? null,+ admission,+ alarmAt: await this.ctx.storage.getAlarm(),+ operatorStopped: Boolean(await this.ctx.storage.get('operator-stopped')),+ };+ }+}+export class KilnLifecycleControl extends WorkerEntrypoint<Env> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }+ async runFixed() {+ using result = await this.env.RUN.getByName('lifecycle-v1').run();+ return structuredClone(result);+ }+ async status() {+ using result = await this.env.RUN.getByName('lifecycle-v1').status();+ return structuredClone(result);+ }+ async stop() {+ using result = await this.env.RUN.getByName('lifecycle-v1').stop();+ return structuredClone(result);+ }+}+export default { fetch: () => new Response('Not found', { status: 404 }) };diff --git a/hosting/probe/manifest-startup-worker.ts b/hosting/probe/manifest-startup-worker.tsnew file mode 100644index 00000000..bdee9dcd--- /dev/null+++ b/hosting/probe/manifest-startup-worker.ts@@ -0,0 +1,32 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ManagedStartupDiagnostic } from './startup-diagnostic';++interface Bindings {+ STARTUP_JOB: DurableObjectNamespace<KilnManifestStartupJob>;+}++export class KilnManifestStartupJob extends DurableObject {+ async runFixed() {+ return new ManagedStartupDiagnostic(this.ctx, 'kiln-manifest').run();+ }++ async alarm() {+ await new ManagedStartupDiagnostic(this.ctx, 'kiln-manifest').alarm();+ }+}++export class KilnManifestStartupControl extends WorkerEntrypoint<Bindings> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }++ async runFixed() {+ return this.env.STARTUP_JOB.getByName('kiln-manifest-2026-10-06').runFixed();+ }+}++export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler<Bindings>;diff --git a/hosting/probe/manifest-startup.wrangler.jsonc b/hosting/probe/manifest-startup.wrangler.jsoncnew file mode 100644index 00000000..774c6104--- /dev/null+++ b/hosting/probe/manifest-startup.wrangler.jsonc@@ -0,0 +1,35 @@+{+ "name": "kiln-private-manifest-startup",+ "main": "./manifest-startup-worker.ts",+ "compatibility_date": "2026-10-06",+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": { "cpu_ms": 30000, "subrequests": 50 },+ "observability": {+ "enabled": true,+ "logs": { "enabled": true, "invocation_logs": true }+ },+ "containers": [+ {+ "name": "kiln-private-manifest-startup",+ "class_name": "KilnManifestStartupJob",+ "scheduling_policy": "durable_object",+ "images": {+ "control": {+ "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8"+ }+ },+ "observability": { "logs": { "enabled": false } }+ }+ ],+ "durable_objects": {+ "bindings": [+ { "name": "STARTUP_JOB", "class_name": "KilnManifestStartupJob" }+ ]+ },+ "exports": {+ "KilnManifestStartupControl": { "type": "worker" },+ "KilnManifestStartupJob": { "type": "durable-object", "storage": "sqlite" }+ }+}diff --git a/hosting/probe/observe-container.ts b/hosting/probe/observe-container.tsnew file mode 100644index 00000000..3a5b1714--- /dev/null+++ b/hosting/probe/observe-container.ts@@ -0,0 +1,35 @@+// Operator-only diagnostics. Never return native exception text or process output.+const operations = new Set([+ 'start',+ 'monitor',+ 'setInactivityTimeout',+ 'exec',+ 'inspect',+ 'destroy',+]);++export function observeContainer(actual: Container, script?: string) {+ let failedOperation: string | undefined;+ const container = new Proxy(actual, {+ get(target, key) {+ const value = Reflect.get(target, key);+ if (typeof value !== 'function') return value;+ if (typeof key !== 'string' || !operations.has(key)) return value.bind(target);+ return (...args: unknown[]) => {+ const fail = (error: unknown): never => {+ failedOperation ??= key;+ throw error;+ };+ try {+ if (key === 'exec' && script)+ args[0] = ['/usr/local/bin/node', '--input-type=module', '-e', script];+ const result = value.apply(target, args);+ return result instanceof Promise ? result.catch(fail) : result;+ } catch (error) {+ return fail(error);+ }+ };+ },+ });+ return { container, failure: () => failedOperation };+}diff --git a/hosting/probe/qualification-accounts.ts b/hosting/probe/qualification-accounts.tsnew file mode 100644index 00000000..69dcf2d2--- /dev/null+++ b/hosting/probe/qualification-accounts.ts@@ -0,0 +1,133 @@+import { OAuthAuthorizationServer } from '@cloudflare/workers-oauth-provider';+import { D1BrowserSessions } from '../src/browser-sessions';+import { D1Connections } from '../src/connections';+import { readBounded, sha256 } from '../src/http';++export const qualificationOrigin = 'https://kiln-private-qualification.invalid';+export interface QualificationAccountsEnv {+ PUBLIC_ORIGIN: string;+ QUALIFICATION_MODE: string;+ ACCOUNTS: D1Database;+ OAUTH_KV: KVNamespace;+ GATEWAY: Fetcher;+}+export function assertQualification(env: QualificationAccountsEnv): void {+ if (+ env.PUBLIC_ORIGIN !== qualificationOrigin ||+ env.QUALIFICATION_MODE !== 'isolated-synthetic-v1'+ )+ throw new Error('PRIVATE_QUALIFICATION_ONLY');+}+export function qualificationOAuth(env: QualificationAccountsEnv) {+ assertQualification(env);+ return new OAuthAuthorizationServer<QualificationAccountsEnv>({+ issuer: qualificationOrigin,+ resources: [`${qualificationOrigin}/mcp`],+ authorizeEndpoint: `${qualificationOrigin}/authorize`,+ tokenEndpoint: `${qualificationOrigin}/oauth/token`,+ clientRegistrationEndpoint: `${qualificationOrigin}/register`,+ scopesSupported: ['kiln:use'],+ accessTokenTTL: 900,+ refreshTokenTTL: 30 * 86400,+ onError: () => {},+ }).getOAuthApi(env);+}+export async function privateJson(+ response: Response,+ status = 200,+): Promise<Record<string, unknown>> {+ const bytes = await readBounded(response.body, 65536);+ if (response.status !== status) throw new Error('PRIVATE_QUALIFICATION_RESPONSE');+ const value: unknown = JSON.parse(new TextDecoder().decode(bytes));+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new Error('PRIVATE_QUALIFICATION_RESPONSE');+ return value as Record<string, unknown>;+}++/** Synthetic private fixture only. This bypasses upstream consent, not token validation.+ * Credentials stay inside the private runner; never put this module in a gateway bundle.+ */+export async function syntheticAccount(env: QualificationAccountsEnv, name: 'alice' | 'bob') {+ assertQualification(env);+ const identity = { issuer: 'https://github.com', subject: `kiln-private-qualification-${name}` };+ const sessions = new D1BrowserSessions(env.ACCOUNTS, qualificationOrigin);+ const browser = await sessions.issue(identity);+ const redirect = 'http://127.0.0.1:49317/callback';+ const client = await privateJson(+ await env.GATEWAY.fetch(+ new Request(`${qualificationOrigin}/register`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ client_name: 'Kiln private qualification',+ redirect_uris: [redirect],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth_method: 'none',+ }),+ }),+ ),+ 201,+ );+ if (typeof client.client_id !== 'string') throw new Error('PRIVATE_QUALIFICATION_CLIENT');+ const verifier = `${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().replaceAll('-', '')}`;+ const query = new URLSearchParams({+ client_id: client.client_id,+ response_type: 'code',+ redirect_uri: redirect,+ resource: `${qualificationOrigin}/mcp`,+ scope: 'kiln:use',+ state: crypto.randomUUID(),+ code_challenge: await sha256(verifier),+ code_challenge_method: 'S256',+ });+ const api = qualificationOAuth(env);+ const request = await api.parseAuthRequest(+ new Request(`${qualificationOrigin}/authorize?${query}`),+ );+ const connections = new D1Connections(env.ACCOUNTS);+ const props = await connections.create(+ browser.account,+ request,+ await api.describeConsent(request),+ );+ const { redirectTo } = await api.completeAuthorization({+ request,+ userId: browser.account.id,+ metadata: { connectionId: props.connectionId },+ scope: request.scope,+ props,+ revokeExistingGrants: false,+ });+ const code = new URL(redirectTo).searchParams.get('code');+ if (!code) throw new Error('PRIVATE_QUALIFICATION_CODE');+ const token = await privateJson(+ await env.GATEWAY.fetch(+ new Request(`${qualificationOrigin}/oauth/token`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'authorization_code',+ code,+ code_verifier: verifier,+ client_id: client.client_id,+ redirect_uri: redirect,+ resource: `${qualificationOrigin}/mcp`,+ }),+ }),+ ),+ );+ if (typeof token.access_token !== 'string' || typeof token.refresh_token !== 'string')+ throw new Error('PRIVATE_QUALIFICATION_TOKEN');+ // Keep only the Cookie pair, never the Set-Cookie attributes.+ const cookie = browser.cookie.split(';')[0]!;+ return {+ identity,+ account: browser.account,+ connectionId: props.connectionId,+ cookie,+ accessToken: token.access_token,+ refreshToken: token.refresh_token,+ clientId: client.client_id,+ };+}diff --git a/hosting/probe/qualification-rpc.ts b/hosting/probe/qualification-rpc.tsnew file mode 100644index 00000000..e4e0053c--- /dev/null+++ b/hosting/probe/qualification-rpc.ts@@ -0,0 +1,24 @@+const dispose = (value: unknown) =>+ (value as { [Symbol.dispose]?: () => void } | null | undefined)?.[Symbol.dispose]?.();++/** Control RPCs return JSON values only. Detach them and release both the RPC+ * promise and result capabilities so an observer cannot pin a completed run. */+export async function qualificationControl<T>(work: Promise<T>): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const result = await Promise.race([+ work,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('PRIVATE_CONTROL_DEADLINE')), 10000);+ }),+ ]);+ try {+ return structuredClone(result);+ } finally {+ dispose(result);+ }+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ dispose(work);+ }+}diff --git a/hosting/probe/qualification.wrangler.jsonc b/hosting/probe/qualification.wrangler.jsoncnew file mode 100644index 00000000..fe0ef28d--- /dev/null+++ b/hosting/probe/qualification.wrangler.jsonc@@ -0,0 +1,52 @@+{+ "name": "kiln-private-manifest-qualification",+ "main": "./worker.ts",+ "compatibility_date": "2026-10-06",+ "compatibility_flags": [+ "enable_ctx_exports"+ ],+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": {+ "cpu_ms": 30000,+ "subrequests": 50+ },+ "observability": {+ "enabled": true,+ "logs": {+ "enabled": true,+ "invocation_logs": true+ }+ },+ "containers": [+ {+ "name": "kiln-private-manifest-qualification-jobs",+ "class_name": "KilnProbeJob",+ "scheduling_policy": "durable_object",+ "images": {+ "kiln": {+ "image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8"+ }+ },+ "observability": {+ "logs": {+ "enabled": false+ }+ }+ }+ ],+ "exports": {+ "KilnProbeControl": {+ "type": "worker"+ },+ "KilnProbeRun": {+ "type": "durable-object",+ "storage": "sqlite"+ },+ "KilnProbeJob": {+ "type": "durable-object",+ "storage": "sqlite"+ }+ }+}diff --git a/hosting/probe/resilience-execution.ts b/hosting/probe/resilience-execution.tsnew file mode 100644index 00000000..8c8fb93d--- /dev/null+++ b/hosting/probe/resilience-execution.ts@@ -0,0 +1,173 @@+import { ContainerEvaluationJob, ContainerJobFailure } from '../src/container-job';+import { engineRequest } from './fixtures';+import { resilienceFixtures } from './resilience-fixtures';+import { observeResilience } from './resilience-observation';+import { checkResilienceResult } from './resilience-result';+import { resilienceCases, type ResilienceCase, type ResilienceResult } from './resilience-run';++export const resilienceImage =+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99';+type Context = Pick<DurableObjectState, 'container' | 'storage'>;+interface ProbeClaim {+ name: ResilienceCase;+ started: number;+}++/** Only fixed test programs and a single deliberate cleanup fault enter this class. */+export class ResilienceExecution {+ constructor(private readonly context: Context) {}++ async run(name: ResilienceCase): Promise<ResilienceResult> {+ if (!resilienceCases.includes(name)) throw new Error('Unknown fixed case');+ const actual = this.context.container;+ if (!actual) return { name, passed: false, reason: 'CONTAINER_UNAVAILABLE' };+ if (actual.images.kiln !== resilienceImage)+ return { name, passed: false, reason: 'IMAGE_UNAVAILABLE' };+ const started = Date.now();+ const claimed = await this.context.storage.transaction(async (transaction) => {+ if (await transaction.get('probe')) return false;+ await transaction.put('probe', { name, started } satisfies ProbeClaim);+ return true;+ });+ if (!claimed) return (await this.read()) ?? { name, passed: false, reason: 'ALREADY_CLAIMED' };+ const abort = new AbortController();+ let cancelTimer: ReturnType<typeof setTimeout> | undefined;+ let readyAt: number | undefined;+ const observed = observeResilience(+ actual,+ resilienceFixtures[name] ?? '',+ () => {+ readyAt = Date.now();+ if (name === 'native-cancel' || name === 'alarm-recovery')+ cancelTimer = setTimeout(() => abort.abort(), 250);+ },+ name === 'alarm-recovery',+ );+ const deadlineMs = name === 'native-deadline' || name === 'alarm-recovery' ? 15_000 : 60_000;+ let output: Uint8Array | undefined;+ let reason: string | undefined;+ try {+ // The final engine check uses the real image entry without substitution.+ output = await new ContainerEvaluationJob({+ container: name === 'engine-after' ? actual : observed.container,+ storage: this.context.storage,+ }).run(name === 'engine-after' ? engineRequest : new TextEncoder().encode('{}'), {+ deadlineMs,+ maxResponseBytes:+ name === 'stdout-flood' ? 1024 : name === 'software-views' ? 512 * 1024 : 64 * 1024,+ signal: abort.signal,+ });+ } catch (error) {+ reason = error instanceof ContainerJobFailure ? error.code : 'CHECK_FAILED';+ } finally {+ if (cancelTimer !== undefined) clearTimeout(cancelTimer);+ }+ const job = await this.context.storage.get<{ state: string }>('job');+ // Production controller marks finished only after bounded destroy+inspection.+ const stopped = job?.state === 'finished' && !actual.running;+ const common = {+ image: resilienceImage,+ elapsedMs: Date.now() - started,+ ready: observed.ready(),+ readyAfterMs: readyAt === undefined ? undefined : readyAt - started,+ exitCode: observed.exitCode(),+ };+ let result: ResilienceResult;+ if (+ name === 'alarm-recovery' &&+ reason === 'CLEANUP_FAILED' &&+ actual.running &&+ observed.ready() &&+ job?.state === 'running'+ ) {+ result = {+ name,+ passed: false,+ stopped: false,+ pendingAlarm: true,+ reason: 'AWAITING_DURABLE_ALARM',+ ...common,+ };+ } else {+ result = {+ ...(await checkResilienceResult({+ name,+ stopped,+ ready: observed.ready(),+ reason,+ output,+ })),+ ...common,+ };+ // A startup timeout must not masquerade as sustained native-loop evidence.+ if (+ name === 'native-deadline' &&+ (readyAt === undefined || readyAt - started > deadlineMs - 1000)+ )+ result.passed = false;+ }+ await this.context.storage.put('probeResult', result);+ return result;+ }++ read() {+ return this.context.storage.get<ResilienceResult>('probeResult');+ }++ async alarm(): Promise<void> {+ await new ContainerEvaluationJob(this.context).alarm();+ const [claim, result, job] = await Promise.all([+ this.context.storage.get<ProbeClaim>('probe'),+ this.read(),+ this.context.storage.get<{ state: string; outcome: string }>('job'),+ ]);+ if (claim?.name !== 'alarm-recovery' || !result?.pendingAlarm || job?.state !== 'finished')+ return;+ const passed =+ job.outcome === 'DEADLINE_EXCEEDED' &&+ !this.context.container?.running &&+ result.ready === true;+ await this.context.storage.put('probeResult', {+ ...result,+ passed,+ stopped: !this.context.container?.running,+ pendingAlarm: false,+ reason: passed ? 'ALARM_RECOVERED' : 'RECOVERY_FAILED',+ elapsedMs: Date.now() - claim.started,+ } satisfies ResilienceResult);+ }++ /** Teardown after observation expires. It can never turn failed recovery into a pass. */+ async stopUnconfirmed(): Promise<ResilienceResult> {+ const prior = await this.read();+ if (!prior?.pendingAlarm)+ return prior ?? { name: 'alarm-recovery', passed: false, reason: 'NO_RECOVERY' };+ let timer: ReturnType<typeof setTimeout> | undefined;+ let stopped = false;+ try {+ const actual = this.context.container!;+ stopped = await Promise.race([+ (async () => {+ await actual.destroy();+ return (await actual.inspect()) === null && !actual.running;+ })(),+ new Promise<false>((resolve) => {+ timer = setTimeout(() => resolve(false), 5000);+ }),+ ]);+ } catch {+ /* Preserve failure; the operator must reconcile any live instance. */+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+ const result = {+ ...prior,+ passed: false,+ pendingAlarm: false,+ stopped,+ reason: 'ALARM_NOT_OBSERVED',+ };+ await this.context.storage.put('probeResult', result);+ return result;+ }+}diff --git a/hosting/probe/resilience-fixtures.ts b/hosting/probe/resilience-fixtures.tsnew file mode 100644index 00000000..26a708f6--- /dev/null+++ b/hosting/probe/resilience-fixtures.ts@@ -0,0 +1,76 @@+import { nativeFixtures } from './fixtures';++const prefix = 'import fs from "node:fs";fs.readFileSync(0);';+const ready = 'fs.writeSync(1,"KILN_PROBE_READY\\n");';+const busy = `${prefix}+ const {spawn}=await import('node:child_process');+ const child=spawn(process.execPath,['-e','process.title="kiln-resilience-child";for(;;){}'],{detached:true,stdio:'ignore',env:{},cwd:'/tmp'});+ child.unref();await new Promise(resolve=>setTimeout(resolve,100));+ if(!Number.isSafeInteger(child.pid))throw new Error('Missing child');+ process.kill(child.pid,0);${ready}for(;;){}`;+const renderPrefix = `${prefix}+ const {createEvaluatorRequestV2,evaluateEvaluatorRequestV2,decodeEvaluatorResultV2}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/evaluator/index.js');+ const {createRequire}=await import('node:module');+ const {PNG}=createRequire('/opt/kiln/node_modules/@instruktlabs/kiln/package.json')('pngjs');+ const finishJson=value=>new Promise((resolve,reject)=>process.stdout.write(JSON.stringify(value),error=>error?reject(error):resolve()));+ async function evaluate(code){+ const {json}=createEvaluatorRequestV2({requestId:'resilience-render',code,maxGlbBytes:2097152});+ const wire=await evaluateEvaluatorRequestV2(json,{}, {deadlineMs:60000,maxResponseBytes:8*1024*1024});+ const result=decodeEvaluatorResultV2(wire,2097152,'resilience-render');+ if(!result.ok)throw new Error('Evaluation failed');return result.render.glb;+ }`;++/** Fixed native code only, never user input or an engine security-boundary claim. */+export const resilienceFixtures: Record<string, string> = {+ ...nativeFixtures,+ 'native-deadline': busy,+ 'native-cancel': busy,+ 'alarm-recovery': busy,+ 'stdout-flood': `${prefix}${ready}await new Promise(r=>setTimeout(r,100));const chunk=Buffer.alloc(8192,120);for(;;)fs.writeSync(1,chunk);`,+ 'stderr-flood': `${prefix}${ready}await new Promise(r=>setTimeout(r,100));const chunk=Buffer.alloc(8192,120);for(;;)fs.writeSync(2,chunk);`,+ 'memory-limit': `${prefix}+ const {spawn}=await import('node:child_process');+ let counterSource='cgroup';+ const counter=()=>{+ if(counterSource==='cgroup'){+ try{const text=fs.readFileSync('/sys/fs/cgroup/memory.events','utf8');const m=text.match(/^oom_kill (\\d+)$/m);if(m)return Number(m[1]);}catch{}+ counterSource='vmstat';+ }+ const m=fs.readFileSync('/proc/vmstat','utf8').match(/^oom_kill (\\d+)$/m);if(!m)throw new Error('No OOM counter');return Number(m[1]);+ };+ const before=counter();+ const child=spawn(process.execPath,['-e', 'require("node:fs").writeFileSync("/proc/self/oom_score_adj","500");const allocated=[];for(let n=0;n<256;n++)allocated.push(Buffer.alloc(64*1024*1024,1));process.exit(2);'],{stdio:'ignore',env:{},cwd:'/tmp'});+ const ended=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('exit',(code,signal)=>resolve({code,signal}));});+ const oomKills=counter()-before;+ if(oomKills<1||ended.signal!=='SIGKILL')throw new Error('Memory exhaustion not observed');+ fs.writeSync(1,JSON.stringify({ok:true,oomKills,signal:ended.signal,counterSource}));process.exit(0);`,+ 'cpu-preview': `${renderPrefix}+ const glb=await evaluate('function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}');+ const {renderGlbViewCell}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/views/index.js');+ const view=await renderGlbViewCell(glb,{name:'qualification',dir:[1,0.4,1]},{size:128});+ const decoded=PNG.sync.read(Buffer.from(view.png));+ if(decoded.width!==128||decoded.height!==128)throw new Error('Invalid dimensions');+ await finishJson({ok:true,views:[{backdrop:'neutral',index:0,pngBase64:Buffer.from(view.png).toString('base64')}]});process.exit(0);`,+ 'software-views': `${renderPrefix}+ process.env.VK_ICD_FILENAMES='/opt/kiln/lvp-icd.json';+ const glb=await evaluate("function build(){const root=createRoot('Root');const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}");+ await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/register-hooks.mjs');+ const {initRenderer,renderGlb}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/renderer.mjs');+ const gpu=await import('/opt/kiln/node_modules/@instruktlabs/kiln/render-service/src/gpu.mjs');+ await initRenderer({allowSoftware:true});const device=await gpu.acquireGpu();+ if(device.software!==true)throw new Error('Expected software adapter');+ const views=[];+ for(const backdrop of ['neutral','dark','light']){+ const result=await renderGlb(glb,{size:128,viewDirs:[[1,0.4,1],[0,0,1]],backdrop});+ if(result.views.length!==2)throw new Error('Invalid views');+ for(const [index,png] of result.views.entries()){+ const decoded=PNG.sync.read(Buffer.from(png));if(decoded.width!==128||decoded.height!==128)throw new Error('Invalid dimensions');+ let red=0,green=0;+ for(let n=0;n<decoded.data.length;n+=4){const [r,g,b]=decoded.data.subarray(n,n+3);if(r>g+12&&r>b+12)red++;if(g>r+12&&g>b+12)green++;}+ if(red<21||green<21)throw new Error('Missing texture evidence');+ views.push({backdrop,index,red,green,pngBase64:Buffer.from(png).toString('base64')});+ }+ }+ gpu.markGpuShutdown();device.device.destroy();+ await finishJson({ok:true,software:true,views});process.exit(0);`,+};diff --git a/hosting/probe/resilience-observation.ts b/hosting/probe/resilience-observation.tsnew file mode 100644index 00000000..6c83c622--- /dev/null+++ b/hosting/probe/resilience-observation.ts@@ -0,0 +1,70 @@+const marker = new TextEncoder().encode('KILN_PROBE_READY\n');++/** Fixed probe instrumentation only; never imported by a production Worker. */+export function observeResilience(+ actual: Container,+ script: string,+ onReady: () => void,+ failFirstDestruction = false,+) {+ let ready = false;+ let index = 0;+ let invalidPrefix = false;+ let exitCode: number | undefined;+ let injectFailure = failFirstDestruction;+ const container = new Proxy(actual, {+ get(target, key) {+ if (key === 'destroy')+ return async () => {+ if (injectFailure) {+ injectFailure = false;+ throw new Error('Fixed probe destruction fault');+ }+ return target.destroy();+ };+ if (key === 'exec')+ return async (_command: string[], options?: ContainerExecOptions) => {+ const process = await target.exec(+ ['/usr/local/bin/node', '--input-type=module', '-e', script],+ options,+ );+ const exited = process.exitCode.then((code) => {+ exitCode = code;+ return code;+ });+ void exited.catch(() => {});+ const stdout = process.stdout?.pipeThrough(+ new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ if (!ready && !invalidPrefix) {+ for (const byte of chunk) {+ if (byte !== marker[index++]) {+ invalidPrefix = true;+ break;+ }+ if (index === marker.length) {+ ready = true;+ onReady();+ break;+ }+ }+ }+ controller.enqueue(chunk);+ },+ }),+ );+ return new Proxy(process, {+ get(processTarget, property) {+ if (property === 'stdout') return stdout;+ if (property === 'exitCode') return exited;+ const value = Reflect.get(processTarget, property);+ return typeof value === 'function' ? value.bind(processTarget) : value;+ },+ });+ };+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ return { container, ready: () => ready, exitCode: () => exitCode };+}diff --git a/hosting/probe/resilience-result.ts b/hosting/probe/resilience-result.tsnew file mode 100644index 00000000..5aaef769--- /dev/null+++ b/hosting/probe/resilience-result.ts@@ -0,0 +1,163 @@+import { glbDigest } from './fixtures';+import type { ResilienceCase, ResilienceResult } from './resilience-run';++async function sha(bytes: Uint8Array<ArrayBuffer>) {+ return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (b) =>+ b.toString(16).padStart(2, '0'),+ ).join('');+}+function bytes(value: unknown, max: number) {+ if (+ typeof value !== 'string' ||+ value.length > Math.ceil(max / 3) * 4 ||+ !/^[A-Za-z0-9+/]*={0,2}$/.test(value)+ )+ throw new Error('Invalid bytes');+ const decoded = Uint8Array.from(atob(value), (c) => c.charCodeAt(0));+ if (!decoded.length || decoded.length > max) throw new Error('Invalid byte limit');+ return decoded;+}+function object(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new Error('Invalid result');+ return value as Record<string, unknown>;+}+function validPng(png: Uint8Array): boolean {+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];+ if (png.length < 57 || signature.some((byte, index) => png[index] !== byte)) return false;+ const view = new DataView(png.buffer, png.byteOffset, png.byteLength);+ let offset = 8;+ let imageData = false;+ while (offset + 12 <= png.length) {+ const length = view.getUint32(offset);+ const end = offset + 12 + length;+ if (end > png.length) return false;+ const kind = String.fromCharCode(...png.subarray(offset + 4, offset + 8));+ let crc = 0xffffffff;+ for (let i = offset + 4; i < end - 4; i++) {+ crc ^= png[i]!;+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);+ }+ if ((crc ^ 0xffffffff) >>> 0 !== view.getUint32(end - 4)) return false;+ if (offset === 8) {+ if (+ kind !== 'IHDR' ||+ length !== 13 ||+ view.getUint32(16) !== 128 ||+ view.getUint32(20) !== 128+ )+ return false;+ // CPU previews are RGB; software material views may also carry alpha.+ if (+ png[24] !== 8 ||+ ![2, 6].includes(png[25]!) ||+ png[26] !== 0 ||+ png[27] !== 0 ||+ png[28] !== 0+ )+ return false;+ } else if (kind === 'IHDR') return false;+ if (kind === 'IDAT' && length > 0) imageData = true;+ if (kind === 'IEND') return length === 0 && imageData && end === png.length;+ offset = end;+ }+ return false;+}+const expectedFailures: Partial<Record<ResilienceCase, string>> = {+ 'native-deadline': 'DEADLINE_EXCEEDED',+ 'native-cancel': 'CANCELLED',+ 'stdout-flood': 'OUTPUT_LIMIT_EXCEEDED',+ 'stderr-flood': 'OUTPUT_LIMIT_EXCEEDED',+};++/** Strictly retain fixed proof fields; no arbitrary native diagnostic strings. */+export async function checkResilienceResult(input: {+ name: ResilienceCase;+ stopped: boolean;+ ready?: boolean;+ reason?: string;+ output?: Uint8Array;+}): Promise<ResilienceResult> {+ const result: ResilienceResult = { name: input.name, passed: false, stopped: input.stopped };+ if (!input.stopped) return { ...result, reason: 'CLEANUP_UNCONFIRMED' };+ const expected = expectedFailures[input.name];+ if (expected)+ return {+ ...result,+ passed: input.reason === expected && input.ready === true,+ reason: input.reason,+ };+ if (input.reason || !input.output || input.output.byteLength > 1024 * 1024) return result;+ try {+ const value = object(+ JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input.output)),+ );+ if (value.ok !== true) return result;+ if (input.name === 'engine-after') {+ if (value.version !== 'kiln.evaluator.result.v2' || value.requestId !== 'image-fixture')+ return result;+ const glb = bytes(object(value.render).glbBase64, 2097152);+ const digest = await sha(glb);+ return { ...result, passed: glb.length === 1912 && digest === glbDigest, digest };+ }+ if (input.name === 'memory-limit') {+ if (+ !Number.isSafeInteger(value.oomKills) ||+ (value.oomKills as number) < 1 ||+ (value.oomKills as number) > 100 ||+ !['cgroup', 'vmstat'].includes(String(value.counterSource)) ||+ value.signal !== 'SIGKILL'+ )+ return result;+ return {+ ...result,+ passed: true,+ oomKills: value.oomKills as number,+ counterSource: value.counterSource as string,+ };+ }+ if (input.name === 'cpu-preview' || input.name === 'software-views') {+ const expectedCount = input.name === 'cpu-preview' ? 1 : 6;+ if (!Array.isArray(value.views) || value.views.length !== expectedCount) return result;+ const views: NonNullable<ResilienceResult['views']> = [];+ for (const [i, entry] of value.views.entries()) {+ const view = object(entry);+ const png = bytes(view.pngBase64, 128 * 1024);+ if (!validPng(png)) return result;+ const backdrop =+ input.name === 'cpu-preview'+ ? 'neutral'+ : ['neutral', 'dark', 'light'][Math.floor(i / 2)]!;+ const index = input.name === 'cpu-preview' ? 0 : i % 2;+ if (view.backdrop !== backdrop || view.index !== index) return result;+ const digest = await sha(png);+ if (input.name === 'cpu-preview') {+ if (digest !== '75be56a750d986a9d444328aa6ec3c5b8555ede64734b1f83ac6860b6939e527')+ return result;+ } else if (+ value.software !== true ||+ !Number.isSafeInteger(view.red) ||+ !Number.isSafeInteger(view.green) ||+ (view.red as number) < 21 ||+ (view.green as number) < 21 ||+ (view.red as number) > 16384 ||+ (view.green as number) > 16384+ )+ return result;+ views.push({+ backdrop,+ index,+ pngBase64: view.pngBase64 as string,+ sha256: digest,+ ...(input.name === 'software-views'+ ? { red: view.red as number, green: view.green as number }+ : {}),+ });+ }+ return { ...result, passed: true, views };+ }+ return { ...result, passed: ['network', 'write-marker', 'read-marker'].includes(input.name) };+ } catch {+ return result;+ }+}diff --git a/hosting/probe/resilience-run.ts b/hosting/probe/resilience-run.tsnew file mode 100644index 00000000..b31ce981--- /dev/null+++ b/hosting/probe/resilience-run.ts@@ -0,0 +1,70 @@+export const resilienceCases = [+ 'cpu-preview',+ 'software-views',+ 'network',+ 'write-marker',+ 'read-marker',+ 'native-deadline',+ 'native-cancel',+ 'stdout-flood',+ 'stderr-flood',+ 'memory-limit',+ 'alarm-recovery',+ 'engine-after',+] as const;+export type ResilienceCase = (typeof resilienceCases)[number];+export interface ResilienceResult {+ name: ResilienceCase;+ passed: boolean;+ stopped?: boolean;+ reason?: string;+ image?: string;+ elapsedMs?: number;+ ready?: boolean;+ readyAfterMs?: number;+ exitCode?: number;+ digest?: string;+ views?: {+ backdrop: string;+ index: number;+ pngBase64: string;+ sha256: string;+ red?: number;+ green?: number;+ }[];+ oomKills?: number;+ counterSource?: string;+ pendingAlarm?: boolean;+}+interface RunRecord {+ state: 'running' | 'finished';+ results: ResilienceResult[];+}++/** A new allowance, never a reset or continuation of earlier exhausted probes. */+export async function runResilienceOnce(+ storage: DurableObjectStorage,+ execute: (name: ResilienceCase) => Promise<ResilienceResult>,+): Promise<RunRecord> {+ const claimed = await storage.transaction(async (transaction) => {+ if (await transaction.get('run')) return false;+ await transaction.put('run', { state: 'running', results: [] } satisfies RunRecord);+ return true;+ });+ if (!claimed) return (await storage.get<RunRecord>('run'))!;+ const record: RunRecord = { state: 'running', results: [] };+ for (const name of resilienceCases) {+ let result: ResilienceResult;+ try {+ result = await execute(name);+ } catch {+ result = { name, passed: false, reason: 'PROBE_FAILED' };+ }+ record.results.push(result);+ await storage.put('run', record);+ if (!result.passed) break;+ }+ record.state = 'finished';+ await storage.put('run', record);+ return record;+}diff --git a/hosting/probe/resilience-worker.ts b/hosting/probe/resilience-worker.tsnew file mode 100644index 00000000..d248453e--- /dev/null+++ b/hosting/probe/resilience-worker.ts@@ -0,0 +1,56 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ResilienceExecution } from './resilience-execution';+import { runResilienceOnce, type ResilienceCase } from './resilience-run';++interface Bindings {+ KilnResilienceRun: DurableObjectNamespace<KilnResilienceRun>;+ KilnResilienceJob: DurableObjectNamespace<KilnResilienceJob>;+}+export class KilnResilienceJob extends DurableObject {+ runFixture(name: ResilienceCase) {+ return new ResilienceExecution(this.ctx).run(name);+ }+ readResult() {+ return new ResilienceExecution(this.ctx).read();+ }+ stopUnconfirmed() {+ return new ResilienceExecution(this.ctx).stopUnconfirmed();+ }+ alarm() {+ return new ResilienceExecution(this.ctx).alarm();+ }+}+export class KilnResilienceRun extends DurableObject {+ async run() {+ const bindings = this.ctx.exports as unknown as Bindings;+ return runResilienceOnce(this.ctx.storage, async (name) => {+ const job = bindings.KilnResilienceJob.getByName(`stable-resilience-v1/${name}`);+ let result = await job.runFixture(name);+ if (!result.pendingAlarm) return result;+ // A different DO observes the actual alarm callback. It never calls alarm()+ // itself and cannot restart a VM or submit new source while polling.+ const until = Date.now() + 45_000;+ while (Date.now() < until) {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ const next = await job.readResult();+ if (next) result = next;+ if (!result.pendingAlarm) return result;+ }+ return job.stopUnconfirmed();+ });+ }+}+export class KilnResilienceControl extends WorkerEntrypoint {+ fetch() {+ return new Response('Not found', { status: 404 });+ }+ runFixed() {+ const bindings = this.ctx.exports as unknown as Bindings;+ return bindings.KilnResilienceRun.getByName('stable-resilience-v1').run();+ }+}+export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler;diff --git a/hosting/probe/resilience.wrangler.jsonc b/hosting/probe/resilience.wrangler.jsoncnew file mode 100644index 00000000..74576540--- /dev/null+++ b/hosting/probe/resilience.wrangler.jsonc@@ -0,0 +1,23 @@+{+ "name": "kiln-private-stable-resilience",+ "main": "./resilience-worker.ts",+ "compatibility_date": "2026-10-06",+ "compatibility_flags": ["enable_ctx_exports"],+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": {"cpu_ms": 30000, "subrequests": 50},+ "observability": {"enabled": true, "logs": {"enabled": true, "invocation_logs": true}},+ "containers": [{+ "name": "kiln-private-stable-resilience-jobs",+ "class_name": "KilnResilienceJob",+ "scheduling_policy": "durable_object",+ "images": {"kiln": {"image": "registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:84a0fa62bcffa010b9ac1c5f2f0e2cf9045a9cdb6407f621e8049e6a37f9de99"}},+ "observability": {"logs": {"enabled": false}}+ }],+ "exports": {+ "KilnResilienceControl": {"type": "worker"},+ "KilnResilienceRun": {"type": "durable-object", "storage": "sqlite"},+ "KilnResilienceJob": {"type": "durable-object", "storage": "sqlite"}+ }+}diff --git a/hosting/probe/run-once.ts b/hosting/probe/run-once.tsnew file mode 100644index 00000000..71b9b769--- /dev/null+++ b/hosting/probe/run-once.ts@@ -0,0 +1,43 @@+export const probeCases = ['engine-a', 'network', 'write-marker', 'read-marker'] as const;+export type ProbeCase = (typeof probeCases)[number];+export interface ProbeResult {+ name: ProbeCase;+ passed: boolean;+ image?: string;+ stopped?: boolean;+ elapsedMs?: number;+ digest?: string;+ reason?: string;+ failedOperation?: string;+}+interface RunRecord {+ state: 'running' | 'finished';+ results: ProbeResult[];+}++export async function runProbeOnce(+ storage: DurableObjectStorage,+ execute: (name: ProbeCase) => Promise<ProbeResult>,+): Promise<RunRecord> {+ const claimed = await storage.transaction(async (transaction) => {+ if (await transaction.get('run')) return false;+ await transaction.put('run', { state: 'running', results: [] } satisfies RunRecord);+ return true;+ });+ if (!claimed) return (await storage.get<RunRecord>('run'))!;+ const record: RunRecord = { state: 'running', results: [] };+ for (const name of probeCases) {+ let result: ProbeResult;+ try {+ result = await execute(name);+ } catch {+ result = { name, passed: false, reason: 'PROBE_FAILED' };+ }+ record.results.push(result);+ await storage.put('run', record);+ if (!result.passed) break;+ }+ record.state = 'finished';+ await storage.put('run', record);+ return record;+}diff --git a/hosting/probe/startup-diagnostic.ts b/hosting/probe/startup-diagnostic.tsnew file mode 100644index 00000000..6040867d--- /dev/null+++ b/hosting/probe/startup-diagnostic.ts@@ -0,0 +1,327 @@+const IMAGE = 'cloudflare/debian-trixie';+const KILN_IMAGE =+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a';+const KILN_MANIFEST_IMAGE =+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8';+const DEADLINE_MS = 60_000;+const CLEANUP_MS = 5_000;+const COMMAND = [+ '/usr/local/bin/node',+ '--eval',+ 'process.stdout.write(JSON.stringify({version:process.version,uid:process.getuid(),gid:process.getgid()}))',+];++type Operation =+ | 'start'+ | 'monitor'+ | 'inactivity'+ | 'exec'+ | 'inspect'+ | 'output'+ | 'destroy'+ | 'stopped';+type Reason =+ | 'ISOLATION_UNAVAILABLE'+ | 'IMAGE_UNAVAILABLE'+ | 'PREEXISTING_CONTAINER'+ | 'START_FAILED'+ | 'MONITOR_FAILED'+ | 'CONTAINER_EXITED'+ | 'INACTIVITY_FAILED'+ | 'EXEC_FAILED'+ | 'INSPECT_FAILED'+ | 'OUTPUT_FAILED'+ | 'DEADLINE_EXCEEDED'+ | 'CLEANUP_FAILED';+interface Phase {+ operation: Operation;+ event: 'entered' | 'completed' | 'failed';+ elapsedMs: number;+ duringCleanup: boolean;+}+interface StartupRecord {+ state: 'running' | 'finished';+ passed: boolean;+ claimedAt: number;+ deadlineAt: number;+ phases: Phase[];+ cleanupRequired: boolean;+ stopped: boolean;+ reason?: Reason;+ runtime?: { version: string; uid: number; gid: number };+}+class DiagnosticFailure extends Error {+ constructor(readonly reason: Reason) {+ super(reason);+ }+}++function mark(+ record: StartupRecord,+ operation: Operation,+ event: Phase['event'],+ duringCleanup: boolean,+) {+ // Only fixed operation names and numeric timing leave this diagnostic.+ if (record.phases.length < 32)+ record.phases.push({+ operation,+ event,+ elapsedMs: Math.max(0, Date.now() - record.claimedAt),+ duringCleanup,+ });+}++async function boundedOutput(+ stream: ReadableStream<Uint8Array> | null | undefined,+ check: () => void,+) {+ if (!stream) throw new DiagnosticFailure('OUTPUT_FAILED');+ const bytes = new Uint8Array(1024);+ let length = 0;+ const reader = stream.getReader();+ try {+ for (;;) {+ check();+ const { value, done } = await reader.read();+ check();+ if (done) return bytes.slice(0, length);+ if (!(value instanceof Uint8Array) || length + value.byteLength > bytes.length)+ throw new DiagnosticFailure('OUTPUT_FAILED');+ bytes.set(value, length);+ length += value.byteLength;+ }+ } catch (error) {+ void reader.cancel().catch(() => {});+ throw error;+ } finally {+ reader.releaseLock();+ }+}++async function cleanup(container: Container | undefined, record: StartupRecord): Promise<boolean> {+ if (!container) {+ record.stopped = true;+ return true;+ }+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = Date.now() + CLEANUP_MS;+ try {+ await Promise.race([+ (async () => {+ mark(record, 'destroy', 'entered', true);+ await container.destroy();+ if (Date.now() >= deadline) throw new DiagnosticFailure('CLEANUP_FAILED');+ mark(record, 'destroy', 'completed', true);+ mark(record, 'stopped', 'entered', true);+ const info = await container.inspect();+ if (Date.now() >= deadline || container.running || info !== null)+ throw new DiagnosticFailure('CLEANUP_FAILED');+ record.stopped = true;+ mark(record, 'stopped', 'completed', true);+ })(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new DiagnosticFailure('CLEANUP_FAILED')), CLEANUP_MS);+ }),+ ]);+ return true;+ } catch {+ mark(record, 'stopped', 'failed', true);+ return false;+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++/** Fixed platform diagnostic only. No source, image, command or run ID is accepted. */+export class ManagedStartupDiagnostic {+ constructor(+ private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,+ private readonly imageSource: 'managed' | 'configured' | 'kiln' | 'kiln-manifest' = 'managed',+ ) {}++ async run(): Promise<StartupRecord> {+ const storage = this.context.storage;+ const record: StartupRecord = {+ state: 'running',+ passed: false,+ claimedAt: Date.now(),+ deadlineAt: Date.now() + DEADLINE_MS,+ phases: [],+ cleanupRequired: true,+ stopped: false,+ };+ const claimed = await storage.transaction(async (transaction) => {+ if (await transaction.get('startup')) return false;+ await transaction.put('startup', record);+ await transaction.setAlarm(record.deadlineAt);+ return true;+ });+ if (!claimed) return (await storage.get<StartupRecord>('startup'))!;++ const container = this.context.container;+ let closing = false;+ let reason: Reason | undefined;+ let rejectStopped: (error: DiagnosticFailure) => void = () => {};+ const stopped = new Promise<never>((_, reject) => {+ rejectStopped = reject;+ });+ void stopped.catch(() => {});+ const stop = (failure: Reason) => {+ if (closing || reason) return;+ reason = failure;+ rejectStopped(new DiagnosticFailure(failure));+ };+ const check = () => {+ if (closing) throw new DiagnosticFailure('EXEC_FAILED');+ if (Date.now() >= record.deadlineAt) stop('DEADLINE_EXCEEDED');+ if (reason) throw new DiagnosticFailure(reason);+ };+ const step = async <T>(+ operation: Operation,+ failure: Reason,+ action: () => T | Promise<T>,+ ): Promise<T> => {+ check();+ mark(record, operation, 'entered', false);+ try {+ const result = await action();+ check();+ mark(record, operation, 'completed', false);+ return result;+ } catch (error) {+ mark(record, operation, 'failed', closing);+ throw error instanceof DiagnosticFailure ? error : new DiagnosticFailure(failure);+ }+ };+ const timer = setTimeout(+ () => stop('DEADLINE_EXCEEDED'),+ Math.max(0, record.deadlineAt - Date.now()),+ );+ try {+ const execute = async () => {+ if (!container) throw new DiagnosticFailure('ISOLATION_UNAVAILABLE');+ const kilnImage =+ this.imageSource === 'kiln'+ ? KILN_IMAGE+ : this.imageSource === 'kiln-manifest'+ ? KILN_MANIFEST_IMAGE+ : undefined;+ const image = this.imageSource === 'managed' ? IMAGE : container.images?.control;+ if (+ this.imageSource !== 'managed' &&+ (typeof image !== 'string' ||+ !/^registry\.cloudflare\.com\/[a-f0-9]{32}\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/.test(+ image,+ ))+ )+ throw new DiagnosticFailure('IMAGE_UNAVAILABLE');+ if (kilnImage && image !== kilnImage) throw new DiagnosticFailure('IMAGE_UNAVAILABLE');+ if (container.running) throw new DiagnosticFailure('PREEXISTING_CONTAINER');+ await step('start', 'START_FAILED', () =>+ container.start({+ image,+ instance: 'standard-2',+ enableInternet: false,+ entrypoint: ['sleep', 'infinity'],+ env: {},+ }),+ );+ mark(record, 'monitor', 'entered', false);+ try {+ void container.monitor().then(+ () => {+ mark(record, 'monitor', 'completed', closing);+ stop('CONTAINER_EXITED');+ },+ () => {+ mark(record, 'monitor', 'failed', closing);+ stop('MONITOR_FAILED');+ },+ );+ } catch {+ mark(record, 'monitor', 'failed', false);+ throw new DiagnosticFailure('MONITOR_FAILED');+ }+ await step('inactivity', 'INACTIVITY_FAILED', () =>+ container.setInactivityTimeout(120_000),+ );+ const process = await step('exec', 'EXEC_FAILED', () =>+ container.exec(COMMAND, {+ stdout: 'pipe',+ stderr: 'pipe',+ ...(kilnImage ? { user: '1000:1000' } : {}),+ }),+ );+ await step('inspect', 'INSPECT_FAILED', async () => {+ const observed = await container.inspect();+ if (observed?.image !== image) throw new DiagnosticFailure('INSPECT_FAILED');+ });+ record.runtime = await step('output', 'OUTPUT_FAILED', async () => {+ const [stdout, stderr, exitCode] = await Promise.all([+ boundedOutput(process.stdout, check),+ boundedOutput(process.stderr, check),+ process.exitCode,+ ]);+ check();+ if (exitCode !== 0 || stderr.byteLength !== 0)+ throw new DiagnosticFailure('OUTPUT_FAILED');+ const value: unknown = JSON.parse(+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(stdout),+ );+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new DiagnosticFailure('OUTPUT_FAILED');+ const data = value as Record<string, unknown>;+ if (+ Object.keys(data).sort().join(',') !== 'gid,uid,version' ||+ typeof data.version !== 'string' ||+ data.version !== (kilnImage ? 'v22.23.3' : 'v24.20.0') ||+ (kilnImage && (data.uid !== 1000 || data.gid !== 1000)) ||+ !Number.isSafeInteger(data.uid) ||+ !Number.isSafeInteger(data.gid) ||+ Number(data.uid) < 0 ||+ Number(data.gid) < 0 ||+ Number(data.uid) > 0xffff_ffff ||+ Number(data.gid) > 0xffff_ffff+ )+ throw new DiagnosticFailure('OUTPUT_FAILED');+ return { version: data.version, uid: Number(data.uid), gid: Number(data.gid) };+ });+ };+ await Promise.race([execute(), stopped]);+ } catch (error) {+ record.reason = error instanceof DiagnosticFailure ? error.reason : 'EXEC_FAILED';+ } finally {+ closing = true;+ clearTimeout(timer);+ record.cleanupRequired = !(await cleanup(container, record));+ if (record.cleanupRequired) record.reason ??= 'CLEANUP_FAILED';+ record.state = 'finished';+ record.passed = record.reason === undefined && record.stopped;+ await storage.put('startup', record);+ if (record.cleanupRequired) await storage.setAlarm(Date.now() + 30_000);+ else await storage.deleteAlarm();+ }+ return structuredClone(record);+ }++ async alarm(): Promise<void> {+ const storage = this.context.storage;+ const record = await storage.get<StartupRecord>('startup');+ if (!record?.cleanupRequired) {+ await storage.deleteAlarm();+ return;+ }+ if (record.state === 'running' && Date.now() < record.deadlineAt) {+ await storage.setAlarm(record.deadlineAt);+ return;+ }+ record.state = 'finished';+ record.passed = false;+ record.reason ??= 'DEADLINE_EXCEEDED';+ record.cleanupRequired = !(await cleanup(this.context.container, record));+ await storage.put('startup', record);+ if (record.cleanupRequired) await storage.setAlarm(Date.now() + 30_000);+ else await storage.deleteAlarm();+ }+}diff --git a/hosting/probe/startup-worker.ts b/hosting/probe/startup-worker.tsnew file mode 100644index 00000000..737c405a--- /dev/null+++ b/hosting/probe/startup-worker.ts@@ -0,0 +1,33 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ManagedStartupDiagnostic } from './startup-diagnostic';++interface Bindings {+ STARTUP_JOB: DurableObjectNamespace<KilnManagedStartupJob>;+}++export class KilnManagedStartupJob extends DurableObject {+ async runFixed() {+ return new ManagedStartupDiagnostic(this.ctx).run();+ }++ async alarm() {+ await new ManagedStartupDiagnostic(this.ctx).alarm();+ }+}++/** The authenticated operator can invoke only this fixed, retained diagnostic. */+export class KilnStartupControl extends WorkerEntrypoint<Bindings> {+ fetch() {+ return new Response('Not found', { status: 404 });+ }++ async runFixed() {+ return this.env.STARTUP_JOB.getByName('managed-runtime-2026-10-06').runFixed();+ }+}++export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+} satisfies ExportedHandler<Bindings>;diff --git a/hosting/probe/startup.wrangler.jsonc b/hosting/probe/startup.wrangler.jsoncnew file mode 100644index 00000000..78c95b81--- /dev/null+++ b/hosting/probe/startup.wrangler.jsonc@@ -0,0 +1,30 @@+{+ "name": "kiln-private-startup-diagnostic",+ "main": "./startup-worker.ts",+ "compatibility_date": "2026-10-06",+ "workers_dev": false,+ "preview_urls": false,+ "routes": [],+ "limits": { "cpu_ms": 30000, "subrequests": 50 },+ "observability": {+ "enabled": true,+ "logs": { "enabled": true, "invocation_logs": true }+ },+ "containers": [+ {+ "name": "kiln-private-managed-startup",+ "class_name": "KilnManagedStartupJob",+ "scheduling_policy": "durable_object",+ "observability": { "logs": { "enabled": false } }+ }+ ],+ "durable_objects": {+ "bindings": [+ { "name": "STARTUP_JOB", "class_name": "KilnManagedStartupJob" }+ ]+ },+ "exports": {+ "KilnStartupControl": { "type": "worker" },+ "KilnManagedStartupJob": { "type": "durable-object", "storage": "sqlite" }+ }+}diff --git a/hosting/probe/worker.ts b/hosting/probe/worker.tsnew file mode 100644index 00000000..3396ebc5--- /dev/null+++ b/hosting/probe/worker.ts@@ -0,0 +1,108 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ContainerEvaluationJob, ContainerJobFailure } from '../src/container-job';+import { engineRequest, glbDigest, nativeFixtures } from './fixtures';+import { observeContainer } from './observe-container';+import { probeCases, runProbeOnce, type ProbeCase, type ProbeResult } from './run-once';++interface ProbeBindings {+ KilnProbeRun: DurableObjectNamespace<KilnProbeRun>;+ KilnProbeJob: DurableObjectNamespace<KilnProbeJob>;+}++async function digest(bytes: Uint8Array<ArrayBuffer>): Promise<string> {+ return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (byte) =>+ byte.toString(16).padStart(2, '0'),+ ).join('');+}++export class KilnProbeJob extends DurableObject {+ async runFixture(name: ProbeCase): Promise<ProbeResult> {+ if (!probeCases.includes(name)) throw new Error('Unknown fixed fixture');+ const actual = this.ctx.container;+ if (!actual) return { name, passed: false, reason: 'CONTAINER_UNAVAILABLE' };+ const image = actual.images.kiln;+ const started = Date.now();+ const script = nativeFixtures[name];+ // This substitution exists only in the private probe bundle. Production+ // ContainerEvaluationJob always invokes the immutable evaluate.mjs entry.+ const observed = observeContainer(actual, script);+ try {+ const output = await new ContainerEvaluationJob({+ container: observed.container,+ storage: this.ctx.storage,+ }).run(script ? new TextEncoder().encode('{}') : engineRequest, {+ deadlineMs: 60_000,+ maxResponseBytes: 1024 * 1024,+ });+ const stopped = !actual.running && (await actual.inspect()) === null;+ const value = JSON.parse(+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(output),+ );+ let passed = value.ok === true;+ let outputDigest: string | undefined;+ if (!script) {+ passed &&=+ value.version === 'kiln.evaluator.result.v2' && value.requestId === 'image-fixture';+ const binary = atob(value.render?.glbBase64 ?? '');+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));+ outputDigest = await digest(bytes);+ passed &&= bytes.byteLength === 1912 && outputDigest === glbDigest;+ }+ return {+ name,+ passed: passed && stopped,+ stopped,+ image,+ elapsedMs: Date.now() - started,+ digest: outputDigest,+ };+ } catch (error) {+ return {+ name,+ passed: false,+ image,+ elapsedMs: Date.now() - started,+ stopped: !actual.running && (await actual.inspect()) === null,+ reason: error instanceof ContainerJobFailure ? error.code : 'CHECK_FAILED',+ failedOperation: observed.failure(),+ };+ }+ }++ async alarm() {+ await new ContainerEvaluationJob(this.ctx).alarm();+ }+}++export class KilnProbeRun extends DurableObject {+ async run() {+ const bindings = this.ctx.exports as unknown as ProbeBindings;+ return runProbeOnce(this.ctx.storage, (name) =>+ bindings.KilnProbeJob.getByName(`availability-rc1/${name}`).runFixture(name),+ );+ }+}++/** Operator-only service binding; never accepts source, commands or a new run ID. */+export class KilnProbeControl extends WorkerEntrypoint {+ fetch() {+ return new Response('Not found', { status: 404 });+ }++ async runFixed() {+ const bindings = this.ctx.exports as unknown as ProbeBindings;+ return bindings.KilnProbeRun.getByName('availability-rc1').run();+ }+}++export default {+ fetch() {+ return new Response('Not found', { status: 404 });+ },+ async scheduled(_event: ScheduledController, _env: unknown, ctx: ExecutionContext) {+ const bindings = ctx.exports as unknown as ProbeBindings;+ const result = await bindings.KilnProbeRun.getByName('availability-rc1').run();+ // No source, credentials or arbitrary container output enter logs.+ console.log(JSON.stringify({ kind: 'kiln-private-availability-probe', ...result }));+ },+} satisfies ExportedHandler;diff --git a/hosting/scripts/build-boundary.mjs b/hosting/scripts/build-boundary.mjsnew file mode 100644index 00000000..30567c62--- /dev/null+++ b/hosting/scripts/build-boundary.mjs@@ -0,0 +1,14 @@+export function assertProductionBoundary(entry, inputs) {+ const paths = inputs.map((name) => name.replaceAll('\\', '/'));+ if (paths.some((name) => /(?:^|\/)(?:test|probe)\//.test(name)))+ throw new Error('Production bundle includes test or probe helpers');+ if (+ entry !== 'worker' &&+ paths.some((name) =>+ /oauth|(?:^|\/)(?:auth|github|google|connections|account-(?:page|actions)|browser-(?:login|sessions|cookies))\.ts$/.test(+ name,+ ),+ )+ )+ throw new Error('Storage bundle includes authorization-server code');+}diff --git a/hosting/scripts/build-integrated-probe.mjs b/hosting/scripts/build-integrated-probe.mjsnew file mode 100644index 00000000..a72309cd--- /dev/null+++ b/hosting/scripts/build-integrated-probe.mjs@@ -0,0 +1,174 @@+// Local-only build. Upload, R2 provisioning and deployment require a reviewed allowance.+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { dirname, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';+import { build } from 'esbuild';+import {+ OutputRootConfigSchema,+ OutputWorkerSchema,+ OutputContainerSchema,+ convertToWranglerConfig,+} from '@cloudflare/config';++const { values } = parseArgs({+ options: {+ account: { type: 'string' },+ output: { type: 'string' },+ 'cf-package': { type: 'string' },+ },+});+assert.match(values.account ?? '', /^[a-f0-9]{32}$/);+assert(values.output && values['cf-package']);+const cli = JSON.parse(await readFile(values['cf-package'], 'utf8'));+assert.equal(cli.name, 'cf');+assert.equal(cli.version, '1.0.0-beta.12');+const root = fileURLToPath(new URL('../../', import.meta.url)),+ output = resolve(values.output);+assert(output.startsWith(resolve(root, '.cache') + sep));+const name = 'kiln-private-integrated-v1',+ bucket = 'kiln-private-integrated-v1-evidence';+const coordinator = `registry.cloudflare.com/${values.account}/kiln-coordinator@sha256:029c4fba6f0521a5a18c9dde364d07b5ffc076fe4d988358868950de40134b66`;+const software = `registry.cloudflare.com/${values.account}/kiln-software@sha256:64022900f0c298668076db054c44e019dad6a3813751a92dec7a06ceb734fe24`;+const compiled = await build({+ entryPoints: [fileURLToPath(new URL('../probe/integrated-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ target: 'es2022',+ external: ['cloudflare:workers'],+ metafile: true,+});+const inputs = Object.keys(compiled.metafile.inputs);+assert(+ !inputs.some((path) =>+ /oauth|\/src\/(?:auth|github|google|browser-|account-)/.test(path.replaceAll('\\', '/')),+ ),+);+const doBinding = (exportName) => ({ type: 'durable-object', worker: name, exportName });+const text = (value) => ({ type: 'text', value });+const applications = [+ ['coordinator', 'IntegratedRequestJob', 'coordinator', coordinator],+ ['evaluation', 'IntegratedEvaluationJob', 'kiln', software],+ ['render', 'IntegratedRenderJob', 'renderer', software],+];+const exports = {+ KilnIntegratedControl: { type: 'worker' },+ KilnNativeStorage: { type: 'worker' },+ KilnNativeEvaluation: { type: 'worker' },+ KilnNativeRender: { type: 'worker' },+ KilnIntegratedRun: { type: 'durable-object', storage: 'sqlite' },+ KilnIntegratedBudget: { type: 'durable-object', storage: 'sqlite' },+ KilnAdmission: { type: 'durable-object', storage: 'sqlite' },+ KilnTenant: { type: 'durable-object', storage: 'sqlite' },+};+for (const [kind, exportName] of applications)+ exports[exportName] = { type: 'durable-object', storage: 'sqlite', container: `${name}-${kind}` };+const worker = OutputWorkerSchema.parse({+ name,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports', 'enable_request_signal'],+ workersDev: false,+ previewUrls: false,+ domains: [],+ triggers: [],+ limits: { cpuMs: 30000, subrequests: 500 },+ observability: {+ enabled: true,+ logs: { enabled: true, headSamplingRate: 1, invocationLogs: true, persist: true },+ },+ env: {+ BUDGET: doBinding('KilnIntegratedBudget'),+ RUN: doBinding('KilnIntegratedRun'),+ ADMISSION: doBinding('KilnAdmission'),+ TENANTS: doBinding('KilnTenant'),+ REQUESTS: doBinding('IntegratedRequestJob'),+ EVALUATIONS: doBinding('IntegratedEvaluationJob'),+ RENDERS: doBinding('IntegratedRenderJob'),+ ARTIFACTS: { type: 'r2', name: bucket },+ PUBLIC_ORIGIN: text('https://kiln.instruktlabs.com'),+ STORAGE_MAX_BYTES: text('67108864'),+ STORAGE_MAX_OBJECTS: text('256'),+ STORAGE_MAX_GROUPS: text('64'),+ COMPUTE_MAX_CONCURRENT: text('1'),+ COMPUTE_TENANT_PER_MINUTE: text('9'),+ COMPUTE_TENANT_PER_DAY: text('9'),+ COMPUTE_GLOBAL_PER_DAY: text('9'),+ COMPUTE_GLOBAL_PER_MONTH: text('9'),+ COMPUTE_DEADLINE_MS: text('120000'),+ },+ exports,+ manifest: {+ type: 'complete',+ mainModule: 'worker.mjs',+ modules: { 'worker.mjs': { type: 'esm' } },+ },+});+const files = {+ 'config.json': OutputRootConfigSchema.parse({+ accountId: values.account,+ buildContext: { isPreview: false },+ }),+ 'workers/default/worker.config.json': worker,+};+for (const [kind, , key, image] of applications)+ files[`containers/${name}-${kind}/container.config.json`] = OutputContainerSchema.parse({+ name: `${name}-${kind}`,+ schedulingPolicy: 'durable-object',+ ssh: { enabled: false },+ images: { [key]: { reference: image } },+ observability: { enabled: false, logs: { enabled: false } },+ });+for (const [name, value] of Object.entries(files)) {+ const path = resolve(output, '.cloudflare/output/v0', name);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);+}+const bytes = compiled.outputFiles[0].contents,+ path = resolve(output, '.cloudflare/output/v0/workers/default/bundle/worker.mjs');+await mkdir(dirname(path), { recursive: true });+await writeFile(path, bytes);+// cf beta.12 serializes every named DO binding with script_name, even when the+// target is this Worker. Container deployment rejects that external-binding form.+// Keep the Build Output for inspection and emit an equivalent Wrangler config+// referencing these exact bytes. The seven self-bindings are explicitly local.+const wrangler = convertToWranglerConfig({+ accountId: values.account,+ worker: { ...worker, entrypoint: './.cloudflare/output/v0/workers/default/bundle/worker.mjs' },+ containers: applications.map(+ ([kind]) => files[`containers/${name}-${kind}/container.config.json`],+ ),+});+assert.equal(wrangler.durable_objects.bindings.length, 7);+for (const binding of wrangler.durable_objects.bindings) {+ assert.equal(binding.script_name, worker.name);+ assert.equal(worker.exports[binding.class_name]?.type, 'durable-object');+ delete binding.script_name;+}+wrangler.routes = [];+await writeFile(resolve(output, 'wrangler.json'), `${JSON.stringify(wrangler, null, 2)}\n`);+const receipt = {+ worker: name,+ bucket,+ coordinator,+ software,+ workerSha256: createHash('sha256').update(bytes).digest('hex'),+ bytes: bytes.length,+ cli: cli.version,+ deploymentConfig: 'wrangler.json',+ deployWithoutBundling: true,+ inputs,+ maxMcpRequests: 9,+ quotaRejectionRequests: 1,+ maxVmStarts: { coordinator: 9, evaluation: 4, render: 4, total: 17 },+ deadlineMs: 120000,+ maxActiveParents: 1,+ maxActiveChildrenPerParent: 1,+ publicHttp: false,+ deployed: false,+};+await writeFile(resolve(output, 'build-receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);+console.log(JSON.stringify(receipt));diff --git a/hosting/scripts/build-provider-probe.mjs b/hosting/scripts/build-provider-probe.mjsnew file mode 100644index 00000000..0256a0a1--- /dev/null+++ b/hosting/scripts/build-provider-probe.mjs@@ -0,0 +1,115 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';+import { build } from 'esbuild';+import {+ OutputRootConfigSchema,+ OutputWorkerSchema,+ OutputContainerSchema,+} from '@cloudflare/config';++// Explicit local preparation only. cf deploy --prebuilt consumes this reviewed+// output after approval; this script never uploads, provisions or invokes a VM.+const { values } = parseArgs({+ options: {+ 'cf-package': { type: 'string' },+ account: { type: 'string' },+ image: { type: 'string' },+ output: { type: 'string' },+ },+});+assert.match(values.account ?? '', /^[a-f0-9]{32}$/);+assert.match(+ values.image ?? '',+ /^registry\.cloudflare\.com\/[a-f0-9]{32}\/[a-z0-9-]+@sha256:[a-f0-9]{64}$/,+);+assert.ok(values.image.startsWith(`registry.cloudflare.com/${values.account}/`));+assert.ok(values['cf-package'] && values.output);+const cliPackage = resolve(values['cf-package']);+const cli = JSON.parse(await readFile(cliPackage, 'utf8'));+assert.equal(cli.name, 'cf');+assert.equal(cli.version, '1.0.0-beta.12');+const output = resolve(values.output);+const workerName = 'kiln-private-evaluation-probe';+const containerName = 'kiln-private-evaluation-probe-jobs';+const bundle = await build({+ entryPoints: [fileURLToPath(new URL('../probe/worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ target: 'es2022',+ external: ['cloudflare:workers'],+ metafile: true,+});+const bytes = bundle.outputFiles[0].contents;+const rootConfig = OutputRootConfigSchema.parse({+ accountId: values.account,+ buildContext: { isPreview: false },+});+const workerConfig = OutputWorkerSchema.parse({+ name: workerName,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports'],+ workersDev: false,+ previewUrls: false,+ domains: [],+ limits: { cpuMs: 30000, subrequests: 50 },+ // The operator uses an authenticated remote service binding. No background+ // trigger can consume the fixed allowance before the operator is connected.+ triggers: [],+ observability: {+ enabled: true,+ logs: { enabled: true, headSamplingRate: 1, invocationLogs: true, persist: true },+ },+ exports: {+ KilnProbeControl: { type: 'worker' },+ KilnProbeRun: { type: 'durable-object', storage: 'sqlite' },+ KilnProbeJob: { type: 'durable-object', storage: 'sqlite', container: containerName },+ },+ manifest: {+ type: 'complete',+ mainModule: 'worker.mjs',+ modules: { 'worker.mjs': { type: 'esm' } },+ },+});+const containerConfig = OutputContainerSchema.parse({+ name: containerName,+ schedulingPolicy: 'durable-object',+ ssh: { enabled: false },+ images: { kiln: { reference: values.image } },+ observability: { enabled: false, logs: { enabled: false } },+});+const files = {+ 'config.json': rootConfig,+ 'workers/default/worker.config.json': workerConfig,+ [`containers/${containerName}/container.config.json`]: containerConfig,+};+for (const [name, content] of Object.entries(files)) {+ const path = resolve(output, '.cloudflare/output/v0', name);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, `${JSON.stringify(content, null, 2)}\n`);+}+const modulePath = resolve(output, '.cloudflare/output/v0/workers/default/bundle/worker.mjs');+await mkdir(dirname(modulePath), { recursive: true });+await writeFile(modulePath, bytes);+const receipt = {+ worker: workerName,+ image: values.image,+ workerSha256: createHash('sha256').update(bytes).digest('hex'),+ bytes: bytes.length,+ cli: cli.version,+ inputs: Object.keys(bundle.metafile.inputs),+ maxJobs: 4,+ priorTrialJobs: 1,+ totalApprovedJobs: 5,+ maxConcurrent: 1,+ deadlineMs: 60000,+ publicHttp: false,+ deployed: false,+};+await writeFile(resolve(output, 'build-receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);+console.log(JSON.stringify(receipt));diff --git a/hosting/scripts/build.mjs b/hosting/scripts/build.mjsindex f614d843..4b0e0a81 100644--- a/hosting/scripts/build.mjs+++ b/hosting/scripts/build.mjs@@ -2,36 +2,54 @@ import { mkdir, writeFile } from 'node:fs/promises';import { createHash } from 'node:crypto';import { fileURLToPath } from 'node:url';import { build } from 'esbuild';+import { assertProductionBoundary } from './build-boundary.mjs';const output = new URL('../../.cache/hosted-worker/', import.meta.url);await mkdir(output, { recursive: true });-for (const entry of ['worker', 'tenant-worker', 'native-programs', 'native-assets', 'native-mcp']) {+const nativeOnly = process.argv.includes('--native-only');+if (!nativeOnly) {+ const { checkEdgeManifest } = await import('./edge-manifest.mjs');+ await checkEdgeManifest();+}+for (const entry of [+ 'worker',+ 'tenant-worker',+ 'evaluation-worker',+ 'render-worker',+ 'request-worker',+ 'admission-worker',+ 'native-programs',+ 'native-assets',+ 'native-materials',+ 'native-mcp',+ 'native-host',+ 'native-evaluator',+ 'native-render',+]) {+ // The installed-image build must not depend on a checkout SDK or edge snapshot.+ if (nativeOnly && !entry.startsWith('native-')) continue;const result = await build({entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],bundle: true,write: false,format: 'esm',platform: entry.startsWith('native-') ? 'node' : 'browser',+ conditions: entry.startsWith('native-') ? undefined : ['workerd'],target: 'es2022',metafile: true,- external: [- 'cloudflare:workers',- '@instruktlabs/kiln',- '@instruktlabs/kiln/*',- '@modelcontextprotocol/server',- ],+ external: entry.startsWith('native-')+ ? [+ 'cloudflare:workers',+ '@instruktlabs/kiln',+ '@instruktlabs/kiln/*',+ '@modelcontextprotocol/server',+ '@modelcontextprotocol/node',+ ]+ : ['cloudflare:workers'],});const bytes = result.outputFiles[0].contents;const inputs = Object.keys(result.metafile.inputs);- if (inputs.some((name) => /(?:^|\/)test\//.test(name.replaceAll('\\', '/')))) {- throw new Error('Production bundle includes test helpers');- }- if (- entry !== 'worker' &&- inputs.some((name) => /oauth|(?:^|\/)auth\.ts$/.test(name.replaceAll('\\', '/')))- ) {- throw new Error('Storage bundle includes authorization-server code');- }+ assertProductionBoundary(entry, inputs);await writeFile(new URL(`${entry}.mjs`, output), bytes);await writeFile(new URL(entry === 'worker' ? 'build.json' : `${entry}-build.json`, output),diff --git a/hosting/scripts/deployment-config.mjs b/hosting/scripts/deployment-config.mjsnew file mode 100644index 00000000..6233b555--- /dev/null+++ b/hosting/scripts/deployment-config.mjs@@ -0,0 +1,321 @@+import {+ OutputRootConfigSchema,+ OutputWorkerSchema,+ OutputContainerSchema,+ convertToWranglerConfig,+} from '@cloudflare/config';++const fail = () => {+ throw new Error('Invalid deployment manifest');+};+function fields(value, names) {+ if (+ !value ||+ typeof value !== 'object' ||+ Array.isArray(value) ||+ Object.keys(value).sort().join(',') !== [...names].sort().join(',')+ )+ fail();+}+function matches(value, pattern) {+ if (typeof value !== 'string' || value.trim() !== value || !pattern.test(value)) fail();+}+function count(value, maximum = Number.MAX_SAFE_INTEGER) {+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) fail();+}++// Inputs have already passed manifest validation. This is a reviewable candidate,+// not a Notifications API payload or evidence of live alert delivery.+function monitoringCandidate(account, datasetName) {+ const dataset = `events.analyticsEngine.${datasetName}`;+ const query = (filters) =>+ `SELECT COUNT(*) AS value\nFROM ${dataset}\nWHERE accountTag = '${account}'\n AND timestamp >= NOW() - INTERVAL '5' MINUTE\n AND blob1 = 'kiln.ops.v1'\n AND ${filters}`;+ return {+ schemaVersion: 1,+ configured: false,+ destination: null,+ dataset,+ dialect: 'Cloudflare Analytics SQL API',+ alerts: [+ [+ 'deletion-heartbeat',+ "blob2 = 'health' AND blob3 = 'deletion' AND blob4 = 'ok' AND double5 = 1",+ '<',+ 1,+ ],+ ['compute-heartbeat', "blob2 = 'health' AND blob3 = 'compute' AND blob4 = 'ok'", '<', 1],+ [+ 'deletion-overdue',+ "blob2 = 'health' AND blob3 = 'deletion' AND blob4 = 'ok' AND double4 > 0",+ '>=',+ 1,+ ],+ [+ 'compute-cleanup',+ "blob2 = 'health' AND blob3 = 'compute' AND blob4 = 'ok' AND double4 > 0",+ '>=',+ 3,+ ],+ ['gateway-errors', "blob2 = 'http' AND blob4 LIKE '5%'", '>=', 5],+ ['gateway-rejections', "blob2 = 'http' AND blob4 = '429'", '>=', 100],+ ].map(([name, filters, comparison, threshold]) => ({+ name,+ query: query(filters),+ comparison,+ threshold,+ executionIntervalMinutes: 1,+ repeatIntervalMinutes: 60,+ })),+ };+}++/** Pure preparation: no Cloudflare requests, credentials, resource creation or public routes. */+export function deploymentConfig(m) {+ fields(m, [+ 'account',+ 'prefix',+ 'origin',+ 'database',+ 'oauthKv',+ 'bucket',+ 'images',+ 'compute',+ 'storage',+ 'requestLimits',+ ]);+ fields(m.database, ['id', 'name']);+ fields(m.images, ['coordinator', 'software']);+ fields(m.compute, [+ 'maxConcurrent',+ 'tenantPerMinute',+ 'tenantPerDay',+ 'globalPerDay',+ 'globalPerMonth',+ 'deadlineMs',+ ]);+ fields(m.storage, ['maxBytes', 'maxObjects', 'maxGroups']);+ fields(m.requestLimits, ['edge', 'account']);+ for (const policy of Object.values(m.requestLimits)) {+ fields(policy, ['namespace', 'perMinute']);+ matches(policy.namespace, /^[1-9][0-9]*$/);+ count(Number(policy.namespace));+ count(policy.perMinute);+ }+ if (m.requestLimits.edge.namespace === m.requestLimits.account.namespace) fail();+ matches(m.account, /^[a-f0-9]{32}$/);+ matches(m.prefix, /^kiln-[a-z0-9]+(?:-[a-z0-9]+)*$/);+ if (m.prefix.length > 40) fail();+ matches(m.database.id, /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/);+ matches(m.oauthKv, /^[a-f0-9]{32}$/);+ if (m.database.name !== `${m.prefix}-accounts` || m.bucket !== `${m.prefix}-artifacts`) fail();+ let origin;+ try {+ origin = new URL(m.origin);+ } catch {+ fail();+ }+ if (+ origin.protocol !== 'https:' ||+ origin.origin !== m.origin ||+ origin.username ||+ origin.password+ )+ fail();+ for (const [kind, image] of Object.entries(m.images)) {+ matches(+ image,+ /^registry\.cloudflare\.com\/[a-f0-9]{32}\/kiln-(?:coordinator|software)@sha256:[a-f0-9]{64}$/,+ );+ if (!image.startsWith(`registry.cloudflare.com/${m.account}/kiln-${kind}@sha256:`)) fail();+ }+ for (const value of Object.values(m.compute)) count(value);+ for (const value of Object.values(m.storage)) count(value);+ count(m.compute.maxConcurrent, 16);+ count(m.compute.deadlineMs, 120000);+ if (+ m.compute.tenantPerMinute > m.compute.tenantPerDay ||+ m.compute.tenantPerDay > m.compute.globalPerDay ||+ m.compute.globalPerDay > m.compute.globalPerMonth+ )+ fail();+ const names = Object.fromEntries(+ ['gateway', 'tenant', 'admission', 'request', 'evaluation', 'render'].map((role) => [+ role,+ `${m.prefix}-${role}`,+ ]),+ );+ const text = (value) => ({ type: 'text', value: String(value) });+ const object = (role, exportName) => ({+ type: 'durable-object',+ worker: names[role],+ exportName,+ });+ const workerBinding = (role, exportName) => ({ type: 'worker', worker: names[role], exportName });+ const sqlite = { type: 'durable-object', storage: 'sqlite' };+ const entry = { type: 'worker' };+ const containers = {};+ for (const [role, imageKey, kind] of [+ ['request', 'coordinator', 'coordinator'],+ ['evaluation', 'kiln', 'software'],+ ['render', 'renderer', 'software'],+ ]) {+ containers[role] = OutputContainerSchema.parse({+ name: `${names[role]}-vm`,+ schedulingPolicy: 'durable-object',+ ssh: { enabled: false },+ observability: { enabled: false, logs: { enabled: false } },+ images: { [imageKey]: { reference: m.images[kind] } },+ });+ }+ const definitions = {+ gateway: {+ entry: 'worker',+ env: {+ ACCOUNTS: { type: 'd1', ...m.database },+ OAUTH_KV: { type: 'kv', id: m.oauthKv },+ OPERATIONS: {+ type: 'analytics-engine-dataset',+ name: `${m.prefix.replaceAll('-', '_')}_ops`,+ },+ PUBLIC_ORIGIN: text(m.origin),+ ...Object.fromEntries(+ [+ ['edge', 'EDGE_REQUEST_LIMIT'],+ ['account', 'ACCOUNT_REQUEST_LIMIT'],+ ].map(([kind, name]) => [+ name,+ {+ type: 'rate-limit',+ namespace: m.requestLimits[kind].namespace,+ simple: { limit: m.requestLimits[kind].perMinute, period: 60 },+ },+ ]),+ ),+ TENANTS: object('tenant', 'KilnTenant'),+ NATIVE_COMPUTE: workerBinding('admission', 'KilnCompute'),+ ...Object.fromEntries(+ [+ 'GOOGLE_CLIENT_ID',+ 'GOOGLE_CLIENT_SECRET',+ 'GITHUB_CLIENT_ID',+ 'GITHUB_CLIENT_SECRET',+ ].map((name) => [name, { type: 'secret' }]),+ ),+ },+ exports: {},+ },+ tenant: {+ entry: 'tenant-worker',+ env: {+ ARTIFACTS: { type: 'r2', name: m.bucket },+ STORAGE_MAX_BYTES: text(m.storage.maxBytes),+ STORAGE_MAX_OBJECTS: text(m.storage.maxObjects),+ STORAGE_MAX_GROUPS: text(m.storage.maxGroups),+ },+ exports: { KilnTenant: sqlite },+ },+ admission: {+ entry: 'admission-worker',+ env: {+ ADMISSION: object('admission', 'KilnAdmission'),+ REQUESTS: object('request', 'KilnNativeRequest'),+ COMPUTE_MAX_CONCURRENT: text(m.compute.maxConcurrent),+ COMPUTE_TENANT_PER_MINUTE: text(m.compute.tenantPerMinute),+ COMPUTE_TENANT_PER_DAY: text(m.compute.tenantPerDay),+ COMPUTE_GLOBAL_PER_DAY: text(m.compute.globalPerDay),+ COMPUTE_GLOBAL_PER_MONTH: text(m.compute.globalPerMonth),+ COMPUTE_DEADLINE_MS: text(m.compute.deadlineMs),+ },+ exports: { KilnAdmission: sqlite, KilnCompute: entry, KilnComputeControl: entry },+ },+ request: {+ entry: 'request-worker',+ env: {+ PUBLIC_ORIGIN: text(m.origin),+ TENANTS: object('tenant', 'KilnTenant'),+ REQUESTS: object('request', 'KilnNativeRequest'),+ EVALUATIONS: object('evaluation', 'KilnEvaluationJob'),+ RENDERS: object('render', 'KilnRenderJob'),+ },+ exports: {+ KilnNativeRequest: { ...sqlite, container: containers.request.name },+ KilnNativeStorage: entry,+ KilnNativeEvaluation: entry,+ KilnNativeRender: entry,+ },+ },+ evaluation: {+ entry: 'evaluation-worker',+ env: { EVALUATIONS: object('evaluation', 'KilnEvaluationJob') },+ exports: { KilnEvaluationJob: { ...sqlite, container: containers.evaluation.name } },+ },+ render: {+ entry: 'render-worker',+ env: { RENDERS: object('render', 'KilnRenderJob') },+ exports: { KilnRenderJob: { ...sqlite, container: containers.render.name } },+ },+ };+ const workers = {},+ wrangler = {};+ for (const [role, definition] of Object.entries(definitions)) {+ const worker = OutputWorkerSchema.parse({+ name: names[role],+ compatibilityDate: '2026-10-06',+ compatibilityFlags: [+ 'enable_ctx_exports',+ 'enable_request_signal',+ 'global_fetch_strictly_public',+ ],+ workersDev: false,+ previewUrls: false,+ domains: [],+ triggers: role === 'gateway' ? [{ type: 'scheduled', schedule: '* * * * *' }] : [],+ limits: { cpuMs: 30000, subrequests: 500 },+ // URLs can contain authorization codes and download capabilities. Do not+ // persist request/trace payloads; sanitized operational metrics are separate.+ observability: {+ enabled: false,+ redactQueryString: true,+ logs: { enabled: false, invocationLogs: false, persist: false },+ traces: { enabled: false, persist: false },+ },+ env: definition.env,+ exports: definition.exports,+ manifest: {+ type: 'complete',+ mainModule: 'worker.mjs',+ modules: { 'worker.mjs': { type: 'esm' } },+ },+ });+ workers[role] = worker;+ const config = convertToWranglerConfig({+ accountId: m.account,+ worker: {+ ...worker,+ entrypoint: `./.cloudflare/output/v0/workers/${role}/bundle/worker.mjs`,+ },+ containers: containers[role] ? [containers[role]] : [],+ });+ // cf beta.12 emits script_name even for self bindings; Containers require+ // those to be local. Never remove it from an actual cross-service binding.+ for (const binding of config.durable_objects?.bindings ?? [])+ if (binding.script_name === worker.name) delete binding.script_name;+ config.routes = [];+ if (role === 'gateway') config.d1_databases[0].migrations_dir = './migrations';+ wrangler[role] = config;+ }+ return {+ monitoring: monitoringCandidate(m.account, definitions.gateway.env.OPERATIONS.name),+ root: OutputRootConfigSchema.parse({+ accountId: m.account,+ buildContext: { isPreview: false },+ }),+ workers,+ containers,+ wrangler,+ entries: Object.fromEntries(+ Object.entries(definitions).map(([role, value]) => [role, value.entry]),+ ),+ deployOrder: ['tenant', 'evaluation', 'render', 'request', 'admission', 'gateway'],+ };+}diff --git a/hosting/scripts/edge-manifest.mjs b/hosting/scripts/edge-manifest.mjsnew file mode 100644index 00000000..ac4cd2d5--- /dev/null+++ b/hosting/scripts/edge-manifest.mjs@@ -0,0 +1,96 @@+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { pathToFileURL } from 'node:url';+import { createMcpHandler } from '@modelcontextprotocol/server';+import { createKilnMcpServer } from '../../dist/mcp-engine.mjs';+import { listDiscoveryEntries } from '../../lib/discovery/index.js';+import { HOSTED_PROGRAM_RETENTION } from '../src/program-contract.ts';++const destination = new URL('../src/generated/edge-manifest.json', import.meta.url);++/** Capture metadata only. These sentinels cannot evaluate source or access user storage. */+export async function generateEdgeManifest() {+ const unavailable = () => {+ throw new Error('Metadata generation must not access host services');+ };+ const service = new Proxy(+ {},+ { get: (_target, key) => (key === 'retention' ? HOSTED_PROGRAM_RETENTION : unavailable) },+ );+ const createServer = () =>+ createKilnMcpServer({+ assetLibrary: service,+ programStore: service,+ materialLibrary: service,+ workspace: { run: unavailable, current: () => undefined },+ evaluatorProfile: 'evaluator-required',+ evaluatorPort: { render: unavailable },+ cacheEvaluations: false,+ cacheCaptures: false,+ });+ const handler = createMcpHandler(createServer, { legacy: 'stateless', maxSubscriptions: 0 });+ async function rpc(method, params = {}) {+ const response = await handler.fetch(+ new Request('http://kiln-native.internal/mcp', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2025-11-25',+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ }),+ );+ const text = await response.text();+ const message = response.headers.get('content-type')?.includes('text/event-stream')+ ? text+ .split('\n')+ .filter((line) => line.startsWith('data:'))+ .map((line) => JSON.parse(line.slice(5)))+ .findLast((value) => value.id !== undefined)+ : JSON.parse(text);+ if (response.status !== 200 || !message?.result || message.error)+ throw new Error(`Cannot capture native metadata for ${method}`);+ return message.result;+ }+ try {+ const { serverInfo, capabilities, instructions } = await rpc('initialize', {+ protocolVersion: '2025-11-25',+ capabilities: {},+ clientInfo: { name: 'metadata-build', version: '1' },+ });+ const { tools } = await rpc('tools/list');+ const { resources } = await rpc('resources/list');+ const { resourceTemplates } = await rpc('resources/templates/list');+ return {+ kind: 'kiln.hosted-edge.v1',+ serverInfo,+ capabilities,+ instructions,+ tools,+ resources,+ resourceTemplates,+ catalog: listDiscoveryEntries(),+ };+ } finally {+ await handler.close();+ }+}++export async function checkEdgeManifest() {+ const expected = `${JSON.stringify(await generateEdgeManifest(), null, 2)}\n`;+ if ((await readFile(destination, 'utf8')) !== expected)+ throw new Error(+ 'Hosted edge manifest is stale. Run node hosting/scripts/edge-manifest.mjs --write',+ );+}++if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {+ if (process.argv.includes('--write')) {+ await mkdir(new URL('../src/generated/', import.meta.url), { recursive: true });+ await writeFile(destination, `${JSON.stringify(await generateEdgeManifest(), null, 2)}\n`);+ console.log('Generated hosted metadata from the native engine; no services called.');+ } else {+ await checkEdgeManifest();+ console.log('Hosted edge metadata matches the native engine.');+ }+}diff --git a/hosting/scripts/package-public-plugin.mjs b/hosting/scripts/package-public-plugin.mjsnew file mode 100644index 00000000..af766f84--- /dev/null+++ b/hosting/scripts/package-public-plugin.mjs@@ -0,0 +1,220 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { zipSync } from 'three/addons/libs/fflate.module.js';+import { createPublicTools, HOSTED_TOOL_SURFACE } from '../src/public-tools.ts';++const repo = await realpath(fileURLToPath(new URL('../../', import.meta.url)));+const json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');+const origin = 'https://kiln.instruktlabs.com';++function noPrivateConfiguration(value) {+ if (!value || typeof value !== 'object') return;+ for (const [key, child] of Object.entries(value)) {+ if (+ /^(?:apps|hooks|headers|env|password|credentials|reviewer_credentials|client_secret|access_token|refresh_token|authorization)$/i.test(+ key,+ )+ )+ throw new Error('Public metadata contains private configuration or an unsupported component');+ noPrivateConfiguration(child);+ }+}++export function validatePublicMetadata(manifest, mcp, cases, toolNames) {+ noPrivateConfiguration(manifest);+ noPrivateConfiguration(mcp);+ noPrivateConfiguration(cases);+ const allowed = new Set([+ '$schema',+ 'name',+ 'version',+ 'description',+ 'author',+ 'homepage',+ 'repository',+ 'license',+ 'keywords',+ 'extensions',+ ]);+ assert(+ Object.keys(manifest).every((key) => allowed.has(key)),+ 'Unsupported public manifest component',+ );+ assert.deepEqual(Object.keys(manifest.extensions), ['com.openai']);+ assert.equal(manifest.$schema, 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json');+ assert.equal(manifest.name, 'kiln-engine');+ assert.equal(manifest.author.name, 'Instrukt Labs');+ assert.equal(manifest.license, 'MIT');+ const metadata = manifest.extensions['com.openai'];+ assert(+ Object.keys(metadata).every((key) =>+ ['interface', 'onboardingSkill', 'publication'].includes(key),+ ),+ 'Unsupported public extension field',+ );+ const display = metadata.interface;+ assert(display.displayName.length > 0 && display.displayName.length <= 30);+ assert(display.shortDescription.length > 0 && display.shortDescription.length <= 30);+ assert(display.longDescription.length > 0 && display.longDescription.length <= 4000);+ assert.equal(display.category, 'Developer Tools');+ assert.equal(display.websiteURL, origin);+ assert.equal(display.supportURL, `${origin}/support`);+ assert.equal(display.privacyPolicyURL, `${origin}/privacy`);+ assert.equal(display.termsOfServiceURL, `${origin}/terms`);+ assert.equal(metadata.onboardingSkill, './skills/kiln-hosted/SKILL.md');+ assert.equal(display.composerIcon, './assets/icon.svg');+ assert.equal(display.logo, './assets/icon.svg');+ assert(display.defaultPrompt.length > 0 && display.defaultPrompt.length <= 3);+ for (const prompt of display.defaultPrompt)+ assert(typeof prompt === 'string' && prompt.length <= 128);+ assert.deepEqual(mcp, {+ $schema: 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json',+ mcpServers: { kiln: { type: 'streamable-http', url: `${origin}/mcp` } },+ });+ assert.equal(cases.positive.length, 5);+ assert.equal(cases.negative.length, 3);+ for (const item of [...cases.positive, ...cases.negative]) {+ for (const key of ['description', 'prompt', 'expected_behavior'])+ assert(typeof item[key] === 'string' && item[key].trim());+ assert.equal(typeof item.tools_triggered, 'string');+ for (const name of item.tools_triggered+ .split(',')+ .map((value) => value.trim())+ .filter(Boolean))+ assert(toolNames.has(name), `Review case names an unadvertised operation: ${name}`);+ }+ for (const item of cases.positive) assert(item.tools_triggered.trim());+}++/** Offline draft only: packaging neither validates a live endpoint nor submits it. */+export async function packagePublicPlugin(destination) {+ const output = resolve(destination);+ try {+ await lstat(output);+ throw new Error('Public plugin output already exists');+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }+ const sources = {};+ async function source(name, limit = 262144) {+ const path = resolve(repo, name);+ assert.equal(await realpath(path), path, 'Plugin inputs must not traverse symlinks');+ const stat = await lstat(path);+ assert(stat.isFile() && stat.size <= limit, 'Unexpected plugin source file');+ const bytes = await readFile(path);+ sources[name] = hash(bytes);+ return bytes;+ }+ const sourceJson = async (name) => JSON.parse(await source(name));+ const pkg = await sourceJson('package.json');+ const manifest = await sourceJson('hosting/plugin/plugin.json');+ const mcp = await sourceJson('hosting/plugin/mcp.json');+ const cases = await sourceJson('hosting/plugin/review-cases.json');+ assert.equal(pkg.name, '@instruktlabs/kiln');+ assert.equal(manifest.version, pkg.version, 'Review plugin version against the pinned engine');+ // This metadata snapshot is larger than plugin inputs and is never copied into+ // the ZIP. The build's existing regeneration check qualifies it separately.+ const native = JSON.parse(+ await source('hosting/src/generated/edge-manifest.json', 2 * 1024 * 1024),+ );+ await source('hosting/src/public-tools.ts');+ const toolNames = new Set(createPublicTools(native.tools).tools.map((tool) => tool.name));+ validatePublicMetadata(manifest, mcp, cases, toolNames);+ manifest.extensions['com.openai'].review = {+ test_cases: cases,+ commerce: false,+ commerce_description:+ 'Kiln does not sell products or process payments through this integration.',+ };++ const files = new Map([+ ['plugin.json', json(manifest)],+ ['mcp.json', json(mcp)],+ ['README.md', await source('hosting/plugin/README.md')],+ ['LICENSE', await source('LICENSE')],+ ['skills/kiln-hosted/SKILL.md', await source('hosting/plugin/skills/kiln-hosted/SKILL.md')],+ ]);+ for (const name of [+ 'program-contract.md',+ 'geometry-recipes.md',+ 'camera-recipes.md',+ 'reusable-frame.kiln.js',+ ])+ files.set(+ `skills/kiln-hosted/references/${name}`,+ await source(`skills/kiln-author-asset/references/${name}`),+ );+ const favicon = (await source('site/public/favicon.svg')).toString('utf8');+ assert.match(favicon, /^<svg xmlns="http:\/\/www.w3.org\/2000\/svg" viewBox="0 0 32 32">/);+ assert.doesNotMatch(favicon, /<\s*(?:script|foreignObject|image|use)\b|href\s*=|\bon\w+\s*=/i);+ const inner = favicon.replace(/^<svg[^>]+>\s*/, '').replace(/\s*<\/svg>\s*$/, '');+ files.set(+ 'assets/icon.svg',+ Buffer.from(+ `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">\n<g transform="scale(2)">\n${inner}\n</g>\n</svg>\n`,+ ),+ );+ files.set(+ 'package-provenance.json',+ json({+ kind: 'kiln.public-plugin.v1',+ engineVersion: pkg.version,+ hostedToolSurface: HOSTED_TOOL_SURFACE,+ sources,+ files: Object.fromEntries([...files].map(([name, bytes]) => [name, hash(bytes)])),+ }),+ );+ const ordered = [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const archive = Buffer.from(+ zipSync(Object.fromEntries(ordered), { level: 6, mtime: new Date(1980, 0, 1) }),+ );+ const receipt = {+ kind: 'kiln.public-plugin.draft.v1',+ submissionReady: false,+ engineVersion: pkg.version,+ hostedToolSurface: HOSTED_TOOL_SURFACE,+ remaining: [+ 'live-endpoint-and-terms',+ 'live-client-review-cases',+ 'demo-recording',+ 'review-account-access',+ 'publisher-and-domain-verification',+ 'portal-validation-and-submission',+ ],+ sources,+ files: Object.fromEntries(ordered.map(([name, bytes]) => [name, hash(bytes)])),+ archive: { name: 'kiln-engine-draft.zip', bytes: archive.length, sha256: hash(archive) },+ };+ await mkdir(dirname(output), { recursive: true });+ await mkdir(output); // Refuse an output created concurrently after validation.+ for (const [name, bytes] of ordered) {+ const path = join(output, 'plugin', name);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, bytes, { flag: 'wx' });+ }+ await writeFile(join(output, receipt.archive.name), archive, { flag: 'wx' });+ await writeFile(join(output, 'receipt.json'), json(receipt), { flag: 'wx' });+ return receipt;+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const [destination, ...extra] = process.argv.slice(2);+ if (!destination || extra.length)+ throw new Error('Usage: node hosting/scripts/package-public-plugin.mjs FRESH_OUTPUT_DIRECTORY');+ const receipt = await packagePublicPlugin(destination);+ console.log(+ JSON.stringify(+ {+ ...receipt.archive,+ submissionReady: receipt.submissionReady,+ remaining: receipt.remaining,+ },+ null,+ 2,+ ),+ );+}diff --git a/hosting/scripts/prepare-deployment.mjs b/hosting/scripts/prepare-deployment.mjsnew file mode 100644index 00000000..10d53803--- /dev/null+++ b/hosting/scripts/prepare-deployment.mjs@@ -0,0 +1,165 @@+// Offline only. Provisioning, secrets, image upload and deployment are separate+// reviewed operations. This command deliberately exposes no public route.+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';+import { dirname, relative, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs, promisify } from 'node:util';+import { build } from 'esbuild';+import { assertProductionBoundary } from './build-boundary.mjs';+import { deploymentConfig } from './deployment-config.mjs';+import { lifecycleConfig } from '../probe/lifecycle-config.mjs';+import { assertLifecycleBoundary } from '../probe/lifecycle-build-boundary.mjs';++const root = fileURLToPath(new URL('../../', import.meta.url));+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');+async function main() {+ const { values } = parseArgs({+ options: {+ manifest: { type: 'string' },+ output: { type: 'string' },+ 'private-lifecycle': { type: 'boolean', default: false },+ },+ });+ assert(values.manifest && values.output);+ const raw = await readFile(values.manifest);+ assert(raw.length <= 16384);+ const manifest = JSON.parse(raw);+ const privateLifecycle = values['private-lifecycle'];+ const configuration = privateLifecycle ? lifecycleConfig(manifest) : deploymentConfig(manifest);+ const cache = await realpath(resolve(root, '.cache'));+ const output = resolve(values.output),+ parent = await realpath(dirname(output));+ assert(parent === cache || parent.startsWith(cache + sep));+ // Refuse an existing output, including a link or a partly prepared candidate.+ await mkdir(output);+ assert((await realpath(output)).startsWith(cache + sep));+ const files = [];+ const put = async (path, bytes) => {+ const destination = resolve(output, path);+ assert(destination.startsWith(output + sep));+ await mkdir(dirname(destination), { recursive: true });+ await writeFile(destination, bytes, { flag: 'wx' });+ files.push({ path, sha256: hash(bytes), bytes: Buffer.byteLength(bytes) });+ };+ const json = (path, value) => put(path, `${JSON.stringify(value, null, 2)}\n`);+ const git = async (...args) =>+ (await promisify(execFile)('git', args, { cwd: root })).stdout.trim();+ const sourceCommit = await git('rev-parse', 'HEAD');+ const sourceDirty = Boolean(await git('status', '--porcelain'));+ const receipt = {+ schemaVersion: 1,+ mode: privateLifecycle ? 'private-lifecycle' : 'production-candidate',+ sourceCommit,+ sourceDirty,+ configSchema: '0.23.0',+ publicHttp: false,+ deployed: false,+ resourcesCreated: false,+ manifestSha256: hash(raw),+ deployOrder: configuration.deployOrder,+ requiredGatewaySecrets: Object.keys(configuration.workers.gateway.env).filter(+ (name) => configuration.workers.gateway.env[name].type === 'secret',+ ),+ images: manifest.images,+ workers: [],+ migrations: [],+ files,+ launchGates: privateLifecycle+ ? [+ 'exact-source CI',+ 'disposable resource ownership',+ 'immutable image identity',+ 'verified dependency-order deployment',+ 'no-public-route readback',+ 'bounded operator and verified cleanup',+ 'owner private-trial approval',+ ]+ : [+ 'exact-source CI',+ 'resource ownership',+ 'image identity',+ 'provider secrets',+ 'public ingress protection',+ 'sanitized operational monitoring',+ 'live OAuth and lifecycle qualification',+ 'owner deployment approval',+ ],+ };+ const schemaPackage = JSON.parse(+ await readFile(+ new URL('../node_modules/@cloudflare/config/package.json', import.meta.url),+ 'utf8',+ ),+ );+ assert.equal(schemaPackage.version, receipt.configSchema);+ await json('.cloudflare/output/v0/config.json', configuration.root);+ await json('monitoring-candidate.json', configuration.monitoring);+ for (const [role, entry] of Object.entries(configuration.entries)) {+ const result = await build({+ entryPoints: [resolve(root, 'hosting/src', `${entry}.ts`)],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ target: 'es2022',+ metafile: true,+ external: ['cloudflare:workers'],+ });+ const bytes = result.outputFiles[0].contents;+ const inputs = Object.keys(result.metafile.inputs);+ if (privateLifecycle) assertLifecycleBoundary(role, inputs);+ else assertProductionBoundary(entry, inputs);+ const built = Object.values(result.metafile.outputs)[0];+ const worker = configuration.workers[role];+ for (const name of ['default', ...Object.keys(worker.exports)])+ assert(built.exports.includes(name));+ assert(built.imports.every((item) => item.external && item.path === 'cloudflare:workers'));+ const bundle = `.cloudflare/output/v0/workers/${role}/bundle/worker.mjs`;+ await put(bundle, bytes);+ await json(`.cloudflare/output/v0/workers/${role}/worker.config.json`, worker);+ await json(`${role}.wrangler.json`, configuration.wrangler[role]);+ receipt.workers.push({+ role,+ name: worker.name,+ entry,+ bundle,+ sha256: hash(bytes),+ bytes: bytes.length,+ inputs: inputs.map((input) => relative(root, resolve(input)).replaceAll('\\', '/')),+ });+ }+ for (const container of Object.values(configuration.containers))+ await json(+ `.cloudflare/output/v0/containers/${container.name}/container.config.json`,+ container,+ );+ const migrations = resolve(root, 'hosting/migrations');+ for (const name of (await readdir(migrations))+ .filter((name) => /^\d{4}_[a-z_]+\.sql$/.test(name))+ .sort()) {+ const bytes = await readFile(resolve(migrations, name));+ await put(`migrations/${name}`, bytes);+ receipt.migrations.push({ name, sha256: hash(bytes) });+ }+ assert.equal(await git('rev-parse', 'HEAD'), sourceCommit);+ await writeFile(+ resolve(output, 'deployment-receipt.json'),+ `${JSON.stringify(receipt, null, 2)}\n`,+ { flag: 'wx' },+ );+ console.log(JSON.stringify(receipt));+}+try {+ await main();+} catch {+ // A malformed input could contain a mistakenly supplied credential. Never+ // echo it, parser excerpts or arbitrary provider/configuration error text.+ console.error(+ 'Deployment preparation failed. Check the manifest, pinned dependencies and a fresh output directory under .cache; nothing was deployed.',+ );+ process.exitCode = 1;+}diff --git a/hosting/scripts/prepare-native-host.mjs b/hosting/scripts/prepare-native-host.mjsnew file mode 100644index 00000000..081df53e--- /dev/null+++ b/hosting/scripts/prepare-native-host.mjs@@ -0,0 +1,82 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { copyFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { dirname, join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { assertProductionBoundary } from './build-boundary.mjs';++const root = fileURLToPath(new URL('../../', import.meta.url));+const archive = process.argv[2];+if (!archive)+ throw new Error(+ 'Usage: node hosting/scripts/prepare-native-host.mjs <qualified.tgz> [cache-directory]',+ );+const output = resolve(process.argv[3] ?? join(root, '.cache/native-host-image/context'));+if (!output.startsWith(join(root, '.cache') + sep))+ throw new Error('Build context must be within this checkout cache');+await mkdir(output, { recursive: true });+if ((await readdir(output)).length) throw new Error('Build context must be empty');+const published = JSON.parse(+ await readFile(join(root, '.github/published-candidate.json'), 'utf8'),+);+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');+assert.equal(+ hash(await readFile(archive)),+ published.sha256,+ 'Use the exact public release archive',+);+const files = {};+for (const name of ['native-mcp', 'native-host']) {+ const base = join(root, '.cache/hosted-worker');+ const identity = JSON.parse(await readFile(join(base, `${name}-build.json`), 'utf8'));+ const bytes = await readFile(join(base, `${name}.mjs`));+ assert.equal(hash(bytes), identity.sha256);+ assertProductionBoundary(name, identity.inputs);+ await writeFile(join(output, `${name}.mjs`), bytes);+ files[`${name}.mjs`] = identity.sha256;+}+for (const [source, destination] of [+ ['Dockerfile.host', 'Dockerfile'],+ ['serve.mjs', 'serve.mjs'],+]) {+ const path = join(root, 'hosting/container', source);+ await copyFile(path, join(output, destination));+ files[destination] = hash(await readFile(path));+}+await copyFile(archive, join(output, 'candidate.tgz'));+await writeFile(join(output, 'candidate.sha256'), `${published.sha256} candidate.tgz\n`);+const dependencies = JSON.parse(+ await readFile(join(root, 'hosting/package.json'), 'utf8'),+).dependencies;+await writeFile(+ join(output, 'package.json'),+ `${JSON.stringify(+ {+ name: 'kiln-private-native-host',+ version: published.version,+ private: true,+ type: 'module',+ dependencies: {+ '@instruktlabs/kiln': 'file:./candidate.tgz',+ '@modelcontextprotocol/node': dependencies['@modelcontextprotocol/node'],+ '@modelcontextprotocol/server': dependencies['@modelcontextprotocol/server'],+ },+ },+ null,+ 2,+ )}\n`,+);+await writeFile(+ join(dirname(output), 'context-receipt.json'),+ `${JSON.stringify(+ {+ output,+ engine: published,+ files,+ next: 'Generate package-lock.json in this context, then build Dockerfile for linux/amd64. Retain the resulting immutable image and inventories.',+ },+ null,+ 2,+ )}\n`,+);+console.log(`Prepared minimal native host context: ${output}`);diff --git a/hosting/scripts/smoke-native-host.mjs b/hosting/scripts/smoke-native-host.mjsnew file mode 100644index 00000000..26424941--- /dev/null+++ b/hosting/scripts/smoke-native-host.mjs@@ -0,0 +1,166 @@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { createHash, randomUUID } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = fileURLToPath(new URL('../../', import.meta.url));+const image = process.argv[2];+if (!image || !/^[a-zA-Z0-9._:/@-]+$/.test(image))+ throw new Error('Supply the built image reference');+const output = resolve(process.argv[3] ?? join(root, '.cache/native-host-image/qualification'));+if (!output.startsWith(join(root, '.cache') + sep))+ throw new Error('Receipt must be in the checkout cache');+await mkdir(output, { recursive: true });+const name = `kiln-host-qualification-${randomUUID()}`;+const published = JSON.parse(+ await readFile(join(root, '.github/published-candidate.json'), 'utf8'),+);+const receipt = {+ image,+ container: name,+ engine: published,+ status: 'running',+ cloudflareQualified: false,+};++async function docker(args, input) {+ return new Promise((done, fail) => {+ const child = spawn('docker', args, {+ windowsHide: true,+ stdio: ['pipe', 'pipe', 'pipe'],+ timeout: 60_000,+ });+ const stdout = [],+ stderr = [];+ let bytes = 0;+ for (const [stream, chunks] of [+ [child.stdout, stdout],+ [child.stderr, stderr],+ ])+ stream.on('data', (chunk) => {+ bytes += chunk.length;+ if (bytes > 1024 * 1024) child.kill();+ else chunks.push(chunk);+ });+ child.stdin.on('error', () => {});+ child.once('error', fail);+ child.once('close', (code) =>+ code === 0+ ? done(Buffer.concat(stdout).toString('utf8'))+ : fail(new Error(`Docker ${args[0]} failed: ${Buffer.concat(stderr).toString('utf8')}`)),+ );+ child.stdin.end(input);+ });+}++const check = `+import assert from 'node:assert/strict';+import {request} from 'node:http';+import {readFile} from 'node:fs/promises';+import {createHash} from 'node:crypto';+const pkg=JSON.parse(await readFile('/opt/kiln/node_modules/@instruktlabs/kiln/package.json','utf8'));+const hash=b=>createHash('sha256').update(b).digest('hex');+function call(path,method='GET',headers={},body='') {return new Promise((resolve,reject)=>{+ const req=request({hostname:'127.0.0.1',port:3000,path,method,headers:{host:'kiln-native.internal',...headers}},res=>{+ let text='';res.on('data',c=>{text+=c;if(text.length>256*1024)req.destroy();});res.on('end',()=>resolve({status:res.statusCode,text}));res.on('error',reject);+ });req.on('error',reject);req.end(body);+});}+let ready=false;for(let i=0;i<100;i++){try{ready=(await call('/_ready')).status===204;}catch{}if(ready)break;await new Promise(r=>setTimeout(r,100));}assert(ready);+const meta={'io.modelcontextprotocol/protocolVersion':'2026-07-28','io.modelcontextprotocol/clientInfo':{name:'native-host-fixture',version:'1'},'io.modelcontextprotocol/clientCapabilities':{}};+const headers={'content-type':'application/json',accept:'application/json, text/event-stream','mcp-protocol-version':'2026-07-28','mcp-method':'tools/list'};+const body=JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/list',params:{_meta:meta}});+const listed=await call('/mcp','POST',headers,body);assert.equal(listed.status,200);const result=JSON.parse(listed.text);assert(!result.error);+const names=result.result.tools.map(t=>t.name).sort();assert.equal(new Set(names).size,names.length);for(const n of ['kiln_discover','kiln_render','kiln_save','kiln_source','kiln_export','kiln_material'])assert(names.includes(n));+assert(result.result.tools.find(t=>t.name==='kiln_render').inputSchema.properties.materialDependencies);+const presets=await call('/mcp','POST',{...headers,'mcp-method':'tools/call','mcp-name':'kiln_material'},JSON.stringify({jsonrpc:'2.0',id:4,method:'tools/call',params:{_meta:meta,name:'kiln_material',arguments:{action:'presets'}}}));assert.equal(presets.status,200);const presetResult=JSON.parse(presets.text).result;assert(!presetResult.isError);assert(JSON.parse(presetResult.content.find(x=>x.type==='text').text).presets.length>0);+const legacy=await call('/mcp','POST',{'content-type':'application/json',accept:'application/json, text/event-stream','mcp-protocol-version':'2025-11-25'},JSON.stringify({jsonrpc:'2.0',id:2,method:'initialize',params:{protocolVersion:'2025-11-25',capabilities:{},clientInfo:{name:'legacy-fixture',version:'1'}}}));assert.equal(legacy.status,200);assert(legacy.text.includes(pkg.version));+assert.equal((await call('/mcp','POST',{...headers,host:'foreign.example'},body)).status,421);+assert.equal((await call('/mcp','POST',{...headers,authorization:'Bearer PRIVATE_FIXTURE'},body)).status,403);+const failed=await call('/mcp','POST',{...headers,'mcp-method':'tools/call','mcp-name':'kiln_render'},JSON.stringify({jsonrpc:'2.0',id:3,method:'tools/call',params:{_meta:meta,name:'kiln_render',arguments:{code:'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}'}}}));assert.equal(failed.status,200);const failure=JSON.parse(failed.text).result;assert.equal(failure.isError,true);assert(!failure.content.some(x=>x.type==='image'));+// Trusted fixed fixture tests the installed protocol adapter, not VM isolation.+const {loadContainerMcpRuntime}=await import('/opt/kiln/native-mcp.mjs');+const {evaluateEvaluatorRequestV2}=await import('/opt/kiln/node_modules/@instruktlabs/kiln/lib/evaluator/index.js');+const fixtureSource='function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}';+const fixtureImage='sha256:'+'a'.repeat(64);+const fixtureTransport=withIdentity=>async request=>{const input=await request.text();assert.equal(JSON.parse(input).code,fixtureSource);return new Response(await evaluateEvaluatorRequestV2(input),{headers:withIdentity?{'x-kiln-execution-image':fixtureImage}:{}});};+const qualified=await loadContainerMcpRuntime({fetch:fixtureTransport(true)});+const evaluated=await qualified.evaluatorPort.render(fixtureSource);+assert.equal(qualified.evaluatorPort.executionImage(evaluated),fixtureImage);+assert.equal(qualified.evaluatorPort.executionImage({...evaluated}),undefined);+const unqualified=await loadContainerMcpRuntime({fetch:fixtureTransport(false)});+await assert.rejects(unqualified.evaluatorPort.render(fixtureSource),error=>error.code==='WORKER_FAILED');+console.log(JSON.stringify({version:pkg.version,archiveSha256:hash(await readFile('/opt/kiln/candidate.tgz')),tools:names,checks:['ready','modern-tool-catalog','material-binding-schema','material-presets-from-installed-package','legacy-initialize','foreign-host-denied','credentials-denied','missing-private-services-fail-closed','controller-image-bound-to-installed-evaluation','missing-controller-image-denied'],bundleSha256:Object.fromEntries(await Promise.all(['native-host.mjs','native-mcp.mjs','serve.mjs'].map(async name=>[name,hash(await readFile('/opt/kiln/'+name))])))}));+`;++try {+ receipt.imageIdentity = JSON.parse(+ await docker([+ 'image',+ 'inspect',+ image,+ '--format',+ '{"id":{{json .Id}},"os":{{json .Os}},"architecture":{{json .Architecture}},"user":{{json .Config.User}}}',+ ]),+ );+ assert.equal(receipt.imageIdentity.os, 'linux');+ assert.equal(receipt.imageIdentity.architecture, 'amd64');+ assert.equal(receipt.imageIdentity.user, 'node');+ await docker([+ 'create',+ '--name',+ name,+ '--network',+ 'none',+ '--cpus',+ '1',+ '--memory',+ '1g',+ '--memory-swap',+ '1g',+ '--pids-limit',+ '128',+ '--cap-drop',+ 'ALL',+ '--security-opt',+ 'no-new-privileges',+ '--read-only',+ '--tmpfs',+ '/tmp:rw,noexec,nosuid,size=64m',+ '--env',+ 'KILN_PUBLIC_ORIGIN=https://kiln.example.com',+ image,+ ]);+ await docker(['start', name]);+ assert.equal(+ (await docker(['inspect', name, '--format', '{{.Image}}'])).trim(),+ receipt.imageIdentity.id,+ );+ receipt.result = JSON.parse(+ await docker(['exec', '-i', '--user', '1000:1000', name, 'node', '--input-type=module'], check),+ );+ assert.equal(receipt.result.version, published.version);+ assert.equal(receipt.result.archiveSha256, published.sha256);+ for (const file of ['package-lock.json', 'os-packages.txt', 'node-version.txt'])+ await docker(['cp', `${name}:/opt/kiln/${file}`, join(output, file)]);+ receipt.lockSha256 = createHash('sha256')+ .update(await readFile(join(output, 'package-lock.json')))+ .digest('hex');+ receipt.status = 'passed';+} catch (error) {+ receipt.status = 'failed';+ receipt.error = error.message;+ process.exitCode = 1;+} finally {+ try {+ await docker(['rm', '--force', name]);+ receipt.removed = true;+ } catch (error) {+ receipt.cleanupError = error.message;+ receipt.status = 'failed';+ process.exitCode = 1;+ }+ await writeFile(join(output, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);+}+console.log(JSON.stringify(receipt, null, 2));diff --git a/hosting/scripts/smoke-native-render.mjs b/hosting/scripts/smoke-native-render.mjsnew file mode 100644index 00000000..a95af5ca--- /dev/null+++ b/hosting/scripts/smoke-native-render.mjs@@ -0,0 +1,138 @@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { createHash, randomUUID } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = fileURLToPath(new URL('../../', import.meta.url));+const image = process.argv[2];+if (!image || !/^[a-zA-Z0-9._:/@-]+$/.test(image))+ throw new Error('Supply the built image reference');+const output = resolve(process.argv[3] ?? join(root, '.cache/software-render-entry/qualification'));+if (!output.startsWith(join(root, '.cache') + sep))+ throw new Error('Receipt must be in the checkout cache');+await mkdir(output, { recursive: true });+const name = `kiln-render-qualification-${randomUUID()}`;+const published = JSON.parse(+ await readFile(join(root, '.github/published-candidate.json'), 'utf8'),+);+const receipt = {+ image,+ container: name,+ engine: published,+ status: 'running',+ cloudflareQualified: false,+ hostileSourceQualified: false,+};+async function docker(args, input) {+ return new Promise((done, fail) => {+ const child = spawn('docker', args, {+ windowsHide: true,+ stdio: ['pipe', 'pipe', 'pipe'],+ timeout: 60_000,+ });+ const stdout = [],+ stderr = [];+ let bytes = 0,+ excessive = false;+ for (const [stream, chunks] of [+ [child.stdout, stdout],+ [child.stderr, stderr],+ ])+ stream.on('data', (chunk) => {+ bytes += chunk.length;+ if (bytes > 20 * 1024 * 1024) {+ excessive = true;+ child.kill();+ } else chunks.push(chunk);+ });+ child.stdin.on('error', () => {});+ child.once('error', fail);+ child.once('close', (code) =>+ code === 0 && !excessive+ ? done(Buffer.concat(stdout).toString('utf8'))+ : fail(new Error(`Docker ${args[0]} failed: ${Buffer.concat(stderr).toString('utf8')}`)),+ );+ child.stdin.end(input);+ });+}+try {+ receipt.imageIdentity = JSON.parse(+ await docker([+ 'image',+ 'inspect',+ image,+ '--format',+ '{"id":{{json .Id}},"os":{{json .Os}},"architecture":{{json .Architecture}},"user":{{json .Config.User}}}',+ ]),+ );+ assert.equal(receipt.imageIdentity.os, 'linux');+ assert.equal(receipt.imageIdentity.architecture, 'amd64');+ assert.equal(receipt.imageIdentity.user, 'node');+ await docker([+ 'create',+ '--interactive',+ '--name',+ name,+ '--network',+ 'none',+ '--cpus',+ '2',+ '--memory',+ '4g',+ '--memory-swap',+ '4g',+ '--pids-limit',+ '128',+ '--cap-drop',+ 'ALL',+ '--security-opt',+ 'no-new-privileges',+ image,+ 'node',+ '--input-type=module',+ ]);+ assert.equal(+ (await docker(['inspect', name, '--format', '{{.Image}}'])).trim(),+ receipt.imageIdentity.id,+ );+ const fixture = await readFile(new URL('./software-render-fixture.mjs', import.meta.url));+ receipt.fixtureSha256 = createHash('sha256').update(fixture).digest('hex');+ receipt.result = JSON.parse(await docker(['start', '--attach', '--interactive', name], fixture));+ assert.equal(receipt.result.version, published.version);+ assert.equal(receipt.result.archiveSha256, published.sha256);+ assert.equal(receipt.result.images.length, 8);+ for (const item of receipt.result.images) {+ assert.match(item.name, /^[a-z0-9-]+\.png$/);+ const bytes = Buffer.from(item.base64, 'base64');+ assert.equal(createHash('sha256').update(bytes).digest('hex'), item.sha256);+ await writeFile(join(output, item.name), bytes);+ delete item.base64;+ }+ for (const file of ['package-lock.json', 'os-packages.txt', 'node-version.txt'])+ await docker(['cp', `${name}:/opt/kiln/${file}`, join(output, file)]);+ receipt.lockSha256 = createHash('sha256')+ .update(await readFile(join(output, 'package-lock.json')))+ .digest('hex');+ receipt.status = 'passed';+} catch (error) {+ receipt.status = 'failed';+ receipt.error = error.message;+ process.exitCode = 1;+} finally {+ try {+ await docker(['rm', '--force', name]);+ assert.equal(+ (await docker(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])).trim(),+ '',+ );+ receipt.removed = true;+ } catch (error) {+ receipt.cleanupError = error.message;+ receipt.status = 'failed';+ process.exitCode = 1;+ }+ await writeFile(join(output, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);+}+console.log(JSON.stringify(receipt, null, 2));diff --git a/hosting/scripts/software-render-fixture.mjs b/hosting/scripts/software-render-fixture.mjsnew file mode 100644index 00000000..40bd94c6--- /dev/null+++ b/hosting/scripts/software-render-fixture.mjs@@ -0,0 +1,142 @@+// Fixed trusted fixture, passed over stdin to the disposable image by the smoke script.+// No host workspace, network, user program or credential is available to this process.+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { readFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { renderGLB } from '@instruktlabs/kiln';+import {+ createNativeRenderPort,+ encodeRenderRequest,+ RENDER_LIMITS,+} from '/opt/kiln/native-render.mjs';++const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');+const pkg = JSON.parse(await readFile('/opt/kiln/node_modules/@instruktlabs/kiln/package.json'));+const { PNG } = createRequire('/opt/kiln/node_modules/@instruktlabs/kiln/package.json')('pngjs');+const source = `function build(){const root=createRoot('Root');+ const albedo=proceduralTexture({schemaVersion:2,size:32,usage:'albedo',layers:[{op:'checker',colorA:0xcc2211,colorB:0x22bb33,squares:4}]});+ createPart('Textured',boxGeo(1,1,1),pbrMaterial({albedo,roughness:0.7,metalness:0.1}),{parent:root});+ createPart('Blue',sphereGeo(0.35),pbrMaterial({albedo:0x2233dd,roughness:0.25,metalness:0.4}),{parent:root,position:[0,0.2,0.85]});return root;}`;+const { glb } = await renderGLB(source);+const images = [];+const runs = [];+function entry(input) {+ // Deliberately omit the image's Vulkan environment: Cloudflare exec does too.+ return spawnSync('/usr/local/bin/node', ['/opt/kiln/render.mjs'], {+ input,+ env: { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/node' },+ timeout: 30_000,+ maxBuffer: RENDER_LIMITS.responseBytes,+ });+}+function record(name, bytes) {+ const png = PNG.sync.read(Buffer.from(bytes));+ assert.equal(png.width, 128);+ assert.equal(png.height, 128);+ let red = 0,+ green = 0;+ for (let n = 0; n < png.data.length; n += 4) {+ const [r, g, b] = png.data.subarray(n, n + 3);+ if (r > g + 12 && r > b + 12) red++;+ if (g > r + 12 && g > b + 12) green++;+ }+ assert(red > 20 && green > 20, `${name}: expected textured colours`);+ images.push({+ name,+ sha256: hash(bytes),+ red,+ green,+ base64: Buffer.from(bytes).toString('base64'),+ });+}+const port = createNativeRenderPort({+ fetch: async (request) => {+ assert.equal(request.url, 'http://kiln-renderer.internal/render');+ const result = entry(Buffer.from(await request.arrayBuffer()));+ assert.equal(result.status, 0, result.stderr?.toString() || result.error?.message);+ assert.equal(result.signal, null);+ runs.push({ stderrSha256: hash(result.stderr), bytes: result.stdout.length });+ return new Response(result.stdout);+ },+});+for (const backdrop of ['neutral', 'dark', 'light']) {+ const result = await port({+ glb,+ size: 128,+ viewDirs: [+ [1, 0.4, 1],+ [0, 0, 1],+ ],+ backdrop,+ ...(backdrop === 'neutral' ? { beautySize: 128 } : {}),+ });+ assert.equal(result.ok, true, JSON.stringify(result));+ assert.equal(result.backend, 'vulkan');+ assert.equal(result.derivativeFidelity.inputGlbSha256, `sha256:${hash(glb)}`);+ assert.equal(result.derivativeFidelity.materialFaithful, true);+ assert.equal(result.viewsPng.length, 2);+ for (const [i, bytes] of result.viewsPng.entries()) record(`${backdrop}-${i}.png`, bytes);+ if (backdrop === 'neutral') record('beauty.png', result.beautyPng);+ runs.at(-1).rendererId = result.rendererId;+}+const cameras = [+ {+ position: [2, 1.2, 2],+ target: [0, 0, 0],+ up: [0, 1, 0],+ fovDeg: 50,+ aspect: 1,+ near: 0.1,+ far: 20,+ },+];+const camera = await port({+ glb,+ cameras,+ width: 128,+ height: 128,+ lightingPresetId: 'review-neutral-v1',+});+assert.equal(camera.ok, true, JSON.stringify(camera));+assert.deepEqual(camera.cameras, cameras);+assert.equal(camera.width, 128);+assert.equal(camera.height, 128);+assert.equal(camera.lightingPresetId, 'review-neutral-v1');+record('camera.png', camera.viewsPng[0]);+for (const bytes of [+ Buffer.from('{'),+ encodeRenderRequest({ glb: Buffer.from('not a GLB'), size: 128, viewDirs: [[1, 0, 0]] }).bytes,+]) {+ const result = entry(bytes);+ assert.equal(result.status, 1);+ assert.equal(result.stdout.length, 0);+ assert.equal(result.stderr.toString(), 'Kiln software render input or execution failed.\n');+}+console.log(+ JSON.stringify({+ version: pkg.version,+ archiveSha256: hash(await readFile('/opt/kiln/candidate.tgz')),+ inputGlbSha256: hash(glb),+ runs,+ images,+ checks: [+ 'actual-render-entry',+ 'fixed-software-device',+ 'exact-glb-identity',+ 'three-backdrops',+ 'beauty',+ 'exact-camera',+ 'malformed-input-before-device',+ ],+ bundleSha256: Object.fromEntries(+ await Promise.all(+ ['native-render.mjs', 'render.mjs'].map(async (name) => [+ name,+ hash(await readFile(`/opt/kiln/${name}`)),+ ]),+ ),+ ),+ }),+);diff --git a/hosting/src/account-actions.ts b/hosting/src/account-actions.tsnew file mode 100644index 00000000..fda5679f--- /dev/null+++ b/hosting/src/account-actions.ts@@ -0,0 +1,181 @@+import type { OAuthHelpers } from '@cloudflare/workers-oauth-provider';+import { IDENTITY_ISSUERS } from './accounts';+import type { SignInEnv } from './auth';+import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';+import { D1BrowserSessions, type BrowserSession } from './browser-sessions';+import { D1Connections } from './connections';+import { githubAuthorizationUrl, githubIdentity } from './github';+import { googleAuthorizationUrl, googleIdentity } from './google';+import { HttpFailure, sha256 } from './http';+import type { SignInProvider } from './login-intents';++const COOKIE = '__Host-kiln-action';+const invalid = () =>+ new HttpFailure(+ 400,+ 'Invalid or expired account confirmation; return to your account and try again',+ );+const denied = () =>+ new HttpFailure(403, 'Account action unavailable; return to your account and try again');+const hash = (origin: string, kind: 'state' | 'binding', value: string) =>+ sha256(JSON.stringify(['kiln-account-action-v1', origin, kind, value]));+const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;++export async function beginAccountAction(+ request: Request,+ origin: string,+ env: SignInEnv,+): Promise<Response> {+ if (request.method !== 'POST')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });+ if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')+ throw new HttpFailure(415, 'Expected form data');+ const form = await request.formData();+ const fields = ['csrf', 'action', 'connectionId', 'provider'];+ if (+ fields.some((key) => form.getAll(key).length !== 1) ||+ [...form.keys()].some((key) => !fields.includes(key))+ )+ throw denied();+ const provider = form.get('provider');+ const target = String(form.get('connectionId'));+ if (+ (provider !== 'google' && provider !== 'github') ||+ form.get('action') !== 'disconnect' ||+ !/^kc_[a-f0-9]{32}$/.test(target)+ )+ throw denied();+ const session = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(+ request,+ String(form.get('csrf')),+ );+ const binding = randomBrowserToken();+ const flow = {+ state: `ka1_${randomBrowserToken()}`,+ verifier: randomBrowserToken(),+ nonce: randomBrowserToken(),+ selectAccount: true,+ };+ const now = Date.now();+ const previous = browserToken(request, origin, COOKIE);+ const database = env.ACCOUNTS.withSession('first-primary');+ const rows = await database.batch([+ database+ .prepare(`DELETE FROM kiln_account_actions WHERE state_hash IN+ (SELECT state_hash FROM kiln_account_actions WHERE expires_at<=? LIMIT 128)`)+ .bind(now),+ database+ .prepare('DELETE FROM kiln_account_actions WHERE binding_hash=?')+ .bind(previous ? await hash(origin, 'binding', previous) : ''),+ database+ .prepare(`INSERT INTO kiln_account_actions+ (state_hash,binding_hash,session_hash,account_id,account_epoch,provider,purpose,target,verifier,nonce,expires_at)+ SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,'disconnect',?,?,?,? FROM kiln_browser_sessions s+ JOIN kiln_accounts a ON a.id=s.account_id WHERE s.token_hash=? AND s.csrf=? AND s.account_epoch=?+ AND s.account_id=? AND a.state='active' AND a.authorization_epoch=s.account_epoch AND s.expires_at>? AND s.idle_expires_at>?+ AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?)+ AND EXISTS (SELECT 1 FROM kiln_connections c WHERE c.id=? AND c.account_id=s.account_id AND c.account_epoch=s.account_epoch+ AND c.state IN ('pending','active') AND c.expires_at>?)+ AND (SELECT COUNT(*) FROM kiln_account_actions WHERE account_id=s.account_id)<4+ AND (SELECT COUNT(*) FROM kiln_account_actions)<4096 RETURNING state_hash`)+ .bind(+ await hash(origin, 'state', flow.state),+ await hash(origin, 'binding', binding),+ provider,+ target,+ flow.verifier,+ flow.nonce,+ now + 600_000,+ session.binding,+ session.csrf,+ session.accountEpoch,+ session.accountId,+ now,+ now,+ IDENTITY_ISSUERS[provider],+ target,+ now,+ ),+ ]);+ if (rows[2]?.results.length !== 1) throw denied();+ const location =+ provider === 'google'+ ? await googleAuthorizationUrl(origin, flow, env, request.signal)+ : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env, true);+ return new Response(null, {+ status: 302,+ headers: {+ location,+ 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=600`,+ },+ });+}++export async function finishAccountAction(+ request: Request,+ origin: string,+ env: SignInEnv,+ provider: SignInProvider,+ oauth: OAuthHelpers,+ ctx: ExecutionContext,+): Promise<Response> {+ const url = new URL(request.url);+ const state = url.searchParams.get('state') ?? '';+ const binding = browserToken(request, origin, COOKIE);+ if (+ request.method !== 'GET' ||+ url.pathname !== `/oauth/${provider}/callback` ||+ url.searchParams.getAll('state').length !== 1 ||+ !/^ka1_[a-f0-9]{64}$/.test(state) ||+ !binding+ )+ throw invalid();+ const sessions = new D1BrowserSessions(env.ACCOUNTS, origin);+ let session: BrowserSession;+ try {+ session = await sessions.read(request);+ } catch (error) {+ if (error instanceof HttpFailure && error.status === 401) throw invalid();+ throw error;+ }+ const now = Date.now();+ const flow = await env.ACCOUNTS.withSession('first-primary')+ .prepare(+ `DELETE FROM kiln_account_actions WHERE state_hash=? AND binding_hash=? AND provider=? AND purpose='disconnect'+ AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?+ AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_account_actions.account_id AND a.state='active' AND a.authorization_epoch=kiln_account_actions.account_epoch)+ RETURNING target,verifier,nonce`,+ )+ .bind(+ await hash(origin, 'state', state),+ await hash(origin, 'binding', binding),+ provider,+ session.binding,+ session.accountId,+ session.accountEpoch,+ now,+ )+ .first<{ target: string; verifier: string; nonce: string }>();+ if (!flow) throw invalid();+ if (url.searchParams.has('error'))+ return new Response('Confirmation was cancelled. Return to your account to try again.', {+ status: 400,+ headers: { 'set-cookie': clearCookie },+ });+ const code = url.searchParams.get('code');+ if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();+ const identity =+ provider === 'google'+ ? await googleIdentity(request, origin, { ...flow, state }, env)+ : await githubIdentity(code, flow.verifier, origin, env);+ const grantId = await new D1Connections(env.ACCOUNTS).revoke(session, identity, flow.target);+ // The primary deny is already committed. KV cleanup is supplemental and may+ // propagate later; failure cannot re-enable a connection, and records have TTLs.+ if (grantId) ctx.waitUntil(oauth.revokeGrant(grantId, session.accountId).catch(() => {}));+ const renewed = await sessions.renew(identity, session, request);+ const headers = new Headers({ location: '/account' });+ headers.append('set-cookie', clearCookie);+ headers.append('set-cookie', renewed.cookie);+ return new Response(null, { status: 303, headers });+}diff --git a/hosting/src/account-deletions.ts b/hosting/src/account-deletions.tsnew file mode 100644index 00000000..74df5d3f--- /dev/null+++ b/hosting/src/account-deletions.ts@@ -0,0 +1,238 @@+import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';+import type { BrowserSession } from './browser-sessions';+import { HttpFailure, sha256 } from './http';++type Phase = 'compute' | 'storage' | 'grants' | 'identity' | 'complete';+interface Claim {+ id: string;+ account_id: string;+ phase: Exclude<Phase, 'complete'>;+ lease_token: string;+ attempts: number;+}+export interface DeletionPorts {+ retireCompute(accountId: string): Promise<void>;+ retireStorage(accountId: string): Promise<boolean>;+ revokeGrants(accountId: string): Promise<boolean>;+}+const denied = () => new HttpFailure(403, 'Account deletion could not be confirmed');+const RECEIPT_LIFETIME = 7 * 86400_000;++/** Primary revocation plus a durable, leased outbox. No caller supplies a job ID. */+export class D1AccountDeletions {+ constructor(+ private readonly database: D1Database,+ private readonly origin: string,+ private readonly ports?: DeletionPorts,+ private readonly now: () => number = Date.now,+ ) {+ const url = new URL(origin);+ if (url.protocol !== 'https:' || url.origin !== origin)+ throw new Error('Invalid deletion origin');+ }++ private hash(receipt: string) {+ return sha256(JSON.stringify(['kiln-deletion-receipt-v1', this.origin, receipt]));+ }++ /** Call only after consuming a purpose-bound flow and verifying its provider. */+ async request(proof: BrowserSession, identity: VerifiedIdentity, receipt: string) {+ if (+ !proof ||+ !identity ||+ typeof receipt !== 'string' ||+ !/^[a-f0-9]{64}(?![\s\S])/.test(receipt) ||+ typeof proof.accountId !== 'string' ||+ !/^ka_[a-f0-9]{32}(?![\s\S])/.test(proof.accountId) ||+ !Number.isSafeInteger(proof.accountEpoch) ||+ proof.accountEpoch < 1 ||+ typeof proof.binding !== 'string' ||+ typeof proof.csrf !== 'string' ||+ !Object.values(IDENTITY_ISSUERS).some((issuer) => issuer === identity.issuer) ||+ typeof identity.subject !== 'string' ||+ !/^[\x21-\x7e]{1,255}(?![\s\S])/.test(identity.subject)+ )+ throw denied();+ const id = `kd_${crypto.randomUUID().replace(/-/g, '')}`,+ now = this.now();+ const database = this.database.withSession('first-primary');+ const result = await database.batch([+ database+ .prepare(`INSERT INTO kiln_deletions+ (id,account_id,receipt_hash,phase,created_at,updated_at,retry_at)+ SELECT ?,a.id,?,'compute',?,?,? FROM kiln_accounts a+ JOIN kiln_browser_sessions s ON s.account_id=a.id+ WHERE a.id=? AND a.state='active' AND a.authorization_epoch=?+ AND s.token_hash=? AND s.csrf=? AND s.account_epoch=a.authorization_epoch+ AND s.expires_at>? AND s.idle_expires_at>?+ AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=a.id AND i.issuer=? AND i.subject=?)+ ON CONFLICT(account_id) DO NOTHING RETURNING id`)+ .bind(+ id,+ await this.hash(receipt),+ now,+ now,+ now,+ proof.accountId,+ proof.accountEpoch,+ proof.binding,+ proof.csrf,+ now,+ now,+ identity.issuer,+ identity.subject,+ ),+ database+ .prepare(`UPDATE kiln_accounts SET state='deleting',authorization_epoch=authorization_epoch+1+ WHERE id=? AND state='active' AND changes()=1+ AND EXISTS (SELECT 1 FROM kiln_deletions WHERE id=? AND account_id=kiln_accounts.id) RETURNING id`)+ .bind(proof.accountId, id),+ database+ .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=? AND changes()=1')+ .bind(proof.accountId),+ database+ .prepare(`UPDATE kiln_connections SET state='revoked' WHERE account_id=?+ AND EXISTS (SELECT 1 FROM kiln_deletions WHERE id=? AND account_id=kiln_connections.account_id)`)+ .bind(proof.accountId, id),+ ]);+ if (result[1]?.results.length !== 1) throw denied();+ return { id };+ }++ async status(receipt: unknown) {+ if (typeof receipt !== 'string' || !/^[a-f0-9]{64}(?![\s\S])/.test(receipt))+ throw new HttpFailure(404, 'Deletion receipt unavailable');+ const row = await this.database+ .withSession('first-primary')+ .prepare(`SELECT id,phase,created_at AS createdAt,completed_at AS completedAt+ FROM kiln_deletions WHERE receipt_hash=? AND (completed_at IS NULL OR completed_at>?)`)+ .bind(await this.hash(receipt), this.now() - RECEIPT_LIFETIME)+ .first<{ id: string; phase: Phase; createdAt: number; completedAt: number | null }>();+ if (!row) throw new HttpFailure(404, 'Deletion receipt unavailable');+ return {+ ...row,+ state: row.phase === 'complete' ? ('complete' as const) : ('pending' as const),+ };+ }++ private async claim(): Promise<Claim | null> {+ const now = this.now(),+ lease = crypto.randomUUID();+ return this.database+ .withSession('first-primary')+ .prepare(`UPDATE kiln_deletions SET lease_token=?,lease_until=?,attempts=attempts+1,updated_at=?+ WHERE id=(SELECT d.id FROM kiln_deletions d JOIN kiln_accounts a ON a.id=d.account_id+ WHERE d.phase!='complete' AND d.retry_at<=? AND d.lease_until<=? AND a.state='deleting'+ ORDER BY d.retry_at,d.created_at,d.id LIMIT 1)+ RETURNING id,account_id,phase,lease_token,attempts`)+ .bind(lease, now + 60_000, now, now, now)+ .first<Claim>();+ }++ private async advance(claim: Claim, phase: Phase, retry = 0): Promise<void> {+ const now = this.now();+ await this.database+ .withSession('first-primary')+ .prepare(`UPDATE kiln_deletions SET attempts=CASE WHEN phase=? THEN attempts ELSE 0 END,+ phase=?,retry_at=?,updated_at=?,lease_token=NULL,lease_until=0+ WHERE id=? AND account_id=? AND phase=? AND lease_token=? AND lease_until>?+ AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_deletions.account_id AND a.state='deleting')`)+ .bind(+ phase,+ phase,+ now + retry,+ now,+ claim.id,+ claim.account_id,+ claim.phase,+ claim.lease_token,+ now,+ )+ .run();+ }++ private async finish(claim: Claim): Promise<void> {+ const database = this.database.withSession('first-primary'),+ now = this.now();+ const authorized = `EXISTS (SELECT 1 FROM kiln_deletions d JOIN kiln_accounts a ON a.id=d.account_id+ WHERE d.id=? AND d.account_id=? AND d.phase='identity' AND d.lease_token=? AND d.lease_until>?+ AND a.state='deleting')`;+ const args = [claim.id, claim.account_id, claim.lease_token, now];+ await database.batch([+ ...[+ 'kiln_browser_sessions',+ 'kiln_connections',+ 'kiln_account_events',+ 'kiln_identities',+ ].map((table) =>+ database+ .prepare(`DELETE FROM ${table} WHERE account_id=? AND ${authorized}`)+ .bind(claim.account_id, ...args),+ ),+ database+ .prepare(`DELETE FROM kiln_accounts WHERE id=? AND ${authorized}`)+ .bind(claim.account_id, ...args),+ // The foreign key clears account_id in the same transaction. A failed+ // identity/account delete cannot leave a completed receipt behind.+ database+ .prepare(`UPDATE kiln_deletions SET phase='complete',completed_at=?,updated_at=?,+ lease_token=NULL,lease_until=0,retry_at=0 WHERE id=? AND account_id IS NULL+ AND phase='identity' AND lease_token=? AND changes()=1`)+ .bind(now, now, claim.id, claim.lease_token),+ ]);+ }++ /** Called by the trusted scheduled handler, with a bounded immediate attempt after confirmation. */+ async recover(): Promise<{ steps: number }> {+ if (!this.ports) throw new Error('Deletion recovery is not configured');+ await this.database+ .withSession('first-primary')+ .prepare(`DELETE FROM kiln_deletions WHERE id IN+ (SELECT id FROM kiln_deletions WHERE phase='complete' AND completed_at<=? LIMIT 128)`)+ .bind(this.now() - RECEIPT_LIFETIME)+ .run();+ const end = Date.now() + 25_000;+ let steps = 0;+ for (; steps < 4 && Date.now() < end; steps++) {+ const claim = await this.claim();+ if (!claim) break;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const work = async () => {+ if (claim.phase === 'compute') {+ await this.ports!.retireCompute(claim.account_id);+ return true;+ }+ if (claim.phase === 'storage') return this.ports!.retireStorage(claim.account_id);+ if (claim.phase === 'grants') return this.ports!.revokeGrants(claim.account_id);+ await this.finish(claim);+ return true;+ };+ const done = await Promise.race([+ work(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('Deletion step deadline')),+ Math.max(1, Math.min(20_000, end - Date.now())),+ );+ }),+ ]);+ if (claim.phase !== 'identity') {+ const next = { compute: 'storage', storage: 'grants', grants: 'identity' } as const;+ await this.advance(claim, done ? next[claim.phase] : claim.phase, done ? 0 : 60_000);+ }+ } catch {+ // No exception text or provider data is retained. A late idempotent+ // cleanup cannot advance a replaced lease or reactivate an account.+ await this.advance(+ claim,+ claim.phase,+ Math.min(3600_000, 60_000 * 2 ** Math.min(claim.attempts - 1, 6)),+ );+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+ }+ return { steps };+ }+}diff --git a/hosting/src/account-page.ts b/hosting/src/account-page.tsnew file mode 100644index 00000000..457d3f85--- /dev/null+++ b/hosting/src/account-page.ts@@ -0,0 +1,156 @@+import { IDENTITY_ISSUERS } from './accounts';+import { D1BrowserSessions, type BrowserSession } from './browser-sessions';+import { HttpFailure } from './http';+import { GOOGLE_SIGN_IN_BUTTON } from './google-button';+import { D1Connections } from './connections';+import { validLoginReturn } from './download-path';+import { escapeHtml, htmlPage } from './html-page';++function page(content: string, status = 200): Response {+ return htmlPage('Your account', content, { status });+}++export function signInPage(returnTo = '/account'): Response {+ if (!validLoginReturn(returnTo)) throw new HttpFailure(400, 'Invalid sign-in destination');+ return page(+ `<h1>Sign in to Kiln</h1><p>${+ returnTo === '/account'+ ? 'Free hosted access, with private saved assets and a personal usage quota.'+ : 'Sign in to the Kiln account that saved this asset to download it. This link expires after ten minutes; you can request a new link from your connected app.'+ }</p>+<section><h2>Welcome back</h2><p>Use the same sign-in method as before to reach your saved work. Kiln requests no GitHub repository access or Google Drive access.</p>+<form class="provider-buttons" method="post" action="/account/login"><input type="hidden" name="returnTo" value="${escapeHtml(returnTo)}"><button class="google-button" name="provider" value="google"><img src="${GOOGLE_SIGN_IN_BUTTON}" width="198" height="44" alt="Sign in with Google"></button>+<button class="github-button" name="provider" value="github">Sign in with GitHub</button></form></section>`,+ 401,+ );+}++export function accountNoticePage(message: string): Response {+ return page(+ `<h1>${escapeHtml(message)}</h1><p>Your saved assets and Kiln account stay the same. All browser sessions and connected apps have been signed out.</p><p><a href="/account">Sign in to continue</a>, then reconnect any apps you want to use.</p>`,+ );+}++export function deletionStatusPage(status: {+ id: string;+ state: 'pending' | 'complete';+ createdAt: number;+}): Response {+ return page(+ status.state === 'complete'+ ? `<h1>Account deleted</h1><p>Your Kiln account and files have been removed from the active service. Access from this account remains revoked.</p><p>This does not remove copies you previously downloaded or shared. Inaccessible authorization records and provider backups follow the retention policy.</p><p>This private receipt is available for seven days. You can <a href="/account">create a new, empty account</a> if you return.</p>`+ : `<h1>Deletion in progress</h1><p>Access to your account is blocked while Kiln stops outstanding work and removes your files and sign-in records. You can close this page; cleanup continues automatically.</p><p><a href="/account/deletion">Refresh deletion status</a>. If this remains pending, contact support with reference <strong>${escapeHtml(status.id)}</strong>.</p><p>Requested ${escapeHtml(new Date(status.createdAt).toISOString())}.</p>`,+ );+}++export async function accountPage(+ request: Request,+ database: D1Database,+ origin: string,+): Promise<Response> {+ const url = new URL(request.url);+ if (url.search) throw new HttpFailure(400, 'Query parameters are not supported on account pages');+ const sessions = new D1BrowserSessions(database, origin);+ if (url.pathname === '/account/logout') {+ if (request.method !== 'POST')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });+ if (request.headers.get('origin') !== origin)+ throw new HttpFailure(403, 'Invalid account form');+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')+ throw new HttpFailure(415, 'Expected form data');+ const form = await request.formData();+ if (form.getAll('csrf').length !== 1 || [...form.keys()].some((key) => key !== 'csrf'))+ throw new HttpFailure(403, 'Invalid account form');+ const cookie = await sessions.logout(request, String(form.get('csrf')));+ return new Response(null, {+ status: 303,+ headers: { location: '/account', 'set-cookie': cookie },+ });+ }+ if (request.method !== 'GET')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'GET' } });+ let session: BrowserSession;+ try {+ session = await sessions.read(request);+ } catch (error) {+ if (!(error instanceof HttpFailure) || error.status !== 401) throw error;+ return signInPage();+ }+ const identities = await database+ .withSession('first-primary')+ .prepare('SELECT issuer FROM kiln_identities WHERE account_id=? ORDER BY issuer LIMIT 3')+ .bind(session.accountId)+ .all<{ issuer: string }>();+ const providers = identities.results.map(({ issuer }) =>+ issuer === IDENTITY_ISSUERS.google+ ? 'Google'+ : issuer === IDENTITY_ISSUERS.github+ ? 'GitHub'+ : 'Unknown provider',+ );+ const connections = await new D1Connections(database).list(+ session.accountId,+ session.accountEpoch,+ );+ const providerOptions = identities.results+ .flatMap(({ issuer }) =>+ issuer === IDENTITY_ISSUERS.google+ ? ['<option value="google">Google</option>']+ : issuer === IDENTITY_ISSUERS.github+ ? ['<option value="github">GitHub</option>']+ : [],+ )+ .join('');+ const connectionCards = connections+ .map(+ (connection) => `<article><h3>${escapeHtml(connection.clientName)}</h3>+<p>${connection.clientDomain ? `Client domain: ${escapeHtml(connection.clientDomain)}.` : 'This client registered its own name; that name is not verified.'}+Return address: ${escapeHtml(new URL(connection.redirectUri).host)}.</p>+<p>${connection.state === 'pending' ? 'Waiting for the app to finish connecting.' : 'Connected'} · ${escapeHtml(new Date(connection.createdAt).toISOString().slice(0, 16).replace('T', ' '))} UTC</p>+<form method="post" action="/account/action"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">+<input type="hidden" name="action" value="disconnect"><input type="hidden" name="connectionId" value="${escapeHtml(connection.id)}">+<label>Confirm using <select name="provider">${providerOptions}</select></label> <button type="submit">Disconnect this app</button></form></article>`,+ )+ .join('');+ const identityControls = (['google', 'github'] as const)+ .map((target) => {+ const linked = identities.results.some(({ issuer }) => issuer === IDENTITY_ISSUERS[target]);+ const confirmer = (['google', 'github'] as const).find(+ (provider) =>+ provider !== target &&+ identities.results.some(({ issuer }) => issuer === IDENTITY_ISSUERS[provider]),+ );+ if (!confirmer) return '';+ const label = target === 'google' ? 'Google' : 'GitHub';+ return `<form method="post" action="/account/identity"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">+<input type="hidden" name="action" value="${linked ? 'unlink' : 'link'}"><input type="hidden" name="target" value="${target}">+<input type="hidden" name="provider" value="${confirmer}"><button type="submit">${linked ? 'Remove' : 'Add'} ${label}</button></form>`;+ })+ .join('');+ const events = await database+ .withSession('first-primary')+ .prepare(+ 'SELECT kind,provider,created_at AS createdAt FROM kiln_account_events WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT 20',+ )+ .bind(session.accountId)+ .all<{ kind: 'link' | 'unlink'; provider: string; createdAt: number }>();+ const activity = events.results+ .map(+ (event) =>+ `<li>${event.kind === 'link' ? 'Sign-in method added' : 'Sign-in method removed'}: ${event.provider === 'google' ? 'Google' : 'GitHub'} · ${escapeHtml(new Date(event.createdAt).toISOString().slice(0, 16).replace('T', ' '))} UTC</li>`,+ )+ .join('');+ return page(`<h1>Your Kiln account</h1><p>Free hosted access, with private saved assets and a personal usage quota.</p>+<section><h2>Sign-in methods</h2><ul>${providers.map((provider) => `<li>${escapeHtml(provider)}</li>`).join('')}</ul>+<p>Adding a method asks you to confirm your current provider, then the new one. Removing a method asks you to confirm the one you will keep. Each change signs out all browsers and connected apps. Saved assets stay in this account. Already separate Kiln accounts cannot be merged.</p><div class="provider-buttons">${identityControls}</div></section>+<section><h2>Recent security activity</h2>${activity ? `<ul>${activity}</ul>` : '<p>No sign-in method changes.</p>'}<p>Kiln shows security notices in the app. It does not send email alerts for sign-in method changes or account deletion.</p></section>+<section><h2>Connected apps</h2><p>Disconnecting blocks new requests from that connection. Confirm with a sign-in method to continue.</p>${connectionCards || '<p>No connected apps.</p>'}</section>+<section><h2>This browser</h2><p>Signing out here leaves your connected apps working.</p>+<form method="post" action="/account/logout"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">+<button type="submit">Sign out of this browser</button></form></section>+<section><h2>Delete your account</h2><p>This permanently removes your hosted Kiln account and saved files. Download anything you want to keep first. Your local npm package and local files are unaffected.</p>+<form method="post" action="/account/delete"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}">+<p><label><input type="checkbox" name="confirmation" value="delete-my-account" required> I understand that my hosted files will be deleted.</label></p>+<p><label>Confirm using <select name="provider">${providerOptions}</select></label></p><button type="submit">Confirm account deletion</button></form>+<p>Next, confirm control of a linked sign-in method. Cancelling that step leaves your account unchanged. After confirmation, access is revoked and deletion cannot be undone.</p></section>`);+}diff --git a/hosting/src/admission-worker.ts b/hosting/src/admission-worker.tsnew file mode 100644index 00000000..aad5d2c9--- /dev/null+++ b/hosting/src/admission-worker.ts@@ -0,0 +1,108 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import { ComputeAdmission, admissionFailure } from './admission';+import type { KilnNativeRequest } from './request-worker';++interface ComputeBinding {+ ADMISSION: DurableObjectNamespace<KilnAdmission>;+}+interface AdmissionEnv extends ComputeBinding {+ REQUESTS: DurableObjectNamespace<KilnNativeRequest>;+ COMPUTE_MAX_CONCURRENT: string;+ COMPUTE_TENANT_PER_MINUTE: string;+ COMPUTE_TENANT_PER_DAY: string;+ COMPUTE_GLOBAL_PER_DAY: string;+ COMPUTE_GLOBAL_PER_MONTH: string;+ COMPUTE_DEADLINE_MS: string;+}++function limit(value: string): number {+ if (typeof value !== 'string' || !/^[1-9][0-9]*$/.test(value))+ throw new Error('Missing compute policy');+ return Number(value);+}++export class KilnAdmission extends DurableObject<AdmissionEnv> {+ private readonly admission: ComputeAdmission;+ constructor(ctx: DurableObjectState, env: AdmissionEnv) {+ super(ctx, env);+ this.admission = new ComputeAdmission(+ ctx.storage,+ {+ run: (id, tenant, request, deadline) =>+ env.REQUESTS.getByName(id).run(tenant, request, deadline),+ cancel: async (id) => {+ await env.REQUESTS.getByName(id).cancel();+ },+ },+ {+ maxConcurrent: limit(env.COMPUTE_MAX_CONCURRENT),+ tenantPerMinute: limit(env.COMPUTE_TENANT_PER_MINUTE),+ tenantPerDay: limit(env.COMPUTE_TENANT_PER_DAY),+ globalPerDay: limit(env.COMPUTE_GLOBAL_PER_DAY),+ globalPerMonth: limit(env.COMPUTE_GLOBAL_PER_MONTH),+ deadlineMs: limit(env.COMPUTE_DEADLINE_MS),+ },+ );+ }+ async dispatch(tenant: string, request: Request): Promise<Response> {+ try {+ return await this.admission.dispatch(tenant, request);+ } catch (error) {+ return admissionFailure(error);+ }+ }+ status() {+ return this.admission.status();+ }+ async setPaused(paused: boolean) {+ await this.admission.setPaused(paused);+ return this.admission.status();+ }+ retireTenant(tenant: string): Promise<void> {+ return this.admission.retireTenant(tenant);+ }+ alarm(): Promise<void> {+ return this.admission.alarm();+ }+}++/** Gateway receives only this binding, never a selectable DO namespace. */+export class KilnCompute extends WorkerEntrypoint<ComputeBinding> {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ }+ /** Aggregate read-only health, with no tenant identifiers or operator controls. */+ health() {+ return this.env.ADMISSION.getByName('global-v1').status();+ }+ async dispatch(tenant: string, request: Request): Promise<Response> {+ try {+ return await this.env.ADMISSION.getByName('global-v1').dispatch(tenant, request);+ } catch (error) {+ return admissionFailure(error);+ }+ }+ /** Only the gateway's verified account-deletion controller may call this. */+ retireTenant(tenant: string): Promise<void> {+ return this.env.ADMISSION.getByName('global-v1').retireTenant(tenant);+ }+}++/** Bind only to an authenticated operator service; never to the public gateway. */+export class KilnComputeControl extends WorkerEntrypoint<ComputeBinding> {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ }+ status() {+ return this.env.ADMISSION.getByName('global-v1').status();+ }+ setPaused(paused: boolean) {+ return this.env.ADMISSION.getByName('global-v1').setPaused(paused);+ }+}++export default {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ },+};diff --git a/hosting/src/admission.ts b/hosting/src/admission.tsnew file mode 100644index 00000000..3facb72e--- /dev/null+++ b/hosting/src/admission.ts@@ -0,0 +1,391 @@+import { boundedRequest, HttpFailure, privateResponse, serviceFailure } from './http';+import { nativeRequestHeaders } from './request-job';++const MINUTE = 60_000;+const DAY = 86_400_000;+const RECOVERY_DELAY = 30_000;+const CLEANUP_DEADLINE = 15_000;++export interface ComputePolicy {+ maxConcurrent: number;+ tenantPerMinute: number;+ tenantPerDay: number;+ globalPerDay: number;+ globalPerMonth: number;+ deadlineMs: number;+}+export interface ComputePorts {+ run(id: string, tenant: string, request: Request, deadlineAt: number): Promise<Response>;+ cancel(id: string): Promise<void>;+}+type Active = {+ id: string;+ tenant: string;+ state: string;+ deadline_at: number;+ recover_at: number;+};+type Bucket = { owner: string; period: string; start: number; end: number; limit: number };++class QuotaFailure extends HttpFailure {+ constructor(readonly retryAfter: number) {+ super(429, 'Compute quota or capacity reached');+ }+}+export function admissionFailure(error: unknown): Response {+ const response = serviceFailure(error);+ if (error instanceof QuotaFailure) response.headers.set('retry-after', String(error.retryAfter));+ return privateResponse(response);+}++/** One global SQLite authority. Expiration starts cleanup; it never releases capacity. */+export class ComputeAdmission {+ private readonly sql: SqlStorage;+ private readonly closing = new Map<string, Promise<void>>();++ constructor(+ private readonly storage: DurableObjectStorage,+ private readonly ports: ComputePorts,+ private readonly policy: ComputePolicy,+ private readonly now: () => number = Date.now,+ ) {+ for (const key of [+ 'maxConcurrent',+ 'tenantPerMinute',+ 'tenantPerDay',+ 'globalPerDay',+ 'globalPerMonth',+ 'deadlineMs',+ ] as const) {+ const value = policy[key];+ if (!Number.isSafeInteger(value) || value < 1 || value > 1_000_000)+ throw new Error('Invalid compute policy');+ }+ if (policy.maxConcurrent > 16 || policy.deadlineMs > 120_000)+ throw new Error('Invalid compute capacity');+ this.sql = storage.sql;+ this.sql.exec(`+ CREATE TABLE IF NOT EXISTS compute_format (version INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS compute_active (+ id TEXT PRIMARY KEY, tenant TEXT NOT NULL UNIQUE, state TEXT NOT NULL,+ deadline_at INTEGER NOT NULL, recover_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS compute_recovery ON compute_active(recover_at);+ CREATE TABLE IF NOT EXISTS compute_usage (+ owner TEXT NOT NULL, period TEXT NOT NULL, window_start INTEGER NOT NULL,+ used INTEGER NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY(owner,period)+ );+ CREATE INDEX IF NOT EXISTS compute_expiry ON compute_usage(expires_at);+ CREATE TABLE IF NOT EXISTS compute_control (id INTEGER PRIMARY KEY, paused INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS compute_retired (tenant TEXT PRIMARY KEY NOT NULL);+ INSERT OR IGNORE INTO compute_control VALUES (1,0);+ `);+ const versions = this.sql+ .exec<{ version: number }>('SELECT version FROM compute_format')+ .toArray();+ if (!versions.length) this.sql.exec('INSERT INTO compute_format VALUES (1)');+ else if (versions.length !== 1 || versions[0]?.version !== 1)+ throw new Error('Unsupported compute format');+ }++ private active(id: string): Active | undefined {+ return this.sql.exec<Active>('SELECT * FROM compute_active WHERE id = ?', id).toArray()[0];+ }+ private paused(): boolean {+ return (+ this.sql.exec<{ paused: number }>('SELECT paused FROM compute_control WHERE id = 1').one()+ .paused !== 0+ );+ }+ private assertAvailable(tenant: string): void {+ if (this.sql.exec('SELECT 1 FROM compute_retired WHERE tenant=?', tenant).toArray().length)+ throw new HttpFailure(410, 'Account compute has been retired');+ }+ status(): {+ paused: boolean;+ activeRequests: number;+ pendingCleanup: number;+ maxConcurrent: number;+ } {+ const counts = this.sql+ .exec<{ total: number; closing: number }>(+ "SELECT COUNT(*) AS total, COALESCE(SUM(state = 'closing'),0) AS closing FROM compute_active",+ )+ .one();+ return {+ paused: this.paused(),+ activeRequests: counts.total,+ pendingCleanup: counts.closing,+ maxConcurrent: this.policy.maxConcurrent,+ };+ }+ private buckets(tenant: string, now: number): Bucket[] {+ const minute = Math.floor(now / MINUTE) * MINUTE;+ const day = Math.floor(now / DAY) * DAY;+ const date = new Date(now);+ const month = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);+ const nextMonth = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);+ return [+ {+ owner: tenant,+ period: 'minute',+ start: minute,+ end: minute + MINUTE,+ limit: this.policy.tenantPerMinute,+ },+ { owner: tenant, period: 'day', start: day, end: day + DAY, limit: this.policy.tenantPerDay },+ {+ owner: 'global',+ period: 'day',+ start: day,+ end: day + DAY,+ limit: this.policy.globalPerDay,+ },+ {+ owner: 'global',+ period: 'month',+ start: month,+ end: nextMonth,+ limit: this.policy.globalPerMonth,+ },+ ];+ }++ // Call inside a storage transaction so records and their recovery alarm commit together.+ private async schedule(): Promise<void> {+ const active = this.sql+ .exec<{ at: number | null }>('SELECT MIN(recover_at) AS at FROM compute_active')+ .one().at;+ const expiry = this.sql+ .exec<{ at: number | null }>('SELECT MIN(expires_at) AS at FROM compute_usage')+ .one().at;+ const maintenance = expiry === null ? Infinity : Math.max(this.now() + RECOVERY_DELAY, expiry);+ const next = Math.min(active ?? Infinity, maintenance);+ if (Number.isFinite(next)) await this.storage.setAlarm(next);+ else await this.storage.deleteAlarm();+ }++ private async reserve(tenant: string): Promise<Active> {+ return this.storage.transaction(async () => {+ const now = this.now();+ this.assertAvailable(tenant);+ if (this.paused()) throw new HttpFailure(503, 'Compute is temporarily paused');+ const count = this.sql+ .exec<{ total: number }>('SELECT COUNT(*) AS total FROM compute_active')+ .one().total;+ if (+ count >= this.policy.maxConcurrent ||+ this.sql.exec('SELECT 1 FROM compute_active WHERE tenant = ?', tenant).toArray().length+ )+ throw new QuotaFailure(30);+ const buckets = this.buckets(tenant, now).map((bucket) => {+ const existing = this.sql+ .exec<{ window_start: number; used: number }>(+ 'SELECT window_start,used FROM compute_usage WHERE owner = ? AND period = ?',+ bucket.owner,+ bucket.period,+ )+ .toArray()[0];+ const used = existing?.window_start === bucket.start ? existing.used : 0;+ if (used >= bucket.limit)+ throw new QuotaFailure(Math.max(1, Math.ceil((bucket.end - now) / 1000)));+ return { ...bucket, used };+ });+ for (const bucket of buckets)+ this.sql.exec(+ 'INSERT OR REPLACE INTO compute_usage VALUES (?,?,?,?,?)',+ bucket.owner,+ bucket.period,+ bucket.start,+ bucket.used + 1,+ bucket.end,+ );+ const record: Active = {+ id: crypto.randomUUID(),+ tenant,+ state: 'running',+ deadline_at: now + this.policy.deadlineMs,+ recover_at: now + this.policy.deadlineMs,+ };+ this.sql.exec(+ 'INSERT INTO compute_active VALUES (?,?,?,?,?)',+ record.id,+ record.tenant,+ record.state,+ record.deadline_at,+ record.recover_at,+ );+ await this.schedule();+ return record;+ });+ }++ async dispatch(tenant: string, request: Request): Promise<Response> {+ nativeRequestHeaders(tenant, request);+ const bounded = await boundedRequest(request, 1024 * 1024);+ if (request.signal.aborted) throw new HttpFailure(499, 'Request cancelled');+ const record = await this.reserve(tenant);+ let response: Response | undefined;+ let received: Response | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let onAbort: () => void = () => {};+ let done = false;+ let failed = false;+ let failure: unknown;+ try {+ this.assertAvailable(tenant);+ // Pause/recovery may have run while the durable reservation was committing.+ if (this.paused() || this.active(record.id)?.state !== 'running')+ throw new HttpFailure(503, 'Compute is temporarily paused');+ if (this.now() >= record.deadline_at) throw new HttpFailure(504, 'Compute timed out');+ if (request.signal.aborted) throw new HttpFailure(499, 'Request cancelled');+ const cancelled = new Promise<never>((_, reject) => {+ onAbort = () => reject(new HttpFailure(499, 'Request cancelled'));+ request.signal.addEventListener('abort', onAbort, { once: true });+ timer = setTimeout(+ () => reject(new HttpFailure(504, 'Compute timed out')),+ Math.max(0, record.deadline_at - this.now()),+ );+ });+ const pending = this.ports+ .run(record.id, tenant, bounded, record.deadline_at)+ .then((result) => {+ received = result;+ if (done) void result.body?.cancel().catch(() => {});+ return result;+ });+ response = await Promise.race([pending, cancelled]);+ if (this.now() >= record.deadline_at) throw new HttpFailure(504, 'Compute timed out');+ } catch (error) {+ failed = true;+ failure = error;+ } finally {+ done = true;+ if (timer !== undefined) clearTimeout(timer);+ request.signal.removeEventListener('abort', onAbort);+ }+ if (failed) void received?.body?.cancel().catch(() => {});+ // Failed cleanup takes precedence over any response, including successful work.+ try {+ await this.close(record.id);+ } catch (error) {+ void received?.body?.cancel().catch(() => {});+ throw error;+ }+ if (failed) {+ throw failure;+ }+ // A completed result cannot escape after account retirement interleaved with+ // the run or its verified cleanup. Previously delivered bytes cannot be recalled.+ try {+ this.assertAvailable(tenant);+ } catch (error) {+ void response?.body?.cancel().catch(() => {});+ throw error;+ }+ if (!response) throw new Error('Missing compute result');+ return response;+ }++ private close(id: string): Promise<void> {+ const existing = this.closing.get(id);+ if (existing) return existing;+ const work = this.closeOnce(id);+ this.closing.set(id, work);+ const clear = () => {+ if (this.closing.get(id) === work) this.closing.delete(id);+ };+ void work.then(clear, clear);+ return work;+ }++ private async closeOnce(id: string): Promise<void> {+ const present = await this.storage.transaction(async () => {+ if (!this.active(id)) return false;+ this.sql.exec(+ "UPDATE compute_active SET state = 'closing', recover_at = ? WHERE id = ?",+ this.now() + RECOVERY_DELAY,+ id,+ );+ await this.schedule();+ return true;+ });+ if (!present) return;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ // This acknowledgement includes the coordinator and all of its children.+ // The parent's durable cancellation fence also prevents a late run RPC.+ await Promise.race([+ this.ports.cancel(id),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Cleanup not confirmed')), CLEANUP_DEADLINE);+ }),+ ]);+ await this.storage.transaction(async () => {+ this.sql.exec('DELETE FROM compute_active WHERE id = ?', id);+ await this.schedule();+ });+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+ }++ async setPaused(paused: boolean): Promise<void> {+ if (typeof paused !== 'boolean') throw new Error('Invalid pause setting');+ const active = await this.storage.transaction(async () => {+ this.sql.exec('UPDATE compute_control SET paused = ? WHERE id = 1', paused ? 1 : 0);+ const active = paused ? this.sql.exec<Active>('SELECT * FROM compute_active').toArray() : [];+ if (paused)+ this.sql.exec("UPDATE compute_active SET state = 'closing', recover_at = ?", this.now());+ await this.schedule();+ return active;+ });+ await Promise.allSettled(active.map((row) => this.close(row.id)));+ }++ /** Permanent account-deletion fence, followed by verified whole-request cleanup. */+ async retireTenant(tenant: string): Promise<void> {+ if (typeof tenant !== 'string' || !/^[A-Za-z0-9_-]{43}(?![\s\S])/.test(tenant))+ throw new HttpFailure(400, 'Invalid compute identity');+ const active = await this.storage.transaction(async () => {+ this.sql.exec('INSERT OR IGNORE INTO compute_retired VALUES (?)', tenant);+ const active = this.sql+ .exec<Active>('SELECT * FROM compute_active WHERE tenant=?', tenant)+ .toArray()[0];+ if (active)+ this.sql.exec(+ "UPDATE compute_active SET state='closing',recover_at=? WHERE id=?",+ this.now(),+ active.id,+ );+ await this.schedule();+ return active;+ });+ // Cleanup failure deliberately rejects: a caller must not proceed as if the+ // tenant is drained. The deny and the active lease survive eviction/retry.+ if (active) await this.close(active.id);+ await this.storage.transaction(async () => {+ if (this.sql.exec('SELECT 1 FROM compute_active WHERE tenant=?', tenant).toArray().length)+ throw new Error('Account compute cleanup is not confirmed');+ this.sql.exec('DELETE FROM compute_usage WHERE owner=?', tenant);+ // Global counters retain the cost of admitted work. The opaque deny record+ // persists without its own alarm and cannot be cleared by pause/resume.+ await this.schedule();+ });+ }++ async alarm(): Promise<void> {+ const due = this.sql+ .exec<Active>('SELECT * FROM compute_active WHERE recover_at <= ?', this.now())+ .toArray();+ await Promise.allSettled(due.map((row) => this.close(row.id)));+ await this.storage.transaction(async () => {+ // Bound each maintenance batch, including after a long idle period.+ this.sql.exec(+ 'DELETE FROM compute_usage WHERE rowid IN (SELECT rowid FROM compute_usage WHERE expires_at <= ? LIMIT 256)',+ this.now(),+ );+ await this.schedule();+ });+ }+}diff --git a/hosting/src/artifact-store.ts b/hosting/src/artifact-store.tsindex cb0a2b16..099af470 100644--- a/hosting/src/artifact-store.ts+++ b/hosting/src/artifact-store.ts@@ -41,6 +41,7 @@ export interface StoragePolicy {export class ArtifactStore {private readonly sql: SqlStorage;private readonly prefix: string;+ private purging?: Promise<ReturnType<ArtifactStore['retirementStatus']>>;constructor(private readonly ctx: DurableObjectState,@@ -85,7 +86,131 @@ export class ArtifactStore {CREATE INDEX IF NOT EXISTS artifact_pins ON group_files(artifact_id);CREATE INDEX IF NOT EXISTS artifact_expiry ON artifacts(state, expires_at);CREATE INDEX IF NOT EXISTS artifact_content ON artifacts(sha256, filename, media_type);- CREATE TABLE IF NOT EXISTS maintenance (id INTEGER PRIMARY KEY, cursor TEXT NOT NULL)`);+ CREATE TABLE IF NOT EXISTS maintenance (id INTEGER PRIMARY KEY, cursor TEXT NOT NULL);+ CREATE TABLE IF NOT EXISTS storage_retirement (id INTEGER PRIMARY KEY, state TEXT NOT NULL);+ CREATE TABLE IF NOT EXISTS artifact_writes (artifact_id TEXT PRIMARY KEY NOT NULL)`);+ }++ retirementStatus() {+ const state =+ this.sql+ .exec<{ state: 'retiring' | 'purged' }>('SELECT state FROM storage_retirement WHERE id=1')+ .toArray()[0]?.state ?? 'active';+ return {+ state,+ pendingWrites: this.sql.exec<{ n: number }>('SELECT COUNT(*) AS n FROM artifact_writes').one()+ .n,+ remainingObjects: this.sql.exec<{ n: number }>('SELECT COUNT(*) AS n FROM artifacts').one().n,+ };+ }++ assertActive(): void {+ if (this.sql.exec('SELECT 1 FROM storage_retirement WHERE id=1').toArray().length)+ throw new HttpFailure(410, 'Account storage has been retired');+ }++ /** Caller must first revoke account access and verify compute retirement. */+ async retire(revokeDownloads: () => void = () => {}) {+ await this.ctx.storage.transaction(async () => {+ this.sql.exec("INSERT OR IGNORE INTO storage_retirement VALUES (1,'retiring')");+ // The tenant's ticket store shares this SQLite transaction. No issuance+ // can interleave between revocation and the durable storage deny.+ revokeDownloads();+ // Preserve evidence of old interrupted uploads too. Absence in R2 alone is+ // not proof that an unacknowledged write can no longer arrive.+ this.sql.exec(+ "INSERT OR IGNORE INTO artifact_writes SELECT id FROM artifacts WHERE state='uploading'",+ );+ this.sql.exec("UPDATE artifacts SET state='deleting'");+ this.sql.exec('DELETE FROM group_files; DELETE FROM saved_groups; DELETE FROM maintenance');+ if (this.retirementStatus().state !== 'purged') await this.schedule(this.now() + 30_000);+ });+ return this.purge();+ }++ purge(): Promise<ReturnType<ArtifactStore['retirementStatus']>> {+ if (this.purging) return this.purging;+ const work = this.purgeOnce();+ this.purging = work;+ const clear = () => {+ if (this.purging === work) this.purging = undefined;+ };+ void work.then(clear, clear);+ return work;+ }++ private async purgeOnce() {+ if (this.retirementStatus().state === 'active')+ throw new HttpFailure(409, 'Storage is not retired');+ let retry = 30_000;+ try {+ // A matching immutable R2 object is positive evidence that its unique,+ // create-only put committed. This also recovers a lost acknowledgement.+ const pending = this.sql+ .exec<ArtifactRow>(`SELECT a.* FROM artifacts a+ JOIN artifact_writes w ON w.artifact_id=a.id LIMIT 32`)+ .toArray();+ for (const row of pending) {+ await this.settleCommittedWrite(row);+ }+ const candidates = this.sql+ .exec<ArtifactRow>(`SELECT * FROM artifacts a+ WHERE NOT EXISTS (SELECT 1 FROM artifact_writes w WHERE w.artifact_id=a.id) LIMIT 32`)+ .toArray();+ if (candidates.length) {+ await this.bucket.delete(candidates.map((row) => row.object_key));+ for (const row of candidates) this.sql.exec('DELETE FROM artifacts WHERE id=?', row.id);+ }+ // Delete all retired-prefix orphans, including recent/nonstandard keys.+ // Never delete a key whose put is still unresolved, or any other prefix.+ const listing = await this.bucket.list({ prefix: this.prefix, limit: 100 });+ const keys = listing.objects+ .filter(+ (object) =>+ !this.sql+ .exec(+ 'SELECT 1 FROM artifact_writes WHERE artifact_id=?',+ object.key.slice(this.prefix.length),+ )+ .toArray().length,+ )+ .map((object) => object.key);+ if (keys.length) await this.bucket.delete(keys);+ const status = this.retirementStatus();+ if (!status.pendingWrites && !status.remainingObjects) {+ const remaining = await this.bucket.list({ prefix: this.prefix, limit: 1 });+ if (!remaining.objects.length && !remaining.truncated)+ this.sql.exec("UPDATE storage_retirement SET state='purged' WHERE id=1");+ }+ if (listing.truncated || candidates.length === 32) retry = 10_000;+ // Unknown writes after a crash retain a daily recovery alarm. They are not+ // declared erased based on a timeout. Positive commit evidence or a live+ // failed-put acknowledgement can settle them on a later pass.+ else if (this.retirementStatus().pendingWrites) retry = DAY;+ return this.retirementStatus();+ } finally {+ await this.ctx.storage.transaction(async () => {+ if (this.retirementStatus().state === 'purged') await this.ctx.storage.deleteAlarm();+ else await this.schedule(this.now() + retry);+ });+ }+ }++ private pendingWrite(id: string): boolean {+ return (+ this.sql.exec('SELECT 1 FROM artifact_writes WHERE artifact_id=?', id).toArray().length > 0+ );+ }++ private async settleCommittedWrite(row: ArtifactRow): Promise<void> {+ if (!this.pendingWrite(row.id)) return;+ const object = await this.bucket.head(row.object_key);+ const digest = object?.checksums.sha256;+ const hex = digest+ ? Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')+ : '';+ if (object && object.size === row.bytes && hex === row.sha256)+ this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', row.id);}private artifact(id: string): ArtifactRow | undefined {@@ -101,7 +226,12 @@ export class ArtifactStore {}private readable(row: ArtifactRow | undefined): row is ArtifactRow {- return !!row && row.state === 'ready' && (row.expires_at > this.now() || this.pinned(row.id));+ return (+ !this.sql.exec('SELECT 1 FROM storage_retirement WHERE id=1').toArray().length &&+ !!row &&+ row.state === 'ready' &&+ (row.expires_at > this.now() || this.pinned(row.id))+ );}usage() {@@ -137,6 +267,8 @@ export class ArtifactStore {private async schedule(at = this.now() + DAY): Promise<void> {const existing = await this.ctx.storage.getAlarm();+ // An older upload or maintenance pass may resume after account retirement.+ if (this.retirementStatus().state === 'purged') return;if (existing === null || existing > at) await this.ctx.storage.setAlarm(at);}@@ -169,6 +301,7 @@ export class ArtifactStore {}async upload(request: Request) {+ this.assertActive();const rawSize = request.headers.get('content-length') ?? '';const bytes = Number(rawSize);const sha256 = request.headers.get('x-artifact-sha256') ?? '';@@ -200,6 +333,7 @@ export class ArtifactStore {state: 'uploading',};this.ctx.storage.transactionSync(() => {+ this.assertActive();const usage = this.usage();if (usage.objects >= this.policy.maxObjects ||@@ -219,6 +353,7 @@ export class ArtifactStore {row.expires_at,row.state,);+ this.sql.exec('INSERT INTO artifact_writes VALUES (?)', id);});const abort = new AbortController();let timer: ReturnType<typeof setTimeout> | undefined;@@ -234,16 +369,22 @@ export class ArtifactStore {const pipe = (request.body ?? new Blob([]).stream()).pipeTo(fixed.writable, {signal: abort.signal,});- const put = Promise.resolve().then(() =>- this.bucket.put(row.object_key, fixed.readable, {- sha256,- onlyIf: { etagDoesNotMatch: '*' },- httpMetadata: { contentType: mediaType },- }),- );+ const put = Promise.resolve()+ .then(() => {+ this.assertActive();+ return this.bucket.put(row.object_key, fixed.readable, {+ sha256,+ onlyIf: { etagDoesNotMatch: '*' },+ httpMetadata: { contentType: mediaType },+ });+ })+ .finally(() => {+ this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', id);+ });try {const [, stored] = await Promise.race([Promise.all([pipe, put]), timeout]);if (!stored || stored.size !== bytes) throw new Error('Artifact write did not complete');+ this.assertActive();const updated = this.sql.exec<{ id: string }>("UPDATE artifacts SET state = 'ready' WHERE id = ? AND state = 'uploading' RETURNING id",@@ -260,6 +401,7 @@ export class ArtifactStore {this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", id);const cleanup = (async () => {await Promise.allSettled([pipe, put]);+ this.sql.exec('DELETE FROM artifact_writes WHERE artifact_id=?', id);try {await this.bucket.delete(row.object_key);this.sql.exec("DELETE FROM artifacts WHERE id = ? AND state = 'deleting'", id);@@ -329,6 +471,7 @@ export class ArtifactStore {}save(input: unknown, conditions: { parentKey?: string; absentPrefix?: string } = {}) {+ this.assertActive();if (!input || typeof input !== 'object' || Array.isArray(input))throw new HttpFailure(400, 'Invalid saved revision');const { key, files, metadata } = input as Record<string, unknown>;@@ -470,21 +613,31 @@ export class ArtifactStore {}async sweep(): Promise<{ removed: number }> {+ if (this.retirementStatus().state !== 'active') {+ const before = this.retirementStatus().remainingObjects;+ const after = await this.purge();+ return { removed: before - after.remainingObjects };+ }const now = this.now();let removed = 0;try {- const candidates = this.sql+ let candidates = this.sql.exec<ArtifactRow>(`SELECT * FROM artifacts WHERE state = 'deleting'OR (state = 'uploading' AND created_at <= ?)OR (state = 'ready' AND expires_at <= ? AND NOT EXISTS- (SELECT 1 FROM group_files WHERE artifact_id = artifacts.id)) LIMIT 32`,+ (SELECT 1 FROM group_files WHERE artifact_id = artifacts.id))+ ORDER BY EXISTS (SELECT 1 FROM artifact_writes WHERE artifact_id=artifacts.id)+ LIMIT 32`,now - UPLOAD_GRACE,now,).toArray();for (const row of candidates)this.sql.exec("UPDATE artifacts SET state = 'deleting' WHERE id = ?", row.id);+ for (const row of candidates) await this.settleCommittedWrite(row);+ if (this.retirementStatus().state !== 'active') return { removed };+ candidates = candidates.filter((row) => !this.pendingWrite(row.id));if (candidates.length) {await this.bucket.delete(candidates.map((row) => row.object_key));this.ctx.storage.transactionSync(() => {@@ -503,6 +656,7 @@ export class ArtifactStore {limit: 100,cursor: cursor || undefined,});+ if (this.retirementStatus().state !== 'active') return { removed };const orphans = listing.objects.filter((object) =>object.uploaded.getTime() <= now - UPLOAD_GRACE &&@@ -510,6 +664,7 @@ export class ArtifactStore {!this.artifact(object.key.slice(this.prefix.length)),);if (orphans.length) await this.bucket.delete(orphans.map((object) => object.key));+ if (this.retirementStatus().state !== 'active') return { removed };this.sql.exec('INSERT OR REPLACE INTO maintenance VALUES (1, ?)',listing.truncated ? listing.cursor : '',diff --git a/hosting/src/asset-downloads.ts b/hosting/src/asset-downloads.tsnew file mode 100644index 00000000..b9b04bb1--- /dev/null+++ b/hosting/src/asset-downloads.ts@@ -0,0 +1,126 @@+import type { ArtifactStore } from './artifact-store';+import type { AssetIndex } from './asset-index';+import { HttpFailure, sha256 } from './http';+import { DOWNLOAD_FILES, DOWNLOAD_TOKEN } from './download-path';++const LIFETIME_MS = 600_000;+const MAX_TICKETS = 128;+const MAX_TRANSFERS = 32;+const denied = () => new HttpFailure(404, 'Download link unavailable; request a new link');+type Ticket = { token_hash: string; group_id: string; expires_at: number; uses: number };++/**+ * Tenant-local download selection, not authentication. The browser gateway must+ * select this tenant from a current signed-in account before presenting a ticket.+ * A link alone never authorizes a caller to select another tenant or an R2 key.+ */+export class AssetDownloadTickets {+ private readonly sql: SqlStorage;+ constructor(+ private readonly storage: DurableObjectStorage,+ private readonly artifacts: Pick<ArtifactStore, 'group' | 'download'>,+ private readonly assets: Pick<AssetIndex, 'read'>,+ private readonly now: () => number = Date.now,+ ) {+ this.sql = storage.sql;+ this.sql.exec(`CREATE TABLE IF NOT EXISTS asset_download_tickets (+ token_hash TEXT PRIMARY KEY NOT NULL,+ group_id TEXT NOT NULL,+ expires_at INTEGER NOT NULL,+ uses INTEGER NOT NULL DEFAULT 0 CHECK (uses >= 0 AND uses <= 32)+ );+ CREATE INDEX IF NOT EXISTS asset_download_expiry ON asset_download_tickets(expires_at)`);+ }++ revokeAll(): void {+ this.sql.exec('DELETE FROM asset_download_tickets');+ }++ async issue(collection: unknown, assetId: unknown, revisionId: unknown) {+ const group = this.assets.read(collection, assetId, revisionId);+ const files = Object.keys(group.files).sort();+ if (!files.length || files.some((name) => !DOWNLOAD_FILES.has(name))) throw denied();+ const token = Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>+ byte.toString(16).padStart(2, '0'),+ ).join('');+ const tokenHash = await this.hash(token);+ const expiresAt = this.now() + LIFETIME_MS;+ this.storage.transactionSync(() => {+ // Hashing yields. Recheck the immutable revision before granting a link.+ this.artifacts.group(group.id);+ this.sweep();+ if (+ this.sql+ .exec<{ count: number }>('SELECT COUNT(*) AS count FROM asset_download_tickets')+ .one().count >= MAX_TICKETS+ )+ throw new HttpFailure(+ 429,+ 'Download link limit reached; try again after existing links expire',+ );+ this.sql.exec(+ 'INSERT INTO asset_download_tickets(token_hash,group_id,expires_at,uses) VALUES (?,?,?,0)',+ tokenHash,+ group.id,+ expiresAt,+ );+ });+ return { ticket: token, expiresAt, files };+ }++ private hash(token: string): Promise<string> {+ return sha256(JSON.stringify(['kiln-asset-download-v1', token]));+ }+ private current(hash: string): Ticket {+ const row = this.sql+ .exec<Ticket>(+ 'SELECT * FROM asset_download_tickets WHERE token_hash=? AND expires_at>?',+ hash,+ this.now(),+ )+ .toArray()[0];+ if (!row) throw denied();+ return row;+ }+ private file(row: Ticket, name: string): string {+ const group = this.artifacts.group(row.group_id);+ const id = group.files[name];+ if (!id) throw denied();+ return id;+ }++ async download(token: string, filename: string, headOnly = false): Promise<Response> {+ if (+ typeof token !== 'string' ||+ !DOWNLOAD_TOKEN.test(token) ||+ !DOWNLOAD_FILES.has(filename) ||+ typeof headOnly !== 'boolean'+ )+ throw denied();+ const hash = await this.hash(token);+ const selected = this.storage.transactionSync(() => {+ const row = this.current(hash);+ const id = this.file(row, filename);+ if (row.uses >= MAX_TRANSFERS)+ throw new HttpFailure(429, 'Download link limit reached; request a new link');+ this.sql.exec('UPDATE asset_download_tickets SET uses=uses+1 WHERE token_hash=?', hash);+ return { id, groupId: row.group_id };+ });+ // Failed reads still consume an attempt; requests cannot refund their own quota.+ const response = await this.artifacts.download(selected.id, headOnly);+ try {+ const current = this.current(hash);+ if (current.group_id !== selected.groupId || this.file(current, filename) !== selected.id)+ throw denied();+ return response;+ } catch (error) {+ void response.body?.cancel().catch(() => {});+ throw error;+ }+ }++ /** Bounded by the fixed 128-row per-tenant ceiling; never extends asset retention. */+ sweep(): void {+ this.sql.exec('DELETE FROM asset_download_tickets WHERE expires_at<=?', this.now());+ }+}diff --git a/hosting/src/auth.ts b/hosting/src/auth.tsindex eb716fdb..437eca8c 100644--- a/hosting/src/auth.ts+++ b/hosting/src/auth.ts@@ -4,15 +4,21 @@ import {type ConsentDescription,type OAuthHelpers,} from '@cloudflare/workers-oauth-provider';-import { HttpFailure, readBounded, sha256 } from './http';-import { D1AccountDirectory, IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';+import { HttpFailure } from './http';+import { githubAuthorizationUrl, githubIdentity, type GitHubEnv } from './github';+import { D1BrowserSessions } from './browser-sessions';+import { finishBrowserLogin } from './browser-login';+import { D1Connections } from './connections';+import { finishAccountAction } from './account-actions';+import { finishIdentityAction } from './identity-actions';+import { finishDeletionAction } from './deletion-actions';import { googleAuthorizationUrl, type GoogleEnv, googleIdentity } from './google';import { D1LoginIntents, type SignInProvider } from './login-intents';+import { escapeHtml, htmlPage } from './html-page';+import { GOOGLE_SIGN_IN_BUTTON } from './google-button';export const SCOPES = ['kiln:use', 'offline_access'];-export interface SignInEnv extends GoogleEnv {- GITHUB_CLIENT_ID: string;- GITHUB_CLIENT_SECRET: string;+export interface SignInEnv extends GoogleEnv, GitHubEnv {ACCOUNTS: D1Database;}interface SignInTransaction {@@ -22,87 +28,27 @@ interface SignInTransaction {verifier: string;nonce: string;}-const escapeHtml = (value: string) =>- value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);--function consentPage(details: ConsentDescription, handle: string): string {+function consentPage(details: ConsentDescription, handle: string, headers: Headers): Response {const descriptions: Record<string, string> = {'kiln:use':'Create, inspect, edit, save, download and delete your Kiln assets within your quota.',offline_access: 'Keep this connection working without signing in again for up to 30 days.',};- return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">-<title>Connect to Kiln</title><main><h1>Connect ${escapeHtml(details.clientName)} to Kiln</h1>-<p>${details.clientDomain ? `Client domain: <strong>${escapeHtml(details.clientDomain)}</strong>.` : 'This client registered its own name; that name is not verified.'}</p>-<p>Access will be returned to <strong>${escapeHtml(details.redirectHost)}</strong>.</p>+ return htmlPage(+ 'Connect to Kiln',+ `<h1>Connect ${escapeHtml(details.clientName)} to Kiln</h1>+<section><h2>Review this connection</h2><p class="client-detail">${details.clientDomain ? `Client domain: <strong>${escapeHtml(details.clientDomain)}</strong>.` : 'This client registered its own name; that name is not verified.'}</p>+<p class="client-detail">Access will be returned to <strong>${escapeHtml(details.redirectHost)}</strong>.</p>${details.redirectIsLoopback ? '<p>This connects an app on your computer. Continue only if you started that connection.</p>' : ''}-<ul>${details.scope.map((scope) => `<li>${escapeHtml(descriptions[scope] ?? scope)}</li>`).join('')}</ul>+<ul class="permission-list">${details.scope.map((scope) => `<li>${escapeHtml(descriptions[scope] ?? scope)}</li>`).join('')}</ul></section><p>Hosted access is free within your quota. Sign in to keep saved assets private. Kiln requests no GitHub repository access or Google Drive access.</p><p>Use the same sign-in method when returning to your library.</p><form method="post" action="/authorize"><input type="hidden" name="handle" value="${escapeHtml(handle)}">-<button name="decision" value="google">Continue with Google</button>-<button name="decision" value="github">Continue with GitHub</button>-<button name="decision" value="deny">Cancel</button></form></main></html>`;-}--async function upstreamJson(url: string, init: RequestInit): Promise<Record<string, unknown>> {- const response = await fetch(url, {- ...init,- redirect: 'manual',- signal: AbortSignal.timeout(10_000),- });- if (!response.ok) {- void response.body?.cancel().catch(() => {});- throw new HttpFailure(502, 'Sign-in provider unavailable; restart sign-in');- }- const value: unknown = JSON.parse(- new TextDecoder().decode(await readBounded(response.body, 32_768)),+<div class="provider-buttons"><button class="google-button" name="decision" value="google" aria-label="Continue with Google"><img src="${GOOGLE_SIGN_IN_BUTTON}" width="198" height="44" alt="Sign in with Google"></button>+<button class="github-button" name="decision" value="github">Continue with GitHub</button></div>+<p><button class="secondary" name="decision" value="deny">Cancel connection</button></p></form>`,+ { headers },);- if (!value || typeof value !== 'object' || Array.isArray(value))- throw new HttpFailure(502, 'Invalid sign-in response');- return value as Record<string, unknown>;-}--async function githubIdentity(- code: string,- verifier: string,- origin: string,- env: SignInEnv,-): Promise<VerifiedIdentity> {- const token = await upstreamJson('https://github.com/login/oauth/access_token', {- method: 'POST',- headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },- body: new URLSearchParams({- client_id: env.GITHUB_CLIENT_ID,- client_secret: env.GITHUB_CLIENT_SECRET,- code,- code_verifier: verifier,- redirect_uri: `${origin}/oauth/github/callback`,- }),- });- if (- typeof token.access_token !== 'string' ||- !token.access_token ||- token.access_token.length > 4096 ||- typeof token.token_type !== 'string' ||- token.token_type.toLowerCase() !== 'bearer'- ) {- throw new HttpFailure(400, 'Sign-in failed; restart sign-in');- }- const user = await upstreamJson('https://api.github.com/user', {- headers: {- accept: 'application/vnd.github+json',- authorization: `Bearer ${token.access_token}`,- 'user-agent': 'Kiln-Instrukt-Labs',- 'x-github-api-version': '2026-03-10',- },- });- if (typeof user.id !== 'number' || !Number.isSafeInteger(user.id) || user.id <= 0) {- throw new HttpFailure(502, 'Invalid sign-in identity');- }- // Immutable provider id, never a mutable login or email. Upstream tokens are- // discarded here; the account directory owns the provider-neutral subject.- return { issuer: IDENTITY_ISSUERS.github, subject: String(user.id) };}export async function authorize(@@ -110,6 +56,7 @@ export async function authorize(oauth: OAuthHelpers,origin: string,env: SignInEnv,+ ctx: ExecutionContext,): Promise<Response> {const url = new URL(request.url);const intents = new D1LoginIntents(env.ACCOUNTS, origin);@@ -130,12 +77,7 @@ export async function authorize(}const details = await oauth.describeConsent(auth);const consent = await oauth.beginConsent(auth);- consent.headers.set('content-type', 'text/html; charset=utf-8');- consent.headers.set(- 'content-security-policy',- "default-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",- );- return new Response(consentPage(details, consent.handle), { headers: consent.headers });+ return consentPage(details, consent.handle, consent.headers);}if (url.pathname === '/authorize' && request.method === 'POST') {if (request.headers.get('origin') !== origin) throw new HttpFailure(403, 'Invalid form origin');@@ -188,16 +130,10 @@ export async function authorize();return new Response(null, { status: 302, headers: upstream.headers });}- const target = new URL('https://github.com/login/oauth/authorize');- target.search = new URLSearchParams({- client_id: env.GITHUB_CLIENT_ID,- redirect_uri: `${origin}/oauth/github/callback`,- scope: '',- state: upstream.state,- code_challenge: await sha256(verifier),- code_challenge_method: 'S256',- }).toString();- upstream.headers.set('location', target.href);+ upstream.headers.set(+ 'location',+ await githubAuthorizationUrl(origin, upstream.state, verifier, env),+ );return new Response(null, { status: 302, headers: upstream.headers });}const callbackProvider =@@ -209,6 +145,14 @@ export async function authorize(if (callbackProvider && request.method === 'GET') {if (url.searchParams.getAll('state').length !== 1)throw new HttpFailure(400, 'Invalid sign-in state');+ if (url.searchParams.get('state')?.startsWith('kb1_'))+ return finishBrowserLogin(request, origin, env, callbackProvider);+ if (url.searchParams.get('state')?.startsWith('ka1_'))+ return finishAccountAction(request, origin, env, callbackProvider, oauth, ctx);+ if (url.searchParams.get('state')?.startsWith('ki1_'))+ return finishIdentityAction(request, origin, env, callbackProvider);+ if (url.searchParams.get('state')?.startsWith('kd1_'))+ return finishDeletionAction(request, origin, env, callbackProvider);const resumed = await oauth.finishUpstream<SignInTransaction>(request);if (!resumed.data ||@@ -241,16 +185,33 @@ export async function authorize(env,): await githubIdentity(code, resumed.data.verifier, origin, env);- const account = await new D1AccountDirectory(env.ACCOUNTS).resolveIdentity(identity);+ const browser = await new D1BrowserSessions(env.ACCOUNTS, origin).issue(identity, request);+ const account = browser.account;const userId = account.id;- const { redirectTo } = await oauth.completeAuthorization({- request: resumed.request,- userId,- metadata: {},- scope: resumed.request.scope,- props: { userId, accountEpoch: account.authorizationEpoch },- });+ const connections = new D1Connections(env.ACCOUNTS);+ const props = await connections.create(+ account,+ resumed.request,+ await oauth.describeConsent(resumed.request),+ );+ let redirectTo: string;+ try {+ ({ redirectTo } = await oauth.completeAuthorization({+ request: resumed.request,+ userId,+ metadata: { connectionId: props.connectionId },+ scope: resumed.request.scope,+ props,+ // Each consent is an independently revocable connection. Do not silently+ // revoke another installation that shares this MCP client's identifier.+ revokeExistingGrants: false,+ }));+ } catch (error) {+ await connections.cancelPending(props);+ throw error;+ }resumed.headers.set('location', redirectTo);+ resumed.headers.append('set-cookie', browser.cookie);return new Response(null, { status: 302, headers: resumed.headers });}return new Response('Method not allowed', { status: 405 });diff --git a/hosting/src/browser-cookies.ts b/hosting/src/browser-cookies.tsnew file mode 100644index 00000000..4ca839e1--- /dev/null+++ b/hosting/src/browser-cookies.ts@@ -0,0 +1,21 @@+/** Browser credentials are accepted only once, from a host-scoped cookie. */+export function browserToken(request: Request, origin: string, name: string): string | null {+ if (new URL(request.url).origin !== origin) return null;+ const header = request.headers.get('cookie') ?? '';+ if (header.length > 8192) return null;+ const values = header+ .split(';')+ .map((item) => item.trim())+ .filter((item) => item.split('=', 1)[0] === name);+ if (values.length !== 1) return null;+ const token = values[0]!.slice(name.length + 1);+ return /^[a-f0-9]{64}$/.test(token) ? token : null;+}++export function randomBrowserToken(): string {+ return Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) =>+ byte.toString(16).padStart(2, '0'),+ ).join('');+}++export const BROWSER_COOKIE_ATTRIBUTES = 'Path=/; Secure; HttpOnly; SameSite=Lax';diff --git a/hosting/src/browser-download.ts b/hosting/src/browser-download.tsnew file mode 100644index 00000000..5a3d26b5--- /dev/null+++ b/hosting/src/browser-download.ts@@ -0,0 +1,66 @@+import { signInPage } from './account-page';+import { D1BrowserSessions, type BrowserSession } from './browser-sessions';+import { parseDownloadPath } from './download-path';+import { HttpFailure } from './http';+import { tenantForAccount } from './tenant-identity';+import { limitAccount, type RequestLimitEnv } from './request-limits';++export async function browserDownload(+ request: Request,+ env: { ACCOUNTS: D1Database; TENANTS: DurableObjectNamespace } & Pick<+ RequestLimitEnv,+ 'ACCOUNT_REQUEST_LIMIT'+ >,+ origin: string,+): Promise<Response> {+ const url = new URL(request.url);+ if (url.origin !== origin || url.search || url.hash)+ throw new HttpFailure(400, 'Invalid download link');+ const selected = parseDownloadPath(url.pathname);+ if (!selected) throw new HttpFailure(404, 'Download link unavailable; request a new link');+ if (!['GET', 'HEAD'].includes(request.method))+ return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } });+ const incomingOrigin = request.headers.get('origin');+ const site = request.headers.get('sec-fetch-site');+ if (+ (incomingOrigin !== null && incomingOrigin !== origin) ||+ ((site === 'cross-site' || site === 'same-site') &&+ (request.headers.get('sec-fetch-mode') !== 'navigate' ||+ request.headers.get('sec-fetch-dest') !== 'document'))+ )+ throw new HttpFailure(403, 'Open the download link directly');+ const sessions = new D1BrowserSessions(env.ACCOUNTS, origin);+ let session: BrowserSession;+ try {+ session = await sessions.read(request);+ } catch (error) {+ if (!(error instanceof HttpFailure) || error.status !== 401) throw error;+ return request.method === 'HEAD'+ ? new Response(null, { status: 401 })+ : signInPage(url.pathname);+ }+ const limited = await limitAccount(request, env, origin, session.accountId);+ if (limited) return limited;+ const tenant = await tenantForAccount(origin, session.accountId);+ // Forward no caller headers, cookies, bearer tokens or object selectors.+ const response = await env.TENANTS.getByName(tenant).fetch(+ new Request(+ `https://tenant.internal/internal/downloads/${selected.token}/${selected.filename}`,+ {+ method: request.method,+ signal: request.signal,+ redirect: 'manual',+ },+ ),+ );+ try {+ // Storage reads yield. Revocation must be checked again before releasing bytes.+ const current = await sessions.read(request);+ if (current.accountId !== session.accountId || current.accountEpoch !== session.accountEpoch)+ throw new HttpFailure(401, 'Sign in to continue');+ return response;+ } catch (error) {+ void response.body?.cancel().catch(() => {});+ throw error;+ }+}diff --git a/hosting/src/browser-login.ts b/hosting/src/browser-login.tsnew file mode 100644index 00000000..7d826362--- /dev/null+++ b/hosting/src/browser-login.ts@@ -0,0 +1,130 @@+import type { SignInEnv } from './auth';+import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';+import { D1BrowserSessions } from './browser-sessions';+import { githubAuthorizationUrl, githubIdentity } from './github';+import { googleAuthorizationUrl, googleIdentity } from './google';+import { HttpFailure, sha256 } from './http';+import type { SignInProvider } from './login-intents';+import { validLoginReturn } from './download-path';++const COOKIE = '__Host-kiln-login';+const invalid = () => new HttpFailure(400, 'Invalid or expired sign-in; restart sign-in');+const hash = (origin: string, kind: 'binding' | 'state', value: string) =>+ sha256(JSON.stringify(['kiln-browser-login-v1', origin, kind, value]));+const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;++export async function beginBrowserLogin(+ request: Request,+ origin: string,+ env: SignInEnv,+): Promise<Response> {+ if (request.method !== 'POST')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });+ if (request.headers.get('origin') !== origin) throw new HttpFailure(403, 'Invalid sign-in form');+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')+ throw new HttpFailure(415, 'Expected form data');+ if (new URL(request.url).search) throw invalid();+ const form = await request.formData();+ const provider = form.get('provider');+ const returnTo = form.get('returnTo') ?? '/account';+ if (+ form.getAll('provider').length !== 1 ||+ form.getAll('returnTo').length > 1 ||+ !validLoginReturn(returnTo) ||+ [...form.keys()].some((key) => key !== 'provider' && key !== 'returnTo') ||+ (provider !== 'google' && provider !== 'github')+ )+ throw invalid();+ const flow = {+ state: `kb1_${randomBrowserToken()}`,+ verifier: randomBrowserToken(),+ nonce: randomBrowserToken(),+ };+ const binding = randomBrowserToken();+ const now = Date.now();+ const previous = browserToken(request, origin, COOKIE);+ const database = env.ACCOUNTS.withSession('first-primary');+ const results = await database.batch([+ database+ .prepare(`DELETE FROM kiln_browser_logins WHERE state_hash IN+ (SELECT state_hash FROM kiln_browser_logins WHERE expires_at<=? LIMIT 128)`)+ .bind(now),+ database+ .prepare('DELETE FROM kiln_browser_logins WHERE binding_hash=?')+ .bind(previous ? await hash(origin, 'binding', previous) : ''),+ database+ .prepare(`INSERT INTO kiln_browser_logins(state_hash, binding_hash, provider, verifier, nonce, expires_at, return_to)+ SELECT ?, ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM kiln_browser_logins)<4096 RETURNING state_hash`)+ .bind(+ await hash(origin, 'state', flow.state),+ await hash(origin, 'binding', binding),+ provider,+ flow.verifier,+ flow.nonce,+ now + 600_000,+ returnTo,+ ),+ ]);+ if (results[2]?.results.length !== 1)+ throw new HttpFailure(429, 'Sign-in is busy; please try again later');+ const target =+ provider === 'google'+ ? await googleAuthorizationUrl(origin, flow, env, request.signal)+ : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env);+ return new Response(null, {+ status: 302,+ headers: {+ location: target,+ 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=600`,+ },+ });+}++/** A separate server-retained transaction; no synthetic MCP client or issuer. */+export async function finishBrowserLogin(+ request: Request,+ origin: string,+ env: SignInEnv,+ provider: SignInProvider,+): Promise<Response> {+ const url = new URL(request.url);+ const state = url.searchParams.get('state') ?? '';+ const binding = browserToken(request, origin, COOKIE);+ if (+ request.method !== 'GET' ||+ url.pathname !== `/oauth/${provider}/callback` ||+ url.searchParams.getAll('state').length !== 1 ||+ !/^kb1_[a-f0-9]{64}$/.test(state) ||+ !binding+ )+ throw invalid();+ const flow = await env.ACCOUNTS.withSession('first-primary')+ .prepare(+ `DELETE FROM kiln_browser_logins WHERE state_hash=? AND binding_hash=? AND provider=? AND expires_at>?+ RETURNING verifier, nonce, return_to AS returnTo`,+ )+ .bind(+ await hash(origin, 'state', state),+ await hash(origin, 'binding', binding),+ provider,+ Date.now(),+ )+ .first<{ verifier: string; nonce: string; returnTo: string }>();+ if (!flow || !validLoginReturn(flow.returnTo)) throw invalid();+ if (url.searchParams.has('error'))+ return new Response('Sign-in was cancelled. Return to the account page to try again.', {+ status: 400,+ headers: { 'set-cookie': clearCookie },+ });+ const code = url.searchParams.get('code');+ if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();+ const identity =+ provider === 'google'+ ? await googleIdentity(request, origin, { ...flow, state }, env)+ : await githubIdentity(code, flow.verifier, origin, env);+ const session = await new D1BrowserSessions(env.ACCOUNTS, origin).issue(identity, request);+ const headers = new Headers({ location: flow.returnTo });+ headers.append('set-cookie', clearCookie);+ headers.append('set-cookie', session.cookie);+ return new Response(null, { status: 303, headers });+}diff --git a/hosting/src/browser-sessions.ts b/hosting/src/browser-sessions.tsnew file mode 100644index 00000000..408f371b--- /dev/null+++ b/hosting/src/browser-sessions.ts@@ -0,0 +1,174 @@+import { D1AccountDirectory, type KilnAccount, type VerifiedIdentity } from './accounts';+import { HttpFailure, sha256 } from './http';+import {+ BROWSER_COOKIE_ATTRIBUTES as cookieAttributes,+ browserToken,+ randomBrowserToken,+} from './browser-cookies';++const COOKIE = '__Host-kiln-session';+export const clearBrowserSessionCookie = `${COOKIE}=; ${cookieAttributes}; Max-Age=0`;+const LIFETIME_MS = 86_400_000;+const IDLE_MS = 1_800_000;+const denied = () => new HttpFailure(401, 'Sign in to continue');++export interface BrowserSession {+ /** Server-only session binding. Never render it or accept it as a credential. */+ binding: string;+ accountId: string;+ accountEpoch: number;+ authenticatedAt: number;+ expiresAt: number;+ csrf: string;+}++export class D1BrowserSessions {+ constructor(+ private readonly database: D1Database,+ private readonly origin: string,+ ) {+ const url = new URL(origin);+ if (url.protocol !== 'https:' || url.origin !== origin)+ throw new Error('Invalid browser-session origin');+ }++ /** Call only after a provider adapter has verified a fresh sign-in response. */+ async issue(identity: VerifiedIdentity, previousRequest?: Request) {+ const account = await new D1AccountDirectory(this.database).resolveIdentity(identity);+ return this.issueAccount(account, previousRequest);+ }++ async renew(identity: VerifiedIdentity, proof: BrowserSession, request: Request) {+ if ((await this.requestHash(request)) !== proof.binding) throw denied();+ const account = await new D1AccountDirectory(this.database).getAccount(proof.accountId);+ const binding = await this.database+ .withSession('first-primary')+ .prepare(+ 'SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=? AND account_id=?',+ )+ .bind(identity.issuer, identity.subject, proof.accountId)+ .first();+ if (+ account?.state !== 'active' ||+ account.authorizationEpoch !== proof.accountEpoch ||+ !binding+ )+ throw denied();+ return this.issueAccount(account, request);+ }++ private async issueAccount(account: KilnAccount, previousRequest?: Request) {+ const token = randomBrowserToken();+ const hash = await this.hash(token);+ const csrf = randomBrowserToken();+ const now = Date.now();+ let previousHash = '';+ if (previousRequest) {+ try {+ previousHash = await this.requestHash(previousRequest);+ } catch (error) {+ if (!(error instanceof HttpFailure) || error.status !== 401) throw error;+ }+ }+ const session = this.database.withSession('first-primary');+ const results = await session.batch([+ session+ .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash IN (+ SELECT token_hash FROM kiln_browser_sessions WHERE expires_at<=? LIMIT 128+ )`)+ .bind(now),+ session.prepare('DELETE FROM kiln_browser_sessions WHERE token_hash=?').bind(previousHash),+ session+ .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash IN (+ SELECT token_hash FROM kiln_browser_sessions WHERE account_id=?+ ORDER BY authenticated_at DESC, token_hash DESC LIMIT -1 OFFSET 7+ ) AND EXISTS (SELECT 1 FROM kiln_accounts WHERE id=? AND state='active'+ AND authorization_epoch=?)`)+ .bind(account.id, account.id, account.authorizationEpoch),+ session+ .prepare(`INSERT INTO kiln_browser_sessions+ (token_hash, account_id, account_epoch, authenticated_at, expires_at, idle_expires_at, csrf)+ SELECT ?, id, authorization_epoch, ?, ?, ?, ? FROM kiln_accounts+ WHERE id=? AND state='active' AND authorization_epoch=? RETURNING token_hash`)+ .bind(+ hash,+ now,+ now + LIFETIME_MS,+ now + IDLE_MS,+ csrf,+ account.id,+ account.authorizationEpoch,+ ),+ ]);+ if (results[3]?.results.length !== 1) throw denied();+ return {+ account,+ csrf,+ cookie: `${COOKIE}=${token}; ${cookieAttributes}; Max-Age=${LIFETIME_MS / 1000}`,+ };+ }++ async read(request: Request): Promise<BrowserSession> {+ return this.readCurrent(request, null);+ }++ async authorizeForm(request: Request, csrf: string): Promise<BrowserSession> {+ if (+ request.method !== 'POST' ||+ request.headers.get('origin') !== this.origin ||+ typeof csrf !== 'string' ||+ !/^[a-f0-9]{64}$/.test(csrf)+ )+ throw new HttpFailure(403, 'Invalid account form');+ return this.readCurrent(request, csrf);+ }++ private async readCurrent(request: Request, csrf: string | null): Promise<BrowserSession> {+ const hash = await this.requestHash(request);+ const now = Date.now();+ const session = await this.database+ .withSession('first-primary')+ .prepare(`UPDATE kiln_browser_sessions SET idle_expires_at=MIN(expires_at, ?)+ WHERE token_hash=? AND expires_at>? AND idle_expires_at>? AND (? IS NULL OR csrf=?)+ AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_browser_sessions.account_id+ AND a.state='active' AND a.authorization_epoch=kiln_browser_sessions.account_epoch)+ RETURNING token_hash AS binding, account_id AS accountId, account_epoch AS accountEpoch,+ authenticated_at AS authenticatedAt, expires_at AS expiresAt, csrf`)+ .bind(now + IDLE_MS, hash, now, now, csrf, csrf)+ .first<BrowserSession>();+ if (!session) throw csrf === null ? denied() : new HttpFailure(403, 'Invalid account form');+ return session;+ }++ async logout(request: Request, csrf: string): Promise<string> {+ if (+ request.method !== 'POST' ||+ request.headers.get('origin') !== this.origin ||+ typeof csrf !== 'string' ||+ !/^[a-f0-9]{64}$/.test(csrf)+ )+ throw new HttpFailure(403, 'Invalid account form');+ const hash = await this.requestHash(request);+ const row = await this.database+ .withSession('first-primary')+ .prepare(`DELETE FROM kiln_browser_sessions WHERE token_hash=? AND csrf=?+ AND expires_at>? AND idle_expires_at>? AND EXISTS (SELECT 1 FROM kiln_accounts a+ WHERE a.id=kiln_browser_sessions.account_id AND a.state='active'+ AND a.authorization_epoch=kiln_browser_sessions.account_epoch)+ RETURNING token_hash`)+ .bind(hash, csrf, Date.now(), Date.now())+ .first();+ if (!row) throw new HttpFailure(403, 'Invalid account form');+ return clearBrowserSessionCookie;+ }++ private hash(token: string): Promise<string> {+ return sha256(JSON.stringify(['kiln-browser-session-v1', this.origin, token]));+ }++ private requestHash(request: Request): Promise<string> {+ const token = browserToken(request, this.origin, COOKIE);+ if (!token) throw denied();+ return this.hash(token);+ }+}diff --git a/hosting/src/connections.ts b/hosting/src/connections.tsnew file mode 100644index 00000000..2548a73d--- /dev/null+++ b/hosting/src/connections.ts@@ -0,0 +1,202 @@+import type {+ AuthRequest,+ ConsentDescription,+ GrantType,+} from '@cloudflare/workers-oauth-provider';+import type { KilnAccount, VerifiedIdentity } from './accounts';+import type { BrowserSession } from './browser-sessions';+import { HttpFailure } from './http';++export interface ConnectionProps {+ userId: string;+ accountEpoch: number;+ connectionId: string;+}++export interface KilnConnection {+ id: string;+ clientName: string;+ clientDomain: string | null;+ redirectUri: string;+ scope: string;+ state: 'pending' | 'active' | 'revoked';+ createdAt: number;+ expiresAt: number;+}++function validProps(userId: unknown, props: unknown): props is ConnectionProps {+ if (+ typeof userId !== 'string' ||+ !/^ka_[a-f0-9]{32}$/.test(userId) ||+ !props ||+ typeof props !== 'object'+ )+ return false;+ const value = props as Record<string, unknown>;+ return (+ value.userId === userId &&+ Number.isSafeInteger(value.accountEpoch) &&+ Number(value.accountEpoch) > 0 &&+ typeof value.connectionId === 'string' &&+ /^kc_[a-f0-9]{32}$/.test(value.connectionId)+ );+}++const activeAccount = `EXISTS (SELECT 1 FROM kiln_accounts a+ WHERE a.id=kiln_connections.account_id AND a.state='active'+ AND a.authorization_epoch=kiln_connections.account_epoch)`;++/** This primary SQL authority complements, and never replaces, library token validation. */+export class D1Connections {+ constructor(private readonly database: D1Database) {}++ async create(+ account: KilnAccount,+ request: AuthRequest,+ details: ConsentDescription,+ ): Promise<ConnectionProps> {+ const connectionId = `kc_${crypto.randomUUID().replace(/-/g, '')}`;+ const now = Date.now();+ const session = this.database.withSession('first-primary');+ const rows = await session.batch([+ session+ .prepare(`DELETE FROM kiln_connections WHERE id IN (+ SELECT id FROM kiln_connections WHERE expires_at<=? OR (state='pending' AND created_at<=?) LIMIT 128+ )`)+ .bind(now, now - 600_000),+ session+ .prepare(`INSERT INTO kiln_connections+ (id, account_id, account_epoch, client_id, client_name, client_domain, redirect_uri, scope, created_at, expires_at)+ SELECT ?, id, authorization_epoch, ?, ?, ?, ?, ?, ?, ? FROM kiln_accounts+ WHERE id=? AND state='active' AND authorization_epoch=? AND+ (SELECT COUNT(*) FROM kiln_connections WHERE account_id=? AND account_epoch=?+ AND state IN ('pending','active') AND expires_at>?)<32 RETURNING id`)+ .bind(+ connectionId,+ request.clientId,+ details.clientName,+ details.clientDomain ?? null,+ request.redirectUri,+ request.scope.join(' '),+ now,+ now + 30 * 86_400_000,+ account.id,+ account.authorizationEpoch,+ account.id,+ account.authorizationEpoch,+ now,+ ),+ ]);+ if (rows[1]?.results.length !== 1)+ throw new HttpFailure(+ 429,+ 'Cannot add a connection; sign in again or disconnect an unused app',+ );+ return { userId: account.id, accountEpoch: account.authorizationEpoch, connectionId };+ }++ async cancelPending(props: ConnectionProps): Promise<void> {+ await this.database+ .withSession('first-primary')+ .prepare(+ "DELETE FROM kiln_connections WHERE id=? AND account_id=? AND account_epoch=? AND state='pending'",+ )+ .bind(props.connectionId, props.userId, props.accountEpoch)+ .run();+ }++ /** Claim authorization-code exchange once, before the library writes any token. */+ async exchange(+ userId: string,+ props: unknown,+ clientId: string,+ grantId: string,+ kind: GrantType,+ ): Promise<boolean> {+ if (!validProps(userId, props) || !/^[A-Za-z0-9_-]{1,255}$/.test(grantId)) return false;+ const now = Date.now();+ const session = this.database.withSession('first-primary');+ const predicate = `id=? AND account_id=? AND account_epoch=? AND client_id=? AND expires_at>? AND ${activeAccount}`;+ if (kind === 'authorization_code') {+ const row = await session+ .prepare(`UPDATE kiln_connections SET state='active', grant_id=?+ WHERE ${predicate} AND state='pending' AND grant_id IS NULL AND created_at>?+ RETURNING id`)+ .bind(grantId, props.connectionId, userId, props.accountEpoch, clientId, now, now - 600_000)+ .first();+ return row !== null;+ }+ const row = await session+ .prepare(`SELECT id FROM kiln_connections WHERE ${predicate}+ AND state='active' AND grant_id=?`)+ .bind(props.connectionId, userId, props.accountEpoch, clientId, now, grantId)+ .first();+ return row !== null;+ }++ async accepts(userId: string, props: unknown, clientId: string): Promise<boolean> {+ if (!validProps(userId, props)) return false;+ const row = await this.database+ .withSession('first-primary')+ .prepare(+ `SELECT id FROM kiln_connections WHERE id=? AND account_id=? AND account_epoch=? AND client_id=?+ AND state='active' AND grant_id IS NOT NULL AND expires_at>? AND ${activeAccount}`,+ )+ .bind(props.connectionId, userId, props.accountEpoch, clientId, Date.now())+ .first();+ return row !== null;+ }++ async list(accountId: string, epoch: number): Promise<KilnConnection[]> {+ const now = Date.now();+ const rows = await this.database+ .withSession('first-primary')+ .prepare(+ `SELECT id, client_name AS clientName, client_domain AS clientDomain, redirect_uri AS redirectUri,+ scope, state, created_at AS createdAt, expires_at AS expiresAt FROM kiln_connections+ WHERE account_id=? AND account_epoch=? AND state IN ('pending','active') AND expires_at>?+ AND (state='active' OR created_at>?) AND ${activeAccount}+ ORDER BY created_at DESC, id LIMIT 32`,+ )+ .bind(accountId, epoch, now, now - 600_000)+ .all<KilnConnection>();+ return rows.results;+ }++ /** Only a consumed action and a newly verified, already-linked identity reach this method. */+ async revoke(+ proof: BrowserSession,+ identity: VerifiedIdentity,+ connectionId: string,+ ): Promise<string | null> {+ const now = Date.now();+ const row = await this.database+ .withSession('first-primary')+ .prepare(+ `UPDATE kiln_connections SET state='revoked' WHERE id=? AND account_id=? AND account_epoch=?+ AND state IN ('pending','active') AND expires_at>? AND ${activeAccount}+ AND EXISTS (SELECT 1 FROM kiln_browser_sessions s WHERE s.token_hash=? AND s.account_id=kiln_connections.account_id+ AND s.account_epoch=kiln_connections.account_epoch AND s.expires_at>? AND s.idle_expires_at>?)+ AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=kiln_connections.account_id AND i.issuer=? AND i.subject=?)+ RETURNING grant_id AS grantId`,+ )+ .bind(+ connectionId,+ proof.accountId,+ proof.accountEpoch,+ now,+ proof.binding,+ now,+ now,+ identity.issuer,+ identity.subject,+ )+ .first<{ grantId: string | null }>();+ if (!row)+ throw new HttpFailure(+ 403,+ 'Could not verify this account action; return to your account and try again',+ );+ return row.grantId;+ }+}diff --git a/hosting/src/container-job.ts b/hosting/src/container-job.tsnew file mode 100644index 00000000..c81ec264--- /dev/null+++ b/hosting/src/container-job.ts@@ -0,0 +1,353 @@+import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';++type FailureCode =+ | 'INPUT_INVALID'+ | 'JOB_ALREADY_USED'+ | 'ISOLATION_UNAVAILABLE'+ | 'WORKER_FAILED'+ | 'OUTPUT_LIMIT_EXCEEDED'+ | 'DEADLINE_EXCEEDED'+ | 'CANCELLED'+ | 'CLEANUP_FAILED';++export class ContainerJobFailure extends Error {+ constructor(readonly code: FailureCode) {+ super(code);+ }+}++interface JobRecord {+ state: 'running' | 'finished';+ deadlineAt: number;+ cancelled?: boolean;+ outcome?: FailureCode | 'completed';+}++/** Private host limits, deliberately below the engine protocol's general limits. */+const STDERR_BYTES = 16 * 1024;+const CLEANUP_MS = 5_000;++function boundedInteger(value: number, max: number): boolean {+ return Number.isSafeInteger(value) && value >= 1 && value <= max;+}++async function capture(+ stream: ReadableStream<Uint8Array> | null,+ limit: number,+ check: () => void,+) {+ if (!stream) throw new ContainerJobFailure('WORKER_FAILED');+ const reader = stream.getReader();+ // Tiny chunks must not turn a byte allowance into an unbounded array of objects.+ const bytes = new Uint8Array(limit);+ let size = 0;+ try {+ for (;;) {+ check();+ const { value, done } = await reader.read();+ check();+ if (done) break;+ if (!(value instanceof Uint8Array)) throw new ContainerJobFailure('WORKER_FAILED');+ if (size + value.byteLength > limit) throw new ContainerJobFailure('OUTPUT_LIMIT_EXCEEDED');+ bytes.set(value, size);+ size += value.byteLength;+ }+ return bytes.slice(0, size);+ } catch (error) {+ void reader.cancel().catch(() => {});+ throw error;+ } finally {+ reader.releaseLock();+ }+}++export async function destroyContainer(container: Container): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ (async () => {+ await container.destroy();+ // Keep the watchdog and suppress output unless the provider confirms+ // destruction. Inspection shares the cleanup deadline, including errors+ // and a hung readback; a successful destroy acknowledgement alone is+ // insufficient to release admission for an unconfirmed VM.+ const remaining = await container.inspect();+ if (container.running || remaining !== null)+ throw new ContainerJobFailure('CLEANUP_FAILED');+ })(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new ContainerJobFailure('CLEANUP_FAILED')), CLEANUP_MS);+ }),+ ]);+ } catch {+ throw new ContainerJobFailure('CLEANUP_FAILED');+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++/**+ * One private Durable Object per job. Bytes returned here remain untrusted;+ * the caller must validate the engine's versioned evaluator response.+ * Unit tests cover orchestration, not the provider's isolation guarantees.+ */+class ContainerExecutionJob {+ private readonly verifiedOutputs = new WeakMap<Uint8Array, string>();+ private readonly cancellation = new AbortController();+ private activeRun?: Promise<Uint8Array>;+ private cancellationWork?: Promise<void>;++ constructor(+ private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,+ private readonly kind: ExecutionKind,+ ) {}++ /** Only a returned output after verified image inspection and complete VM cleanup. */+ executionImage(output: Uint8Array): string | undefined {+ return this.verifiedOutputs.get(output);+ }++ run(+ request: Uint8Array,+ controls: { deadlineMs: number; maxResponseBytes: number; signal?: AbortSignal },+ ): Promise<Uint8Array> {+ if (this.activeRun) return Promise.reject(new ContainerJobFailure('JOB_ALREADY_USED'));+ const pending = this.runOnce(request, {+ ...controls,+ signal: controls.signal+ ? AbortSignal.any([controls.signal, this.cancellation.signal])+ : this.cancellation.signal,+ }).then(({ output, image }) => {+ this.verifiedOutputs.set(output, image);+ return output;+ });+ this.activeRun = pending;+ const finished = () => {+ if (this.activeRun === pending) this.activeRun = undefined;+ };+ void pending.then(finished, finished);+ return pending;+ }++ /**+ * Private parent-controller RPC: fence even an as-yet-undelivered child request.+ * Keep one controller per DO instance so cancellation reaches a pending claim+ * before it can start compute. Durable state protects subsequent incarnations.+ * Success means no child VM remains; failure must retain outer admission.+ */+ cancel(): Promise<void> {+ if (this.cancellationWork) return this.cancellationWork;+ const pending = this.cancelOnce().catch(() => {+ throw new ContainerJobFailure('CLEANUP_FAILED');+ });+ this.cancellationWork = pending;+ const finished = () => {+ if (this.cancellationWork === pending) this.cancellationWork = undefined;+ };+ void pending.then(finished, finished);+ return pending;+ }++ private async cancelOnce(): Promise<void> {+ this.cancellation.abort();+ await this.context.storage.transaction(async (transaction) => {+ const job = await transaction.get<JobRecord>('job');+ if (job?.state === 'finished') return;+ if (!job) {+ // A VM is never started before its durable record exists. This tombstone+ // denies a request still in transport, including after this DO is evicted.+ await transaction.put('job', {+ state: 'finished',+ deadlineAt: Date.now(),+ outcome: 'CANCELLED',+ } satisfies JobRecord);+ return;+ }+ await transaction.put('job', { ...job, cancelled: true } satisfies JobRecord);+ await transaction.setAlarm(Date.now());+ });+ // A live run owns its cleanup. Do not race its pending startup with a separate+ // destruction and then return success while that run can still resume.+ await this.activeRun?.catch(() => {});+ const job = await this.context.storage.get<JobRecord>('job');+ if (job?.state === 'running') await this.recover(job);+ }++ private async runOnce(+ request: Uint8Array,+ controls: { deadlineMs: number; maxResponseBytes: number; signal?: AbortSignal },+ ): Promise<{ output: Uint8Array; image: string }> {+ const container = this.context.container;+ if (!container) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');+ const profile = EXECUTION_PROFILES[this.kind];+ const image = container.images[profile.image];+ if (+ typeof image !== 'string' ||+ image.length > 512 ||+ !/^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$/.test(image) ||+ !(request instanceof Uint8Array) ||+ request.byteLength === 0 ||+ request.byteLength > profile.requestBytes ||+ !boundedInteger(controls.deadlineMs, profile.deadlineMs) ||+ !boundedInteger(controls.maxResponseBytes, profile.responseBytes)+ )+ throw new ContainerJobFailure('INPUT_INVALID');+ if (controls.signal?.aborted) throw new ContainerJobFailure('CANCELLED');++ const job: JobRecord = { state: 'running', deadlineAt: Date.now() + controls.deadlineMs };+ // Persist the watchdog before starting compute. Never reuse a completed ID.+ // Another request's failed claim must not destroy the first request's VM.+ const admitted = await this.context.storage.transaction(async (transaction) => {+ if (await transaction.get('job')) return false;+ await transaction.put('job', job);+ await transaction.setAlarm(job.deadlineAt);+ return true;+ });+ if (!admitted) throw new ContainerJobFailure('JOB_ALREADY_USED');++ let failure: ContainerJobFailure | undefined;+ let closing = false;+ let rejectStopped: (error: ContainerJobFailure) => void = () => {};+ const stopped = new Promise<never>((_, reject) => {+ rejectStopped = reject;+ });+ void stopped.catch(() => {});+ const stop = (code: FailureCode) => {+ if (closing || failure) return;+ failure = new ContainerJobFailure(code);+ rejectStopped(failure);+ };+ const check = () => {+ if (failure) throw failure;+ if (closing) throw new ContainerJobFailure('WORKER_FAILED');+ if (Date.now() >= job.deadlineAt) {+ stop('DEADLINE_EXCEEDED');+ throw failure;+ }+ };+ const onAbort = () => stop('CANCELLED');+ controls.signal?.addEventListener('abort', onAbort, { once: true });+ if (controls.signal?.aborted) onAbort();+ const timer = setTimeout(+ () => stop('DEADLINE_EXCEEDED'),+ Math.max(0, job.deadlineAt - Date.now()),+ );++ try {+ const execute = async () => {+ check();+ if (container.running) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');+ container.start({+ image,+ enableInternet: false,+ instance: 'standard-2',+ entrypoint: ['/usr/bin/sleep', 'infinity'],+ env: {},+ });+ void container.monitor().then(+ () => stop('WORKER_FAILED'),+ () => stop('WORKER_FAILED'),+ );+ // A fallback for abandoned requests, never a substitute for the watchdog.+ await container.setInactivityTimeout(120_000);+ check();+ const process = await container.exec(['/usr/local/bin/node', profile.entry], {+ // Native exec requires numeric uid:gid; the pinned image's node user+ // is 1000:1000. This selects file ownership, not an isolation boundary.+ user: '1000:1000',+ env: profile.env,+ stdin: 'pipe',+ stdout: 'pipe',+ stderr: 'pipe',+ });+ check();+ const observed = await container.inspect();+ check();+ if (observed?.image !== image) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');+ if (!process.stdin) throw new ContainerJobFailure('WORKER_FAILED');+ const write = async () => {+ const writer = process.stdin!.getWriter();+ try {+ await writer.write(request);+ await writer.close();+ } finally {+ writer.releaseLock();+ }+ };+ const [, stdout, , exitCode] = await Promise.all([+ write(),+ capture(process.stdout, controls.maxResponseBytes, check),+ capture(process.stderr, STDERR_BYTES, check),+ process.exitCode,+ ]);+ check();+ if (exitCode !== 0 || stdout.byteLength === 0)+ throw new ContainerJobFailure('WORKER_FAILED');+ return stdout;+ };+ return { output: await Promise.race([execute(), stopped]), image };+ } catch (error) {+ failure =+ error instanceof ContainerJobFailure ? error : new ContainerJobFailure('WORKER_FAILED');+ throw failure;+ } finally {+ closing = true;+ clearTimeout(timer);+ controls.signal?.removeEventListener('abort', onAbort);+ // A process kill can leave children running. Wait for destruction of the VM+ // before accepting output or releasing its admission reservation.+ await destroyContainer(container);+ await this.context.storage.put('job', {+ ...job,+ state: 'finished',+ outcome: failure?.code ?? 'completed',+ } satisfies JobRecord);+ await this.context.storage.deleteAlarm();+ }+ }++ async alarm(): Promise<void> {+ const job = await this.context.storage.get<JobRecord>('job');+ if (!job || job.state === 'finished') {+ await this.context.storage.deleteAlarm();+ return;+ }+ // Coalesce an at-least-once alarm with a live parent cancellation instead of+ // starting a second cleanup while the run still owns its destruction.+ if (job.cancelled) return this.cancel();+ if (Date.now() < job.deadlineAt) {+ await this.context.storage.setAlarm(job.deadlineAt);+ return;+ }+ await this.recover(job);+ }++ private async recover(job: JobRecord): Promise<void> {+ const container = this.context.container;+ if (!container) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');+ try {+ await destroyContainer(container);+ await this.context.storage.put('job', {+ ...job,+ state: 'finished',+ outcome: job.cancelled ? 'CANCELLED' : 'DEADLINE_EXCEEDED',+ } satisfies JobRecord);+ await this.context.storage.deleteAlarm();+ } catch {+ await this.context.storage.setAlarm(Date.now() + 30_000);+ throw new ContainerJobFailure('CLEANUP_FAILED');+ }+ }+}++export class ContainerEvaluationJob extends ContainerExecutionJob {+ constructor(context: Pick<DurableObjectState, 'container' | 'storage'>) {+ super(context, 'evaluation');+ }+}++export class ContainerRenderJob extends ContainerExecutionJob {+ constructor(context: Pick<DurableObjectState, 'container' | 'storage'>) {+ super(context, 'render');+ }+}diff --git a/hosting/src/deletion-actions.ts b/hosting/src/deletion-actions.tsnew file mode 100644index 00000000..619cda2e--- /dev/null+++ b/hosting/src/deletion-actions.ts@@ -0,0 +1,190 @@+import { IDENTITY_ISSUERS } from './accounts';+import { D1AccountDeletions } from './account-deletions';+import { deletionStatusPage } from './account-page';+import type { SignInEnv } from './auth';+import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';+import {+ D1BrowserSessions,+ clearBrowserSessionCookie,+ type BrowserSession,+} from './browser-sessions';+import { githubAuthorizationUrl, githubIdentity } from './github';+import { googleAuthorizationUrl, googleIdentity } from './google';+import { HttpFailure, sha256 } from './http';+import type { SignInProvider } from './login-intents';++const COOKIE = '__Host-kiln-delete';+const RECEIPT_COOKIE = '__Host-kiln-deletion-receipt';+const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;+const denied = () => new HttpFailure(403, 'Account deletion could not be confirmed');+const invalid = () =>+ new HttpFailure(+ 400,+ 'Invalid or expired deletion confirmation; return to your account to start again',+ );+const hash = (origin: string, kind: 'state' | 'binding', value: string) =>+ sha256(JSON.stringify(['kiln-delete-action-v1', origin, kind, value]));++export async function beginDeletionAction(+ request: Request,+ origin: string,+ env: SignInEnv,+): Promise<Response> {+ if (request.method !== 'POST')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });+ if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')+ throw new HttpFailure(415, 'Expected form data');+ const form = await request.formData(),+ fields = ['csrf', 'provider', 'confirmation'];+ if (+ fields.some((field) => form.getAll(field).length !== 1) ||+ [...form.keys()].some((field) => !fields.includes(field))+ )+ throw denied();+ const provider = form.get('provider');+ if (+ (provider !== 'google' && provider !== 'github') ||+ form.get('confirmation') !== 'delete-my-account'+ )+ throw denied();+ const proof = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(+ request,+ String(form.get('csrf')),+ );+ const flow = {+ state: `kd1_${randomBrowserToken()}`,+ verifier: randomBrowserToken(),+ nonce: randomBrowserToken(),+ selectAccount: true,+ };+ const binding = randomBrowserToken(),+ now = Date.now();+ const previous = browserToken(request, origin, COOKIE);+ const database = env.ACCOUNTS.withSession('first-primary');+ const rows = await database.batch([+ database+ .prepare(`DELETE FROM kiln_deletion_actions WHERE state_hash IN+ (SELECT state_hash FROM kiln_deletion_actions WHERE expires_at<=? LIMIT 128)`)+ .bind(now),+ database+ .prepare('DELETE FROM kiln_deletion_actions WHERE binding_hash=?')+ .bind(previous ? await hash(origin, 'binding', previous) : ''),+ database+ .prepare(`INSERT INTO kiln_deletion_actions+ (state_hash,binding_hash,session_hash,account_id,account_epoch,provider,verifier,nonce,expires_at)+ SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,?,?,? FROM kiln_browser_sessions s+ JOIN kiln_accounts a ON a.id=s.account_id+ WHERE s.token_hash=? AND s.account_id=? AND s.account_epoch=? AND s.csrf=?+ AND s.expires_at>? AND s.idle_expires_at>? AND a.state='active' AND a.authorization_epoch=s.account_epoch+ AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=a.id AND i.issuer=?)+ AND (SELECT COUNT(*) FROM kiln_deletion_actions WHERE account_id=a.id)<4+ AND (SELECT COUNT(*) FROM kiln_deletion_actions)<4096 RETURNING state_hash`)+ .bind(+ await hash(origin, 'state', flow.state),+ await hash(origin, 'binding', binding),+ provider,+ flow.verifier,+ flow.nonce,+ now + 300_000,+ proof.binding,+ proof.accountId,+ proof.accountEpoch,+ proof.csrf,+ now,+ now,+ IDENTITY_ISSUERS[provider],+ ),+ ]);+ if (rows[2]?.results.length !== 1) throw denied();+ const location =+ provider === 'google'+ ? await googleAuthorizationUrl(origin, flow, env, request.signal)+ : await githubAuthorizationUrl(origin, flow.state, flow.verifier, env, true);+ return new Response(null, {+ status: 302,+ headers: {+ location,+ 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=300`,+ },+ });+}++export async function finishDeletionAction(+ request: Request,+ origin: string,+ env: SignInEnv,+ provider: SignInProvider,+): Promise<Response> {+ const url = new URL(request.url),+ state = url.searchParams.get('state') ?? '';+ const binding = browserToken(request, origin, COOKIE);+ if (+ request.method !== 'GET' ||+ url.pathname !== `/oauth/${provider}/callback` ||+ url.searchParams.getAll('state').length !== 1 ||+ !/^kd1_[a-f0-9]{64}(?![\s\S])/.test(state) ||+ !binding+ )+ throw invalid();+ let proof: BrowserSession;+ try {+ proof = await new D1BrowserSessions(env.ACCOUNTS, origin).read(request);+ } catch (error) {+ if (error instanceof HttpFailure && error.status === 401) throw invalid();+ throw error;+ }+ const flow = await env.ACCOUNTS.withSession('first-primary')+ .prepare(`DELETE FROM kiln_deletion_actions WHERE state_hash=? AND binding_hash=? AND provider=?+ AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?+ AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_deletion_actions.account_id+ AND a.state='active' AND a.authorization_epoch=kiln_deletion_actions.account_epoch)+ RETURNING verifier,nonce,expires_at AS expiresAt`)+ .bind(+ await hash(origin, 'state', state),+ await hash(origin, 'binding', binding),+ provider,+ proof.binding,+ proof.accountId,+ proof.accountEpoch,+ Date.now(),+ )+ .first<{ verifier: string; nonce: string; expiresAt: number }>();+ if (!flow) throw invalid();+ if (url.searchParams.has('error'))+ return new Response('Deletion was cancelled. Your account is unchanged.', {+ status: 400,+ headers: { 'set-cookie': clearCookie },+ });+ const code = url.searchParams.get('code');+ if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();+ const identity =+ provider === 'google'+ ? await googleIdentity(request, origin, { ...flow, state }, env)+ : await githubIdentity(code, flow.verifier, origin, env);+ if (Date.now() >= flow.expiresAt || identity.issuer !== IDENTITY_ISSUERS[provider])+ throw invalid();+ const receipt = randomBrowserToken();+ await new D1AccountDeletions(env.ACCOUNTS, origin).request(proof, identity, receipt);+ const headers = new Headers({ location: '/account/deletion' });+ headers.append('set-cookie', clearCookie);+ headers.append('set-cookie', clearBrowserSessionCookie);+ headers.append(+ 'set-cookie',+ `${RECEIPT_COOKIE}=${receipt}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=2592000`,+ );+ return new Response(null, { status: 303, headers });+}++export async function accountDeletionStatus(+ request: Request,+ database: D1Database,+ origin: string,+): Promise<Response> {+ if (new URL(request.url).search)+ throw new HttpFailure(400, 'Query parameters are not supported on deletion status');+ if (request.method !== 'GET')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'GET' } });+ const receipt = browserToken(request, origin, RECEIPT_COOKIE);+ return deletionStatusPage(await new D1AccountDeletions(database, origin).status(receipt));+}diff --git a/hosting/src/deletion-recovery.ts b/hosting/src/deletion-recovery.tsnew file mode 100644index 00000000..feb57ed4--- /dev/null+++ b/hosting/src/deletion-recovery.ts@@ -0,0 +1,88 @@+import type { OAuthHelpers } from '@cloudflare/workers-oauth-provider';+import { D1AccountDeletions, type DeletionPorts } from './account-deletions';+import type { TenantEnv } from './gateway';+import { readBounded } from './http';+import { tenantForAccount } from './tenant-identity';++export function deletionPorts(+ env: TenantEnv & { ACCOUNTS: D1Database },+ origin: string,+ oauth: Pick<OAuthHelpers, 'listUserGrants' | 'revokeGrant'>,+): DeletionPorts {+ return {+ async retireCompute(accountId) {+ if (!env.NATIVE_COMPUTE) throw new Error('Compute retirement is not configured');+ await env.NATIVE_COMPUTE.retireTenant(await tenantForAccount(origin, accountId));+ },+ async retireStorage(accountId) {+ const tenant = await tenantForAccount(origin, accountId);+ const response = await env.TENANTS.getByName(tenant).fetch(+ 'https://tenant.internal/internal/account-deletion',+ { method: 'POST' },+ );+ if (!response.ok) {+ void response.body?.cancel().catch(() => {});+ throw new Error('Storage retirement failed');+ }+ const value: unknown = JSON.parse(+ new TextDecoder().decode(await readBounded(response.body, 1024)),+ );+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new Error('Invalid storage retirement response');+ const result = value as Record<string, unknown>;+ if (+ Object.keys(result).some(+ (key) => !['state', 'pendingWrites', 'remainingObjects'].includes(key),+ ) ||+ !['retiring', 'purged'].includes(String(result.state)) ||+ !Number.isSafeInteger(result.pendingWrites) ||+ Number(result.pendingWrites) < 0 ||+ !Number.isSafeInteger(result.remainingObjects) ||+ Number(result.remainingObjects) < 0+ )+ throw new Error('Invalid storage retirement response');+ if (+ result.state === 'purged' &&+ (result.pendingWrites !== 0 || result.remainingObjects !== 0)+ )+ throw new Error('Storage purge is unconfirmed');+ return result.state === 'purged';+ },+ async revokeGrants(accountId) {+ const database = env.ACCOUNTS.withSession('first-primary');+ const known = await database+ .prepare(+ 'SELECT DISTINCT grant_id AS id FROM kiln_connections WHERE account_id=? AND grant_id IS NOT NULL LIMIT 4',+ )+ .bind(accountId)+ .all<{ id: string }>();+ const listed = await oauth.listUserGrants(accountId, { limit: 4 });+ if (listed.items.length > 4 || listed.items.some((grant) => grant.userId !== accountId))+ throw new Error('Invalid grant cleanup inventory');+ const ids = [+ ...new Set([...known.results.map((row) => row.id), ...listed.items.map((row) => row.id)]),+ ].slice(0, 4);+ for (const id of ids) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}(?![\s\S])/.test(id))+ throw new Error('Invalid grant cleanup identifier');+ await oauth.revokeGrant(id, accountId);+ await database+ .prepare('UPDATE kiln_connections SET grant_id=NULL WHERE account_id=? AND grant_id=?')+ .bind(accountId, id)+ .run();+ }+ // Empty eventually-consistent KV is not an immediate erasure guarantee.+ // Primary deletion already denies all old grants. Late/stale library records+ // retain their configured TTL; privacy documentation must say so.+ return ids.length === 0 && !listed.cursor;+ },+ };+}++export function recoverAccountDeletions(+ env: TenantEnv & { ACCOUNTS: D1Database },+ origin: string,+ oauth: OAuthHelpers,+) {+ return new D1AccountDeletions(env.ACCOUNTS, origin, deletionPorts(env, origin, oauth)).recover();+}diff --git a/hosting/src/download-path.ts b/hosting/src/download-path.tsnew file mode 100644index 00000000..95ceded6--- /dev/null+++ b/hosting/src/download-path.ts@@ -0,0 +1,20 @@+/** One exact route grammar for native links, browser reads and sign-in resumption. */+export const DOWNLOAD_FILES = new Set([+ 'asset.glb',+ 'source.kiln.js',+ 'preview.png',+ 'manifest.json',+ 'materials.kiln.json',+]);+export const DOWNLOAD_TOKEN = /^[a-f0-9]{64}(?![\s\S])/;++export function parseDownloadPath(path: unknown): { token: string; filename: string } | null {+ if (typeof path !== 'string') return null;+ const parts = path.match(/^\/downloads\/([a-f0-9]{64})\/([a-z.]+)(?![\s\S])/);+ if (!parts || !DOWNLOAD_FILES.has(parts[2]!)) return null;+ return { token: parts[1]!, filename: parts[2]! };+}++export function validLoginReturn(path: unknown): path is string {+ return path === '/account' || parseDownloadPath(path) !== null;+}diff --git a/hosting/src/edge-mcp.ts b/hosting/src/edge-mcp.tsnew file mode 100644index 00000000..feb90149--- /dev/null+++ b/hosting/src/edge-mcp.ts@@ -0,0 +1,163 @@+import {+ createMcpHandler,+ Server,+ ProtocolError,+ ProtocolErrorCode,+ type Tool,+} from '@modelcontextprotocol/server';+import { createDiscoveryService } from '../../src/discovery/service';+import { discoveryInputSchema } from '../../src/discovery/query-schema';+import { describeInputError, schemaFields } from '../../src/tools/actions';+import { parseCatalog } from '../../src/discovery/catalog-schema';+import { createLexicalDiscoveryIndex } from '../../src/discovery/lexical-index';+import { REMOVED_AUTHORING_HELPERS } from '../../src/geometry-catalog';+import manifest from './generated/edge-manifest.json';+import { privateResponse, readBounded } from './http';+import { createPublicTools, hostedInstructions } from './public-tools';++const surface = createPublicTools(manifest.tools as unknown as Tool[]);+const catalog = parseCatalog(manifest.catalog);+const discover = createDiscoveryService(+ catalog,+ createLexicalDiscoveryIndex(catalog),+ async () => {+ throw new Error('Live capabilities require the native host');+ },+ REMOVED_AUTHORING_HELPERS,+);+const fixedCache = { ttlMs: 86_400_000, cacheScope: 'public' as const };+const handler = createMcpHandler(+ () => {+ const server = new Server(manifest.serverInfo, {+ capabilities: manifest.capabilities,+ instructions: hostedInstructions,+ cacheHints: {+ 'server/discover': fixedCache,+ 'tools/list': fixedCache,+ 'resources/list': fixedCache,+ 'resources/templates/list': fixedCache,+ },+ });+ server.setRequestHandler('tools/list', () => ({ tools: surface.tools }));+ server.setRequestHandler('resources/list', () => ({ resources: manifest.resources }));+ server.setRequestHandler('resources/templates/list', () => ({+ resourceTemplates: manifest.resourceTemplates,+ }));+ server.setRequestHandler('tools/call', async (request) => {+ if (+ request.params.name !== 'kiln_discover' ||+ !surface.resolve(request.params.name, request.params.arguments ?? {})+ )+ throw new ProtocolError(+ ProtocolErrorCode.InvalidParams,+ 'Unknown tool or invalid tool request',+ );+ try {+ const result = await discover(request.params.arguments ?? {});+ const { text, textTruncated, ...structured } = result;+ const content = textTruncated+ ? JSON.stringify(structured)+ : structured.suggestions?.length+ ? `${text}\nSuggestions: ${structured.suggestions.join(', ')}`+ : text;+ return { content: [{ type: 'text', text: content }] };+ } catch (error) {+ const text =+ describeInputError('kiln_discover', error, {+ fields: schemaFields(discoveryInputSchema),+ }) ?? 'Discovery is temporarily unavailable';+ // Match the pinned engine's diagnostic redaction without importing its Node-only core.+ // Native-host parity tests cover both schema errors and caller-supplied path keys.+ const safe = text.replace(+ /(?<![A-Za-z0-9])(?:[A-Za-z]:[\\/]|\\\\[^\s"'`]+|\/(?:home|Users|tmp|var|opt|mnt|root|srv|private)\/)[^\s"'`)\]]*/gu,+ '<local path>',+ );+ return { isError: true, content: [{ type: 'text', text: safe }] };+ }+ });+ return server;+ },+ { legacy: 'stateless', maxRequestBodySize: 1024 * 1024, maxSubscriptions: 0, onerror: () => {} },+);++const record = (value: unknown): value is Record<string, unknown> =>+ value !== null && typeof value === 'object' && !Array.isArray(value);++function nativeCall(value: unknown): { params?: Record<string, unknown> } | undefined {+ if (+ !record(value) ||+ value.jsonrpc !== '2.0' ||+ !(+ typeof value.id === 'string' ||+ (typeof value.id === 'number' && Number.isFinite(value.id))+ ) ||+ !record(value.params)+ )+ return undefined;+ if (value.method === 'resources/read')+ return typeof value.params.uri === 'string' ? {} : undefined;+ if (value.method !== 'tools/call' || typeof value.params.name !== 'string') return undefined;+ if (value.params.arguments !== undefined && !record(value.params.arguments)) return undefined;+ const resolved = surface.resolve(value.params.name, value.params.arguments ?? {});+ if (!resolved || value.params.name === 'kiln_discover') return undefined;+ return resolved.name === value.params.name ? {} : { params: { ...value.params, ...resolved } };+}++/** Called only after OAuth and account checks, over the bounded credential-free request. */+export async function routeEdgeMcp(request: Request): Promise<Response | Request> {+ if (request.method === 'POST') {+ // Inspect a bounded copy; the original stream remains available to native admission.+ const bytes = await readBounded(request.clone().body, 1024 * 1024, request.signal);+ let message: unknown;+ try {+ message = JSON.parse(+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes),+ );+ } catch {+ /* The maintained MCP handler owns malformed-message responses. */+ }+ if (record(message) && record(message.params)) {+ const method = request.headers.get('mcp-method');+ const name = request.headers.get('mcp-name');+ const toolName = typeof message.params.name === 'string' ? message.params.name : '';+ const matchesName =+ name === toolName ||+ (/^[\x20-\x7e]+$/.test(toolName) && name === `=?base64?${btoa(toolName)}?=`);+ if (+ (method !== null && method !== message.method) ||+ (name !== null && message.method === 'tools/call' && !matchesName)+ ) {+ return privateResponse(+ Response.json(+ {+ jsonrpc: '2.0',+ id:+ typeof message.id === 'string' || typeof message.id === 'number'+ ? message.id+ : null,+ error: {+ code: ProtocolErrorCode.InvalidParams,+ message: 'MCP routing headers disagree with the request',+ },+ },+ { status: 400 },+ ),+ );+ }+ }+ const native = nativeCall(message);+ if (native) {+ if (!native.params) return request;+ const headers = new Headers(request.headers);+ // Modern MCP checks routing metadata as well as the JSON envelope.+ // Rewrite only a header already matched against the public operation above.+ if (headers.has('mcp-name')) headers.set('mcp-name', String(native.params.name));+ headers.delete('content-length');+ return new Request(request, {+ headers,+ body: JSON.stringify({ ...(message as object), params: native.params }),+ });+ }+ }+ return privateResponse(await handler.fetch(request));+}diff --git a/hosting/src/evaluation-request.ts b/hosting/src/evaluation-request.tsnew file mode 100644index 00000000..67434153--- /dev/null+++ b/hosting/src/evaluation-request.ts@@ -0,0 +1,133 @@+import { ContainerJobFailure, type ContainerEvaluationJob } from './container-job';+import { HttpFailure, privateResponse, readBounded, serviceFailure } from './http';+import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';++const allowedHeaders = new Set([+ 'content-type',+ 'content-length',+ 'x-kiln-deadline-ms',+ 'x-kiln-max-response-bytes',+ // Fetch implementations add these transport fields. None selects identity or work.+ 'accept',+ 'accept-encoding',+ 'accept-language',+ 'connection',+ 'host',+ 'user-agent',+ 'sec-fetch-mode',+]);+type ExecutionJob = Pick<ContainerEvaluationJob, 'run'> &+ Partial<Pick<ContainerEvaluationJob, 'executionImage'>>;++function limit(header: string | null, max: number): number {+ if (header === null || !/^[1-9]\d{0,8}$/.test(header) || Number(header) > max)+ throw new HttpFailure(400, 'Invalid evaluation limit');+ return Number(header);+}++/**+ * Private, single-job HTTP boundary. The outer controller supplies the fresh DO+ * and holds admission; this handler cannot choose a tenant, image or executable.+ * Never expose this route directly from a public Worker.+ */+async function handleExecutionRequest(+ request: Request,+ job: ExecutionJob,+ kind: ExecutionKind,+): Promise<Response> {+ const profile = EXECUTION_PROFILES[kind];+ try {+ if (request.url !== profile.url || request.method !== 'POST')+ throw new HttpFailure(400, 'Invalid evaluation request');+ for (const [name, value] of request.headers)+ if (!allowedHeaders.has(name) || value.length > 512)+ throw new HttpFailure(400, 'Invalid evaluation header');+ if (request.headers.get('content-type') !== 'application/json')+ throw new HttpFailure(415, 'Evaluation requires application/json');+ const deadlineMs = limit(request.headers.get('x-kiln-deadline-ms'), profile.deadlineMs);+ const maxResponseBytes = limit(+ request.headers.get('x-kiln-max-response-bytes'),+ profile.responseBytes,+ );+ const declared = limit(request.headers.get('content-length'), profile.requestBytes);+ const deadlineAt = Date.now() + deadlineMs;+ const reading = new AbortController();+ const cancelRead = () => reading.abort();+ let expired = false;+ request.signal.addEventListener('abort', cancelRead, { once: true });+ if (request.signal.aborted) cancelRead();+ const timer = setTimeout(() => {+ expired = true;+ reading.abort();+ }, deadlineMs);+ let body: Uint8Array<ArrayBuffer>;+ try {+ body = await readBounded(request.body, profile.requestBytes, reading.signal);+ } catch (error) {+ if (expired) throw new HttpFailure(504, 'Evaluation deadline exceeded');+ throw error;+ } finally {+ clearTimeout(timer);+ request.signal.removeEventListener('abort', cancelRead);+ }+ if (body.byteLength !== declared) throw new HttpFailure(400, 'Invalid evaluation length');+ const remaining = deadlineAt - Date.now();+ if (remaining < 1) throw new HttpFailure(504, 'Evaluation deadline exceeded');+ // No independent timeout race here: run owns the deadline, durable watchdog+ // and verified VM destruction. Aborting HTTP must not abandon that cleanup.+ const output = await job.run(body, {+ deadlineMs: remaining,+ maxResponseBytes,+ signal: request.signal,+ });+ if (+ !(output instanceof Uint8Array) ||+ output.byteLength === 0 ||+ output.byteLength > maxResponseBytes+ )+ throw new Error('Invalid evaluation output');+ const headers = new Headers({+ 'content-type': 'application/json',+ 'content-length': String(output.byteLength),+ });+ if (kind === 'evaluation') {+ const image = job.executionImage?.(output);+ const digest =+ typeof image === 'string' && image.length <= 512+ ? /^[a-zA-Z0-9._:/-]+@(sha256:[a-f0-9]{64})(?![\s\S])/.exec(image)?.[1]+ : undefined;+ if (!digest) throw new ContainerJobFailure('ISOLATION_UNAVAILABLE');+ // This header is outside the VM's stdout and is never copied from a request.+ headers.set('x-kiln-execution-image', digest);+ }+ return privateResponse(+ new Response(output, {+ headers,+ }),+ );+ } catch (error) {+ void request.body?.cancel().catch(() => {});+ if (error instanceof ContainerJobFailure) {+ const statuses = {+ INPUT_INVALID: 400,+ JOB_ALREADY_USED: 409,+ ISOLATION_UNAVAILABLE: 503,+ WORKER_FAILED: 503,+ OUTPUT_LIMIT_EXCEEDED: 502,+ DEADLINE_EXCEEDED: 504,+ CANCELLED: 499,+ CLEANUP_FAILED: 503,+ } as const;+ return privateResponse(+ new Response('Evaluation did not complete', { status: statuses[error.code] }),+ );+ }+ return privateResponse(serviceFailure(error));+ }+}++export const handleEvaluationRequest = (request: Request, job: ExecutionJob) =>+ handleExecutionRequest(request, job, 'evaluation');++export const handleRenderRequest = (request: Request, job: Pick<ContainerEvaluationJob, 'run'>) =>+ handleExecutionRequest(request, job, 'render');diff --git a/hosting/src/evaluation-worker.ts b/hosting/src/evaluation-worker.tsnew file mode 100644index 00000000..5498f307--- /dev/null+++ b/hosting/src/evaluation-worker.ts@@ -0,0 +1,26 @@+import { DurableObject } from 'cloudflare:workers';+import { ContainerEvaluationJob } from './container-job';+import { handleEvaluationRequest } from './evaluation-request';++/** Only the private dispatcher receives this binding; never the public gateway. */+export class KilnEvaluationJob extends DurableObject {+ private readonly job = new ContainerEvaluationJob(this.ctx);++ fetch(request: Request): Promise<Response> {+ return handleEvaluationRequest(request, this.job);+ }++ cancel(): Promise<void> {+ return this.job.cancel();+ }++ alarm(): Promise<void> {+ return this.job.alarm();+ }+}++export default {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ },+};diff --git a/hosting/src/execution-profiles.ts b/hosting/src/execution-profiles.tsnew file mode 100644index 00000000..509e1101--- /dev/null+++ b/hosting/src/execution-profiles.ts@@ -0,0 +1,24 @@+import { RENDER_LIMITS } from './render-limits';++/** Host-selected profiles only. No HTTP or tool field chooses code, image or environment. */+export const EXECUTION_PROFILES = {+ evaluation: {+ url: 'http://kiln-evaluator.internal/evaluate',+ image: 'kiln',+ entry: '/opt/kiln/evaluate.mjs',+ env: { KILN_RENDER: 'cpu' } as Record<string, string>,+ requestBytes: 4 * 1024 * 1024,+ responseBytes: 8 * 1024 * 1024,+ deadlineMs: 60_000,+ },+ render: {+ url: 'http://kiln-renderer.internal/render',+ image: 'renderer',+ entry: '/opt/kiln/render.mjs',+ env: {} as Record<string, string>,+ requestBytes: RENDER_LIMITS.requestBytes,+ responseBytes: RENDER_LIMITS.responseBytes,+ deadlineMs: RENDER_LIMITS.deadlineMs,+ },+} as const;+export type ExecutionKind = keyof typeof EXECUTION_PROFILES;diff --git a/hosting/src/gateway.ts b/hosting/src/gateway.tsindex 3e066b7e..ce5ce052 100644--- a/hosting/src/gateway.ts+++ b/hosting/src/gateway.ts@@ -1,19 +1,26 @@import { insufficientScope, type OAuthResourceContext } from '@cloudflare/workers-oauth-provider';-import { boundedRequest, HttpFailure, sha256 } from './http';+import { boundedRequest, HttpFailure } from './http';+import { tenantForAccount } from './tenant-identity';+import type { KilnCompute } from './admission-worker';+import { routeEdgeMcp } from './edge-mcp';+import { limitAccount, type RequestLimitEnv } from './request-limits';export interface TenantEnv {TENANTS: DurableObjectNamespace;+ NATIVE_COMPUTE?: Service<KilnCompute>;}export async function forwardTenant(request: Request,- env: TenantEnv,+ env: TenantEnv & Pick<RequestLimitEnv, 'ACCOUNT_REQUEST_LIMIT'>,ctx: OAuthResourceContext<unknown>,origin: string,): Promise<Response> {if (!ctx.auth.scope.includes('kiln:use')) return insufficientScope(ctx.auth, ['kiln:use']);const userId = ctx.auth.userId;if (!userId || !/^ka_[a-f0-9]{32}$/.test(userId)) throw new HttpFailure(401, 'Invalid identity');+ const limited = await limitAccount(request, env, origin, userId);+ if (limited) return limited;const url = new URL(request.url);const isMcp = url.pathname === '/mcp';const isArtifact = /^\/mcp\/artifacts\/[A-Za-z0-9_-]{16,128}$/.test(url.pathname);@@ -33,7 +40,7 @@ export async function forwardTenant(const bounded = await boundedRequest(request, 1024 * 1024);// Only verified authorization identity selects the object. Token, client id,// session id, source refs, cookies and caller tenant headers cannot select it.- const tenant = await sha256(JSON.stringify(['kiln-tenant-v1', origin, userId]));+ const tenant = await tenantForAccount(origin, userId);const headers = new Headers();for (const name of ['accept',@@ -55,5 +62,11 @@ export async function forwardTenant(signal: bounded.signal,redirect: 'manual',});+ if (isMcp) {+ const edge = await routeEdgeMcp(internal);+ if (edge instanceof Response) return edge;+ if (!env.NATIVE_COMPUTE) throw new HttpFailure(503, 'Native compute is not configured');+ return env.NATIVE_COMPUTE.dispatch(tenant, edge);+ }return env.TENANTS.getByName(tenant).fetch(internal);}diff --git a/hosting/src/generated/edge-manifest.json b/hosting/src/generated/edge-manifest.jsonnew file mode 100644index 00000000..be15f200--- /dev/null+++ b/hosting/src/generated/edge-manifest.json@@ -0,0 +1,12655 @@+{+ "kind": "kiln.hosted-edge.v1",+ "serverInfo": {+ "name": "kiln",+ "version": "1.0.0"+ },+ "capabilities": {+ "tools": {},+ "resources": {},+ "extensions": {+ "io.modelcontextprotocol/ui": {+ "mimeTypes": [+ "text/html;profile=mcp-app"+ ]+ }+ }+ },+ "instructions": "Kiln turns JavaScript you write into GLB assets and returns rendered views. Work by reference: send a program once to kiln_validate or kiln_render, keep the returned programRef exactly, and use it for every later render, inspect, kiln_source and kiln_edit call; never resend a program to change part of it. Call kiln_discover first for helper contracts, with capabilities:true for the host's runtime, project and camera facts. Read viewFidelity before judging materials: a CPU view shows shape, not material; GPU views need the render service in render-service/. Agent Skills for authoring, refining, QA and scenes ship in skills/ beside this server's dist/; read the matching SKILL.md first.",+ "tools": [+ {+ "name": "kiln_discover",+ "description": "Discover Kiln operations, assemblies, recipes, tool-input shapes and current host capabilities. Omit arguments for a compact overview. Search with ordinary modeling language using query; refine with family, kind or tags. Fetch complete contracts/examples with ids (up to six exact IDs, executable names or shape: ids). Overview/search pages default to six summaries. Recipes guide construction without restricting the asset. Search runs locally without models or network calls.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 1,+ "maxLength": 500+ },+ "ids": {+ "minItems": 1,+ "maxItems": 6,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 120+ }+ },+ "overview": {+ "type": "boolean",+ "const": true+ },+ "capabilities": {+ "type": "boolean",+ "const": true+ },+ "family": {+ "type": "string",+ "minLength": 1,+ "maxLength": 120+ },+ "kind": {+ "type": "string",+ "enum": [+ "operation",+ "assembly",+ "recipe",+ "shape"+ ]+ },+ "tags": {+ "minItems": 1,+ "maxItems": 8,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 120+ }+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 10000+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 12+ }+ },+ "additionalProperties": false+ },+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_renderer",+ "description": "Inspect status, or reprobe after renderer setup/repair to refresh this session and reset failed starts. Never installs, starts, stops or renders. Preserves CPU/local/remote selection; environment/credential changes require a host restart. Read viewFidelity after rendering.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "action": {+ "default": "status",+ "type": "string",+ "enum": [+ "status",+ "reprobe"+ ]+ }+ },+ "additionalProperties": false+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_validate",+ "description": "Check program syntax, sandbox rules and retired globals before building. Returns findings with codes, lines and repair hints where available; use kiln_render to evaluate geometry and see the asset. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ }+ }+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_render",+ "description": "Build and return metrics, part paths and images. If partsTruncated, use kiln_inspect listParts. Omit capture for six views, preset/cells for orbit grids, or kiln.capture.v1/v2 shots for exact orthographic/perspective cameras; v2 adds hide. Check viewFidelity before judging materials. Failed builds return errors without images. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "capture": {+ "description": "Omit for six views; preset/cells for orbit sheets. Use kiln.capture.v1 or v2 with 1..9 shots for exact cameras. v2 adds hide: exact paths or unique names. Framing retains subject bounds.",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "version": {+ "type": "string",+ "enum": [+ "kiln.capture.v1",+ "kiln.capture.v2"+ ]+ },+ "shots": {+ "minItems": 1,+ "maxItems": 9,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "subject": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "visibility": {+ "type": "string",+ "enum": [+ "context",+ "isolate"+ ]+ },+ "hide": {+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1024+ }+ },+ "camera": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "orbit"+ },+ "azimuthDeg": {+ "type": "number"+ },+ "elevationDeg": {+ "type": "number"+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ }+ },+ "required": [+ "type"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "explicit"+ },+ "projection": {+ "type": "string",+ "enum": [+ "orthographic",+ "perspective"+ ]+ },+ "position": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "target": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part",+ "local"+ ]+ },+ "frame": {+ "type": "object",+ "properties": {+ "origin": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "rotation": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ }+ },+ "additionalProperties": false+ },+ "framing": {+ "type": "string",+ "enum": [+ "explicit",+ "bounds"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ },+ "targetOffset": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "up": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "halfHeight": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "fovDeg": {+ "type": "number",+ "exclusiveMinimum": 0,+ "exclusiveMaximum": 180+ },+ "near": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "far": {+ "type": "number",+ "exclusiveMinimum": 0+ }+ },+ "required": [+ "type",+ "projection",+ "position"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "additionalProperties": false+ }+ },+ "cols": {+ "type": "integer",+ "minimum": 1,+ "maximum": 3+ },+ "size": {+ "type": "integer",+ "minimum": 128,+ "maximum": 2048+ },+ "output": {+ "type": "string",+ "enum": [+ "grid",+ "separate"+ ]+ },+ "backdrop": {+ "description": "neutral (default); light for dark parts, dark for light parts.",+ "type": "string",+ "enum": [+ "neutral",+ "dark",+ "light"+ ]+ }+ },+ "required": [+ "version",+ "shots"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "preset": {+ "description": "COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3.",+ "type": "string",+ "enum": [+ "1x1",+ "1x2",+ "2x1",+ "3x1",+ "2x2",+ "3x2",+ "3x3"+ ]+ },+ "cells": {+ "description": "Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9).",+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "azimuthDeg": {+ "type": "number",+ "description": "0 = front, 90 = right, 180 = back, 270 = left. Wraps."+ },+ "elevationDeg": {+ "type": "number",+ "description": "0 eye level; positive above, negative below. Clamped -89..89."+ },+ "zoom": {+ "description": "Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing.",+ "type": "number"+ },+ "name": {+ "description": "Label; defaults to angles.",+ "type": "string"+ }+ },+ "required": [+ "azimuthDeg",+ "elevationDeg"+ ]+ }+ },+ "backdrop": {+ "description": "neutral (default); light for dark parts, dark for light parts.",+ "type": "string",+ "enum": [+ "neutral",+ "dark",+ "light"+ ]+ }+ },+ "additionalProperties": false+ }+ ]+ },+ "detail": {+ "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",+ "type": "string",+ "enum": [+ "lean",+ "compact",+ "full"+ ]+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ }+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_screenshot_animation",+ "description": "Review animation images, poseBounds and loopClosure endpoint evidence. loopIntent is createClip({loop}); open is valid for one-shots; closed endpoints do not prove smooth velocity. Check motion, attachments and requested clearance; sampled bounds do not certify continuous contact or collision safety. Use shot for camera/subject, frameTimes for phases, and framing locked (default) or follow. Add phases when symmetry hides motion. The program must define animate(). Check viewFidelity before judging materials. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "shot": {+ "description": "One exact camera shot. Shape: kiln_discover ids [\"shape:camera-shot\"].",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "measureParts": {+ "description": "Exact names or paths of subtrees measured together at each phase, independent of camera selection.",+ "minItems": 1,+ "maxItems": 16,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ "frames": {+ "type": "integer",+ "minimum": 2,+ "maximum": 6+ },+ "frameTimes": {+ "description": "Ordered phase fractions 0..1; mutually exclusive with frames.",+ "minItems": 1,+ "maxItems": 9,+ "type": "array",+ "items": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "framing": {+ "type": "string",+ "enum": [+ "locked",+ "follow"+ ]+ },+ "size": {+ "description": "Frame size in px; default 256.",+ "type": "integer",+ "minimum": 128,+ "maximum": 1024+ },+ "detail": {+ "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",+ "type": "string",+ "enum": [+ "lean",+ "compact",+ "full"+ ]+ },+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "clip": {+ "type": "string",+ "description": "The animation clip to view, by name (e.g. \"walk\", \"attack\"). Must be one your animate() returns."+ },+ "camera": {+ "description": "Camera angle: right (default — side profile, best for leg swing + knee bend direction), front (reveals sideways/lateral motion), back, left, top, or three-quarter.",+ "type": "string"+ },+ "perFrame": {+ "description": "Return the frames as separate high-res images instead of one composite grid. Default false.",+ "type": "boolean"+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "clip"+ ]+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_view_interior",+ "description": "Render roof-off floor-plan, dollhouse, and eye-level cutaway views. Optional versioned capture selects custom roof-off shots. Select a roof by nodeName or let Kiln resolve its role/name. Review roofsHidden and warnings for unresolved occlusion. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "capture": {+ "description": "Cameras, as kiln_render capture takes them. Shape: kiln_discover ids [\"shape:capture\"].",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "nodeName": {+ "description": "Override: lift the roof by exact node name instead of by role. Matches that node and its children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built with createRoofPlanes/createGableRoof), falling back to historical \"Roof\" naming.",+ "type": "string"+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ }+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_inspect",+ "description": "List part paths and inspect joints, clearances and edit preservation. listParts filters names/paths with query; follow partListing.nextOffset on the same programRef/query. measure/surfacePairs return distances, not fit certificates. compare reports static changes and separate animation channel changes; paths adds complete static subtree summaries. image:false skips rendering. Otherwise use part/orbit or exact shot; check viewFidelity for materials. Supply code OR programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas). Invalid drafts keep a ref.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "image": {+ "description": "False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true.",+ "type": "boolean"+ },+ "detail": {+ "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",+ "type": "string",+ "enum": [+ "lean",+ "compact",+ "full"+ ]+ },+ "listParts": {+ "description": "List exported-scene paths, including nested parts. Default 80, max 100 per page. Follow partListing.nextOffset with the same programRef/query. image:false avoids rendering.",+ "type": "object",+ "properties": {+ "query": {+ "description": "Case-insensitive substring of name or exact encoded path; not a regex.",+ "type": "string",+ "maxLength": 4096+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100+ },+ "placement": {+ "description": "Add world position, rotation, scale, mirroring and bounds per part; pages of 50.",+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },+ "surfacePairs": {+ "description": "[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result.",+ "minItems": 1,+ "maxItems": 12,+ "type": "array",+ "items": {+ "minItems": 2,+ "maxItems": 2,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 4096+ }+ }+ },+ "compare": {+ "description": "Static geometry/material/transform/bounds under current host settings. Follow nextOffset; paths adds complete subtrees.",+ "type": "object",+ "properties": {+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100+ },+ "paths": {+ "description": "Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.",+ "minItems": 1,+ "maxItems": 12,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 4096+ }+ }+ },+ "required": [+ "programRef"+ ],+ "additionalProperties": false+ },+ "measure": {+ "description": "Default anchors: origin/local-point distance. Surface: disjoint mesh triangles, omit points. Rest pose, asset units. Check status/bounds; no solid clearance/attachment proof.",+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "anchors",+ "surface"+ ]+ },+ "from": {+ "type": "object",+ "properties": {+ "subject": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "point": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ }+ },+ "required": [+ "subject"+ ],+ "additionalProperties": false+ },+ "to": {+ "type": "object",+ "properties": {+ "subject": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "point": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ }+ },+ "required": [+ "subject"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "from",+ "to"+ ],+ "additionalProperties": false+ },+ "shot": {+ "description": "One exact camera shot. Shape: kiln_discover ids [\"shape:camera-shot\"].",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "part": {+ "description": "Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset.",+ "type": "string"+ },+ "view": {+ "description": "front/right/back/left/top/three-quarter (default). Orbit angles override.",+ "type": "string"+ },+ "azimuthDeg": {+ "description": "Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps.",+ "type": "number"+ },+ "elevationDeg": {+ "description": "Elevation degrees: 0 eye level, positive above. Clamped -89..89.",+ "type": "number"+ },+ "zoom": {+ "description": "Bounds padding 1..4; default 1.2. Larger = more context.",+ "type": "number"+ },+ "isolate": {+ "description": "Hide surrounding geometry. Requires part; default false.",+ "type": "boolean"+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ }+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_edit",+ "description": "Atomically apply ordered exact-string replacements and render. Copy anchors from kiln_source. Supply code OR programRef. Returns programRef (unsaved source is kept for seven days after upload; saved source is retained until its last saved revision is deleted, within tenant quotas), parentRef, diff and preservation comparing static data and animation channels. Review changes; use kiln_inspect compare for more pages or protected subtrees. Failed comparison preserves the repair; render:false leaves preservation not_assessed. capture selects cameras; includeCode adds the patched source, bounded.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "code": {+ "description": "New source.",+ "type": "string"+ },+ "edits": {+ "minItems": 1,+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "oldString": {+ "type": "string",+ "description": "The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."+ },+ "newString": {+ "type": "string",+ "description": "The replacement text. Use an empty string to delete."+ },+ "replaceAll": {+ "description": "Replace every occurrence instead of failing when oldString matches more than once.",+ "type": "boolean"+ }+ },+ "required": [+ "oldString",+ "newString"+ ]+ },+ "description": "Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."+ },+ "render": {+ "description": "Render the patched program and return the views (default true). false = patch only.",+ "type": "boolean"+ },+ "capture": {+ "description": "Cameras, as kiln_render capture takes them. Shape: kiln_discover ids [\"shape:capture\"].",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "detail": {+ "description": "compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path",+ "type": "string",+ "enum": [+ "lean",+ "compact",+ "full"+ ]+ },+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "includeCode": {+ "description": "Also return the patched source, bounded with the result; kiln_source pages it. Default false.",+ "type": "boolean"+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "edits"+ ]+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_source",+ "description": "Read a saved program revision without changing it. Returns exact source text in bounded pages, or searches for literal text with surrounding context. Copy edit anchors from code. Follow nextOffset for more; use matchOffset + 1 to find the next match. Offsets count UTF-16 characters, not bytes.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "programRef": {+ "type": "string",+ "pattern": "^(?:sha256:[a-f0-9]{64}|p_[a-f0-9]{12}(?:[a-f0-9]{4}){0,13})(?![\\s\\S])",+ "description": "Returned p_ handle or full sha256 ref."+ },+ "offset": {+ "default": 0,+ "description": "UTF-16 character offset; use nextOffset to continue.",+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "default": 8000,+ "description": "Maximum characters returned.",+ "type": "integer",+ "minimum": 1,+ "maximum": 16000+ },+ "query": {+ "description": "Find literal text at or after offset; return bounded surrounding source.",+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ }+ },+ "required": [+ "programRef"+ ]+ },+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_material",+ "description": "Manage optional immutable material resources in this workspace. presets discovers shipped architecture, wood, metal, fabric and ground recipes; create-preset bakes one with an explicit seed, creator and license; list returns compact material/revision summaries; get returns full provenance, hashes, map conventions, physical repeat scale and a code-ready portable material spec; create-procedural bakes bounded editable layer recipes including optional height-derived normals; import accepts complete normalized records with embedded PNG bytes. No action downloads URLs or executes source. Pin the returned materialId/revisionId through per-invocation materialDependencies or project dependencies before authored evaluation resolves the resources; no project is required.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "presets",+ "create-preset",+ "list",+ "get",+ "create-procedural",+ "import"+ ]+ },+ "tag": {+ "description": "presets, list: keep one tag.",+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "presetId": {+ "description": "create-preset: an id from presets.",+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "seed": {+ "description": "create-preset.",+ "type": "integer",+ "minimum": -2147483648,+ "maximum": 2147483647+ },+ "size": {+ "description": "create-preset: map edge in pixels; default 256.",+ "anyOf": [+ {+ "type": "number",+ "const": 64+ },+ {+ "type": "number",+ "const": 128+ },+ {+ "type": "number",+ "const": 256+ },+ {+ "type": "number",+ "const": 512+ }+ ]+ },+ "creator": {+ "description": "create-preset.",+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "license": {+ "description": "create-preset: spdx, url and attribution.",+ "type": "object",+ "properties": {+ "spdx": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "url": {+ "type": "string",+ "maxLength": 2000,+ "format": "uri"+ },+ "attribution": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "required": [+ "spdx",+ "url",+ "attribution"+ ],+ "additionalProperties": false+ },+ "materialId": {+ "description": "get: the id a project palette lists as resourceId; create-preset: optional id.",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "description": "get: the immutable revision; omitted, the material's only revision.",+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "draft": {+ "description": "create-procedural: materialId, name, tileable, sources, maps with layered procedural specs; optional tags, physicalSizeMeters, parameters. Shape: kiln_discover({ ids: ['shape:material-draft'] }).",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "payload": {+ "description": "import: schemaVersion 1 and complete normalized records with embedded PNG bytes. Shape: kiln_discover({ ids: ['shape:material-import'] }).",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_save",+ "description": "Save a completed source revision into the user-requested collection, or project when none was requested. Persists exact GLB, source, preview and build record. Use programRef returned by render/edit. To revise an asset, pass assetId and parentRevision; earlier revisions stay intact. Returns downloadable resources; draft renders never populate collections.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "programRef": {+ "type": "string"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "parentRevision": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "tags": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 80+ }+ },+ "brief": {+ "type": "string",+ "maxLength": 8000+ },+ "description": {+ "type": "string",+ "maxLength": 4000+ },+ "attribution": {+ "type": "object",+ "properties": {+ "model": {+ "type": "string",+ "maxLength": 200+ },+ "harness": {+ "type": "string",+ "maxLength": 200+ },+ "author": {+ "type": "string",+ "maxLength": 200+ }+ }+ },+ "backdrop": {+ "description": "Preview backdrop: the one the reviewed sheet used.",+ "type": "string",+ "enum": [+ "neutral",+ "dark",+ "light"+ ]+ },+ "projectId": {+ "description": "Project; omit for the configured default, null for standalone.",+ "anyOf": [+ {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ {+ "type": "null"+ }+ ]+ },+ "projectRevision": {+ "description": "Exact project revision.",+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "materialDependencies": {+ "description": "Pins for this call; each replaces the project pin of its resourceId.",+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "programRef",+ "name"+ ]+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_assets",+ "description": "Browse saved assets: collections discovers storage; catalog searches all configured collections; list searches one. Both searches paginate. get returns a build record/downloads; restore loads exact source for kiln_source/kiln_edit. Collection is not project membership. Binary-only assets cannot restore source.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "action": {+ "default": "list",+ "type": "string",+ "enum": [+ "collections",+ "catalog",+ "list",+ "get",+ "restore"+ ]+ },+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "description": "get, restore: the saved revision; omitted, the newest.",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "query": {+ "type": "string",+ "maxLength": 200+ },+ "offset": {+ "default": 0,+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "default": 20,+ "type": "integer",+ "minimum": 1,+ "maximum": 50+ }+ }+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_present",+ "description": "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "assetId",+ "revisionId"+ ]+ },+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ },+ "_meta": {+ "ui": {+ "resourceUri": "ui://kiln/asset-v5.html",+ "visibility": [+ "model"+ ]+ },+ "openai/outputTemplate": "ui://kiln/asset-v5.html",+ "ui/resourceUri": "ui://kiln/asset-v5.html"+ },+ "outputSchema": {+ "type": "object",+ "properties": {+ "ok": {+ "type": "boolean",+ "const": true+ },+ "collection": {+ "type": "string"+ },+ "asset": {+ "type": "object",+ "properties": {+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "parentRevision": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "tags": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 80+ }+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"+ },+ "editable": {+ "type": "boolean"+ },+ "files": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {+ "type": "object",+ "properties": {+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "bytes": {+ "type": "integer",+ "minimum": 0,+ "maximum": 67108864+ }+ },+ "required": [+ "sha256",+ "bytes"+ ],+ "additionalProperties": false+ }+ },+ "build": {+ "type": "object",+ "properties": {+ "engine": {+ "type": "string"+ },+ "rebuild": {+ "type": "string",+ "enum": [+ "engine-required",+ "external-dependencies-required"+ ]+ },+ "warningCount": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "warnings": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "engine",+ "rebuild",+ "warningCount",+ "warnings"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "assetId",+ "revisionId",+ "name",+ "tags",+ "createdAt",+ "editable",+ "files"+ ],+ "additionalProperties": false+ },+ "resources": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "resource_link"+ },+ "name": {+ "type": "string"+ },+ "uri": {+ "type": "string"+ },+ "mimeType": {+ "type": "string"+ },+ "size": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "annotations": {+ "type": "object",+ "properties": {+ "audience": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "user",+ "assistant"+ ]+ }+ },+ "priority": {+ "type": "number"+ }+ },+ "required": [+ "audience",+ "priority"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "type",+ "name",+ "uri",+ "mimeType",+ "size",+ "annotations"+ ],+ "additionalProperties": false+ }+ },+ "downloadUrls": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "required": [+ "ok",+ "collection",+ "asset",+ "resources"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "kiln_export",+ "description": "Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "profile": {+ "default": "editable",+ "description": "editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.",+ "type": "string",+ "enum": [+ "editable",+ "runtime"+ ]+ }+ },+ "required": [+ "assetId",+ "revisionId"+ ]+ },+ "annotations": {+ "readOnlyHint": true,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ },+ {+ "name": "kiln_import",+ "description": "Copy a pinned asset revision between configured collections, preserving identity and provenance. Copies never track later edits automatically. For a GLB or downloaded ZIP on disk, use kiln import <file> --collection <name> in the CLI.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "collection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "sourceCollection": {+ "default": "project",+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$",+ "description": "Collection ID (list with kiln_assets action=collections): the user destination, else project."+ }+ },+ "required": [+ "assetId",+ "revisionId"+ ]+ },+ "annotations": {+ "readOnlyHint": false,+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": false+ }+ }+ ],+ "resources": [+ {+ "uri": "ui://kiln/asset-v5.html",+ "name": "kiln-asset-viewer",+ "mimeType": "text/html;profile=mcp-app",+ "description": "Interactive Kiln asset viewer and downloads",+ "_meta": {+ "ui": {+ "prefersBorder": true,+ "csp": {+ "connectDomains": [],+ "resourceDomains": []+ }+ },+ "openai/widgetDescription": "Inspect the saved 3D asset and download its GLB or editable bundle.",+ "openai/widgetPrefersBorder": true+ }+ }+ ],+ "resourceTemplates": [+ {+ "name": "asset-file",+ "uriTemplate": "kiln://assets/{collection}/{asset}/{revision}/{file}",+ "description": "Saved GLB/source/preview/manifest/bundle, or derived runtime GLB and metadata sidecar."+ }+ ],+ "catalog": [+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:projectUV",+ "name": "projectUV",+ "summary": "Generates UV0 explicitly in a rigid geometry-local frame. Planar maps XY; box maps each face; cylindrical wraps frame Y with separate caps and split angular seams. Replaces existing UVs and removes stale tangents. To preserve good UVs use direct sharing or copyGeometry instead.",+ "family": "uv",+ "tags": [+ "uv",+ "texture coordinates"+ ],+ "aliases": [+ "planar projection",+ "box mapping",+ "cylindrical UVs",+ "rotated UV frame"+ ],+ "intents": [+ "generate directional texture coordinates in an explicit frame"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "alternative"+ },+ {+ "id": "operation:remapUV",+ "relation": "companion"+ },+ {+ "id": "operation:autoUnwrap",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/uv-project.ts"+ ],+ "limitations": [+ "Full-wrap seam corners may use U above 1 and require repeat sampling. Side triangles spanning more than half a revolution fail; subdivide the profile. Zero extent maps to 0.5. This is projection, not an atlas or a stretch-free guarantee."+ ],+ "kind": "operation",+ "contract": {+ "signature": "projectUV(geometry: BufferGeometry, opts: { projection: 'planar'|'box'|'cylindrical', frame?: { origin?: [x,y,z], rotation?: [xDeg,yDeg,zDeg] }, seamDegrees?: number, angularRange?: [startDeg,sweepDeg], caps?: 'planar'|'side' })",+ "returns": "THREE.BufferGeometry (owned, non-indexed triangle corners)",+ "units": "UVs are dimensionless; source positions retain authored units.",+ "axes": "Rigid frame in geometry-local coordinates: planar XY, box face planes, cylindrical around Y. Euler XYZ rotations are degrees.",+ "origin": "Frame origin is explicit, default [0,0,0]; geometry positions are preserved.",+ "execution": "sync",+ "ownership": "Owned non-indexed geometry and copied attributes/metadata; input unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Planar/box axes and cylindrical height normalize each geometry extent to 0..1. This is not metre-scaled UV mapping; a shared frame does not preserve texel density or texture continuity across separate pieces. Preserve authored physical UVs or map each face with explicit dimensions when that is required.",+ "projection is required. frame uses origin/rotation. Cylinder seamDegrees defaults to 180, measured from +X toward +Z; angularRange is [start degrees, positive sweep <=360] instead of seamDegrees.",+ "Cylindrical caps default to planar for triangle normals within 1e-6 of frame Y; caps:side uses side mapping. Partial ranges must cover side vertices, allowing 1e-6 radians of Float32 boundary roundoff.",+ "Nonempty finite positions, valid triangle indices and matching per-vertex attributes; morph targets are unsupported. At most 2000000 source samples/corners and 128 MiB expanded attribute storage."+ ],+ "topology": [+ "UV generation does not certify or repair solid topology."+ ],+ "preservation": [+ "Triangle order, positions, normals, matching attributes, material groups and draw range retained. UV0 replaced; tangents removed with a diagnostic. No geometric repair."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in source vertices and triangle corners; indexed meshes expand to one vertex per triangle corner.",+ "example": "const mapped = projectUV(rawGeometry, { projection: 'cylindrical', frame: { rotation: [0,0,-90] }, seamDegrees: 180 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:describeAssembly",+ "name": "describeAssembly",+ "summary": "Describes an existing subtree through common roles, frames, sockets, material slots and root-local bounds. Lookup lists are snapshots with live scene/resource references; bounds are null for geometry-free scaffolds. No asset category is needed.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "inspection",+ "semantics",+ "bounds",+ "joints"+ ],+ "aliases": [+ "subtree inventory",+ "assembly dimensions",+ "part sockets",+ "semantic joints",+ "wheel pivots"+ ],+ "intents": [+ "inspect an existing multipart object",+ "find roles frames and materials in a part",+ "find joint chain wheel and steering pivots without relying on names"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:replicateAssembly",+ "relation": "companion"+ }+ ],+ "references": [+ "src/assembly.ts"+ ],+ "limitations": [+ "Not a complete rig or solid-validity certificate. Skinning, morphs, instancing and custom node classes are unsupported."+ ],+ "kind": "operation",+ "contract": {+ "signature": "describeAssembly(root: Object3D, opts?: { clips?: readonly AnimationClip[] })",+ "returns": "AssemblyView { version, root, nodes, roles: Map, frames, sockets, materials, bounds, clips, ownership }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Preserves the authored XYZ axes; frames are affine matrices and can include inherited scale/shear.",+ "origin": "The supplied subtree root defines the assembly origin.",+ "execution": "sync",+ "ownership": "Returns snapshot lookup lists, metadata and bounds with borrowed live references to scene nodes/resources and clips. It is not a frozen scene.",+ "coordinates": "Bounds and frame matrices use root-local coordinates, excluding the root transform and ancestors.",+ "parameters": [+ "At most 10,000 nodes and 2,000,000 placed position samples. Bounds scan all position samples, including unused vertices.",+ "Finite invertible local TRS is required. Local shear, zero scale and matrixWorldAutoUpdate=false are unsupported.",+ "Optional clips are combined with clips attached inside the subtree; duplicate names and unsupported tracks fail."+ ],+ "topology": [+ "Supports ordinary Object3D, Group and Mesh subtrees; does not certify manifoldness or whole-asset validity."+ ],+ "preservation": [+ "Scaffold bounds are null. Bounds do not include morph, skin, shader or displacement deformation."+ ],+ "semantics": [+ "Classification roles, semantic frames/sockets, material slots and rigid articulation are inspected without assigning an asset category.",+ "Snapshot node IDs n0,n1,... are not persistent across hierarchy edits. Re-describe after edits.",+ "joints lists semantic articulated, wheel-spin and steering nodes with node IDs, kinds, roles and detached articulated descriptors where present. Names need not start Joint_; duplicate names remain distinct. Match nodeId to frames for wheel axes. This does not infer arbitrary custom joint roles or prove animation target uniqueness."+ ],+ "cost": "Linear in nodes, placed position samples, metadata and animation samples; geometry sharing still incurs bounds work at each placement.",+ "example": "const assembly = describeAssembly(bay); const dimensions = assembly.bounds?.size;"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:replicateAssembly",+ "name": "replicateAssembly",+ "summary": "Replicates a complete supported hierarchy with namespaced semantic and animation references. Owns new nodes/clips; shares geometry/materials unless copy is requested. Revalidates the live source before attaching. Default local placement preserves authored transforms; returns the new subtree as result.root.",+ "family": "instancing",+ "tags": [+ "instancing",+ "assembly",+ "copy",+ "ownership",+ "animation",+ "semantics"+ ],+ "aliases": [+ "clone full hierarchy",+ "repeat multipart object"+ ],+ "intents": [+ "repeat a bay with all child parts",+ "copy a wheel or articulated structure without identity collisions",+ "duplicate animated mechanism",+ "copy articulated hierarchy",+ "independent mutable geometry option"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:describeAssembly",+ "relation": "prerequisite"+ },+ {+ "id": "operation:createInstance",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/assembly.ts"+ ],+ "limitations": [+ "World placement of animated/joint roots needs unsupported track/rest rebasing; use a static wrapper or local placement.",+ "Skinning, morphs, GPU instancing, custom node types and additive clips are unsupported. External preservation is not self-contained acceptance."+ ],+ "kind": "operation",+ "contract": {+ "signature": "replicateAssembly(source: AssemblyView, opts: { namespace: string, parent?: Object3D, space?: 'local' | 'world', geometry?: 'share' | 'copy', materials?: 'share' | 'copy', externalReferences?: 'reject' | 'preserve', unknownMetadata?: 'reject' | 'copy-json' })",+ "returns": "AssemblyReplica extends AssemblyView { nodeMap, nameMap, jointRoleMap, clipMap, externalReferences }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Preserves the authored XYZ axes; frames are affine matrices and can include inherited scale/shear.",+ "origin": "The supplied subtree root defines the assembly origin.",+ "execution": "sync",+ "ownership": "Owns a new hierarchy and copied clips. Geometry/materials default to share; copy clones each unique resource once, retaining sharing inside the replica. Material copying keeps textures shared.",+ "coordinates": "Default space=local preserves root/child local TRS under the chosen parent. space=world reparents the source world matrix only when the new root-local matrix is lossless TRS.",+ "parameters": [+ "At most 10,000 nodes and 2,000,000 placed position samples. Bounds scan all position samples, including unused vertices.",+ "Finite invertible local TRS is required. Local shear, zero scale and matrixWorldAutoUpdate=false are unsupported.",+ "namespace is required: 1–64 characters, lowercase letter first, lowercase letters/digits with single internal underscores or hyphens. Use unique namespaces for detached replicas later composed together.",+ "Defaults: space=local, geometry=share, materials=share, externalReferences=reject, unknownMetadata=reject. Unknown options fail.",+ "externalReferences=preserve keeps and lists external target strings; caller owns their bindings. unknownMetadata=copy-json copies inert finite JSON without guessing reference identity."+ ],+ "topology": [+ "Supports ordinary Object3D, Group and Mesh subtrees; does not certify manifoldness or whole-asset validity."+ ],+ "preservation": [+ "Revalidates current source after edits; attaches the result.root only after successful preflight and construction.",+ "Remaps internal names/UUID references, sockets, joint roles/aliases/parents and rigid rig graphs. Repeated classification roles are preserved; ambiguous targets fail.",+ "Preserves stored clip times/values/duration and LINEAR/STEP interpolation. Returns nodeMap, nameMap, jointRoleMap and clipMap.",+ "Copying custom resource classes/clone hooks/material callbacks fails rather than silently losing behavior. Opaque JSON metadata is not reference-remapped or guaranteed portable to GLB."+ ],+ "semantics": [+ "Classification roles, semantic frames/sockets, material slots and rigid articulation are inspected without assigning an asset category.",+ "New names are namespace-qualified. This is hierarchy replication, not GPU instancing or attachment solving."+ ],+ "cost": "Linear in nodes, placed position samples, metadata and animation samples; geometry sharing still incurs bounds work at each placement. Resource copying adds allocation proportional to unique copied buffers/materials.",+ "example": "const repeated = replicateAssembly(describeAssembly(bay), { namespace: 'bay2', parent: root }); repeated.root.position.x = 3;"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:remapUV",+ "name": "remapUV",+ "summary": "Scales and offsets existing UV0 on an independent geometry. Defaults are scale [1,1], offset [0,0]. Requires finite two-component UVs; does not unwrap or project. Reads interleaved and normalized attributes. Preserves topology and other attributes; nonidentity scaling removes stale tangents with a warning.",+ "family": "uv",+ "tags": [+ "uv",+ "texture",+ "ownership"+ ],+ "aliases": [+ "UV scale and offset",+ "texture atlas region"+ ],+ "intents": [+ "sample a region of a shared texture",+ "mirror or resize texture coordinates",+ "rescale texture repetition",+ "existing UV tiling scale offset",+ "texture coordinates without reshaping geometry"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:projectUV",+ "relation": "prerequisite"+ },+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ }+ ],+ "references": [+ "src/uv-shapes.ts"+ ],+ "limitations": [+ "Requires existing UVs; does not project new coordinates or change texture wrap mode."+ ],+ "kind": "operation",+ "contract": {+ "signature": "remapUV(geometry: BufferGeometry, opts?: { scale?: [u, v], offset?: [u, v] })",+ "returns": "THREE.BufferGeometry (owned clone, UV0 stored as Float32)",+ "units": "Dimensionless UV multipliers and offsets; authored geometry units are unchanged.",+ "axes": "The two components are U then V.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "scale defaults to [1,1]; offset defaults to [0,0]. Both must be finite pairs. Negative and zero scales are permitted.",+ "Requires existing finite UV0 with two components per position vertex. Mapped values must remain finite Float32 values. Unknown options are rejected."+ ],+ "topology": [+ "Preserves source topology; does not generate UVs, unwrap, or repair geometry."+ ],+ "preservation": [+ "Copies geometry attributes, indices and groups, replacing UV0 with an independent Float32 buffer.",+ "Nonidentity scaling drops stale tangents and records a warning; pure offsets preserve tangents. Regenerate tangents for normal mapping when needed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation.",+ "No material or texture object is copied."+ ],+ "cost": "Linear in vertex UV count plus the cloned geometry buffers.",+ "example": "const strip = remapUV(cylinderGeo(0.4, 0.4, 1), { scale: [1, 0.3], offset: [0, 0] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:materialBudgetAdvisory",+ "name": "materialBudgetAdvisory",+ "summary": "Counts distinct material object identities and optionally compares an explicit nonnegative integer budget. Without maxMaterials it reports a count with null budget/exceeded and no warnings. Does not measure draw calls, validate geometry, choose an asset category, or establish asset validity.",+ "family": "utility",+ "tags": [+ "utility",+ "metrics",+ "materials",+ "advisory"+ ],+ "aliases": [+ "material count budget"+ ],+ "intents": [+ "compare material diversity against an explicit budget"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:countMaterials",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Does not measure draw calls or validate an asset. Use kiln_validate and applicable QA for acceptance."+ ],+ "kind": "operation",+ "contract": {+ "signature": "materialBudgetAdvisory(root: Object3D, opts?: { maxMaterials?: number })",+ "returns": "{ materialCount, maxMaterials: number | null, exceeded: boolean | null, warnings: string[] }",+ "units": "Counts distinct material object references.",+ "axes": "Not applicable.",+ "origin": "Not applicable.",+ "execution": "sync",+ "ownership": "Read-only traversal; returns a new advisory object and warning array.",+ "coordinates": "Traverses the subtree without modifying transforms.",+ "parameters": [+ "maxMaterials is an optional nonnegative safe integer; there is no default material budget or category policy."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not change geometry, materials, hierarchy or metadata."+ ],+ "semantics": [+ "Returns materialCount, maxMaterials, exceeded and warnings. Omitted budget yields null maxMaterials/exceeded.",+ "An advisory is not an asset acceptance result and contains no valid or errors fields."+ ],+ "cost": "Linear in subtree meshes and material references.",+ "example": "const advisory = materialBudgetAdvisory(root, { maxMaterials: 8 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:copyGeometry",+ "name": "copyGeometry",+ "summary": "Returns an independent geometry with copied vertex buffers. Use before direct mutation of a cached primitive.",+ "family": "instancing",+ "tags": [+ "instancing",+ "ownership",+ "copy"+ ],+ "aliases": [+ "independent geometry copy"+ ],+ "intents": [+ "edit vertices without changing other parts",+ "independent geometry copy",+ "duplicate mesh vertices",+ "edit without changing original"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "copyGeometry(geometry: BufferGeometry)",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Preserves source axes.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "A BufferGeometry."+ ],+ "topology": [+ "Preserves source topology, including any defects."+ ],+ "preservation": [+ "Copies vertex attributes and index buffers; no whole Object3D hierarchy is copied.",+ "Three.js clone semantics apply to groups, morph attributes and userData; arbitrary application object identity is not promised."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in copied geometry buffers.",+ "example": "const editable = copyGeometry(boxGeo(1, 1, 1)); editable.translate(0, 0.5, 0);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:copyMaterial",+ "name": "copyMaterial",+ "summary": "Copies material properties so edits do not change other parts. Referenced textures remain shared.",+ "family": "instancing",+ "tags": [+ "instancing",+ "material",+ "ownership",+ "copy"+ ],+ "aliases": [+ "independent material copy"+ ],+ "intents": [+ "change one part material without recoloring shared parts",+ "independent material copy",+ "edit material without changing original"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "copyMaterial(material: Material)",+ "returns": "THREE.Material (same subtype)",+ "units": "Material property units are preserved; no geometry units apply.",+ "axes": "Not applicable to a material.",+ "origin": "Not applicable to a material.",+ "execution": "sync",+ "ownership": "Returns an independent material object of the same subtype; referenced textures remain shared.",+ "coordinates": "No geometry transform.",+ "parameters": [+ "A Three.js material."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Copies material properties under Three.js clone semantics; does not copy texture bytes or a containing mesh."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Depends on material properties, not scene triangle count.",+ "example": "const red = copyMaterial(steel); red.color.set(0xaa2222);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:meshGeo",+ "name": "meshGeo",+ "summary": "Builds an owned triangle mesh from flat numeric arrays. Validates finite values, attribute lengths and indices; computes normals if absent. Counterclockwise winding.",+ "family": "geometry",+ "tags": [+ "geometry",+ "custom geometry",+ "triangles",+ "owned geometry"+ ],+ "aliases": [+ "raw mesh",+ "indexed triangles"+ ],+ "intents": [+ "build custom vertices and faces"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/geometry.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "meshGeo({ positions: number[], indices?: number[], normals?: number[], uvs?: number[], tangents?: number[] })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Caller supplies XYZ; triangle winding is counterclockwise when viewed from the front.",+ "origin": "Exactly the supplied vertex positions.",+ "execution": "sync",+ "ownership": "Copies authored numeric arrays into new geometry buffers.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite Float32-compatible positions in XYZ triples; indices in range and complete triangles.",+ "Optional normals, UVs and tangents must match vertex counts."+ ],+ "topology": [+ "Accepts triangle meshes with counterclockwise winding; finite/index checks do not certify a manifold, nondegenerate or self-intersection-free solid."+ ],+ "preservation": [+ "Creates supplied UVs/tangents; supplied normals are normalized, otherwise normals are computed.",+ "Computes bounding box and sphere."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in supplied vertex/triangle arrays; no general allocation cap is claimed.",+ "example": "const triangle = meshGeo({ positions: [0,0,0, 1,0,0, 0,1,0], indices: [0,1,2] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:parametricSurface",+ "name": "parametricSurface",+ "summary": "At most 262,144 endpoint-inclusive samples per call, checked before invoking the sampler. Samples an equation into an owned surface with UVs. Periodic endpoints must agree within 1e-6 of the sampled diagonal, independent of origin and units; UV seams retain matching normals. A surface is not automatically a watertight solid.",+ "family": "geometry",+ "tags": [+ "geometry",+ "custom geometry",+ "surface",+ "equation"+ ],+ "aliases": [+ "equation surface",+ "parametric mesh"+ ],+ "intents": [+ "sample a mathematical surface"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/geometry.ts"+ ],+ "limitations": [+ "Callback termination and self-intersection are not certified.",+ "Use a non-collapsed parameterization or explicit meshGeo fan topology at singular tips. geometryDiagnostics reports degenerate triangles; supplying arbitrary normals does not repair collapsed topology."+ ],+ "kind": "operation",+ "contract": {+ "signature": "parametricSurface(sample: (u,v) => [x,y,z], opts?: { u?: [0,1], v?: [0,1], uSegments?: 24, vSegments?: 24, periodicU?: false, periodicV?: false, orientation?: 'uv'|'vu' })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Sampler returns XYZ; orientation selects uv or vu winding.",+ "origin": "Defined by sampler outputs, not centered automatically.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Positive safe-integer u/v segment counts; finite nonzero domains and domain extents; at most 262,144 samples including endpoints.",+ "Periodic endpoints must agree within 1e-6 of the sampled bounding-box diagonal, independent of translation or world units; orientation must be uv or vu."+ ],+ "topology": [+ "A sampled surface, not automatically a closed solid; periodic seams retain separate UV vertices.",+ "Each grid cell becomes two triangles. Collapsed parameter rows or columns are not converted into pole fans; they can create degenerate triangles and zero normals."+ ],+ "preservation": [+ "Generates UVs and normals, aligns normals across validated periodic seams, computes bounds."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "(uSegments + 1) × (vSegments + 1) samples, capped at 262,144 before callbacks/allocation; 2 × uSegments × vSegments triangles. The evaluator still owns callback timeouts.",+ "example": "const canopy = parametricSurface((u,v) => [u, 0.3*Math.sin(u*3)*Math.cos(v*2), v], { u: [-2,2], v: [-1,1] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:geometryDiagnostics",+ "name": "geometryDiagnostics",+ "summary": "Counts topology issues after position-grid matching. Default tolerance is 1e-6 times the finite-position diagonal; an explicit positive value is absolute. Reports effective tolerance and scale. Open boundaries are valid for sheets; closed edges do not certify a self-intersection-free solid.",+ "family": "utility",+ "tags": [+ "utility",+ "diagnostics",+ "topology"+ ],+ "aliases": [+ "mesh diagnostics",+ "watertightness inspection"+ ],+ "intents": [+ "inspect open edges and malformed mesh data",+ "boundary nonmanifold edges",+ "welded seam topology",+ "degenerate triangle orientation"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/geometry.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "geometryDiagnostics(geometry: BufferGeometry, tolerance?: number)",+ "returns": "{ tolerance, toleranceMode, positionScale, vertices, triangles, boundaryEdges, nonManifoldEdges, orientationConflicts, degenerateTriangles, invalidIndices, nonFiniteVertices }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. tolerance uses position units.",+ "axes": "Reads source XYZ without changing it.",+ "origin": "Does not reposition geometry.",+ "execution": "sync",+ "ownership": "Read-only inspection; returns counts, not repaired geometry.",+ "coordinates": "Geometry-local positions; position-based seam matching uses tolerance.",+ "parameters": [+ "A BufferGeometry; omitted tolerance is 1e-6 times its finite-position bounding-box diagonal. A supplied positive finite tolerance is an absolute distance and must resolve the extent within safe integer quantization.",+ "Returns effective tolerance, toleranceMode (relative or absolute) and positionScale with the counts; a collapsed extent uses zero default tolerance."+ ],+ "topology": [+ "Counts boundary/nonmanifold/orientation/degenerate/index/finite issues; does not detect arbitrary triangle self-intersections.",+ "An open sheet can be valid for its intended use.",+ "Position matching quantizes a grid relative to the bounds minimum, not an exact distance weld. Invalid-position triangles are excluded from edge/area counts and nonfinite vertices remain reported.",+ "collapsedByToleranceTriangles counts faces whose corners merge in that grid; they are excluded from edge counts, not removed from geometry. Nonzero means topology detail was lost at this tolerance; inspect at a finer tolerance before interpreting edge counts. This is separate from area-based degenerateTriangles."+ ],+ "preservation": [+ "Input buffers and topology are unchanged."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Visits vertices and triangle edges; memory grows with unique welded positions/edges.",+ "example": "const topology = geometryDiagnostics(shell);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:creaseNormals",+ "name": "creaseNormals",+ "summary": "Returns owned geometry with angle-limited smooth normals, preserving UV corners. Angle is degrees. Default position tolerance is 1e-8 times the diagonal, with no world-unit floor; explicit tolerance is absolute. Invalidates tangents; use after shaping for sharp rims and smooth walls.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "shading",+ "normals"+ ],+ "aliases": [+ "hard edges",+ "smooth normals"+ ],+ "intents": [+ "keep sharp rims while smoothing curved faces",+ "smooth normals",+ "preserve sharp edges",+ "hard surface shading"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/geometry.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "creaseNormals(geometry: BufferGeometry, opts?: { angle?: 60, tolerance?: number })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle is degrees; tolerance is a distance.",+ "axes": "Preserves source coordinate axes.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite crease angle; default 60 degrees. Omitted tolerance is 1e-8 times the finite-position bounding-box diagonal, without a world-unit floor; an explicit positive finite distance overrides it."+ ],+ "topology": [+ "Can split corners for shading; no topology repair or solid-validity guarantee."+ ],+ "preservation": [+ "Preserves UV corner seams; recomputes angle-limited normals and bounds; invalidates tangents."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Depends on faces and vertex adjacency; highly connected neighborhoods can increase work.",+ "example": "const shell = creaseNormals(cylinderGeo(1,1,2,32), { angle: 45 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:bend",+ "name": "bend",+ "summary": "Bends local +Y toward +X through angle degrees. Returns owned geometry and updated normals/bounds; preserves UVs, invalidates tangents. Frame rotation is Euler XYZ degrees.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "deformation",+ "owned geometry"+ ],+ "aliases": [+ "curve a mesh"+ ],+ "intents": [+ "bend an existing segmented shape"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:subdivide",+ "relation": "companion"+ },+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/deform.ts"+ ],+ "limitations": [+ "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."+ ],+ "kind": "operation",+ "contract": {+ "signature": "bend(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",+ "axes": "Bends frame-local +Y toward +X; local Z is the bend axis.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",+ "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",+ "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",+ "Deformation interval uses local Y distances; outside vertices stay unchanged. Add enough segments before bending. Falloff returns 0..1; use it to avoid a discontinuity at a selected interval boundary."+ ],+ "topology": [+ "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."+ ],+ "preservation": [+ "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",+ "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",+ "example": "const arch = bend(planeGeo(1,4,4,32), { angle: 90 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:twist",+ "name": "twist",+ "summary": "Rotates the cross-section progressively around local +Y, reaching angle degrees at the end. Returns owned geometry; frame rotation uses Euler XYZ degrees.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "deformation",+ "owned geometry"+ ],+ "aliases": [+ "torsion"+ ],+ "intents": [+ "twist a column or handle"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:subdivide",+ "relation": "companion"+ },+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/deform.ts"+ ],+ "limitations": [+ "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."+ ],+ "kind": "operation",+ "contract": {+ "signature": "twist(geometry, { angle, frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",+ "axes": "Rotates cross-sections around frame-local +Y along the interval.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",+ "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",+ "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation."+ ],+ "topology": [+ "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."+ ],+ "preservation": [+ "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",+ "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",+ "example": "const spiral = twist(column, { angle: 120 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:taper",+ "name": "taper",+ "summary": "Scales local X/Z across the local Y interval using positive start/end scale pairs. Returns owned geometry; preserves UVs and invalidates tangents.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "deformation",+ "owned geometry"+ ],+ "aliases": [+ "narrow a mesh"+ ],+ "intents": [+ "vary the width of a segmented shape"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:subdivide",+ "relation": "companion"+ },+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/deform.ts"+ ],+ "limitations": [+ "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."+ ],+ "kind": "operation",+ "contract": {+ "signature": "taper(geometry, { startScale?: [1,1], endScale: [x,z], frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",+ "axes": "Scales frame-local X/Z along local Y.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",+ "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",+ "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",+ "startScale/endScale contain two finite positive scale factors."+ ],+ "topology": [+ "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."+ ],+ "preservation": [+ "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",+ "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",+ "example": "const narrowed = taper(column, { endScale: [0.4,0.7] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:displace",+ "name": "displace",+ "summary": "Adds an authored displacement vector in the chosen local frame. Returns owned geometry; callback coordinates are local and t is normalized along the interval.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "deformation",+ "owned geometry"+ ],+ "aliases": [+ "vertex displacement"+ ],+ "intents": [+ "shape a mesh using an authored offset field"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:subdivide",+ "relation": "companion"+ },+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/deform.ts"+ ],+ "limitations": [+ "Enough longitudinal segments must exist before deforming; discontinuous interval boundaries remain possible."+ ],+ "kind": "operation",+ "contract": {+ "signature": "displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin, rotation }, interval?: [minY,maxY], falloff?: t => weight })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. frame rotations and angle parameters use Euler XYZ degrees; scale and falloff are dimensionless.",+ "axes": "Callback receives frame-local XYZ and normalized interval distance.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Frame origin/rotation finite; interval finite and increasing; falloff returns a finite weight in [0,1].",+ "Outside positions stay unchanged with endpoint roundoff bounded to one millionth of interval length; nonzero intervals retain normalized progress at tiny scales.",+ "At most 2000000 vertices / 3000000 triangle corners; morph targets require deformation before morph creation.",+ "Callback returns a finite XYZ displacement vector, not an absolute position."+ ],+ "topology": [+ "Keeps connectivity but can create degenerate or self-intersecting shapes; no automatic subdivision."+ ],+ "preservation": [+ "Preserves UVs, groups and cloned attributes. Unchanged positions keep authored normals; changed geometry rebuilds area-weighted normals across authored smooth seam classes while retaining hard creases.",+ "Seam matching uses 1e-7 of geometry diagonal for position and 1e-6 normal components; tangents are removed with DEFORM_TANGENTS_DROPPED. No topology-validity guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in vertex count plus normal recomputation and callback cost; callback termination is a host responsibility.",+ "example": "const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:sweepProfile",+ "name": "sweepProfile",+ "summary": "Sweeps a simple noncircular profile along polyline stations using transported frames. Supports total twist in degrees and per-station scales. Generates UVs and optional caps.",+ "family": "curves",+ "tags": [+ "curves",+ "sweep",+ "profile",+ "path"+ ],+ "aliases": [+ "extrude along path",+ "noncircular tube"+ ],+ "intents": [+ "carry a cross-section along a rail",+ "profile along a path",+ "extruded rail",+ "curved trim"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:loftProfiles",+ "relation": "alternative"+ },+ {+ "id": "operation:pipeAlongPath",+ "relation": "alternative"+ },+ {+ "id": "operation:extrudeProfile",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/sweep.ts"+ ],+ "limitations": [+ "Tight-turn warnings use the scaled profile radius at the turning station and adjacent segment lengths. This local heuristic does not test swept-volume intersections, rapid scale changes, or certify a solid."+ ],+ "kind": "operation",+ "contract": {+ "signature": "sweepProfile(profile: [x,z][], path: [x,y,z][], opts?: { cap?: true | false | 'start' | 'end', creaseAngle?: 60, closed?: false, up?: [x,y,z], twist?: 0, scale?: number | [x,z][] })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. twist/frame rotations are degrees; scale is dimensionless.",+ "axes": "Profile coordinates are local XZ; local +Y is the longitudinal direction.",+ "origin": "Defined by supplied path stations or section frames.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite simple profile and distinct path stations: at least 2 open or 3 closed.",+ "Profile and path checks use their respective extents, not fixed world-unit cutoffs; up specifies a direction regardless of its nonzero magnitude. Output positions remain Float32.",+ "Closed paths omit the repeated endpoint and require twist to be a multiple of 360 degrees.",+ "Transported frames and per-station positive scales define the cross-section.",+ "cap is true (both ends, default), false, 'start' or 'end'; a one-ended cap needs an open path.",+ "creaseAngle is degrees in [0, 180], default 60. Side panels meeting at more than it, across a profile corner or a path station, get separate vertices and a hard shading edge; hexagons and finer profiles stay smooth at the default.",+ "First version supports one simple profile without holes. Closed paths omit the repeated endpoint and require twist to be a multiple of 360. up sets the initial profile +Z direction and cannot parallel the path. cap caps both ends by default; 'start' or 'end' caps only that end of an open path. creaseAngle (degrees) keeps side faces meeting at more than it hard-edged, at profile corners and sharp path corners: at the default 60, squares, triangles and pentagons stay faceted while hexagons and finer profiles shade smooth; 180 smooths every edge. Tight-turn warnings do not replace visual inspection for self-intersections."+ ],+ "topology": [+ "Simple profiles without holes; supplied holes fields fail explicitly. Optional caps do not prove freedom from self-intersection or create wall thickness.",+ "Warped side panels use four triangles around a bilinear midpoint to avoid diagonal bias; planar panels use two. This is piecewise-linear sampling, not a smooth surface.",+ "A corresponding edge that collapses between stations is rejected. Check matching starts/order or add intermediate stations for an intended twist. Bounded local analysis observes tight station curvature and intersecting consecutive rings; distant segments remain unchecked."+ ],+ "preservation": [+ "Generates UVs, normals and bounds; SWEEP_SELF_INTERSECTION observes station radius or intersecting consecutive rings. Incomplete analysis keeps an unchecked warning and partial finding."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Geometry grows with profile points × stations; each warped side panel adds one midpoint and two triangles. Local analysis is capped at 4096 stations, 512 points per ring and 65536 segment/triangle tests; no global surface-intersection certification or geometry allocation cap.",+ "example": "const rail = sweepProfile([[-.1,-.2],[.1,-.2],[.1,.2],[-.1,.2]], [[0,0,0],[0,1,0],[1,2,0]]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:loftProfiles",+ "name": "loftProfiles",+ "summary": "Joins corresponding simple profiles in explicit local XZ planes. Frames use Euler XYZ degrees; initial section travel determines outward winding. Profiles need equal point counts and corresponding vertices.",+ "family": "curves",+ "tags": [+ "curves",+ "loft",+ "profile",+ "frames"+ ],+ "aliases": [+ "join cross-sections"+ ],+ "intents": [+ "transition between different cross-section shapes",+ "loft cross sections",+ "varying cross section",+ "join cross sections",+ "matching polygon outlines",+ "blend section shapes"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:sweepProfile",+ "relation": "alternative"+ },+ {+ "id": "operation:extrudeProfile",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/sweep.ts"+ ],+ "limitations": [+ "Closed boundaries do not certify a self-intersection-free solid."+ ],+ "kind": "operation",+ "contract": {+ "signature": "loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opts?: { cap?: true })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. twist/frame rotations are degrees; scale is dimensionless.",+ "axes": "Profiles lie in rigid local XZ planes. Initial section travel relative to the first plane determines face winding; sections may progress in either direction.",+ "origin": "Defined by supplied path stations or section frames.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "At least two simple profiles with equal point counts and corresponding vertex order.",+ "Profile validation is relative to its extent. Nonzero section travel has no fixed world-unit minimum; output positions remain Float32.",+ "Explicit rigid frames position local XZ profiles; no automatic profile correspondence or holes. Coplanar or crossed section arrangements are not certified solids.",+ "No holes or automatic profile correspondence. Opposite winding is normalized while preserving the first point. Caps close boundaries but do not prove the loft has no self-intersections."+ ],+ "topology": [+ "Simple profiles without holes; supplied holes fields fail explicitly. Optional caps do not prove freedom from self-intersection or create wall thickness.",+ "Warped side panels use four triangles around a bilinear midpoint to avoid diagonal bias; planar panels use two. This is piecewise-linear sampling, not a smooth surface.",+ "A corresponding edge that collapses between stations is rejected. Check matching starts/order or add intermediate stations for an intended twist. Bounded local analysis observes tight station curvature and intersecting consecutive rings; distant segments remain unchecked."+ ],+ "preservation": [+ "Generates UVs, normals and bounds; SWEEP_SELF_INTERSECTION observes station radius or intersecting consecutive rings. Incomplete analysis keeps an unchecked warning and partial finding."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Geometry grows with profile points × stations; each warped side panel adds one midpoint and two triangles. Local analysis is capped at 4096 stations, 512 points per ring and 65536 segment/triangle tests; no global surface-intersection certification or geometry allocation cap.",+ "example": "const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin: [0,2,0] } }]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:implicitSurface",+ "name": "implicitSurface",+ "summary": "Experimental positive-inside implicit field sampled into a solid mesh. Requires explicit bounds and resolution; checks grid size and actual evaluation count. Output has no UVs.",+ "family": "geometry",+ "tags": [+ "geometry",+ "implicit surface",+ "field",+ "solid"+ ],+ "aliases": [+ "signed field",+ "isosurface"+ ],+ "intents": [+ "sample a blended volumetric shape"+ ],+ "stability": "experimental",+ "related": [],+ "references": [+ "src/implicit.ts"+ ],+ "limitations": [+ "No CAD accuracy or thin-feature preservation guarantee; requires host execution limits."+ ],+ "kind": "operation",+ "contract": {+ "signature": "await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max }, edgeLength, maxCells?: 1000000, maxEvaluations?: 8000000, level?: 0, tolerance?: -1, smooth?: true })",+ "returns": "Promise<THREE.BufferGeometry>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Field receives XYZ; positive values describe the inside.",+ "origin": "Explicit sampling bounds min/max define the evaluated region.",+ "execution": "async",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite increasing bounds on all axes; finite positive edgeLength.",+ "Positive safe-integer maxCells/maxEvaluations; level finite, tolerance -1 or positive.",+ "Defaults: 1,000,000 estimated cells and 8,000,000 actual callback evaluations.",+ "Use async build and await. Smaller edgeLength increases cost sharply. This helper cannot stop a callback that never returns; the host evaluator process provides that boundary. Thin features and geometric accuracy require inspection."+ ],+ "topology": [+ "Manifold level-set extraction is resolution-dependent; thin features and boundary clipping require review."+ ],+ "preservation": [+ "Generates normals and bounds; no UVs; stamps experimental sampling settings and warnings."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Checks estimated grid and actual callback counts before/between samples; cannot interrupt a callback that never returns.",+ "example": "const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createRoot",+ "name": "createRoot",+ "summary": "Creates the root Object3D for an asset. Call first in build().",+ "family": "structure",+ "tags": [+ "structure",+ "hierarchy",+ "root"+ ],+ "aliases": [+ "asset root"+ ],+ "intents": [+ "start an asset hierarchy"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "createRoot(name: string)",+ "returns": "THREE.Object3D",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Identity transform at [0,0,0].",+ "execution": "sync",+ "ownership": "Creates a new root Object3D.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Names identify nodes; parent attachment changes the supplied parent hierarchy."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "One node.",+ "example": "const root = createRoot('FuelDrum');"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createPivot",+ "name": "createPivot",+ "summary": "Creates an empty pivot node for skeletal animation. Name is auto-prefixed with `Joint_`.",+ "family": "structure",+ "tags": [+ "structure",+ "hierarchy",+ "pivot",+ "animation"+ ],+ "aliases": [+ "hinge",+ "joint pivot"+ ],+ "intents": [+ "rotate a part around an articulated origin"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "createPivot(name: string, position?: [x, y, z], parent?: Object3D)",+ "returns": "THREE.Object3D (prefixed `Joint_`)",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Names identify nodes; parent attachment changes the supplied parent hierarchy."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Prefixes the node name with Joint_; that name does not itself prove a skeletal role."+ ],+ "cost": "One pivot node.",+ "example": "const hip = createPivot('Hip', [0, 1, 0], root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createJointChain",+ "name": "createJointChain",+ "summary": "Creates one body-plan-neutral deterministic Joint_* chain with explicit parent edges, rest frames, local axes, end effectors, contacts, and semantic metadata.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "rig",+ "skeleton"+ ],+ "aliases": [+ "joint chain",+ "articulated chain"+ ],+ "intents": [+ "create a body-plan-neutral articulated chain"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/character.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "createJointChain(name, segments: { role, offset, aliases?, side?, localForwardAxis?, localBendAxis?, endEffector?, contact? }[], opts?: { parent?, parentRole? })",+ "returns": "{ root, end, nodes, byRole, descriptors }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Per-joint forward/bend axes are explicit descriptors; +Y up is conventional, not a mandatory body plan.",+ "origin": "Each offset is local to the preceding joint, starting under the supplied parent.",+ "execution": "sync",+ "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Ordered role descriptors with finite offsets and explicit semantic parent relationships.",+ "Use only the resolved body-plan graph. Offsets are local to the previous joint; contact end effectors must land at world Y=0."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Creates rest frames, local axes, role lookup and parent edges; does not create skinning or a character mesh."+ ],+ "semantics": [+ "Stamps versioned joint/role metadata, contacts and end-effectors when declared."+ ],+ "cost": "Linear in number of joint descriptors.",+ "example": "const leg = createJointChain('LegL', [{ role: 'hip.left', offset: [0, 1, -0.2], side: 'left' }, { role: 'knee.left', offset: [0, -0.5, 0], side: 'left' }, { role: 'ankle.left', offset: [0, -0.5, 0], side: 'left', endEffector: true, contact: true }], { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createVehicleFrame",+ "name": "createVehicleFrame",+ "summary": "Creates a canonical +X-forward/+Y-up/+Z-right vehicle frame with typed semantic sockets for chassis, support, steering, and propulsion.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "frame",+ "sockets",+ "vehicle"+ ],+ "aliases": [+ "chassis sockets",+ "vehicle scaffold"+ ],+ "intents": [+ "coordinate support and propulsion attachment locations"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/vehicle.ts"+ ],+ "limitations": [+ "Socket declarations alone do not prove ground support or working propulsion."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createVehicleFrame(name, opts?: { chassis?, axles?, seats?, contacts?, steering?, propulsion?, parent? })",+ "returns": "{ root, chassis, axles, seats, contacts, steering, propulsion }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "+X forward, +Y up, +Z right.",+ "origin": "Socket positions are local to the new frame root.",+ "execution": "sync",+ "ownership": "Creates new Object3D nodes; attaches them to the supplied parent when present.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Typed chassis/axle/seat/contact/steering/propulsion descriptors; identifiers and coordinates are validated.",+ "Generated vehicles keep +X as front. Boats and other non-wheeled subtypes use declared support/propulsion sockets, not wheel rules."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Creates socket nodes and typed semantic relationships; geometry and wheels are separate."+ ],+ "semantics": [+ "Marks vehicle frame/socket roles; these labels do not activate category-specific policy."+ ],+ "cost": "Linear in declared sockets.",+ "example": "const frame = createVehicleFrame('CarFrame', { axles: [{ id: 'front', position: [1.2, 0.45, 0] }, { id: 'rear', position: [-1.2, 0.45, 0] }], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createWheelGeometrySet",+ "name": "createWheelGeometrySet",+ "summary": "Creates one reusable +Z-axle tire/rim/hub geometry set for instanced wheel assemblies.",+ "family": "instancing",+ "tags": [+ "instancing",+ "geometry",+ "wheel",+ "reuse"+ ],+ "aliases": [+ "shared wheel geometry"+ ],+ "intents": [+ "reuse matching tire and rim buffers"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "assembly:createWheelAssembly",+ "relation": "companion"+ }+ ],+ "references": [+ "src/vehicle.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "createWheelGeometrySet(radius: number, width: number)",+ "returns": "{ tire, rim, hub } shared THREE.BufferGeometry set",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "+Z axle; tire lies around XY.",+ "origin": "Axle center [0,0,0].",+ "execution": "sync",+ "ownership": "Allocates a tire/rim/hub geometry set intended to be shared by multiple assemblies.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Positive radius and width; width must be less than the diameter."+ ],+ "topology": [+ "Torus tire plus capped rim/hub cylinders; not a boolean union."+ ],+ "preservation": [+ "Generates standard geometry normals and UVs."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Fixed segment choices: torus 8 × 20 plus rim/hub cylinders.",+ "example": "const wheelGeo = createWheelGeometrySet(0.45, 0.22);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createWheelAssembly",+ "name": "createWheelAssembly",+ "summary": "Creates one axle-centered wheel pivot containing concentric tire/rim/hub roles, a contact marker, +Z spin frame, and optional steering pivot.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "wheel",+ "pivot"+ ],+ "aliases": [+ "articulated wheel"+ ],+ "intents": [+ "build a wheel with steering and spin pivots"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:createWheelGeometrySet",+ "relation": "companion"+ },+ {+ "id": "assembly:createVehicleFrame",+ "relation": "companion"+ }+ ],+ "references": [+ "src/vehicle.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "createWheelAssembly(name, { tire, rim, hub? }, { radius, width, side, index, position?, rimRadius?, hubRadius?, steering?, loadBearing?, geometries?, parent? })",+ "returns": "{ root, steeringPivot?, spinPivot, tire, rim, hub, contact, radius, width, side, index, spinAxis, geometryChecks }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "+Z spin axis, optional +Y steering axis.",+ "origin": "Concentric components at the axle pivot; position moves that pivot under the assembly root.",+ "execution": "sync",+ "ownership": "Creates new wheel hierarchy; supplied geometry set and material references are shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Positive dimensions; hubRadius < rimRadius < radius; rim/hub widths cannot exceed tire width.",+ "side is 'left', 'right' or 'center'; index identifies the axle. These label identity without inferring position, paired wheels or the number of fork arms.",+ "Supplied geometry is checked without mutation: geometryChecks reports radius/width/center differences at relative tolerance 1e-5. At most 2000000 position samples per component; empty/nonfinite geometry fails. A mismatch is advisory, never an automatic resize.",+ "side is 'left', 'right', or 'center': identity relative to the host, not fork design or automatic positioning. Centerline wheels need no partner. Keep tire, rim, and hub concentric at the axle pivot. Reuse geometry across matching wheels."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Preserves component hierarchy and semantic contacts/relationships. Supplied geometry stays shared; contacts retain declared radius. Review geometryChecks when customizing."+ ],+ "semantics": [+ "Typed wheel/tire/rim/hub/pivot/contact roles with load-bearing and steering metadata."+ ],+ "cost": "Three wheel meshes plus pivots/contact markers; sharing geometry is not one draw call.",+ "example": "createWheelAssembly('FrontLeft', { tire: rubber, rim: metal }, { radius: 0.45, width: 0.22, side: 'left', index: 'front', position: [1.2, 0.45, -0.9], steering: true, geometries: wheelGeo, parent: frame.root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createPart",+ "name": "createPart",+ "summary": "Creates a mesh using supplied geometry and material, with optional pivot and parent attachment. Rotation triples are degrees.",+ "family": "structure",+ "tags": [+ "structure",+ "mesh",+ "hierarchy",+ "placement"+ ],+ "aliases": [+ "place a mesh",+ "make a part"+ ],+ "intents": [+ "turn geometry into a placed part"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Attach once using parent; do not separately add the returned node to another parent."+ ],+ "kind": "operation",+ "contract": {+ "signature": "createPart(name, geometry, material, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, pivot, parent })",+ "returns": "THREE.Object3D (mesh or wrapping pivot)",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates a new mesh and optional pivot wrapper; input geometry and material are shared, not copied.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Names identify nodes; parent attachment changes the supplied parent hierarchy.",+ "AUTO-ADDS to opts.parent. NEVER call parent.add(createPart(...)) — pass { parent } instead. rotation is DEGREES — writing radians (e.g. 0.785 or Math.PI/4) silently produces ~zero rotation."+ ],+ "topology": [+ "Uses input geometry unchanged; no repair or solid guarantee."+ ],+ "preservation": [+ "Keeps geometry/material references; does not import another subtree."+ ],+ "semantics": [+ "Names the mesh Mesh_<name>; optional pivot is a distinct parent node.",+ "With pivot:true, position moves the pivot while rotation/scale remain on the child mesh.",+ "Optional semantic input is stamped on the returned mesh or pivot."+ ],+ "cost": "One mesh plus optional pivot; geometry/material buffers are shared.",+ "example": "createPart('Barrel', cylinderGeo(0.1, 0.1, 1), gameMaterial(0x556b2f), { position: [0, 0.5, 0], rotation: [0, 0, 90], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:defineLod",+ "name": "defineLod",+ "summary": "Declares LOD tiers (sibling nodes named Body_LOD0, Body_LOD1, ...) and their screen-coverage thresholds. Use only when the brief asks for LOD tiers.",+ "family": "structure",+ "tags": [+ "structure",+ "hierarchy",+ "lod",+ "export"+ ],+ "aliases": [+ "level of detail",+ "LOD tiers",+ "MSFT_lod",+ "screen coverage"+ ],+ "intents": [+ "export level-of-detail tiers as one chain"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/lod.ts",+ "src/lod-export.ts"+ ],+ "limitations": [+ "Tiers are authored, not generated: Kiln simplifies no geometry.",+ "Sets cannot nest inside another tier; material LOD chains are not created."+ ],+ "kind": "operation",+ "contract": {+ "signature": "defineLod(levels: Object3D[], opts: { screenCoverage: number[] })",+ "returns": "Object3D[] (levels, unchanged)",+ "units": "screenCoverage values are fractions of the screen area, 0..1; no lengths.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Each lower level keeps its own transform and replaces LOD0 under the same parent.",+ "execution": "sync",+ "ownership": "Records the thresholds on the LOD0 node; creates no nodes and moves nothing until export.",+ "coordinates": "Not a placement operation.",+ "parameters": [+ "levels: two or more sibling tier nodes named with one stem and tokens LOD0, LOD1, ... in order.",+ "screenCoverage: one value per level, each from 0 to 1, strictly decreasing, LOD0 first; the last may be 0, which never culls.",+ "Only when the brief asks for LOD tiers; otherwise build one tier. Tiers are sibling nodes named with one stem and consecutive LOD<n> tokens. screenCoverage has one value per level, strictly decreasing; below the last the asset is culled, and a last value of 0 never culls."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Level i draws while the asset covers at least screenCoverage[i] of the screen; below the last value it is culled.",+ "Export writes the set as one MSFT_lod chain: LOD0 stays in the scene and lists the lower levels, which leave it; LOD0 extras.MSFT_screencoverage holds the thresholds.",+ "Reported triangles and bounds count LOD0; levelsOfDetail in render results lists each level with its triangles and path.",+ "A set of two or more tiers without this declaration, with a gap, or without LOD0 is an LOD_SET build error."+ ],+ "cost": "Metadata on one node; lower levels still cost file size.",+ "example": "const tiers = ['Body_LOD0', 'Body_LOD1', 'Body_LOD2'].map((name) => { const g = new THREE.Group(); g.name = name; root.add(g); return g; });\ndefineLod(tiers, { screenCoverage: [0.25, 0.06, 0.01] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:markOpenShell",+ "name": "markOpenShell",+ "summary": "Marks a part that is open on purpose (a C-channel closed by end plates, a single-sided sheet) with the reason, so QA reports it as acknowledged rather than unmeasured.",+ "family": "structure",+ "tags": [+ "structure",+ "qa",+ "hierarchy",+ "export"+ ],+ "aliases": [+ "open shell",+ "intentionally open",+ "not manifold",+ "single-sided sheet",+ "acknowledge unmeasured part"+ ],+ "intents": [+ "mark a part that is open on purpose"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:createPart",+ "relation": "companion"+ },+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ }+ ],+ "references": [+ "src/open-shell.ts",+ "src/qa/self-intersection.ts"+ ],+ "limitations": [+ "A mark states intent and measures nothing: overlap with the part stays unmeasured and part-volume coverage stays partial.",+ "Close a part that is meant to be solid instead of marking it."+ ],+ "kind": "operation",+ "contract": {+ "signature": "markOpenShell(part: Object3D, reason: string)",+ "returns": "Object3D (part, unchanged)",+ "units": "No lengths; reason is text of 1 to 200 characters after trimming.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Not a placement operation.",+ "execution": "sync",+ "ownership": "Writes one validated mark to part.userData.kilnOpenShell; creates no nodes and changes no geometry.",+ "coordinates": "Not a placement operation.",+ "parameters": [+ "part: a scene node, such as the mesh createPart returned or a group; a mark on a group covers the meshes under it.",+ "reason: why the shell is open, 1 to 200 characters after trimming.",+ "Only for shells open by design; close a part meant to be solid instead. A mark on a group covers its meshes. Overlap with a marked part stays unmeasured, not clear."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.",+ "Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.",+ "A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.",+ "Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.",+ "Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error."+ ],+ "cost": "Metadata on one node: about 50 bytes of extras plus the reason.",+ "example": "const rail = createPart('Rail', new THREE.CylinderGeometry(0.2, 0.2, 2, 16, 1, true), steel, { parent: root });\nmarkOpenShell(rail, 'Tube closed by the end plates');"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:beamBetween",+ "name": "beamBetween",+ "summary": "Creates a cylindrical rail/strut exactly between two endpoints in its parent frame. Derive attachment endpoints from the neighboring geometry; the helper does not find joints or join surfaces. Use for braces, barrels, struts, cables, and scaffolding.",+ "family": "structure",+ "tags": [+ "structure",+ "beam",+ "path",+ "placement"+ ],+ "aliases": [+ "strut",+ "brace",+ "rail"+ ],+ "intents": [+ "connect two points with a straight circular beam",+ "beam between points",+ "bar connecting endpoints"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "beamBetween(name, start: [x,y,z], end: [x,y,z], radius, material, opts?: { segments, parent })",+ "returns": "THREE.Object3D (prefixed `Mesh_`)",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Cylinder +Y is oriented from start to end.",+ "origin": "Midpoint of supplied endpoints.",+ "execution": "sync",+ "ownership": "Creates a new cylinder geometry and mesh; material remains shared.",+ "coordinates": "Endpoints are in the selected parent local coordinates.",+ "parameters": [+ "Finite distinct endpoints and a usable radius/segment count are required by the intended shape; full validation remains unqualified."+ ],+ "topology": [+ "Capped circular beam for nondegenerate endpoints; not automatic connection to adjacent geometry."+ ],+ "preservation": [+ "Generated cylinder geometry has normals/UVs; no input geometry is transformed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "One mesh; triangle count grows with radial segments.",+ "example": "beamBetween('SkidBraceA', [0.8, 0.3, 0.7], [0.8, 1.0, 0.45], 0.025, black, { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:snapTo",+ "name": "snapTo",+ "summary": "Moves a part so its world bounding box contacts or overlaps the host bounding box. Useful for coarse alignment; it does not mate exact surfaces.",+ "family": "structure",+ "tags": [+ "structure",+ "alignment",+ "bounds",+ "placement"+ ],+ "aliases": [+ "bounding box contact",+ "align surfaces"+ ],+ "intents": [+ "close a visible bounding-box gap"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "AABBs can overlap even when the actual surfaces do not."+ ],+ "kind": "operation",+ "contract": {+ "signature": "snapTo(part: Object3D, host: Object3D, opts?: { axis?: 'x'|'y'|'z', overlap?: 0.02 })",+ "returns": "THREE.Object3D (the part, for chaining)",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Changes the part translation; does not create a new pivot.",+ "execution": "sync",+ "ownership": "Mutates and returns the supplied part; leaves geometry/material buffers unchanged.",+ "coordinates": "Measures world AABBs after ancestor refresh, then converts displacement into part-parent coordinates.",+ "parameters": [+ "Closes AABB gaps on all axes. Optional axis selects only the overlap-bias direction; it does not constrain movement. overlap defaults to 0.02 scene units."+ ],+ "topology": [+ "Bounding-box overlap/contact is not exact surface contact or a boolean union."+ ],+ "preservation": [+ "Preserves rotation, scale, hierarchy and geometry; translation changes."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Traverses part/host bounds; cost depends on subtree geometry.",+ "example": "const scope = createPart('Scope', cylinderXGeo(0.04, 0.04, 0.3), steel, { parent: root, position: [0.1, 0.32, 0] });\nsnapTo(scope, receiver);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createLadder",+ "name": "createLadder",+ "summary": "Builds a rooted ladder with perpendicular rails/rungs and bottom/top endpoint frames and sockets. Describe or replicate result.root as one assembly. Explicit widthDirection is projected perpendicular to the endpoints.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "ladder rungs"+ ],+ "intents": [+ "build rails and evenly spaced rungs"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "No structural-load or climbability guarantee. Rail/rung access remains available; they now belong to result.root."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createLadder(name, { bottom, top, material, width?, rungCount?, railRadius?, rungRadius?, segments?, widthAxis?, widthDirection?, parent? })",+ "returns": "{ root: Object3D, leftRail: Object3D, rightRail: Object3D, rungs: Object3D[] }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Rails follow bottom-to-top. widthAxis is a preferred basis projected perpendicular to that line; a parallel basis uses the least-aligned canonical axis.",+ "origin": "Endpoints are supplied in parent coordinates; returned root is at bottom, children are root-local.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Finite endpoints; positive width and rail/rung radii; integer rungCount 0..10000 and segments 3..4096. Width axis is x or z; explicit finite nonzero widthDirection is projected and rejects parallel directions. Endpoint distance exceeds 1e-4."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Two rails plus rungCount meshes.",+ "example": "createLadder('TowerLadder', { bottom: [0,0,0], top: [0,2.2,0], width: 0.45, rungCount: 7, material: steel, parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createWingPair",+ "name": "createWingPair",+ "summary": "Creates mirrored trapezoid aircraft wings with roots attached at +/-rootZ. Use for aircraft wings and helicopter stub wings.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "paired wings",+ "aircraft wings"+ ],+ "intents": [+ "build a symmetric pair of swept panels"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Returns left/right nodes without a shared assembly root."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createWingPair(name, material, { rootZ, span, rootChord, tipChord, sweep?, thickness?, dihedral?, rootX?, rootY?, parent? })",+ "returns": "{ right: Object3D, left: Object3D }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. dihedral is a tip height offset, not degrees.",+ "axes": "Two wings extend toward ±Z; positive sweep moves tips toward -X.",+ "origin": "Roots at ±rootZ with optional rootX/rootY offsets.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Uses wingGeo dimensions and explicit mirrored placement."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Creates separately owned mirrored geometry with corrected reflected triangle winding; material remains shared."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Two fixed-complexity wing meshes.",+ "example": "createWingPair('MainWing', olive, { rootX: 0, rootY: 1.0, rootZ: 0.42, span: 2.4, rootChord: 0.9, tipChord: 0.35, sweep: 0.25, dihedral: 0.08, parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:room",+ "name": "room",+ "summary": "Creates four walls with rectangular openings and an optional floor. Front faces +X; compose, stack or adapt rooms without selecting an asset category.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "hollow room",+ "interior"+ ],+ "intents": [+ "build an enterable room",+ "hollow enclosure",+ "walls and floor",+ "room with doors and windows"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "assembly:wallWithOpening",+ "relation": "companion"+ },+ {+ "id": "assembly:createGableShell",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "room(name, material, { width?, depth?, height?, wallThickness?, floor?, floorThickness?, openings?: [{ wall: 'front'|'back'|'left'|'right', kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",+ "returns": "{ root: Object3D, walls: { front, back, left, right }, floor: Object3D | null }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Width spans Z, depth spans X, height Y; front faces +X.",+ "origin": "Wall base and floor top are local Y=0; floor extends downward.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Default width/depth/height describe a small room; dimensions are not an overall building/storey limit.",+ "Per-wall rectangular openings are explicit; floor may be disabled.",+ "Use for any building the player enters. Do NOT model a building as a solid block — room() guarantees real interior space and a doorway gap. Pass openings to add windows / side doors."+ ],+ "topology": [+ "Four box-segment walls with real apertures; optional floor. No roof or automatic whole-building watertightness."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Mesh count grows with aperture segmentation, plus optional floor.",+ "example": "const { root: hut } = room('Hut', wood, { width: 5, depth: 4, height: 2.8, openings: [{ wall: 'front', kind: 'door' }, { wall: 'right', kind: 'window' }], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:wallWithOpening",+ "name": "wallWithOpening",+ "summary": "A wall panel with real rectangular door/window gaps, composed from solid box segments. Supply opening or openings, never both. Multiple or vertically stacked apertures must not overlap or extend outside the wall. Base at local Y=0, centered on the run axis. Use to compose custom layouts and interior dividing walls.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "door opening",+ "window wall",+ "partition"+ ],+ "intents": [+ "build a wall with real doorway or window gaps",+ "wall aperture",+ "cut a window",+ "doorway opening",+ "door or window in a wall"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "wallWithOpening(name, material, { length, height, thickness, axis?: 'x'|'z', opening?: { kind?: 'door'|'window', offset?, width?, height?, sill? }, openings?: [{ kind?: 'door'|'window', offset?, width?, height?, sill? }], parent? })",+ "returns": "THREE.Object3D (wall container)",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Wall run axis X or Z; vertical axis Y.",+ "origin": "Centered on run axis; base Y=0.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Positive finite length/height/thickness; opening or openings, never both.",+ "Rectangular apertures must not overlap or extend outside the wall; touching edges are allowed."+ ],+ "topology": [+ "Actual aperture gaps are composed from box segments; no solid boolean or wall-assembly union."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Segmentation grows with aperture boundary coordinates; no generic architectural complexity cap.",+ "example": "wallWithOpening('Partition', plaster, { length: 4, height: 2.8, thickness: 0.12, axis: 'x', opening: { kind: 'door', offset: 0.5 }, parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createRoofPlanes",+ "name": "createRoofPlanes",+ "summary": "A pitched roof: two thin slopes meeting at one ridge and falling DOWN-AND-OUTWARD (opposite tilts — never mirrored the same way), footprint-matched with an eave overhang. Outer top eave at local Y=0, ridge at Y=height. Thickness extends inward. For a wall-bearing datum use createGableRoof. Returns a named group (e.g. `Roof`) the engine can lift to reveal the interior.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "pitched roof planes"+ ],+ "intents": [+ "place two roof slopes over walls"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "assembly:createGableRoof",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "createRoofPlanes(name, material, { width, depth, height, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",+ "returns": "{ root: Object3D, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Pitched gable roof; ridgeAxis selects X or Z.",+ "origin": "Outer top eave at local Y=0; ridge reaches height. Roof thickness extends inward.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "width spans Z and depth spans X; createGableRoof exposes explicit spanX/spanZ instead.",+ "The two slopes must fall AWAY from each other from the ridge — createRoofPlanes does this for you. Its outer top eave is the datum; createGableRoof instead anchors the wall bearing line."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "One shared constructor across imports; returns root/slopes/face frames. Use describeAssembly(result.root) for common access and replication."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Two slope meshes plus root.",+ "example": "const { root: roof } = createRoofPlanes('Roof', shingle, { width: 5, depth: 4, height: 1.6, overhang: 0.4, ridgeAxis: 'x', parent: root });\nroof.position.y = 2.8;"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createGableRoof",+ "name": "createGableRoof",+ "summary": "Explicit-axis gable roof using unambiguous footprint spans. Each face owns a rigid frame with ridge tangent, outward normal, downhill direction, ridge/eave endpoints, dimensions, and a live local-to-world transform.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "architecture",+ "gable"+ ],+ "aliases": [+ "gable roof",+ "roof face frames"+ ],+ "intents": [+ "build a pitched roof with usable attachment frames"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "assembly:createRoofSurfaceLayout",+ "relation": "companion"+ }+ ],+ "references": [+ "src/architecture.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "createGableRoof(name, material, { spanX, spanZ, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, parent? })",+ "returns": "{ root, slopes: [Object3D, Object3D], faces: [RoofFaceFrame, RoofFaceFrame], rise, pitchDegrees }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. pitchDegrees uses degrees.",+ "axes": "spanX/spanZ are explicit footprint axes; ridgeAxis X or Z.",+ "origin": "Wall-bearing line at Y=0; rise determines ridge elevation. Overhang descends below the bearing line.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Finite positive footprint spans; validated rise/pitch, overhang and thickness options.",+ "Prefer this over width/depth roof math. ridgeAxis is the direction of the ridge; roof panels run along each returned face downhill direction."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Returns live rigid roof-face frames with tangents, normals, dimensions and world conversion."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Two roof slopes with frame metadata.",+ "example": "const roof = createGableRoof('Roof', shingles, { spanX: 8, spanZ: 5, pitchDegrees: 35, overhang: 0.35, ridgeAxis: 'x', parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createGableEndPanel",+ "name": "createGableEndPanel",+ "summary": "Exact thick triangular end closure for a gable roof, with optional rectangular openings cut from the geometry and semantic boundary metadata.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "architecture",+ "gable"+ ],+ "aliases": [+ "triangular end wall",+ "gable closure"+ ],+ "intents": [+ "close a pitched roof end"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/architecture.ts"+ ],+ "limitations": [],+ "kind": "assembly",+ "contract": {+ "signature": "createGableEndPanel(name, material, { span, rise, thickness?, ridgeAxis?: 'x'|'z', side?: 'positive'|'negative', openings?: [{ id?, offset?, bottom?, width, height }], parent? })",+ "returns": "{ root, geometry, openings }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Vertical triangular panel perpendicular to ridgeAxis; side chooses the outward end.",+ "origin": "Panel base Y=0, centered across span.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Finite positive span/rise/thickness; explicit rectangular opening dimensions/offsets."+ ],+ "topology": [+ "Triangulated thick gable closure with clipped apertures; this is one panel, not a complete building."+ ],+ "preservation": [+ "Generated panel geometry and semantic boundary metadata; input material shared."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Depends on aperture clipping and triangulation.",+ "example": "createGableEndPanel('FrontGable', siding, { span: 5, rise: 1.8, ridgeAxis: 'x', side: 'positive', parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createGableShell",+ "name": "createGableShell",+ "summary": "Composes a gable-roof building shell from walls, floor, slopes and end panels, with optional enterability and openings.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "architecture",+ "gable"+ ],+ "aliases": [+ "gable building shell"+ ],+ "intents": [+ "construct a small pitched-roof enclosure",+ "enclosed building shell",+ "gable house with openings"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/architecture.ts"+ ],+ "limitations": [+ "Gable-specific construction; not a universal building generator."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createGableShell(name, { wall, roof, floor?, gable? }, { spanX, spanZ, wallHeight?, rise?, pitchDegrees?, overhang?, ridgeAxis?: 'x'|'z', thickness?, wallThickness?, floorThickness?, closedEnds?, enterable?, openings?, gableOpenings?, parent? })",+ "returns": "{ root, walls, floor, roof, gables, openings }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "spanX/spanZ, +Y wall height and X/Z ridge axis; front is +X.",+ "origin": "Floor top and wall base Y=0.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "Optional floor/gable materials use documented defaults; openings/enterability are explicit.",+ "One gable shell per call; arbitrary environments can compose multiple shells or other geometry.",+ "Use for complete gable buildings. It stamps wall, floor, slope, gable, opening, adjacency, coverage, and separability semantics for deterministic QA and roof-off views."+ ],+ "topology": [+ "Separate walls/floor/slopes/end panels; closed-by-default enclosure does not imply one manifold mesh."+ ],+ "preservation": [+ "Creates semantic wall, opening, roof and boundary descriptions."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Depends on wall/opening segmentation and gable geometry.",+ "example": "const house = createGableShell('House', { wall: plaster, roof: shingles }, { spanX: 8, spanZ: 5, wallHeight: 2.8, pitchDegrees: 35, ridgeAxis: 'x', parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createRoofSurfaceLayout",+ "name": "createRoofSurfaceLayout",+ "summary": "Places roof-local panels, shingles, seams, or corrugations from a returned RoofFaceFrame, so repeated elements run ridge-to-eave for either ridge axis without manual Euler rotations.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly",+ "architecture",+ "gable"+ ],+ "aliases": [+ "roof shingles",+ "standing seams",+ "corrugated roof"+ ],+ "intents": [+ "repeat details consistently over a roof face"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "assembly:createGableRoof",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/architecture.ts"+ ],+ "limitations": [+ "Box approximations, not interlocking or physically folded roofing. Material and visual quality still need review.",+ "Separate-parent placement is a construction-time snapshot. Reparenting that requires local shear is rejected; use face.roofRoot to preserve inherited affine transforms."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createRoofSurfaceLayout(name, material, { face, kind: 'panels'|'shingles'|'seams'|'corrugations', parent?, panelWidth?, rowHeight?, spacing?, thickness? })",+ "returns": "{ root, items: Object3D[], cost: { meshes, triangles } }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Uses the supplied roof-face tangent/downhill/normal frame.",+ "origin": "Relative to the supplied roof face.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "kind selects panels/shingles/seams/corrugations; finite positive dimensions and at most 10000 generated boxes.",+ "Panels keep 2% width gaps; staggered shingles keep 4% gaps within clipped boundary cells, overlap rows by up to 8%, and clip at the eave.",+ "Seams/corrugations clip edge strips to the face; a face narrower than one strip receives one clipped strip.",+ "Always pass the face object returned by createGableRoof/createGableShell. Never infer the panel rotation from world axes."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Uses live face frames; creates individual mesh elements with shared material."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "Returns cost.meshes and cost.triangles (12 per box); one mesh per element, no hardware-instanced batching or draw-call promise.",+ "example": "for (const face of roof.faces) createRoofSurfaceLayout('Panels_' + face.side, metal, { face, kind: 'panels', parent: roof.root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "assembly:createStairs",+ "name": "createStairs",+ "summary": "A straight flight of stairs: box treads (with optional risers) climbing totalRise over totalRun from local origin toward +axis. Use for porch/entry steps or to connect storeys in a multi-storey building.",+ "family": "structure",+ "tags": [+ "structure",+ "assembly"+ ],+ "aliases": [+ "stair flight",+ "steps"+ ],+ "intents": [+ "connect elevations with straight stairs",+ "stair flight",+ "steps",+ "tiered seating",+ "rise and run"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "No curved staircase, landing sockets or navigability certificate."+ ],+ "kind": "assembly",+ "contract": {+ "signature": "createStairs(name, material, { steps?, totalRise, totalRun, width, axis?: 'x'|'z', treadThickness?, riser?, parent? })",+ "returns": "{ root: Object3D, steps: Object3D[] }",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Signed totalRise changes Y; signed totalRun advances along selected X or Z.",+ "origin": "Starts from the local origin; totalRise/totalRun define the flight.",+ "execution": "sync",+ "ownership": "Creates new nodes and generated geometry; supplied materials remain shared.",+ "coordinates": "Parent-local transform inputs, not automatic world-space placement.",+ "parameters": [+ "steps must be an integer from 1 to 10000; finite rise/run magnitudes below 1e-4 are rejected.",+ "Width and treadThickness are positive finite. Negative rise/run preserve descending/reversed placement with positive solid dimensions."+ ],+ "topology": [+ "Composed parts remain separate meshes; no union or watertight whole-assembly guarantee."+ ],+ "preservation": [+ "Does not clone a containing parent hierarchy."+ ],+ "semantics": [+ "Part naming and metadata are helper-specific; no category or whole-asset acceptance is selected."+ ],+ "cost": "steps treads plus optional steps risers.",+ "example": "createStairs('Porch', stone, { steps: 4, totalRise: 0.6, totalRun: 1.0, width: 1.4, axis: 'x', parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:boxGeo",+ "name": "boxGeo",+ "summary": "6-face box. 12 tris regardless of size. Cheapest geometry.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "cuboid",+ "rectangular prism"+ ],+ "intents": [+ "make a rectangular block"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "boxGeo(width: number, height: number, depth: number)",+ "returns": "THREE.BoxGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Width X, height Y, depth Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "12 triangles; dimensions do not increase tessellation.",+ "example": "const geo = boxGeo(1, 0.5, 2);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:sphereGeo",+ "name": "sphereGeo",+ "summary": "UV sphere. Default 8x6 segments = 84 tris. Bump segments for smoother curves.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "ball",+ "orb"+ ],+ "intents": [+ "make a rounded ball"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Raw computeVertexNormals replaces analytic normals and can leave unused pole vertices with zero normals, which fail GLTF validation. Preserve the existing normals for affine transforms."+ ],+ "kind": "operation",+ "contract": {+ "signature": "sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)",+ "returns": "THREE.SphereGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Latitude axis Y; circular cross-sections in XZ.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Supplies analytic normals and UVs. Geometry scale/rotation transforms the existing normals; no extra computeVertexNormals is needed for those transforms."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Grows with widthSegments × heightSegments; default 8 × 6.",+ "example": "const geo = sphereGeo(0.5, 12, 8);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:cylinderGeo",+ "name": "cylinderGeo",+ "summary": "Y-axis cylinder. Use radiusTop != radiusBottom for cones / tapered pieces.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "y axis cylinder",+ "frustum"+ ],+ "intents": [+ "make an axle or tapered circular body"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "cylinderGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Cylinder axis Y; radiusTop is toward +Y, radiusBottom toward -Y.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Each radius is nonnegative; at least one must be positive. Height/length is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",+ "example": "const geo = cylinderGeo(0.25, 0.25, 1, 12);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:cylinderYGeo",+ "name": "cylinderYGeo",+ "summary": "Alias for cylinderGeo — a Y-axis cylinder. Provided because the sandbox exposes cylinderXGeo / cylinderZGeo and the symmetric Y form is commonly reached for.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "y axis cylinder",+ "frustum"+ ],+ "intents": [+ "make an axle or tapered circular body"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "cylinderYGeo(radiusTop: number, radiusBottom: number, height: number, segments?: 8)",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Cylinder axis Y; radiusTop is toward +Y, radiusBottom toward -Y.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Each radius is nonnegative; at least one must be positive. Height/length is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",+ "example": "const geo = cylinderYGeo(0.25, 0.25, 1, 12);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:cylinderXGeo",+ "name": "cylinderXGeo",+ "summary": "Cylinder pre-rotated to run along +X/-X. Use for fuselages, cannons, barrels, axles, and forward-facing tubes.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "x axis cylinder",+ "frustum"+ ],+ "intents": [+ "make an axle or tapered circular body"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "cylinderXGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Cylinder axis X; radiusTop is toward +X, radiusBottom toward -X.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Each radius is nonnegative; at least one must be positive. Height/length is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",+ "example": "const geo = cylinderXGeo(0.1, 0.1, 1.2, 12);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:cylinderZGeo",+ "name": "cylinderZGeo",+ "summary": "Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "z axis cylinder",+ "frustum"+ ],+ "intents": [+ "make an axle or tapered circular body"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "cylinderZGeo(radiusTop: number, radiusBottom: number, length: number, segments?: 8)",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Cylinder axis Z; radiusTop is toward +Z, radiusBottom toward -Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Each radius is nonnegative; at least one must be positive. Height/length is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8; 3 to 4096 radial segments.",+ "example": "const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:cylinderOnAxis",+ "name": "cylinderOnAxis",+ "summary": "Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "oriented cylinder"+ ],+ "intents": [+ "align a cylinder to a non-cardinal direction"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Local +Y is rotated onto the supplied normal; top cap follows normal.",+ "origin": "Vertices are translated to the supplied center.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "center and normal are finite triples. Normal length must be at least 1e-6; normalization handles large finite components. Cylinder radii are nonnegative with at least one positive; height is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments plus a vertex transform.",+ "example": "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:capsuleGeo",+ "name": "capsuleGeo",+ "summary": "Stadium shape (cylinder with hemispherical caps). Good for limbs.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pill",+ "rounded capsule"+ ],+ "intents": [+ "make a rounded limb or pod"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "capsuleGeo(radius: number, height: number, segments?: 6)",+ "returns": "THREE.CapsuleGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Longitudinal axis Y.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",+ "Cap subdivision is fixed at 2; radial segments default to 6."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments with fixed cap subdivision.",+ "example": "const geo = capsuleGeo(0.1, 0.5, 6);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:capsuleYGeo",+ "name": "capsuleYGeo",+ "summary": "Alias for capsuleGeo — a Y-axis capsule. Provided for symmetry with capsuleXGeo / capsuleZGeo.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pill",+ "rounded capsule"+ ],+ "intents": [+ "make a rounded limb or pod"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "capsuleYGeo(radius: number, height: number, segments?: 6)",+ "returns": "THREE.CapsuleGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Longitudinal axis Y.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",+ "Cap subdivision is fixed at 2; radial segments default to 6."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments with fixed cap subdivision.",+ "example": "const geo = capsuleYGeo(0.1, 0.5, 6);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:capsuleXGeo",+ "name": "capsuleXGeo",+ "summary": "Capsule pre-rotated to run along +X/-X. Use for aircraft bodies, rounded vehicle hulls, and missiles.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pill",+ "rounded capsule"+ ],+ "intents": [+ "make a rounded limb or pod"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "capsuleXGeo(radius: number, length: number, segments?: 6)",+ "returns": "THREE.CapsuleGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Longitudinal axis X.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",+ "Cap subdivision is fixed at 2; radial segments default to 6."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments with fixed cap subdivision.",+ "example": "const geo = capsuleXGeo(0.35, 2.4, 10);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:capsuleZGeo",+ "name": "capsuleZGeo",+ "summary": "Capsule pre-rotated to run along +Z/-Z. Use for lateral pods, floats, and side tanks.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pill",+ "rounded capsule"+ ],+ "intents": [+ "make a rounded limb or pod"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "capsuleZGeo(radius: number, length: number, segments?: 6)",+ "returns": "THREE.CapsuleGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Longitudinal axis Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "height/length is the nonnegative straight middle section; zero is supported. Radius is positive; total outer length is height/length + 2 × radius.",+ "Cap subdivision is fixed at 2; radial segments default to 6."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments with fixed cap subdivision.",+ "example": "const geo = capsuleZGeo(0.18, 1.1, 8);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:coneGeo",+ "name": "coneGeo",+ "summary": "Y-axis cone (pointed up). Use for spikes, roofs, projectiles.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pointed cone",+ "spike"+ ],+ "intents": [+ "make a tapered point"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "coneGeo(radius: number, height: number, segments?: 8)",+ "returns": "THREE.ConeGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Apex points toward +Y; height/length spans the Y axis.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8.",+ "example": "const geo = coneGeo(0.3, 0.8, 8);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:coneYGeo",+ "name": "coneYGeo",+ "summary": "Alias for coneGeo — a Y-axis cone (point +Y). Provided for symmetry with coneXGeo / coneZGeo.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pointed cone",+ "spike"+ ],+ "intents": [+ "make a tapered point"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "coneYGeo(radius: number, height: number, segments?: 8)",+ "returns": "THREE.ConeGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Apex points toward +Y; height/length spans the Y axis.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8.",+ "example": "const geo = coneYGeo(0.3, 0.8, 8);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:coneXGeo",+ "name": "coneXGeo",+ "summary": "Cone pre-rotated so its point faces +X. Use for noses, rockets, shells, and forward-facing tips.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pointed cone",+ "spike"+ ],+ "intents": [+ "make a tapered point"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "coneXGeo(radius: number, length: number, segments?: 8)",+ "returns": "THREE.ConeGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Apex points toward +X; height/length spans the X axis.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8.",+ "example": "const geo = coneXGeo(0.18, 0.45, 12);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:coneZGeo",+ "name": "coneZGeo",+ "summary": "Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "pointed cone",+ "spike"+ ],+ "intents": [+ "make a tapered point"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "coneZGeo(radius: number, length: number, segments?: 8)",+ "returns": "THREE.ConeGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Apex points toward +Z; height/length spans the Z axis.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8.",+ "example": "const geo = coneZGeo(0.12, 0.35, 10);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:taperConeGeo",+ "name": "taperConeGeo",+ "summary": "Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "truncated cone",+ "frustum"+ ],+ "intents": [+ "make a circular taper with two end radii"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",+ "returns": "THREE.CylinderGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "axis must be x/y/z, default y; smaller radius is not inferred from the parameter name.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Radii are nonnegative, with at least one positive. Height is positive."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in radial segments, default 8.",+ "example": "const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:torusGeo",+ "name": "torusGeo",+ "summary": "Donut shape. For rings, tyres, barrel ribs.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "donut",+ "ring"+ ],+ "intents": [+ "make a circular ring with a round tube"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "torusGeo(radius: number, tube: number, radialSegments?: 8, tubularSegments?: 12)",+ "returns": "THREE.TorusGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Ring lies in XY; hole axis Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Grows with radialSegments × tubularSegments (defaults 8 × 12).",+ "example": "const geo = torusGeo(0.4, 0.04, 8, 16);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:planeGeo",+ "name": "planeGeo",+ "summary": "Creates a subdividable XY rectangular sheet with UVs. Place and orient it explicitly; use a solid primitive when thickness matters.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "quad",+ "sheet"+ ],+ "intents": [+ "make a flat textured surface"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "planeGeo(width: number, height: number, widthSegments?: 1, heightSegments?: 1)",+ "returns": "THREE.PlaneGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Width X, height Y; front normal +Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction."+ ],+ "topology": [+ "Open rectangular sheet; no thickness or watertightness."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "2 × widthSegments × heightSegments triangles.",+ "example": "const geo = planeGeo(4, 4);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:decalBox",+ "name": "decalBox",+ "summary": "Thin box for solid-color surface decals: red stars, hull numbers, stamps, no-texture windows. Unlike planeGeo, has real depth so it visibly attaches to its host surface. Must be placed on a surface with position + rotation.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "thin plaque",+ "solid decal"+ ],+ "intents": [+ "attach a colored plate to a surface"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Does not place itself on another surface or prevent z-fighting."+ ],+ "kind": "operation",+ "contract": {+ "signature": "decalBox(width: number, height: number, depth?: 0.01)",+ "returns": "THREE.BoxGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Width X, height Y, depth Z.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Dimensions must be finite and Float32-representable, positive unless an explicit zero case is listed. Use planeGeo for zero-thickness sheets.",+ "Segments are safe integers up to 4096. Minimum is 3 for circular segments, 2 for sphere heightSegments, and 1 for plane segments. Sphere/torus/plane grids also require (firstSegments + 1) * (secondSegments + 1) <= 262144. No silent rounding or tessellation reduction.",+ "Width/height positive; depth nonnegative, default 0.01 and clamped to a documented minimum of 0.002.",+ "Offset at least 0.01 outside the host surface to avoid z-fighting (a 0.8-wide hull has faces at z=±0.4, so place the decal at z=±0.41)."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "12 triangles; default depth 0.01 scene units.",+ "example": "const star = decalBox(0.18, 0.18, 0.01);\ncreatePart('Mesh_StarPort', star, gameMaterial(0xc61f2a), { position: [0.4, 0.6, 0.41], parent: fuselage });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:foliageCardGeo",+ "name": "foliageCardGeo",+ "summary": "Single-quad foliage card with a configurable Y pivot. yPivot=0 plants the quad on the ground. Pair with an alpha-tested material and a leaf/plant sprite.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "leaf card",+ "billboard"+ ],+ "intents": [+ "make a plant sprite card",+ "thin leaf cutout",+ "foliage card"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "foliageCardGeo(opts?: { width?, height?, yPivot?: 0..1 })",+ "returns": "THREE.PlaneGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Card lies in XY, front normal +Z.",+ "origin": "yPivot is a fraction of height; 0 puts the bottom edge at Y=0, 0.5 centers it.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Positive finite width/height; yPivot may lie outside 0..1, but resulting coordinates must fit finite Float32.",+ "The example uses an approved 4x4 teaching placeholder, not production foliage detail."+ ],+ "topology": [+ "One open quad; alpha masking is material behavior, not geometric trimming."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Stamps kilnGeometryRole=foliageCard."+ ],+ "cost": "Two triangles.",+ "example": "const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\nconst leaves = foliageMaterial(albedo);\nconst quad = foliageCardGeo({ width: 0.6, height: 1, yPivot: 0 });\ncreatePart('LeafCard', quad, leaves, { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:crossedQuadsGeo",+ "name": "crossedQuadsGeo",+ "summary": "Cross-billboard bush primitive: 2 or 3 planes intersecting along the Y axis. Reads as a dense plant from any angle, cheaper than real geometry.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "cross billboard",+ "bush cards"+ ],+ "intents": [+ "make inexpensive vegetation with multiple silhouettes"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "crossedQuadsGeo(opts?: { width?, height?, planes?: 2 | 3, yPivot? })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Intersecting vertical sheets rotate around Y.",+ "origin": "yPivot controls the Y datum as a fraction of height.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Positive finite width/height; finite Float32 coordinates after pivot; planes must be exactly 2 or 3."+ ],+ "topology": [+ "Intersecting open quads; not a closed solid."+ ],+ "preservation": [+ "Generates positions, normals and UVs unless specified otherwise; does not preserve an input mesh because none is supplied.",+ "Eager bounding volumes are not guaranteed; compute bounds when the consuming operation needs them."+ ],+ "semantics": [+ "Stamps billboard geometry role metadata."+ ],+ "cost": "Two triangles per plane; intended plane count is 2 or 3.",+ "example": "const leaves = await materialRecipe('kiln.material.leaf.v1');\nconst bush = crossedQuadsGeo({ width: 2, height: 2, planes: 3 });\ncreatePart('Mesh_Bush', bush, leaves, { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:octaGridPlane",+ "name": "octaGridPlane",+ "summary": "Atlas-ready billboard quad. UVs are pre-scaled to cover one tile of a tilesX×tilesY atlas; the consumer shader adds per-instance tile offsets at draw time.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "atlas billboard",+ "impostor card"+ ],+ "intents": [+ "make a card for an atlas-aware runtime"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "The GLB material alone does not implement per-instance tile selection."+ ],+ "kind": "operation",+ "contract": {+ "signature": "octaGridPlane({ tilesX, tilesY, width?, height?, yPivot? })",+ "returns": "THREE.PlaneGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Atlas card lies in XY, front normal +Z.",+ "origin": "yPivot controls the Y datum as a fraction of height.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "tilesX/tilesY must be positive safe integers; width/height positive finite and pivoted coordinates finite Float32."+ ],+ "topology": [+ "Open quad; atlas tile selection requires consumer shader support."+ ],+ "preservation": [+ "Generates UVs covering the top-left atlas tile; no tile-selection shader is generated."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Two triangles independent of atlas tile count.",+ "example": "const card = octaGridPlane({ tilesX: 4, tilesY: 4, width: 6, height: 6 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:wingGeo",+ "name": "wingGeo",+ "summary": "Trapezoid wing panel. Local root edge is at Z=0, span extends toward +Z, positive sweep moves the tip aft along -X.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "trapezoid wing",+ "tapered panel"+ ],+ "intents": [+ "make a swept wing panel"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "wingGeo(opts?: { span, rootChord, tipChord, sweep, thickness, dihedral })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. dihedral is tip Y displacement, not an angle.",+ "axes": "Root at Z=0, span toward +Z; positive sweep shifts the tip leading edge toward -X relative to the root leading edge, not the chord midpoint.",+ "origin": "Root chord midpoint at [0,0,0].",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Positive finite span/rootChord/thickness; tipChord may be zero for a pointed wing. Signed sweep and dihedral are finite length displacements; generated coordinates must fit Float32."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Creates positions and normals; no UV attribute is generated."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Fixed trapezoid or triangular prism tessellation.",+ "example": "const geo = wingGeo({ span: 2.2, rootChord: 0.8, tipChord: 0.3, sweep: 0.25, dihedral: 0.08 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:gearGeo",+ "name": "gearGeo",+ "summary": "Stylized gear with flat edges and an optional center bore; no CSG. Use boreRadius < rootRadius < tipRadius. Radii are absolute: an omitted rootRadius stays 0.8 when tipRadius changes. Set all three radii for small gears.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "cog",+ "sprocket"+ ],+ "intents": [+ "make a stylized toothed wheel"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/gears.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Gear lies in XZ, thickness on Y.",+ "origin": "Centered at local [0,0,0] unless this helper states another datum.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Absolute bore/root/tip radii; do not assume an omitted root radius scales with tipRadius.",+ "teeth is an integer from 3 to 4096; finite radii obey 0 <= bore < root < tip, height is positive, and toothWidthFrac is strictly between 0 and 1.",+ "Stylized teeth, not an involute engineering profile."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Creates positions and normals; UV preservation is not applicable and UVs are not generated."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Linear in tooth count; inspect tooth and radius validity.",+ "example": "const g = gearGeo({ teeth: 28, rootRadius: 0.063, tipRadius: 0.075, boreRadius: 0.012, height: 0.024 });\ncreatePart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:bladeGeo",+ "name": "bladeGeo",+ "summary": "Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.",+ "family": "geometry",+ "tags": [+ "geometry",+ "primitive",+ "shared geometry"+ ],+ "aliases": [+ "sword blade",+ "tapered blade"+ ],+ "intents": [+ "make a pointed blade"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyGeometry",+ "relation": "companion"+ },+ {+ "id": "operation:createPart",+ "relation": "companion"+ }+ ],+ "references": [+ "src/gears.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Length +Y, width X, thickness Z.",+ "origin": "Blade base at Y=0; centered across width and thickness.",+ "execution": "sync",+ "ownership": "Sandbox calls with identical serializable arguments reuse cached geometry. Treat it as shared; use copyGeometry before mutation. Direct module calls allocate separately.",+ "coordinates": "Geometry-local vertices; Object3D parent transforms are not applied.",+ "parameters": [+ "Positive finite length/baseWidth/thickness; 0 <= tipLength < length; edgeBevel is finite in 0..1. Zero tip length is a square end.",+ "edgeBevel controls a closed cross-section: flat rectangle at 0, partial bevels, diamond at 1. This is not a generic mesh bevel."+ ],+ "topology": [+ "Built-in triangulation describes the nominal shape; degenerate inputs are not a solid-validity certificate."+ ],+ "preservation": [+ "Creates positions and normals; UVs are not generated."+ ],+ "semantics": [+ "Sandbox cache may stamp source ranges; this is geometry provenance, not an assembly or QA policy."+ ],+ "cost": "Fixed tessellation with a bounded choice of cross-section; beveled tips taper to one point.",+ "example": "const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });\ncreatePart('Blade', b, steel, { position: [0, 0, 0], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:gameMaterial",+ "name": "gameMaterial",+ "summary": "Creates a configurable MeshStandardMaterial with flat shading enabled by default.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "flat shaded PBR"+ ],+ "intents": [+ "make a simple solid-color PBR material"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "gameMaterial(color, opts?: { metalness, roughness, emissive, emissiveIntensity, flatShading })",+ "returns": "THREE.MeshStandardMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "MeshStandardMaterial; defaults to flat shading with configurable roughness/metalness/emissive."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const mat = gameMaterial(0x8b7355, { roughness: 0.9 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:materialRecipe",+ "name": "materialRecipe",+ "summary": "Resolves a versioned portable bark/leaf/wood/stone/rubber/painted-metal/cloth/skin/glass/emissive recipe to standard glTF PBR.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "material preset"+ ],+ "intents": [+ "start from a named reusable material recipe"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts",+ "src/material-recipes.ts"+ ],+ "limitations": [+ "A recipe name does not imply surface relief, geometry, or visual qualification."+ ],+ "kind": "operation",+ "contract": {+ "signature": "await materialRecipe(recipeId, overrides?: { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })",+ "returns": "Promise<THREE.MeshStandardMaterial>",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "async",+ "ownership": "Resolves a new portable material through the host-injected recipe/texture boundary; resource caching is host-specific.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "A versioned approved recipe ID and its permitted overrides; availability depends on host resources.",+ "textureResources maps baseColor, normal, metallicRoughness, emissive or occlusion to approved resource ID strings. Use baseColor here, not the pbrMaterial field albedo. Check each resource allowedSlots and recipeIds.",+ "Use only listed kiln.material.*.v1 IDs and approved kiln.texture.* resource IDs. textureResources uses portable slots baseColor, normal, metallicRoughness, emissive and occlusion with ID string values; albedo is a pbrMaterial field, not a recipe slot. Check resource allowedSlots and recipeIds. All numeric overrides (including emissiveIntensity) are finite 0..1. Recipe emission is baked into the core glTF emissive factor. Leaf is MASK, glass is BLEND, and host file paths are forbidden. Overrides differ by recipe; any other key is rejected: bark, wood, stone, rubber, painted-metal, cloth: baseColor, roughness, metalness, doubleSided, textureResources; leaf: baseColor, roughness, alphaCutoff, doubleSided, textureResources; skin: baseColor, roughness, doubleSided; glass: baseColor, roughness, opacity, doubleSided; emissive: baseColor, roughness, doubleSided, emissiveColor, emissiveIntensity, textureResources."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Compiles portable material settings; texture delivery/quality is explicit resource metadata."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const bark = await materialRecipe('kiln.material.bark.v1', { baseColor: '#6b4328' });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:compilePortableMaterialSpecV2",+ "name": "compilePortableMaterialSpecV2",+ "summary": "Compiles the strict portable material contract. Texture refs are typed procedural V2 specs or typed approved-resource references; bare IDs, paths, URLs, raw textures, callbacks, and shader source are rejected.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "portable material specification",+ "project material library"+ ],+ "intents": [+ "compile a strict portable material definition"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/portable-material-runtime.ts",+ "docs/material-library.md",+ "docs/projects-and-live-review.md"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', name?, baseColor?, roughness?, metalness?, emissive?, emissiveIntensity?, alphaMode?, alphaCutoff?, doubleSided?, textures?: { baseColor?, normal?, metallicRoughness?, emissive?, occlusion? } })",+ "returns": "Promise<THREE.MeshStandardMaterial>",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "async",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "Strict schemaVersion 2 pbrMetallicRoughness specification.",+ "For workspace library materials, use the exact portableSpec returned by kiln_material and pin its material revision through per-call materialDependencies (CLI --materials) or an optional project lock. The host supplies verified map bytes; generated source cannot read library paths or fetch missing resources.",+ "baseColor and emissive are numeric color integers from 0x000000 to 0xffffff, for example baseColor: 0x8a867c. CSS strings and materialRecipe hex-string overrides are not accepted here.",+ "Texture references use typed procedural specs or approved resource IDs; arbitrary URLs, paths, callbacks and shaders are rejected.",+ "Each texture value is { kind: \"resource\", resourceId: \"kiln.texture...\" } or { kind: \"procedural\", spec: { schemaVersion: 2, ... } }. Bare ID strings are invalid; unlike materialRecipe.textureResources, this API requires the tagged object.",+ "Use textures: { baseColor: { kind: \"resource\", resourceId: \"kiln.texture.rough-concrete-albedo.v1\" } } for an approved resource, or { kind: \"procedural\", spec: { schemaVersion: 2, ... } }; bare ID strings are invalid. Use metallicRoughness as one packed G=roughness/B=metalness map. Every procedural ref usage must match its slot; resource refs must be approved for that exact slot. baseColor and emissive are numeric color integers from 0x000000 to 0xffffff, not CSS or materialRecipe hex strings. roughness, metalness and alphaCutoff are finite 0..1; emissiveIntensity is finite 0..64 (unlike materialRecipe, whose intensity is 0..1)."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Enforces supported portable material representation; does not certify visual similarity in every consumer."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const steel = await compilePortableMaterialSpecV2({ schemaVersion: 2, model: 'pbrMetallicRoughness', roughness: 0.45, metalness: 0.85, textures: { metallicRoughness: { kind: 'procedural', spec: { schemaVersion: 2, usage: 'metallicRoughness', size: 64, layers: [{ op: 'solid', color: 0x0080cc }] } } } });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:basicMaterial",+ "name": "basicMaterial",+ "summary": "Unlit flat material. For UI / effects where lighting is baked in.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "unlit material"+ ],+ "intents": [+ "make an unlit surface"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Does not provide physical lighting response."+ ],+ "kind": "operation",+ "contract": {+ "signature": "basicMaterial(color, opts?: { transparent, opacity })",+ "returns": "THREE.MeshBasicMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "Inspect alpha, roughness, metalness and color inputs against the exact signature."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Creates MeshBasicMaterial; unlit behavior depends on exporter and destination support."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const mat = basicMaterial(0xffffff, { transparent: true, opacity: 0.5 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:glassMaterial",+ "name": "glassMaterial",+ "summary": "Creates a transparent double-sided standard material using alpha blending.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "transparent panel"+ ],+ "intents": [+ "make a transparent-looking panel"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Approximate transparency, not physical transmission or refraction; sorting and overlapping surfaces require review."+ ],+ "kind": "operation",+ "contract": {+ "signature": "glassMaterial(color, opts?: { opacity, roughness, metalness })",+ "returns": "THREE.MeshStandardMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "Creates alpha-blended, double-sided MeshStandardMaterial; opacity is configurable."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const mat = glassMaterial(0x66ccff, { opacity: 0.3 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:lambertMaterial",+ "name": "lambertMaterial",+ "summary": "Creates a diffuse MeshLambertMaterial with optional flat shading and emission.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "diffuse material"+ ],+ "intents": [+ "make a simple diffuse surface"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Portable export may approximate the original shading model."+ ],+ "kind": "operation",+ "contract": {+ "signature": "lambertMaterial(color, opts?: { flatShading, emissive })",+ "returns": "THREE.MeshLambertMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "Creates MeshLambertMaterial; no PBR metalness/roughness inputs."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const mat = lambertMaterial(0x2a4d14, { flatShading: true });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:rotationTrack",+ "name": "rotationTrack",+ "summary": "Absolute local XYZ Euler degrees converted to quaternion keys. Use an exact node name; Joint_ is a convention. LINEAR follows shortest quaternion arcs; STEP holds until the next key. CUBICSPLINE is one smooth curve through the keys; EASE_IN, EASE_OUT and EASE_IN_OUT ease every segment, so one key pair is a smooth swing. The last four export as glTF CUBICSPLINE and need two or more keys.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "rotate joint",+ "quaternion keyframes"+ ],+ "intents": [+ "animate a pivot rotation"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "rotationTrack(jointName: string, keyframes: Array<{ time, rotation: [xDeg, yDeg, zDeg] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",+ "returns": "THREE.QuaternionKeyframeTrack",+ "units": "Times in seconds; Euler XYZ input rotations in degrees, converted to quaternion keyframes.",+ "axes": "Target-local XYZ axes.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",+ "rotation contains XYZ degree triples. LINEAR, the cubic modes and the eases follow shortest quaternion arcs between keys, not Euler turns; use quarter-turn samples for a full revolution."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not automatically preserve target rest transforms; author their values explicitly."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics.",+ "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",+ "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."+ ],+ "cost": "Linear in keyframe/track count.",+ "example": "rotationTrack('Joint_Lid', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [90, 0, 0] }], 'EASE_IN_OUT');"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:positionTrack",+ "name": "positionTrack",+ "summary": "Creates a translation track from absolute parent-local position keyframes and times in seconds.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "translation keyframes"+ ],+ "intents": [+ "animate a part position"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "positionTrack(jointName: string, keyframes: Array<{ time, position: [x, y, z] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",+ "returns": "THREE.VectorKeyframeTrack",+ "units": "Times in seconds; translation uses authored length units.",+ "axes": "Target-local XYZ axes.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",+ "position contains absolute parent-local XYZ values, not value:."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not automatically preserve target rest transforms; author their values explicitly."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics.",+ "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",+ "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."+ ],+ "cost": "Linear in keyframe/track count.",+ "example": "positionTrack('Joint_Body', [{ time: 0, position: [0, 0, 0] }, { time: 1, position: [0, 0.1, 0] }]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:scaleTrack",+ "name": "scaleTrack",+ "summary": "Uniform or per-axis scale track.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "scaling keyframes"+ ],+ "intents": [+ "animate uniform or per-axis scale"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "scaleTrack(jointName: string, keyframes: Array<{ time, scale: [x, y, z] }>, interp?: 'LINEAR' | 'STEP' | 'CUBICSPLINE' | 'EASE_IN' | 'EASE_OUT' | 'EASE_IN_OUT')",+ "returns": "THREE.VectorKeyframeTrack",+ "units": "Times in seconds; XYZ scale factors are dimensionless.",+ "axes": "Target-local XYZ axes.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not automatically preserve target rest transforms; author their values explicitly."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics.",+ "CUBICSPLINE passes one smooth curve through every key with PCHIP slopes: monotone between keys, never overshooting a key, at rest where the value holds or turns; two keys give a straight line.",+ "EASE_IN (s^2), EASE_OUT (2s - s^2) and EASE_IN_OUT (3s^2 - 2s^3) shape each segment between consecutive keys, s being the fraction of that segment; one key pair makes a smooth swing without sub-keys."+ ],+ "cost": "Linear in keyframe/track count.",+ "example": "scaleTrack('Joint_Chest', [{ time: 0, scale: [1, 1, 1] }, { time: 1, scale: [1.1, 1.1, 1.1] }]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createClip",+ "name": "createClip",+ "summary": "Validates supported position/quaternion/scale tracks and collects them into a named clip. Duration is seconds (-1 derives from keys); explicit duration must include every key. loop: true declares a cycle, false a one-shot; exported as the glTF animation extra kilnLoopIntent and reported by animation review. Returned from animate().",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "animation clip"+ ],+ "intents": [+ "collect tracks into a named motion"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "createClip(name: string, duration: number, tracks: KeyframeTrack[], options?: { loop?: boolean })",+ "returns": "THREE.AnimationClip",+ "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",+ "axes": "Defined by the supplied tracks.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates an AnimationClip sharing supplied track objects. Later caller mutation still needs validation. Export adds trailing holds on copied tracks only.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",+ "Only position/scale vector and quaternion tracks, unique target/channel pairs, valid strides and unit quaternion samples (squared-length tolerance 1e-4). No silent repairs.",+ "A cubic-spline track holds [in-tangent, value, out-tangent] per key, as a glTF CUBICSPLINE sampler does, and needs at least two keys; only its key values must be unit quaternions.",+ "Duration -1 derives from keys; explicit nonnegative seconds must include every key. Zero-duration time-zero static clips are valid. Longer duration is preserved by a held final native sample.",+ "options.loop: true declares a cycle and false a one-shot; omitted is unspecified. Exported as animations[].extras.kilnLoopIntent (loop | once); three.js GLTFLoader exposes it as clip.userData.kilnLoopIntent. Animation review reports it in loopClosure.loopIntent and warns when a declared loop does not close."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not automatically preserve target rest transforms; author their values explicitly."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics."+ ],+ "cost": "Linear in keyframe/track count.",+ "example": "return [createClip('Open', 1, [rotationTrack('Joint_Lid', [...])], { loop: false })];"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:idleBreathing",+ "name": "idleBreathing",+ "summary": "Gentle parent-local Y bob around options.basePosition, default [0,0,0]. Give the authored base explicitly or animate a separate zero-origin pivot.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "bob",+ "idle motion"+ ],+ "intents": [+ "make a simple vertical motion loop"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [+ "Target name cannot infer its rest pose. Supply basePosition explicitly or use a separate zero-origin animation pivot."+ ],+ "kind": "operation",+ "contract": {+ "signature": "idleBreathing(bodyJoint: string, duration?: 2, amount?: 0.02, options?: { basePosition?: [x, y, z] })",+ "returns": "THREE.AnimationClip",+ "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",+ "axes": "Translation along parent-local Y.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",+ "Positive duration in seconds; finite amount/height in authored length units. options.basePosition is a finite XYZ triple, default [0,0,0]."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Writes absolute positions around the supplied basePosition while leaving rotation/scale untouched. Snapshot numeric base components without mutating the caller array."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics."+ ],+ "cost": "One three-keyframe position track.",+ "example": "return [idleBreathing('Joint_Body', 2, 0.02, { basePosition: [0, 1.2, 0] })];"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:bobbingAnimation",+ "name": "bobbingAnimation",+ "summary": "Parent-local Y motion loop around options.basePosition, default [0,0,0]. A target name alone cannot infer its rest translation.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "bob",+ "idle motion"+ ],+ "intents": [+ "make a simple vertical motion loop"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [+ "Target name cannot infer its rest pose. Supply basePosition explicitly or use a separate zero-origin animation pivot."+ ],+ "kind": "operation",+ "contract": {+ "signature": "bobbingAnimation(rootName: string, duration?: 2, height?: 0.1, options?: { basePosition?: [x, y, z] })",+ "returns": "THREE.AnimationClip",+ "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",+ "axes": "Translation along parent-local Y.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected.",+ "Positive duration in seconds; finite amount/height in authored length units. options.basePosition is a finite XYZ triple, default [0,0,0]."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Writes absolute positions around the supplied basePosition while leaving rotation/scale untouched. Snapshot numeric base components without mutating the caller array."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics."+ ],+ "cost": "One three-keyframe position track.",+ "example": "return [bobbingAnimation('Joint_Root', 1.5, 0.08, { basePosition: [0, 0.5, 0] })];"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:spinAnimation",+ "name": "spinAnimation",+ "summary": "360° rotation over `duration` around `axis`.",+ "family": "animation",+ "tags": [+ "animation",+ "keyframes"+ ],+ "aliases": [+ "continuous rotation",+ "spin loop"+ ],+ "intents": [+ "rotate a named pivot through a complete turn"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/animation-spline.ts"+ ],+ "limitations": [+ "Place authored orientation on a parent pivot when using this identity-based preset."+ ],+ "kind": "operation",+ "contract": {+ "signature": "spinAnimation(jointName: string, duration?: 2, axis?: 'x' | 'y' | 'z')",+ "returns": "THREE.AnimationClip",+ "units": "Keyframe times and durations are seconds; transform values are absolute, not additive offsets.",+ "axes": "Selected local X/Y/Z rotation axis, default Y.",+ "origin": "Does not infer the target rest pose.",+ "execution": "sync",+ "ownership": "Creates track/clip data; does not mutate target scene nodes while constructing it.",+ "coordinates": "Absolute parent-local TRS values replace target components during playback.",+ "parameters": [+ "Exact nonempty node names; no property/path syntax or control characters. Existence and uniqueness require scene-aware inspection.",+ "Nonempty finite keyframes; nonnegative times must remain strictly increasing after float32 storage. Values must fit finite float32.",+ "LINEAR, STEP, CUBICSPLINE and the EASE_IN, EASE_OUT and EASE_IN_OUT shorthands survive native export and source/GLB review; the last four are glTF CUBICSPLINE samplers with computed tangents and need at least two keys. three.js smooth and Bezier interpolants have no glTF form and are rejected."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Writes absolute rotations from identity; does not compose an authored rest rotation."+ ],+ "semantics": [+ "Animation target strings bind to node names; names alone do not certify rig semantics."+ ],+ "cost": "One five-keyframe quaternion track using quarter turns.",+ "example": "return [spinAnimation('Joint_Rotor', 0.5, 'y')];"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:createInstance",+ "name": "createInstance",+ "summary": "Creates a new mesh reusing an existing part's geometry + material at a new transform. Cheapest way to replicate wheels / bolts / fence posts / windows. `rotation` is in DEGREES, like createPart.",+ "family": "instancing",+ "tags": [+ "instancing",+ "reuse",+ "mesh instances"+ ],+ "aliases": [+ "reuse mesh",+ "duplicate mesh node"+ ],+ "intents": [+ "place another copy of a single mesh"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts",+ "src/primitives.ts"+ ],+ "limitations": [+ "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."+ ],+ "kind": "operation",+ "contract": {+ "signature": "createInstance(name, source, opts?: { position, rotation: [xDeg, yDeg, zDeg], scale, parent })",+ "returns": "THREE.Object3D",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",+ "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",+ "parameters": [+ "source is a Mesh or has a direct Mesh child; absence throws.",+ "Position/rotation/scale are explicit new transforms; rotation is degrees."+ ],+ "topology": [+ "Source mesh geometry is shared unchanged."+ ],+ "preservation": [+ "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced."+ ],+ "semantics": [+ "New mesh names do not preserve full source semantic identity."+ ],+ "cost": "One new mesh; shared geometry/material buffers.",+ "example": "const wheelFL = createPart('WheelFL', wheelGeo, rubberMat, { position: [-0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelFR', wheelFL, { position: [0.8, 0.3, 1.2], parent: root });\ncreateInstance('WheelRL', wheelFL, { position: [-0.8, 0.3, -1.2], parent: root });\ncreateInstance('WheelRR', wheelFL, { position: [0.8, 0.3, -1.2], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:boolUnion",+ "name": "boolUnion",+ "summary": "Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.",+ "family": "csg",+ "tags": [+ "csg",+ "boolean",+ "solid",+ "async"+ ],+ "aliases": [+ "union",+ "fuse solids"+ ],+ "intents": [+ "combine overlapping volumes",+ "join overlapping solids",+ "boolean union"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ },+ {+ "id": "operation:autoUnwrap",+ "relation": "companion"+ }+ ],+ "references": [+ "src/solids.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",+ "returns": "Promise<THREE.Mesh>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",+ "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",+ "execution": "async",+ "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",+ "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",+ "parameters": [+ "Use closed, valid solid operands; Manifold WASM is loaded lazily.",+ "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",+ "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",+ "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",+ "Requires at least two operands."+ ],+ "topology": [+ "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."+ ],+ "preservation": [+ "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",+ "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",+ "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."+ ],+ "semantics": [+ "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."+ ],+ "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",+ "example": "const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);\nconst turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);\nturret.position.y = 0.5;\nconst hull = await boolUnion('Hull', body, turret);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:boolDiff",+ "name": "boolDiff",+ "summary": "Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.",+ "family": "csg",+ "tags": [+ "csg",+ "boolean",+ "solid",+ "async"+ ],+ "aliases": [+ "subtract",+ "carve",+ "cut holes"+ ],+ "intents": [+ "remove cutter volume from a solid",+ "subtract solids",+ "cut out a shape",+ "boolean difference"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ },+ {+ "id": "operation:autoUnwrap",+ "relation": "companion"+ }+ ],+ "references": [+ "src/solids.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false, preserveAttributes?: boolean })",+ "returns": "Promise<THREE.Mesh>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",+ "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",+ "execution": "async",+ "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",+ "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",+ "parameters": [+ "Use closed, valid solid operands; Manifold WASM is loaded lazily.",+ "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",+ "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",+ "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",+ "Requires body and at least one cutter."+ ],+ "topology": [+ "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."+ ],+ "preservation": [+ "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",+ "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",+ "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."+ ],+ "semantics": [+ "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."+ ],+ "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",+ "example": "const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);\nconst teeth = [...]; // 8 radially-arrayed box meshes\nconst gear = await boolDiff('Gear', body, ...teeth); // hard-edged"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:roundedBoxGeo",+ "name": "roundedBoxGeo",+ "summary": "A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.",+ "family": "csg",+ "tags": [+ "csg",+ "profile",+ "solid",+ "async"+ ],+ "aliases": [+ "rounded box",+ "chamfered block"+ ],+ "intents": [+ "make a block with softened edges"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/profile.ts"+ ],+ "limitations": [+ "This is a specific primitive, not a generic selected-edge bevel operation."+ ],+ "kind": "operation",+ "contract": {+ "signature": "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",+ "returns": "Promise<THREE.BufferGeometry>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",+ "axes": "Width X, height Y, depth Z.",+ "origin": "Centered at local origin; requested outer extents are maintained.",+ "execution": "async",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite positive dimensions and radius; radius must be less than half the smallest dimension.",+ "style round or chamfer; segments affect rounded construction.",+ "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await."+ ],+ "topology": [+ "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."+ ],+ "preservation": [+ "New geometry/normals/bounds; does not carry authored UVs from an input mesh."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",+ "example": "const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);\ncreatePart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:extrudeProfile",+ "name": "extrudeProfile",+ "summary": "Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.",+ "family": "csg",+ "tags": [+ "csg",+ "profile",+ "solid",+ "async"+ ],+ "aliases": [+ "extrude outline",+ "profile extrusion"+ ],+ "intents": [+ "make a solid from a planar cross-section with optional holes"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:circleProfile",+ "relation": "companion"+ },+ {+ "id": "operation:sweepProfile",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/profile.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: 0, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",+ "returns": "Promise<THREE.BufferGeometry>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",+ "axes": "For profile (u,v) and extrusion depth coordinate d, output XYZ is axis x: (d, v, -u); axis y: (u, d, -v); axis z: (u, v, d). Default axis is y. For a desired XZ footprint on axis y, pass profile [X,-Z].",+ "origin": "center defaults true; center false starts depth at the selected-axis origin.",+ "execution": "async",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Finite closed outline, optional finite hole outlines, positive depth.",+ "Twist is degrees; taper is dimensionless; divisions is a whole number >= 0 of intermediate rings, default 0 (16 when twisting).",+ "Bevel uses profile units. If its inward offset empties the section, execution rejects with repair advice: reduce bevel below half the narrowest width, disable it, or widen the section.",+ "Profile (u,v) maps to XYZ as axis x: (d,v,-u), axis y: (u,d,-v), axis z: (u,v,d), where d is extrusion depth. For a desired XZ footprint on axis y, pass [X,-Z]; positive profile v projects toward -Z. The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. divisions is the whole number (>= 0) of intermediate rings between the caps: default 0, or 16 when twisting; a straight or tapered sweep needs none. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build()."+ ],+ "topology": [+ "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."+ ],+ "preservation": [+ "New geometry/normals/bounds; does not carry authored UVs from an input mesh."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",+ "example": "// L-bracket, inner AND outer corners filleted\nconst outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];\nconst geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });\ncreatePart('Bracket', geo, steel, { parent: root });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:revolveProfile",+ "name": "revolveProfile",+ "summary": "Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.",+ "family": "csg",+ "tags": [+ "csg",+ "profile",+ "solid",+ "async"+ ],+ "aliases": [+ "solid revolution",+ "turned solid"+ ],+ "intents": [+ "turn a closed section into a solid vessel or knob"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:revolveGeo",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/profile.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",+ "returns": "Promise<THREE.BufferGeometry>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. angle/twist and pitch parameters use degrees.",+ "axes": "Profile x is radial distance, y is distance along selected X/Y/Z axis (default Y). Around Y, the sweep starts at +X and proceeds toward -Z.",+ "origin": "Rotation axis passes through local origin.",+ "execution": "async",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Closed finite profile; only nonnegative radial side is used.",+ "angle in (0,360] degrees; segments and bevel options control tessellation.",+ "Bevel uses profile units. If its inward offset empties the section, execution rejects with repair advice: reduce bevel below half the narrowest width, disable it, or widen the section.",+ "Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build()."+ ],+ "topology": [+ "Manifold-backed solid generation from valid profiles; not a guarantee that any arbitrary input describes the intended solid."+ ],+ "preservation": [+ "New geometry/normals/bounds; does not carry authored UVs from an input mesh."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "WASM complexity depends on profile vertices, segments and divisions; no general allocation bound is claimed.",+ "example": "// capsule tank with a rounded rim, then carve a port into it\nconst profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];\nconst body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });\nconst tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:circleProfile",+ "name": "circleProfile",+ "summary": "Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.",+ "family": "csg",+ "tags": [+ "csg",+ "profile",+ "circle"+ ],+ "aliases": [+ "circular outline"+ ],+ "intents": [+ "create a reusable circular profile"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/profile.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "circleProfile(radius: number, segments?: 24, center?: [number, number])",+ "returns": "[number, number][]",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "2D points in caller-selected profile plane.",+ "origin": "Optional 2D center; default origin.",+ "execution": "sync",+ "ownership": "Returns a new point array.",+ "coordinates": "Profile-local 2D coordinates.",+ "parameters": [+ "Finite positive radius; segment count must be an integer at least 3."+ ],+ "topology": [+ "Closed outline represented without repeating the endpoint; no 3D mesh."+ ],+ "preservation": [+ "Generates profile points only."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in segments, default 24.",+ "example": "const washer = await extrudeProfile(circleProfile(1), {\n depth: 0.1,\n holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],\n});"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:boolIntersect",+ "name": "boolIntersect",+ "summary": "Keeps only the volume where both operands overlap. Default flat shading.",+ "family": "csg",+ "tags": [+ "csg",+ "boolean",+ "solid",+ "async"+ ],+ "aliases": [+ "intersection",+ "overlap volume"+ ],+ "intents": [+ "retain only the shared volume",+ "intersection of solids",+ "overlapping volume"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ },+ {+ "id": "operation:autoUnwrap",+ "relation": "companion"+ }+ ],+ "references": [+ "src/solids.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false, preserveAttributes?: boolean })",+ "returns": "Promise<THREE.Mesh>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",+ "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",+ "execution": "async",+ "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",+ "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",+ "parameters": [+ "Use closed, valid solid operands; Manifold WASM is loaded lazily.",+ "Use static triangle meshes. Bake instances, skin poses and active morphs before CSG; these operands are rejected rather than read as base geometry.",+ "smooth affects normals; preserveAttributes requests UV/material provenance where supported.",+ "Keep shape detail in local coordinates; a common frame cannot recover precision already lost in input buffers/transforms or resolve arbitrarily tiny features across a vast combined extent.",+ "Two operands."+ ],+ "topology": [+ "Uses Manifold solid operations; malformed/degenerate operands can fail. Empty boolean results are rejected with diagnostics."+ ],+ "preservation": [+ "Default path does not promise UV retention; preservation mode carries supported UV/material groups and reports losses.",+ "Cut-face UV0/materials come from the cutter. Colors, secondary UVs, tangents, skin/custom attributes and inactive morph targets are dropped with diagnostics; normals are regenerated.",+ "Source attribute/geometry diagnostics are retained without sharing mutable records. Arbitrary user metadata and animation are not carried onto the new topology."+ ],+ "semantics": [+ "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."+ ],+ "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",+ "example": "const lens = await boolIntersect('Lens', boxMesh, sphereMesh);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:hull",+ "name": "hull",+ "summary": "Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.",+ "family": "csg",+ "tags": [+ "csg",+ "boolean",+ "solid",+ "async"+ ],+ "aliases": [+ "convex hull",+ "convex envelope"+ ],+ "intents": [+ "enclose geometry with a convex shape"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:geometryDiagnostics",+ "relation": "companion"+ },+ {+ "id": "operation:autoUnwrap",+ "relation": "companion"+ }+ ],+ "references": [+ "src/solids.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true, preserveAttributes?: boolean })",+ "returns": "Promise<THREE.Mesh>",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Uses one translated and uniformly normalized computation frame for all operands; output axes remain world-aligned.",+ "origin": "The unparented result mesh.position is the first contributing mesh world origin; geometry positions are local to that origin. Preserve the returned mesh transform.",+ "execution": "async",+ "ownership": "Creates output mesh/geometry; does not mutate operand geometry. Material sharing and generated groups depend on preservation options.",+ "coordinates": "World operand relationships are preserved, not their hierarchy. Read world bounds or apply the returned matrix when inspecting positions; geometry alone no longer contains the world translation.",+ "parameters": [+ "At least one part; convex enclosure uses its input points."+ ],+ "topology": [+ "Convex solid envelope; removes concavities and does not preserve internal cavities."+ ],+ "preservation": [+ "Generated hull faces have unknown source UV/material provenance; do not infer original texture mapping."+ ],+ "semantics": [+ "Output is a new mesh, not the source articulated assembly; provenance is operation-specific."+ ],+ "cost": "WASM work depends on operand topology/intersections; no universal input-size or time bound is claimed.",+ "example": "const rockChunks = [...]; // scattered box meshes\nconst rock = await hull('Rock', ...rockChunks);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:arrayLinear",+ "name": "arrayLinear",+ "summary": "`count` is the TOTAL, source included: the source stays where it is as copy 0 and the call returns count-1 new instances, so count 10 gives 10 posts, not 11. Copies share geometry + material via createInstance, and carry the source rotation and scale.",+ "family": "arrays",+ "tags": [+ "arrays",+ "reuse",+ "mesh instances"+ ],+ "aliases": [+ "linear repeat",+ "row of parts"+ ],+ "intents": [+ "repeat a mesh at regular offsets",+ "linear repetition",+ "repeat along a line",+ "straight row",+ "regular spacing",+ "bench or fence slats"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts",+ "src/primitives.ts"+ ],+ "limitations": [+ "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."+ ],+ "kind": "operation",+ "contract": {+ "signature": "arrayLinear(namePrefix, source, count, offset: [x,y,z], parent?)",+ "returns": "THREE.Object3D[]",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Three.js local XYZ; +Y is the normal up convention.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",+ "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",+ "parameters": [+ "count is a safe integer from 1 to 10,000 including the original source; returns count-1 new meshes.",+ "offset and source transforms must be finite; resulting positions are checked before any attachment. Coordinates are source-parent local."+ ],+ "topology": [+ "Source mesh geometry is shared unchanged."+ ],+ "preservation": [+ "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",+ "Copies preserve source rotation and scale."+ ],+ "semantics": [+ "New mesh names do not preserve full source semantic identity."+ ],+ "cost": "count-1 new mesh nodes; draw calls are not automatically batched.",+ "example": "const post = createPart('Post0', cylinderGeo(0.05,0.05,1.5,6), wood, { position: [0,0.75,0], parent: root });\narrayLinear('Post', post, 10, [0.5, 0, 0], root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:arrayRadial",+ "name": "arrayRadial",+ "summary": "`count` is the TOTAL, source included: the source stays at its angle as copy 0 and the call returns count-1 new mesh instances. Copies preserve source scale. Default outward rotation follows the orbit; relative orientation composes the orbit with the source rotation. Copies orbit the parent's origin unless you pass center. This is mesh reuse, not hierarchy-preserving assembly replication.",+ "family": "arrays",+ "tags": [+ "arrays",+ "reuse",+ "mesh instances"+ ],+ "aliases": [+ "circular repeat",+ "radial pattern"+ ],+ "intents": [+ "repeat a mesh around a center",+ "radial repetition",+ "repeat around a circle",+ "circular pattern",+ "ring of supports",+ "arena seating"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts",+ "src/primitives.ts"+ ],+ "limitations": [+ "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."+ ],+ "kind": "operation",+ "contract": {+ "signature": "arrayRadial(namePrefix, source, count, axis?: 'x'|'y'|'z', parent?, center?: [x,y,z], opts?: { orientation?: 'outward'|'relative' })",+ "returns": "THREE.Object3D[]",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Orbit around selected local X/Y/Z axis, default Y.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",+ "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",+ "parameters": [+ "count is a safe integer from 1 to 10,000 including source; finite center defaults to parent origin.",+ "axis must be x/y/z; orientation outward follows orbit and relative composes with source rotation. Source transforms and all resulting positions must be finite."+ ],+ "topology": [+ "Source mesh geometry is shared unchanged."+ ],+ "preservation": [+ "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",+ "Preserves source scale; rotation follows the explicit orientation mode."+ ],+ "semantics": [+ "New mesh names do not preserve full source semantic identity."+ ],+ "cost": "count-1 mesh nodes; no automatic draw-call batching.",+ "example": "const bolt = createPart('Bolt0', cylinderGeo(0.02,0.02,0.1,6), steel, { position: [1,0,0], parent: root });\narrayRadial('Bolt', bolt, 8, 'y', root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:mirror",+ "name": "mirror",+ "summary": "Reflects source across the plane whose normal is `axis`. Uses negative scale (winding flip handled by viewers).",+ "family": "arrays",+ "tags": [+ "arrays",+ "reuse",+ "mesh instances"+ ],+ "aliases": [+ "reflect part"+ ],+ "intents": [+ "place a reflected counterpart",+ "reflection across a plane",+ "opposite side",+ "symmetric counterpart"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts",+ "src/primitives.ts"+ ],+ "limitations": [+ "Mesh reuse is not hierarchy-preserving assembly replication or hardware instancing."+ ],+ "kind": "operation",+ "contract": {+ "signature": "mirror(name, source, axis: 'x'|'y'|'z', parent?)",+ "returns": "THREE.Object3D",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. explicit rotation triples use degrees unless stated otherwise.",+ "axes": "Reflects across the origin plane normal to X/Y/Z.",+ "origin": "Position is relative to the selected parent.",+ "execution": "sync",+ "ownership": "Creates new mesh nodes sharing source geometry/material; not deep copies.",+ "coordinates": "Source local transform values and array offsets are interpreted without converting between different parent frames.",+ "parameters": [+ "A source mesh/direct mesh child and explicit reflection axis.",+ "Requires a finite nonsingular local transform representable as TRS; local shear is rejected."+ ],+ "topology": [+ "Source mesh geometry is shared unchanged."+ ],+ "preservation": [+ "Only the source mesh or first direct Mesh child is used; nested assemblies, child transforms and semantic hierarchy are not reproduced.",+ "Reflection is represented by transforms; viewers/exporters must respect negative determinant winding."+ ],+ "semantics": [+ "New mesh names do not preserve full source semantic identity."+ ],+ "cost": "One new mesh sharing geometry/material.",+ "example": "mirror('WingR', wingL, 'x', root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:subdivide",+ "name": "subdivide",+ "summary": "Loop subdivision returns new geometry; each iteration roughly quadruples triangles and smooths the surface. Use preserveUV:true for textured meshes. Legacy position-only welding discards UVs and reports that loss. This smooths shapes, not selected-edge beveling.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "mesh processing",+ "subdivision"+ ],+ "aliases": [+ "smooth subdivision"+ ],+ "intents": [+ "add segments and smooth a coarse mesh"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [+ "Conservative per-operation budgets include presplit growth. They are not a peak-memory guarantee; host evaluation limits still apply."+ ],+ "kind": "operation",+ "contract": {+ "signature": "subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { preserveUV?: boolean, split?: boolean, uvSmooth?: boolean, preserveEdges?: boolean, flatOnly?: boolean, weld?: boolean })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Preserves source axes; smoothing moves vertices.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "iterations is an integer 0..10, default 1; options determine welding, UV preservation and edge behavior.",+ "preserveUV must be explicit for the textured preservation path; subdivide before skin binding because joint indices cannot be interpolated safely.",+ "Continuous vertex attributes have 1..4 components; normalized storage is decoded to owned Float32 and all four RGBA channels are interpolated. Morph attributes currently require three components."+ ],+ "topology": [+ "Loop subdivision changes topology and shape; not selected-edge beveling or general remeshing."+ ],+ "preservation": [+ "preserveUV path retains corner UVs, material groups and supported morph attributes. Position-only welding reports removed UVs, other attributes, groups and morphs; tangents are invalidated.",+ "All paths normalize working coordinates before position welding and upstream adjacency hashing, then restore original units; features near the relative weld/grid resolution need review.",+ "Normals/bounds are updated and unsupported provenance is invalidated."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Preflight upper bound is input triangles × 4^iterations × 4 when split is enabled (default). Rejects above 1,000,000 triangles or 128 MiB of output attributes, including morph channels, before cloning/welding. No silent truncation.",+ "example": "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:mergeVertices",+ "name": "mergeVertices",+ "summary": "Returns indexed geometry. Default welding preserves attribute seams, so a textured cube retains separate face corners. positionOnly:true welds coincident positions and discards other attributes; use it explicitly when changing topology and regenerate shading/UVs afterward.",+ "family": "mesh-ops",+ "tags": [+ "mesh-ops",+ "mesh processing",+ "weld"+ ],+ "aliases": [+ "weld vertices"+ ],+ "intents": [+ "merge duplicate vertices deliberately"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [+ "Do not use position-only welding as an invisible textured-mesh optimization."+ ],+ "kind": "operation",+ "contract": {+ "signature": "mergeVertices(geometry: BufferGeometry, opts?: { tolerance?: 1e-4, positionOnly?: boolean } | number)",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Preserves source axes.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "sync",+ "ownership": "Normally returns new indexed geometry; positionOnly mode with no position attribute currently returns the input unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "tolerance defaults 1e-4; default attribute-aware weld preserves seams.",+ "positionOnly explicitly discards non-position attributes."+ ],+ "topology": [+ "Merges matching vertices; does not prove manifoldness or repair self-intersections."+ ],+ "preservation": [+ "Default weld retains differing attribute seams; positionOnly loses UVs/normals/other attributes and requires regeneration."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Depends on vertex count and hashed attribute width.",+ "example": "const welded = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true });\nconst rock = displace(subdivide(welded, 2), ([x,y,z]) => [0.08*Math.sin(y*7+z*3), 0.04*Math.sin(x*9), 0]);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:curveToMesh",+ "name": "curveToMesh",+ "summary": "Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a circle profile. Use for pipes, cables, tubular frames.",+ "family": "curves",+ "tags": [+ "curves",+ "curve",+ "surface",+ "path"+ ],+ "aliases": [+ "tube along spline",+ "cable"+ ],+ "intents": [+ "make a round tube along a curved path",+ "curved tube",+ "tube following a curve",+ "hose conduit cable"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [+ "Open path ends are uncapped; input stations can overshoot under spline interpolation."+ ],+ "kind": "operation",+ "contract": {+ "signature": "curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Path points use XYZ; frames are chosen by the curve implementation.",+ "origin": "Defined by path/profile coordinates.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Circular tube follows Catmull-Rom interpolation of points; closed controls the path.",+ "radius is required: positive, finite and representable in Float32, in asset units. Undefined dimensions fail instead of selecting a default radius.",+ "Default tubularSegments 32, radialSegments 8."+ ],+ "topology": [+ "Generates a surface; endpoint caps and a watertight solid are not implicit."+ ],+ "preservation": [+ "Generates normals and UVs; eager bounding volumes are not guaranteed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Tessellation grows with longitudinal × radial segments; no broad resource cap is claimed.",+ "example": "const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:pipeAlongPath",+ "name": "pipeAlongPath",+ "summary": "Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.",+ "family": "curves",+ "tags": [+ "curves",+ "curve",+ "surface",+ "path"+ ],+ "aliases": [+ "pipe",+ "rounded path"+ ],+ "intents": [+ "make a tube with softened path corners",+ "tube along a path",+ "curved pipe",+ "hose conduit cable"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:sweepProfile",+ "relation": "alternative"+ },+ {+ "id": "operation:curveToMesh",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [+ "Tube ends remain open; this does not construct a hollow pipe wall."+ ],+ "kind": "operation",+ "contract": {+ "signature": "pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Path points use XYZ; frames are chosen by the curve implementation.",+ "origin": "Defined by path/profile coordinates.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "bendRadius inserts interpolated corner waypoints; it is not an exact circular fillet radius.",+ "radius is required: positive, finite and representable in Float32, in asset units. Undefined dimensions fail instead of selecting a default radius.",+ "Other tube options follow the signature."+ ],+ "topology": [+ "Generates a surface; endpoint caps and a watertight solid are not implicit."+ ],+ "preservation": [+ "Generates normals and UVs; eager bounding volumes are not guaranteed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Tessellation grows with longitudinal × radial segments; no broad resource cap is claimed.",+ "example": "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:lathe",+ "name": "lathe",+ "summary": "Surface of revolution. Spins a 2D profile around the Y axis. For bottles, vases, wheels, turned wood parts.",+ "family": "curves",+ "tags": [+ "curves",+ "curve",+ "surface",+ "path"+ ],+ "aliases": [+ "lathe surface"+ ],+ "intents": [+ "turn a radial profile into a surface"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:revolveProfile",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "lathe(profile: [x,y][], segments?: 12)",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "Profile x is radius, y is height; spins around Y.",+ "origin": "Defined by path/profile coordinates.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Open or closed profile point list; segments default 12."+ ],+ "topology": [+ "Generates a surface; endpoint caps and a watertight solid are not implicit."+ ],+ "preservation": [+ "Generates normals and UVs; eager bounding volumes are not guaranteed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in profile points × revolution segments.",+ "example": "const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:revolveGeo",+ "name": "revolveGeo",+ "summary": "Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.",+ "family": "curves",+ "tags": [+ "curves",+ "curve",+ "surface",+ "path"+ ],+ "aliases": [+ "surface revolution",+ "partial lathe"+ ],+ "intents": [+ "revolve a surface about an arbitrary axis"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:revolveProfile",+ "relation": "alternative"+ }+ ],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })",+ "returns": "THREE.BufferGeometry",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion. sweep angle is radians (default 2π), unlike revolveProfile degrees.",+ "axes": "Profile x is radius, y is axial distance; arbitrary nonzero axis vector. Before axis reorientation, the Y sweep starts at +Z and proceeds toward +X.",+ "origin": "Defined by path/profile coordinates.",+ "execution": "sync",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Profile points and revolution segments; explicit angular sweep in radians."+ ],+ "topology": [+ "Generates a surface; endpoint caps and a watertight solid are not implicit."+ ],+ "preservation": [+ "Generates normals and UVs; eager bounding volumes are not guaranteed."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in profile points × revolution segments.",+ "example": "// Half-dome (180° sweep around +Y):\nconst quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });\nconst dome = revolveGeo(quarter, { angle: Math.PI });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:bezierCurve",+ "name": "bezierCurve",+ "summary": "Samples a quadratic (3 ctrl pts) or cubic (4 ctrl pts) Bézier into a point list you can feed into curveToMesh.",+ "family": "curves",+ "tags": [+ "curves",+ "curve",+ "surface",+ "path"+ ],+ "aliases": [+ "bezier samples",+ "quadratic curve",+ "cubic curve"+ ],+ "intents": [+ "sample a controlled curved path",+ "quadratic cubic bezier control points",+ "sample curved path"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/ops.ts"+ ],+ "limitations": [+ "Passing samples to curveToMesh applies Catmull-Rom interpolation again."+ ],+ "kind": "operation",+ "contract": {+ "signature": "bezierCurve(controlPoints: [x,y,z][], samples?: 32)",+ "returns": "[x,y,z][]",+ "units": "Lengths use authored scene units (normally metres); no automatic unit conversion.",+ "axes": "XYZ control points.",+ "origin": "Defined by supplied control points.",+ "execution": "sync",+ "ownership": "Returns a new array of sampled points.",+ "coordinates": "Control-point coordinate space; no parent transforms.",+ "parameters": [+ "Exactly 3 quadratic or 4 cubic control points; sample count controls point density."+ ],+ "topology": [+ "Point sequence only; no geometry or caps."+ ],+ "preservation": [+ "Retains sampled curve positions, not a reusable parametric curve object."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in sample count.",+ "example": "const path = bezierCurve([[0,0,0],[1,2,0],[3,2,0],[4,0,0]], 24);\nconst geo = curveToMesh(path, 0.1);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:autoUnwrap",+ "name": "autoUnwrap",+ "summary": "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",+ "family": "uv",+ "tags": [+ "uv",+ "atlas",+ "async"+ ],+ "aliases": [+ "UV atlas",+ "unwrap charts"+ ],+ "intents": [+ "create packed UVs for baked textures",+ "unwrap texture coordinates",+ "UV atlas",+ "unfold mesh"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/uv.ts"+ ],+ "limitations": [+ "Arbitrary chart rotation is unsuitable when directional tileable textures should retain analytic mapping."+ ],+ "kind": "operation",+ "contract": {+ "signature": "await autoUnwrap(geometry: BufferGeometry, opts?: { resolution?: 1024, padding?: 2, useNormals?: false })",+ "returns": "Promise<THREE.BufferGeometry>",+ "units": "UVs are dimensionless; source positions retain authored units.",+ "axes": "Chart orientation is selected by xatlas, not a directional material frame.",+ "origin": "Preserves the authored origin unless stated otherwise.",+ "execution": "async",+ "ownership": "Returns independent geometry buffers; the input remains unchanged.",+ "coordinates": "Geometry-local coordinates; parent transforms are not applied.",+ "parameters": [+ "Nonempty complete triangle geometry; resolution is a packing limit, not guaranteed final dimensions.",+ "padding defaults 2; useNormals defaults false."+ ],+ "topology": [+ "Reindexes/splits vertices for charts; does not repair malformed source topology."+ ],+ "preservation": [+ "Returns new positions/index/UVs and atlas metadata; normals depend on input/options.",+ "Arbitrary custom attributes, groups, materials and original UV orientation are not preserved by this reconstruction."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "WASM charting/packing depends on mesh complexity and resolution; no general time bound.",+ "example": "const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });\nconst mesh = new THREE.Mesh(unwrapped, bakedPbr);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:loadApprovedTexture",+ "name": "loadApprovedTexture",+ "summary": "Loads one approved kiln.texture.* resource ID through the host-injected closed resolver. The registry fixes bytes, MIME, usage, dimensions, hash, and deadline; paths, URLs, byte arrays, resolver objects, hashes, and options are rejected.",+ "family": "textures",+ "tags": [+ "textures",+ "texture",+ "approved resources",+ "async"+ ],+ "aliases": [+ "approved texture"+ ],+ "intents": [+ "load a permitted material resource"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts",+ "src/material-resources.ts"+ ],+ "limitations": [+ "Missing resource capability fails; arbitrary file/network loading is not exposed."+ ],+ "kind": "operation",+ "contract": {+ "signature": "await loadApprovedTexture(resourceId)",+ "returns": "Promise<THREE.DataTexture>",+ "units": "Texture sizes in pixels; color/data usage is explicit.",+ "axes": "Image U/V coordinates, not scene axes.",+ "origin": "Image-local coordinates.",+ "execution": "async",+ "ownership": "Returns the host-resolved texture; cache sharing is host-specific and not an independent-copy guarantee.",+ "coordinates": "Texture space; does not generate mesh UVs.",+ "parameters": [+ "One approved kiln.texture.* resource ID; paths, URLs, arbitrary bytes and loader options are rejected.",+ "Host resolver fixes dimensions, bytes/hash, MIME, usage and deadlines.",+ "Use only a concrete resource ID listed in material capabilities; never invent one. Prefer materialRecipe when a recipe already binds the family, or proceduralTexture V2 for authored surfaces. NEVER texture.clone() a loaded texture (clone() corrupts encoded bytes and breaks GLB export)."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Portable texture bytes and usage metadata matter independently of material appearance."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Host-bounded approved resource loading; network availability is host-specific.",+ "example": "const bark = await loadApprovedTexture('kiln.texture.bark-brown-01-albedo.v1');"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:proceduralTexture",+ "name": "proceduralTexture",+ "summary": "Builds a repeat-wrapped texture from a bounded layer stack, with no image file needed. Layers composite bottom-first; the same spec produces the same bytes. Seeded noise is tileable, while other patterns can have visible repeat seams. Baked to PNG and embedded in the GLB automatically.",+ "family": "textures",+ "tags": [+ "textures",+ "texture",+ "procedural",+ "deterministic"+ ],+ "aliases": [+ "generated texture",+ "noise texture",+ "layered pattern"+ ],+ "intents": [+ "generate a repeatable texture without external image files"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/procedural-texture.ts"+ ],+ "limitations": [+ "Repeat wrapping does not guarantee matching edge colors. Odd stripe counts, angled patterns and nonconstant gradients can show seams; inspect the chosen pattern at its repeat boundaries."+ ],+ "kind": "operation",+ "contract": {+ "signature": "proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers: ProceduralLayer[] })",+ "returns": "THREE.DataTexture (tiling, sRGB or linear per usage)",+ "units": "Texture sizes in pixels; color/data usage is explicit.",+ "axes": "Image U/V coordinates, not scene axes.",+ "origin": "Image-local coordinates.",+ "execution": "sync",+ "ownership": "Creates a new DataTexture with generated bytes and portable metadata.",+ "coordinates": "Texture space; does not generate mesh UVs.",+ "parameters": [+ "Strict schemaVersion 2; size power-of-two 4..1024; at most 8 layers.",+ "Pattern counts 1..256 and noise octaves 1..6; seeded patterns are deterministic.",+ "For stripes and gradient, angleDeg rotates the direction of color variation in UV space about the image center. At 0 degrees colors vary across U: stripe bands run along V. At 90 degrees colors vary across V: bands run along U. This does not rotate the mesh UVs.",+ "Stripes count is the number of alternating bands across one unit of the projected coordinate, not the number of colorA/colorB pairs. Gradient runs from its from color to its to color along that coordinate and clamps outside 0..1.",+ "Unknown keys, callbacks, paths, URLs and shader source are rejected.",+ "Layer fields by op — solid: { color }; checker: { colorA, colorB, squares? }; stripes: { colorA, colorB, count?, angleDeg? }; gradient: { from, to, angleDeg? }; bricks: { brick, mortar, rows?, cols?, mortarWidth?: 0..1 (fraction of a brick cell, default 0.06), stagger?: 0..1 (row offset fraction, default 0.5) }; noise: { colorA, colorB, scale?, octaves?, seed? }. Every layer also accepts blend?: 'normal'|'multiply'|'screen'|'overlay' and opacity?: 0..1. Pattern counts are integers 1..256; noise octaves are 1..6. Sync — no await. Unknown/prototype keys, callbacks, paths, URLs, and shader source are rejected. Max 8 layers."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Produces repeat-wrapped encoded texture content; color space follows usage."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Bounded pixel/layer budgets; generation scales with pixels × layers × pattern work.",+ "example": "const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name: 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:normalMapFromHeight",+ "name": "normalMapFromHeight",+ "summary": "Derives a tangent-space normal map from the source texture's brightness, treating it as height. The cheap way to get real PBR surface relief out of a procedural albedo. Wraps at the edges, so a tiling source gives a tiling normal map.",+ "family": "textures",+ "tags": [+ "textures",+ "texture",+ "normal map"+ ],+ "aliases": [+ "height to normal",+ "bump relief"+ ],+ "intents": [+ "derive surface normals from a height image"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/procedural-texture.ts"+ ],+ "limitations": [+ "Does not displace actual geometry or certify the supplied albedo is a meaningful height field."+ ],+ "kind": "operation",+ "contract": {+ "signature": "normalMapFromHeight(source: THREE.Texture, { strength?: number, name?: string })",+ "returns": "THREE.DataTexture (linear normal map)",+ "units": "Texture sizes in pixels; color/data usage is explicit.",+ "axes": "Image U/V coordinates, not scene axes.",+ "origin": "Image-local coordinates.",+ "execution": "sync",+ "ownership": "Creates a new linear-data normal texture; source pixels are read, not changed.",+ "coordinates": "Texture space; does not generate mesh UVs.",+ "parameters": [+ "Source must expose supported pixel data; strength controls height-gradient magnitude.",+ "strength 1 is subtle, 4-8 reads clearly at normal viewing distance. Output is always linear data — never assign it to an albedo/emissive slot."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Uses brightness as height and wraps image edges; output is tangent-space normal data, not albedo."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Linear in source pixel count with neighboring pixel samples.",+ "example": "const bark = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x3d2f21, colorB: 0x7a6248, scale: 6, octaves: 4 }] });\nconst mat = pbrMaterial({ albedo: bark, normal: normalMapFromHeight(bark, { strength: 4 }) });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:pbrMaterial",+ "name": "pbrMaterial",+ "summary": "Portable glTF PBR material. Use an explicit packed metallicRoughness texture (G=roughness, B=metalness); separate data maps are rejected instead of silently dropping a channel. alphaMode takes lowercase opaque/mask/blend and exports uppercase glTF modes. Supports double-sided output.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "textured PBR",+ "metallic roughness material"+ ],+ "intents": [+ "bind portable material textures and scalar factors"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/textures.ts"+ ],+ "limitations": [+ "CPU views do not prove texture/metalness appearance."+ ],+ "kind": "operation",+ "contract": {+ "signature": "pbrMaterial({ albedo?, normal?, roughness?, metalness?, metallicRoughness?, emissive?, emissiveIntensity?, aoMap?, aoMapIntensity?, alphaMode?: 'opaque'|'mask'|'blend', alphaCutoff?, doubleSided? })",+ "returns": "THREE.MeshStandardMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "alphaMode input is lowercase: opaque (default), mask or blend. Exported glTF uses uppercase OPAQUE/MASK/BLEND; do not pass those as authoring values.",+ "Use packed metallicRoughness data (G roughness, B metalness); unsupported separate data maps are rejected."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Binds texture slots with usage-appropriate color spaces; geometry must provide suitable UVs."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const wood = proceduralTexture({ schemaVersion: 2, usage: 'albedo', layers: [{ op: 'noise', colorA: 0x4f301c, colorB: 0x9a6b3e, scale: 8, octaves: 3, seed: 4 }] });\nconst crate = pbrMaterial({ albedo: wood, roughness: 0.85, metalness: 0 });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:foliageMaterial",+ "name": "foliageMaterial",+ "summary": "Portable foliage material that defaults to glTF MASK, cutoff 0.5, rough nonmetal, and double-sided. Use an alpha-bearing albedo texture.",+ "family": "material",+ "tags": [+ "material"+ ],+ "aliases": [+ "alpha cutout",+ "leaf material"+ ],+ "intents": [+ "render cutout cards with portable alpha masking",+ "leaf transparency",+ "foliage cutout",+ "alpha mask"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:copyMaterial",+ "relation": "companion"+ }+ ],+ "references": [+ "src/textures.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "foliageMaterial(albedo, { alphaCutoff?, roughness?, doubleSided? })",+ "returns": "THREE.MeshStandardMaterial",+ "units": "Color/material parameters, not geometry lengths; scalar factors follow the helper signature.",+ "axes": "Not applicable to material construction.",+ "origin": "Not applicable to material construction.",+ "execution": "sync",+ "ownership": "Returns a new material; supplied textures remain referenced, not deep-copied.",+ "coordinates": "Does not place geometry or generate UV coordinates.",+ "parameters": [+ "Defaults to MASK, alphaCutoff 0.5, rough nonmetal and double-sided; requires useful alpha-bearing albedo.",+ "The example uses an approved 4x4 teaching placeholder. Check GPU and destination alpha filtering; a geometry-flat CPU view cannot establish the cutout silhouette."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Material portability depends on supported glTF properties and the selected exporter; renderer appearance is not a portability guarantee."+ ],+ "semantics": [+ "No asset category or whole-asset acceptance is inferred from this operation."+ ],+ "cost": "Material creation itself is small; texture resolution and mesh usage determine memory/draw costs.",+ "example": "const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\nconst mat = foliageMaterial(albedo, { alphaCutoff: 0.5, doubleSided: true });"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:countTriangles",+ "name": "countTriangles",+ "summary": "Sums placed mesh triangles across the subtree, including active InstancedMesh copies and two triangles per sprite. Not draw calls or visible-frame cost.",+ "family": "utility",+ "tags": [+ "utility",+ "metrics",+ "triangles"+ ],+ "aliases": [+ "triangle count"+ ],+ "intents": [+ "measure geometry complexity"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [],+ "kind": "operation",+ "contract": {+ "signature": "countTriangles(root: Object3D)",+ "returns": "number",+ "units": "Counts, not physical units.",+ "axes": "No axis convention required.",+ "origin": "Does not reposition the input.",+ "execution": "sync",+ "ownership": "Read-only traversal; returns counts or names.",+ "coordinates": "Inspects the supplied subtree.",+ "parameters": [+ "An Object3D root; results describe that subtree, not a renderer frame."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not mutate geometry, materials or hierarchy."+ ],+ "semantics": [+ "Counts placed mesh triangles, multiplying active InstancedMesh count, and each sprite as two triangles. Ignores visibility/culling, drawRange and material groups; finalized GLB metrics describe exported primitives separately.",+ "Not an acceptance threshold, visible-frame count, draw-call count or GPU timing."+ ],+ "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",+ "example": "meta.tris = countTriangles(root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:countMaterials",+ "name": "countMaterials",+ "summary": "Unique material count (by reference) across the subtree.",+ "family": "utility",+ "tags": [+ "utility",+ "metrics",+ "materials"+ ],+ "aliases": [+ "material count"+ ],+ "intents": [+ "measure material reference diversity"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Several meshes sharing one material can still require several draw calls."+ ],+ "kind": "operation",+ "contract": {+ "signature": "countMaterials(root: Object3D)",+ "returns": "number",+ "units": "Counts, not physical units.",+ "axes": "No axis convention required.",+ "origin": "Does not reposition the input.",+ "execution": "sync",+ "ownership": "Read-only traversal; returns counts or names.",+ "coordinates": "Inspects the supplied subtree.",+ "parameters": [+ "An Object3D root; results describe that subtree, not a renderer frame."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not mutate geometry, materials or hierarchy."+ ],+ "semantics": [+ "Counts unique material object references; not draw calls, texture memory or material equivalence."+ ],+ "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",+ "example": "const mats = countMaterials(root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "operation:getJointNames",+ "name": "getJointNames",+ "summary": "All node names beginning with `Joint_`. Use to sanity-check animation targets.",+ "family": "utility",+ "tags": [+ "utility",+ "inspection",+ "rig",+ "names"+ ],+ "aliases": [+ "joint names"+ ],+ "intents": [+ "list named animation pivots"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:describeAssembly",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts"+ ],+ "limitations": [+ "Prefix lookup is not body-plan or skeleton validation. Use describeAssembly(root).joints for semantic joint-chain, wheel-spin and steering nodes, independent of names."+ ],+ "kind": "operation",+ "contract": {+ "signature": "getJointNames(root: Object3D)",+ "returns": "string[]",+ "units": "Counts, not physical units.",+ "axes": "No axis convention required.",+ "origin": "Does not reposition the input.",+ "execution": "sync",+ "ownership": "Read-only traversal; returns counts or names.",+ "coordinates": "Inspects the supplied subtree.",+ "parameters": [+ "An Object3D root; results describe that subtree, not a renderer frame."+ ],+ "topology": [+ "Not a mesh-producing operation; no manifold or watertightness claim."+ ],+ "preservation": [+ "Does not mutate geometry, materials or hierarchy."+ ],+ "semantics": [+ "Returns names beginning Joint_; does not discover every semantic pivot or validate a rig graph."+ ],+ "cost": "Linear traversal over the scene subtree and relevant mesh/material records.",+ "example": "const joints = getJointNames(root);"+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-bark-v1",+ "name": "Bark material baseline",+ "summary": "Rough, nonmetal tree bark with optional approved albedo and normal resources. Call await materialRecipe(\"kiln.material.bark.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "bark"+ ],+ "aliases": [+ "tree trunk",+ "woody stem"+ ],+ "intents": [+ "apply bark appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.bark.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"BarkSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.bark.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.14702726649759498,0.05780543019106723,0.019382360956935723,1],\"metallicFactor\":0,\"roughnessFactor\":0.93,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-leaf-v1",+ "name": "Leaf material baseline",+ "summary": "Alpha-tested, double-sided foliage using glTF MASK rather than blending. Call await materialRecipe(\"kiln.material.leaf.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "leaf"+ ],+ "aliases": [+ "foliage",+ "leaves",+ "alpha cutout"+ ],+ "intents": [+ "apply leaf appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",+ "MASK mode alone does not create a cutout. Supply alpha data and UVs for shaped leaf cards."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.leaf.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"LeafSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.leaf.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, alphaCutoff, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.04970656598412723,0.21223075741405523,0.042311410620809675,1],\"metallicFactor\":0,\"roughnessFactor\":0.86,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"MASK\",\"doubleSided\":true,\"textureResources\":{},\"alphaCutoff\":0.5}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-wood-v1",+ "name": "Wood material baseline",+ "summary": "Portable nonmetal wood with a warm authored base color. Call await materialRecipe(\"kiln.material.wood.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "wood"+ ],+ "aliases": [+ "wooden",+ "timber",+ "grain",+ "plank"+ ],+ "intents": [+ "apply wood appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.wood.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"WoodSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.wood.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.32314320911295075,0.14412847085805777,0.042311410620809675,1],\"metallicFactor\":0,\"roughnessFactor\":0.78,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-stone-v1",+ "name": "Stone material baseline",+ "summary": "Dry rough stone with no runtime shader dependency. Call await materialRecipe(\"kiln.material.stone.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "stone"+ ],+ "aliases": [+ "rock",+ "masonry",+ "mineral"+ ],+ "intents": [+ "apply stone appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.stone.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"StoneSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.stone.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.20507873639031693,0.19461783044157582,0.17464740365558504,1],\"metallicFactor\":0,\"roughnessFactor\":0.95,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-rubber-v1",+ "name": "Rubber material baseline",+ "summary": "Dark, high-roughness rubber for tires, grips, and seals. Call await materialRecipe(\"kiln.material.rubber.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "rubber"+ ],+ "aliases": [+ "tire",+ "tyre",+ "grip",+ "seal"+ ],+ "intents": [+ "apply rubber appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.rubber.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"RubberSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.rubber.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.014443843596092545,0.01520851442291271,0.017641954488384078,1],\"metallicFactor\":0,\"roughnessFactor\":0.88,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-painted-metal-v1",+ "name": "Painted metal material baseline",+ "summary": "Coated metal with restrained metallic response and a durable painted finish. Call await materialRecipe(\"kiln.material.painted-metal.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "painted-metal"+ ],+ "aliases": [+ "paint",+ "coating",+ "vehicle panel",+ "cast iron",+ "steel"+ ],+ "intents": [+ "apply painted metal appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.painted-metal.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"Painted metalSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.painted-metal.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.45078578283822346,0.042311410620809675,0.03189603307301153,1],\"metallicFactor\":0.18,\"roughnessFactor\":0.38,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-cloth-v1",+ "name": "Cloth material baseline",+ "summary": "Very rough, nonmetal woven cloth represented with core glTF PBR. Call await materialRecipe(\"kiln.material.cloth.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "cloth"+ ],+ "aliases": [+ "fabric",+ "woven",+ "textile"+ ],+ "intents": [+ "apply cloth appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.cloth.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"ClothSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.cloth.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, metalness, doubleSided, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.1589608350608804,0.17788841598362914,0.22696587351009836,1],\"metallicFactor\":0,\"roughnessFactor\":1,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-skin-v1",+ "name": "Skin material baseline",+ "summary": "Portable skin baseline without nonstandard subsurface extensions. Call await materialRecipe(\"kiln.material.skin.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "skin"+ ],+ "aliases": [+ "flesh",+ "organic surface"+ ],+ "intents": [+ "apply skin appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",+ "This baseline has no subsurface scattering."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.skin.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"SkinSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.skin.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, doubleSided. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.4793201831008268,0.1912016827407914,0.12213877222960187,1],\"metallicFactor\":0,\"roughnessFactor\":0.62,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-glass-v1",+ "name": "Glass material baseline",+ "summary": "Portable alpha-blended glass fallback using core glTF fields only. Call await materialRecipe(\"kiln.material.glass.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "glass"+ ],+ "aliases": [+ "transparent",+ "window",+ "translucent"+ ],+ "intents": [+ "apply glass appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",+ "Core glTF BLEND approximates transparency; this is not refraction or physical transmission. Sorting depends on the destination renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.glass.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"GlassSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.glass.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, opacity, doubleSided. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.39675523072562685,0.6866853124353134,0.8069522576692516,0.32],\"metallicFactor\":0,\"roughnessFactor\":0.12,\"emissiveFactor\":[0,0,0],\"alphaMode\":\"BLEND\",\"doubleSided\":true,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:material-emissive-v1",+ "name": "Emissive material baseline",+ "summary": "Core glTF emissive material with intensity baked into emissiveFactor. Call await materialRecipe(\"kiln.material.emissive.v1\"). Optional editable surface recipe; the example is a material swatch, not a finished asset.",+ "family": "materials",+ "tags": [+ "material",+ "pbr",+ "surface",+ "emissive"+ ],+ "aliases": [+ "glowing",+ "lamp",+ "light source"+ ],+ "intents": [+ "apply emissive appearance to any asset"+ ],+ "stability": "stable",+ "related": [+ {+ "id": "operation:materialRecipe",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Defaults contain no texture resources or geometric detail. Material naming alone does not establish realism.",+ "Uses core glTF metallic-roughness fields; visually check the actual destination importer and renderer.",+ "Emissive color does not create a scene light or guarantee bloom in the destination renderer."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:materialRecipe",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Await materialRecipe(\"kiln.material.emissive.v1\") in async build().",+ "Attach the returned material to the intended parts; reuse or create separate instances according to required surface variation.",+ "Render the exported asset and inspect material fidelity before finishing."+ ],+ "example": "const meta = { name: \"EmissiveSwatch\" };\nasync function build() {\n const root = createRoot(meta.name);\n const surface = await materialRecipe(\"kiln.material.emissive.v1\");\n createPart('Swatch', sphereGeo(0.5), surface, { parent: root, position: [0, 0.5, 0] });\n return root;\n}",+ "adaptations": [+ "Allowed overrides: baseColor, roughness, doubleSided, emissiveColor, emissiveIntensity, textureResources. Pass them as the second materialRecipe argument.",+ "Baseline portable fields: {\"baseColorFactor\":[0.042311410620809675,0.017641954488384078,0.005181516702338386,1],\"metallicFactor\":0,\"roughnessFactor\":0.5,\"emissiveFactor\":[1,0.25415209433082675,0.01599629336550963],\"alphaMode\":\"OPAQUE\",\"doubleSided\":false,\"textureResources\":{}}. These are starting values, not asset requirements.",+ "If using textures, retrieve the current approved resources and helper contract; author UVs and inspect texture scale on the intended geometry."+ ],+ "checks": [+ "Inspect glTF material fields and texture bindings in the exported artifact.",+ "Use a PBR-capable view and check viewFidelity; geometry-flat CPU views cannot establish material appearance.",+ "Check silhouette and dimensions separately from surface appearance."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-biped-v1",+ "name": "biped rig guidance",+ "summary": "Optional biped semantic rig preset graph. The supplied graph has hips, spine, head, paired arm chains and paired leg chains. Adapt the rest offsets and contact roles to the intended proportions.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "biped"+ ],+ "aliases": [+ "two legged",+ "humanoid",+ "person",+ "robot"+ ],+ "intents": [+ "articulate a biped asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "The preset supplies semantic joints only, not anatomy, skinning or finished asset geometry.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "The supplied graph has hips, spine, head, paired arm chains and paired leg chains. Adapt the rest offsets and contact roles to the intended proportions.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"bipedRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"hips\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"pelvis\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"spine\",\"parentRole\":\"hips\",\"offset\":[0,0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"torso\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"head\",\"parentRole\":\"spine\",\"offset\":[0,0.55,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"shoulder.left\",\"parentRole\":\"spine\",\"offset\":[0,0.3,-0.25],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.left\",\"parentRole\":\"shoulder.left\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wrist.left\",\"parentRole\":\"elbow.left\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"hand.left\",\"grip.left\"],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false},{\"role\":\"shoulder.right\",\"parentRole\":\"spine\",\"offset\":[0,0.3,0.25],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.right\",\"parentRole\":\"shoulder.right\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wrist.right\",\"parentRole\":\"elbow.right\",\"offset\":[0,-0.35,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"hand.right\",\"grip.right\"],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false},{\"role\":\"hip.left\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,-0.14],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.left\",\"parentRole\":\"hip.left\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"ankle.left\",\"parentRole\":\"knee.left\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"foot.left\"],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.right\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,0.14],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.right\",\"parentRole\":\"hip.right\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"ankle.right\",\"parentRole\":\"knee.right\",\"offset\":[0,-0.45,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"foot.right\"],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"biped\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-quadruped-v1",+ "name": "quadruped rig guidance",+ "summary": "Optional quadruped semantic rig preset graph. The supplied graph has an axial hips/spine/neck/head chain and four leg chains. Adapt limb lengths and paw contacts to the creature.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "quadruped"+ ],+ "aliases": [+ "four legged creature",+ "animal",+ "dog",+ "horse"+ ],+ "intents": [+ "articulate a quadruped asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "The preset supplies semantic joints only, not anatomy, skinning or finished asset geometry.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "The supplied graph has an axial hips/spine/neck/head chain and four leg chains. Adapt limb lengths and paw contacts to the creature.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"quadrupedRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"hips\",\"offset\":[0,0.8,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[\"pelvis\"],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"spine\",\"parentRole\":\"hips\",\"offset\":[0.7,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"neck\",\"parentRole\":\"spine\",\"offset\":[0.45,0.1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"head\",\"parentRole\":\"neck\",\"offset\":[0.3,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"shoulder.fore.left\",\"parentRole\":\"spine\",\"offset\":[0.2,-0.1,-0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.fore.left\",\"parentRole\":\"shoulder.fore.left\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.fore.left\",\"parentRole\":\"elbow.fore.left\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"shoulder.fore.right\",\"parentRole\":\"spine\",\"offset\":[0.2,-0.1,0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"elbow.fore.right\",\"parentRole\":\"shoulder.fore.right\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.fore.right\",\"parentRole\":\"elbow.fore.right\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.hind.left\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,-0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.hind.left\",\"parentRole\":\"hip.hind.left\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.hind.left\",\"parentRole\":\"knee.hind.left\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"left\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true},{\"role\":\"hip.hind.right\",\"parentRole\":\"hips\",\"offset\":[0,-0.1,0.28],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"knee.hind.right\",\"parentRole\":\"hip.hind.right\",\"offset\":[0,-0.4,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"paw.hind.right\",\"parentRole\":\"knee.hind.right\",\"offset\":[0,-0.3,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"right\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":true}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"quadruped\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-avian-v1",+ "name": "avian rig guidance",+ "summary": "Optional avian semantic rig guidance with a partial scaffold. Extend the example torso/wing branch with an axial neck/head graph, paired wing chains and any requested leg/contact chains.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "avian"+ ],+ "aliases": [+ "bird",+ "wings",+ "winged creature"+ ],+ "intents": [+ "articulate a avian asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Extend the example torso/wing branch with an axial neck/head graph, paired wing chains and any requested leg/contact chains.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"avianRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"wing.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"avian\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-serpentine-v1",+ "name": "serpentine rig guidance",+ "summary": "Optional serpentine semantic rig guidance with a partial scaffold. Extend the continuous axial chain with explicit bend axes and requested contact nodes; no limb graph is implied.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "serpentine"+ ],+ "aliases": [+ "snake",+ "tail",+ "worm",+ "axial chain"+ ],+ "intents": [+ "articulate a serpentine asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Extend the continuous axial chain with explicit bend axes and requested contact nodes; no limb graph is implied.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"serpentineRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"tail.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"serpentine\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-multi-limb-v1",+ "name": "multi-limb rig guidance",+ "summary": "Optional multi-limb semantic rig guidance with a partial scaffold. Expand each requested branch with distinct semantic roles, explicit parent edges and contact/end-effector labels.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "multi-limb"+ ],+ "aliases": [+ "many legs",+ "spider",+ "branched tentacles"+ ],+ "intents": [+ "articulate a multi-limb asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Expand each requested branch with distinct semantic roles, explicit parent edges and contact/end-effector labels.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"multi-limbRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"multi-limb\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-wheeled-v1",+ "name": "wheeled rig guidance",+ "summary": "Optional wheeled semantic rig guidance with a partial scaffold. Build the character core and articulated appendages as distinct roles; discover wheel assemblies separately for wheel geometry and locomotion.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "wheeled"+ ],+ "aliases": [+ "wheeled robot",+ "mobile character"+ ],+ "intents": [+ "articulate a wheeled asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Build the character core and articulated appendages as distinct roles; discover wheel assemblies separately for wheel geometry and locomotion.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"wheeledRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"wheeled\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:rig-custom-v1",+ "name": "custom rig guidance",+ "summary": "Optional custom semantic rig guidance with a partial scaffold. Design the graph for the brief, preserving explicit parent edges and local frames without inheriting a different body plan.",+ "family": "rigs",+ "tags": [+ "rig",+ "skeleton",+ "joint",+ "custom"+ ],+ "aliases": [+ "custom skeleton",+ "unusual creature",+ "articulated mechanism"+ ],+ "intents": [+ "articulate a custom asset",+ "attach geometry to semantic joint pivots"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Only a two-node teaching scaffold is supplied. This is not a complete body-plan preset.",+ "No clips, inverse kinematics, gait or contact solver are generated. Visual and motion qualification are separate.",+ "Selecting a recipe does not create or change host requirements. Joint graph metadata is descriptive evidence, not policy."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Design the graph for the brief, preserving explicit parent edges and local frames without inheriting a different body plan.",+ "Create parents before children with unique roles; attach each chain under the actual parent node and retain its parentRole.",+ "Attach asset geometry to the intended pivots and declare the collected descriptors in root.userData.kilnCharacterRig.",+ "Add requested clips targeting unique Joint_* node names, then render and inspect rest and animated poses."+ ],+ "example": "const meta = { name: \"customRigScaffold\" };\nfunction build() {\n const root = createRoot(meta.name);\n const specs = [{\"role\":\"core\",\"offset\":[0,1,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":false,\"contact\":false},{\"role\":\"appendage.tip\",\"parentRole\":\"core\",\"offset\":[0.5,0,0],\"restRotation\":[0,0,0,1],\"restScale\":[1,1,1],\"aliases\":[],\"side\":\"center\",\"localForwardAxis\":[1,0,0],\"localBendAxis\":[0,0,1],\"endEffector\":true,\"contact\":false}];\n const nodes = new Map();\n const descriptors = [];\n for (const spec of specs) {\n const chain = createJointChain('Scaffold', [spec], {\n parent: spec.parentRole ? nodes.get(spec.parentRole) : root,\n parentRole: spec.parentRole\n });\n nodes.set(spec.role, chain.root);\n descriptors.push(...chain.descriptors);\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: \"custom\", joints: descriptors };\n // A visible marker only. Attach the actual asset geometry to its intended joints.\n createPart('CoreMarker', boxGeo(0.25, 0.25, 0.25), gameMaterial('#718096'), { parent: nodes.get(specs[0].role) });\n return root;\n}",+ "adaptations": [+ "Offsets and transforms are parent-local. Update rest offsets, frames, geometry and contact positions together when changing proportions.",+ "Combine rigs, structures, surfaces and mechanisms freely; a body-plan label does not select an asset category.",+ "Contact roles must match the intended ground plane. Adapt the sample +X forward and +Y up conventions explicitly if the host requires a different frame."+ ],+ "checks": [+ "Verify every graph role resolves to exactly one node and each parentRole matches the actual hierarchy.",+ "Check GLB joint extras and animation targets after export; source metadata alone is insufficient.",+ "Review contact, attachment, silhouette and motion views. Structural QA does not establish a natural gait or skin deformation."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:joined-frame-v1",+ "name": "Braced frame from shared attachment points",+ "summary": "Keep both ends of braces attached after resizing a frame by deriving them from the same post endpoints. Separate intended joints from surfaces that must remain apart; adapt to supports, furniture, chassis or scaffolding.",+ "family": "structure",+ "tags": [+ "brace",+ "frame",+ "attachment",+ "junction",+ "clearance",+ "resize"+ ],+ "aliases": [+ "floating support bars",+ "disconnected struts",+ "joined beams",+ "bench frame",+ "table legs and rails",+ "chair or stool frame"+ ],+ "intents": [+ "connect both ends of a support",+ "resize a frame without detached braces"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:beamBetween",+ "relation": "prerequisite"+ },+ {+ "id": "recipe:editable-assembly-v1",+ "relation": "companion"+ }+ ],+ "references": [+ "skills/kiln-refine-asset/references/revision-and-views.md"+ ],+ "limitations": [+ "Centerline joints intentionally overlap. This is neither a Boolean union nor a welded, load-bearing or manufacturing certificate.",+ "The interpolation below describes straight posts in one local frame. Curved or transformed neighbors need attachment points derived from their actual geometry and frames.",+ "A connected-component report can pass when only one end touches. Inspect each intended pair separately; zero unsigned surface distance can mean intersection."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:createRoot",+ "operation:createPart",+ "operation:beamBetween"+ ],+ "steps": [+ "Choose the assembly frame and derive support endpoints from shared dimensions. Identify which interfaces must meet and which must have clearance.",+ "Derive brace endpoints along those same supports instead of entering unrelated coordinates. Rebuild dependent members when dimensions change.",+ "Inspect each brace against each intended post. Then check its clearance from the deck; contact at a required joint must not substitute for clearance elsewhere."+ ],+ "example": "const meta = { name: 'BracedFrame' };\nconst span = 1.2;\nconst height = 0.8;\nconst depth = 0.45;\nconst radius = 0.025;\nfunction build() {\n const root = createRoot(meta.name);\n const steel = gameMaterial('#637987');\n const along = (a, b, t) => a.map((v, i) => v + (b[i] - v) * t);\n for (const [side, z] of [['Near', -depth / 2], ['Far', depth / 2]]) {\n const a0 = [-span / 2, 0, z], a1 = [-span / 2, height, z];\n const b0 = [span / 2, 0, z], b1 = [span / 2, height, z];\n beamBetween(side + 'PostA', a0, a1, radius, steel, { parent: root });\n beamBetween(side + 'PostB', b0, b1, radius, steel, { parent: root });\n beamBetween(side + 'Rail', a1, b1, radius, steel, { parent: root });\n beamBetween(side + 'Brace', along(a0, a1, 0.25), along(b0, b1, 0.75),\n radius, steel, { parent: root });\n }\n const thickness = 0.06;\n createPart('Deck', boxGeo(span + 0.1, thickness, depth + 0.1), gameMaterial('#947653'),\n { parent: root, position: [0, height + radius + thickness / 2, 0] });\n return root;\n}",+ "adaptations": [+ "Change span or height and rebuild. Keep tube thickness independent; scaling the assembly would also scale thickness and clearances.",+ "For a removable connector, give it a local root at the attachment point. For a gap or bearing, derive the separation explicitly instead of overlapping parts."+ ],+ "checks": [+ "Measure each Near/FarBrace against both corresponding PostA and PostB surfaces with kiln_inspect measure.mode=surface. Inspect those joints in context.",+ "Check each rail against the deck underside and each brace against the deck separately. The latter should have positive separation; a whole-frame minimum can hide the wrong connection.",+ "After edits, compare exported bounds and protected components. A rendered image or connected graph alone does not establish all required joints."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:editable-assembly-v1",+ "name": "Editable multipart assembly",+ "summary": "Group a replaceable support under a real root, repeat its full hierarchy, then replace one bracket in its local frame while retaining the post and base. Adapt the same pattern to bays, wheels or mechanisms.",+ "family": "structure",+ "tags": [+ "assembly",+ "replacement",+ "hierarchy",+ "reuse",+ "local frame"+ ],+ "aliases": [+ "replaceable multipart support",+ "coherent parts",+ "group components",+ "swap bracket"+ ],+ "intents": [+ "move or replace an assembly together",+ "edit one repeated component independently"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:describeAssembly",+ "relation": "prerequisite"+ },+ {+ "id": "operation:replicateAssembly",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/assembly.ts",+ "skills/kiln-author-asset/references/geometry-recipes.md"+ ],+ "limitations": [+ "A common name prefix does not create a shared transform or replacement root. The actual parent-child hierarchy must carry the assembly.",+ "Replication does not solve attachment, clearances or load-bearing contact. Check the new component against its neighbors.",+ "This static example has no animation or external references. Animated replacements must preserve or explicitly retarget tracks, joint roles and rest frames."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:createRoot",+ "operation:createPart",+ "operation:describeAssembly",+ "operation:replicateAssembly"+ ],+ "steps": [+ "Create a static root at the support placement datum. Parent every support component beneath it and author child dimensions in that local frame.",+ "Give the replaceable bracket its own root at the connection datum. Retain that root when changing bracket geometry.",+ "Replicate describeAssembly(support.root) with an explicit unique namespace; use nodeMap for the copied bracket instead of guessing a renamed path.",+ "Move or rotate the support root. Replace only the bracket children, then inspect exported parents, unchanged parts and contact views."+ ],+ "example": "const meta = { name: 'EditableSupports' };\nconst replaceSecond = false;\nfunction build() {\n const root = createRoot(meta.name);\n const metal = gameMaterial('#637987');\n function bracketParts(bracket, style, prefix) {\n if (style === 'fork') {\n for (const side of [-1, 1]) createPart(prefix + 'Arm' + side,\n boxGeo(0.04, 0.18, 0.10), metal,\n { parent: bracket, position: [side * 0.055, 0.07, 0], rotation: [0, 0, -side * 35] });\n } else createPart(prefix + 'Saddle', boxGeo(0.30, 0.04, 0.18), metal, { parent: bracket });\n }\n function makeSupport(name, height) {\n const support = createRoot(name);\n root.add(support);\n createPart('Base', boxGeo(0.30, 0.04, 0.30), metal,\n { parent: support, position: [0, 0.02, 0] });\n createPart('Post', boxGeo(0.06, height, 0.06), metal,\n { parent: support, position: [0, height / 2, 0] });\n const bracket = createRoot('Bracket');\n bracket.position.y = height;\n support.add(bracket);\n bracketParts(bracket, 'saddle', '');\n return { root: support, bracket };\n }\n const support = makeSupport('Support', 0.8);\n support.root.position.x = -0.6;\n const second = replicateAssembly(describeAssembly(support.root),\n { namespace: 'second', parent: root });\n second.root.position.x = 0.6;\n second.root.rotation.y = Math.PI / 6; // Object3D rotations use radians.\n if (replaceSecond) {\n const bracket = second.nodeMap.get(support.bracket);\n bracket.clear(); // Retain the attachment root and its local transform.\n bracketParts(bracket, 'fork', 'second__');\n }\n return root;\n}",+ "adaptations": [+ "Set replaceSecond=true for the local bracket replacement. A different bracket height may require moving the connection datum or its neighbor; do not silently stretch the post.",+ "Use ordinary factories for parametric variants and replicateAssembly for a repeated hierarchy. Geometry/materials default to shared; request copy or clone before independently mutating resources.",+ "Flat hierarchies remain valid for independent parts. Add assembly roots when shared placement, articulation or replacement is requested."+ ],+ "checks": [+ "Verify each exported assembly root contains its intended components and each replacement has the intended local transform.",+ "Compare retained geometry, world transforms, materials and animation targets across the edit; test rotated placements as well as the original.",+ "Inspect the connection in context. Names and axis-aligned bounds alone do not prove physical contact."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:surface-detail-v1",+ "name": "Attached raised surface detail",+ "summary": "Create a raised strip whose boundary reuses the actual sampled carrier vertices. Optional starting point for a vein, rib, seam or embossed panel, with shared coordinates and independent materials.",+ "family": "geometry",+ "tags": [+ "surface",+ "attachment",+ "vein",+ "rib",+ "seam",+ "custom geometry"+ ],+ "aliases": [+ "attached raised vein seam",+ "detail follows curved surface",+ "organic surface rib"+ ],+ "intents": [+ "keep detail attached after a shape edit",+ "avoid floating surface decoration"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:parametricSurface",+ "relation": "prerequisite"+ },+ {+ "id": "operation:meshGeo",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/geometry.ts",+ "skills/kiln-author-asset/references/geometry-recipes.md"+ ],+ "limitations": [+ "This is an open carrier sheet and an attached raised strip, not a watertight solid, Boolean union or general attachment solver.",+ "The strip follows a grid-aligned UV band. Arbitrary branches require splitting carrier faces at their boundaries or another explicitly checked attachment construction.",+ "Offsets follow sampled vertex normals; extreme curvature, coarse tessellation or excessive height can produce intersections. Coincident boundaries are intentional; inspect shading and the actual destination."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:parametricSurface",+ "operation:meshGeo",+ "operation:createPart"+ ],+ "steps": [+ "Build the carrier once. Derive the detail from its position, normal, UV and index buffers in the same local frame.",+ "Select complete carrier triangles in a narrow UV band; reuse their topology and boundary positions.",+ "Raise interior vertices along carrier normals, tapering to zero at the entire boundary. Rebuild both meshes from shared dimensions after a shape edit.",+ "Inspect exported boundary contact and overall dimensions, then review the detail in context from the side and underside."+ ],+ "example": "const meta = { name: 'AttachedSurfaceDetail' };\nconst width = 0.8;\nfunction build() {\n const root = createRoot(meta.name);\n const carrier = parametricSurface((u, v) => [\n width * (u - 0.5) * (0.5 + 0.5 * Math.sin(Math.PI * v)),\n 1.2 * v,\n 0.12 * Math.sin(Math.PI * v) + 0.04 * Math.sin(Math.PI * u)\n ], { uSegments: 32, vSegments: 32 });\n createPart('Carrier', carrier, gameMaterial('#47785a'), { parent: root });\n const p = carrier.getAttribute('position'), n = carrier.getAttribute('normal');\n const uv = carrier.getAttribute('uv'), index = carrier.getIndex();\n const lo = 15 / 32, hi = 17 / 32;\n const positions = [], uvs = [], indices = [], remap = new Map();\n function vertex(original) {\n if (remap.has(original)) return remap.get(original);\n const u = uv.getX(original), v = uv.getY(original);\n const boundary = u === lo || u === hi || v === 0 || v === 1;\n const lift = boundary ? 0 : 0.015 * Math.sin(Math.PI * (u - lo) / (hi - lo)) * Math.sin(Math.PI * v);\n const result = positions.length / 3;\n positions.push(p.getX(original) + n.getX(original) * lift,\n p.getY(original) + n.getY(original) * lift,\n p.getZ(original) + n.getZ(original) * lift);\n uvs.push(u, v);\n remap.set(original, result);\n return result;\n }\n for (let t = 0; t < index.count; t += 3) {\n const face = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];\n if (face.every(i => uv.getX(i) >= lo && uv.getX(i) <= hi)) indices.push(...face.map(vertex));\n }\n createPart('RaisedDetail', meshGeo({ positions, indices, uvs }), gameMaterial('#a5bd79'), { parent: root });\n return root;\n}",+ "adaptations": [+ "Change width or the carrier equation to reshape both surfaces together. Keep band limits on sampled UV columns, or split triangles where the new boundary crosses them.",+ "For fine detail without geometric relief, use an authored texture or normal map with matching UVs. For rounded tubes, check their swept cross-sections against the actual surface instead of assuming shared control points prove contact.",+ "Choose tessellation and detail height for the intended scale. Local normal offsets can change any dimension; measure the final asset when a brief requires a fixed envelope."+ ],+ "checks": [+ "Verify the exported strip boundary coincides with the carrier and the strip rises on the intended side; matching equations alone are insufficient.",+ "After edits, compare unchanged regions, dimensions and boundary contact separately from silhouette and shading.",+ "A close view with neighboring surfaces retained should expose gaps, clipping or z-fighting. Structural QA alone does not establish continuous attachment."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:foliage-cutout-v1",+ "name": "Alpha-bearing foliage card",+ "summary": "Bind an approved alpha-bearing albedo to a UV-mapped card with foliageMaterial. An executable cutout teaching fixture; adapt the card shape, placement and approved resource to the asset.",+ "family": "materials",+ "tags": [+ "foliage",+ "alpha",+ "cutout",+ "card",+ "UV",+ "double sided"+ ],+ "aliases": [+ "leaf mask",+ "transparent leaf silhouette",+ "plant billboard"+ ],+ "intents": [+ "make a leaf card with a cutout silhouette",+ "bind alpha to foliage"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:foliageCardGeo",+ "relation": "prerequisite"+ },+ {+ "id": "operation:foliageMaterial",+ "relation": "prerequisite"+ },+ {+ "id": "operation:loadApprovedTexture",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/material-recipes.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "The bundled leaf-mask resource is a 4 by 4 placeholder. It demonstrates alpha delivery, not production foliage detail or a photorealistic leaf.",+ "MASK alone does not cut out an opaque texture. The albedo must contain alpha and the mesh must provide matching UVs.",+ "A card has no physical thickness. Double-sided rendering does not make a solid; destination filtering, mipmaps, shadows and alpha cutoff can change the silhouette.",+ "Raw THREE.DataTexture construction is not an authoring-sandbox route. Use an approved resource available in the current host; do not mutate resource pixels or provenance."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:loadApprovedTexture",+ "operation:foliageCardGeo",+ "operation:foliageMaterial"+ ],+ "steps": [+ "Check material capabilities for an approved alpha-bearing albedo, its availability, license and quality. The example uses the embedded teaching resource.",+ "Await loadApprovedTexture in async build, pass it to foliageMaterial, and bind the material to a card with UVs.",+ "Place cards with ordinary local roots and transforms. Add stems or geometric leaves only when the brief needs them; a billboard construction is optional.",+ "Inspect GPU views from both sides and at the intended distance. Check the exported alphaMode, cutoff, doubleSided, UVs and embedded texture in the destination."+ ],+ "example": "const meta = { name: 'FoliageCutoutTeachingCard' };\nasync function build() {\n const root = createRoot(meta.name);\n // Embedded 4x4 placeholder: replace with a suitable approved resource for delivery.\n const albedo = await loadApprovedTexture('kiln.texture.leaf-mask-albedo.v1');\n const leaf = foliageMaterial(albedo, { alphaCutoff: 0.5, roughness: 0.85, doubleSided: true });\n createPart('LeafCard', foliageCardGeo({ width: 0.6, height: 1, yPivot: 0 }), leaf, { parent: root });\n return root;\n}",+ "adaptations": [+ "Change width, height and yPivot to match placement. For bent cards, preserve UVs when deforming the geometry and inspect the back face.",+ "A custom solid leaf or sampled surface is equally valid. Discover surface geometry and attached detail when a card is inappropriate.",+ "Replace the resource ID only with a host-approved resource that actually has alpha. Change cutoff deliberately and compare the final silhouette, not just the rectangular card bounds."+ ],+ "checks": [+ "A geometry-flat CPU view can confirm placement, but cannot establish the alpha-cut silhouette or material fidelity. Inspect viewFidelity and a GPU image.",+ "Reimport the GLB and verify both transparent and opaque texture samples survive. A nonempty texture binding alone is insufficient.",+ "Review the actual destination at near and far distances for edge loss, halos, backfaces and shadow behavior. Do not present the placeholder as final foliage."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:directional-sweep-v1",+ "name": "Directional texture on a curved sweep",+ "summary": "Use the sweep UVs to keep lengthwise stripes aligned through a bend. A diagnostic pattern for rails, stems, hoses or beams; adapt the material without replacing meaningful UVs with an arbitrarily rotated atlas.",+ "family": "materials",+ "tags": [+ "UV",+ "directional",+ "sweep",+ "stripes",+ "grain",+ "curved rail"+ ],+ "aliases": [+ "texture follows curve",+ "lengthwise wood grain",+ "striped hose"+ ],+ "intents": [+ "keep texture direction along a curved part",+ "preserve UVs through a path edit"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:sweepProfile",+ "relation": "prerequisite"+ },+ {+ "id": "operation:proceduralTexture",+ "relation": "prerequisite"+ },+ {+ "id": "operation:pbrMaterial",+ "relation": "prerequisite"+ }+ ],+ "references": [+ "src/sweep.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "The example uses a conspicuous diagnostic stripe pattern, not realistic wood grain. Material appearance needs GPU and destination review.",+ "Sweep side U follows the profile perimeter and V follows normalized path distance. End caps have separate planar UVs and need distinct treatment for convincing end grain.",+ "Normalized path UVs stretch with path length. Use an explicit repeat/UV scale tied to measured dimensions when physical texture scale must remain constant.",+ "Sweep frames and caps do not prove absence of self-intersection. Keep profile size appropriate to curvature and inspect tight bends and seams."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:sweepProfile",+ "operation:proceduralTexture",+ "operation:pbrMaterial"+ ],+ "steps": [+ "Sample the path at sufficient stations and sweep a simple profile using an explicit up reference.",+ "Keep the generated side UVs: U wraps around the profile; V progresses along path length. Choose a pattern varying across U for stripes that run along V.",+ "Bind the albedo using pbrMaterial. Rebuild from changed path parameters while retaining the intended UV convention.",+ "Inspect both bends, the UV seam and caps with GPU views; reimport and check texture direction in the intended destination."+ ],+ "example": "const meta = { name: 'DirectionalSweepTeachingPattern' };\nconst curveOffset = 0.2;\nfunction build() {\n const root = createRoot(meta.name);\n const profile = Array.from({ length: 16 }, (_, i) => {\n const angle = 2 * Math.PI * i / 16;\n return [0.07 * Math.cos(angle), 0.07 * Math.sin(angle)];\n });\n const path = Array.from({ length: 33 }, (_, i) => {\n const t = i / 32;\n return [1.2 * t, 0.25, curveOffset * Math.sin(2 * Math.PI * t)];\n });\n const albedo = proceduralTexture({ schemaVersion: 2, size: 128, usage: 'albedo',\n layers: [{ op: 'stripes', colorA: 0x8a4b24, colorB: 0xe4bc70, count: 16, angleDeg: 0 }] });\n createPart('CurvedRail', sweepProfile(profile, path, { up: [0, 1, 0] }),\n pbrMaterial({ albedo, roughness: 0.7, metalness: 0 }), { parent: root });\n return root;\n}",+ "adaptations": [+ "Change curveOffset to its negative to mirror the path while preserving length and UV scale; changing length requires a separate texture-density decision.",+ "Replace stripes with a suitable authored or approved directional texture. Match its direction to these UV axes rather than assuming all textures use the same convention.",+ "Use an atlas when you need independent baked surface detail. Its arbitrary chart rotations are a different contract from continuous directional tiling."+ ],+ "checks": [+ "Check the exported TEXCOORD_0 and texture binding, then inspect that stripes follow the path rather than running across it.",+ "Compare UVs, texture bytes and retained parts after a shape edit. GPU appearance and structural dimensions are separate evidence.",+ "Verify the destination preserves texture direction, seams and cap treatment at useful viewing distances; a CPU geometry sheet cannot establish these."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:structural-bays-v1",+ "name": "Editable structural bays and openings",+ "summary": "Compose any number of storeys from independently placed bays with real wall apertures and replaceable recessed glazing. Resize one bay without scaling its neighbors; the example leaves a clear ground-level entry.",+ "family": "structure",+ "tags": [+ "facade",+ "bay",+ "opening",+ "storey",+ "local frame",+ "replacement"+ ],+ "aliases": [+ "stack editable facade bays and openings",+ "multi-level wall",+ "recessed window",+ "modular architecture"+ ],+ "intents": [+ "resize one structural bay",+ "replace window infill independently",+ "build an open facade without a house preset"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:wallWithOpening",+ "relation": "prerequisite"+ },+ {+ "id": "recipe:editable-assembly-v1",+ "relation": "companion"+ }+ ],+ "references": [+ "src/primitives.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "A teaching facade, not a complete building, load-bearing design or navigation certificate. Add floors, access, returns and support only when requested.",+ "The clear entry is intentionally unfilled. Adding doors, plinths, trim or collision meshes can obstruct it; check the finished passage, not just the aperture parameters.",+ "Glazing is a core glTF transparency approximation. Review GPU appearance and the intended destination; this example has no textures or physical refraction."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:wallWithOpening",+ "operation:createRoot",+ "operation:createPart",+ "operation:boxGeo",+ "operation:glassMaterial"+ ],+ "steps": [+ "Choose storey heights and bay widths from the brief. Put placement on each bay root; author its wall and infill in bay-local coordinates.",+ "Use one front-plane datum: this example faces +Z at Z=0, with the wall in -thickness..0. Position glazing and trim relative to that plane once, avoiding a second parent offset.",+ "Create an actual opening, then give its replaceable infill its own root. Keep an entry free of full-width plinths and unrelated decorations.",+ "For a width edit, rebuild affected dimensions and reposition neighboring roots. For an infill swap, retain its root and replace only its children."+ ],+ "example": "const meta = { name: 'StructuralBays' };\nconst centerWidth = 3;\nconst storeys = 6;\nconst replaceCenterFourth = false;\nfunction build() {\n const root = createRoot(meta.name);\n const wallMaterial = gameMaterial('#a87a64');\n const frameMaterial = gameMaterial('#cad0ca');\n const glass = glassMaterial('#83b4c3', { opacity: 0.45 });\n const widths = [2.5, centerWidth, 2.5], height = 3, thickness = 0.3;\n const totalWidth = widths.reduce((sum, width) => sum + width, 0);\n function infill(group, name, width, tall, divided) {\n if (divided) {\n for (const side of [-1, 1]) createPart(name + '_Pane' + side,\n boxGeo((width - 0.12) / 2, tall - 0.08, 0.02), glass,\n { parent: group, position: [side * (width - 0.04) / 4, tall / 2, -0.18] });\n createPart(name + '_Divider', boxGeo(0.04, tall, 0.05), frameMaterial,\n { parent: group, position: [0, tall / 2, -0.16] });\n } else createPart(name + '_Pane', boxGeo(width - 0.08, tall - 0.08, 0.02), glass,\n { parent: group, position: [0, tall / 2, -0.18] });\n }\n for (let level = 1; level <= storeys; level++) {\n const floor = createRoot('Storey_' + level);\n floor.position.y = (level - 1) * height;\n root.add(floor);\n let left = -totalWidth / 2;\n for (let bayIndex = 0; bayIndex < widths.length; bayIndex++) {\n const width = widths[bayIndex], name = 'Bay_' + level + '_' + bayIndex;\n const bay = createRoot(name);\n bay.position.x = left + width / 2;\n floor.add(bay);\n left += width;\n const entry = level === 1 && bayIndex === 1;\n const apertureWidth = entry ? 1.4 : width * 0.5;\n const apertureHeight = entry ? 2.4 : 1.6, sill = entry ? 0 : 0.8;\n const wall = wallWithOpening(name + '_Wall', wallMaterial, {\n length: width, height, thickness, axis: 'x',\n opening: { kind: entry ? 'door' : 'window', width: apertureWidth, height: apertureHeight, sill },\n parent: bay\n });\n wall.position.z = -thickness / 2;\n // Surround is outside the aperture, so the declared entry remains clear.\n for (const side of [-1, 1]) createPart(name + '_Jamb' + side,\n boxGeo(0.08, apertureHeight, 0.12), frameMaterial,\n { parent: bay, position: [side * (apertureWidth / 2 + 0.04), sill + apertureHeight / 2, 0] });\n createPart(name + '_Lintel', boxGeo(apertureWidth + 0.16, 0.08, 0.12), frameMaterial,\n { parent: bay, position: [0, sill + apertureHeight + 0.04, 0] });\n if (!entry) {\n const glazing = createRoot('Glazing_' + level + '_' + bayIndex);\n glazing.position.y = sill;\n bay.add(glazing);\n infill(glazing, name, apertureWidth, apertureHeight, false);\n if (replaceCenterFourth && level === 4 && bayIndex === 1) {\n glazing.clear();\n infill(glazing, name, apertureWidth, apertureHeight, true);\n }\n }\n }\n }\n return root;\n}",+ "adaptations": [+ "Change centerWidth or storeys; there is no category or two-floor restriction. Preserve outer detailing by moving the outer roots rather than scaling the whole facade.",+ "Set replaceCenterFourth=true to swap one infill. For a balcony or roof, use a separate attachment root and an explicit physical interface; check neighbor contact after replacement.",+ "Remove bays or combine this open wall with other structures freely. For repeated identical hierarchies, discover replicateAssembly and its explicit resource/identity policies."+ ],+ "checks": [+ "Measure exported bay widths, storey heights and final passage clearance including trim. A wall opening alone does not prove usable access.",+ "Confirm recessed glazing lies inside the intended wall depth in world space; a parent offset applies to every child.",+ "Compare retained geometry, hierarchy and world transforms after a local swap, including with a rotated/scaled ancestor."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:open-tiered-seating-v1",+ "name": "Open tiered seating sectors",+ "summary": "Build an open arena or amphitheater from separately editable stepped sectors, reserving an entrance before placing geometry. Each sector has a local placement root; no enclosing roof, house layout or floor-count policy is implied.",+ "family": "structure",+ "tags": [+ "arena",+ "amphitheater",+ "seating",+ "tiers",+ "open structure",+ "entrance"+ ],+ "aliases": [+ "open arena tiered seating entrance",+ "coliseum seating",+ "stadium terraces"+ ],+ "intents": [+ "keep a path into an open structure",+ "replace one seating sector",+ "build tiered environment geometry"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "operation:extrudeProfile",+ "relation": "prerequisite"+ },+ {+ "id": "recipe:structural-bays-v1",+ "relation": "companion"+ }+ ],+ "references": [+ "src/profile.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Faceted solid tier blocks are a layout scaffold, not individual seats, a circulation plan, structural engineering or a collision/navigation certificate.",+ "The reserved entrance stays open only if later walls, trim, platforms and collision geometry also respect it. Evaluate the complete asset and requested approach route.",+ "Adjacent sectors meet on matching radial planes; coarse sectors approximate circular arcs with chords. The independent solids are not Boolean-unioned."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "operation:extrudeProfile",+ "operation:createRoot",+ "operation:createPart"+ ],+ "steps": [+ "Reserve an entrance sector before generating tiers. Define inner radius, row depth/rise and the open angular interval explicitly.",+ "Give each seating sector a root at its inner-edge midpoint. Use sector-local profiles so placement is carried by the root instead of baked world coordinates.",+ "Extrude individual tier footprints from ground to their requested top height. Keep sectors and rows separately addressable for edits.",+ "Inspect the exported entrance with all neighboring geometry present, then verify sector seams and unchanged neighbors after a replacement or omission."+ ],+ "example": "const meta = { name: 'OpenTieredSeating' };\nconst omittedSector = -1;\nasync function build() {\n const root = createRoot(meta.name);\n const stone = gameMaterial('#a6947c');\n const innerRadius = 6, rowDepth = 0.8, rowRise = 0.4, rows = 4;\n const sectors = 20, entranceDegrees = 60;\n const span = (360 - entranceDegrees) / sectors;\n const half = span * Math.PI / 360;\n // extrudeProfile(axis:'y') maps profile (u,v) to world-local (X,-Z).\n function point(radius, angle) {\n return [radius * Math.cos(angle) - innerRadius, -radius * Math.sin(angle)];\n }\n for (let sector = 0; sector < sectors; sector++) {\n if (sector === omittedSector) continue;\n const angle = (entranceDegrees / 2 + (sector + 0.5) * span) * Math.PI / 180;\n const group = createRoot('Sector_' + sector);\n group.position.set(innerRadius * Math.cos(angle), 0, innerRadius * Math.sin(angle));\n group.rotation.y = -angle; // Object3D rotation is radians.\n root.add(group);\n for (let row = 0; row < rows; row++) {\n const near = innerRadius + row * rowDepth, far = near + rowDepth;\n const footprint = [point(near, -half), point(far, -half), point(far, half), point(near, half)];\n const geometry = await extrudeProfile(footprint, { axis: 'y', depth: (row + 1) * rowRise, center: false });\n createPart('Sector_' + sector + '_Tier_' + row, geometry, stone, { parent: group });\n }\n }\n return root;\n}",+ "adaptations": [+ "Change rows, rise, radius or the open angle to fit the brief. For a larger arc budget use smaller sectors; do not add floors or a roof unless requested.",+ "Set omittedSector=6 to remove one complete sector while preserving its neighbors. Build replacement geometry beneath that same placement root to retain its interface.",+ "Use createStairs for a straight access flight where needed; seating rise is not automatically a walkable stair or accessibility ramp. Check approach clearance and destination collision separately."+ ],+ "checks": [+ "Trace the approach through the final exported asset near the ground and at the requested clearance height. Decorative or structural additions must not silently close it.",+ "Verify exported sector roots carry placement, tier top heights match requested rise and adjoining radial endpoints agree.",+ "Inspect the inside, outside and underside; independent solids and plausible silhouettes alone do not prove all navigation or material requirements."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:steerable-wheel-v1",+ "name": "Steerable wheel with a local fork",+ "summary": "Compose a wheel, fork and axle around separate steering and spin pivots. Resize from shared dimensions and inspect actual animated geometry; usable as a caster or mechanism without selecting a vehicle category.",+ "family": "articulation",+ "tags": [+ "wheel",+ "caster",+ "steering",+ "spin",+ "local frame",+ "animation"+ ],+ "aliases": [+ "swivel support",+ "steer and spin a caster wheel",+ "rotating wheel fork"+ ],+ "intents": [+ "add an editable rolling support",+ "separate steering from wheel rotation"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createWheelAssembly",+ "relation": "prerequisite"+ },+ {+ "id": "recipe:editable-assembly-v1",+ "relation": "companion"+ }+ ],+ "references": [+ "src/vehicle.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "A teaching assembly, not a suspension, physics model or load certificate. Spin is in place; translation is not synchronized to rolling distance.",+ "The contact marker is a rest-pose reference under the spin pivot. Evaluate actual tire geometry over motion; nominal radius or marker position cannot certify rolling contact.",+ "The host mounting surface is not included. Bind external support relationships when integrating into the host, and check mounting contact and clearance independently."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createWheelAssembly",+ "operation:createRoot",+ "operation:createPart",+ "operation:rotationTrack",+ "operation:createClip"+ ],+ "steps": [+ "Choose the axle datum and dimensions. This example uses +Y up, +Z spin and +Y steering; put the assembly placement on a parent root.",+ "Parent the fork and axle to the steering pivot and the tire, rim, hub and spin marker to the spin pivot. Keep the fork out of wheel rotation.",+ "Derive fork spacing, axle length, clearance and placement from radius and width. Rebuild after a dimension edit rather than scaling hardware thickness.",+ "Use intermediate quaternion keys for a full spin. Export and inspect both clips, sampled tread bounds and fork clearance before attaching a host."+ ],+ "example": "const meta = { name: 'SteerableCaster' };\nconst radius = 0.25;\nconst width = 0.12;\nfunction build() {\n const root = createRoot(meta.name);\n const steel = gameMaterial('#7894a3');\n const wheel = createWheelAssembly('Caster', {\n tire: gameMaterial('#252b30'), rim: steel\n }, { radius, width, side: 'center', index: 'caster', steering: true,\n position: [0, radius, 0], parent: root,\n geometries: { tire: torusGeo(radius - width / 2, width / 2, 12, 64) } });\n const fork = createRoot('Fork');\n wheel.steeringPivot.add(fork);\n const legZ = width / 2 + 0.04, top = radius + 0.10;\n for (const side of [-1, 1]) createPart('ForkLeg' + side,\n boxGeo(0.08, top, 0.04), steel,\n { parent: fork, position: [0, top / 2, side * legZ] });\n createPart('ForkCap', boxGeo(0.10, 0.05, 2 * legZ + 0.04), steel,\n { parent: fork, position: [0, top + 0.025, 0] });\n createPart('Axle', cylinderZGeo(0.025, 0.025, 2 * legZ + 0.06, 20), steel,\n { parent: fork, semantic: { roles: ['axle.caster'] } });\n createPart('SpinMarker', boxGeo(radius * 0.2, 0.015, 0.008), gameMaterial('#edbd54'),\n { parent: wheel.spinPivot, position: [radius * 0.43, 0, width * 0.4 + 0.002] });\n return root;\n}\nfunction animate(root) {\n const steering = root.getObjectByName('SteeringPivot_center_caster');\n const spin = root.getObjectByName('WheelPivot_center_caster');\n return [\n createClip('Steer', 1, [rotationTrack(steering.name, [\n { time: 0, rotation: [0, 0, 0] },\n { time: 0.5, rotation: [0, 40, 0] },\n { time: 1, rotation: [0, 0, 0] }\n ])]),\n createClip('Spin', 1, [rotationTrack(spin.name,\n [0, 90, 180, 270, 360].map((angle, i) => ({ time: i / 4, rotation: [0, 0, angle] })))])\n ];\n}",+ "adaptations": [+ "Use center identity for a wheel on the host centerline. A single-sided fork is an explicit design alternative: preserve the axle-to-hub connection and inspect it; the wheel helper does not choose the support arrangement.",+ "Change radius or width and rebuild. Preserve the declared axle frame when replacing tire geometry; check the helper geometryChecks advisory and actual exported bounds.",+ "Replicate describeAssembly(root, { clips }) with a unique namespace and an explicit external-reference decision; use the returned remapped clips and nodeMap.",+ "For a real rolling assembly, account for tread protrusions, wheel profile and sampled rotation when choosing center height. A smooth polygonal tire is still a contact approximation."+ ],+ "checks": [+ "Verify fork and spin are siblings beneath steering, and the entire assembly moves together under a transformed parent.",+ "Sample exported spin and steering independently. The tire must not rotate the fork; steering must carry both.",+ "Inspect the actual axle/fork/hub interface, ground clearance and host attachment. Semantic roles and matching bounding boxes do not prove physical mating."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "recipe:branched-articulation-v1",+ "name": "Branched articulation with preserved rest frames",+ "summary": "Build a two-branch mechanical gripper with local links, explicit parent roles and nonzero rest rotations. Animate bends without resetting joint offsets or assuming a humanoid skeleton.",+ "family": "articulation",+ "tags": [+ "rig",+ "branch",+ "gripper",+ "rest frame",+ "local rotation",+ "animation"+ ],+ "aliases": [+ "branching articulated gripper",+ "non humanoid mechanism",+ "jointed appendages"+ ],+ "intents": [+ "animate a branching mechanism",+ "retain rest offsets during a bend"+ ],+ "stability": "experimental",+ "related": [+ {+ "id": "assembly:createJointChain",+ "relation": "prerequisite"+ },+ {+ "id": "recipe:rig-custom-v1",+ "relation": "companion"+ }+ ],+ "references": [+ "src/character.ts",+ "docs/geometry.md"+ ],+ "limitations": [+ "Rigid articulated teaching geometry, without skinning, inverse kinematics, grasp constraints or collision avoidance. Inspect each intended pose and edited proportion.",+ "The animation demonstrates local bending only. A graph label does not establish locomotion, stable contact or a functional grasp."+ ],+ "kind": "recipe",+ "recipe": {+ "prerequisites": [+ "assembly:createJointChain",+ "operation:createRoot",+ "operation:createPart",+ "operation:rotationTrack",+ "operation:createClip"+ ],+ "steps": [+ "Place a shared core, then parent each branch explicitly with parentRole. Give every role a unique name and author links in each joint local frame.",+ "Set rest rotations as quaternions and derive geometry and downstream offsets from the same lengths. Record the returned descriptors on the root graph.",+ "Rotation tracks are absolute local rotations, not deltas. Start from the rest orientation; leave translations untouched unless intentionally changing them.",+ "Export the graph and clips; verify parent edges, rest frames and moving geometry. For replication, remap the full assembly and its clips together."+ ],+ "example": "const meta = { name: 'BranchedGripper' };\nconst upperLength = 0.4;\nconst lowerLength = 0.28;\nfunction build() {\n const root = createRoot(meta.name);\n const metal = gameMaterial('#748e9c'), jointMaterial = gameMaterial('#35464f');\n const core = createJointChain('Fork', [{ role: 'core', offset: [0, 0.3, 0] }], { parent: root });\n createPart('Core', boxGeo(0.32, 0.18, 0.18), metal, { parent: core.root });\n const descriptors = [...core.descriptors];\n function zRotation(degrees) {\n const half = degrees * Math.PI / 360;\n return [0, 0, Math.sin(half), Math.cos(half)];\n }\n for (const side of [-1, 1]) {\n const label = side < 0 ? 'left' : 'right';\n const branch = createJointChain('Fork', [\n { role: label + '.shoulder', offset: [side * 0.1, 0, 0],\n restRotation: zRotation(-side * 35), localBendAxis: [0, 0, 1] },\n { role: label + '.elbow', offset: [0, upperLength, 0],\n restRotation: zRotation(side * 15), localBendAxis: [0, 0, 1] },\n { role: label + '.tip', offset: [0, lowerLength, 0], endEffector: true }\n ], { parent: core.end, parentRole: 'core' });\n descriptors.push(...branch.descriptors);\n createPart(label + 'Upper', boxGeo(0.08, upperLength, 0.08), metal,\n { parent: branch.nodes[0], position: [0, upperLength / 2, 0] });\n createPart(label + 'Lower', boxGeo(0.07, lowerLength, 0.07), metal,\n { parent: branch.nodes[1], position: [0, lowerLength / 2, 0] });\n for (let i = 0; i < 2; i++) createPart(label + 'Hinge' + i,\n cylinderZGeo(0.055, 0.055, 0.1, 16), jointMaterial, { parent: branch.nodes[i] });\n createPart(label + 'Pad', boxGeo(0.11, 0.06, 0.12), jointMaterial, { parent: branch.end });\n }\n root.userData.kilnCharacterRig = { schemaVersion: 1, bodyPlan: 'custom', joints: descriptors };\n return root;\n}\nfunction animate(root) {\n const tracks = [];\n root.traverse(node => {\n const descriptor = node.userData.kilnCharacterJoint;\n if (!descriptor || !descriptor.role.endsWith('.elbow')) return;\n const rest = descriptor.rest.rotation;\n const degrees = 2 * Math.atan2(rest[2], rest[3]) * 180 / Math.PI;\n const bend = descriptor.role.startsWith('left.') ? -45 : 45;\n tracks.push(rotationTrack(node.name, [\n { time: 0, rotation: [0, 0, degrees] },\n { time: 0.5, rotation: [0, 0, degrees + bend] },\n { time: 1, rotation: [0, 0, degrees] }\n ]));\n });\n return [createClip('Bend', 1, tracks)];\n}",+ "adaptations": [+ "Change upperLength or lowerLength, rebuilding links and child offsets together. The core and the opposite branch need not change for a one-branch edit.",+ "Add branches with distinct roles and explicit parent edges. No body-plan preset or asset category is required.",+ "This example bends about local Z only. For arbitrary rest frames, compose rest and delta quaternions in the intended order rather than adding Euler angles."+ ],+ "checks": [+ "Every graph role must resolve to one exported joint and parentRole must match the real hierarchy.",+ "At time zero, sampled animation must agree with the declared rest frame. Bending must retain translations and move the attached links and end effectors.",+ "Review open and bent views, hinge contact, self-intersection and the intended destination playback. Structural validity alone cannot certify useful motion."+ ]+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:project-draft",+ "name": "project-draft",+ "summary": "The record kiln_project create takes: name, brief, design (style, scale, palette, materialRoles, conventions, exceptions), inventory, deliveryProfiles, materialDependencies, references and reviews, with an optional projectId.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_project",+ "draft"+ ],+ "aliases": [+ "project draft",+ "new project fields",+ "project record"+ ],+ "intents": [+ "create a project for a pack",+ "write a project brief and inventory"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/projects-and-live-review.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_project",+ "field": "draft",+ "schema": {+ "type": "object",+ "properties": {+ "projectId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "brief": {+ "default": "",+ "type": "string",+ "maxLength": 16000+ },+ "design": {+ "default": {+ "style": "",+ "scale": "",+ "palette": [],+ "materialRoles": [],+ "conventions": [],+ "exceptions": []+ },+ "type": "object",+ "properties": {+ "style": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "scale": {+ "default": "",+ "type": "string",+ "maxLength": 1000+ },+ "palette": {+ "default": [],+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "role": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "color": {+ "type": "string",+ "pattern": "^#[a-fA-F0-9]{6}$"+ }+ },+ "required": [+ "role",+ "color"+ ],+ "additionalProperties": false+ }+ },+ "materialRoles": {+ "default": [],+ "maxItems": 128,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "role": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ }+ },+ "required": [+ "role"+ ],+ "additionalProperties": false+ }+ },+ "conventions": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ },+ "exceptions": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ }+ },+ "additionalProperties": false+ },+ "inventory": {+ "default": [],+ "maxItems": 1000,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "kind": {+ "default": "asset",+ "type": "string",+ "enum": [+ "asset",+ "environment"+ ]+ },+ "brief": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "references": {+ "default": [],+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "asset": {+ "type": "object",+ "properties": {+ "collectionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collectionId",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "id",+ "name"+ ],+ "additionalProperties": false+ }+ },+ "deliveryProfiles": {+ "default": [],+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "target": {+ "type": "string",+ "enum": [+ "three",+ "godot",+ "unity",+ "unreal",+ "roblox",+ "sbox",+ "usdz",+ "custom"+ ]+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "performanceIntent": {+ "default": "",+ "type": "string",+ "maxLength": 1000+ },+ "constraints": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ }+ },+ "required": [+ "id",+ "target"+ ],+ "additionalProperties": false+ }+ },+ "materialDependencies": {+ "default": [],+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ },+ "references": {+ "default": [],+ "maxItems": 256,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "uri": {+ "type": "string",+ "minLength": 1,+ "maxLength": 2048+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ }+ },+ "required": [+ "id",+ "title",+ "uri"+ ],+ "additionalProperties": false+ }+ },+ "reviews": {+ "default": [],+ "maxItems": 2000,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "inventoryId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "projectRevisionId": {+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "asset": {+ "type": "object",+ "properties": {+ "collectionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collectionId",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+ },+ "reviewer": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "verdict": {+ "type": "string",+ "enum": [+ "comment",+ "changes-requested",+ "accepted"+ ]+ },+ "notes": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "required": [+ "id",+ "inventoryId",+ "projectRevisionId",+ "asset",+ "reviewer",+ "verdict",+ "notes"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "name"+ ],+ "additionalProperties": false+ }+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:project-patch",+ "name": "project-patch",+ "summary": "The record kiln_project update takes: the same top-level fields as the draft, each optional; a supplied field replaces its previous value whole, so read and merge design before changing one preference.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_project",+ "patch"+ ],+ "aliases": [+ "project patch",+ "project update fields"+ ],+ "intents": [+ "update a project brief, design, inventory or material pins"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/projects-and-live-review.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_project",+ "field": "patch",+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "brief": {+ "type": "string",+ "maxLength": 16000+ },+ "design": {+ "type": "object",+ "properties": {+ "style": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "scale": {+ "default": "",+ "type": "string",+ "maxLength": 1000+ },+ "palette": {+ "default": [],+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "role": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "color": {+ "type": "string",+ "pattern": "^#[a-fA-F0-9]{6}$"+ }+ },+ "required": [+ "role",+ "color"+ ],+ "additionalProperties": false+ }+ },+ "materialRoles": {+ "default": [],+ "maxItems": 128,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "role": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ }+ },+ "required": [+ "role"+ ],+ "additionalProperties": false+ }+ },+ "conventions": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ },+ "exceptions": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ }+ },+ "additionalProperties": false+ },+ "inventory": {+ "maxItems": 1000,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "kind": {+ "default": "asset",+ "type": "string",+ "enum": [+ "asset",+ "environment"+ ]+ },+ "brief": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "references": {+ "default": [],+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "asset": {+ "type": "object",+ "properties": {+ "collectionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collectionId",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "id",+ "name"+ ],+ "additionalProperties": false+ }+ },+ "deliveryProfiles": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "target": {+ "type": "string",+ "enum": [+ "three",+ "godot",+ "unity",+ "unreal",+ "roblox",+ "sbox",+ "usdz",+ "custom"+ ]+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "performanceIntent": {+ "default": "",+ "type": "string",+ "maxLength": 1000+ },+ "constraints": {+ "default": [],+ "maxItems": 100,+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 1000+ }+ }+ },+ "required": [+ "id",+ "target"+ ],+ "additionalProperties": false+ }+ },+ "materialDependencies": {+ "maxItems": 512,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "resourceId": {+ "type": "string",+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$"+ },+ "revisionId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "role": {+ "type": "string",+ "maxLength": 100+ }+ },+ "required": [+ "resourceId",+ "revisionId",+ "sha256"+ ],+ "additionalProperties": false+ }+ },+ "references": {+ "maxItems": 256,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "uri": {+ "type": "string",+ "minLength": 1,+ "maxLength": 2048+ },+ "description": {+ "default": "",+ "type": "string",+ "maxLength": 4000+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ }+ },+ "required": [+ "id",+ "title",+ "uri"+ ],+ "additionalProperties": false+ }+ },+ "reviews": {+ "maxItems": 2000,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "inventoryId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "projectRevisionId": {+ "type": "string",+ "pattern": "^r_[0-9]{10}_[a-f0-9]{64}$"+ },+ "asset": {+ "type": "object",+ "properties": {+ "collectionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "assetId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ }+ },+ "required": [+ "collectionId",+ "assetId",+ "revisionId"+ ],+ "additionalProperties": false+ },+ "reviewer": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "verdict": {+ "type": "string",+ "enum": [+ "comment",+ "changes-requested",+ "accepted"+ ]+ },+ "notes": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "required": [+ "id",+ "inventoryId",+ "projectRevisionId",+ "asset",+ "reviewer",+ "verdict",+ "notes"+ ],+ "additionalProperties": false+ }+ }+ },+ "additionalProperties": false+ }+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:material-draft",+ "name": "material-draft",+ "summary": "The record kiln_material create-procedural takes: materialId, name, tileable, sources with license, and maps whose layered procedural specs (solid, checker, stripes, gradient, bricks, noise) bake into PNG maps; optional tags, physicalSizeMeters and parameters.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_material",+ "draft"+ ],+ "aliases": [+ "procedural material",+ "material recipe draft",+ "texture layers"+ ],+ "intents": [+ "bake a custom tileable material from layers"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/projects-and-live-review.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_material",+ "field": "draft",+ "schema": {+ "type": "object",+ "properties": {+ "materialId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "tags": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ }+ },+ "tileable": {+ "type": "boolean"+ },+ "physicalSizeMeters": {+ "type": "object",+ "properties": {+ "width": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100000+ },+ "height": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100000+ }+ },+ "required": [+ "width",+ "height"+ ],+ "additionalProperties": false+ },+ "parameters": {+ "type": "object",+ "properties": {+ "baseColor": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "roughness": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "metalness": {+ "default": 0,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "emissive": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "emissiveIntensity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 64+ },+ "alphaMode": {+ "default": "opaque",+ "type": "string",+ "enum": [+ "opaque",+ "mask",+ "blend"+ ]+ },+ "alphaCutoff": {+ "default": 0.5,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "doubleSided": {+ "default": false,+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },+ "sources": {+ "minItems": 1,+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "kind": {+ "type": "string",+ "enum": [+ "external",+ "procedural"+ ]+ },+ "provider": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "creator": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "assetId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "assetUrl": {+ "type": "string",+ "maxLength": 2000,+ "format": "uri"+ },+ "accessedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"+ },+ "license": {+ "type": "object",+ "properties": {+ "spdx": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "url": {+ "type": "string",+ "maxLength": 2000,+ "format": "uri"+ },+ "attribution": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "required": [+ "spdx",+ "url",+ "attribution"+ ],+ "additionalProperties": false+ },+ "originalFiles": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "bytes": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 1073741824+ }+ },+ "required": [+ "name",+ "sha256",+ "bytes"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "id",+ "kind",+ "provider",+ "creator",+ "license",+ "originalFiles"+ ],+ "additionalProperties": false+ }+ },+ "maps": {+ "minItems": 1,+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "slot": {+ "type": "string",+ "enum": [+ "baseColor",+ "normal",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ]+ },+ "sourceId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "transforms": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "operation": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "tool": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "version": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "parameters": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "maxLength": 100+ },+ "additionalProperties": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 2000+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ }+ }+ },+ "required": [+ "operation",+ "tool",+ "version"+ ],+ "additionalProperties": false+ }+ },+ "normalConvention": {+ "type": "string",+ "const": "opengl"+ },+ "channelPacking": {+ "type": "string",+ "const": "r-occlusion-g-roughness-b-metallic"+ },+ "procedural": {+ "type": "object",+ "properties": {+ "schemaVersion": {+ "type": "number",+ "const": 2+ },+ "size": {+ "default": 256,+ "type": "integer",+ "minimum": 4,+ "maximum": 1024+ },+ "usage": {+ "default": "albedo",+ "type": "string",+ "enum": [+ "albedo",+ "normal",+ "roughness",+ "metalness",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ]+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "layers": {+ "minItems": 1,+ "maxItems": 8,+ "type": "array",+ "items": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "solid"+ },+ "color": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "color"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "checker"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "squares": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "stripes"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "count": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "angleDeg": {+ "default": 0,+ "type": "number",+ "minimum": -36000,+ "maximum": 36000+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "gradient"+ },+ "from": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "to": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "angleDeg": {+ "default": 0,+ "type": "number",+ "minimum": -36000,+ "maximum": 36000+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "from",+ "to"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "bricks"+ },+ "brick": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "mortar": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "rows": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "cols": {+ "default": 4,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "mortarWidth": {+ "default": 0.06,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "stagger": {+ "default": 0.5,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "brick",+ "mortar"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "noise"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "scale": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "octaves": {+ "default": 3,+ "type": "integer",+ "minimum": 1,+ "maximum": 6+ },+ "seed": {+ "default": 0,+ "type": "integer",+ "minimum": -2147483648,+ "maximum": 2147483647+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ }+ ]+ }+ }+ },+ "required": [+ "schemaVersion",+ "layers"+ ],+ "additionalProperties": false+ },+ "derive": {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "normal-from-height"+ },+ "strength": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 64+ }+ },+ "required": [+ "kind",+ "strength"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "slot",+ "sourceId",+ "transforms",+ "procedural"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "materialId",+ "name",+ "tileable",+ "sources",+ "maps"+ ],+ "additionalProperties": false+ }+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:material-import",+ "name": "material-import",+ "summary": "The record kiln_material import takes: schemaVersion 1 and complete normalized material records, each a manifest plus base64 PNG files keyed by map name.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_material",+ "payload"+ ],+ "aliases": [+ "material import payload",+ "material records"+ ],+ "intents": [+ "import a material library payload"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/projects-and-live-review.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_material",+ "field": "payload",+ "schema": {+ "type": "object",+ "properties": {+ "schemaVersion": {+ "type": "number",+ "const": 1+ },+ "records": {+ "maxItems": 16,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "manifest": {+ "type": "object",+ "properties": {+ "schemaVersion": {+ "type": "number",+ "const": 1+ },+ "materialId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "revisionId": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "tags": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ }+ },+ "tileable": {+ "type": "boolean"+ },+ "physicalSizeMeters": {+ "type": "object",+ "properties": {+ "width": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100000+ },+ "height": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100000+ }+ },+ "required": [+ "width",+ "height"+ ],+ "additionalProperties": false+ },+ "parameters": {+ "type": "object",+ "properties": {+ "baseColor": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "roughness": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "metalness": {+ "default": 0,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "emissive": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "emissiveIntensity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 64+ },+ "alphaMode": {+ "default": "opaque",+ "type": "string",+ "enum": [+ "opaque",+ "mask",+ "blend"+ ]+ },+ "alphaCutoff": {+ "default": 0.5,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "doubleSided": {+ "default": false,+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },+ "sources": {+ "minItems": 1,+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "kind": {+ "type": "string",+ "enum": [+ "external",+ "procedural"+ ]+ },+ "provider": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "creator": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "assetId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "assetUrl": {+ "type": "string",+ "maxLength": 2000,+ "format": "uri"+ },+ "accessedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"+ },+ "license": {+ "type": "object",+ "properties": {+ "spdx": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "url": {+ "type": "string",+ "maxLength": 2000,+ "format": "uri"+ },+ "attribution": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "required": [+ "spdx",+ "url",+ "attribution"+ ],+ "additionalProperties": false+ },+ "originalFiles": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "bytes": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 1073741824+ }+ },+ "required": [+ "name",+ "sha256",+ "bytes"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "id",+ "kind",+ "provider",+ "creator",+ "license",+ "originalFiles"+ ],+ "additionalProperties": false+ }+ },+ "maps": {+ "minItems": 1,+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "slot": {+ "type": "string",+ "enum": [+ "baseColor",+ "normal",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ]+ },+ "file": {+ "type": "string",+ "enum": [+ "baseColor.png",+ "normal.png",+ "metallicRoughness.png",+ "emissive.png",+ "occlusion.png"+ ]+ },+ "sha256": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "bytes": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 8388608+ },+ "width": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 4096+ },+ "height": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 4096+ },+ "usage": {+ "type": "string",+ "enum": [+ "albedo",+ "normal",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ]+ },+ "colorSpace": {+ "type": "string",+ "enum": [+ "srgb",+ "linear"+ ]+ },+ "normalConvention": {+ "type": "string",+ "const": "opengl"+ },+ "channelPacking": {+ "type": "string",+ "const": "r-occlusion-g-roughness-b-metallic"+ },+ "sourceId": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "originalFile": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "transforms": {+ "maxItems": 30,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "operation": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "tool": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "version": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ },+ "parameters": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "maxLength": 100+ },+ "additionalProperties": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 2000+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ }+ }+ },+ "required": [+ "operation",+ "tool",+ "version"+ ],+ "additionalProperties": false+ }+ },+ "procedural": {+ "type": "object",+ "properties": {+ "compiler": {+ "type": "string",+ "const": "kiln.procedural-texture.v2"+ },+ "spec": {+ "type": "object",+ "properties": {+ "schemaVersion": {+ "type": "number",+ "const": 2+ },+ "size": {+ "default": 256,+ "type": "integer",+ "minimum": 4,+ "maximum": 1024+ },+ "usage": {+ "default": "albedo",+ "type": "string",+ "enum": [+ "albedo",+ "normal",+ "roughness",+ "metalness",+ "metallicRoughness",+ "emissive",+ "occlusion"+ ]+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 80+ },+ "layers": {+ "minItems": 1,+ "maxItems": 8,+ "type": "array",+ "items": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "solid"+ },+ "color": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "color"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "checker"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "squares": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "stripes"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "count": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "angleDeg": {+ "default": 0,+ "type": "number",+ "minimum": -36000,+ "maximum": 36000+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "gradient"+ },+ "from": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "to": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "angleDeg": {+ "default": 0,+ "type": "number",+ "minimum": -36000,+ "maximum": 36000+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "from",+ "to"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "bricks"+ },+ "brick": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "mortar": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "rows": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "cols": {+ "default": 4,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "mortarWidth": {+ "default": 0.06,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "stagger": {+ "default": 0.5,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "brick",+ "mortar"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "noise"+ },+ "colorA": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "colorB": {+ "type": "integer",+ "minimum": 0,+ "maximum": 16777215+ },+ "scale": {+ "default": 8,+ "type": "integer",+ "minimum": 1,+ "maximum": 256+ },+ "octaves": {+ "default": 3,+ "type": "integer",+ "minimum": 1,+ "maximum": 6+ },+ "seed": {+ "default": 0,+ "type": "integer",+ "minimum": -2147483648,+ "maximum": 2147483647+ },+ "blend": {+ "default": "normal",+ "type": "string",+ "enum": [+ "normal",+ "multiply",+ "screen",+ "overlay"+ ]+ },+ "opacity": {+ "default": 1,+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": [+ "op",+ "colorA",+ "colorB"+ ],+ "additionalProperties": false+ }+ ]+ }+ }+ },+ "required": [+ "schemaVersion",+ "layers"+ ],+ "additionalProperties": false+ },+ "derive": {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "normal-from-height"+ },+ "strength": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 64+ }+ },+ "required": [+ "kind",+ "strength"+ ],+ "additionalProperties": false+ },+ "recipeHash": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "pixelHash": {+ "type": "string",+ "pattern": "^sha256:[a-f0-9]{64}$"+ },+ "encoder": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "const": "sharp"+ },+ "version": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1000+ }+ },+ "required": [+ "name",+ "version"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "compiler",+ "spec",+ "recipeHash",+ "pixelHash",+ "encoder"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "slot",+ "file",+ "sha256",+ "bytes",+ "width",+ "height",+ "usage",+ "colorSpace",+ "sourceId",+ "transforms"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "schemaVersion",+ "materialId",+ "revisionId",+ "name",+ "tags",+ "tileable",+ "parameters",+ "sources",+ "maps"+ ],+ "additionalProperties": false+ },+ "files": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "pattern": "^(baseColor|normal|metallicRoughness|emissive|occlusion)\\.png$"+ },+ "additionalProperties": {+ "type": "string",+ "maxLength": 11184812+ }+ }+ },+ "required": [+ "manifest",+ "files"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "schemaVersion",+ "records"+ ],+ "additionalProperties": false+ }+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:capture",+ "name": "capture",+ "summary": "The capture record kiln_render, kiln_edit and kiln_view_interior take: either preset/cells/backdrop for an orbit sheet, or kiln.capture.v1 or v2 with 1 to 9 shots, cols, size, output and backdrop; v2 shots may hide nodes.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_render",+ "capture"+ ],+ "aliases": [+ "capture config",+ "camera sheet",+ "exact cameras",+ "orbit grid"+ ],+ "intents": [+ "choose cameras for a render",+ "render exact orthographic or perspective views"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/cameras.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_render",+ "field": "capture",+ "schema": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "version": {+ "type": "string",+ "enum": [+ "kiln.capture.v1",+ "kiln.capture.v2"+ ]+ },+ "shots": {+ "minItems": 1,+ "maxItems": 9,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "subject": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "visibility": {+ "type": "string",+ "enum": [+ "context",+ "isolate"+ ]+ },+ "hide": {+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1024+ }+ },+ "camera": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "orbit"+ },+ "azimuthDeg": {+ "type": "number"+ },+ "elevationDeg": {+ "type": "number"+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ }+ },+ "required": [+ "type"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "explicit"+ },+ "projection": {+ "type": "string",+ "enum": [+ "orthographic",+ "perspective"+ ]+ },+ "position": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "target": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part",+ "local"+ ]+ },+ "frame": {+ "type": "object",+ "properties": {+ "origin": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "rotation": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ }+ },+ "additionalProperties": false+ },+ "framing": {+ "type": "string",+ "enum": [+ "explicit",+ "bounds"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ },+ "targetOffset": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "up": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "halfHeight": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "fovDeg": {+ "type": "number",+ "exclusiveMinimum": 0,+ "exclusiveMaximum": 180+ },+ "near": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "far": {+ "type": "number",+ "exclusiveMinimum": 0+ }+ },+ "required": [+ "type",+ "projection",+ "position"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "additionalProperties": false+ }+ },+ "cols": {+ "type": "integer",+ "minimum": 1,+ "maximum": 3+ },+ "size": {+ "type": "integer",+ "minimum": 128,+ "maximum": 2048+ },+ "output": {+ "type": "string",+ "enum": [+ "grid",+ "separate"+ ]+ },+ "backdrop": {+ "description": "neutral (default); light for dark parts, dark for light parts.",+ "type": "string",+ "enum": [+ "neutral",+ "dark",+ "light"+ ]+ }+ },+ "required": [+ "version",+ "shots"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "preset": {+ "description": "COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3.",+ "type": "string",+ "enum": [+ "1x1",+ "1x2",+ "2x1",+ "3x1",+ "2x2",+ "3x2",+ "3x3"+ ]+ },+ "cells": {+ "description": "Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9).",+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "azimuthDeg": {+ "type": "number",+ "description": "0 = front, 90 = right, 180 = back, 270 = left. Wraps."+ },+ "elevationDeg": {+ "type": "number",+ "description": "0 eye level; positive above, negative below. Clamped -89..89."+ },+ "zoom": {+ "description": "Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing.",+ "type": "number"+ },+ "name": {+ "description": "Label; defaults to angles.",+ "type": "string"+ }+ },+ "required": [+ "azimuthDeg",+ "elevationDeg"+ ]+ }+ },+ "backdrop": {+ "description": "neutral (default); light for dark parts, dark for light parts.",+ "type": "string",+ "enum": [+ "neutral",+ "dark",+ "light"+ ]+ }+ },+ "additionalProperties": false+ }+ ]+ }+ }+ },+ {+ "version": "kiln.catalog-entry.v1",+ "id": "shape:camera-shot",+ "name": "camera-shot",+ "summary": "One shot, as kiln_inspect shot and kiln_screenshot_animation shot take it and as capture.shots lists it: optional name, subject (path or exact name), visibility, hide, and an orbit or explicit camera.",+ "family": "tool-input",+ "tags": [+ "schema",+ "kiln_inspect",+ "shot"+ ],+ "aliases": [+ "camera shot",+ "explicit camera",+ "orbit camera"+ ],+ "intents": [+ "frame one part with an exact camera"+ ],+ "stability": "stable",+ "related": [],+ "references": [+ "docs/cameras.md"+ ],+ "limitations": [],+ "kind": "shape",+ "shape": {+ "tool": "kiln_inspect",+ "field": "shot",+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "subject": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "visibility": {+ "type": "string",+ "enum": [+ "context",+ "isolate"+ ]+ },+ "hide": {+ "maxItems": 64,+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 1024+ }+ },+ "camera": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "orbit"+ },+ "azimuthDeg": {+ "type": "number"+ },+ "elevationDeg": {+ "type": "number"+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ }+ },+ "required": [+ "type"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "explicit"+ },+ "projection": {+ "type": "string",+ "enum": [+ "orthographic",+ "perspective"+ ]+ },+ "position": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "target": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "relativeTo": {+ "type": "string",+ "enum": [+ "world",+ "asset",+ "part",+ "local"+ ]+ },+ "frame": {+ "type": "object",+ "properties": {+ "origin": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "rotation": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ }+ },+ "additionalProperties": false+ },+ "framing": {+ "type": "string",+ "enum": [+ "explicit",+ "bounds"+ ]+ },+ "padding": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 100+ },+ "targetOffset": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "up": {+ "minItems": 3,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "number"+ }+ },+ "halfHeight": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "fovDeg": {+ "type": "number",+ "exclusiveMinimum": 0,+ "exclusiveMaximum": 180+ },+ "near": {+ "type": "number",+ "exclusiveMinimum": 0+ },+ "far": {+ "type": "number",+ "exclusiveMinimum": 0+ }+ },+ "required": [+ "type",+ "projection",+ "position"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "additionalProperties": false+ }+ }+ }+ ]+}diff --git a/hosting/src/github.ts b/hosting/src/github.tsnew file mode 100644index 00000000..e1874f59--- /dev/null+++ b/hosting/src/github.ts@@ -0,0 +1,87 @@+import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';+import { HttpFailure, readBounded, sha256 } from './http';++export interface GitHubEnv {+ GITHUB_CLIENT_ID: string;+ GITHUB_CLIENT_SECRET: string;+}++async function upstreamJson(url: string, init: RequestInit): Promise<Record<string, unknown>> {+ const response = await fetch(url, {+ ...init,+ redirect: 'manual',+ signal: AbortSignal.timeout(10_000),+ });+ if (!response.ok) {+ void response.body?.cancel().catch(() => {});+ throw new HttpFailure(502, 'Sign-in provider unavailable; restart sign-in');+ }+ const value: unknown = JSON.parse(+ new TextDecoder().decode(await readBounded(response.body, 32_768)),+ );+ if (!value || typeof value !== 'object' || Array.isArray(value))+ throw new HttpFailure(502, 'Invalid sign-in response');+ return value as Record<string, unknown>;+}++export async function githubIdentity(+ code: string,+ verifier: string,+ origin: string,+ env: GitHubEnv,+): Promise<VerifiedIdentity> {+ const token = await upstreamJson('https://github.com/login/oauth/access_token', {+ method: 'POST',+ headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ client_id: env.GITHUB_CLIENT_ID,+ client_secret: env.GITHUB_CLIENT_SECRET,+ code,+ code_verifier: verifier,+ redirect_uri: `${origin}/oauth/github/callback`,+ }),+ });+ if (+ typeof token.access_token !== 'string' ||+ !token.access_token ||+ token.access_token.length > 4096 ||+ typeof token.token_type !== 'string' ||+ token.token_type.toLowerCase() !== 'bearer'+ ) {+ throw new HttpFailure(400, 'Sign-in failed; restart sign-in');+ }+ const user = await upstreamJson('https://api.github.com/user', {+ headers: {+ accept: 'application/vnd.github+json',+ authorization: `Bearer ${token.access_token}`,+ 'user-agent': 'Kiln-Instrukt-Labs',+ 'x-github-api-version': '2026-03-10',+ },+ });+ if (typeof user.id !== 'number' || !Number.isSafeInteger(user.id) || user.id <= 0) {+ throw new HttpFailure(502, 'Invalid sign-in identity');+ }+ // Immutable provider id, never a mutable login or email. Upstream tokens are+ // discarded here; the account directory owns the provider-neutral subject.+ return { issuer: IDENTITY_ISSUERS.github, subject: String(user.id) };+}++export async function githubAuthorizationUrl(+ origin: string,+ state: string,+ verifier: string,+ env: GitHubEnv,+ selectAccount = false,+): Promise<string> {+ const target = new URL('https://github.com/login/oauth/authorize');+ target.search = new URLSearchParams({+ client_id: env.GITHUB_CLIENT_ID,+ redirect_uri: `${origin}/oauth/github/callback`,+ scope: '',+ state,+ code_challenge: await sha256(verifier),+ code_challenge_method: 'S256',+ ...(selectAccount ? { prompt: 'select_account' } : {}),+ }).toString();+ return target.href;+}diff --git a/hosting/src/google-button.ts b/hosting/src/google-button.tsnew file mode 100644index 00000000..5c74dd16--- /dev/null+++ b/hosting/src/google-button.ts@@ -0,0 +1,3 @@+// Unmodified pre-approved Google sign-in PNG. See ../assets/README.md.+export const GOOGLE_SIGN_IN_BUTTON =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWgAAABQCAYAAAA0u++hAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAFvJJREFUeAHtnQusHNV5x/8zu9f3jW3CwxhMXCAtYGNIyyutgeImNEVqcCmV3FKlBaVWKSK4kWncqAIDbepQh0chTWpVpEJIcVpSILQUTNW42CY0hcoYcB5gc3nZIAVf36fvY3cm3392v/VhsrOP67t7Z6+/n3U8OzszZ+fMnPOfb77znXM9xFi7bt2v+2FwVQisDBEuhmEYhtEwPGCnLHZmvMztGzZs6IttK7B+/fp5w4dGbwPCNTAMwzCajg/v3q7OrttFjw9yPRJoivPIoZHvidV8XkdHBy5ZfglOP+10SafBMAzDaBz79u3Dth3b8cKLL0TrtKi7O7svp0hn+MX5F134t7JYOX/+fHz+xpuwdMkSHCufDcMwjMbS29sbae4Fv3I+Xtn9Kg6NjS3I5XIdO3bseNpbt27d4lyYf4M7fumLf4n5JsyGYRgzQn9/P+657x6KtJjS4eV+Pszfxg3ni3qbOBuGYcwc1ODl4mImXuit9Ol35solv7YchmEYxszC/r8iV/koCvTChQthGIZhzCwanCHG82IfhmEYRioxgTYMw0gpJtCGYRgpxQTaMAwjpZhAG4ZhpBQTaMMwjJRiAm0YhpFSTKANwzBSigm0YRhGSjGBNgzDSCkm0IZhGCnFBNowDCOlZJFWdu1E+NJLwN49CPe8Dm9kBBgeKmzr6QEWLAC6ZXnOefDOPQ9YtgyGYRiziXQJ9PvvIXzmaYT/9h1gZBie5yEMw5/fb3gY2LMXsoMI+SsIv7VZBPtkEetl8K5dBZxwPAzDMFqddAi0iHH4T/cj3PI0EPjRPHvkQ9JMMaZY6zLawYeXaUPotcH76SDC7z0HbP1f4DcuBVZdLUJ9HAzDMFqVGRfo8KnNCDd/ExgYFY+4XxDfsPjHxl3ruSTKFGk/Sl5mjqxLEfz2SKQLLnXZ/l//A7z0MvD7vwN8cgUMwzBakZkV6G9vBJ7cDG9CTiOTQRgUreNIi71CKgoz//c8Z7sv+4uQex6LkJE9uS0vKSdpEtj/FnD3PeI22Qdc+4cwDMNoNWYmimNsEPiHP0b47ENAWyCPiTy8bCAWMa3jsKTNCoU5EudoxS9Y2kEk2WI5yzYKczAhacxJ44W05anIhWIYhtFqzIwF/dAfAO+8BrRnCtZwyM5AEeq8CHVQ7BgMcNgXLeslgY4saNnoc11EPZgsZpovWtDFxINPPBG4a2Mh2sMwDKPFaL5Ab7sNGNwFdGaL/X1ewedMQaa2BsV1psiS9orWchF+pyJNcfbyhe8jYS6qOpcnLhBx/mphaRiG0YI0V6D3fgt4/eti0WYLzpXIKC66NCKRprvCF33NR995vXPhfeYaYNm5wOmnH7aE6bLYsyeKkcajj0bheQVhDgtLxkjfdbeJs2EYLU3zBPqQdNrt+bKIrFi99DX7heRJiuzjotUcBj68jywEfvdz8Fb8Vvm8KNQUbaaVVwPPbAEe/mfgvfeKlnO6xPmdd97B888/Hy3J2WefHaVTTjkl8ZgtW7ZgcHAQF198ccX90oaWs9XOO4lWLo+eu9Y7nj8Ty2K0Bs0T6DfvlP/E4u0Sv3NWJDkTlIQ6GpAinX+BCLS/bAW869bLfr215/2pKwojCb/+NeCGG1MjzmwYa9eujRpKOa6//nqsWbMGxxxzzIe+v+OOO/Dggw9Gn9mgnnzyyZ/bJ43wobJ69erS+ubNm1taDO69994okSO5D8uXLy+J5Pbt2xsq9Hyos+4w8XM5+PvXXHNNlGbDQ7QabH+rVq2KPrM+sl62Cs2J4hh/E+h/COgQUe4S90VXDugRS7p3QpYTCHpzyPXkEV66Et6NX61PnBWK8vo7UyXOrBRJ4kzYiLhPvCFR6Nx8tHGnnXhZK5W9Fah2H7j+yCOPRCkNZWV94sOAD5UkcSY8b+7DuueW0UgfzbGg9/914ZcYQucXLWexosOsh8D3kZP13PFL0X31nZgtsPJrg6bVRWuFbg02nN27d0eNmvAzG8utt95aOpZWTfy1tBVg+Sqttxq0tnh/SLn7oG9Iuu9MWmauta/wnNSdxnrH86Uga93ikm88fDNo9Xs1W2mOQI9sE1H2igJN9wZ/OUAoYp0T98ZY+0fQu+IBzBZcfzNhwy0nXnRlEIq1K9CbNm0qvaJS2FvBvUF4roTlpzhcccUVaGXofuJ9YnnojkrrfWBdccWZ58z6VM69xO9Z37g/66iW0UgnjRfoYRHnybcKg0sigUYhbM6PgjYwjjnwF62G33MyZguuOFOkyjUANnjtfIo3JAoBG04ror7N2YC++aS5PKxD+qAnPNeNGzdWPIb7sM7RmmY9NNJL4wV6ZHth9F9h4F9xpKC4N3wPebRhrK0Tx56yErOVSr5A12qOH6Ov1hSJJAuHlp2+svIY7scHggq++kXjeTBvPS9+z+2al/4uv2fjrde94vpi3QdPuWgC9eHq+cTPvxrudYr/notb3iSXkXt+er2S7oPm5/42192y63VNgvuy7PxN7qdvHPVeb9dy5rHVxNndtx5xZvn0Xuk5M49671c8D16nWjsreTzrqL6hxq+bew+rXf9GlXG68dZ+8ZYoyu3vNtyFhtB3rZT8icMCrXNrhOLayHVivOf3MO/M2t0bf/PERCl02pMPhaT5FoZ+h8VlEG0tDkik0S4PhsJI8hAL5nq4/rI2NAK315hQiOtpDKwk6tssZxGxIrFhaqRHHB7D37vyyiuj9bh/1O28pP+R+ahPPE6957548eLS576+vtJn10fK8rAMruXnwt9Leni5MI9lzjzg5SIk2NDYcabwzaTc2wl9sdphpr/v3gf3GrpRGUm4ESzxKI6kyB4KAq9Nra6hePkbFTWjdS3J2OD58noliWy1+kpYZ3lfkvLg9eJ1K3fded34+/rQI+61qCWKQ91ESWWsdn7TzS3r/iJaNt6CnnwbkT9D59YoDk4J5bvQz6Bt7oWoh0dfyRZ0vpCNO2UHgMNTlOrkSqXnAlAScn7b2yEN8TI0BHVbaCOkEPGprK+WRworm2u9xVEroBZYKSv15PPctbNpumBjqHR+3F6LhacWlF7ncq/scSHktSkn0O5+jfSdVwq7pDhwOx+atQiBm0+j4pt5PkkPb0XfvCh88fNmmarVV6KRMOXy4LGuwRNHr9tUxTPewcp6xcR8VbD1/Jod8tr4MDsKtE5w5OksSH5xFLeHOd1n1pObWMW+uEb8aBlIvvlYCoopiqsu2teBY2sXjsng4HgGQ2NoGLSE3ArDG8xKRmsqyRKoBVYkt7JTkGiV0Vrlkr/LClSrQLNxqeW2a9euKGkeSiXLZyrouVEoec78zXjDjEckJOGKUrkHTfy7cuFybHiuC6Sa0NFa4zVyHwZ8gPE7TZUsQW5jeVlult99YGgccy2497gRHX28B64408DQ86ZQueXUsNK4BarGicJrxmNZX7l0y+5GxbjfubH16sbhOTAPno/2EUylTWnIoaJ1sly9jO/bDBpvQecGnPkz9MvCnM6+x1nsphDzHKNkUVehZEUXPw+NI7KkG4E2wngld2Nn631tUh+ZEn9d1wEIbKzlGksScYtNK7w2lkbE+MZdJ/rqqe4IDQurdm14rtpo1DfsPlzKiXbcinb3qcUKVQub10XFVDsUq6H1QsvldghrOXg+tbh4XEGqJNAqntVQV4UeExcu95pp+B6vF11per94PXQ/resKhdW9RpoHf1frK6+pRgERNyIqfu2Ivq3yOk7FkHAfCOXcX1ovtYxavmZZ0U0YqFKcvEjnySilABlMwp+iQLsek6DGfXWlFjGfDvRpz6dxuQ43Vl7e+Fqt3XhlTYr00A6+WkjqoHFf86d7oEyS+4Lfu0JTy++6nX7xjjtXeCk82qgqDahpdMRGUkeg+7uNGJikbw6Vknvt4i6fpLrGsrgPE/c4V+ArRcPE66srtHGDJOmBPRXR1CkYtByVyuieezMH9zTegs6IAOcPlszXaOrQaEPB+YDRXcCc+n1HoeaHw9NHJwlvGDuuVot7utBK7HZkaMVTHx1FvFoFcxtQNT9prf7IpHwaaSFUOvep/K5rRbPxaNndhsR9NAJAXRr8LVeYmjFPRZJITcV/6h5TTdQrdeCVe9Nyr121usbt6rONX1ul2oPPvYeuyNfaN6ARIfW87cWjcCq9ZbhlqdWgmg4aL9C+CHTuwIdcHEEYRt2EAb3DE2/UZ8YXFbn0pwm9w1/XeGipg7G3HU1HX8mY6J/TBkLBrmb1ug2pWoOutcHPxOCL6f7NuB9aLTptrPoKTBHQ7/R6J4UFNorpLLv7tlFJmFgXaACUw50/xT23euqa26mmx8YFup76muSaq3bt6n3IVQqTrEStrsPpoPEC3bEUGH8jEuQwLMxcx3EqefnEFBx8HL0n3Fh7fp7+CSyvfAiHV+XQ4nb6nhvlf1Yq+VApFq6fT0erVSKpAZWjmZVoplEBVj+om4hab64FphEfcSu7lYiX2/Xd1kq9/vc0U2+dd9tTuQFjSTTzOjVcoMOe5QgPPlb0PIfIUZxFqPl3UCaYRv4f3eIC8TPzasrv3/+M/3tV9/vurhCbSkaDV5pyWi3ohbX93JSgD01Djyq5LlwLqJbK5eZT7WnfzNewNEBxVd+lO+CGaINyw/L0VdwdzNNqAsVz5kNH3WUaolerlR7vxHMfYK5hwWtZ6drEI2P0WHdOGeZRycJNikhx86j2AKq3zsevUxpH7za+k7BjmQhygMkgj/EgwJh8HhGBHpLlgKx/kOvHu+/dV3N2C+d6klA17RssuFBCr+BMCUuPiDByj/zSiWgIGpSvAlApLKfeziC3AcXn+4jT7HCgmSZuHbvuDVcY3P3UxRT/vpVwO8d02HctD/u4zzXeWewKYaVBKsQVefe4eB6VcLe7Au3el0p56KjMenDz1tGDSZQLz2wGDRdor/cyTPhzMS6fR0WYC+IcYkDSAUk/Fd18af/9GBrvw3Tx7mCAR3ePI5/JIe/lEPicmCksinXh3/mnoiGwscR7pMtVLA1JUmoN0XIrvTtjnsKGRJ/iTFSmmURf94n78IpfV3c9yXqcCu5w8mYSjz7QyKBKb1jcxn3coe1x61E7/ogKfzl04iXFvb7uBFP8zSSjIR6K6p5L/MFbLg/mnXR+lXDfmrTdlLuHGqbIENB6wleng+bMZnfCTRjed7u4NDyxoEOMgmINDMlySJYDuQH8x+ursWrJ9ISv3Pf8MCayOXF2+8iGWfhhRvzfGXka6fPIxy+fWt1NMlVYMd0nOiuPG12gr9hKPdEDDNtz405ZadRKjPeiH01+aOK6OZRyE1G5ow/1u6kIdNxFxfvCvHWWuGa5TFjf3Lc1FRSdR8IV2nJvXuUG1ujgJe1A1JF0rujG58GOh9Kp8Kt4qhBrHu7cGko8lI7XkPvrfdU8dK4NPhjd+VLqrfNue2I+/Mzfc+dicd8g4nH2jaYpAt154s14+93bI3E+JOsjxTQkTuHB0I/S3oHvY+K1m/DZj92PI2HTywfw8Ov9yLS1oS1oQ15SNsgiI4ki7UlacQbdII17eeANZHC7a+HGRdndl9OL1toDrcH6rpUczzfeuI4WKEbxV+WkGO/piN7QtyX9zbhPt5mosOk0ono+ldwCGqefVH6Nf3aFP8lSZR7lBteUe3gk5aEDt+Jovu51jj9k1Eip9/pre1LLuNL5cV+21WbSlL+owg7ArgU3Y0A+HwyZPPQHkkSY+wOmrLg82vDU+4/izt03Yv/YPkyFr/3wbdzyfz/BWNsQJttGxIo+hFx2DJMZpnHk/EnkJV17fuOLrTe+kuuClWoqk6Vzf83bfZqrdXi0TsDuujlI0rWPW8tH4t6odzKpRqJDsauNTlXLlvWk2sOJ+5WbzzyeF/dJsiy5vdLwd53sqNJMfLo9fr46xuBI/lgCy8ZrkVRf3Os1lXj1I6Hxs9kVyeUP4pmdp4k74yCGRaCHxd0xLAI9JMLMNBh2yrJblj3omfOLuO6jq3H1SZ+sKe83R4fwJz/4AbbtH4E32SXWcifach2y7EA2P0cs6XZk8lmxpOdgUc8c/Pfnmhv7q69K8QER0/Wq5I4uVNwZvChAzX7yH23oPdYpKpv5GpyEdnzFp1Gd6sNb89OIDB35WU9ZtR1oCOpUBge5g2vcOu/O0jjVmf20fDrdqBo9zb6fOptd0wSa/HD/32Pbm38u7g0RZrGgR8TDQnEeRoesd4pg98h6IY1KOr59Ea456XL86vyzcU7PqZib7YryGciN4q3RA3j2QB+e2P8Gtr7/AcK8XMB8jzwJRKDzTO0izhTo9kikMyLOWXF37PijBTj5mAxaGZ27udJ8De4sZGmy8gyjXnQgV6X5Tiio6ksm7lS3rUjzpht1OOukz2P/eJ9Yug9EIj0i/uBRtOGQiOdY2CGpHeOSJiXlpHOvb+wDbNj7GAJ815lnyYtOO5RjArGQw6Abnt8t/uUx2SbFyWSime4KB3ilQ8J8iC9cOK/lxdmdt5iUE2n3bx6SVv/TU8bRC40Rja5Qa7acm8HtyJstf9GHNFWgyYrFd+PHw6/g1cHv41A4RzoN26M0hoI4809gTcpp5TidaEhf8eFx3V5xutIwmlAjL+scizgpAp2DF0wg9MdlmxRJhD+f8Yt/yaUwJ/TSY9vxhQsaODqlSeifKiKslKzAGgvr9jortf61CsNII+pCUbcGrWTWaTU6tGM2HgkyW2iqi0M5lBvAV17+bfx45DVxZXRI6pLULRZ1V5TGxB89IeKdE+s6mts5Elm1oSnWfmQth+KyCMQ1EgRdYiF3IxAXR5jn504RbEl5+qHb8QtdvfjPTy/FqeJ/ng2wl7mWqRW1MzEN/lDDmCoaNlhLbH/SX8xpNdTF0ZQojjid2blY//Fn8amFfyoWczsmxGoeF190JMqyzCNTnJTf07+QFeG5szl7HCUYRFZ0NK+0Nwnfn5ASTcDL0JqWJMulx7Vjx2eWzRpxJtqjXalXvFrPumG0CrVGRGkEy2xiRixol6ffexzf6Psm9o4NiMujS1JHJNiTYiFzxmh3ljoPBUs6WkaDT2hFt8uyM7KcA7Gcw0CXHbjpjKW4++PLMJvhq507Uf10R4gYRprQKAs3IupIIlPSyox0EpbjNxdchXPmXYQH+h7G5n3PRtYzfc+hY9yrMIeOXHteceJ/j9P1iy/aEz+0PyliPYnLTliEvzrzQlx2/ALMduqZhcswWh0NzTtaOr5nXKDJwo4F+PKZa3HD4s9i4xvfwbP9P0HfoQOl7SrMXmmqfxQngw4KnYVhHvPbsljaczK+9LEVuPS4RTAMw2h1UiHQyqKOE3DfWTdEn7f3/wjbJO04+CMczI3i7bEPMDA5GvURzst24ZhMN87p/ShObT8ey+efhUuOPQNzs50wDMOYLaRKoF2Wzz8zSoZhGEcrMxLFYRiGYVTHBNowDCOlmEAbhmGkFBNowzCMlGICbRiGkVJMoA3DMFKKCbRhGEZKMYE2DMNIKSbQhmEYKcUE2jAMI6WYQBuGYaQUE2jDMIyU4nvw+vhhz969MAzDMGaWffv3RUvR5p1+gPBxruzduweGYRjGzLJt+/bCBy/c6Xte+Fj05Y7tONB/AIZhGMbMQA1+4cUXos8ZZG7PPLf9ub5PLP/E/Fwuf/Gru1/FkiVL0NlpE98bhmE0E4rzNzb9I8bGxvh3Se676yt3bc5ww0UXXPS8n818WjYs2C6WdH9/P46dPx+9vb0wDMMwGgf7/14Uq/nb//ovGB4epjjv7O7svm7r1q1jnu60Zs2aeZn2zHoP/s0wDMMwmg4tZxHn9cLB4vqHWbdu3eIccusReufK6nkwDMMwGobneX0Iw8dD6Q/cuGHjVnfbzwDasyDjaUgtnwAAAABJRU5ErkJggg==';diff --git a/hosting/src/google.ts b/hosting/src/google.tsindex 9297f6d0..82932b59 100644--- a/hosting/src/google.ts+++ b/hosting/src/google.ts@@ -12,6 +12,7 @@ export interface GoogleFlow {state: string;verifier: string;nonce: string;+ selectAccount?: boolean;}const issuer = new URL(IDENTITY_ISSUERS.google);@@ -111,6 +112,7 @@ export async function googleAuthorizationUrl(nonce: flow.nonce,code_challenge: await oauth.calculatePKCECodeChallenge(flow.verifier),code_challenge_method: 'S256',+ ...(flow.selectAccount ? { prompt: 'select_account' } : {}),}).toString();return target.href;}diff --git a/hosting/src/html-page.ts b/hosting/src/html-page.tsnew file mode 100644index 00000000..e8b2f97a--- /dev/null+++ b/hosting/src/html-page.ts@@ -0,0 +1,36 @@+export const escapeHtml = (value: string) =>+ value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);++/** Content is trusted application markup; escape each interpolated user value. */+export function htmlPage(title: string, content: string, options: ResponseInit = {}): Response {+ const nonce = crypto.randomUUID().replace(/-/g, '');+ const headers = new Headers(options.headers);+ headers.set('content-type', 'text/html; charset=utf-8');+ headers.set(+ 'content-security-policy',+ `default-src 'none'; img-src data:; style-src 'nonce-${nonce}'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`,+ );+ return new Response(+ `<!doctype html><html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)} · Kiln</title>+<style nonce="${nonce}">+:root{font-family:system-ui,sans-serif;color:#292821;background:#f6f4ef;color-scheme:light}+*{box-sizing:border-box}body{margin:0}main{max-width:42rem;margin:8vh auto;padding:1.5rem}+header{display:flex;align-items:baseline;flex-wrap:wrap;gap:.8rem;margin-bottom:2.5rem}header strong{font-size:1.7rem}header a{text-decoration:none;color:inherit}+header span,footer{font-size:.9rem;color:#59594f}h1{font-size:2rem;line-height:1.2;overflow-wrap:anywhere}+p,li{line-height:1.6}section{border:1px solid #d6d3c9;background:#fff;border-radius:.75rem;padding:1.5rem;margin:1.5rem 0}+h2{font-size:1.15rem;margin-top:0}button{font:inherit;font-weight:600;min-height:2.75rem;padding:.65rem 1.2rem;border:0;border-radius:.35rem;background:#3d5139;color:#fff;cursor:pointer}+button:focus-visible,a:focus-visible{outline:3px solid #a25c24;outline-offset:4px}a{color:#365231}code{overflow-wrap:anywhere}+article+article{border-top:1px solid #d6d3c9;margin-top:1.5rem;padding-top:1.5rem}article h3,article p{overflow-wrap:anywhere}+article form{display:flex;align-items:center;flex-wrap:wrap;gap:.75rem}select{font:inherit;min-height:2.75rem;border:1px solid #747775;border-radius:.35rem;background:#fff;color:#292821;padding:.4rem}+select:focus-visible{outline:3px solid #a25c24;outline-offset:4px}+.provider-buttons{display:flex;flex-wrap:wrap;gap:.75rem}.google-button{padding:0;background:transparent;line-height:0}+.google-button img{display:block;width:198px;height:44px}.github-button{width:198px;min-height:44px;padding:0;background:#fff;color:#1f1f1f;border:1px solid #747775;font-size:14px;font-weight:500}+.secondary{background:transparent;color:#365231;border:1px solid #747775}.permission-list{padding-left:1.25rem}.client-detail{overflow-wrap:anywhere}+footer{margin-top:2rem}footer nav{display:flex;gap:1rem;flex-wrap:wrap}+</style></head><body><main><header><strong><a href="/">Kiln</a></strong><span>by Instrukt Labs</span></header>+${content}<footer><nav aria-label="Support and policies"><a href="/account">Your account</a><a href="/privacy">Privacy</a><a href="/terms">Terms</a><a href="/support">Support</a>+<a href="https://github.com/instruktlabs/kiln">Open source</a></nav></footer></main></body></html>`,+ { ...options, headers },+ );+}diff --git a/hosting/src/http.ts b/hosting/src/http.tsindex 6807844b..2daa571b 100644--- a/hosting/src/http.ts+++ b/hosting/src/http.ts@@ -19,9 +19,14 @@ export async function readBounded(limit: number,signal?: AbortSignal,): Promise<Uint8Array<ArrayBuffer>> {+ if (signal?.aborted) {+ void body?.cancel().catch(() => {});+ throw new HttpFailure(499, 'Request cancelled');+ }if (!body) return new Uint8Array();const reader = body.getReader();- const chunks: Uint8Array[] = [];+ const deadlineAt = Date.now() + 10_000;+ let bytes = new Uint8Array(Math.min(limit, 64 * 1024));let length = 0;let timer: ReturnType<typeof setTimeout> | undefined;let onAbort: () => void = () => {};@@ -36,25 +41,35 @@ export async function readBounded(void reader.cancel().catch(() => {});}, 10_000);});+ void timeout.catch(() => {});+ const check = () => {+ if (signal?.aborted) throw new HttpFailure(499, 'Request cancelled');+ if (Date.now() >= deadlineAt) throw new HttpFailure(408, 'Request timed out');+ };try {- if (signal?.aborted) onAbort();for (;;) {+ check();const { done, value } = await Promise.race([reader.read(), timeout]);+ check();if (done) break;- length += value.byteLength;- if (length > limit) {- void reader.cancel().catch(() => {});+ const nextLength = length + value.byteLength;+ if (nextLength > limit) {throw new HttpFailure(413, 'Request too large');}- chunks.push(value);- }- const bytes = new Uint8Array(length);- let offset = 0;- for (const chunk of chunks) {- bytes.set(chunk, offset);- offset += chunk.byteLength;+ if (nextLength > bytes.byteLength) {+ const grown = new Uint8Array(Math.min(limit, Math.max(nextLength, bytes.byteLength * 2)));+ grown.set(bytes.subarray(0, length));+ bytes = grown;+ }+ // Copy before the next read; neither tiny chunks nor reused buffers retain+ // an unbounded collection of views or change previously received bytes.+ bytes.set(value, length);+ length = nextLength;}- return bytes;+ return bytes.byteLength === length ? bytes : bytes.slice(0, length);+ } catch (error) {+ void reader.cancel().catch(() => {});+ throw error;} finally {signal?.removeEventListener('abort', onAbort);if (timer !== undefined) clearTimeout(timer);@@ -69,7 +84,7 @@ export async function boundedRequest(request: Request, limit: number): Promise<Rthrow new HttpFailure(413, 'Request too large');}if (!request.body) return request;- const body = await readBounded(request.body, limit);+ const body = await readBounded(request.body, limit, request.signal);return new Request(request, { body });}diff --git a/hosting/src/identity-actions.ts b/hosting/src/identity-actions.tsnew file mode 100644index 00000000..9d6007ce--- /dev/null+++ b/hosting/src/identity-actions.ts@@ -0,0 +1,322 @@+import { IDENTITY_ISSUERS, type VerifiedIdentity } from './accounts';+import type { SignInEnv } from './auth';+import { BROWSER_COOKIE_ATTRIBUTES, browserToken, randomBrowserToken } from './browser-cookies';+import {+ clearBrowserSessionCookie,+ D1BrowserSessions,+ type BrowserSession,+} from './browser-sessions';+import { accountNoticePage } from './account-page';+import { githubAuthorizationUrl, githubIdentity } from './github';+import { googleAuthorizationUrl, googleIdentity } from './google';+import { HttpFailure, sha256 } from './http';+import type { SignInProvider } from './login-intents';++const COOKIE = '__Host-kiln-identity';+const clearCookie = `${COOKIE}=; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=0`;+const denied = () =>+ new HttpFailure(403, 'Sign-in method change unavailable; return to your account and try again');+const invalid = () =>+ new HttpFailure(+ 400,+ 'Invalid or expired sign-in confirmation; return to your account and try again',+ );+const isProvider = (value: unknown): value is SignInProvider =>+ value === 'google' || value === 'github';+const hash = (origin: string, kind: 'state' | 'binding', value: string) =>+ sha256(JSON.stringify(['kiln-identity-action-v1', origin, kind, value]));+interface Flow {+ purpose: 'link' | 'unlink';+ phase: 'confirm' | 'target';+ provider: SignInProvider;+ target: SignInProvider;+ confirmer: SignInProvider;+ confirmedSubject: string | null;+ confirmedAt: number | null;+ expiresAt: number;+ verifier: string;+ nonce: string;+}+const currentSession = `s.token_hash=? AND s.account_id=? AND s.account_epoch=?+ AND s.expires_at>? AND s.idle_expires_at>? AND a.state='active'+ AND a.authorization_epoch=s.account_epoch`;+const proofArgs = (proof: BrowserSession, now: number) => [+ proof.binding,+ proof.accountId,+ proof.accountEpoch,+ now,+ now,+];++/** Every phase is purpose-bound, browser-bound and consumed before provider I/O. */+async function redirect(+ request: Request,+ origin: string,+ env: SignInEnv,+ proof: BrowserSession,+ flow: Pick<+ Flow,+ 'purpose' | 'phase' | 'provider' | 'target' | 'confirmer' | 'confirmedSubject' | 'confirmedAt'+ >,+): Promise<Response> {+ const state = `ki1_${randomBrowserToken()}`,+ binding = randomBrowserToken();+ const verifier = randomBrowserToken(),+ nonce = randomBrowserToken(),+ now = Date.now();+ const previous = browserToken(request, origin, COOKIE);+ const database = env.ACCOUNTS.withSession('first-primary');+ const rows = await database.batch([+ database+ .prepare(`DELETE FROM kiln_identity_actions WHERE state_hash IN+ (SELECT state_hash FROM kiln_identity_actions WHERE expires_at<=? LIMIT 128)`)+ .bind(now),+ database+ .prepare('DELETE FROM kiln_identity_actions WHERE binding_hash=?')+ .bind(previous ? await hash(origin, 'binding', previous) : ''),+ database+ .prepare(`INSERT INTO kiln_identity_actions+ (state_hash,binding_hash,session_hash,account_id,account_epoch,purpose,phase,provider,target,confirmer,+ confirmed_subject,confirmed_at,verifier,nonce,expires_at)+ SELECT ?,?,s.token_hash,s.account_id,s.account_epoch,?,?,?,?,?,?,?,?,?,? FROM kiln_browser_sessions s+ JOIN kiln_accounts a ON a.id=s.account_id WHERE ${currentSession}+ AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?+ AND (? IS NULL OR i.subject=?))+ AND (SELECT COUNT(*) FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=?)=?+ AND (SELECT COUNT(*) FROM kiln_identity_actions WHERE account_id=s.account_id)<4+ AND (SELECT COUNT(*) FROM kiln_identity_actions)<4096 RETURNING state_hash`)+ .bind(+ await hash(origin, 'state', state),+ await hash(origin, 'binding', binding),+ flow.purpose,+ flow.phase,+ flow.provider,+ flow.target,+ flow.confirmer,+ flow.confirmedSubject,+ flow.confirmedAt,+ verifier,+ nonce,+ now + 300_000,+ ...proofArgs(proof, now),+ IDENTITY_ISSUERS[flow.confirmer],+ flow.confirmedSubject,+ flow.confirmedSubject,+ IDENTITY_ISSUERS[flow.target],+ flow.purpose === 'link' ? 0 : 1,+ ),+ ]);+ if (rows[2]?.results.length !== 1) throw denied();+ const location =+ flow.provider === 'google'+ ? await googleAuthorizationUrl(+ origin,+ { state, verifier, nonce, selectAccount: true },+ env,+ request.signal,+ )+ : await githubAuthorizationUrl(origin, state, verifier, env, true);+ return new Response(null, {+ status: 302,+ headers: {+ location,+ 'set-cookie': `${COOKIE}=${binding}; ${BROWSER_COOKIE_ATTRIBUTES}; Max-Age=300`,+ },+ });+}++export async function beginIdentityAction(+ request: Request,+ origin: string,+ env: SignInEnv,+): Promise<Response> {+ if (request.method !== 'POST')+ return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } });+ if (new URL(request.url).search || request.headers.get('origin') !== origin) throw denied();+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/x-www-form-urlencoded')+ throw new HttpFailure(415, 'Expected form data');+ const form = await request.formData(),+ fields = ['csrf', 'action', 'provider', 'target'];+ if (+ fields.some((field) => form.getAll(field).length !== 1) ||+ [...form.keys()].some((field) => !fields.includes(field))+ )+ throw denied();+ const purpose = form.get('action'),+ provider = form.get('provider'),+ target = form.get('target');+ // Unlink proves control of the method that will remain, never the one removed.+ if (+ (purpose !== 'link' && purpose !== 'unlink') ||+ !isProvider(provider) ||+ !isProvider(target) ||+ provider === target+ )+ throw denied();+ const proof = await new D1BrowserSessions(env.ACCOUNTS, origin).authorizeForm(+ request,+ String(form.get('csrf')),+ );+ return redirect(request, origin, env, proof, {+ purpose,+ provider,+ target,+ phase: 'confirm',+ confirmer: provider,+ confirmedSubject: null,+ confirmedAt: null,+ });+}++/** Called only with a consumed confirmation and freshly validated provider response. */+async function changeIdentity(+ env: SignInEnv,+ proof: BrowserSession,+ flow: Flow,+ confirmed: VerifiedIdentity,+ target: VerifiedIdentity,+) {+ const now = Date.now();+ if (+ now >= flow.expiresAt ||+ (flow.phase === 'target' &&+ (!flow.confirmedAt || now - flow.confirmedAt > 300_000 || flow.confirmedAt > now))+ )+ throw invalid();+ const database = env.ACCOUNTS.withSession('first-primary');+ const authorized = `EXISTS (SELECT 1 FROM kiln_browser_sessions s JOIN kiln_accounts a ON a.id=s.account_id+ WHERE ${currentSession} AND EXISTS (SELECT 1 FROM kiln_identities i WHERE i.account_id=s.account_id AND i.issuer=? AND i.subject=?))`;+ const args = [...proofArgs(proof, now), confirmed.issuer, confirmed.subject];+ const mutation =+ flow.purpose === 'link'+ ? database+ .prepare(`INSERT INTO kiln_identities (issuer,subject,account_id,created_at)+ SELECT ?,?,?,? WHERE ${authorized}+ AND NOT EXISTS (SELECT 1 FROM kiln_identities WHERE issuer=? AND (subject=? OR account_id=?))+ ON CONFLICT DO NOTHING`)+ .bind(+ target.issuer,+ target.subject,+ proof.accountId,+ now,+ ...args,+ target.issuer,+ target.subject,+ proof.accountId,+ )+ : database+ .prepare(`DELETE FROM kiln_identities WHERE account_id=? AND issuer=? AND ${authorized}+ AND (SELECT COUNT(*) FROM kiln_identities WHERE account_id=?)>1`)+ .bind(proof.accountId, target.issuer, ...args, proof.accountId);+ // Each of the next three statements depends on exactly one preceding change.+ // D1 batch is a transaction: identity, notification record, epoch and session+ // revocation either commit together or all roll back. No external I/O in between.+ const result = await database.batch([+ mutation,+ database+ .prepare(`INSERT INTO kiln_account_events(id,account_id,kind,provider,created_at)+ SELECT ?,?,?,?,? WHERE changes()=1`)+ .bind(crypto.randomUUID(), proof.accountId, flow.purpose, flow.target, now),+ database+ .prepare(`UPDATE kiln_accounts SET authorization_epoch=authorization_epoch+1+ WHERE id=? AND authorization_epoch=? AND changes()=1 RETURNING id`)+ .bind(proof.accountId, proof.accountEpoch),+ database+ .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=? AND changes()=1')+ .bind(proof.accountId),+ database+ .prepare(`DELETE FROM kiln_account_events WHERE id IN+ (SELECT id FROM kiln_account_events WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT -1 OFFSET 20)`)+ .bind(proof.accountId),+ ]);+ if (result[2]?.results.length !== 1) throw denied();+}++export async function finishIdentityAction(+ request: Request,+ origin: string,+ env: SignInEnv,+ provider: SignInProvider,+): Promise<Response> {+ const url = new URL(request.url),+ state = url.searchParams.get('state') ?? '';+ const binding = browserToken(request, origin, COOKIE);+ if (+ request.method !== 'GET' ||+ url.pathname !== `/oauth/${provider}/callback` ||+ url.searchParams.getAll('state').length !== 1 ||+ !/^ki1_[a-f0-9]{64}$/.test(state) ||+ !binding+ )+ throw invalid();+ let proof: BrowserSession;+ try {+ proof = await new D1BrowserSessions(env.ACCOUNTS, origin).read(request);+ } catch (error) {+ if (error instanceof HttpFailure && error.status === 401) throw invalid();+ throw error;+ }+ const flow = await env.ACCOUNTS.withSession('first-primary')+ .prepare(`DELETE FROM kiln_identity_actions+ WHERE state_hash=? AND binding_hash=? AND provider=? AND session_hash=? AND account_id=? AND account_epoch=? AND expires_at>?+ AND EXISTS (SELECT 1 FROM kiln_accounts a WHERE a.id=kiln_identity_actions.account_id AND a.state='active'+ AND a.authorization_epoch=kiln_identity_actions.account_epoch)+ RETURNING purpose,phase,provider,target,confirmer,confirmed_subject AS confirmedSubject,confirmed_at AS confirmedAt,+ expires_at AS expiresAt,verifier,nonce`)+ .bind(+ await hash(origin, 'state', state),+ await hash(origin, 'binding', binding),+ provider,+ proof.binding,+ proof.accountId,+ proof.accountEpoch,+ Date.now(),+ )+ .first<Flow>();+ if (!flow) throw invalid();+ if (url.searchParams.has('error'))+ return new Response('Confirmation was cancelled. Return to your account to try again.', {+ status: 400,+ headers: { 'set-cookie': clearCookie },+ });+ const code = url.searchParams.get('code');+ if (!code || code.length > 1024 || url.searchParams.getAll('code').length !== 1) throw invalid();+ const identity =+ provider === 'google'+ ? await googleIdentity(request, origin, { ...flow, state }, env)+ : await githubIdentity(code, flow.verifier, origin, env);+ if (Date.now() >= flow.expiresAt) throw invalid();+ if (flow.phase === 'confirm' && flow.purpose === 'link')+ return redirect(request, origin, env, proof, {+ ...flow,+ phase: 'target',+ provider: flow.target,+ confirmedSubject: identity.subject,+ confirmedAt: Date.now(),+ });+ const confirmed =+ flow.phase === 'confirm'+ ? identity+ : {+ issuer: IDENTITY_ISSUERS[flow.confirmer],+ subject: flow.confirmedSubject ?? '',+ };+ if (+ confirmed.issuer !== IDENTITY_ISSUERS[flow.confirmer] ||+ (flow.phase === 'target' && (flow.purpose !== 'link' || provider !== flow.target))+ )+ throw invalid();+ await changeIdentity(+ env,+ proof,+ flow,+ confirmed,+ flow.purpose === 'link' ? identity : { issuer: IDENTITY_ISSUERS[flow.target], subject: '' },+ );+ const response = accountNoticePage(+ flow.purpose === 'link' ? 'Sign-in method added' : 'Sign-in method removed',+ );+ response.headers.append('set-cookie', clearCookie);+ response.headers.append('set-cookie', clearBrowserSessionCookie);+ return response;+}diff --git a/hosting/src/material-index.ts b/hosting/src/material-index.tsnew file mode 100644index 00000000..82eba7b1--- /dev/null+++ b/hosting/src/material-index.ts@@ -0,0 +1,80 @@+import type { ArtifactStore } from './artifact-store';+import { HttpFailure } from './http';++const id = /^[a-z][a-z0-9_-]{0,79}(?![\s\S])/;+const revision = /^sha256:[a-f0-9]{64}(?![\s\S])/;+const cursor = /^materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}(?![\s\S])/;+const fileId = /^[a-f0-9]{32}(?![\s\S])/;+const allowedFiles = new Set([+ 'manifest.json',+ 'baseColor.png',+ 'normal.png',+ 'metallicRoughness.png',+ 'emissive.png',+ 'occlusion.png',+]);+const invalid = () => new HttpFailure(400, 'Invalid saved material');+function object(value: unknown): Record<string, unknown> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid();+ return value as Record<string, unknown>;+}+function key(materialId: unknown, revisionId: unknown): string {+ if (+ typeof materialId !== 'string' ||+ !id.test(materialId) ||+ typeof revisionId !== 'string' ||+ !revision.test(revisionId)+ )+ throw invalid();+ return `materials/${materialId}/${revisionId.slice(7)}`;+}++/** Tenant ownership and immutable pins; the native SDK verifies material contents. */+export class MaterialIndex {+ constructor(private readonly artifacts: ArtifactStore) {}++ commit(input: unknown) {+ const value = object(input);+ if (Object.keys(value).some((name) => !['materialId', 'revisionId', 'files'].includes(name)))+ throw invalid();+ const logicalKey = key(value.materialId, value.revisionId);+ const entries = Object.entries(object(value.files));+ if (+ entries.length < 2 ||+ entries.length > 6 ||+ !entries.some(([name]) => name === 'manifest.json') ||+ entries.some(+ ([name, value]) =>+ !allowedFiles.has(name) || typeof value !== 'string' || !fileId.test(value),+ )+ )+ throw invalid();+ const files = Object.fromEntries(entries) as Record<string, string>;+ this.artifacts.assertFileNames(files);+ return this.artifacts.save({+ key: logicalKey,+ files,+ metadata: {+ kind: 'kiln.hosted-material.v1',+ materialId: value.materialId,+ revisionId: value.revisionId,+ },+ });+ }++ read(materialId: unknown, revisionId: unknown) {+ return this.artifacts.groupByKey(key(materialId, revisionId));+ }++ list(input: unknown) {+ const value = object(input);+ const after = value.after ?? '';+ if (+ Object.keys(value).some((name) => name !== 'after') ||+ typeof after !== 'string' ||+ (after !== '' && !cursor.test(after))+ )+ throw invalid();+ return this.artifacts.groupPage('materials/', after);+ }+}diff --git a/hosting/src/native-assets.ts b/hosting/src/native-assets.tsindex 86a7948c..6e9ed99d 100644--- a/hosting/src/native-assets.ts+++ b/hosting/src/native-assets.ts@@ -16,6 +16,7 @@ import { createMaterialLibraryPayload } from '@instruktlabs/kiln/material-librarimport type { MaterialLibrary, MaterialRecordV1 } from '../../src/material-library';import { programReference } from '../../src/program-store';import { NativeHttpClient, StorageFailure, type NativeStorageOptions } from './native-http';+import { DOWNLOAD_FILES, DOWNLOAD_TOKEN } from './download-path';type Group = {id: string;@@ -64,7 +65,11 @@ async function hash(bytes: Uint8Array): Promise<string> {export class NativeAssetLibrary implements AssetLibrary {private readonly http: NativeHttpClient;constructor(- private readonly options: NativeStorageOptions & { materials?: MaterialLibrary } = {},+ private readonly options: NativeStorageOptions & {+ materials?: MaterialLibrary;+ /** Host-only proof for newly evaluated saves; imports retain original provenance. */+ executionIdentity?: (draft: Pick<AssetDraft, 'code' | 'glb'>) => string;+ } = {},) {this.http = new NativeHttpClient({ ...options, timeoutMs: options.timeoutMs ?? 60_000 },@@ -360,11 +365,26 @@ export class NativeAssetLibrary implements AssetLibrary {}async save(target: string, draft: AssetDraft): Promise<AssetManifest> {collection(target);+ const code = draft.code,+ glb = Uint8Array.from(draft.glb);+ const build = draft.build+ ? { ...draft.build, rebuild: draft.build.rebuild ?? ('engine-required' as const) }+ : undefined;+ if (this.options.executionIdentity) {+ if (!build) throw new Error('Saved asset has no matching verified evaluation');+ const engine = this.options.executionIdentity({ code, glb });+ if (+ typeof engine !== 'string' ||+ !/^cloudflare-container:sha256:[a-f0-9]{64}(?![\s\S])/.test(engine)+ )+ throw new Error('Saved asset has no matching verified evaluation');+ build.engine = engine;+ }const assetId = identity(draft.assetId ?? `a_${crypto.randomUUID().replaceAll('-', '')}`);if (draft.parentRevision) await this.read(target, assetId, draft.parentRevision);- if (draft.code !== undefined) await programReference(draft.code);- const files: Record<string, Uint8Array> = { 'asset.glb': Uint8Array.from(draft.glb) };- if (draft.code !== undefined) files['source.kiln.js'] = new TextEncoder().encode(draft.code);+ if (code !== undefined) await programReference(code);+ const files: Record<string, Uint8Array> = { 'asset.glb': glb };+ if (code !== undefined) files['source.kiln.js'] = new TextEncoder().encode(code);if (draft.preview) files['preview.png'] = Uint8Array.from(draft.preview);const inventory: AssetManifest['files'] = {};for (const [name, bytes] of Object.entries(files))@@ -380,11 +400,9 @@ export class NativeAssetLibrary implements AssetLibrary {description: draft.description,brief: draft.brief,attribution: draft.attribution,- editable: draft.code !== undefined,+ editable: code !== undefined,files: inventory,- build: draft.build- ? { ...draft.build, rebuild: draft.build.rebuild ?? 'engine-required' }- : undefined,+ build,preview: draft.previewInfo,});const [record] = await this.prepare([{ manifest, files }]);@@ -394,6 +412,39 @@ export class NativeAssetLibrary implements AssetLibrary {async exportBundle(input: AssetRecord[]): Promise<Uint8Array> {return encodeAssetBundle(await this.prepare(input));}+ /** Browser delivery uses the current Kiln account; links never embed a tenant or bearer credential. */+ async downloadUrls(+ publicOrigin: string,+ target: string,+ assetId: string,+ revisionId: string,+ ): Promise<Record<string, string>> {+ const origin = new URL(publicOrigin);+ if (origin.protocol !== 'https:' || origin.origin !== publicOrigin)+ throw new Error('Invalid public origin');+ const raw = await this.json('/internal/downloads', {+ collection: collection(target),+ assetId: identity(assetId),+ revisionId: identity(revisionId),+ });+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw failure();+ const value = raw as { ticket: string; expiresAt: number; files: string[] };+ if (+ typeof value.ticket !== 'string' ||+ !DOWNLOAD_TOKEN.test(value.ticket) ||+ !Number.isSafeInteger(value.expiresAt) ||+ value.expiresAt <= Date.now() ||+ !Array.isArray(value.files) ||+ !value.files.length ||+ value.files.length > DOWNLOAD_FILES.size ||+ new Set(value.files).size !== value.files.length ||+ value.files.some((name) => typeof name !== 'string' || !DOWNLOAD_FILES.has(name))+ )+ throw failure();+ return Object.fromEntries(+ value.files.map((name) => [name, `${publicOrigin}/downloads/${value.ticket}/${name}`]),+ );+ }/** Host UI/account operation; the engine's MCP registry defines no extra delete tool. */async deleteRevision(target: string, assetId: string, revisionId: string): Promise<void> {const group = await this.find(target, assetId, revisionId);diff --git a/hosting/src/native-build-identity.ts b/hosting/src/native-build-identity.tsnew file mode 100644index 00000000..6c514289--- /dev/null+++ b/hosting/src/native-build-identity.ts@@ -0,0 +1,35 @@+import { createHash } from 'node:crypto';+import type { AssetDraft } from '@instruktlabs/kiln/assets';++const unavailable = () => new Error('Saved asset has no matching verified evaluation');+const hash = (bytes: string | Uint8Array) => createHash('sha256').update(bytes).digest('hex');+function key(code: string | undefined, glb: Uint8Array): string {+ if (+ typeof code !== 'string' ||+ Buffer.byteLength(code) > 1024 * 1024 ||+ !(glb instanceof Uint8Array) ||+ glb.byteLength === 0 ||+ glb.byteLength > 4 * 1024 * 1024+ )+ throw unavailable();+ return `${hash(code)}:${hash(glb)}`;+}++/** One admitted request's accepted evaluations; never persisted or supplied by authored source. */+export class NativeBuildIdentities {+ private readonly records = new Map<string, string>();+ record(code: string, glb: Uint8Array, image: string | undefined): void {+ if (typeof image !== 'string' || !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(image))+ throw unavailable();+ const id = key(code, glb),+ value = `cloudflare-container:${image}`;+ const prior = this.records.get(id);+ if ((prior && prior !== value) || (!prior && this.records.size >= 16)) throw unavailable();+ this.records.set(id, value);+ }+ forDraft(draft: Pick<AssetDraft, 'code' | 'glb'>): string {+ const value = this.records.get(key(draft.code, draft.glb));+ if (!value) throw unavailable();+ return value;+ }+}diff --git a/hosting/src/native-evaluator.ts b/hosting/src/native-evaluator.tsnew file mode 100644index 00000000..937b4eff--- /dev/null+++ b/hosting/src/native-evaluator.ts@@ -0,0 +1,84 @@+import {+ createEvaluatorPortV2,+ EvaluatorPortError,+ type EvaluatorPortV2,+} from '@instruktlabs/kiln/evaluator';+import { NativeHttpClient, StorageFailure } from './native-http';++export interface NativeEvaluatorOptions {+ fetch?: (request: Request) => Promise<Response>;+}+type EvaluationResult = Awaited<ReturnType<EvaluatorPortV2['render']>>;+export interface NativeEvaluatorPort extends EvaluatorPortV2 {+ executionImage(result: EvaluationResult): string | undefined;+}++/** Validate first; clamping must not turn NaN, zero or negative controls into authority. */+function capped(value: number | undefined, max: number): number {+ if (value === undefined) return max;+ if (!Number.isSafeInteger(value) || value < 1) throw new EvaluatorPortError('INPUT_INVALID');+ return Math.min(value, max);+}++/**+ * The host's protocol client, never an in-process evaluator. The controller binds+ * a fresh isolated job to this fixed virtual hostname outside the native host.+ * A deadline/cancellation result alone does not establish VM cleanup or release+ * global admission; the controller must retain its lease until destruction.+ */+export function createNativeEvaluatorPort(+ options: NativeEvaluatorOptions = {},+): NativeEvaluatorPort {+ const verified = new WeakMap<EvaluationResult, string>();+ return {+ executionImage: (result) => verified.get(result),+ async render(code, renderOptions, controls = {}) {+ let image: string | undefined;+ // Per-call closure: overlapping responses cannot exchange their image identities.+ const port = createEvaluatorPortV2(async (json, controls) => {+ const body = new TextEncoder().encode(json);+ if (body.byteLength > 4 * 1024 * 1024) throw new EvaluatorPortError('INPUT_INVALID');+ const client = new NativeHttpClient(+ { fetch: options.fetch, timeoutMs: controls.deadlineMs, signal: () => controls.signal },+ 'Evaluator',+ 'evaluator',+ );+ try {+ const result = await client.bytes('/evaluate', {+ method: 'POST',+ body,+ headers: {+ 'content-type': 'application/json',+ 'x-kiln-deadline-ms': String(controls.deadlineMs),+ 'x-kiln-max-response-bytes': String(controls.maxResponseBytes),+ },+ limit: controls.maxResponseBytes,+ onResponseHeaders: (headers) => {+ const value = headers.get('x-kiln-execution-image');+ if (!value || !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(value))+ throw new Error('Missing verified evaluation identity');+ image = value;+ },+ });+ return new TextDecoder('utf-8', { fatal: true }).decode(result);+ } catch (error) {+ if (error instanceof StorageFailure && error.status === 504)+ throw new EvaluatorPortError('DEADLINE_EXCEEDED');+ if (error instanceof StorageFailure && error.status === 499)+ throw new EvaluatorPortError('CANCELLED');+ // The SDK maps other transport failures to a fixed WORKER_FAILED message.+ throw error;+ }+ });+ const result = await port.render(code, renderOptions, {+ signal: controls.signal,+ deadlineMs: capped(controls.deadlineMs, 60_000),+ maxGlbBytes: capped(controls.maxGlbBytes, 4 * 1024 * 1024),+ maxResponseBytes: capped(controls.maxResponseBytes, 8 * 1024 * 1024),+ });+ if (!image) throw new EvaluatorPortError('WORKER_FAILED');+ verified.set(result, image);+ return result;+ },+ };+}diff --git a/hosting/src/native-host.ts b/hosting/src/native-host.tsnew file mode 100644index 00000000..e2e641f7--- /dev/null+++ b/hosting/src/native-host.ts@@ -0,0 +1,53 @@+import { createServer } from 'node:http';+import { toNodeHandler, type FetchLikeMcpHandler } from '@modelcontextprotocol/node';++/** Private port adapter. Only the externally scoped VM controller may reach it. */+export function createNativeHttpServer(+ handler: FetchLikeMcpHandler,+ options: { requestTimeoutMs?: number } = {},+) {+ const timeout = options.requestTimeoutMs ?? 10_000;+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 10_000)+ throw new Error('Invalid native upload deadline');+ const adapter = toNodeHandler(handler, { maxRequestBodySize: 1024 * 1024, onerror: () => {} });+ const server = createServer(+ {+ requestTimeout: timeout,+ headersTimeout: timeout,+ connectionsCheckingInterval: Math.min(1000, timeout),+ keepAliveTimeout: 5000,+ maxHeaderSize: 16 * 1024,+ },+ (request, response) => {+ const refuse = (status: number) => {+ response.writeHead(status, {+ 'content-type': 'text/plain',+ 'cache-control': 'no-store',+ connection: 'close',+ });+ response.end('Invalid native request', () => request.destroy());+ };+ if (request.headers.host !== 'kiln-native.internal') return refuse(421);+ if (request.url === '/_ready' && request.method === 'GET') {+ response.writeHead(204, { 'cache-control': 'no-store' });+ response.end();+ return;+ }+ if (request.url !== '/mcp') return refuse(404);+ const declared = request.headers['content-length'];+ if (declared !== undefined && (!/^\d+$/.test(declared) || Number(declared) > 1024 * 1024))+ return refuse(413);+ // The SDK buffers the request before calling fetch. Bound that phase as well+ // as the handler's own execution deadline; disconnects are propagated by SDK.+ const timer = setTimeout(() => request.destroy(), timeout);+ timer.unref();+ const clear = () => clearTimeout(timer);+ request.once('end', clear);+ request.once('close', clear);+ void adapter(request, response).catch(() => response.destroy());+ },+ );+ server.maxConnections = 4;+ server.maxRequestsPerSocket = 16;+ return server;+}diff --git a/hosting/src/native-http.ts b/hosting/src/native-http.tsindex b7c53735..a6e71c3d 100644--- a/hosting/src/native-http.ts+++ b/hosting/src/native-http.ts@@ -10,6 +10,8 @@ export interface NativeStorageRequest {headers?: Record<string, string>;limit: number;statuses?: readonly number[];+ /** Synchronous validation of metadata from the fixed private service. */+ onResponseHeaders?: (headers: Headers) => void;}export class StorageFailure extends Error {constructor(@@ -23,25 +25,34 @@ export class StorageFailure extends Error {export class NativeHttpClient {private readonly timeoutMs: number;private readonly send: (request: Request) => Promise<Response>;+ private readonly origin: string;constructor(private readonly options: NativeStorageOptions = {},private readonly label = 'Storage',+ private readonly service: 'storage' | 'evaluator' | 'renderer' = 'storage',) {+ if (service !== 'storage' && service !== 'evaluator' && service !== 'renderer')+ throw new Error('Invalid private service');+ this.origin = `http://kiln-${service}.internal`;this.timeoutMs = options.timeoutMs ?? 15_000;if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 60_000)throw new Error('Invalid storage timeout');this.send = options.fetch ?? ((request) => fetch(request));}async bytes(path: string, request: NativeStorageRequest): Promise<Uint8Array> {- const { body, limit, headers, method = 'GET', statuses = [200] } = request;- const url = new URL(path, 'http://kiln-storage.internal');+ const { body, limit, headers, method = 'GET', statuses = [200], onResponseHeaders } = request;+ const url = new URL(path, this.origin);if (- url.href !== `http://kiln-storage.internal${path}` ||+ url.href !== `${this.origin}${path}` ||url.search ||url.hash ||- !(path.startsWith('/internal/') || /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path))+ !(this.service === 'evaluator'+ ? path === '/evaluate'+ : this.service === 'renderer'+ ? path === '/render'+ : path.startsWith('/internal/') || /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path)))- throw new Error('Invalid private storage path');+ throw new Error('Invalid private service path');if (!Number.isSafeInteger(limit) ||limit < 0 ||@@ -50,18 +61,37 @@ export class NativeHttpClient {)throw new Error('Invalid storage size limit');const outgoing = new Headers(headers);+ const allowedHeaders =+ this.service !== 'storage'+ ? ['content-type', 'x-kiln-deadline-ms', 'x-kiln-max-response-bytes']+ : ['content-type', 'x-artifact-name', 'x-artifact-sha256'];for (const name of outgoing.keys())- if (!['content-type', 'x-artifact-name', 'x-artifact-sha256'].includes(name))- throw new Error('Invalid private storage header');+ if (!allowedHeaders.includes(name)) throw new Error('Invalid private service header');if (body !== undefined) outgoing.set('content-length', String(body.byteLength));const parent = this.options.signal?.();if (parent?.aborted) throw new StorageFailure(499, `${this.label} request cancelled`);const controller = new AbortController();+ const deadlineAt = Date.now() + this.timeoutMs;const cancel = () => controller.abort();let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;+ let responseBody: ReadableStream<Uint8Array> | null | undefined;let timedOut = false;let finished = false;let abortListener: () => void = () => {};+ const expired = () => {+ if (Date.now() >= deadlineAt) {+ timedOut = true;+ controller.abort();+ }+ return controller.signal.aborted;+ };+ const check = () => {+ if (expired())+ throw new StorageFailure(+ timedOut ? 504 : 499,+ timedOut ? `${this.label} request timed out` : `${this.label} request cancelled`,+ );+ };const aborted = new Promise<never>((_, reject) => {abortListener = () => {reject(@@ -89,11 +119,13 @@ export class NativeHttpClient {signal: controller.signal,});const pending = this.send(request).then((response) => {+ responseBody = response.body;// Even a non-cooperative injected transport cannot leave a late body open.- if (finished || controller.signal.aborted) void response.body?.cancel().catch(() => {});+ if (finished || expired()) void response.body?.cancel().catch(() => {});return response;});const response = await Promise.race([pending, aborted]);+ check();if (!statuses.includes(response.status)) {void response.body?.cancel().catch(() => {});throw new StorageFailure(@@ -108,33 +140,37 @@ export class NativeHttpClient {void response.body?.cancel().catch(() => {});throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);}+ onResponseHeaders?.(new Headers(response.headers));if (!response.body) {if (declared !== null && Number(declared) !== 0)throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);return new Uint8Array();}reader = response.body.getReader();- const chunks: Uint8Array[] = [];+ let bytes = new Uint8Array(Math.min(limit, 64 * 1024));let length = 0;for (;;) {+ // Continuously available chunks can starve timers with microtasks.+ check();const { done, value } = await Promise.race([reader.read(), aborted]);+ check();if (done) break;- length += value.byteLength;- if (length > limit) {+ const nextLength = length + value.byteLength;+ if (nextLength > limit) {void reader.cancel().catch(() => {});throw new StorageFailure(502, `${this.label} response exceeds its size limit`);}- chunks.push(value);+ if (nextLength > bytes.byteLength) {+ const grown = new Uint8Array(Math.min(limit, Math.max(nextLength, bytes.byteLength * 2)));+ grown.set(bytes.subarray(0, length));+ bytes = grown;+ }+ bytes.set(value, length);+ length = nextLength;}if (declared !== null && Number(declared) !== length)throw new StorageFailure(502, `Invalid ${this.label.toLowerCase()} response`);- const bytes = new Uint8Array(length);- let offset = 0;- for (const chunk of chunks) {- bytes.set(chunk, offset);- offset += chunk.byteLength;- }- return bytes;+ return bytes.byteLength === length ? bytes : bytes.slice(0, length);} catch (error) {if (error instanceof StorageFailure) throw error;if (controller.signal.aborted)@@ -149,6 +185,9 @@ export class NativeHttpClient {clearTimeout(timer);parent?.removeEventListener('abort', cancel);controller.signal.removeEventListener('abort', abortListener);+ // Cancellation can win after headers arrive but before a reader attaches.+ // Also close a partially read stream on any validation/read failure.+ void (reader ? reader.cancel() : responseBody?.cancel())?.catch(() => {});reader?.releaseLock();}}diff --git a/hosting/src/native-materials.ts b/hosting/src/native-materials.tsnew file mode 100644index 00000000..8a8eaf3b--- /dev/null+++ b/hosting/src/native-materials.ts@@ -0,0 +1,292 @@+import {+ canonicalMaterialJson,+ MATERIAL_LIBRARY_LIMITS,+ validateMaterialRecordShape,+ type MaterialLibrary,+ type MaterialManifestV1,+ type MaterialRecordV1,+} from '@instruktlabs/kiln/material-library';+import {+ validateMaterialManifestIdentity,+ verifyMaterialRecordV1,+} from '@instruktlabs/kiln/material-library/node';+import { NativeHttpClient, StorageFailure, type NativeStorageOptions } from './native-http';++const BATCH_BYTES = 64 * 1024 * 1024;+const id = /^[a-z][a-z0-9_-]{0,79}(?![\s\S])/;+const revision = /^sha256:[a-f0-9]{64}(?![\s\S])/;+const fileId = /^[a-f0-9]{32}(?![\s\S])/;+const cursor = /^materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}(?![\s\S])/;+const filesAllowed = new Set([+ 'manifest.json',+ 'baseColor.png',+ 'normal.png',+ 'metallicRoughness.png',+ 'emissive.png',+ 'occlusion.png',+]);+const text = (bytes: Uint8Array) => new TextDecoder('utf-8', { fatal: true }).decode(bytes);+const jsonBytes = (value: unknown) => new TextEncoder().encode(canonicalMaterialJson(value));+const failure = () => new Error('Saved material integrity check failed');+type Group = {+ id: string;+ key: string;+ files: Record<string, string>;+ metadata: { kind: string; materialId: string; revisionId: string };+};+function identity(materialId: string, revisionId: string): string {+ if (+ typeof materialId !== 'string' ||+ !id.test(materialId) ||+ typeof revisionId !== 'string' ||+ !revision.test(revisionId)+ )+ throw new Error('Invalid material identity');+ return `materials/${materialId}/${revisionId.slice(7)}`;+}+async function hash(bytes: Uint8Array): Promise<string> {+ return Array.from(+ new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))),+ (byte) => byte.toString(16).padStart(2, '0'),+ ).join('');+}++/** Durable per-tenant materials using the installed engine's verification contract. */+export class NativeMaterialLibrary implements MaterialLibrary {+ private readonly http: NativeHttpClient;+ constructor(private readonly options: NativeStorageOptions = {}) {+ this.http = new NativeHttpClient(+ { ...options, timeoutMs: options.timeoutMs ?? 60_000 },+ 'Material storage',+ );+ }+ private async json(path: string, input?: unknown, limit = 4096): Promise<unknown> {+ const bytes = await this.http.bytes(path, {+ method: input === undefined ? 'GET' : 'POST',+ body: input === undefined ? undefined : jsonBytes(input),+ headers: input === undefined ? undefined : { 'content-type': 'application/json' },+ limit,+ statuses: [200, 201],+ });+ try {+ return JSON.parse(text(bytes));+ } catch {+ throw failure();+ }+ }+ private group(raw: unknown, materialId?: string, revisionId?: string): Group {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw failure();+ const value = raw as Group;+ const meta = value.metadata;+ if (+ typeof value.id !== 'string' ||+ !fileId.test(value.id) ||+ !meta ||+ typeof meta !== 'object' ||+ Array.isArray(meta) ||+ Object.keys(meta).some((name) => !['kind', 'materialId', 'revisionId'].includes(name)) ||+ meta.kind !== 'kiln.hosted-material.v1' ||+ (materialId !== undefined && meta.materialId !== materialId) ||+ (revisionId !== undefined && meta.revisionId !== revisionId) ||+ value.key !== identity(meta.materialId, meta.revisionId) ||+ !value.files ||+ typeof value.files !== 'object' ||+ Array.isArray(value.files) ||+ !value.files['manifest.json'] ||+ Object.keys(value.files).length < 2 ||+ Object.entries(value.files).some(+ ([name, value]) =>+ !filesAllowed.has(name) || typeof value !== 'string' || !fileId.test(value),+ )+ )+ throw failure();+ return value;+ }+ private async find(materialId: string, revisionId: string): Promise<Group | undefined> {+ const path = `/internal/${identity(materialId, revisionId)}`;+ try {+ return this.group(await this.json(path), materialId, revisionId);+ } catch (error) {+ if (error instanceof StorageFailure && error.status === 404) return undefined;+ throw error;+ }+ }+ private download(id: string, limit: number): Promise<Uint8Array> {+ if (!fileId.test(id)) throw failure();+ return this.http.bytes(`/mcp/artifacts/${id}`, { limit });+ }+ private async manifest(group: Group): Promise<MaterialManifestV1> {+ const manifest = validateMaterialManifestIdentity(+ JSON.parse(+ text(+ await this.download(+ group.files['manifest.json']!,+ MATERIAL_LIBRARY_LIMITS.maxManifestBytes,+ ),+ ),+ ),+ );+ if (+ manifest.materialId !== group.metadata.materialId ||+ manifest.revisionId !== group.metadata.revisionId ||+ Object.keys(group.files).length !== manifest.maps.length + 1 ||+ manifest.maps.some((map) => !group.files[map.file])+ )+ throw failure();+ return manifest;+ }+ async read(materialId: string, revisionId: string): Promise<MaterialRecordV1> {+ const group = await this.find(materialId, revisionId);+ if (!group) throw new Error('Saved material not found');+ const manifest = await this.manifest(group);+ const files: Record<string, Uint8Array> = {};+ for (const map of manifest.maps)+ files[map.file] = await this.download(group.files[map.file]!, map.bytes);+ const record = { manifest, files };+ await verifyMaterialRecordV1(record);+ return record;+ }+ async list(): Promise<MaterialManifestV1[]> {+ const records: MaterialManifestV1[] = [];+ let after = '';+ let bytes = 0;+ for (;;) {+ const page = (await this.json(+ '/internal/materials/list',+ after ? { after } : {},+ 128 * 1024,+ )) as { records: unknown[]; next: string | null };+ if (+ !page ||+ !Array.isArray(page.records) ||+ page.records.length > 32 ||+ (page.next !== null &&+ (typeof page.next !== 'string' || !cursor.test(page.next) || page.next <= after))+ )+ throw failure();+ let previous = after;+ for (const raw of page.records) {+ const group = this.group(raw);+ if (group.key <= previous) throw failure();+ previous = group.key;+ const manifest = await this.manifest(group);+ bytes += jsonBytes(manifest).length;+ if (bytes > BATCH_BYTES || records.length >= 10_000)+ throw new Error('Material catalogue exceeds host response limits');+ records.push(manifest);+ }+ if (page.next === null) break;+ if (page.records.length !== 32 || page.next !== previous) throw failure();+ after = page.next;+ }+ return records;+ }+ private async prepare(input: MaterialRecordV1[]): Promise<MaterialRecordV1[]> {+ if (!Array.isArray(input) || !input.length || input.length > 100)+ throw new Error('Import requires 1..100 material revisions');+ let bytes = 0;+ let pixels = 0;+ const keys = new Set<string>();+ for (const record of input) {+ const manifest = validateMaterialRecordShape(record);+ const key = identity(manifest.materialId, manifest.revisionId);+ if (keys.has(key)) throw new Error('Duplicate material revision');+ keys.add(key);+ bytes += jsonBytes(manifest).length;+ for (const map of manifest.maps) {+ bytes += map.bytes;+ pixels += map.width * map.height;+ }+ if (bytes > BATCH_BYTES || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)+ throw new Error('Material batch exceeds host byte or pixel limits');+ }+ // Copy all caller-owned buffers before the first asynchronous verification.+ const records = input.map((record) => ({+ manifest: structuredClone(record.manifest),+ files: Object.fromEntries(+ Object.entries(record.files).map(([name, bytes]) => [name, Uint8Array.from(bytes)]),+ ),+ }));+ for (const record of records) await verifyMaterialRecordV1(record);+ return records;+ }+ private async same(record: MaterialRecordV1): Promise<boolean> {+ const existing = await this.read(record.manifest.materialId, record.manifest.revisionId);+ return canonicalMaterialJson(existing.manifest) === canonicalMaterialJson(record.manifest);+ }+ private async publish(record: MaterialRecordV1): Promise<void> {+ const { materialId, revisionId } = record.manifest;+ if (await this.find(materialId, revisionId)) {+ if (!(await this.same(record))) throw new Error('Saved material revision is immutable');+ return;+ }+ const files: Record<string, string> = {};+ let committed = false;+ try {+ for (const [name, data] of Object.entries({+ ...record.files,+ 'manifest.json': jsonBytes(record.manifest),+ })) {+ const bytes = Uint8Array.from(data);+ const digest = await hash(bytes);+ const receipt = JSON.parse(+ text(+ await this.http.bytes('/internal/artifacts', {+ method: 'POST',+ body: bytes,+ limit: 2048,+ statuses: [201],+ headers: {+ 'content-type': name === 'manifest.json' ? 'application/json' : 'image/png',+ 'x-artifact-name': name,+ 'x-artifact-sha256': digest,+ },+ }),+ ),+ );+ if (+ !receipt ||+ typeof receipt.id !== 'string' ||+ !fileId.test(receipt.id) ||+ receipt.bytes !== bytes.length ||+ receipt.sha256 !== digest+ )+ throw failure();+ files[name] = receipt.id;+ }+ try {+ this.group(+ await this.json('/internal/materials/commit', { materialId, revisionId, files }),+ materialId,+ revisionId,+ );+ committed = true;+ } catch (error) {+ if (!(error instanceof StorageFailure) || error.status !== 409) throw error;+ if (!(await this.same(record))) throw new Error('Saved material revision is immutable');+ }+ } finally {+ if (!committed && Object.keys(files).length) {+ // Pins protect committed data even when its acknowledgement was lost.+ // Failed cleanup stays quota-counted until normal unsaved-work expiry.+ const cleanup = new NativeHttpClient(+ { ...this.options, signal: undefined, timeoutMs: 5000 },+ 'Material cleanup',+ );+ await cleanup+ .bytes('/internal/artifacts/discard', {+ method: 'POST',+ body: jsonBytes(Object.values(files)),+ headers: { 'content-type': 'application/json' },+ limit: 1024,+ })+ .catch(() => {});+ }+ }+ }+ async import(input: MaterialRecordV1[]): Promise<MaterialManifestV1[]> {+ const records = await this.prepare(input);+ for (const record of records) await this.publish(record);+ return records.map((record) => record.manifest);+ }+}diff --git a/hosting/src/native-mcp.ts b/hosting/src/native-mcp.tsindex 4aa06346..52246f33 100644--- a/hosting/src/native-mcp.ts+++ b/hosting/src/native-mcp.ts@@ -1,35 +1,51 @@import { createMcpHandler, type Server } from '@modelcontextprotocol/server';import type { KilnToolContext } from '@instruktlabs/kiln/tools';import type { EvaluatorPortV2, IsolatedEvaluatorHost } from '@instruktlabs/kiln/evaluator';+import type { PbrRenderPort } from '@instruktlabs/kiln/composer';import { NativeProgramStore } from './native-programs';import { NativeAssetLibrary } from './native-assets';+import { NativeMaterialLibrary } from './native-materials';+import { NativeMaterialWorkspace } from './native-workspace';import type { NativeStorageOptions } from './native-http';+import {+ createNativeEvaluatorPort,+ type NativeEvaluatorOptions,+ type NativeEvaluatorPort,+} from './native-evaluator';+import { NativeBuildIdentities } from './native-build-identity';import { HttpFailure, privateResponse, readBounded, serviceFailure } from './http';+import { createNativeRenderPort } from './native-render';+import { RENDER_LIMITS } from './render-limits';export interface NativeMcpRuntime {createServer: (context: KilnToolContext) => Server;- evaluatorPort: EvaluatorPortV2;+ evaluatorPort: EvaluatorPortV2 & Partial<Pick<NativeEvaluatorPort, 'executionImage'>>;+ viewRenderPort?: PbrRenderPort;}-/** Installed-package production route. A failed isolation probe has no fallback. */-export async function loadNativeMcpRuntime(- host: IsolatedEvaluatorHost = { bwrapPath: '/usr/bin/bwrap' },-): Promise<NativeMcpRuntime> {- let engine: { createKilnMcpServer: NativeMcpRuntime['createServer'] };- let evaluator: typeof import('@instruktlabs/kiln/evaluator');+async function loadInstalledEngine(): Promise<NativeMcpRuntime['createServer']> {try {const entry = new URL(import.meta.resolve('@instruktlabs/kiln'));// This private host pins the engine's shipped bundle alongside its SDK.// Do not resolve a checkout source file or a caller-supplied module URL.- engine = await import(new URL('../dist/mcp-engine.mjs', entry).href);- evaluator = await import('@instruktlabs/kiln/evaluator');+ const engine = await import(new URL('../dist/mcp-engine.mjs', entry).href);+ if (typeof engine.createKilnMcpServer !== 'function') throw new Error('Invalid engine');+ return engine.createKilnMcpServer;} catch {throw new Error('Native engine installation is unavailable');}+}++/** Installed-package nested-isolation route. A failed probe has no fallback. */+export async function loadNativeMcpRuntime(+ host: IsolatedEvaluatorHost = { bwrapPath: '/usr/bin/bwrap' },+): Promise<NativeMcpRuntime> {+ const createServer = await loadInstalledEngine();try {+ const evaluator = await import('@instruktlabs/kiln/evaluator');await evaluator.assertIsolatedEvaluatorReady(host);return {- createServer: engine.createKilnMcpServer,+ createServer,evaluatorPort: {render: (code, options, controls) =>evaluator.renderGLBViaIsolatedEvaluator(code, options, { ...controls, host }),@@ -40,6 +56,22 @@ export async function loadNativeMcpRuntime(}}+/**+ * Explicit externally isolated profile. The controller supplies the private+ * evaluator route; unavailable transport fails closed on calls. Never selected+ * automatically after a failed nested-isolation readiness check.+ */+export async function loadContainerMcpRuntime(+ options: NativeEvaluatorOptions = {},+ rendering: { fetch?: (request: Request) => Promise<Response> } = {},+): Promise<NativeMcpRuntime> {+ return {+ createServer: await loadInstalledEngine(),+ evaluatorPort: createNativeEvaluatorPort(options),+ viewRenderPort: createNativeRenderPort(rendering),+ };+}+export interface NativeMcpOptions {publicOrigin: string;storage?: NativeStorageOptions;@@ -163,22 +195,69 @@ export function createNativeMcpHandler(runtime: NativeMcpRuntime, options: Nativtransport = createMcpHandler(() => {const storage = { ...options.storage, signal: () => controller.signal };+ const materials = new NativeMaterialLibrary(storage);+ const builds = runtime.evaluatorPort.executionImage+ ? new NativeBuildIdentities()+ : undefined;+ const assets = new NativeAssetLibrary({+ ...storage,+ materials,+ executionIdentity: builds ? (draft) => builds.forDraft(draft) : undefined,+ });return runtime.createServer({programStore: new NativeProgramStore(storage),- assetLibrary: new NativeAssetLibrary(storage),+ assetLibrary: assets,+ materialLibrary: materials,+ workspace: new NativeMaterialWorkspace(materials),+ assetDownloadUrls: (collection, assetId, revisionId) =>+ assets.downloadUrls(options.publicOrigin, collection, assetId, revisionId),evaluatorProfile: 'evaluator-required',evaluatorPort: {render: async (code, renderOptions, controls) => {if (controller.signal.aborted) throw abortError();evaluations++;try {- return await runtime.evaluatorPort.render(code, renderOptions, controls);+ const result = await runtime.evaluatorPort.render(+ code,+ renderOptions,+ controls,+ );+ if (controller.signal.aborted) throw abortError();+ builds?.record(+ code,+ result.glb,+ runtime.evaluatorPort.executionImage?.(result),+ );+ return result;} finally {evaluations--;release();}},},+ ...(runtime.viewRenderPort+ ? {+ viewRenderPort: async (input, execution) => {+ if (controller.signal.aborted) throw abortError();+ evaluations++;+ try {+ return await runtime.viewRenderPort!(input, {+ signal: execution?.signal+ ? AbortSignal.any([execution.signal, controller.signal])+ : controller.signal,+ });+ } finally {+ evaluations--;+ release();+ }+ },+ viewRenderTimeoutMs: RENDER_LIMITS.deadlineMs,+ }+ : {}),+ captureLimits: {+ maxTotalPixels: 8 * 1024 * 1024,+ maxOutputBytes: RENDER_LIMITS.pngBytes,+ },evaluationControls: () => ({signal: controller.signal,deadlineMs: Math.min(timeoutMs, 60_000),diff --git a/hosting/src/native-render.ts b/hosting/src/native-render.tsnew file mode 100644index 00000000..f773c684--- /dev/null+++ b/hosting/src/native-render.ts@@ -0,0 +1,263 @@+import { createHash, randomUUID } from 'node:crypto';+import {+ validatePbrRenderRequest,+ type PbrRenderRequest,+ type PbrRenderResult,+ type PbrRenderPort,+} from '@instruktlabs/kiln/composer';+import { NativeHttpClient } from './native-http';+import { RENDER_LIMITS } from './render-limits';+export { RENDER_LIMITS } from './render-limits';++const fail = () => new Error('Invalid hosted render message');+const hash = (bytes: Uint8Array): `sha256:${string}` =>+ `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const object = (value: unknown): Record<string, unknown> => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw fail();+ return value as Record<string, unknown>;+};+function keys(value: Record<string, unknown>, allowed: readonly string[]) {+ if (Object.keys(value).some((key) => !allowed.includes(key))) throw fail();+}+function json(bytes: Uint8Array, limit: number): Record<string, unknown> {+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > limit)+ throw fail();+ try {+ return object(+ JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)),+ );+ } catch {+ throw fail();+ }+}+function serialize(value: unknown, limit: number): Uint8Array<ArrayBuffer> {+ const bytes = new TextEncoder().encode(JSON.stringify(value));+ if (bytes.byteLength > limit) throw fail();+ return bytes;+}+function base64(value: unknown, limit: number): Buffer {+ if (+ typeof value !== 'string' ||+ !value.length ||+ value.length % 4 !== 0 ||+ value.length > Math.ceil(limit / 3) * 4 ||+ !/^[A-Za-z0-9+/]*={0,2}$/.test(value)+ )+ throw fail();+ const bytes = Buffer.from(value, 'base64');+ if (bytes.byteLength > limit || bytes.toString('base64') !== value) throw fail();+ return bytes;+}+function admitted(value: unknown): PbrRenderRequest {+ const request = validatePbrRenderRequest(value);+ if (request.glb.byteLength > RENDER_LIMITS.glbBytes) throw fail();+ if (!request.cameras) {+ request.viewDirs ??= [[1, 0.35, 1]];+ request.size ??= 384;+ }+ const width = request.width ?? request.size!;+ const height = request.height ?? request.size!;+ const count = request.cameras?.length ?? request.viewDirs!.length;+ const beauty = request.beautySize ?? 0;+ if (+ Math.max(width, height, beauty) > RENDER_LIMITS.dimension ||+ width * height * count + beauty * beauty > RENDER_LIMITS.pixels+ )+ throw fail();+ return request;+}+export interface RenderInput {+ requestId: string;+ inputGlbSha256: `sha256:${string}`;+ request: PbrRenderRequest;+}+export function encodeRenderRequest(+ value: PbrRenderRequest,+): RenderInput & { bytes: Uint8Array<ArrayBuffer> } {+ const request = admitted(value);+ const { glb, ...options } = request;+ const requestId = randomUUID();+ return {+ request,+ requestId,+ inputGlbSha256: hash(glb),+ bytes: serialize(+ {+ version: 'kiln.hosted-render.request.v1',+ requestId,+ glbBase64: Buffer.from(glb).toString('base64'),+ options,+ },+ RENDER_LIMITS.requestBytes,+ ),+ };+}+/** Validated before renderer import, GPU initialization or image decoding in the child VM. */+export function decodeRenderRequest(bytes: Uint8Array): RenderInput {+ const value = json(bytes, RENDER_LIMITS.requestBytes);+ keys(value, ['version', 'requestId', 'glbBase64', 'options']);+ if (+ value.version !== 'kiln.hosted-render.request.v1' ||+ typeof value.requestId !== 'string' ||+ !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/.test(value.requestId)+ )+ throw fail();+ const options = object(value.options);+ if (Object.hasOwn(options, 'glb')) throw fail();+ const glb = base64(value.glbBase64, RENDER_LIMITS.glbBytes);+ return {+ requestId: value.requestId,+ inputGlbSha256: hash(glb),+ request: admitted({ ...options, glb }),+ };+}+interface RenderOutput {+ rendererId: string;+ backend: string;+ software: boolean;+ views: Uint8Array[];+ beauty?: Uint8Array;+ cameras?: PbrRenderResult['cameras'];+ width?: number;+ height?: number;+ lightingPresetId?: string;+}+/** No rendering or degradation here; the one-shot producer supplies only rendered bytes. */+export function encodeRenderResult(+ input: RenderInput,+ output: RenderOutput,+): Uint8Array<ArrayBuffer> {+ const value = {+ version: 'kiln.hosted-render.result.v1',+ requestId: input.requestId,+ inputGlbSha256: input.inputGlbSha256,+ rendererId: output.rendererId,+ backend: output.backend,+ software: output.software,+ viewsBase64: output.views.map((bytes) => Buffer.from(bytes).toString('base64')),+ ...(output.beauty ? { beautyBase64: Buffer.from(output.beauty).toString('base64') } : {}),+ ...(output.cameras+ ? {+ cameras: output.cameras,+ width: output.width,+ height: output.height,+ lightingPresetId: output.lightingPresetId,+ }+ : {}),+ };+ const bytes = serialize(value, RENDER_LIMITS.responseBytes);+ decodeRenderResult(bytes, input);+ return bytes;+}+export function decodeRenderResult(bytes: Uint8Array, input: RenderInput): PbrRenderResult {+ const value = json(bytes, RENDER_LIMITS.responseBytes);+ keys(value, [+ 'version',+ 'requestId',+ 'inputGlbSha256',+ 'rendererId',+ 'backend',+ 'software',+ 'viewsBase64',+ 'beautyBase64',+ 'cameras',+ 'width',+ 'height',+ 'lightingPresetId',+ ]);+ if (+ value.version !== 'kiln.hosted-render.result.v1' ||+ value.requestId !== input.requestId ||+ value.inputGlbSha256 !== input.inputGlbSha256 ||+ value.software !== true ||+ value.backend !== 'vulkan' ||+ typeof value.rendererId !== 'string' ||+ !value.rendererId.trim() ||+ value.rendererId.length > 512 ||+ [...value.rendererId].some(+ (character) => character.charCodeAt(0) < 32 || character === '\u007f',+ )+ )+ throw fail();+ const expected = input.request.cameras?.length ?? input.request.viewDirs!.length;+ if (!Array.isArray(value.viewsBase64) || value.viewsBase64.length !== expected) throw fail();+ const viewsPng = value.viewsBase64.map((value) => base64(value, RENDER_LIMITS.pngBytes));+ const beautyPng =+ value.beautyBase64 === undefined+ ? undefined+ : base64(value.beautyBase64, RENDER_LIMITS.pngBytes);+ if (Boolean(beautyPng) !== Boolean(input.request.beautySize)) throw fail();+ if (+ viewsPng.reduce((sum, png) => sum + png.byteLength, beautyPng?.byteLength ?? 0) >+ RENDER_LIMITS.pngBytes+ )+ throw fail();+ const result: PbrRenderResult = {+ ok: true,+ rendererId: value.rendererId,+ backend: 'vulkan',+ viewsPng,+ derivativeFidelity: { materialFaithful: true, inputGlbSha256: input.inputGlbSha256 },+ ...(beautyPng ? { beautyPng } : {}),+ };+ if (input.request.cameras) {+ const validated = validatePbrRenderRequest({+ glb: input.request.glb,+ cameras: value.cameras,+ width: value.width,+ height: value.height,+ lightingPresetId: value.lightingPresetId,+ });+ if (+ !validated.cameras ||+ JSON.stringify(validated.cameras) !== JSON.stringify(input.request.cameras) ||+ validated.width !== input.request.width ||+ validated.height !== input.request.height ||+ validated.lightingPresetId !== (input.request.lightingPresetId ?? 'review-neutral-v1')+ )+ throw fail();+ Object.assign(result, {+ cameras: validated.cameras,+ width: validated.width,+ height: validated.height,+ lightingPresetId: validated.lightingPresetId,+ });+ } else if (+ ['cameras', 'width', 'height', 'lightingPresetId'].some((key) => Object.hasOwn(value, key))+ )+ throw fail();+ return result;+}+export function createNativeRenderPort(+ options: { fetch?: (request: Request) => Promise<Response> } = {},+): PbrRenderPort {+ return async (request, execution) => {+ try {+ execution?.signal?.throwIfAborted();+ const input = encodeRenderRequest(request);+ const client = new NativeHttpClient(+ { fetch: options.fetch, signal: () => execution?.signal, timeoutMs: 60_000 },+ 'Renderer',+ 'renderer',+ );+ const bytes = await client.bytes('/render', {+ method: 'POST',+ body: input.bytes,+ headers: {+ 'content-type': 'application/json',+ 'x-kiln-deadline-ms': String(RENDER_LIMITS.deadlineMs),+ 'x-kiln-max-response-bytes': String(RENDER_LIMITS.responseBytes),+ },+ limit: RENDER_LIMITS.responseBytes,+ });+ return decodeRenderResult(bytes, input);+ } catch {+ // The engine owns PNG validation, deadline policy and CPU degradation.+ return {+ ok: false,+ rendererId: 'unavailable',+ error: 'Hosted software rendering is unavailable',+ };+ }+ };+}diff --git a/hosting/src/native-workspace.ts b/hosting/src/native-workspace.tsnew file mode 100644index 00000000..b30983b4--- /dev/null+++ b/hosting/src/native-workspace.ts@@ -0,0 +1,83 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import {+ workspaceSelectionSchema,+ type WorkspaceBinding,+ type WorkspacePort,+ type WorkspaceSelection,+} from '@instruktlabs/kiln/workspace';+import {+ MATERIAL_LIBRARY_LIMITS,+ type MaterialLibrary,+ type MaterialRecordV1,+} from '@instruktlabs/kiln/material-library';+import { createMaterialLibraryPayload } from '@instruktlabs/kiln/material-library/node';++/** Standalone operations bind explicit material revisions, never a local directory or inferred project. */+export class NativeMaterialWorkspace implements WorkspacePort {+ private readonly active = new AsyncLocalStorage<WorkspaceBinding>();+ constructor(private readonly materials: MaterialLibrary) {}+ current(): WorkspaceBinding | undefined {+ return this.active.getStore();+ }++ async run<T>(requested: WorkspaceSelection, execute: () => Promise<T>): Promise<T> {+ const selection = workspaceSelectionSchema.parse(requested);+ if (selection.projectId != null || selection.projectRevision !== undefined)+ throw new Error(+ 'Hosted project storage is not available; omit the project or use projectId: null with explicit materialDependencies.',+ );+ const existing = this.current();+ const inherit = existing && selection.projectId !== null;+ if (inherit && selection.materialDependencies === undefined) return execute();+ const pins = new Map<string, WorkspaceBinding['materialDependencies'][number]>();+ for (const pin of inherit ? existing.materialDependencies : []) pins.set(pin.resourceId, pin);+ for (const pin of selection.materialDependencies ?? []) pins.set(pin.resourceId, pin);+ const dependencies = [...pins.values()].sort((a, b) =>+ a.resourceId.localeCompare(b.resourceId),+ );+ if (dependencies.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)+ throw new Error(+ `An evaluation may resolve at most ${MATERIAL_LIBRARY_LIMITS.maxPayloadRecords} material resources; select a smaller dependency closure.`,+ );+ // Validate the entire selection before reading any tenant storage.+ for (const pin of dependencies) {+ if (+ !/^[a-z][a-z0-9_-]{0,79}(?![\s\S])/.test(pin.resourceId) ||+ !/^sha256:[a-f0-9]{64}(?![\s\S])/.test(pin.revisionId)+ )+ throw new Error('Invalid material identity');+ if (pin.sha256 !== pin.revisionId)+ throw new Error(`Material lock hash mismatch: ${pin.resourceId}`);+ }+ const records: MaterialRecordV1[] = [];+ let bytes = 0,+ pixels = 0;+ // Bound accumulated decoded resources before reading another record. The+ // native library separately verifies each immutable record before returning it.+ for (const pin of dependencies) {+ let record: MaterialRecordV1;+ try {+ record = await this.materials.read(pin.resourceId, pin.revisionId);+ } catch {+ throw new Error(`Locked material unavailable: ${pin.resourceId} at ${pin.revisionId}`);+ }+ if (+ record.manifest.materialId !== pin.resourceId ||+ record.manifest.revisionId !== pin.revisionId+ )+ throw new Error('Locked material identity mismatch');+ for (const map of record.manifest.maps) {+ bytes += map.bytes;+ pixels += map.width * map.height;+ }+ if (+ bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes ||+ pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels+ )+ throw new Error('Material resource payload exceeds byte or pixel budget');+ records.push(record);+ }+ const materialResources = await createMaterialLibraryPayload(records);+ return this.active.run({ materialDependencies: dependencies, materialResources }, execute);+ }+}diff --git a/hosting/src/operations.ts b/hosting/src/operations.tsnew file mode 100644index 00000000..07925cf2--- /dev/null+++ b/hosting/src/operations.ts@@ -0,0 +1,143 @@+import { routeClass } from './request-limits';+import type { TenantEnv } from './gateway';++export interface OperationsEnv {+ OPERATIONS?: Pick<AnalyticsEngineDataset, 'writeDataPoint'>;+}+interface DeletionHealth {+ pending: number;+ oldestPendingMs: number;+ overdue: number;+}+interface ComputeHealth {+ paused: boolean;+ activeRequests: number;+ pendingCleanup: number;+ maxConcurrent: number;+}+export interface OperationalHealth {+ deletion: DeletionHealth | null;+ compute: ComputeHealth | null;+}+const count = (value: unknown): value is number =>+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;+function deletionHealth(value: unknown): DeletionHealth | null {+ if (!value || typeof value !== 'object') return null;+ const v = value as DeletionHealth;+ if (!count(v.pending) || !count(v.oldestPendingMs) || !count(v.overdue) || v.overdue > v.pending)+ return null;+ return { pending: v.pending, oldestPendingMs: v.oldestPendingMs, overdue: v.overdue };+}+function computeHealth(value: unknown): ComputeHealth | null {+ if (!value || typeof value !== 'object') return null;+ const v = value as ComputeHealth;+ if (+ typeof v.paused !== 'boolean' ||+ !count(v.activeRequests) ||+ !count(v.pendingCleanup) ||+ !count(v.maxConcurrent) ||+ v.maxConcurrent === 0 ||+ v.pendingCleanup > v.activeRequests+ )+ return null;+ return {+ paused: v.paused,+ activeRequests: v.activeRequests,+ pendingCleanup: v.pendingCleanup,+ maxConcurrent: v.maxConcurrent,+ };+}+function emit(env: OperationsEnv, index: string, labels: string[], values: number[]): void {+ try {+ // Explicit positional fields only. Never log a Request, response, exception,+ // account, URL, environment or arbitrary caller-provided object.+ env.OPERATIONS?.writeDataPoint({+ indexes: [index],+ blobs: ['kiln.ops.v1', ...labels],+ doubles: [1, ...values],+ });+ } catch {+ /* Observability failure cannot change authorization or cleanup. */+ }+}+export function recordResponse(+ env: OperationsEnv,+ path: string,+ status: number,+ elapsedMs: number,+): void {+ if (+ typeof path !== 'string' ||+ !Number.isInteger(status) ||+ status < 100 ||+ status > 599 ||+ !Number.isFinite(elapsedMs) ||+ elapsedMs < 0 ||+ elapsedMs > Number.MAX_SAFE_INTEGER+ )+ return;+ emit(env, 'http', ['http', routeClass(path), String(status)], [Math.round(elapsedMs)]);+}+export function recordHealth(+ env: OperationsEnv,+ health: OperationalHealth,+ recovered: boolean,+): void {+ const deletion = deletionHealth(health.deletion),+ compute = computeHealth(health.compute);+ emit(+ env,+ 'health:deletion',+ ['health', 'deletion', deletion ? 'ok' : 'unavailable'],+ deletion+ ? [deletion.pending, deletion.oldestPendingMs, deletion.overdue, Number(recovered === true)]+ : [-1, -1, -1, Number(recovered === true)],+ );+ emit(+ env,+ 'health:compute',+ ['health', 'compute', compute ? 'ok' : 'unavailable'],+ compute+ ? [+ Number(compute.paused),+ compute.activeRequests,+ compute.pendingCleanup,+ compute.maxConcurrent,+ ]+ : [-1, -1, -1, -1],+ );+}+async function boundedRead(read: () => Promise<unknown>): Promise<unknown> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ read(),+ new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), 2000);+ }),+ ]);+ } catch {+ return null;+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}+export async function readOperationalHealth(+ env: Pick<TenantEnv, 'NATIVE_COMPUTE'> & { ACCOUNTS: D1Database },+ now = Date.now(),+): Promise<OperationalHealth> {+ const [deletion, compute] = await Promise.all([+ boundedRead(async () =>+ env.ACCOUNTS.withSession('first-primary')+ .prepare(+ `SELECT COUNT(*) AS pending, COALESCE(MAX(0,?-MIN(created_at)),0) AS oldestPendingMs,+ COALESCE(SUM(created_at<=?),0) AS overdue FROM kiln_deletions+ WHERE phase IN ('compute','storage','grants','identity')`,+ )+ .bind(now, now - 15 * 60_000)+ .first(),+ ),+ boundedRead(async () => env.NATIVE_COMPUTE?.health()),+ ]);+ return { deletion: deletionHealth(deletion), compute: computeHealth(compute) };+}diff --git a/hosting/src/public-pages.ts b/hosting/src/public-pages.tsnew file mode 100644index 00000000..d40eeef6--- /dev/null+++ b/hosting/src/public-pages.ts@@ -0,0 +1,94 @@+import { escapeHtml, htmlPage } from './html-page';+import { HttpFailure } from './http';++const contact = '<a href="mailto:[email protected]">[email protected]</a>';++function home(origin: string): Response {+ return htmlPage(+ 'Editable 3D assets',+ `<h1>From JavaScript to editable 3D assets</h1>+<p>Kiln lets your coding assistant create, inspect, render and save 3D assets. Keep the source, materials and GLB together so you can reopen and change your work.</p>+<section><h2>Use hosted Kiln</h2><p>Hosted access is free within personal usage and storage quotas. Sign in with Google or GitHub to keep your saved work private and connect an app. No payment information is required.</p>+<p><a href="/account">Sign in or manage your account</a></p><p>MCP server address:<br><code>${escapeHtml(origin)}/mcp</code></p>+<p>Your app must support a remote MCP server with sign-in. Review the app name and requested access before connecting it.</p></section>+<section><h2>Work locally</h2><p>The open source <code>@instruktlabs/kiln</code> package includes the SDK, CLI and local MCP server. Local use does not require a Kiln account.</p><p><a href="https://github.com/instruktlabs/kiln">Read the installation guide and source</a></p></section>+<p>Kiln is operated by Instrukt Labs. Read <a href="/privacy">how hosted data is handled</a> or <a href="/support">get help</a>.</p>`,+ );+}++function privacy(): Response {+ return htmlPage(+ 'Privacy',+ `<h1>Hosted Kiln privacy</h1><p>This notice covers the Kiln hosted service operated by Instrukt Labs. It does not cover your local Kiln workspace or the assistant you connect. Contact ${contact} about privacy or access to your data.</p>+<section><h2>Sign-in and account data</h2>+<p>Google or GitHub confirms your identity. Kiln receives provider identity and profile information during sign-in, and keeps the provider name and stable account identifier to associate you with a Kiln account. It does not retain your provider profile name, photo or email address. Provider access and ID tokens are discarded after verification.</p>+<p>Google sign-in requests basic identity and profile access. GitHub sign-in uses your public identity without requesting repository or private-email permissions. Kiln does not request Google Drive, Gmail or GitHub repository access.</p>+<p>Kiln stores its own account, session, connected-app, usage and security-activity records. Essential cookies keep sign-in, account confirmations and your browser session bound to you. Browser sessions expire after 30 minutes without activity or 24 hours in total; connected apps can stay authorized for up to 30 days.</p>+<p>Adding another sign-in method requires confirmation of both identities. Accounts are never automatically joined by matching email addresses. Security notices are in-app only: Kiln does not collect a separate security contact email or send alerts about sign-in method changes or deletion.</p></section>+<section><h2>Your source and assets</h2>+<p>Kiln processes the source, geometry, material files, previews, names and metadata you or your connected app send. It stores these privately for your account and returns requested results to the apps you authorize. The hosted service does not call a model provider. Your assistant handles its own conversations and copies under its provider's policies.</p>+<p>Unsaved work expires seven days after upload; background cleanup removes expired files. Saved source, assets and material dependencies remain until deleted, within your storage quota. Removing a saved revision removes that entry; files shared with another revision can remain, and unsaved copies follow the seven-day policy. Download links require your signed-in account and expire after ten minutes.</p></section>+<section><h2>Service providers and operations</h2>+<p>Cloudflare processes network requests, runs Kiln and stores hosted data. Google and GitHub process the sign-in you choose. Kiln's operational metrics record request categories, status codes, timing and aggregate service health, without source, file contents, account identifiers, IP addresses or credentials. These metrics are retained for three months. Cloudflare also processes its own infrastructure and security data under its policies.</p>+<p>Kiln pages do not load advertising or tracking scripts. If you contact support, your email and the details you choose to send are processed in the support inbox to handle your request. Do not include passwords, tokens or recovery codes.</p></section>+<section><h2>Your controls and deletion</h2>+<p>Use <a href="/account">Your account</a> to review sign-in methods, security activity and connected apps. Browser sign-out leaves app connections working. Disconnecting an app blocks its new requests but does not erase copies already returned to it or cancel work already admitted.</p>+<p>You can download your work and request account deletion after confirming a linked sign-in method. Access is revoked while cleanup stops outstanding work and removes active files and identity records. If cleanup is interrupted, the request stays pending while it retries. The private deletion receipt is available for seven days after completion.</p>+<p>Minimal pseudonymous retirement records remain to prevent old credentials or delayed jobs from restoring deleted data. Expiring authorization records and provider backups are separate from active-service deletion: Cloudflare's database recovery history can retain prior account data for up to 30 days. Deletion does not remove copies you downloaded or sent to another app.</p>+<p>For access, correction or deletion questions, contact ${contact}. Use the identity provider's own account controls for your Google or GitHub data.</p></section>`,+ );+}++function support(): Response {+ return htmlPage(+ 'Support',+ `<h1>Get help with Kiln</h1><p>Kiln is an open source project operated by Instrukt Labs. Hosted access is free within quotas; there is no paid support tier.</p>+<section><h2>Account, privacy or security</h2><p>Email ${contact}. Include a short description and, when relevant, the time and the support reference shown by Kiln. Never send passwords, access tokens, recovery codes or private source you do not want to share.</p><p>Use email for security reports and private account details. Do not put them in public issues. Support cannot restore account access solely because an email address matches; your linked Google or GitHub identity establishes ownership.</p></section>+<section><h2>Common account questions</h2><p>Use the same sign-in method as before to reach your work. Add another method from <a href="/account">Your account</a>; separately created accounts cannot be merged.</p><p>A download link requires the account that saved the asset. If it has expired, request a fresh link from your connected app. A quota response means the operation was refused; try again after the stated delay or free saved storage as appropriate.</p><p>Browser sign-out and disconnecting an app are separate controls. Account deletion removes hosted files, so download anything you want to keep first.</p></section>+<section><h2>Bug reports and contributions</h2><p><a href="https://github.com/instruktlabs/kiln/issues">Open a public issue</a> with your Kiln version, operating system, expected behavior and a small reproduction you are comfortable making public. Remove credentials and private assets before posting.</p></section>`,+ );+}++function terms(): Response {+ return htmlPage(+ 'Terms',+ `<h1>Terms of hosted use</h1><p>These terms describe use of the hosted Kiln service operated by Instrukt Labs. By using hosted Kiln, you agree to these terms. Questions can be sent to ${contact}.</p>+<section><h2>Access and accounts</h2>+<p>Hosted access is free within usage and storage quotas. Kiln does not collect payment details or charge your account for exceeding a quota. Requests can be limited, refused or paused when capacity is unavailable. Voluntary sponsorship does not create a paid service level or change your quotas.</p>+<p>Use an identity you control when signing in with Google or GitHub. Keep that account secure and review which apps you connect to Kiln. A connected app can act on the work in your Kiln account within the access you grant. Account controls let you disconnect an app or request account deletion after identity confirmation.</p>+<p>Security activity is shown in your account. Kiln v1 does not send email alerts about sign-in changes or deletion requests.</p></section>+<section><h2>Your work and permissions</h2>+<p>You retain whatever rights you hold in your inputs and outputs. Instrukt Labs does not claim ownership of your assets. You authorize Kiln and its service providers to process, store, render and return your submitted work as needed to operate the service and fulfill your requests. This does not authorize publication of your private assets.</p>+<p>Submit only material you have permission to use. You are responsible for respecting copyright, licenses and other rights in your inputs and in how you use the results. Kiln does not determine whether an asset is legally cleared for your intended use.</p>+<p>The <a href="/privacy">privacy notice</a> explains account data, service providers, retention and deletion. Unsaved work expires after seven days; saved work remains within quota until deleted. Download copies you need to keep independently. Your assistant and other apps may retain their own copies under their own terms.</p></section>+<section><h2>Acceptable use</h2>+<p>Use Kiln lawfully. Do not attempt to access another person's private assets, bypass account or resource limits, interfere with the service, or run code intended to escape evaluation boundaries. Do not submit passwords, provider keys, authentication codes or payment information as source or tool arguments.</p>+<p>We may limit or suspend hosted access to address abuse, security problems, capacity or service maintenance. Contact support if you believe a restriction is mistaken.</p></section>+<section><h2>Availability and results</h2>+<p>Hosted Kiln is provided as available, without a guaranteed uptime or response time. Features and limits may change. Experimental helpers are labeled in the catalog. Inspect outputs before relying on them: syntax checks, structural QA and rendered previews do not guarantee suitability for your destination application.</p>+<p>These hosted-use terms do not replace the MIT license for the open source Kiln software or any licenses attached to material resources. You can use the local package independently of the hosted service.</p></section>+<section><h2>Changes and contact</h2>+<p>Updates to these terms will be posted here. Material changes to hosted access or data handling will be surfaced in the service before they take effect; a policy edit does not authorize an undisclosed new use of existing private data. For support, privacy or security questions, contact ${contact}.</p></section>`,+ );+}++/** Public information is available without authentication or a storage lookup. */+export function publicPage(request: Request, origin: string): Response | undefined {+ const url = new URL(request.url);+ if (!['/', '/privacy', '/support', '/terms'].includes(url.pathname)) return undefined;+ if (url.search)+ throw new HttpFailure(400, 'Query parameters are not supported on information pages');+ if (request.method !== 'GET' && request.method !== 'HEAD') {+ if (!request.bodyUsed) void request.body?.cancel().catch(() => {});+ return new Response('Method not allowed', { status: 405, headers: { allow: 'GET, HEAD' } });+ }+ const response =+ url.pathname === '/'+ ? home(origin)+ : url.pathname === '/privacy'+ ? privacy()+ : url.pathname === '/terms'+ ? terms()+ : support();+ return request.method === 'HEAD' ? new Response(null, { headers: response.headers }) : response;+}diff --git a/hosting/src/public-tools.ts b/hosting/src/public-tools.tsnew file mode 100644index 00000000..fe362d3f--- /dev/null+++ b/hosting/src/public-tools.ts@@ -0,0 +1,227 @@+import type { Tool } from '@modelcontextprotocol/server';++export const HOSTED_TOOL_SURFACE = 'kiln.hosted-tools.v1';++interface Operation {+ description: string;+ fields: readonly string[];+}++// Routing and field selection only. Every field's schema comes from the pinned+// engine registry; the engine still owns parsing, requirements and execution.+const actions: Record<string, Record<string, Operation>> = {+ kiln_renderer: {+ status: { description: 'Inspect the hosted renderer status.', fields: [] },+ reprobe: {+ description:+ 'Refresh renderer availability for this hosted call. Does not install or repair a service.',+ fields: [],+ },+ },+ kiln_material: {+ presets: {+ description: 'List shipped material recipes, optionally filtered by tag.',+ fields: ['tag'],+ },+ 'create-preset': {+ description:+ 'Bake and retain an immutable material from a shipped preset. Supply presetId, seed, creator and license; pin the returned materialId/revisionId for rendering.',+ fields: ['presetId', 'seed', 'creator', 'license', 'size', 'materialId'],+ },+ list: {+ description: 'List private material revisions, optionally filtered by tag.',+ fields: ['tag'],+ },+ get: {+ description:+ 'Read a private material revision, provenance and portable material specification. Supply materialId; omit revisionId only when the material has one revision.',+ fields: ['materialId', 'revisionId'],+ },+ 'create-procedural': {+ description:+ 'Bake and retain an immutable material from a bounded procedural draft. Supply draft; pin the returned materialId/revisionId for rendering. Does not fetch URLs or execute source.',+ fields: ['draft'],+ },+ import: {+ description:+ 'Import complete normalized material records and embedded PNGs into the private account. Supply payload. Does not fetch URLs or execute source.',+ fields: ['payload'],+ },+ },+ kiln_assets: {+ collections: {+ description:+ 'List the private account asset collections. A collection is a storage destination, not project membership.',+ fields: [],+ },+ catalog: {+ description: 'Search saved assets across the private account collections, with pagination.',+ fields: ['assetId', 'query', 'offset', 'limit'],+ },+ list: {+ description: 'Search saved assets in one private account collection, with pagination.',+ fields: ['collection', 'assetId', 'query', 'offset', 'limit'],+ },+ get: {+ description:+ 'Read a saved asset revision and its authenticated download links. Supply assetId; omit revisionId for the newest revision.',+ fields: ['collection', 'assetId', 'revisionId'],+ },+ restore: {+ description:+ 'Restore exact saved source as a retained programRef for editing or rendering. Supply assetId; omit revisionId for the newest revision. Does not overwrite the saved revision. Binary-only assets have no source.',+ fields: ['collection', 'assetId', 'revisionId'],+ },+ },+};++const direct = new Set([+ 'kiln_discover',+ 'kiln_validate',+ 'kiln_render',+ 'kiln_screenshot_animation',+ 'kiln_view_interior',+ 'kiln_inspect',+ 'kiln_edit',+ 'kiln_source',+ 'kiln_save',+ 'kiln_present',+ 'kiln_export',+ 'kiln_import',+]);++const nativeJob =+ ' Runs an isolated hosted job and consumes the account request quota. Temporary job records and any produced artifacts are retained under the hosted retention policy.';+export const hostedInstructions =+ 'Kiln turns authored JavaScript into editable GLB assets in your private account. ' ++ 'Use kiln_discover for geometry helper contracts and input shapes; it cannot execute operations. ' ++ 'Use kiln_capabilities for hosted runtime facts. Send new source once to kiln_validate or kiln_render, ' ++ 'then preserve the exact programRef for later reads, edits and renders. ' ++ 'Read viewFidelity before judging materials: CPU images show geometry; software-rendered PBR views can show materials. ' ++ 'Rendering is managed by the service and requires no local installation. ' ++ 'Each material, asset and renderer operation has its own named tool. ' ++ 'Engine diagnostics can mention their local multi-action names; use the corresponding exposed operation here. ' ++ 'Save only when requested. Unsaved work expires after seven days; saved assets remain until deleted within quotas.';++interface Route {+ engineName: string;+ fixed: Record<string, unknown>;+ tool: Tool;+}++export function createPublicTools(engineTools: readonly Tool[]) {+ const routes = new Map<string, Route>();+ const seen = new Set<string>();+ function add(+ original: Tool,+ name: string,+ fields: readonly string[],+ fixed: Record<string, unknown>,+ description: string,+ ) {+ const schema = original.inputSchema;+ const properties = Object.fromEntries(+ fields.map((key) => {+ if (!Object.hasOwn(schema.properties ?? {}, key))+ throw new Error(`Missing engine field ${original.name}.${key}`);+ return [key, structuredClone(schema.properties![key])];+ }),+ );+ const tool = {+ ...structuredClone(original),+ name,+ description: description + (name === 'kiln_discover' ? '' : nativeJob),+ inputSchema: {+ ...structuredClone(schema),+ properties,+ additionalProperties: false,+ required: (schema.required ?? []).filter((key) => fields.includes(key)),+ },+ annotations: {+ ...original.annotations,+ // Even private reads use a stateful, quota-admitted native job. This+ // conservative hosted annotation differs deliberately from local reads.+ readOnlyHint: name === 'kiln_discover',+ destructiveHint: original.annotations?.destructiveHint ?? false,+ openWorldHint: original.annotations?.openWorldHint ?? false,+ },+ } as Tool;+ if (routes.has(name)) throw new Error('Duplicate hosted tool');+ routes.set(name, { engineName: original.name, fixed, tool });+ }+ for (const tool of engineTools) {+ if (seen.has(tool.name)) throw new Error('Duplicate engine tool');+ seen.add(tool.name);+ const operations = actions[tool.name];+ if (operations) {+ const advertised = tool.inputSchema.properties?.action as { enum?: unknown } | undefined;+ const expected = Object.keys(operations).sort();+ if (+ !Array.isArray(advertised?.enum) ||+ JSON.stringify([...advertised.enum].sort()) !== JSON.stringify(expected)+ )+ throw new Error(`Unreviewed engine actions in ${tool.name}`);+ for (const [action, operation] of Object.entries(operations)) {+ add(+ tool,+ `${tool.name}_${action.replaceAll('-', '_')}`,+ operation.fields,+ { action },+ operation.description,+ );+ }+ } else {+ if (!direct.has(tool.name)) throw new Error(`Unreviewed engine tool ${tool.name}`);+ const fields = Object.keys(tool.inputSchema.properties ?? {});+ if (fields.includes('action')) throw new Error(`Unreviewed engine actions in ${tool.name}`);+ if (tool.name === 'kiln_discover') {+ if (!fields.includes('capabilities')) throw new Error('Missing engine capabilities input');+ add(+ tool,+ tool.name,+ fields.filter((key) => key !== 'capabilities'),+ {},+ 'Read the Kiln geometry-helper catalog and complete input shapes. Search with ordinary modeling language, or fetch up to six exact IDs. Does not execute source, fetch URLs, or expose hidden callable operations.',+ );+ add(+ tool,+ 'kiln_capabilities',+ [],+ { capabilities: true },+ 'Inspect this hosted runtime, supported rendering, camera and storage capabilities.',+ );+ } else {+ add(+ tool,+ tool.name,+ fields,+ {},+ tool.name === 'kiln_import'+ ? 'Copy a pinned private asset revision between account collections, preserving identity and provenance. Copies do not track later edits.'+ : (tool.description ?? tool.name),+ );+ }+ }+ }+ if (seen.size !== direct.size + Object.keys(actions).length)+ throw new Error('Missing engine tools');+ return {+ tools: [...routes.values()].map((route) => route.tool),+ // A caller cannot pick an engine action, supply unadvertised arguments, or+ // introduce another tool. No fallback to the local multi-action names.+ resolve(+ name: string,+ args: Record<string, unknown>,+ ): { name: string; arguments: Record<string, unknown> } | undefined {+ const route = routes.get(name);+ if (+ !route ||+ Object.keys(args).some(+ (key) => !Object.hasOwn(route.tool.inputSchema.properties ?? {}, key),+ )+ )+ return undefined;+ return { name: route.engineName, arguments: { ...args, ...route.fixed } };+ },+ };+}diff --git a/hosting/src/render-limits.ts b/hosting/src/render-limits.tsnew file mode 100644index 00000000..70bc0f7f--- /dev/null+++ b/hosting/src/render-limits.ts@@ -0,0 +1,10 @@+/** Private host admission bounds; these do not change the published engine limits. */+export const RENDER_LIMITS = Object.freeze({+ glbBytes: 4 * 1024 * 1024,+ requestBytes: 6 * 1024 * 1024,+ responseBytes: 20 * 1024 * 1024,+ pngBytes: 12 * 1024 * 1024,+ dimension: 1024,+ pixels: 3 * 1024 * 1024,+ deadlineMs: 30_000,+});diff --git a/hosting/src/render-worker.ts b/hosting/src/render-worker.tsnew file mode 100644index 00000000..0074193c--- /dev/null+++ b/hosting/src/render-worker.ts@@ -0,0 +1,24 @@+import { DurableObject } from 'cloudflare:workers';+import { ContainerRenderJob } from './container-job';+import { handleRenderRequest } from './evaluation-request';++/** Private image-bound rendering job; no source evaluation or public entrypoint. */+export class KilnRenderJob extends DurableObject {+ private readonly job = new ContainerRenderJob(this.ctx);++ fetch(request: Request): Promise<Response> {+ return handleRenderRequest(request, this.job);+ }+ cancel(): Promise<void> {+ return this.job.cancel();+ }+ alarm(): Promise<void> {+ return this.job.alarm();+ }+}++export default {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ },+};diff --git a/hosting/src/request-job.ts b/hosting/src/request-job.tsnew file mode 100644index 00000000..5995bb02--- /dev/null+++ b/hosting/src/request-job.ts@@ -0,0 +1,435 @@+import { ContainerJobFailure, destroyContainer } from './container-job';+import { HttpFailure, privateResponse, readBounded } from './http';+import { EXECUTION_PROFILES, type ExecutionKind } from './execution-profiles';++interface RequestRecord {+ state: 'running' | 'closing' | 'finished';+ tenant?: string;+ deadlineAt: number;+ children: { id: string; kind: ExecutionKind }[];+ activeChild?: string;+}++export interface NativeRequestPorts {+ publicOrigin: string;+ storageInterceptor: Fetcher;+ evaluationInterceptor: Fetcher;+ renderInterceptor: Fetcher;+ storage(tenant: string, request: Request): Promise<Response>;+ evaluate(id: string, request: Request): Promise<Response>;+ cancelEvaluation(id: string): Promise<void>;+ render(id: string, request: Request): Promise<Response>;+ cancelRender(id: string): Promise<void>;+}++const MCP_HEADERS = new Set([+ 'accept',+ 'content-type',+ 'content-length',+ 'mcp-protocol-version',+ 'mcp-method',+ 'mcp-name',+ 'mcp-session-id',+ 'last-event-id',+]);+const STORAGE_HEADERS = new Set([+ 'content-type',+ 'content-length',+ 'x-artifact-name',+ 'x-artifact-sha256',+]);+const EVALUATION_HEADERS = new Set([+ 'content-type',+ 'content-length',+ 'x-kiln-deadline-ms',+ 'x-kiln-max-response-bytes',+]);+const TRANSPORT_HEADERS = new Set([+ 'accept',+ 'accept-encoding',+ 'accept-language',+ 'connection',+ 'host',+ 'user-agent',+ 'sec-fetch-mode',+]);++function checkHeaders(request: Request, allowed: Set<string>, transport = false): Headers {+ const headers = new Headers();+ for (const [key, value] of request.headers) {+ if (value.length > 4096 || (!allowed.has(key) && !(transport && TRANSPORT_HEADERS.has(key))))+ throw new HttpFailure(400, 'Invalid private request header');+ if (allowed.has(key)) headers.set(key, value);+ }+ return headers;+}++export function nativeRequestHeaders(tenant: string, request: Request): Headers {+ if (+ !/^[A-Za-z0-9_-]{43}$/.test(tenant) ||+ request.url !== 'https://tenant.internal/mcp' ||+ !['GET', 'POST', 'DELETE'].includes(request.method)+ )+ throw new HttpFailure(400, 'Invalid native request');+ return checkHeaders(request, MCP_HEADERS);+}++async function untilAbort<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {+ let abort: () => void = () => {};+ const stopped = new Promise<never>((_, reject) => {+ abort = () => reject(new HttpFailure(499, 'Request cancelled'));+ signal.addEventListener('abort', abort, { once: true });+ if (signal.aborted) abort();+ });+ try {+ return await Promise.race([pending, stopped]);+ } finally {+ signal.removeEventListener('abort', abort);+ }+}++async function cleanupChild(cancel: Promise<void>): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ cancel,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new ContainerJobFailure('CLEANUP_FAILED')), 10_000);+ }),+ ]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++/** One coordinator VM per admitted MCP request. Only its outside parent owns tenancy. */+export class NativeRequestJob {+ private readonly stopped = new AbortController();+ private closing?: Promise<void>;+ constructor(+ private readonly context: Pick<DurableObjectState, 'container' | 'storage'>,+ private readonly ports: NativeRequestPorts,+ ) {}++ private check(): void {+ if (this.stopped.signal.aborted) throw new HttpFailure(499, 'Request cancelled');+ }++ private async active(): Promise<RequestRecord & { tenant: string }> {+ this.check();+ const record = await this.context.storage.get<RequestRecord>('request');+ this.check();+ if (record?.state !== 'running' || !record.tenant)+ throw new HttpFailure(409, 'Native request is not active');+ if (Date.now() >= record.deadlineAt) throw new HttpFailure(504, 'Native request timed out');+ return record as RequestRecord & { tenant: string };+ }++ async run(tenant: string, request: Request, deadlineAt: number): Promise<Response> {+ const container = this.context.container;+ const image = container?.images.coordinator;+ let origin: URL;+ try {+ origin = new URL(this.ports.publicOrigin);+ } catch {+ throw new HttpFailure(503, 'Native host is not configured');+ }+ if (+ !container ||+ !image ||+ image.length > 512 ||+ !/^[a-zA-Z0-9._:/-]+@sha256:[a-f0-9]{64}$/.test(image) ||+ origin.protocol !== 'https:' ||+ origin.origin !== this.ports.publicOrigin+ )+ throw new HttpFailure(503, 'Native host is not configured');+ if (+ !Number.isSafeInteger(deadlineAt) ||+ deadlineAt <= Date.now() ||+ deadlineAt > Date.now() + 120_000+ )+ throw new HttpFailure(400, 'Invalid native request');+ const headers = nativeRequestHeaders(tenant, request);+ const admitted = await this.context.storage.transaction(async (tx) => {+ if (await tx.get('request')) return false;+ await tx.put('request', {+ state: 'running',+ tenant,+ deadlineAt,+ children: [],+ } satisfies RequestRecord);+ await tx.setAlarm(deadlineAt);+ return true;+ });+ if (!admitted) throw new HttpFailure(409, 'Native request already used');+ const signal = AbortSignal.any([request.signal, this.stopped.signal]);+ const check = () => {+ this.check();+ if (Date.now() >= deadlineAt) throw new HttpFailure(504, 'Native request timed out');+ if (signal.aborted) throw new HttpFailure(499, 'Request cancelled');+ };+ let deadlineExpired = false;+ const timer = setTimeout(+ () => {+ deadlineExpired = true;+ this.stopped.abort();+ },+ Math.max(0, deadlineAt - Date.now()),+ );+ let response: Response | undefined;+ try {+ check();+ const body = await readBounded(request.body, 1024 * 1024, signal);+ check();+ if (container.running) throw new HttpFailure(503, 'Native host is unavailable');+ await untilAbort(+ container.interceptOutboundHttp('kiln-storage.internal', this.ports.storageInterceptor),+ signal,+ );+ check();+ await untilAbort(+ container.interceptOutboundHttp(+ 'kiln-evaluator.internal',+ this.ports.evaluationInterceptor,+ ),+ signal,+ );+ check();+ await untilAbort(+ container.interceptOutboundHttp('kiln-renderer.internal', this.ports.renderInterceptor),+ signal,+ );+ check();+ container.start({+ image,+ enableInternet: false,+ instance: 'standard-1',+ env: { KILN_PUBLIC_ORIGIN: this.ports.publicOrigin },+ });+ void container.monitor().then(+ () => this.stopped.abort(),+ () => this.stopped.abort(),+ );+ await untilAbort(container.setInactivityTimeout(120_000), signal);+ const port = container.getTcpPort(3000);+ for (;;) {+ check();+ try {+ const ready = await untilAbort(+ port.fetch(new Request('http://kiln-native.internal/_ready', { signal })),+ signal,+ );+ void ready.body?.cancel().catch(() => {});+ if (ready.status === 204) break;+ } catch {+ if (signal.aborted) throw new HttpFailure(499, 'Request cancelled');+ }+ await untilAbort(new Promise((resolve) => setTimeout(resolve, 100)), signal);+ }+ const observed = await untilAbort(container.inspect(), signal);+ check();+ if (observed?.image !== image) throw new HttpFailure(503, 'Native host is unavailable');+ const incoming = new Request('http://kiln-native.internal/mcp', {+ method: request.method,+ headers,+ body: request.body === null ? undefined : body,+ signal,+ redirect: 'manual',+ });+ const pending = port.fetch(incoming).then((result) => {+ if (signal.aborted) void result.body?.cancel().catch(() => {});+ return result;+ });+ response = await untilAbort(pending, signal);+ check();+ if (response.status >= 300 && response.status < 400)+ throw new HttpFailure(502, 'Invalid native response');+ const bytes = await readBounded(response.body, 32 * 1024 * 1024, signal);+ check();+ const outgoing = new Headers();+ for (const key of ['content-type', 'mcp-protocol-version', 'allow']) {+ const value = response.headers.get(key);+ if (value && value.length <= 512) outgoing.set(key, value);+ }+ return privateResponse(+ new Response(bytes.length ? bytes : null, { status: response.status, headers: outgoing }),+ );+ } catch (error) {+ void response?.body?.cancel().catch(() => {});+ if (deadlineExpired || Date.now() >= deadlineAt)+ throw new HttpFailure(504, 'Native request timed out');+ throw error instanceof HttpFailure+ ? error+ : new HttpFailure(503, 'Native host is unavailable');+ } finally {+ clearTimeout(timer);+ await this.cancel();+ }+ }++ async storageRequest(request: Request): Promise<Response> {+ const url = new URL(request.url);+ const path = url.pathname;+ const permitted =+ request.method === 'GET'+ ? path === '/internal/programs' ||+ /^\/internal\/programs\/[^/]+$/.test(path) ||+ /^\/internal\/assets\/[^/]+\/[^/]+\/[^/]+$/.test(path) ||+ /^\/internal\/materials\/[a-z][a-z0-9_-]{0,79}\/[a-f0-9]{64}$/.test(path) ||+ /^\/mcp\/artifacts\/[a-f0-9]{32}$/.test(path)+ : request.method === 'POST'+ ? [+ '/internal/programs',+ '/internal/artifacts',+ '/internal/artifacts/discard',+ '/internal/assets/list',+ '/internal/assets/commit',+ '/internal/materials/list',+ '/internal/materials/commit',+ '/internal/downloads',+ ].includes(path)+ : request.method === 'DELETE' && /^\/internal\/groups\/[a-f0-9]{32}$/.test(path);+ if (url.href !== `http://kiln-storage.internal${path}` || !permitted)+ throw new HttpFailure(400, 'Invalid storage request');+ const headers = checkHeaders(request, STORAGE_HEADERS, true);+ const record = await this.active();+ const signal = AbortSignal.any([request.signal, this.stopped.signal]);+ const incoming = new Request(request, { headers, signal, redirect: 'manual' });+ const pending = this.ports+ .storage(record.tenant, new Request(`https://tenant.internal${path}`, incoming))+ .then((result) => {+ if (signal.aborted) void result.body?.cancel().catch(() => {});+ return result;+ });+ return untilAbort(pending, signal);+ }++ evaluateRequest(request: Request): Promise<Response> {+ return this.executionRequest('evaluation', request);+ }++ renderRequest(request: Request): Promise<Response> {+ return this.executionRequest('render', request);+ }++ private cancelChild(kind: ExecutionKind, id: string): Promise<void> {+ return kind === 'evaluation' ? this.ports.cancelEvaluation(id) : this.ports.cancelRender(id);+ }++ private async executionRequest(kind: ExecutionKind, request: Request): Promise<Response> {+ const profile = EXECUTION_PROFILES[kind];+ if (request.url !== profile.url || request.method !== 'POST')+ throw new HttpFailure(400, 'Invalid execution request');+ const headers = checkHeaders(request, EVALUATION_HEADERS, true);+ const id = crypto.randomUUID();+ const record = await this.context.storage.transaction(async (tx) => {+ this.check();+ const record = await tx.get<RequestRecord>('request');+ this.check();+ if (record?.state !== 'running' || Date.now() >= record.deadlineAt)+ throw new HttpFailure(409, 'Native request is not active');+ if (record.activeChild || record.children.length >= 8)+ throw new HttpFailure(429, 'Execution limit reached');+ record.children.push({ id, kind });+ record.activeChild = id;+ await tx.put('request', record);+ return record;+ });+ let response: Response | undefined;+ const signal = AbortSignal.any([request.signal, this.stopped.signal]);+ try {+ this.check();+ const requested = Number(headers.get('x-kiln-deadline-ms'));+ if (!Number.isSafeInteger(requested) || requested < 1 || requested > profile.deadlineMs)+ throw new HttpFailure(400, 'Invalid execution limit');+ const remaining = Math.min(requested, record.deadlineAt - Date.now());+ if (remaining < 1) throw new HttpFailure(504, 'Native request timed out');+ headers.set('x-kiln-deadline-ms', String(remaining));+ const incoming = new Request(request, { headers, signal });+ const execution =+ kind === 'evaluation' ? this.ports.evaluate(id, incoming) : this.ports.render(id, incoming);+ const pending = execution.then((result) => {+ if (signal.aborted) void result.body?.cancel().catch(() => {});+ return result;+ });+ response = await untilAbort(pending, signal);+ await cleanupChild(this.cancelChild(kind, id));+ await this.context.storage.transaction(async (tx) => {+ const current = await tx.get<RequestRecord>('request');+ if (current?.activeChild === id) {+ delete current.activeChild;+ await tx.put('request', current);+ }+ });+ this.check();+ return response;+ } catch (error) {+ void response?.body?.cancel().catch(() => {});+ throw error;+ }+ }++ cancel(): Promise<void> {+ this.stopped.abort();+ if (this.closing) return this.closing;+ const pending = this.close();+ this.closing = pending;+ const done = () => {+ if (this.closing === pending) this.closing = undefined;+ };+ void pending.then(done, done);+ return pending;+ }++ private async close(): Promise<void> {+ const record = await this.context.storage.transaction(async (tx) => {+ const record = await tx.get<RequestRecord>('request');+ if (!record) {+ await tx.put('request', {+ state: 'finished',+ deadlineAt: Date.now(),+ children: [],+ } satisfies RequestRecord);+ return undefined;+ }+ if (record.state === 'finished') return undefined;+ record.state = 'closing';+ await tx.put('request', record);+ await tx.setAlarm(Date.now());+ return record;+ });+ if (!record) return;+ try {+ const container = this.context.container;+ if (!container) throw new ContainerJobFailure('CLEANUP_FAILED');+ const results = await Promise.allSettled([+ destroyContainer(container),+ ...record.children.map(({ id, kind }) => cleanupChild(this.cancelChild(kind, id))),+ ]);+ if (results.some((result) => result.status === 'rejected'))+ throw new ContainerJobFailure('CLEANUP_FAILED');+ await this.context.storage.put('request', {+ ...record,+ state: 'finished',+ activeChild: undefined,+ } satisfies RequestRecord);+ await this.context.storage.deleteAlarm();+ } catch {+ await this.context.storage.setAlarm(Date.now() + 30_000);+ throw new ContainerJobFailure('CLEANUP_FAILED');+ }+ }++ async alarm(): Promise<void> {+ const record = await this.context.storage.get<RequestRecord>('request');+ if (!record || record.state === 'finished') {+ await this.context.storage.deleteAlarm();+ return;+ }+ if (record.state === 'running' && Date.now() < record.deadlineAt) {+ await this.context.storage.setAlarm(record.deadlineAt);+ return;+ }+ await this.cancel();+ }+}diff --git a/hosting/src/request-limits.ts b/hosting/src/request-limits.tsnew file mode 100644index 00000000..fd0bc66f--- /dev/null+++ b/hosting/src/request-limits.ts@@ -0,0 +1,89 @@+import { privateResponse, sha256 } from './http';++export interface RequestLimitEnv {+ EDGE_REQUEST_LIMIT: RateLimit;+ ACCOUNT_REQUEST_LIMIT: RateLimit;+}+function refused(request: Request, status: 401 | 429 | 503): Response {+ if (!request.bodyUsed) void request.body?.cancel().catch(() => {});+ return privateResponse(+ new Response(+ status === 429+ ? 'Too many requests. Try again shortly.'+ : status === 401+ ? 'Invalid identity'+ : 'Service temporarily unavailable',+ {+ status,+ headers: status === 429 ? { 'retry-after': '60' } : undefined,+ },+ ),+ );+}++const usable = (binding: RateLimit | undefined) => typeof binding?.limit === 'function';+async function check(+ request: Request,+ binding: RateLimit,+ key: string,+): Promise<Response | undefined> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ if (!usable(binding)) return refused(request, 503);+ const result = await Promise.race([+ binding.limit({ key }),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Limiter deadline')), 1000);+ }),+ ]);+ if (!result || typeof result.success !== 'boolean') return refused(request, 503);+ return result.success ? undefined : refused(request, 429);+ } catch {+ return refused(request, 503);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++/** Fixed classes bound anonymous work without storing IPs, credentials or URLs. */+export function routeClass(path: string): string {+ if (path === '/register') return 'registration';+ if (path.startsWith('/oauth/token')) return 'token';+ if (path === '/authorize' || path === '/account/login') return 'sign-in';+ if (path === '/oauth/google/callback' || path === '/oauth/github/callback') return 'callback';+ if (path === '/account' || path.startsWith('/account/')) return 'account';+ if (path.startsWith('/downloads/')) return 'download';+ if (path === '/mcp' || path.startsWith('/mcp/')) return 'mcp';+ if (path.startsWith('/.well-known/')) return 'discovery';+ return 'other';+}++export async function limitIngress(+ request: Request,+ env: RequestLimitEnv,+ origin: string,+): Promise<Response | undefined> {+ if (!usable(env.EDGE_REQUEST_LIMIT) || !usable(env.ACCOUNT_REQUEST_LIMIT))+ return refused(request, 503);+ return check(+ request,+ env.EDGE_REQUEST_LIMIT,+ `kiln-ingress-v1:${origin}:${routeClass(new URL(request.url).pathname)}`,+ );+}++/** Invoke only with verified account ownership, never a token or caller selector. */+export async function limitAccount(+ request: Request,+ env: Pick<RequestLimitEnv, 'ACCOUNT_REQUEST_LIMIT'>,+ origin: string,+ accountId: string,+): Promise<Response | undefined> {+ if (typeof accountId !== 'string' || !/^ka_[a-f0-9]{32}(?![\s\S])/.test(accountId))+ return refused(request, 401);+ return check(+ request,+ env.ACCOUNT_REQUEST_LIMIT,+ `kiln-account-rate-v1:${await sha256(JSON.stringify([origin, accountId]))}`,+ );+}diff --git a/hosting/src/request-worker.ts b/hosting/src/request-worker.tsnew file mode 100644index 00000000..7ae1fe04--- /dev/null+++ b/hosting/src/request-worker.ts@@ -0,0 +1,129 @@+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';+import type { KilnEvaluationJob } from './evaluation-worker';+import type { KilnRenderJob } from './render-worker';+import { NativeRequestJob } from './request-job';+import { privateResponse, serviceFailure } from './http';++interface RequestEnv {+ PUBLIC_ORIGIN: string;+ TENANTS: DurableObjectNamespace;+ REQUESTS: DurableObjectNamespace<KilnNativeRequest>;+ EVALUATIONS: DurableObjectNamespace<KilnEvaluationJob>;+ RENDERS: DurableObjectNamespace<KilnRenderJob>;+}+interface InterceptorProps {+ requestId: string;+}++/** Private binding only. The admission service chooses the tenant and request ID. */+export class KilnNativeRequest extends DurableObject<RequestEnv> {+ private readonly job: NativeRequestJob;++ constructor(ctx: DurableObjectState, env: RequestEnv) {+ super(ctx, env);+ const loopback = ctx.exports as {+ KilnNativeStorage: LoopbackForExport<typeof KilnNativeStorage>;+ KilnNativeEvaluation: LoopbackForExport<typeof KilnNativeEvaluation>;+ KilnNativeRender: LoopbackForExport<typeof KilnNativeRender>;+ };+ const props = { requestId: ctx.id.toString() };+ this.job = new NativeRequestJob(ctx, {+ publicOrigin: env.PUBLIC_ORIGIN,+ storageInterceptor: loopback.KilnNativeStorage({ props }),+ evaluationInterceptor: loopback.KilnNativeEvaluation({ props }),+ renderInterceptor: loopback.KilnNativeRender({ props }),+ storage: (tenant, request) => env.TENANTS.getByName(tenant).fetch(request),+ evaluate: (id, request) => env.EVALUATIONS.getByName(id).fetch(request),+ cancelEvaluation: async (id) => {+ await env.EVALUATIONS.getByName(id).cancel();+ },+ render: (id, request) => env.RENDERS.getByName(id).fetch(request),+ cancelRender: async (id) => {+ await env.RENDERS.getByName(id).cancel();+ },+ });+ }++ async run(tenant: string, request: Request, deadlineAt: number): Promise<Response> {+ try {+ return await this.job.run(tenant, request, deadlineAt);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ } finally {+ // Configuration/one-use checks can reject before the RPC body is read.+ // Close that stream so it cannot retain the caller's execution context.+ if (!request.bodyUsed) await request.body?.cancel().catch(() => {});+ }+ }+ async storage(request: Request): Promise<Response> {+ // Convert deliberate HTTP errors before RPC serializes away their prototype.+ try {+ return await this.job.storageRequest(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+ async evaluate(request: Request): Promise<Response> {+ try {+ return await this.job.evaluateRequest(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+ cancel(): Promise<void> {+ return this.job.cancel();+ }+ async render(request: Request): Promise<Response> {+ try {+ return await this.job.renderRequest(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+ alarm(): Promise<void> {+ return this.job.alarm();+ }+}++/** No HTTP field chooses a request object; only the host-configured binding props do. */+export class KilnNativeStorage extends WorkerEntrypoint<RequestEnv, InterceptorProps> {+ async fetch(request: Request): Promise<Response> {+ try {+ if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');+ const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);+ return await this.env.REQUESTS.get(id).storage(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+}++export class KilnNativeEvaluation extends WorkerEntrypoint<RequestEnv, InterceptorProps> {+ async fetch(request: Request): Promise<Response> {+ try {+ if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');+ const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);+ return await this.env.REQUESTS.get(id).evaluate(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+}++export class KilnNativeRender extends WorkerEntrypoint<RequestEnv, InterceptorProps> {+ async fetch(request: Request): Promise<Response> {+ try {+ if (!/^[a-f0-9]{64}$/.test(this.ctx.props.requestId)) throw new Error('Invalid binding');+ const id = this.env.REQUESTS.idFromString(this.ctx.props.requestId);+ return await this.env.REQUESTS.get(id).render(request);+ } catch (error) {+ return privateResponse(serviceFailure(error));+ }+ }+}++export default {+ fetch(): Response {+ return new Response('Not found', { status: 404 });+ },+};diff --git a/hosting/src/tenant-identity.ts b/hosting/src/tenant-identity.tsnew file mode 100644index 00000000..4a3cd518--- /dev/null+++ b/hosting/src/tenant-identity.ts@@ -0,0 +1,8 @@+import { HttpFailure, sha256 } from './http';++/** Only a verified MCP grant or current primary browser session may supply userId. */+export function tenantForAccount(origin: string, userId: string): Promise<string> {+ if (typeof userId !== 'string' || !/^ka_[a-f0-9]{32}(?![\s\S])/.test(userId))+ throw new HttpFailure(401, 'Invalid identity');+ return sha256(JSON.stringify(['kiln-tenant-v1', origin, userId]));+}diff --git a/hosting/src/tenant.ts b/hosting/src/tenant.tsindex d2d5b60e..c66423fe 100644--- a/hosting/src/tenant.ts+++ b/hosting/src/tenant.ts@@ -4,6 +4,20 @@ import { boundedRequest, HttpFailure, privateResponse, readBounded, serviceFailuimport { decodeProgram, HostedProgramStore } from './programs';import { MAX_PROGRAM_BYTES } from '../../src/program-store';import { AssetIndex } from './asset-index';+import { AssetDownloadTickets } from './asset-downloads';+import { parseDownloadPath } from './download-path';+import { MaterialIndex } from './material-index';++const retirementHeaders = new Set([+ 'content-length',+ 'accept',+ 'accept-encoding',+ 'accept-language',+ 'connection',+ 'host',+ 'user-agent',+ 'sec-fetch-mode',+]);export interface TenantStorageEnv {ARTIFACTS: R2Bucket;@@ -16,6 +30,8 @@ export class KilnTenant extends DurableObject<TenantStorageEnv> {private readonly artifacts: ArtifactStore;private readonly programs: HostedProgramStore;private readonly assets: AssetIndex;+ private readonly downloads: AssetDownloadTickets;+ private readonly materials: MaterialIndex;constructor(ctx: DurableObjectState, env: TenantStorageEnv) {super(ctx, env);@@ -26,9 +42,13 @@ export class KilnTenant extends DurableObject<TenantStorageEnv> {});this.programs = new HostedProgramStore(this.artifacts);this.assets = new AssetIndex(this.artifacts);+ this.materials = new MaterialIndex(this.artifacts);+ this.downloads = new AssetDownloadTickets(ctx.storage, this.artifacts, this.assets);}async alarm(): Promise<void> {+ if (this.artifacts.retirementStatus().state !== 'active') this.downloads.revokeAll();+ this.downloads.sweep();await this.artifacts.sweep();}@@ -37,6 +57,56 @@ export class KilnTenant extends DurableObject<TenantStorageEnv> {const url = new URL(request.url);if (url.origin !== 'https://tenant.internal' || url.search)throw new HttpFailure(400, 'Invalid internal request');+ if (url.pathname === '/internal/account-deletion') {+ if (+ request.method !== 'POST' ||+ [...request.headers].some(+ ([name, value]) => !retirementHeaders.has(name) || value.length > 512,+ ) ||+ ![null, '0'].includes(request.headers.get('content-length'))+ )+ throw new HttpFailure(400, 'Invalid storage retirement');+ await readBounded(request.body, 0, request.signal);+ const result = await this.artifacts.retire(() => this.downloads.revokeAll());+ return privateResponse(Response.json(result));+ }+ this.artifacts.assertActive();+ if (url.pathname === '/internal/downloads' && request.method === 'POST') {+ if (request.headers.get('content-type')?.split(';')[0] !== 'application/json')+ throw new HttpFailure(415, 'Expected download selection');+ const bounded = await boundedRequest(request, 1024);+ let value: unknown;+ try {+ value = await bounded.json();+ } catch {+ throw new HttpFailure(400, 'Invalid download selection');+ }+ if (+ !value ||+ typeof value !== 'object' ||+ Array.isArray(value) ||+ Object.keys(value).some((key) => !['collection', 'assetId', 'revisionId'].includes(key))+ )+ throw new HttpFailure(400, 'Invalid download selection');+ const input = value as Record<string, unknown>;+ return privateResponse(+ Response.json(+ await this.downloads.issue(input.collection, input.assetId, input.revisionId),+ { status: 201 },+ ),+ );+ }+ if (url.pathname.startsWith('/internal/downloads/')) {+ const selected = parseDownloadPath(url.pathname.slice('/internal'.length));+ if (!selected) throw new HttpFailure(404, 'Download link unavailable; request a new link');+ if (!['GET', 'HEAD'].includes(request.method))+ return new Response('Method not allowed', { status: 405 });+ return await this.downloads.download(+ selected.token,+ selected.filename,+ request.method === 'HEAD',+ );+ }if (['/internal/assets/commit', '/internal/assets/list'].includes(url.pathname) &&request.method === 'POST'@@ -58,6 +128,29 @@ export class KilnTenant extends DurableObject<TenantStorageEnv> {const asset = url.pathname.match(/^\/internal\/assets\/([^/]+)\/([^/]+)\/([^/]+)$/);if (asset && request.method === 'GET')return privateResponse(Response.json(this.assets.read(asset[1], asset[2], asset[3])));+ if (+ ['/internal/materials/commit', '/internal/materials/list'].includes(url.pathname) &&+ request.method === 'POST'+ ) {+ const bounded = await boundedRequest(request, 2048);+ let input: unknown;+ try {+ input = await bounded.json();+ } catch {+ throw new HttpFailure(400, 'Invalid saved material');+ }+ if (url.pathname.endsWith('/list'))+ return privateResponse(Response.json(this.materials.list(input)));+ const result = this.materials.commit(input);+ return privateResponse(+ Response.json(result.record, { status: result.created ? 201 : 200 }),+ );+ }+ const material = url.pathname.match(/^\/internal\/materials\/([^/]+)\/([a-f0-9]{64})$/);+ if (material && request.method === 'GET')+ return privateResponse(+ Response.json(this.materials.read(material[1], `sha256:${material[2]}`)),+ );if (url.pathname === '/internal/programs' && request.method === 'GET') {return privateResponse(Response.json({ ...(await this.programs.stats()), retention: this.programs.retention }),@@ -140,8 +233,10 @@ export class KilnTenant extends DurableObject<TenantStorageEnv> {}if (url.pathname === '/internal/usage' && request.method === 'GET')return privateResponse(Response.json(this.artifacts.usage()));- if (url.pathname === '/internal/maintenance' && request.method === 'POST')+ if (url.pathname === '/internal/maintenance' && request.method === 'POST') {+ this.downloads.sweep();return privateResponse(Response.json(await this.artifacts.sweep()));+ }if (url.pathname === '/mcp')return new Response('Native engine is not configured or qualified', { status: 503 });return new Response('Not found', { status: 404 });diff --git a/hosting/src/worker.ts b/hosting/src/worker.tsindex f936e190..cb055e4a 100644--- a/hosting/src/worker.ts+++ b/hosting/src/worker.ts@@ -3,53 +3,109 @@ import {OAuthError,OAuthResourceServer,} from '@cloudflare/workers-oauth-provider';-import { isCurrentAccountGrant } from './accounts';+import { D1Connections } from './connections';+import { accountPage } from './account-page';+import { beginBrowserLogin } from './browser-login';+import { beginAccountAction } from './account-actions';+import { beginIdentityAction } from './identity-actions';+import { beginDeletionAction, accountDeletionStatus } from './deletion-actions';+import { browserDownload } from './browser-download';+import { publicPage } from './public-pages';import { authorize, authorizationFailure, SCOPES, type SignInEnv } from './auth';import { forwardTenant, type TenantEnv } from './gateway';import { boundedRequest, HttpFailure, privateResponse } from './http';+import { recoverAccountDeletions } from './deletion-recovery';+import { limitIngress, type RequestLimitEnv } from './request-limits';+import {+ recordResponse,+ recordHealth,+ readOperationalHealth,+ type OperationsEnv,+} from './operations';-export interface Env extends SignInEnv, TenantEnv {+export interface Env extends SignInEnv, TenantEnv, RequestLimitEnv, OperationsEnv {OAUTH_KV: KVNamespace;PUBLIC_ORIGIN: string;}-export default {+function publicOrigin(env: Env): string {+ const configured = new URL(env.PUBLIC_ORIGIN);+ if (configured.protocol !== 'https:' || configured.origin !== env.PUBLIC_ORIGIN)+ throw new Error('Invalid origin configuration');+ return configured.origin;+}++function authorizationServer(origin: string) {+ return new OAuthAuthorizationServer<Env>({+ issuer: origin,+ resources: [`${origin}/mcp`],+ authorizeEndpoint: `${origin}/authorize`,+ tokenEndpoint: `${origin}/oauth/token`,+ clientRegistrationEndpoint: `${origin}/register`,+ clientIdMetadataDocumentEnabled: true,+ scopesSupported: SCOPES,+ accessTokenTTL: 900,+ refreshTokenTTL: 30 * 24 * 60 * 60,+ tokenExchangeCallback: async ({+ env: bindings,+ userId,+ props,+ clientId,+ grantId,+ grantType,+ }) => {+ if (+ !(await new D1Connections(bindings.ACCOUNTS).exchange(+ userId,+ props,+ clientId,+ grantId,+ grantType,+ ))+ )+ throw new OAuthError('invalid_grant', {+ description: 'Account authorization changed; sign in again',+ });+ },+ // Deliberately do not log request data or provider error descriptions.+ onError: () => {},+ });+}++const gateway = {+ async scheduled(_event: ScheduledController, env: Env): Promise<void> {+ const origin = publicOrigin(env);+ try {+ await recoverAccountDeletions(env, origin, authorizationServer(origin).getOAuthApi(env));+ } catch {+ throw new Error('Account deletion recovery unavailable');+ }+ },async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {try {- const configured = new URL(env.PUBLIC_ORIGIN);- if (configured.protocol !== 'https:' || configured.origin !== env.PUBLIC_ORIGIN)- throw new Error('Invalid origin configuration');- const origin = configured.origin;+ const origin = publicOrigin(env);const url = new URL(request.url);if (url.origin !== origin) throw new HttpFailure(421, 'Invalid request origin');if (url.href.length > 16_384) throw new HttpFailure(414, 'URL too long');+ const limited = await limitIngress(request, env, origin);+ if (limited) return limited;+ const information = publicPage(request, origin);+ if (information) return privateResponse(information);const resource = `${origin}/mcp`;- const auth = new OAuthAuthorizationServer<Env>({- issuer: origin,- resources: [resource],- authorizeEndpoint: `${origin}/authorize`,- tokenEndpoint: `${origin}/oauth/token`,- clientRegistrationEndpoint: `${origin}/register`,- clientIdMetadataDocumentEnabled: true,- scopesSupported: SCOPES,- accessTokenTTL: 900,- refreshTokenTTL: 30 * 24 * 60 * 60,- tokenExchangeCallback: async ({ env: bindings, userId, props }) => {- if (!(await isCurrentAccountGrant(bindings.ACCOUNTS, userId, props)))- throw new OAuthError('invalid_grant', {- description: 'Account authorization changed; sign in again',- });- },- // Deliberately do not log request data or provider error descriptions.- onError: () => {},- });+ const auth = authorizationServer(origin);const protectedResource = new OAuthResourceServer<Env>({resourceMetadata: { resource, authorization_servers: [origin] },requiredScopes: ['kiln:use'],validateToken: (bindings) => async (audience, token) => {const verified = await auth.validateToken(audience, token, bindings);if (!verified) return null;- if (!(await isCurrentAccountGrant(bindings.ACCOUNTS, verified.userId, verified.props)))+ if (+ !(await new D1Connections(bindings.ACCOUNTS).accepts(+ verified.userId,+ verified.props,+ verified.clientId,+ ))+ )throw new OAuthError('invalid_token', {description: 'Account authorization changed; sign in again',});@@ -72,8 +128,18 @@ export default {if (url.search)throw new HttpFailure(400, 'Query parameters are not supported on resource endpoints');response = await protectedResource.fetch(request, env, ctx);+ } else if (url.pathname.startsWith('/downloads/')) {+ response = await browserDownload(request, env, origin);+ } else if (url.pathname === '/account/deletion') {+ response = await accountDeletionStatus(request, env.ACCOUNTS, origin);+ } else if (url.pathname === '/account' || url.pathname === '/account/logout') {+ response = await accountPage(await boundedRequest(request, 4096), env.ACCOUNTS, origin);} else if (url.pathname === '/authorize' ||+ url.pathname === '/account/login' ||+ url.pathname === '/account/action' ||+ url.pathname === '/account/identity' ||+ url.pathname === '/account/delete' ||url.pathname === '/oauth/github/callback' ||url.pathname === '/oauth/google/callback') {@@ -85,12 +151,26 @@ export default {!env.ACCOUNTS)throw new HttpFailure(503, 'Sign-in is not configured');- response = await authorize(- await boundedRequest(request, 16_384),- auth.getOAuthApi(env),- origin,- env,- );+ response =+ url.pathname === '/account/delete'+ ? await beginDeletionAction(await boundedRequest(request, 4096), origin, env)+ : url.pathname === '/account/identity'+ ? await beginIdentityAction(await boundedRequest(request, 4096), origin, env)+ : url.pathname === '/account/action'+ ? await beginAccountAction(await boundedRequest(request, 4096), origin, env)+ : url.pathname === '/account/login'+ ? await beginBrowserLogin(await boundedRequest(request, 4096), origin, env)+ : await authorize(+ await boundedRequest(request, 16_384),+ auth.getOAuthApi(env),+ origin,+ env,+ ctx,+ );+ if (response.status === 303 && response.headers.get('location') === '/account/deletion')+ ctx.waitUntil(+ recoverAccountDeletions(env, origin, auth.getOAuthApi(env)).catch(() => {}),+ );} else if (url.pathname === '/register' ||url.pathname.startsWith('/oauth/token') ||@@ -106,3 +186,30 @@ export default {}},} satisfies ExportedHandler<Env>;++export default {+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {+ const started = performance.now();+ const response = await gateway.fetch(request, env, ctx);+ recordResponse(+ env,+ new URL(request.url).pathname,+ response.status,+ performance.now() - started,+ );+ return response;+ },+ async scheduled(event: ScheduledController, env: Env): Promise<void> {+ let recovered = false;+ try {+ await gateway.scheduled(event, env);+ recovered = true;+ } catch {+ /* Emit component health without recording the underlying exception. */+ }+ const health = await readOperationalHealth(env);+ recordHealth(env, health, recovered);+ if (!recovered || !health.deletion || !health.compute)+ throw new Error('Hosted recovery or health check unavailable');+ },+} satisfies ExportedHandler<Env>;diff --git a/hosting/test/admission-worker.test.mjs b/hosting/test/admission-worker.test.mjsnew file mode 100644index 00000000..bf383e3c--- /dev/null+++ b/hosting/test/admission-worker.test.mjs@@ -0,0 +1,154 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';++let runtime, compute, operator, raw;+before(async () => {+ const bundle = await build({+ stdin: {+ contents: `+ import {DurableObject} from 'cloudflare:workers';+ export * from './src/admission-worker';+ export {default} from './src/admission-worker';+ export class FakeRequest extends DurableObject {+ async run(tenant,request,deadlineAt) {+ const before=await this.env.ADMISSION.getByName('global-v1').status();+ return Response.json({tenant,body:await request.text(),headers:Object.fromEntries(request.headers),before,deadlineAt});+ }+ async cancel(){await this.ctx.storage.put('stopped',true);}+ }+ `,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ workers: [+ {+ name: 'admission',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: {+ ADMISSION: { className: 'KilnAdmission', useSQLite: true },+ REQUESTS: { className: 'FakeRequest', useSQLite: true },+ },+ bindings: {+ COMPUTE_MAX_CONCURRENT: '2',+ COMPUTE_TENANT_PER_MINUTE: '5',+ COMPUTE_TENANT_PER_DAY: '10',+ COMPUTE_GLOBAL_PER_DAY: '2',+ COMPUTE_GLOBAL_PER_MONTH: '3',+ COMPUTE_DEADLINE_MS: '60000',+ },+ },+ {+ name: 'unconfigured-admission',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: {+ ADMISSION: { className: 'KilnAdmission', useSQLite: true },+ REQUESTS: { className: 'FakeRequest', useSQLite: true },+ },+ },+ {+ name: 'gateway-fixture',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: {+ COMPUTE: { name: 'admission', entrypoint: 'KilnCompute' },+ UNCONFIGURED: { name: 'unconfigured-admission', entrypoint: 'KilnCompute' },+ },+ script: `+ export default {async fetch(request,env){+ const url=new URL(request.url);+ if(url.pathname==='/private-http')return env.COMPUTE.fetch(request);+ if(url.pathname==='/health')return Response.json(await env.COMPUTE.health());+ if(url.pathname==='/missing-policy')return env.UNCONFIGURED.dispatch('a'.repeat(43),new Request('https://tenant.internal/mcp'));+ if(url.pathname==='/try-pause') {try {await env.COMPUTE.setPaused(true);return new Response('exposed');}catch{return new Response('unavailable',{status:404});}}+ if(url.pathname==='/retire') {await env.COMPUTE.retireTenant('z'.repeat(43));return Response.json({retired:true});}+ return env.COMPUTE.dispatch(url.searchParams.get('tenant').repeat(43),new Request('https://tenant.internal/mcp',{method:'POST',headers:{'content-type':'application/json'},body:'{}'}));+ }};`,+ },+ {+ name: 'operator-fixture',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: { CONTROL: { name: 'admission', entrypoint: 'KilnComputeControl' } },+ script: `+ export default {async fetch(request,env){const url=new URL(request.url);if(url.pathname==='/pause')return Response.json(await env.CONTROL.setPaused(true));if(url.pathname==='/resume')return Response.json(await env.CONTROL.setPaused(false));return Response.json(await env.CONTROL.status());}};`,+ },+ ],+ }),+ );+ compute = await runtime.getWorker('gateway-fixture');+ operator = await runtime.getWorker('operator-fixture');+ raw = await runtime.getWorker('admission');+});+after(async () => runtime?.dispose());++test('private entrypoint selects one global authority across accounts and exposes no public or operator API', async () => {+ assert.equal((await raw.fetch('https://test.invalid/')).status, 404);+ assert.equal((await compute.fetch('https://test.invalid/private-http')).status, 404);+ assert.equal((await compute.fetch('https://test.invalid/try-pause')).status, 404);+ for (const tenant of ['a', 'b']) {+ const response = await compute.fetch(`https://test.invalid/?tenant=${tenant}`);+ assert.equal(response.status, 200);+ const data = await response.json();+ assert.equal(data.tenant, tenant.repeat(43));+ assert.equal(data.before.activeRequests, 1);+ assert.equal(data.body, '{}');+ assert.equal(data.headers.authorization, undefined);+ assert.equal((await (await operator.fetch('https://test.invalid/')).json()).activeRequests, 0);+ }+ assert.equal((await compute.fetch('https://test.invalid/?tenant=c')).status, 429);+});++test('read-only compute health exposes aggregates without changing admission or exposing pause', async () => {+ const before = await (await operator.fetch('https://test.invalid/')).json();+ assert.deepEqual(await (await compute.fetch('https://test.invalid/health')).json(), before);+ assert.deepEqual(await (await operator.fetch('https://test.invalid/')).json(), before);+ assert.equal((await compute.fetch('https://test.invalid/try-pause')).status, 404);+ assert.equal((await raw.fetch('https://test.invalid/health')).status, 404);+});++test('separate operator binding pauses and resumes without exposing account identifiers', async () => {+ const paused = await (await operator.fetch('https://test.invalid/pause')).json();+ assert.equal(paused.paused, true);+ assert.equal(paused.activeRequests, 0);+ assert.equal((await compute.fetch('https://test.invalid/?tenant=d')).status, 503);+ const resumed = await (await operator.fetch('https://test.invalid/resume')).json();+ assert.equal(resumed.paused, false);+ assert.deepEqual(Object.keys(resumed).sort(), [+ 'activeRequests',+ 'maxConcurrent',+ 'paused',+ 'pendingCleanup',+ ]);+});++test('absent quota configuration refuses work instead of selecting implicit launch limits', async () => {+ const response = await compute.fetch('https://test.invalid/missing-policy');+ assert.equal(response.status, 503);+ assert.equal(await response.text(), 'Service temporarily unavailable');+});++test('verified gateway lifecycle RPC permanently retires a tenant without a public route', async () => {+ assert.equal((await raw.fetch('https://test.invalid/retire')).status, 404);+ assert.deepEqual(await (await compute.fetch('https://test.invalid/retire')).json(), {+ retired: true,+ });+ assert.equal((await compute.fetch('https://test.invalid/?tenant=z')).status, 410);+ assert.deepEqual(await (await compute.fetch('https://test.invalid/retire')).json(), {+ retired: true,+ });+});diff --git a/hosting/test/admission.test.mjs b/hosting/test/admission.test.mjsnew file mode 100644index 00000000..59fe8ece--- /dev/null+++ b/hosting/test/admission.test.mjs@@ -0,0 +1,366 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';++let runtime;+before(async () => {+ const bundle = await build({+ stdin: {+ contents: `+ import {DurableObject} from 'cloudflare:workers';+ import {ComputeAdmission, admissionFailure} from './src/admission';+ export class Fixture extends DurableObject {+ constructor(ctx,env) {+ super(ctx,env); this.pending=new Map(); this.cancelledBodies=0;+ this.admission=new ComputeAdmission(ctx.storage, {+ run: async (id,tenant,request,deadlineAt) => {+ const calls=await ctx.storage.get('calls')||[];+ calls.push({id,tenant,url:request.url,headers:Object.fromEntries(request.headers),deadlineAt});+ await ctx.storage.put('calls',calls);+ if(await ctx.storage.get('abortRace')) {+ this.requestAbort.abort();+ return new Response(new ReadableStream({cancel:()=>{this.cancelledBodies++;}}));+ }+ if(await ctx.storage.get('hold')) return new Promise(resolve=>this.pending.set(id,resolve));+ if(await ctx.storage.get('runFail')) throw Error('private diagnostic');+ return new Response('native result');+ },+ cancel: async id => {+ if(await ctx.storage.get('cancelFail')) throw Error('private cleanup diagnostic');+ const stopped=await ctx.storage.get('stopped')||[];+ stopped.push(id); await ctx.storage.put('stopped',stopped);+ this.pending.get(id)?.(new Response('cancelled',{status:499})); this.pending.delete(id);+ },+ }, {maxConcurrent:2,tenantPerMinute:3,tenantPerDay:4,globalPerDay:7,globalPerMonth:8,deadlineMs:env.FIXTURE_SHORT_DEADLINE===true?250:60000},+ ()=>ctx.storage.kv.get('now')??Date.now());+ }+ async dispatch(tenant,request) {+ this.requestAbort=new AbortController();+ try{return await this.admission.dispatch(tenant,new Request(request,{signal:this.requestAbort.signal}));}catch(e){return admissionFailure(e);}+ }+ async command(command,value) {+ if(command==='retire') {try{await this.admission.retireTenant(value);return {retired:true};}catch(e){return {retired:false,status:admissionFailure(e).status};}}+ if(command==='pause') return this.admission.setPaused(value);+ if(command==='alarm') return this.admission.alarm();+ if(command==='expire') {this.ctx.storage.sql.exec('UPDATE compute_active SET recover_at = 0');return;}+ if(command==='snapshot') return {+ active:this.ctx.storage.sql.exec('SELECT * FROM compute_active').toArray(),+ usage:this.ctx.storage.sql.exec('SELECT * FROM compute_usage').toArray(),+ calls:await this.ctx.storage.get('calls')||[], stopped:await this.ctx.storage.get('stopped')||[],+ alarm:await this.ctx.storage.getAlarm(),+ cancelledBodies:this.cancelledBodies,+ };+ await this.ctx.storage.put(command,value);+ }+ alarm(){return this.admission.alarm();}+ }+ export class ShortFixture extends Fixture {constructor(ctx,env){super(ctx,{...env,FIXTURE_SHORT_DEADLINE:true});}}+ export default {async fetch(request,env) {+ const url=new URL(request.url), stub=env[url.searchParams.has('short')?'SHORT':'FIXTURE'].getByName(url.searchParams.get('fixture'));+ if(url.pathname==='/command') {const {command,value}=await request.json();return Response.json((await stub.command(command,value))??null);}+ const headers=new Headers({'content-type':'application/json'});+ if(url.searchParams.has('hostile')) headers.set('authorization','Bearer must-never-leave');+ return stub.dispatch(url.searchParams.get('tenant'),new Request('https://tenant.internal/mcp',{method:'POST',headers,body:'{}'}));+ }};`,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare({+ ...convertV4MiniflareOptions({+ name: 'admission-fixture',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: {+ FIXTURE: { className: 'Fixture', useSQLite: true },+ SHORT: { className: 'ShortFixture', useSQLite: true },+ },+ outboundService: async () => {+ throw Error('No network');+ },+ }),+ unsafeInspectDurableObjects: true,+ });+});+after(async () => runtime?.dispose());++function fixture(short = false) {+ const id = crypto.randomUUID();+ return {+ id,+ request: (tenant = 'a', hostile = false) =>+ runtime.dispatchFetch(+ `https://test.invalid/?fixture=${id}&tenant=${tenant.repeat(43)}${hostile ? '&hostile=1' : ''}${short ? '&short=1' : ''}`,+ ),+ command: async (command, value) =>+ (+ await runtime.dispatchFetch(+ `https://test.invalid/command?fixture=${id}${short ? '&short=1' : ''}`,+ { method: 'POST', body: JSON.stringify({ command, value }) },+ )+ ).json(),+ };+}+async function waitFor(f, predicate) {+ const deadline = Date.now() + 3000;+ do {+ const snapshot = await f.command('snapshot');+ if (predicate(snapshot)) return snapshot;+ await new Promise((r) => setTimeout(r, 10));+ } while (Date.now() < deadline);+ assert.fail('Fixture did not reach expected state');+}++test('admission reserves before dispatch, uses a fresh job ID and releases only after cancellation acknowledgement', async () => {+ const f = fixture();+ const r = await f.request();+ assert.equal(r.status, 200);+ assert.equal(await r.text(), 'native result');+ await f.request();+ const s = await f.command('snapshot');+ assert.equal(s.active.length, 0);+ assert.equal(s.calls.length, 2);+ assert.notEqual(s.calls[0].id, s.calls[1].id);+ assert.deepEqual(+ s.stopped,+ s.calls.map((c) => c.id),+ );+ assert.equal(s.calls[0].tenant, 'a'.repeat(43));+ assert.equal(s.calls[0].url, 'https://tenant.internal/mcp');+ assert.deepEqual(s.calls[0].headers, { 'content-type': 'application/json' });+ assert.ok(s.alarm > 0);+});++test('only the explicit short-deadline fixture uses the 250 ms deadline', async () => {+ const now = Date.UTC(2030, 0, 2, 12);+ for (const [short, deadlineMs] of [+ [false, 60000],+ [true, 250],+ ]) {+ const f = fixture(short);+ await f.command('now', now);+ assert.equal((await f.request()).status, 200);+ const s = await f.command('snapshot');+ assert.equal(s.calls[0].deadlineAt - now, deadlineMs);+ }+});++test('concurrent admission enforces both one job per account and total capacity', async () => {+ const f = fixture();+ await f.command('hold', true);+ const alice = f.request('a');+ await waitFor(f, (s) => s.calls.length === 1);+ const duplicate = await f.request('a');+ assert.equal(duplicate.status, 429);+ assert.ok(duplicate.headers.get('retry-after'));+ const bob = f.request('b');+ await waitFor(f, (s) => s.calls.length === 2);+ assert.equal((await f.request('c')).status, 429);+ await f.command('pause', true);+ await Promise.all([alice, bob]);+ const s = await f.command('snapshot');+ assert.equal(s.calls.length, 2);+ assert.equal(s.active.length, 0);+ assert.equal((await f.request('c')).status, 503);+});++test('unknown cleanup suppresses output and retains capacity across object eviction until recovery confirms stop', async () => {+ const f = fixture();+ await f.command('cancelFail', true);+ const r = await f.request();+ assert.equal(r.status, 503);+ assert.equal((await r.text()).includes('diagnostic'), false);+ const first = await f.command('snapshot');+ assert.equal(first.active.length, 1);+ assert.equal(first.active[0].state, 'closing');+ assert.equal((await f.request()).status, 429);+ const ns = await runtime.getDurableObjectNamespace('FIXTURE');+ await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {+ id: ns.idFromName(f.id).toString(),+ });+ assert.equal((await f.command('snapshot')).active.length, 1);+ await f.command('cancelFail', false);+ await f.command('expire');+ await f.command('alarm');+ const recovered = await f.command('snapshot');+ assert.equal(recovered.active.length, 0);+ assert.deepEqual(recovered.stopped, [first.calls[0].id]);+ assert.equal((await f.request()).status, 200);+});++test('admitted failed work still consumes minute and daily quotas, with independent UTC windows', async () => {+ const f = fixture();+ const now = Date.UTC(2030, 0, 2, 12);+ await f.command('now', now);+ await f.command('runFail', true);+ for (let i = 0; i < 3; i++) assert.equal((await f.request()).status, 503);+ assert.equal((await f.request()).status, 429);+ await f.command('now', now + 60000);+ assert.equal((await f.request()).status, 503);+ assert.equal((await f.request()).status, 429);+ await f.command('now', now + 86400000);+ assert.equal((await f.request()).status, 503);+ assert.equal((await f.command('snapshot')).calls.length, 5);+});++test('global day and month counters apply across accounts and survive day rollover', async () => {+ const f = fixture(),+ now = Date.UTC(2030, 0, 2, 12);+ await f.command('now', now);+ for (const tenant of ['a', 'b', 'c', 'd', 'e', 'f', 'g'])+ assert.equal((await f.request(tenant)).status, 200);+ assert.equal((await f.request('h')).status, 429);+ await f.command('now', now + 86400000);+ assert.equal((await f.request('h')).status, 200);+ assert.equal((await f.request('i')).status, 429);+ await f.command('now', Date.UTC(2030, 1, 1));+ assert.equal((await f.request('i')).status, 200);+});++test('invalid identity and authority headers fail before consuming quota or starting work', async () => {+ const f = fixture();+ assert.equal((await f.request('invalid')).status, 400);+ assert.equal((await f.request('a', true)).status, 400);+ const s = await f.command('snapshot');+ assert.equal(s.calls.length, 0);+ assert.equal(s.active.length, 0);+ assert.equal(s.usage.length, 0);+});++test('operator pause is durable and cannot release unconfirmed cleanup', async () => {+ const f = fixture();+ await f.command('cancelFail', true);+ await f.request();+ await f.command('pause', true);+ assert.equal((await f.request('b')).status, 503);+ const ns = await runtime.getDurableObjectNamespace('FIXTURE');+ await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {+ id: ns.idFromName(f.id).toString(),+ });+ assert.equal((await f.request('b')).status, 503);+ assert.equal((await f.command('snapshot')).active.length, 1);+ await f.command('pause', false);+ assert.equal((await f.request('a')).status, 429);+});++test('a concurrent burst cannot overbook capacity or charge rejected attempts', async () => {+ const f = fixture();+ await f.command('hold', true);+ const requests = ['a', 'b', 'c', 'd', 'e'].map((tenant) => f.request(tenant));+ await waitFor(f, (s) => s.calls.length === 2);+ await f.command('pause', true);+ const responses = await Promise.all(requests);+ assert.equal(responses.filter((r) => r.status === 429).length, 3);+ const s = await f.command('snapshot');+ assert.equal(s.active.length, 0);+ assert.equal(s.calls.length, 2);+ assert.equal(s.usage.find((row) => row.owner === 'global' && row.period === 'month').used, 2);+});++test('an RPC that does not return is bounded by deadline and out-of-band cancellation', async () => {+ const f = fixture(true);+ await f.command('hold', true);+ assert.equal((await f.request()).status, 504);+ const s = await f.command('snapshot');+ assert.equal(s.active.length, 0);+ assert.equal(s.calls.length, 1);+ assert.deepEqual(s.stopped, [s.calls[0].id]);+});++test('maintenance retires expired usage counters and its alarm after an idle month', async () => {+ const f = fixture();+ await f.command('now', Date.UTC(2030, 0, 2));+ await f.request();+ assert.equal((await f.command('snapshot')).usage.length, 4);+ await f.command('now', Date.UTC(2030, 1, 1));+ await f.command('alarm');+ const s = await f.command('snapshot');+ assert.equal(s.usage.length, 0);+ assert.equal(s.alarm, null);+});++test('a response arriving in the same turn as cancellation has its discarded body closed', async () => {+ const f = fixture();+ await f.command('abortRace', true);+ assert.equal((await f.request()).status, 499);+ const s = await f.command('snapshot');+ assert.equal(s.active.length, 0);+ assert.equal(s.cancelledBodies, 1);+});++test('retired tenants cannot start work or consume quotas, including after eviction and resume', async () => {+ const f = fixture(),+ owner = 'a'.repeat(43);+ assert.deepEqual(await f.command('retire', owner), { retired: true });+ assert.equal((await f.request('a')).status, 410);+ assert.deepEqual((await f.command('snapshot')).usage, []);+ const ns = await runtime.getDurableObjectNamespace('FIXTURE');+ await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {+ id: ns.idFromName(f.id).toString(),+ });+ await f.command('pause', true);+ await f.command('pause', false);+ assert.equal((await f.request('a')).status, 410);+ assert.equal((await f.request('b')).status, 200);+ assert.deepEqual(await f.command('retire', owner), { retired: true });+ assert.equal((await f.command('snapshot')).calls.length, 1);+});++test('retirement cancels only the selected tenant and preserves global usage charges', async () => {+ const f = fixture();+ await f.command('hold', true);+ const a = f.request('a'),+ b = f.request('b');+ await waitFor(f, (s) => s.calls.length === 2);+ const results = await Promise.all([+ f.command('retire', 'a'.repeat(43)),+ f.command('retire', 'a'.repeat(43)),+ ]);+ assert.deepEqual(results, [{ retired: true }, { retired: true }]);+ assert.equal((await a).status, 410);+ const current = await f.command('snapshot');+ assert.equal(current.active.length, 1);+ assert.equal(current.active[0].tenant, 'b'.repeat(43));+ assert.equal(current.stopped.length, 1);+ assert.ok(current.usage.every((row) => row.owner !== 'a'.repeat(43)));+ assert.equal(+ current.usage.find((row) => row.owner === 'global' && row.period === 'month').used,+ 2,+ );+ await f.command('pause', true);+ await b;+});++test('unknown retirement cleanup retains capacity and the permanent deny until confirmed recovery', async () => {+ const f = fixture();+ await f.command('cancelFail', true);+ assert.equal((await f.request()).status, 503);+ assert.deepEqual(await f.command('retire', 'a'.repeat(43)), { retired: false, status: 503 });+ assert.equal((await f.request()).status, 410);+ assert.equal((await f.command('snapshot')).active.length, 1);+ const ns = await runtime.getDurableObjectNamespace('FIXTURE');+ await runtime.unsafeEvictDurableObject('admission-fixture', 'Fixture', {+ id: ns.idFromName(f.id).toString(),+ });+ await f.command('cancelFail', false);+ await f.command('expire');+ await f.command('alarm');+ assert.deepEqual(await f.command('retire', 'a'.repeat(43)), { retired: true });+ assert.equal((await f.command('snapshot')).active.length, 0);+ assert.equal((await f.request()).status, 410);+});++test('retirement validates exact tenant identity before mutating admission', async () => {+ const f = fixture();+ for (const owner of ['', 'a'.repeat(42), 'a'.repeat(44), `${'a'.repeat(43)}\n`, null, 123])+ assert.deepEqual(await f.command('retire', owner), { retired: false, status: 400 });+ assert.equal((await f.request()).status, 200);+});diff --git a/hosting/test/asset-downloads.test.mjs b/hosting/test/asset-downloads.test.mjsnew file mode 100644index 00000000..a93804af--- /dev/null+++ b/hosting/test/asset-downloads.test.mjs@@ -0,0 +1,218 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { after, before, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';++let runtime, namespace;+before(async () => {+ const bundle = await build({+ stdin: {+ contents: String.raw`+ import {DurableObject} from 'cloudflare:workers';+ import {ArtifactStore} from './src/artifact-store';+ import {AssetIndex} from './src/asset-index';+ import {AssetDownloadTickets} from './src/asset-downloads';+ import {serviceFailure} from './src/http';+ export class Fixture extends DurableObject {+ constructor(ctx,env) {+ super(ctx,env);+ const now=()=>ctx.storage.kv.get('fixtureTime')??Date.now();+ this.store=new ArtifactStore(ctx,env.ARTIFACTS,{maxBytes:1048576,maxObjects:32,maxGroups:8},now);+ this.assets=new AssetIndex(this.store);+ this.downloads=new AssetDownloadTickets(ctx.storage,{+ group:id=>this.store.group(id),+ download:async(id,head)=>{+ const response=await this.store.download(id,head);+ const race=await ctx.storage.get('readRace');+ if(race?.group) await this.store.deleteGroup(race.group);+ if(race?.time) await ctx.storage.put('fixtureTime',race.time);+ return response;+ }+ },this.assets,now);+ }+ async fetch(request){+ try{+ const path=new URL(request.url).pathname;+ if(path==='/upload') return Response.json(await this.store.upload(request));+ if(path==='/commit') return Response.json(this.assets.commit(await request.json()).record);+ if(path==='/issue') {const a=await request.json();return Response.json(await this.downloads.issue(a.collection,a.assetId,a.revisionId));}+ if(path==='/delete') {await this.store.deleteGroup(await request.text());return new Response('deleted');}+ if(path==='/command') {const {key,value}=await request.json();await this.ctx.storage.put(key,value);return new Response('set');}+ if(path==='/snapshot') return Response.json(this.ctx.storage.sql.exec('SELECT * FROM asset_download_tickets').toArray());+ if(path==='/cleanup') {this.downloads.sweep();return new Response('swept');}+ const file=path.match(/^\/file\/([^/]+)\/([^/]+)$/);+ if(file)return await this.downloads.download(file[1],decodeURIComponent(file[2]),request.method==='HEAD');+ return new Response('not found',{status:404});+ }catch(error){return serviceFailure(error);}+ }+ alarm(){return this.store.sweep();}+ }+ export default {fetch(){return new Response('private',{status:404});}};`,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare({+ ...convertV4MiniflareOptions({+ name: 'download-fixture',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: { TENANTS: { className: 'Fixture', useSQLite: true } },+ r2Buckets: ['ARTIFACTS'],+ outboundService: async () => {+ throw Error('No network');+ },+ }),+ unsafeInspectDurableObjects: true,+ });+ namespace = await runtime.getDurableObjectNamespace('TENANTS');+});+after(async () => runtime?.dispose());++const send = (owner, path, init) =>+ namespace.getByName(owner).fetch(`https://fixture.invalid${path}`, init);+const post = (owner, path, value) =>+ send(owner, path, { method: 'POST', body: JSON.stringify(value) });+const command = (owner, key, value) => post(owner, '/command', { key, value });+const selector = { collection: 'project', assetId: 'a_box', revisionId: 'r_one' };+const issue = (owner, extra = {}) => post(owner, '/issue', { ...selector, ...extra });+const file = (owner, token, name = 'asset.glb', method = 'GET') =>+ send(owner, `/file/${encodeURIComponent(token)}/${encodeURIComponent(name)}`, { method });+async function seed(owner) {+ const files = {};+ for (const [name, data] of [+ ['asset.glb', 'glTFfixture'],+ ['source.kiln.js', 'function build(){}'],+ ['manifest.json', '{}'],+ ]) {+ const bytes = Buffer.from(data);+ const response = await send(owner, '/upload', {+ method: 'POST',+ body: bytes,+ headers: {+ 'content-type': 'application/octet-stream',+ 'content-length': String(bytes.length),+ 'x-artifact-name': name,+ 'x-artifact-sha256': createHash('sha256').update(bytes).digest('hex'),+ },+ });+ assert.equal(response.status, 200);+ files[name] = (await response.json()).id;+ }+ const response = await post(owner, '/commit', { ...selector, files, mode: 'save' });+ assert.equal(response.status, 200);+ return { group: await response.json(), files };+}++test('download tickets select exact private saved bytes and survive object eviction without retaining raw tokens', async () => {+ await seed('alice');+ const now = Date.UTC(2030, 0, 1);+ await command('alice', 'fixtureTime', now);+ const issued = await (await issue('alice')).json();+ assert.match(issued.ticket, /^[a-f0-9]{64}$/);+ assert.equal(issued.expiresAt, now + 600000);+ assert.deepEqual(issued.files, ['asset.glb', 'manifest.json', 'source.kiln.js']);+ const rows = await (await send('alice', '/snapshot')).json();+ assert.equal(rows.length, 1);+ assert(!JSON.stringify(rows).includes(issued.ticket));+ const result = await file('alice', issued.ticket);+ assert.equal(result.status, 200);+ assert.equal(await result.text(), 'glTFfixture');+ assert.equal(result.headers.get('cache-control'), 'private, no-store');+ assert.match(result.headers.get('content-disposition'), /attachment; filename="asset.glb"/);+ assert.equal((await file('bob', issued.ticket)).status, 404);+ await runtime.unsafeEvictDurableObject('download-fixture', 'Fixture', {+ id: namespace.idFromName('alice').toString(),+ });+ assert.equal(+ await (await file('alice', issued.ticket, 'source.kiln.js')).text(),+ 'function build(){}',+ );+});++test('unknown revisions and unsafe filenames fail without issuing or spending a ticket', async () => {+ await seed('invalid');+ assert.equal((await issue('invalid', { revisionId: 'r_missing' })).status, 404);+ assert.equal((await issue('invalid', { collection: '../project' })).status, 400);+ assert.deepEqual(await (await send('invalid', '/snapshot')).json(), []);+ const { ticket } = await (await issue('invalid')).json();+ for (const name of ['../source.kiln.js', 'not-saved.txt', 'preview.png', 'asset.glb\n']) {+ assert.equal((await file('invalid', ticket, name)).status, 404);+ }+ assert.equal((await file('invalid', `${ticket}\n`)).status, 404);+ assert.equal((await (await send('invalid', '/snapshot')).json())[0].uses, 0);+});++test('ticket expiry is independent of saved retention and is rechecked after reading storage', async () => {+ await seed('expiry');+ const now = Date.UTC(2030, 0, 2);+ await command('expiry', 'fixtureTime', now);+ const { ticket } = await (await issue('expiry')).json();+ await command('expiry', 'readRace', { time: now + 600000 });+ assert.equal((await file('expiry', ticket)).status, 404);+ await command('expiry', 'readRace', null);+ const renewed = await (await issue('expiry')).json();+ assert.notEqual(renewed.ticket, ticket);+ assert.equal(await (await file('expiry', renewed.ticket)).text(), 'glTFfixture');+ assert.equal((await (await send('expiry', '/snapshot')).json()).length, 1);+});++test('deleting the selected revision revokes its ticket even when another revision keeps the same bytes', async () => {+ const { group, files } = await seed('deleted');+ assert.equal(+ (await post('deleted', '/commit', { ...selector, revisionId: 'r_two', files, mode: 'import' }))+ .status,+ 200,+ );+ const { ticket } = await (await issue('deleted')).json();+ await command('deleted', 'readRace', { group: group.id });+ assert.equal((await file('deleted', ticket)).status, 404);+ await command('deleted', 'readRace', null);+ const next = await (await issue('deleted', { revisionId: 'r_two' })).json();+ assert.equal(await (await file('deleted', next.ticket)).text(), 'glTFfixture');+});++test('concurrent redemption cannot exceed the per-ticket transfer limit and HEAD returns no bytes', async () => {+ await seed('uses');+ const { ticket } = await (await issue('uses')).json();+ const head = await file('uses', ticket, 'asset.glb', 'HEAD');+ assert.equal(head.status, 200);+ assert.equal(await head.text(), '');+ const results = await Promise.all(+ Array.from({ length: 40 }, async () => {+ const r = await file('uses', ticket);+ await r.arrayBuffer();+ return r.status;+ }),+ );+ assert.equal(results.filter((status) => status === 200).length, 31);+ assert.equal(results.filter((status) => status === 429).length, 9);+ assert.equal((await (await send('uses', '/snapshot')).json())[0].uses, 32);+});++test('issuance has a bounded persistent count and expired rows can be reclaimed', async () => {+ await seed('capacity');+ const now = Date.UTC(2030, 0, 3);+ await command('capacity', 'fixtureTime', now);+ const results = await Promise.all(+ Array.from({ length: 135 }, async () => {+ const r = await issue('capacity');+ await r.text();+ return r.status;+ }),+ );+ assert.equal(results.filter((s) => s === 200).length, 128);+ assert.equal(results.filter((s) => s === 429).length, 7);+ await command('capacity', 'fixtureTime', now + 600000);+ assert.equal((await send('capacity', '/cleanup', { method: 'POST' })).status, 200);+ assert.deepEqual(await (await send('capacity', '/snapshot')).json(), []);+ assert.equal((await issue('capacity')).status, 200);+});diff --git a/hosting/test/auth.test.mjs b/hosting/test/auth.test.mjsindex 17948b0d..28c70099 100644--- a/hosting/test/auth.test.mjs+++ b/hosting/test/auth.test.mjs@@ -1,18 +1,28 @@import assert from 'node:assert/strict';import { createHash, generateKeyPairSync, randomBytes, sign } from 'node:crypto';import { fileURLToPath } from 'node:url';-import { after, before, test } from 'node:test';+import { after, before, beforeEach, test } from 'node:test';import { build } from 'esbuild';import { convertV4MiniflareOptions, Miniflare } from 'miniflare';import { migrateAccounts } from './database.mjs';+import { rateLimitBindings } from './rate-limit-bindings.mjs';const origin = 'https://kiln.example.com';let runtime;let database;let outboundCalls = 0;+let beforeProviderReply;const googleIssuer = 'https://accounts.google.com';const googleKeys = generateKeyPairSync('rsa', { modulusLength: 2048 });const googleCodes = new Map();+const subjectIds = new Map([+ ['alice', '1001'],+ ['bob', '1002'],+]);+function subjectId(user) {+ if (!subjectIds.has(user)) subjectIds.set(user, String(1001 + subjectIds.size));+ return subjectIds.get(user);+}const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');const digest = (value) => createHash('sha256').update(value).digest('base64url');const cookies = (response) =>@@ -27,17 +37,21 @@ before(async () => {write: false,format: 'esm',platform: 'browser',+ conditions: ['workerd'],external: ['cloudflare:workers'],});runtime = new Miniflare(convertV4MiniflareOptions({+ name: 'auth-fixture',modules: true,script: bundle.outputFiles[0].text,compatibilityDate: '2026-10-06',compatibilityFlags: ['global_fetch_strictly_public'],kvNamespaces: ['OAUTH_KV'],+ ratelimits: rateLimitBindings,d1Databases: ['ACCOUNTS'],durableObjects: { TENANTS: 'TestTenant' },+ serviceBindings: { NATIVE_COMPUTE: { name: 'auth-fixture', entrypoint: 'TestCompute' } },bindings: {PUBLIC_ORIGIN: origin,GITHUB_CLIENT_ID: 'fixture-client',@@ -70,6 +84,7 @@ before(async () => {});}if (request.url === 'https://oauth2.googleapis.com/token') {+ if (beforeProviderReply) await beforeProviderReply();const form = new URLSearchParams(await request.text());const flow = googleCodes.get(form.get('code'));assert.ok(flow);@@ -78,7 +93,7 @@ before(async () => {assert.equal(form.get('client_secret'), 'fixture-google-secret');assert.equal(form.get('redirect_uri'), `${origin}/oauth/google/callback`);const now = Math.floor(Date.now() / 1000);- const input = `${encode({ alg: 'RS256', kid: 'test' })}.${encode({ iss: googleIssuer, sub: flow.user === 'alice' ? '1001' : '1002', aud: 'fixture-google-client', exp: now + 300, iat: now, nonce: flow.nonce })}`;+ const input = `${encode({ alg: 'RS256', kid: 'test' })}.${encode({ iss: googleIssuer, sub: subjectId(flow.user), aud: 'fixture-google-client', exp: now + 300, iat: now, nonce: flow.nonce })}`;return Response.json({access_token: 'fixture-google-token',token_type: 'Bearer',@@ -124,10 +139,11 @@ before(async () => {});}if (request.url === 'https://api.github.com/user') {+ if (beforeProviderReply) await beforeProviderReply();const token = request.headers.get('authorization');- assert.match(token, /^Bearer fixture-(alice|bob)$/);+ assert.match(token, /^Bearer fixture-[a-zA-Z0-9_-]+$/);return Response.json({- id: token.endsWith('alice') ? 1001 : 1002,+ id: Number(subjectId(token.slice('Bearer fixture-'.length))),login: 'not-used-as-identity',});}@@ -139,6 +155,10 @@ before(async () => {await migrateAccounts(database);});after(async () => runtime?.dispose());+// Each scenario owns its connections; prior scenarios must not consume its quota.+beforeEach(async () => {+ await database.prepare('DELETE FROM kiln_connections').run();+});test('unauthenticated MCP is challenged with canonical resource metadata', async () => {const response = await runtime.dispatchFetch(`${origin}/mcp`, { redirect: 'manual' });@@ -240,6 +260,8 @@ async function grant(user = 'alice', options = {}) {code: redirect.searchParams.get('code'),callback,upstreamCookie: cookies(approved),+ browserCookie: cookies(response),+ callbackHeaders: response.headers,};}@@ -266,31 +288,817 @@ async function token(user, options) {return { ...(await response.json()), clientId: authorization.clientId };}-async function mcp(credential, options = {}) {- return runtime.dispatchFetch(`${origin}/mcp`, {+async function mcp(credential, options = {}) {+ return runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ ...options,+ headers: {+ authorization: `Bearer ${credential.access_token}`,+ 'content-type': 'application/json',+ ...options.headers,+ },+ body:+ options.body ??+ JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },+ }),+ });+}++test('browser account sign-in establishes a private session for either verified provider', async () => {+ for (const provider of ['google', 'github']) {+ const authorization = await grant('alice', { provider });+ assert.match(authorization.browserCookie, /__Host-kiln-session=[a-f0-9]{64}/);+ const page = await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ });+ assert.equal(page.status, 200);+ assert.equal(page.headers.get('cache-control'), 'no-store');+ assert.equal(page.headers.get('referrer-policy'), 'no-referrer');+ assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/);+ const html = await page.text();+ assert.match(html, /Your Kiln account/);+ assert.match(html, provider === 'google' ? /Google/ : /GitHub/);+ assert.match(html, /name="csrf" value="[a-f0-9]{64}"/);+ assert.ok(!html.includes(authorization.browserCookie));+ assert.ok(!html.includes('fixture-secret'));+ const sessionCookie = authorization.callbackHeaders+ .getSetCookie()+ .find((value) => value.startsWith('__Host-kiln-session='));+ for (const attribute of ['Secure', 'HttpOnly', 'SameSite=Lax', 'Path=/'])+ assert.ok(sessionCookie.includes(attribute));+ }+});++test('browser account logout is CSRF protected and leaves MCP connections authorized', async () => {+ const authorization = await grant();+ const credential = await (await exchange(authorization)).json();+ const headers = { cookie: authorization.browserCookie };+ const page = await (await runtime.dispatchFetch(`${origin}/account`, { headers })).text();+ const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];+ assert.ok(csrf);+ const post = (body, extra = {}) =>+ runtime.dispatchFetch(`${origin}/account/logout`, {+ method: 'POST',+ redirect: 'manual',+ headers: {+ ...headers,+ origin,+ 'content-type': 'application/x-www-form-urlencoded',+ ...extra,+ },+ body,+ });+ assert.equal((await runtime.dispatchFetch(`${origin}/account/logout`, { headers })).status, 405);+ for (const body of ['', `csrf=${'0'.repeat(64)}`, `csrf=${csrf}&csrf=${csrf}`])+ assert.equal((await post(body)).status, 403);+ for (const badOrigin of ['', 'https://evil.example', 'https://sibling.kiln.example.com'])+ assert.equal((await post(`csrf=${csrf}`, { origin: badOrigin })).status, 403);+ assert.equal(+ (await post(JSON.stringify({ csrf }), { 'content-type': 'application/json' })).status,+ 415,+ );+ assert.equal((await runtime.dispatchFetch(`${origin}/account`, { headers })).status, 200);+ const loggedOut = await post(`csrf=${csrf}`);+ assert.equal(loggedOut.status, 303);+ assert.equal(loggedOut.headers.get('location'), '/account');+ assert.match(loggedOut.headers.get('set-cookie'), /Max-Age=0/);+ assert.equal((await runtime.dispatchFetch(`${origin}/account`, { headers })).status, 401);+ assert.equal((await mcp(credential)).status, 200);+});++test('browser account sessions cannot substitute for MCP tokens or another browser CSRF', async () => {+ const alice = await grant('alice');+ const bob = await grant('bob');+ const alicePage = await (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: alice.browserCookie },+ })+ ).text();+ const csrf = alicePage.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];+ assert.ok(csrf);+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account/logout`, {+ method: 'POST',+ headers: {+ cookie: bob.browserCookie,+ origin,+ 'content-type': 'application/x-www-form-urlencoded',+ },+ body: `csrf=${csrf}`,+ redirect: 'manual',+ })+ ).status,+ 403,+ );+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: { cookie: alice.browserCookie },+ body: '{}',+ })+ ).status,+ 401,+ );+ const credential = await (await exchange(alice)).json();+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { authorization: `Bearer ${credential.access_token}` },+ })+ ).status,+ 401,+ );+ assert.equal(+ (+ await runtime.dispatchFetch(+ `${origin}/account?cookie=${encodeURIComponent(alice.browserCookie)}`,+ )+ ).status,+ 400,+ );+});++async function browserLogin(+ provider = 'github',+ user = 'alice',+ server = runtime,+ cookie = '',+ returnTo,+) {+ const start = await server.dispatchFetch(`${origin}/account/login`, {+ method: 'POST',+ redirect: 'manual',+ headers: { origin, cookie, 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ provider, ...(returnTo === undefined ? {} : { returnTo }) }),+ });+ assert.equal(start.status, 302);+ const upstream = new URL(start.headers.get('location'));+ assert.equal(upstream.origin, provider === 'github' ? 'https://github.com' : googleIssuer);+ assert.equal(upstream.searchParams.get('code_challenge_method'), 'S256');+ assert.equal(upstream.searchParams.get('scope'), provider === 'github' ? '' : 'openid profile');+ const code = provider === 'github' ? user : randomBytes(24).toString('base64url');+ if (provider === 'google')+ googleCodes.set(code, {+ user,+ nonce: upstream.searchParams.get('nonce'),+ challenge: upstream.searchParams.get('code_challenge'),+ });+ return {+ start,+ callback: `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`,+ cookie: cookies(start),+ };+}++test('direct browser login uses either provider, no MCP client and no upstream token in cookies', async () => {+ const signedOut = await runtime.dispatchFetch(`${origin}/account`);+ assert.equal(signedOut.status, 401);+ const html = await signedOut.text();+ assert.match(html, /action="\/account\/login"/);+ for (const provider of ['google', 'github']) {+ const flow = await browserLogin(provider);+ assert.match(flow.cookie, /__Host-kiln-login=[a-f0-9]{64}/);+ const callback = await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(callback.status, 303);+ assert.equal(callback.headers.get('location'), '/account');+ assert.match(callback.headers.get('set-cookie'), /__Host-kiln-session=[a-f0-9]{64}/);+ assert.ok(!callback.headers.get('set-cookie').includes('fixture-'));+ assert.ok(+ callback.headers+ .getSetCookie()+ .some((value) => value.startsWith('__Host-kiln-login=;') && value.includes('Max-Age=0')),+ );+ assert.equal(+ (await runtime.dispatchFetch(`${origin}/account`, { headers: { cookie: cookies(callback) } }))+ .status,+ 200,+ );+ }+});++test('direct browser login requires its browser, exact provider and one-time state before contacting a provider', async () => {+ const flow = await browserLogin();+ const count = outboundCalls;+ for (const [url, cookie] of [+ [flow.callback, ''],+ [flow.callback, `${flow.cookie}; ${flow.cookie}`],+ [flow.callback.replace('/github/', '/google/'), flow.cookie],+ [`${flow.callback}&state=kb1_invalid`, flow.cookie],+ [flow.callback.replace(/state=[^&]+/, `state=kb1_${'0'.repeat(64)}`), flow.cookie],+ ]) {+ const denied = await runtime.dispatchFetch(url, { headers: { cookie }, redirect: 'manual' });+ assert.equal(denied.status, 400);+ assert.ok(!denied.headers.get('set-cookie')?.includes('__Host-kiln-session='));+ }+ assert.equal(outboundCalls, count);+ const results = await Promise.all(+ Array.from({ length: 5 }, () =>+ runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ }),+ ),+ );+ assert.deepEqual(results.map((r) => r.status).sort(), [303, 400, 400, 400, 400]);+ assert.equal(outboundCalls - count, 2);+});++test('direct browser login rejects forged forms and arbitrary return URLs before outbound calls', async () => {+ const count = outboundCalls;+ const post = (body, extra = {}, method = 'POST') =>+ runtime.dispatchFetch(`${origin}/account/login`, {+ method,+ redirect: 'manual',+ headers: { origin, 'content-type': 'application/x-www-form-urlencoded', ...extra },+ ...(method === 'POST' ? { body } : {}),+ });+ assert.equal((await post('', {}, 'GET')).status, 405);+ assert.equal((await post('provider=github', { origin: 'https://evil.example' })).status, 403);+ assert.equal((await post('provider=github', { origin: '' })).status, 403);+ for (const body of [+ 'provider=unknown',+ 'provider=github&provider=google',+ 'provider=github&returnTo=https://evil.example',+ `provider=github&returnTo=${encodeURIComponent('//evil.example')}`,+ `provider=github&returnTo=${encodeURIComponent(`/downloads/${'a'.repeat(64)}/asset.glb?redirect=https://evil.example`)}`,+ `provider=github&returnTo=${encodeURIComponent(`/downloads/${'a'.repeat(64)}/asset.glb\n`)}`,+ 'provider=github&returnTo=/account&returnTo=/account',+ '',+ ])+ assert.equal((await post(body)).status, 400);+ assert.equal((await post('{}', { 'content-type': 'application/json' })).status, 415);+ assert.equal(outboundCalls, count);+});++test('both browser providers resume only the server-retained download path after sign-in', async () => {+ const returnTo = `/downloads/${'a'.repeat(64)}/source.kiln.js`;+ for (const provider of ['google', 'github']) {+ const flow = await browserLogin(provider, 'alice', runtime, '', returnTo);+ const upstream = new URL(flow.start.headers.get('location'));+ assert.ok(!upstream.href.includes(encodeURIComponent(returnTo)));+ const callback = await runtime.dispatchFetch(`${flow.callback}&returnTo=https://evil.example`, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(callback.status, 303);+ assert.equal(callback.headers.get('location'), returnTo);+ assert.match(callback.headers.get('set-cookie'), /__Host-kiln-session=/);+ assert.equal(+ (+ await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ }+});++test('invalid server-retained download continuation fails before provider exchange or session creation', async () => {+ const flow = await browserLogin(+ 'github',+ 'alice',+ runtime,+ '',+ `/downloads/${'b'.repeat(64)}/asset.glb`,+ );+ await database+ .prepare('UPDATE kiln_browser_logins SET return_to=? WHERE state_hash=?')+ .bind(+ '//evil.example',+ digest(+ JSON.stringify([+ 'kiln-browser-login-v1',+ origin,+ 'state',+ new URL(flow.callback).searchParams.get('state'),+ ]),+ ),+ )+ .run();+ const count = outboundCalls;+ const response = await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(response.status, 400);+ assert.equal(response.headers.get('location'), null);+ assert.equal(response.headers.get('set-cookie'), null);+ assert.equal(outboundCalls, count);+});++test('direct browser login cancellation consumes its state and returns a safe retry page', async () => {+ const flow = await browserLogin();+ const cancellation = new URL(flow.callback);+ cancellation.searchParams.delete('code');+ cancellation.searchParams.set('error', 'access_denied');+ cancellation.searchParams.set('error_description', '<script>provider-detail</script>');+ const count = outboundCalls;+ const response = await runtime.dispatchFetch(cancellation, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(response.status, 400);+ assert.ok(!(await response.text()).includes('provider-detail'));+ assert.equal(+ (+ await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, count);+});++test('direct browser login stores hashed state and binding and rejects expiry without provider calls', async () => {+ const flow = await browserLogin();+ const rows = await database.prepare('SELECT * FROM kiln_browser_logins').all();+ const serialized = JSON.stringify(rows.results);+ assert.ok(!serialized.includes(new URL(flow.callback).searchParams.get('state')));+ assert.ok(!serialized.includes(flow.cookie.split('=')[1]));+ await database.prepare('UPDATE kiln_browser_logins SET expires_at=0').run();+ const count = outboundCalls;+ assert.equal(+ (+ await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, count);+});++test('restarting direct browser login retires the old intent and database failure rolls back that retirement', async () => {+ const first = await browserLogin();+ const second = await browserLogin('github', 'alice', runtime, first.cookie);+ const count = outboundCalls;+ assert.equal(+ (+ await runtime.dispatchFetch(first.callback, {+ headers: { cookie: first.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, count);+ await database+ .prepare(`CREATE TRIGGER reject_browser_login BEFORE INSERT ON kiln_browser_logins+ BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)+ .run();+ try {+ const rejected = await runtime.dispatchFetch(`${origin}/account/login`, {+ method: 'POST',+ headers: {+ origin,+ cookie: second.cookie,+ 'content-type': 'application/x-www-form-urlencoded',+ },+ body: 'provider=github',+ redirect: 'manual',+ });+ assert.equal(rejected.status, 503);+ assert.equal(rejected.headers.get('set-cookie'), null);+ assert.equal(await rejected.text(), 'Service temporarily unavailable');+ } finally {+ await database.prepare('DROP TRIGGER reject_browser_login').run();+ }+ assert.equal(+ (+ await runtime.dispatchFetch(second.callback, {+ headers: { cookie: second.cookie },+ redirect: 'manual',+ })+ ).status,+ 303,+ );+});++test('direct browser login has a bounded global intent table and cleans expired reservations', async () => {+ await database+ .prepare(`WITH RECURSIVE numbers(n) AS (+ SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<4096)+ INSERT INTO kiln_browser_logins(state_hash,binding_hash,provider,verifier,nonce,expires_at)+ SELECT 'fixture-cap-'||n,'fixture-cap-'||n,'github','fixture','fixture',? FROM numbers+ LIMIT MAX(0, 4096-(SELECT COUNT(*) FROM kiln_browser_logins))`)+ .bind(Date.now() + 600_000)+ .run();+ try {+ const count = outboundCalls;+ const replies = await Promise.all(+ Array.from({ length: 3 }, () =>+ runtime.dispatchFetch(`${origin}/account/login`, {+ method: 'POST',+ headers: { origin, 'content-type': 'application/x-www-form-urlencoded' },+ body: 'provider=github',+ redirect: 'manual',+ }),+ ),+ );+ assert.deepEqual(+ replies.map((r) => r.status),+ [429, 429, 429],+ );+ assert.equal(+ (await database.prepare('SELECT COUNT(*) AS n FROM kiln_browser_logins').first()).n,+ 4096,+ );+ assert.equal(outboundCalls, count);+ await database+ .prepare("UPDATE kiln_browser_logins SET expires_at=0 WHERE state_hash LIKE 'fixture-cap-%'")+ .run();+ await browserLogin();+ assert.ok(+ (await database.prepare('SELECT COUNT(*) AS n FROM kiln_browser_logins').first()).n < 4096,+ );+ } finally {+ await database+ .prepare("DELETE FROM kiln_browser_logins WHERE state_hash LIKE 'fixture-cap-%'")+ .run();+ }+});++test('metadata advertises the configured audience, scopes, issuer and S256', async () => {+ const resource = await (+ await runtime.dispatchFetch(`${origin}/.well-known/oauth-protected-resource/mcp`)+ ).json();+ assert.equal(resource.resource, `${origin}/mcp`);+ assert.deepEqual(resource.authorization_servers, [origin]);+ assert.deepEqual(resource.scopes_supported, ['kiln:use']);+ const auth = await (+ await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`)+ ).json();+ assert.equal(auth.issuer, origin);+ assert.ok(auth.code_challenge_methods_supported.includes('S256'));+});++test('MCP authorization creates a durable connection and activates it only on code exchange', async () => {+ const authorization = await grant();+ const pending = await database+ .prepare('SELECT * FROM kiln_connections WHERE client_id=?')+ .bind(authorization.clientId)+ .first();+ assert.ok(pending);+ assert.match(pending.id, /^kc_[a-f0-9]{32}$/);+ assert.equal(pending.state, 'pending');+ assert.equal(pending.grant_id, null);+ const credential = await (await exchange(authorization)).json();+ const active = await database+ .prepare('SELECT * FROM kiln_connections WHERE id=?')+ .bind(pending.id)+ .first();+ assert.equal(active.state, 'active');+ assert.ok(active.grant_id);+ assert.ok(!JSON.stringify(active).includes(credential.access_token));+ assert.ok(!JSON.stringify(active).includes(credential.refresh_token));+ assert.equal((await mcp(credential)).status, 200);+});++test('edge discovery requires a scoped active connection and rejects revoked cached credentials', async () => {+ const credential = await token('alice');+ const noScope = await token('alice', { scope: 'offline_access' });+ for (const [method, params] of [+ ['tools/list', {}],+ ['tools/call', { name: 'kiln_discover', arguments: { query: 'wheel' } }],+ ]) {+ const options = {+ headers: { accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ };+ assert.equal((await mcp({ access_token: 'invalid' }, options)).status, 401);+ assert.equal((await mcp(noScope, options)).status, 403);+ const response = await mcp(credential, options);+ assert.equal(response.status, 200);+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.ok(+ (await response.text()).includes(method === 'tools/list' ? '"tools":' : '"content":'),+ );+ }+ await database+ .prepare("UPDATE kiln_connections SET state='revoked' WHERE client_id=?")+ .bind(credential.clientId)+ .run();+ assert.equal(+ (+ await mcp(credential, {+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),+ })+ ).status,+ 401,+ );+});++test('primary connection revocation denies cached access and refresh while preserving another connection', async () => {+ const first = await token('alice');+ const second = await token('alice');+ const own = await database+ .prepare('SELECT id FROM kiln_connections WHERE client_id=?')+ .bind(first.clientId)+ .first();+ assert.ok(own);+ // Leave every provider KV record intact: this models a remote cache seeing stale data.+ await database+ .prepare("UPDATE kiln_connections SET state='revoked' WHERE id=?")+ .bind(own.id)+ .run();+ assert.equal((await mcp(first)).status, 401);+ assert.equal((await mcp(second)).status, 200);+ const refresh = await runtime.dispatchFetch(`${origin}/oauth/token`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: first.refresh_token,+ client_id: first.clientId,+ resource: `${origin}/mcp`,+ }),+ });+ assert.equal(refresh.status, 400);+ assert.equal((await refresh.json()).error, 'invalid_grant');+});++test('stale provider KV cannot exchange an already consumed authorization code again', async () => {+ const authorization = await grant();+ const kv = await runtime.getKVNamespace('OAUTH_KV');+ const saved = await Promise.all(+ (await kv.list({ prefix: 'grant:' })).keys.map(async ({ name }) => [name, await kv.get(name)]),+ );+ assert.equal((await exchange(authorization)).status, 200);+ for (const [name, value] of saved) await kv.put(name, value);+ const again = await exchange(authorization);+ assert.equal(again.status, 400);+ assert.equal((await again.json()).error, 'invalid_grant');+});++async function connectionFor(authorization) {+ return database+ .prepare('SELECT * FROM kiln_connections WHERE client_id=?')+ .bind(authorization.clientId)+ .first();+}++async function startDisconnect(authorization, connectionId, provider = 'github', extra = {}) {+ const page = await (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).text();+ const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];+ assert.ok(csrf);+ return runtime.dispatchFetch(`${origin}/account/action`, {+ method: 'POST',+ redirect: 'manual',+ headers: {+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',+ ...extra.headers,+ },+ body: new URLSearchParams({+ csrf,+ action: 'disconnect',+ connectionId,+ provider,+ ...extra.form,+ }),+ });+}++async function actionCallback(start, authorization, user = 'alice') {+ assert.equal(start.status, 302);+ const upstream = new URL(start.headers.get('location'));+ assert.equal(upstream.searchParams.get('prompt'), 'select_account');+ const provider = upstream.origin === googleIssuer ? 'google' : 'github';+ const code = provider === 'github' ? user : randomBytes(24).toString('base64url');+ if (provider === 'google')+ googleCodes.set(code, {+ user,+ nonce: upstream.searchParams.get('nonce'),+ challenge: upstream.searchParams.get('code_challenge'),+ });+ return {+ callback: `${origin}/oauth/${provider}/callback?${new URLSearchParams({ state: upstream.searchParams.get('state'), code })}`,+ cookie: `${authorization.browserCookie}; ${cookies(start)}`,+ };+}++test('disconnect requires fresh verification of an existing provider and preserves other connections', async () => {+ for (const provider of ['github', 'google']) {+ const second = await token('alice', { provider });+ const authorization = await grant('alice', { provider });+ const credential = await (await exchange(authorization)).json();+ const connection = await connectionFor(authorization);+ const page = await (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).text();+ assert.match(page, /Connected apps/);+ assert.ok(page.includes(connection.id));+ const start = await startDisconnect(authorization, connection.id, provider);+ const flow = await actionCallback(start, authorization);+ // Initiating confirmation alone must not revoke the connection.+ assert.equal((await mcp(credential)).status, 200);+ const response = await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(response.status, 303);+ assert.equal(response.headers.get('location'), '/account');+ assert.match(response.headers.get('set-cookie'), /__Host-kiln-session=/);+ assert.equal((await mcp(credential)).status, 401);+ assert.equal((await mcp(second)).status, 200);+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).status,+ 401,+ );+ assert.equal(+ (await runtime.dispatchFetch(`${origin}/account`, { headers: { cookie: cookies(response) } }))+ .status,+ 200,+ );+ assert.equal(+ (+ await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ }+});++test('disconnect refuses another account, unlinked provider, forged CSRF and cross-origin actions', async () => {+ const bob = await grant('bob');+ await exchange(bob);+ const alice = await grant('alice');+ const credential = await (await exchange(alice)).json();+ const aliceConnection = await connectionFor(alice);+ const bobConnection = await connectionFor(bob);+ const count = outboundCalls;+ for (const [id, provider, extra] of [+ [bobConnection.id, 'github', {}],+ [aliceConnection.id, 'google', {}],+ [aliceConnection.id, 'github', { form: { csrf: '0'.repeat(64) } }],+ [aliceConnection.id, 'github', { headers: { origin: 'https://evil.example' } }],+ [aliceConnection.id, 'github', { form: { accountId: bobConnection.account_id } }],+ ])+ assert.equal((await startDisconnect(alice, id, provider, extra)).status, 403);+ assert.equal(outboundCalls, count);+ assert.equal((await mcp(credential)).status, 200);+});++test('disconnect rejects a different provider identity and a copied action without its session', async () => {+ const authorization = await grant();+ const credential = await (await exchange(authorization)).json();+ const connection = await connectionFor(authorization);+ const start = await startDisconnect(authorization, connection.id);+ const wrong = await actionCallback(start, authorization, 'bob');+ assert.equal(+ (+ await runtime.dispatchFetch(wrong.callback, {+ headers: { cookie: cookies(start) },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(+ (+ await runtime.dispatchFetch(wrong.callback, {+ headers: { cookie: wrong.cookie },+ redirect: 'manual',+ })+ ).status,+ 403,+ );+ assert.equal((await mcp(credential)).status, 200);+});++test('disconnect cancellation and expiry cannot revoke access or replay provider confirmation', async () => {+ const authorization = await grant();+ const credential = await (await exchange(authorization)).json();+ const connection = await connectionFor(authorization);+ const start = await startDisconnect(authorization, connection.id);+ const flow = await actionCallback(start, authorization);+ const cancelled = new URL(flow.callback);+ cancelled.searchParams.delete('code');+ cancelled.searchParams.set('error', 'access_denied');+ const beforeCalls = outboundCalls;+ const options = { headers: { cookie: flow.cookie }, redirect: 'manual' };+ assert.equal((await runtime.dispatchFetch(cancelled.href, options)).status, 400);+ assert.equal((await runtime.dispatchFetch(flow.callback, options)).status, 400);+ assert.equal(outboundCalls, beforeCalls);+ assert.equal((await mcp(credential)).status, 200);+ const next = await actionCallback(+ await startDisconnect(authorization, connection.id),+ authorization,+ );+ await database.prepare('UPDATE kiln_account_actions SET expires_at=0').run();+ assert.equal(+ (+ await runtime.dispatchFetch(next.callback, {+ headers: { cookie: next.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, beforeCalls);+ assert.equal((await mcp(credential)).status, 200);+});++test('concurrent disconnect callbacks consume one confirmation and perform one provider exchange', async () => {+ const authorization = await grant();+ const credential = await (await exchange(authorization)).json();+ const connection = await connectionFor(authorization);+ const flow = await actionCallback(+ await startDisconnect(authorization, connection.id),+ authorization,+ );+ const beforeCalls = outboundCalls;+ const results = await Promise.all(+ [0, 1].map(() =>+ runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ }),+ ),+ );+ assert.deepEqual(results.map((result) => result.status).sort(), [303, 400]);+ assert.equal(outboundCalls - beforeCalls, 2); // One token exchange and one GitHub identity read.+ assert.equal((await mcp(credential)).status, 401);+});++test('a revoked browser session cannot finish its pending disconnect', async () => {+ const authorization = await grant();+ const credential = await (await exchange(authorization)).json();+ const connection = await connectionFor(authorization);+ const flow = await actionCallback(+ await startDisconnect(authorization, connection.id),+ authorization,+ );+ await database+ .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')+ .bind(connection.account_id)+ .run();+ const beforeCalls = outboundCalls;+ assert.equal(+ (+ await runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, beforeCalls);+ assert.equal((await mcp(credential)).status, 200);+});++test('connected app display escapes registered names and oversized action forms never contact a provider', async () => {+ const clientId = await register('<img src=x onerror="alert(1)">');+ const authorization = await grant('alice', { clientId });+ const credential = await (await exchange(authorization)).json();+ const page = await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ });+ const html = await page.text();+ assert.ok(!html.includes('<img src=x'));+ assert.ok(html.includes('<img src=x'));+ assert.match(page.headers.get('content-security-policy'), /default-src 'none'/);+ const beforeCalls = outboundCalls;+ const rejected = await runtime.dispatchFetch(`${origin}/account/action`, {method: 'POST',- ...options,headers: {- authorization: `Bearer ${credential.access_token}`,- 'content-type': 'application/json',- ...options.headers,+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',},- body: options.body ?? JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),+ body: `csrf=${'a'.repeat(4096)}`,});-}--test('metadata advertises the configured audience, scopes, issuer and S256', async () => {- const resource = await (- await runtime.dispatchFetch(`${origin}/.well-known/oauth-protected-resource/mcp`)- ).json();- assert.equal(resource.resource, `${origin}/mcp`);- assert.deepEqual(resource.authorization_servers, [origin]);- assert.deepEqual(resource.scopes_supported, ['kiln:use']);- const auth = await (- await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`)- ).json();- assert.equal(auth.issuer, origin);- assert.ok(auth.code_challenge_methods_supported.includes('S256'));+ assert.equal(rejected.status, 413);+ assert.equal(outboundCalls, beforeCalls);+ assert.equal((await mcp(credential)).status, 200);});test('consent escapes client content and binds approval to its browser', async () => {@@ -300,6 +1108,14 @@ test('consent escapes client content and binds approval to its browser', async (assert.match(start.page, /client\.example/);assert.match(start.response.headers.get('content-security-policy'), /frame-ancestors 'none'/);assert.match(start.response.headers.get('set-cookie'), /HttpOnly/);+ for (const link of ['/privacy', '/support', '/terms', '/account'])+ assert.ok(start.page.includes(`href="${link}"`));+ const nonce = start.page.match(/<style nonce="([a-f0-9]+)">/)?.[1];+ assert.ok(nonce);+ assert.ok(+ start.response.headers.get('content-security-policy').includes(`style-src 'nonce-${nonce}'`),+ );+ assert.match(start.page, /by Instrukt Labs/);const count = outboundCalls;assert.equal((await approve(start, { cookie: '' })).status, 400);assert.equal(outboundCalls, count);@@ -671,15 +1487,23 @@ test('a chunked MCP body is bounded without relying on Content-Length', async ()assert.equal(response.status, 413);});-test('real OAuth gateway authorizes downloads from a separate tenant Worker', async () => {+test('real OAuth gateway authorizes downloads and completes deletion through private tenant storage', async () => {const [gateway, storage] = await Promise.all(['worker', 'tenant-worker'].map((entry) =>build({- entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],+ entryPoints: [+ fileURLToPath(+ new URL(+ entry === 'worker' ? './deletion-integration-worker.ts' : `../src/${entry}.ts`,+ import.meta.url,+ ),+ ),+ ],bundle: true,write: false,format: 'esm',platform: 'browser',+ conditions: ['workerd'],external: ['cloudflare:workers'],}),),@@ -694,7 +1518,9 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', ascompatibilityDate: '2026-10-06',compatibilityFlags: ['global_fetch_strictly_public'],kvNamespaces: ['OAUTH_KV'],+ ratelimits: rateLimitBindings,d1Databases: ['ACCOUNTS'],+ serviceBindings: { NATIVE_COMPUTE: { name: 'gateway', entrypoint: 'EmptyCompute' } },durableObjects: {TENANTS: { className: 'KilnTenant', scriptName: 'tenant', useSQLite: true },},@@ -807,7 +1633,22 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', as).status,404,);- assert.equal((await server.dispatchFetch(`${origin}/mcp`, { headers })).status, 503);+ assert.equal((await server.dispatchFetch(`${origin}/mcp`, { headers })).status, 405);+ assert.equal(+ (+ await server.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: { ...headers, 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },+ }),+ })+ ).status,+ 503,+ );const privateWorker = await server.getWorker('tenant');assert.equal((@@ -818,7 +1659,730 @@ test('real OAuth gateway authorizes downloads from a separate tenant Worker', as).status,404,);+ // Pin the source as a saved revision so deletion must remove retained work.+ assert.equal(+ (+ await tenant.fetch('https://tenant.internal/internal/groups', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ key: 'library/saved/revision',+ files: { 'source.kiln.js': artifact.id },+ metadata: { title: 'Private saved work' },+ }),+ })+ ).status,+ 201,+ );+ const authorization = await grant('alice', { server });+ const flow = await actionCallback(await startDeletion(authorization), authorization, 'alice');+ const confirmed = await server.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+ assert.equal(confirmed.status, 303);+ const receiptCookie = cookies(confirmed);+ for (let i = 0; i < 12; i++) {+ const progress = await accounts.prepare('SELECT phase FROM kiln_deletions').first();+ if (progress?.phase === 'complete') break;+ // Advance retry eligibility only, never steal the live recovery lease.+ await accounts.prepare('UPDATE kiln_deletions SET retry_at=0').run();+ assert.equal((await server.dispatchFetch(`${origin}/fixture/recover`)).status, 200);+ }+ const receipt = await server.dispatchFetch(`${origin}/account/deletion`, {+ headers: { cookie: receiptCookie },+ });+ assert.match(await receipt.text(), /Account deleted/);+ assert.equal(+ await accounts+ .prepare('SELECT 1 FROM kiln_accounts WHERE id=?')+ .bind(identity.account_id)+ .first(),+ null,+ );+ assert.equal(+ (await accounts.prepare('SELECT tenant FROM fixture_retired').first()).tenant,+ name,+ );+ assert.equal((await tenant.fetch('https://tenant.internal/internal/usage')).status, 410);+ const bucket = await server.getR2Bucket('ARTIFACTS', 'tenant');+ assert.equal(+ (await bucket.list({ prefix: `tenants/${namespace.idFromName(name)}/` })).objects.length,+ 0,+ );+ for (const credential of [alice, reconnected])+ assert.equal(+ (+ await server.dispatchFetch(url, {+ headers: { authorization: `Bearer ${credential.access_token}` },+ })+ ).status,+ 401,+ );+ assert.equal(+ (+ await server.dispatchFetch(url, {+ headers: { authorization: `Bearer ${bob.access_token}` },+ })+ ).status,+ 404,+ );+ const fresh = await grant('alice', { server });+ const freshIdentity = await accounts+ .prepare('SELECT account_id FROM kiln_identities WHERE issuer=? AND subject=?')+ .bind('https://github.com', '1001')+ .first();+ assert.notEqual(freshIdentity.account_id, identity.account_id);+ assert.equal(+ (+ await server.dispatchFetch(`${origin}/account`, {+ headers: { cookie: fresh.browserCookie },+ })+ ).status,+ 200,+ );} finally {await server.dispose();}});++async function startDeletion(authorization, provider = 'github', extra = {}) {+ const server = authorization.server ?? runtime;+ const page = await (+ await server.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).text();+ const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];+ assert.ok(csrf);+ return server.dispatchFetch(`${origin}/account/delete`, {+ method: 'POST',+ redirect: 'manual',+ headers: {+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',+ ...extra.headers,+ },+ body: new URLSearchParams({ csrf, provider, confirmation: 'delete-my-account', ...extra.form }),+ });+}++test('account deletion confirms either linked provider then revokes browsers and MCP before background cleanup', async () => {+ for (const provider of ['github', 'google']) {+ const user = `delete-${provider}`,+ authorization = await grant(user, { provider });+ const credential = await (await exchange(authorization)).json();+ const account = (await connectionFor(authorization)).account_id;+ const start = await startDeletion(authorization, provider);+ const flow = await actionCallback(start, authorization, user);+ assert.match(new URL(flow.callback).searchParams.get('state'), /^kd1_/);+ assert.equal((await mcp(credential)).status, 200);+ const response = await finishIdentity(flow);+ assert.equal(response.status, 303);+ assert.equal(response.headers.get('location'), '/account/deletion');+ assert.match(cookies(response), /__Host-kiln-deletion-receipt=[a-f0-9]{64}/);+ assert.equal((await mcp(credential)).status, 401);+ assert.equal(+ (await refreshToken({ ...credential, clientId: authorization.clientId })).status,+ 400,+ );+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).status,+ 401,+ );+ const current = await database+ .prepare('SELECT state,authorization_epoch FROM kiln_accounts WHERE id=?')+ .bind(account)+ .first();+ assert.equal(current.state, 'deleting');+ assert.equal(current.authorization_epoch, 2);+ const receipt = await runtime.dispatchFetch(`${origin}/account/deletion`, {+ headers: { cookie: cookies(response) },+ });+ assert.equal(receipt.status, 200);+ assert.match(await receipt.text(), /Deletion in progress/);+ assert.equal((await runtime.dispatchFetch(`${origin}/account/deletion`)).status, 404);+ assert.equal((await finishIdentity(flow)).status, 400);+ }+});++test('deletion forms and wrong upstream identities cannot select or destroy another account', async () => {+ const user = 'delete-invalid',+ authorization = await grant(user);+ const credential = await (await exchange(authorization)).json();+ for (const extra of [+ { form: { csrf: '0'.repeat(64) } },+ { form: { confirmation: 'no' } },+ { form: { accountId: 'victim' } },+ { headers: { origin: 'https://foreign.example' } },+ ])+ assert.equal((await startDeletion(authorization, 'github', extra)).status, 403);+ assert.equal((await startDeletion(authorization, 'google')).status, 403);+ const flow = await actionCallback(+ await startDeletion(authorization),+ authorization,+ 'foreign-person',+ );+ assert.equal((await finishIdentity(flow)).status, 403);+ assert.equal((await finishIdentity(flow)).status, 400);+ assert.equal((await mcp(credential)).status, 200);+});++test('deletion confirmations reject cancellation, expiry, copied cookies and cross-provider replay', async () => {+ for (const mode of ['cancel', 'expired', 'cookie', 'provider']) {+ const user = `deletion-${mode}`,+ authorization = await grant(user);+ const credential = await (await exchange(authorization)).json();+ const flow = await actionCallback(await startDeletion(authorization), authorization, user);+ const count = outboundCalls;+ if (mode === 'cancel') flow.callback += '&error=access_denied';+ if (mode === 'expired')+ await database.prepare('UPDATE kiln_deletion_actions SET expires_at=0').run();+ if (mode === 'cookie') flow.cookie = authorization.browserCookie;+ if (mode === 'provider') flow.callback = flow.callback.replace('/github/', '/google/');+ assert.equal((await finishIdentity(flow)).status, 400);+ assert.equal(outboundCalls, count);+ assert.equal((await mcp(credential)).status, 200);+ }+});++test('deletion rechecks session, epoch and confirmed identity after upstream I/O', async () => {+ for (const mode of ['session', 'epoch', 'identity']) {+ const user = `deletion-inflight-${mode}`,+ authorization = await grant(user);+ const account = (await connectionFor(authorization)).account_id;+ const flow = await actionCallback(await startDeletion(authorization), authorization, user);+ beforeProviderReply = async () => {+ beforeProviderReply = undefined;+ const query =+ mode === 'session'+ ? 'DELETE FROM kiln_browser_sessions WHERE account_id=?'+ : mode === 'epoch'+ ? 'UPDATE kiln_accounts SET authorization_epoch=authorization_epoch+1 WHERE id=?'+ : 'DELETE FROM kiln_identities WHERE account_id=?';+ await database.prepare(query).bind(account).run();+ };+ try {+ assert.equal((await finishIdentity(flow)).status, 403);+ } finally {+ beforeProviderReply = undefined;+ }+ assert.equal(+ await database+ .prepare('SELECT 1 FROM kiln_deletions WHERE account_id=?')+ .bind(account)+ .first(),+ null,+ );+ assert.equal(+ (await database.prepare('SELECT state FROM kiln_accounts WHERE id=?').bind(account).first())+ .state,+ 'active',+ );+ }+});++test('deletion callback races enqueue one job and a failed enqueue leaves account access unchanged', async () => {+ const authorization = await grant('deletion-race');+ const account = (await connectionFor(authorization)).account_id;+ const flow = await actionCallback(+ await startDeletion(authorization),+ authorization,+ 'deletion-race',+ );+ const results = await Promise.all([finishIdentity(flow), finishIdentity(flow)]);+ assert.deepEqual(results.map((value) => value.status).sort(), [303, 400]);+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_deletions WHERE account_id=?')+ .bind(account)+ .first()+ ).n,+ 1,+ );++ const other = await grant('deletion-enqueue-failure');+ const credential = await (await exchange(other)).json();+ const confirmation = await actionCallback(+ await startDeletion(other),+ other,+ 'deletion-enqueue-failure',+ );+ await database.exec(+ "CREATE TRIGGER deletion_failure BEFORE INSERT ON kiln_deletions BEGIN SELECT RAISE(ABORT,'fixture'); END",+ );+ try {+ assert.equal((await finishIdentity(confirmation)).status, 503);+ } finally {+ await database.exec('DROP TRIGGER deletion_failure');+ }+ assert.equal((await mcp(credential)).status, 200);+ assert.equal((await finishIdentity(confirmation)).status, 400);+});++test('deletion intents are bounded and hashed, and receipt reads reject caller-selected targets', async () => {+ const authorization = await grant('deletion-bounds');+ const account = (await connectionFor(authorization)).account_id;+ for (let i = 0; i < 4; i++) {+ const response = await startDeletion(authorization);+ assert.equal(response.status, 302);+ const state = new URL(response.headers.get('location')).searchParams.get('state');+ const binding = cookies(response).split('=')[1];+ const stored = JSON.stringify(+ (+ await database+ .prepare('SELECT * FROM kiln_deletion_actions WHERE account_id=?')+ .bind(account)+ .all()+ ).results,+ );+ assert(!stored.includes(state));+ assert(!stored.includes(binding));+ }+ const count = outboundCalls;+ assert.equal((await startDeletion(authorization)).status, 403);+ for (const body of [+ 'x'.repeat(4097),+ 'csrf=bad&provider=github&confirmation=delete-my-account&confirmation=delete-my-account',+ ]) {+ const result = await runtime.dispatchFetch(`${origin}/account/delete`, {+ method: 'POST',+ headers: {+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',+ },+ body,+ });+ assert.equal(result.status, body.length > 4096 ? 413 : 403);+ }+ assert.equal(outboundCalls, count);+ assert.equal(+ (await runtime.dispatchFetch(`${origin}/account/deletion?accountId=${account}`)).status,+ 400,+ );+ assert.equal(+ (await runtime.dispatchFetch(`${origin}/account/deletion`, { method: 'POST' })).status,+ 405,+ );+ assert.equal((await runtime.dispatchFetch(`${origin}/account/delete`)).status, 405);+});++async function startIdentity(authorization, action, target, provider, extra = {}) {+ const page = await (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).text();+ const csrf = page.match(/name="csrf" value="([a-f0-9]{64})"/)?.[1];+ assert.ok(csrf);+ return runtime.dispatchFetch(`${origin}/account/identity`, {+ method: 'POST',+ redirect: 'manual',+ headers: {+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',+ ...extra.headers,+ },+ body: new URLSearchParams({ csrf, action, target, provider, ...extra.form }),+ });+}+const finishIdentity = (flow) =>+ runtime.dispatchFetch(flow.callback, {+ headers: { cookie: flow.cookie },+ redirect: 'manual',+ });+async function linkIdentity(authorization, user, provider = 'github', target = 'google') {+ const first = await actionCallback(+ await startIdentity(authorization, 'link', target, provider),+ authorization,+ user,+ );+ const next = await finishIdentity(first);+ const second = await actionCallback(next, authorization, user);+ return { first, second, response: await finishIdentity(second) };+}++test('explicit linking preserves the account and invalidates old browser and MCP access', async () => {+ for (const provider of ['github', 'google']) {+ const user = `link-${provider}`,+ target = provider === 'github' ? 'google' : 'github';+ const authorization = await grant(user, { provider });+ const credential = await (await exchange(authorization)).json();+ const account = (await connectionFor(authorization)).account_id;+ const linked = await linkIdentity(authorization, user, provider, target);+ assert.equal(linked.response.status, 200);+ assert.match(await linked.response.text(), /Sign-in method added/);+ assert.match(linked.response.headers.get('set-cookie'), /Max-Age=0/);+ assert.equal((await mcp(credential)).status, 401);+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).status,+ 401,+ );+ assert.equal((await finishIdentity(linked.second)).status, 400);+ const returning = await grant(user, { provider: target });+ assert.equal((await connectionFor(returning)).account_id, account);+ const html = await (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: returning.browserCookie },+ })+ ).text();+ assert.match(html, /Recent security activity/);+ assert.match(html, /Sign-in method added/);+ assert.match(html, /Remove Google|Remove GitHub/);+ }+});++test('identity linking requires both identities, same-session proof and an unused target', async () => {+ const authorization = await grant('link-denials');+ const credential = await (await exchange(authorization)).json();+ const before = outboundCalls;+ for (const extra of [+ { form: { csrf: '0'.repeat(64) } },+ { headers: { origin: 'https://evil.example' } },+ { form: { accountId: `ka_${'0'.repeat(32)}` } },+ ])+ assert.equal(+ (await startIdentity(authorization, 'link', 'google', 'github', extra)).status,+ 403,+ );+ assert.equal(outboundCalls, before);+ const wrong = await actionCallback(+ await startIdentity(authorization, 'link', 'google', 'github'),+ authorization,+ 'bob',+ );+ assert.equal((await finishIdentity(wrong)).status, 403);+ const first = await actionCallback(+ await startIdentity(authorization, 'link', 'google', 'github'),+ authorization,+ 'link-denials',+ );+ const next = await finishIdentity(first);+ assert.equal(next.status, 302);+ // A Google identity already owned by another Kiln account must not merge libraries.+ const other = await grant('link-other', { provider: 'google' });+ const second = await actionCallback(next, authorization, 'link-other');+ const calls = outboundCalls;+ assert.equal(+ (+ await runtime.dispatchFetch(second.callback, {+ headers: { cookie: cookies(next) },+ redirect: 'manual',+ })+ ).status,+ 400,+ );+ assert.equal(outboundCalls, calls);+ assert.equal((await finishIdentity(second)).status, 403);+ assert.equal((await mcp(credential)).status, 200);+ assert.notEqual(+ (await connectionFor(other)).account_id,+ (await connectionFor(authorization)).account_id,+ );+});++test('unlink confirms the retained method, never removes the last login and revokes prior access', async () => {+ const user = 'unlink-user';+ const first = await grant(user);+ assert.equal((await startIdentity(first, 'unlink', 'github', 'github')).status, 403);+ assert.equal((await linkIdentity(first, user)).response.status, 200);+ const authorization = await grant(user, { provider: 'google' });+ const credential = await (await exchange(authorization)).json();+ const account = (await connectionFor(authorization)).account_id;+ assert.equal((await startIdentity(authorization, 'unlink', 'github', 'github')).status, 403);+ const flow = await actionCallback(+ await startIdentity(authorization, 'unlink', 'github', 'google'),+ authorization,+ user,+ );+ const response = await finishIdentity(flow);+ assert.equal(response.status, 200);+ assert.match(await response.text(), /Sign-in method removed/);+ assert.equal((await mcp(credential)).status, 401);+ const retained = await grant(user, { provider: 'google' });+ assert.equal((await connectionFor(retained)).account_id, account);+ const removed = await grant(user);+ assert.notEqual((await connectionFor(removed)).account_id, account);+ assert.equal((await startIdentity(retained, 'unlink', 'google', 'github')).status, 403);+});++test('link callbacks are one-use across races and cannot cross provider or phase', async () => {+ const user = 'link-races',+ authorization = await grant(user);+ const first = await actionCallback(+ await startIdentity(authorization, 'link', 'google', 'github'),+ authorization,+ user,+ );+ const before = outboundCalls;+ const responses = await Promise.all([finishIdentity(first), finishIdentity(first)]);+ assert.deepEqual(responses.map((r) => r.status).sort(), [302, 400]);+ // One GitHub exchange and identity read, plus discovery for the second phase.+ assert.equal(outboundCalls - before, 3);+ const next = responses.find((r) => r.status === 302);+ const second = await actionCallback(next, authorization, user);+ const wrongProvider = second.callback.replace('/oauth/google/', '/oauth/github/');+ const count = outboundCalls;+ assert.equal((await finishIdentity({ ...second, callback: wrongProvider })).status, 400);+ assert.equal(outboundCalls, count);+ const done = await Promise.all([finishIdentity(second), finishIdentity(second)]);+ assert.deepEqual(done.map((r) => r.status).sort(), [200, 400]);+ const account = (await connectionFor(authorization)).account_id;+ const row = await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_account_events WHERE account_id=?')+ .bind(account)+ .first();+ assert.equal(row.n, 1);+});++test('cancelled, expired and revoked link confirmations cannot change sign-in methods', async () => {+ for (const mode of ['cancel', 'expiry', 'epoch', 'session']) {+ const user = `link-state-${mode}`,+ authorization = await grant(user);+ const account = (await connectionFor(authorization)).account_id;+ const first = await actionCallback(+ await startIdentity(authorization, 'link', 'google', 'github'),+ authorization,+ user,+ );+ const next = await finishIdentity(first);+ const second = await actionCallback(next, authorization, user);+ const before = outboundCalls;+ if (mode === 'cancel') {+ const url = new URL(second.callback);+ url.searchParams.delete('code');+ url.searchParams.set('error', 'access_denied');+ assert.equal((await finishIdentity({ ...second, callback: url.href })).status, 400);+ } else if (mode === 'expiry')+ await database+ .prepare('UPDATE kiln_identity_actions SET expires_at=0 WHERE account_id=?')+ .bind(account)+ .run();+ else if (mode === 'epoch')+ await database+ .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')+ .bind(account)+ .run();+ else+ await database+ .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')+ .bind(account)+ .run();+ assert.equal((await finishIdentity(second)).status, 400);+ assert.equal(outboundCalls, before);+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')+ .bind(account)+ .first()+ ).n,+ 1,+ );+ }+});++test('failed security-event writes roll back identity changes, epochs and sessions', async () => {+ const user = 'link-rollback',+ authorization = await grant(user);+ const credential = await (await exchange(authorization)).json();+ const account = (await connectionFor(authorization)).account_id;+ await database+ .prepare(`CREATE TRIGGER reject_security_event BEFORE INSERT ON kiln_account_events+ BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)+ .run();+ try {+ const linked = await linkIdentity(authorization, user);+ assert.equal(linked.response.status, 503);+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')+ .bind(account)+ .first()+ ).n,+ 1,+ );+ assert.equal(+ (+ await database+ .prepare('SELECT authorization_epoch AS n FROM kiln_accounts WHERE id=?')+ .bind(account)+ .first()+ ).n,+ 1,+ );+ assert.equal((await mcp(credential)).status, 200);+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/account`, {+ headers: { cookie: authorization.browserCookie },+ })+ ).status,+ 200,+ );+ // The consumed provider callback cannot be replayed, even though mutation rolled back.+ assert.equal((await finishIdentity(linked.second)).status, 400);+ } finally {+ await database.prepare('DROP TRIGGER reject_security_event').run();+ }+ assert.equal((await linkIdentity(authorization, user)).response.status, 200);+});++test('unlink races preserve a usable identity and primary revocation rejects stale refresh tokens', async () => {+ const user = 'unlink-race',+ first = await grant(user);+ assert.equal((await linkIdentity(first, user)).response.status, 200);+ const a = await grant(user),+ b = await grant(user, { provider: 'google' });+ const credential = await (await exchange(a)).json();+ const removeGoogle = await actionCallback(+ await startIdentity(a, 'unlink', 'google', 'github'),+ a,+ user,+ );+ const removeGithub = await actionCallback(+ await startIdentity(b, 'unlink', 'github', 'google'),+ b,+ user,+ );+ const results = await Promise.all([finishIdentity(removeGoogle), finishIdentity(removeGithub)]);+ assert.equal(results.filter((r) => r.status === 200).length, 1);+ assert.ok(+ results.filter((r) => r.status !== 200).every((r) => r.status === 400 || r.status === 403),+ );+ const account = (await connectionFor(a)).account_id;+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=?')+ .bind(account)+ .first()+ ).n,+ 1,+ );+ const refreshed = await runtime.dispatchFetch(`${origin}/oauth/token`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: credential.refresh_token,+ client_id: a.clientId,+ resource: `${origin}/mcp`,+ }),+ });+ assert.equal(refreshed.status, 400);+ assert.equal((await refreshed.json()).error, 'invalid_grant');+});++test('state changes during the upstream exchange are rechecked before linking', async () => {+ for (const mutation of ['disabled', 'epoch', 'session', 'confirmer']) {+ const user = `link-inflight-${mutation}`,+ authorization = await grant(user);+ const account = (await connectionFor(authorization)).account_id;+ const first = await actionCallback(+ await startIdentity(authorization, 'link', 'google', 'github'),+ authorization,+ user,+ );+ const second = await actionCallback(await finishIdentity(first), authorization, user);+ beforeProviderReply = async () => {+ beforeProviderReply = undefined;+ if (mutation === 'disabled')+ await database+ .prepare("UPDATE kiln_accounts SET state='disabled' WHERE id=?")+ .bind(account)+ .run();+ else if (mutation === 'epoch')+ await database+ .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')+ .bind(account)+ .run();+ else if (mutation === 'session')+ await database+ .prepare('DELETE FROM kiln_browser_sessions WHERE account_id=?')+ .bind(account)+ .run();+ else+ await database+ .prepare('DELETE FROM kiln_identities WHERE account_id=?')+ .bind(account)+ .run();+ };+ try {+ assert.equal((await finishIdentity(second)).status, 403);+ } finally {+ beforeProviderReply = undefined;+ }+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_identities WHERE account_id=? AND issuer=?')+ .bind(account, googleIssuer)+ .first()+ ).n,+ 0,+ );+ assert.equal(+ (+ await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_account_events WHERE account_id=?')+ .bind(account)+ .first()+ ).n,+ 0,+ );+ }+});++test('identity intents are bounded, store hashes and reject oversized or duplicate forms before provider I/O', async () => {+ const user = 'link-bounds',+ authorization = await grant(user);+ const account = (await connectionFor(authorization)).account_id;+ for (let i = 0; i < 4; i++) {+ const start = await startIdentity(authorization, 'link', 'google', 'github');+ assert.equal(start.status, 302);+ const state = new URL(start.headers.get('location')).searchParams.get('state');+ const binding = cookies(start).split('=')[1];+ const stored = JSON.stringify(+ (+ await database+ .prepare('SELECT * FROM kiln_identity_actions WHERE account_id=?')+ .bind(account)+ .all()+ ).results,+ );+ assert.ok(!stored.includes(state));+ assert.ok(!stored.includes(binding));+ }+ const count = outboundCalls;+ assert.equal((await startIdentity(authorization, 'link', 'google', 'github')).status, 403);+ for (const body of [+ 'x'.repeat(4097),+ 'csrf=bad&csrf=bad&action=link&target=google&provider=github',+ ]) {+ const response = await runtime.dispatchFetch(`${origin}/account/identity`, {+ method: 'POST',+ headers: {+ origin,+ cookie: authorization.browserCookie,+ 'content-type': 'application/x-www-form-urlencoded',+ },+ body,+ });+ assert.equal(response.status, body.length > 4096 ? 413 : 403);+ }+ assert.equal(outboundCalls, count);+});diff --git a/hosting/test/browser-download-worker.ts b/hosting/test/browser-download-worker.tsnew file mode 100644index 00000000..c19f1e05--- /dev/null+++ b/hosting/test/browser-download-worker.ts@@ -0,0 +1,51 @@+import gateway from '../src/worker';+import { KilnTenant } from '../src/tenant';+import { D1BrowserSessions } from '../src/browser-sessions';++// Test-only session issuer and delayed-revocation fixture, excluded from production.+export class DownloadTenant extends KilnTenant {+ override async fetch(request: Request): Promise<Response> {+ const path = new URL(request.url).pathname;+ if (path === '/fixture/revoke') {+ await this.ctx.storage.put('revoke', true);+ return new Response('set');+ }+ if (path === '/fixture/headers')+ return Response.json((await this.ctx.storage.get('headers')) ?? {});+ if (path.startsWith('/internal/downloads/')) {+ await this.ctx.storage.put('headers', Object.fromEntries(request.headers));+ const response = await super.fetch(request);+ if (await this.ctx.storage.get('revoke')) {+ // Simulate account access changing while the tenant awaits object storage.+ const env = this.env as typeof this.env & { ACCOUNTS: D1Database };+ await env.ACCOUNTS.prepare('DELETE FROM kiln_browser_sessions').run();+ }+ return response;+ }+ return super.fetch(request);+ }+}++export default {+ async fetch(request: Request, env: Parameters<typeof gateway.fetch>[1], ctx: ExecutionContext) {+ // Node's fetch overwrites Sec-Fetch-Mode with cors; reproduce browser metadata here.+ if (request.headers.has('x-fixture-fetch-mode')) {+ const headers = new Headers(request.headers);+ headers.set('sec-fetch-mode', headers.get('x-fixture-fetch-mode')!);+ headers.delete('x-fixture-fetch-mode');+ request = new Request(request, { headers });+ }+ if (new URL(request.url).pathname === '/fixture/session') {+ const { subject } = (await request.json()) as { subject: string };+ const session = await new D1BrowserSessions(env.ACCOUNTS, env.PUBLIC_ORIGIN).issue({+ issuer: 'https://github.com',+ subject,+ });+ return Response.json(+ { accountId: session.account.id },+ { headers: { 'set-cookie': session.cookie } },+ );+ }+ return gateway.fetch(request, env, ctx);+ },+};diff --git a/hosting/test/browser-downloads.test.mjs b/hosting/test/browser-downloads.test.mjsnew file mode 100644index 00000000..1975d19d--- /dev/null+++ b/hosting/test/browser-downloads.test.mjs@@ -0,0 +1,322 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { migrateAccounts } from './database.mjs';+import { rateLimitBindings } from './rate-limit-bindings.mjs';+import { mkdir } from 'node:fs/promises';+import { createKilnMcpServer } from '../../dist/mcp-engine.mjs';+import { renderGLB } from '../../lib/render.js';++const origin = 'https://kiln.example.com';+let runtime, namespace, database, createNativeMcpHandler;+const digest = (s) => createHash('sha256').update(s).digest('hex');+before(async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./browser-download-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ name: 'browser-downloads',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['global_fetch_strictly_public'],+ kvNamespaces: ['OAUTH_KV'],+ ratelimits: rateLimitBindings,+ d1Databases: ['ACCOUNTS'],+ durableObjects: { TENANTS: { className: 'DownloadTenant', useSQLite: true } },+ r2Buckets: ['ARTIFACTS'],+ bindings: {+ PUBLIC_ORIGIN: origin,+ STORAGE_MAX_BYTES: '1048576',+ STORAGE_MAX_OBJECTS: '32',+ STORAGE_MAX_GROUPS: '8',+ },+ outboundService: async () => {+ throw Error('No network or compute permitted');+ },+ }),+ );+ namespace = await runtime.getDurableObjectNamespace('TENANTS');+ database = await runtime.getD1Database('ACCOUNTS');+ await migrateAccounts(database);+ const output = new URL('../../.cache/browser-download-test/native-mcp.mjs', import.meta.url);+ await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-mcp.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: Object.fromEntries(+ [+ ['assets', 'assets'],+ ['assets/node', 'assets-node'],+ ['material-library/node', 'material-library-node'],+ ['material-library', 'material-library'],+ ['workspace', 'workspace'],+ ['evaluator', 'evaluator/index'],+ ['composer', 'composer/index'],+ ].map(([name, path]) => [+ `@instruktlabs/kiln/${name}`,+ fileURLToPath(new URL(`../../lib/${path}.js`, import.meta.url)),+ ]),+ ),+ });+ ({ createNativeMcpHandler } = await import(output));+});+after(async () => runtime?.dispose());+const selector = { collection: 'project', assetId: 'a_box', revisionId: 'r_one' };+async function session(subject) {+ const response = await runtime.dispatchFetch(`${origin}/fixture/session`, {+ method: 'POST',+ body: JSON.stringify({ subject }),+ });+ assert.equal(response.status, 200);+ const { accountId } = await response.json();+ const tenant = createHash('sha256')+ .update(JSON.stringify(['kiln-tenant-v1', origin, accountId]))+ .digest('base64url');+ const stub = namespace.getByName(tenant);+ return { accountId, cookie: response.headers.get('set-cookie').split(';')[0], stub };+}+async function seed(user) {+ const files = {};+ for (const [name, data] of [+ ['asset.glb', 'glTFfixture'],+ ['source.kiln.js', 'function build(){}'],+ ['manifest.json', '{}'],+ ]) {+ const response = await user.stub.fetch('https://tenant.internal/internal/artifacts', {+ method: 'POST',+ body: data,+ headers: {+ 'content-type':+ name === 'asset.glb'+ ? 'model/gltf-binary'+ : name.endsWith('.js')+ ? 'application/javascript'+ : 'application/json',+ 'x-artifact-name': name,+ 'x-artifact-sha256': digest(data),+ 'content-length': String(Buffer.byteLength(data)),+ },+ });+ assert.equal(response.status, 201);+ files[name] = (await response.json()).id;+ }+ const commit = await user.stub.fetch('https://tenant.internal/internal/assets/commit', {+ method: 'POST',+ body: JSON.stringify({ ...selector, files, mode: 'save' }),+ });+ assert.equal(commit.status, 201);+ const group = await commit.json();+ const response = await user.stub.fetch('https://tenant.internal/internal/downloads', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(selector),+ });+ assert.equal(response.status, 201);+ const ticket = await response.json();+ return { path: `/downloads/${ticket.ticket}/asset.glb`, group };+}+const get = (path, cookie = '', extra = {}) =>+ runtime.dispatchFetch(`${origin}${path}`, {+ redirect: 'manual',+ ...extra,+ headers: {+ cookie,+ ...extra.headers,+ ...(extra.headers?.['sec-fetch-mode']+ ? { 'x-fixture-fetch-mode': extra.headers['sec-fetch-mode'] }+ : {}),+ },+ });++test('saved bytes require the current owning browser account, with no compute or credential forwarding', async () => {+ const alice = await session('2101'),+ bob = await session('2102');+ const { path } = await seed(alice);+ const anonymous = await get(path);+ assert.equal(anonymous.status, 401);+ assert.match(+ await anonymous.text(),+ new RegExp(`name="returnTo" value="${path.replaceAll('.', '\\.')}"`),+ );+ assert.match(anonymous.headers.get('content-security-policy'), /frame-ancestors 'none'/);+ assert.equal((await get(path, bob.cookie)).status, 404);+ assert.equal(+ (+ await get(path, '', {+ headers: { authorization: 'Bearer fixture', 'x-tenant': alice.accountId },+ })+ ).status,+ 401,+ );+ const response = await get(path, alice.cookie, {+ headers: { authorization: 'Bearer fixture', 'x-tenant': bob.accountId },+ });+ assert.equal(response.status, 200);+ assert.equal(await response.text(), 'glTFfixture');+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal(response.headers.get('referrer-policy'), 'no-referrer');+ assert.match(response.headers.get('content-disposition'), /attachment; filename="asset.glb"/);+ assert.equal(response.headers.get('x-content-type-options'), 'nosniff');+ const headers = await (await alice.stub.fetch('https://tenant.internal/fixture/headers')).json();+ for (const key of ['authorization', 'cookie', 'x-tenant', 'range'])+ assert.equal(headers[key], undefined);+ const head = await get(path, alice.cookie, { method: 'HEAD' });+ assert.equal(head.status, 200);+ assert.equal(await head.text(), '');+ assert.equal(head.headers.get('content-length'), String('glTFfixture'.length));+});++test('download navigation accepts ordinary external links but denies cross-origin embedding and hostile routes', async () => {+ const alice = await session('2103');+ const { path } = await seed(alice);+ const navigate = await get(path, alice.cookie, {+ headers: {+ 'sec-fetch-site': 'cross-site',+ 'sec-fetch-mode': 'navigate',+ 'sec-fetch-dest': 'document',+ },+ });+ assert.equal(navigate.status, 200);+ await navigate.arrayBuffer();+ for (const headers of [+ { origin: 'https://evil.example' },+ { 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors', 'sec-fetch-dest': 'image' },+ { 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'iframe' },+ ])+ assert.equal((await get(path, alice.cookie, { headers })).status, 403);+ assert.equal((await get(path, alice.cookie, { method: 'POST', body: '{}' })).status, 405);+ for (const bad of [+ `${path}?tenant=other`,+ `${path}/extra`,+ path.replace('asset.glb', '%61sset.glb'),+ path.replace('asset.glb', 'secret.txt'),+ path.replace('asset.glb', 'asset.glb%0a'),+ ])+ assert.ok([400, 404].includes((await get(bad, alice.cookie)).status), bad);+ assert.equal((await get(path, '', { method: 'HEAD' })).status, 401);+});++test('browser revocation while storage is being read suppresses bytes, and deleting a saved revision revokes its links', async () => {+ const alice = await session('2104');+ const { path, group } = await seed(alice);+ await alice.stub.fetch('https://tenant.internal/fixture/revoke');+ const revoked = await get(path, alice.cookie);+ assert.equal(revoked.status, 401);+ assert.ok(!(await revoked.text()).includes('glTFfixture'));+ assert.equal((await get(path, alice.cookie)).status, 401);+ const fresh = await session('2104');+ const removed = await alice.stub.fetch(`https://tenant.internal/internal/groups/${group.id}`, {+ method: 'DELETE',+ });+ assert.equal(removed.status, 200);+ // The fixture revokes on every read; storage independently reports 404 first.+ const direct = await alice.stub.fetch(`https://tenant.internal/internal${path}`);+ assert.equal(direct.status, 404);+ assert.ok(fresh.cookie);+});++test('real MCP save and reopen links deliver exact bytes through the actual authenticated browser gateway', async () => {+ const alice = await session('2105'),+ bob = await session('2106');+ const code =+ "function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";+ const host = () =>+ createNativeMcpHandler(+ {+ createServer: createKilnMcpServer,+ evaluatorPort: {+ render: async (source, options) => {+ assert.equal(source, code);+ return renderGLB(source, options);+ },+ },+ },+ {+ publicOrigin: origin,+ storage: {+ fetch: (request) =>+ alice.stub.fetch(+ new Request(`https://tenant.internal${new URL(request.url).pathname}`, request),+ ),+ },+ },+ );+ const call = async (name, args) => {+ const handler = host();+ try {+ const response = await handler.fetch(+ new Request('http://kiln-native.internal/mcp', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2025-11-25',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name, arguments: args },+ }),+ }),+ );+ assert.equal(response.status, 200);+ const raw = await response.text();+ const result = response.headers.get('content-type')?.includes('text/event-stream')+ ? raw+ .split('\n')+ .filter((line) => line.startsWith('data:'))+ .map((line) => JSON.parse(line.slice(5)))+ .findLast((event) => event.id === 1)+ : JSON.parse(raw);+ assert.equal(result.error, undefined);+ assert.notEqual(result.result.isError, true, JSON.stringify(result));+ return JSON.parse(result.result.content.find((item) => item.type === 'text').text);+ } finally {+ await handler.close();+ }+ };+ const rendered = await call('kiln_render', { code, capture: { preset: '1x1' } });+ const saved = await call('kiln_save', {+ programRef: rendered.programRef,+ collection: 'project',+ name: 'Browser delivery box',+ });+ const request = {+ collection: 'project',+ assetId: saved.asset.assetId,+ revisionId: saved.asset.revisionId,+ };+ const reopened = await call('kiln_assets', { ...request, action: 'get' });+ assert.notEqual(saved.downloadUrls['asset.glb'], reopened.downloadUrls['asset.glb']);+ for (const name of ['asset.glb', 'source.kiln.js', 'manifest.json', 'preview.png']) {+ const path = new URL(reopened.downloadUrls[name]).pathname;+ assert.equal((await get(path, bob.cookie)).status, 404);+ const response = await get(path, alice.cookie);+ assert.equal(response.status, 200);+ const bytes = Buffer.from(await response.arrayBuffer());+ if (name === 'source.kiln.js') assert.equal(bytes.toString(), code);+ if (name === 'manifest.json') assert.equal(JSON.parse(bytes).revisionId, request.revisionId);+ if (name === 'asset.glb') {+ assert.equal(bytes.subarray(0, 4).toString(), 'glTF');+ assert.equal(`sha256:${digest(bytes)}`, reopened.asset.files[name].sha256);+ }+ if (name === 'preview.png')+ assert.deepEqual(bytes.subarray(0, 8), Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));+ }+});diff --git a/hosting/test/browser-sessions-worker.ts b/hosting/test/browser-sessions-worker.tsnew file mode 100644index 00000000..f7b634b6--- /dev/null+++ b/hosting/test/browser-sessions-worker.ts@@ -0,0 +1,24 @@+import { D1BrowserSessions } from '../src/browser-sessions';+import { serviceFailure } from '../src/http';++// Fixture only: production identity inputs come exclusively from provider proofs.+export default {+ async fetch(request: Request, env: { ACCOUNTS: D1Database }) {+ try {+ const sessions = new D1BrowserSessions(env.ACCOUNTS, 'https://kiln.test');+ const path = new URL(request.url).pathname;+ if (path === '/issue')+ return Response.json(await sessions.issue(await request.json(), request));+ if (path === '/logout') {+ const body =+ request.method === 'POST' ? ((await request.json()) as { csrf: string }) : { csrf: '' };+ return new Response(null, {+ headers: { 'set-cookie': await sessions.logout(request, body.csrf) },+ });+ }+ return Response.json(await sessions.read(request));+ } catch (error) {+ return serviceFailure(error);+ }+ },+} satisfies ExportedHandler<{ ACCOUNTS: D1Database }>;diff --git a/hosting/test/browser-sessions.test.mjs b/hosting/test/browser-sessions.test.mjsnew file mode 100644index 00000000..54ea0b1c--- /dev/null+++ b/hosting/test/browser-sessions.test.mjs@@ -0,0 +1,201 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { after, before, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';+import { migrateAccounts } from './database.mjs';++let runtime;+let database;+before(async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./browser-sessions-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ d1Databases: ['ACCOUNTS'],+ outboundService: async () => {+ throw new Error('Session storage must not fetch');+ },+ }),+ );+ database = await runtime.getD1Database('ACCOUNTS');+ await migrateAccounts(database);+});+after(async () => runtime?.dispose());++const cookie = (issued) => issued.cookie.split(';')[0];+const issue = async (subject, previous) => {+ const response = await runtime.dispatchFetch('https://kiln.test/issue', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...(previous ? { cookie: cookie(previous) } : {}),+ },+ body: JSON.stringify({ issuer: 'https://github.com', subject }),+ });+ assert.equal(response.status, 200);+ return response.json();+};+const read = (issued, headers = {}, url = 'https://kiln.test/account') =>+ runtime.dispatchFetch(url, { headers: { cookie: cookie(issued), ...headers } });+const logout = (issued, csrf = issued.csrf, origin = 'https://kiln.test', method = 'POST') =>+ runtime.dispatchFetch('https://kiln.test/logout', {+ method,+ headers: { cookie: cookie(issued), origin, 'content-type': 'application/json' },+ body: method === 'GET' ? undefined : JSON.stringify({ csrf }),+ });++test('browser sessions use fresh protected cookies and store only bearer-token hashes', async () => {+ const issued = await issue('browser-storage');+ assert.match(issued.cookie, /^__Host-kiln-session=[a-f0-9]{64};/);+ for (const attribute of ['Secure', 'HttpOnly', 'SameSite=Lax', 'Path=/', 'Max-Age=86400'])+ assert.ok(issued.cookie.includes(attribute));+ assert.ok(!issued.cookie.includes('Domain='));+ assert.match(issued.csrf, /^[a-f0-9]{64}$/);+ const session = await (await read(issued)).json();+ assert.equal(session.accountId, issued.account.id);+ assert.equal(session.accountEpoch, 1);+ const rows = await database.prepare('SELECT * FROM kiln_browser_sessions').all();+ const raw = cookie(issued).split('=')[1];+ assert.ok(!JSON.stringify(rows.results).includes(raw));+ const again = await issue('browser-storage');+ assert.equal(again.account.id, issued.account.id);+ assert.notEqual(cookie(again), cookie(issued));+});++test('a session cannot authenticate with a header, URL token, duplicate cookie, foreign origin or a stored hash', async () => {+ const issued = await issue('browser-cookie-admission');+ const raw = cookie(issued).split('=')[1];+ const stored = await database+ .prepare('SELECT token_hash FROM kiln_browser_sessions WHERE account_id=?')+ .bind(issued.account.id)+ .first();+ for (const headers of [+ { cookie: '', authorization: `Bearer ${raw}` },+ { cookie: `${cookie(issued)}; ${cookie(issued)}` },+ { cookie: `__Host-kiln-session=${stored.token_hash}` },+ { cookie: '__Host-kiln-session=invalid' },+ { cookie: `${cookie(issued)}; padding=${'x'.repeat(8192)}` },+ ])+ assert.equal((await read(issued, headers)).status, 401);+ assert.equal(+ (await read(issued, { cookie: '' }, `https://kiln.test/account?session=${raw}`)).status,+ 401,+ );+ assert.equal((await read(issued, {}, 'https://foreign.test/account')).status, 401);+});++test('expired sessions and changed account state or epoch fail closed', async () => {+ for (const mutation of ['expired', 'epoch', 'disabled', 'deleting']) {+ const issued = await issue(`browser-${mutation}`);+ if (mutation === 'expired')+ await database+ .prepare('UPDATE kiln_browser_sessions SET expires_at=0 WHERE account_id=?')+ .bind(issued.account.id)+ .run();+ else if (mutation === 'epoch')+ await database+ .prepare('UPDATE kiln_accounts SET authorization_epoch=2 WHERE id=?')+ .bind(issued.account.id)+ .run();+ else+ await database+ .prepare('UPDATE kiln_accounts SET state=? WHERE id=?')+ .bind(mutation, issued.account.id)+ .run();+ assert.equal((await read(issued)).status, 401);+ }+});++test('logout requires a same-origin POST and matching session CSRF proof', async () => {+ const issued = await issue('browser-logout');+ const other = await issue('browser-other');+ assert.equal((await logout(issued, issued.csrf, 'https://foreign.test')).status, 403);+ assert.equal((await logout(issued, other.csrf)).status, 403);+ assert.equal((await logout(issued, issued.csrf, 'https://kiln.test', 'GET')).status, 403);+ assert.equal((await read(issued)).status, 200);+ const result = await logout(issued);+ assert.equal(result.status, 200);+ assert.match(result.headers.get('set-cookie'), /Max-Age=0/);+ assert.equal((await read(issued)).status, 401);+ assert.equal((await read(other)).status, 200);+});++test('each account retains at most eight sessions without revoking other accounts', async () => {+ const other = await issue('browser-limit-other');+ const issued = await Promise.all(+ Array.from({ length: 20 }, () => issue('browser-session-limit')),+ );+ const accountId = issued[0].account.id;+ assert.equal(new Set(issued.map((value) => value.account.id)).size, 1);+ const row = await database+ .prepare('SELECT COUNT(*) AS n FROM kiln_browser_sessions WHERE account_id=?')+ .bind(accountId)+ .first();+ assert.equal(row.n, 8);+ assert.equal((await read(other)).status, 200);+});++test('session-write failure rolls back pruning and leaves existing sessions intact', async () => {+ const issued = await issue('browser-rollback');+ await database+ .prepare(`CREATE TRIGGER reject_session BEFORE INSERT ON kiln_browser_sessions+ BEGIN SELECT RAISE(ABORT, 'fixture rejection'); END`)+ .run();+ const response = await runtime.dispatchFetch('https://kiln.test/issue', {+ method: 'POST',+ body: JSON.stringify({ issuer: 'https://github.com', subject: 'browser-rollback' }),+ });+ assert.equal(response.status, 503);+ assert.equal((await read(issued)).status, 200);+ await database.prepare('DROP TRIGGER reject_session').run();+});++test('idle sessions expire and active requests cannot extend the absolute lifetime', async () => {+ const idle = await issue('browser-idle');+ await database+ .prepare('UPDATE kiln_browser_sessions SET idle_expires_at=0 WHERE account_id=?')+ .bind(idle.account.id)+ .run();+ assert.equal((await read(idle)).status, 401);+ assert.equal((await logout(idle)).status, 403);+ const active = await issue('browser-active');+ const absolute = Date.now() + 60_000;+ await database+ .prepare('UPDATE kiln_browser_sessions SET expires_at=? WHERE account_id=?')+ .bind(absolute, active.account.id)+ .run();+ assert.equal((await read(active)).status, 200);+ const stored = await database+ .prepare('SELECT expires_at, idle_expires_at FROM kiln_browser_sessions WHERE account_id=?')+ .bind(active.account.id)+ .first();+ assert.equal(stored.expires_at, absolute);+ assert.equal(stored.idle_expires_at, absolute);+});++test('fresh browser sign-in replaces that browser session without affecting another device', async () => {+ const previous = await issue('browser-rotation');+ const other = await issue('browser-rotation');+ const current = await issue('browser-rotation', previous);+ assert.equal((await read(previous)).status, 401);+ assert.equal((await read(current)).status, 200);+ assert.equal((await read(other)).status, 200);+});++test('rotating a browser at the session limit retains the other seven devices', async () => {+ const devices = [];+ for (let index = 0; index < 8; index++) devices.push(await issue('browser-rotation-limit'));+ const current = await issue('browser-rotation-limit', devices[7]);+ assert.equal((await read(current)).status, 200);+ assert.equal((await read(devices[7])).status, 401);+ for (const device of devices.slice(0, 7)) assert.equal((await read(device)).status, 200);+});diff --git a/hosting/test/build-boundary.test.mjs b/hosting/test/build-boundary.test.mjsnew file mode 100644index 00000000..fe1e2e7f--- /dev/null+++ b/hosting/test/build-boundary.test.mjs@@ -0,0 +1,49 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { assertProductionBoundary } from '../scripts/build-boundary.mjs';++for (const module of [+ 'github',+ 'account-page',+ 'account-actions',+ 'connections',+ 'browser-download',+]) {+ test(`the actual ${module} dependency graph is gateway-only`, async () => {+ const result = await build({+ entryPoints: [fileURLToPath(new URL(`../src/${module}.ts`, import.meta.url))],+ bundle: true,+ write: false,+ metafile: true,+ format: 'esm',+ platform: 'browser',+ });+ const inputs = Object.keys(result.metafile.inputs);+ assert.doesNotThrow(() => assertProductionBoundary('worker', inputs));+ for (const entry of [+ 'tenant-worker',+ 'evaluation-worker',+ 'render-worker',+ 'request-worker',+ 'native-programs',+ 'native-assets',+ 'native-materials',+ 'native-mcp',+ 'native-host',+ 'native-evaluator',+ 'native-render',+ ]) {+ assert.throws(() => assertProductionBoundary(entry, inputs), /authorization-server/);+ assert.throws(+ () =>+ assertProductionBoundary(+ entry,+ inputs.map((name) => name.replaceAll('/', '\\')),+ ),+ /authorization-server/,+ );+ }+ });+}diff --git a/hosting/test/container-entry.test.mjs b/hosting/test/container-entry.test.mjsnew file mode 100644index 00000000..189ac131--- /dev/null+++ b/hosting/test/container-entry.test.mjs@@ -0,0 +1,81 @@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { copyFile, mkdir } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { createEvaluatorRequestV2, decodeEvaluatorResultV2 } from '../../lib/evaluator/index.js';++const output = new URL('../../.cache/hosted-container-test/', import.meta.url);+const entry = fileURLToPath(new URL('evaluate.mjs', output));+const limits = { maxGlbBytes: 2 * 1024 * 1024, maxResponseBytes: 8 * 1024 * 1024 };++before(async () => {+ // Resolve the engine package's compiled exports outside hosting's private scope.+ await mkdir(output, { recursive: true });+ await copyFile(new URL('../container/evaluate.mjs', import.meta.url), entry);+});++// Only trusted fixed fixtures run on the test host. These are protocol checks,+// not evidence that the child process can contain hostile source.+function run(input) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [entry], {+ env: { ...process.env, KILN_RENDER: 'cpu' },+ stdio: ['pipe', 'pipe', 'pipe'],+ timeout: 20_000,+ });+ const stdout = [];+ const stderr = [];+ child.stdout.on('data', (chunk) => stdout.push(chunk));+ child.stderr.on('data', (chunk) => stderr.push(chunk));+ child.stdin.on('error', (error) => {+ if (!['EPIPE', 'ECONNRESET', 'EOF'].includes(error.code)) reject(error);+ });+ child.on('error', reject);+ child.on('close', (code, signal) =>+ resolve({+ code,+ signal,+ stdout: Buffer.concat(stdout).toString('utf8'),+ stderr: Buffer.concat(stderr).toString('utf8'),+ }),+ );+ child.stdin.end(input);+ });+}++test('container entry produces a canonical deterministic GLB from the compiled package', async () => {+ const { json } = createEvaluatorRequestV2({+ requestId: 'container-entry',+ code: 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',+ maxGlbBytes: limits.maxGlbBytes,+ });+ let previous;+ for (let i = 0; i < 2; i++) {+ const result = await run(json);+ assert.equal(result.signal, null);+ assert.equal(result.code, 0, result.stderr);+ const decoded = decodeEvaluatorResultV2(result.stdout, limits.maxGlbBytes, 'container-entry');+ assert.equal(decoded.ok, true);+ assert.equal(decoded.render.glb.subarray(0, 4).toString(), 'glTF');+ assert.ok(Buffer.byteLength(result.stdout) <= limits.maxResponseBytes);+ if (previous) assert.deepEqual(decoded.render.glb, previous);+ previous = decoded.render.glb;+ }+});++test('container entry returns only the canonical rejection for malformed envelopes', async () => {+ const result = await run('{"private":"FIXTURE_SOURCE_DO_NOT_ECHO"}');+ assert.equal(result.code, 0, result.stderr);+ assert.equal(JSON.parse(result.stdout).error.code, 'INPUT_INVALID');+ assert.equal(`${result.stdout}${result.stderr}`.includes('FIXTURE_SOURCE_DO_NOT_ECHO'), false);+});++test('container entry refuses oversized input and invalid UTF-8 without evaluation', async () => {+ for (const input of [Buffer.alloc(4 * 1024 * 1024 + 1, 32), Buffer.from([0xc3, 0x28])]) {+ const result = await run(input);+ assert.equal(result.code, 1);+ assert.equal(result.stdout, '');+ assert.equal(result.stderr, 'Kiln evaluator input or execution failed.\n');+ }+});diff --git a/hosting/test/container-job.test.mjs b/hosting/test/container-job.test.mjsnew file mode 100644index 00000000..72b3915e--- /dev/null+++ b/hosting/test/container-job.test.mjs@@ -0,0 +1,489 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';++let ContainerEvaluationJob, ContainerRenderJob;+const image = `registry.cloudflare.com/fixture/kiln@sha256:${'a'.repeat(64)}`;+const encoder = new TextEncoder();+const input = encoder.encode('{"version":"kiln.evaluator.request.v2"}');+const response = encoder.encode('{"version":"kiln.evaluator.result.v2"}');+const controls = { deadlineMs: 2_000, maxResponseBytes: 1024 };+const code = (expected) => (error) => error.code === expected;++before(async () => {+ const output = new URL('../../.cache/hosted-container-test/job.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/container-job.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ ContainerEvaluationJob, ContainerRenderJob } = await import(output));+});++function fixture(options = {}) {+ const values = new Map();+ const events = [];+ let alarmAt;+ let transactionTail = Promise.resolve();+ let stopped;+ const monitor = new Promise((resolve) => {+ stopped = resolve;+ });+ let releaseExec;+ const pendingExec = new Promise((resolve) => {+ releaseExec = resolve;+ });+ let failCleanup = options.failCleanup ?? false;+ let unconfirmedCleanup = options.unconfirmedCleanup;+ const received = [];+ const stream = (bytes, hanging = false) =>+ new ReadableStream({+ start(controller) {+ if (bytes) controller.enqueue(bytes);+ if (!hanging) controller.close();+ },+ });+ const process = {+ stdin: new WritableStream({+ write(bytes) {+ events.push('input');+ received.push(bytes);+ },+ }),+ stdout: stream(options.output ?? response, options.hanging),+ stderr: stream(options.stderr ?? new Uint8Array()),+ exitCode: options.hanging ? new Promise(() => {}) : Promise.resolve(options.exitCode ?? 0),+ };+ const container = {+ images: { kiln: options.image ?? image, renderer: options.image ?? image },+ running: false,+ start(settings) {+ events.push('start');+ this.settings = settings;+ this.running = true;+ if (options.startFailure) throw new Error('private provider diagnostic');+ },+ async exec(command, settings) {+ events.push('exec');+ this.command = command;+ this.execSettings = settings;+ // The native API rejects named Linux identities. The image uses USER node.+ if (options.requireNumericUser && settings.user !== '1000:1000')+ throw new Error('internal error; fixture requires numeric uid:gid');+ return options.pendingExec ? pendingExec : process;+ },+ monitor() {+ return monitor;+ },+ async inspect() {+ events.push('inspect');+ if (events.includes('destroy')) {+ if (unconfirmedCleanup === 'inspect-error') throw new Error('private inspection failure');+ if (unconfirmedCleanup === 'inspect-pending') return new Promise(() => {});+ if (unconfirmedCleanup === 'inspect-live') return { image };+ }+ return this.running ? { image: options.observedImage ?? image } : null;+ },+ async setInactivityTimeout() {},+ async destroy() {+ events.push('destroy');+ if (failCleanup) throw new Error('private cleanup diagnostic');+ if (unconfirmedCleanup === 'running') return;+ this.running = false;+ stopped();+ },+ };+ const storage = {+ async get(key) {+ return values.get(key);+ },+ async put(key, value) {+ values.set(key, structuredClone(value));+ },+ async setAlarm(value) {+ events.push('alarm');+ alarmAt = Number(value);+ },+ async deleteAlarm() {+ alarmAt = undefined;+ },+ async transaction(callback) {+ const operation = transactionTail.then(() => callback(storage));+ transactionTail = operation.catch(() => {});+ return operation;+ },+ };+ return {+ context: { container, storage },+ values,+ events,+ received,+ get alarmAt() {+ return alarmAt;+ },+ finishStartup() {+ releaseExec(process);+ },+ repairCleanup() {+ failCleanup = false;+ unconfirmedCleanup = undefined;+ },+ };+}++test('render jobs use a fixed software image and entry with the same cleanup fence', async () => {+ const f = fixture();+ const result = await new ContainerRenderJob(f.context).run(input, controls);+ assert.deepEqual(result, response);+ assert.deepEqual(f.context.container.command, ['/usr/local/bin/node', '/opt/kiln/render.mjs']);+ assert.deepEqual(f.context.container.execSettings.env, {});+ assert.equal(f.context.container.settings.enableInternet, false);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').state, 'finished');+ for (const limits of [+ { ...controls, deadlineMs: 30001 },+ { ...controls, maxResponseBytes: 20 * 1024 * 1024 + 1 },+ ]) {+ const rejected = fixture();+ await assert.rejects(+ new ContainerRenderJob(rejected.context).run(input, limits),+ code('INPUT_INVALID'),+ );+ assert.equal(rejected.events.includes('start'), false);+ }+ const wrongImage = fixture();+ delete wrongImage.context.container.images.renderer;+ await assert.rejects(+ new ContainerRenderJob(wrongImage.context).run(input, controls),+ code('INPUT_INVALID'),+ );+ assert.equal(wrongImage.events.includes('start'), false);+});++test('render cancellation survives eviction and unconfirmed cleanup suppresses output', async () => {+ const cancelled = fixture();+ await new ContainerRenderJob(cancelled.context).cancel();+ await assert.rejects(+ new ContainerRenderJob(cancelled.context).run(input, controls),+ code('JOB_ALREADY_USED'),+ );+ assert.equal(cancelled.events.includes('start'), false);+ const f = fixture({ failCleanup: true });+ await assert.rejects(+ new ContainerRenderJob(f.context).run(input, controls),+ code('CLEANUP_FAILED'),+ );+ assert.equal(f.values.get('job').state, 'running');+ f.repairCleanup();+ await new ContainerRenderJob(f.context).cancel();+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').state, 'finished');+});++test('starts one pinned, offline VM and destroys it before returning any output', async () => {+ const f = fixture();+ const job = new ContainerEvaluationJob(f.context);+ const result = await job.run(input, controls);+ assert.equal(job.executionImage(result), image);+ assert.equal(job.executionImage(Uint8Array.from(result)), undefined);+ assert.deepEqual(result, response);+ assert.equal(f.context.container.running, false);+ assert.deepEqual(f.received, [input]);+ assert.equal(f.context.container.settings.enableInternet, false);+ assert.equal(f.context.container.settings.image, image);+ assert.equal(f.context.container.settings.containerSnapshot, undefined);+ assert.deepEqual(f.context.container.command, ['/usr/local/bin/node', '/opt/kiln/evaluate.mjs']);+ assert.deepEqual(f.context.container.execSettings.env, { KILN_RENDER: 'cpu' });+ assert.ok(f.events.indexOf('alarm') < f.events.indexOf('start'));+ assert.ok(f.events.indexOf('inspect') < f.events.indexOf('input'));+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.alarmAt, undefined);+});++test('execution identity is unavailable for failed isolation or unconfirmed cleanup', async () => {+ for (const options of [{ observedImage: 'wrong-image' }, { failCleanup: true }]) {+ const f = fixture(options);+ const job = new ContainerEvaluationJob(f.context);+ await assert.rejects(job.run(input, controls));+ assert.equal(job.executionImage(response), undefined);+ }+});++test('rejects concurrent and subsequent attempts on the same durable job', async () => {+ const f = fixture();+ const first = new ContainerEvaluationJob(f.context);+ const second = new ContainerEvaluationJob(f.context);+ const results = await Promise.allSettled([+ first.run(input, controls),+ second.run(input, controls),+ ]);+ assert.equal(results.filter((result) => result.status === 'fulfilled').length, 1);+ assert.equal(+ results.find((result) => result.status === 'rejected').reason.code,+ 'JOB_ALREADY_USED',+ );+ assert.equal(f.events.filter((event) => event === 'start').length, 1);+ assert.equal(f.events.filter((event) => event === 'destroy').length, 1);+ await assert.rejects(second.run(input, controls), code('JOB_ALREADY_USED'));+});++test('exec explicitly selects the image user by numeric uid and gid', async () => {+ const f = fixture({ requireNumericUser: true });+ assert.deepEqual(await new ContainerEvaluationJob(f.context).run(input, controls), response);+ assert.equal(f.context.container.execSettings.user, '1000:1000');+ assert.equal(f.context.container.running, false);+});++test('rejects unpinned images, excessive requests and invalid limits before starting', async () => {+ for (const [options, request, limits] of [+ [{ image: 'registry.example/kiln:latest' }, input, controls],+ [{}, new Uint8Array(4 * 1024 * 1024 + 1), controls],+ [{}, input, { ...controls, deadlineMs: 60_001 }],+ [{}, input, { ...controls, maxResponseBytes: 8 * 1024 * 1024 + 1 }],+ ]) {+ const f = fixture(options);+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(request, limits),+ code('INPUT_INVALID'),+ );+ assert.equal(f.events.includes('start'), false);+ }+});++test('does not send source to an image whose observed identity differs', async () => {+ const f = fixture({ observedImage: `registry.example/other@sha256:${'b'.repeat(64)}` });+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('ISOLATION_UNAVAILABLE'),+ );+ assert.deepEqual(f.received, []);+ assert.equal(f.context.container.running, false);+});++test('output and stderr floods destroy the VM and cannot return a success', async () => {+ for (const options of [+ { output: new Uint8Array(1025), hanging: true },+ { stderr: new Uint8Array(16_385) },+ ]) {+ const f = fixture(options);+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('OUTPUT_LIMIT_EXCEEDED'),+ );+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').outcome, 'OUTPUT_LIMIT_EXCEEDED');+ }+});++test('the external deadline destroys a hung evaluation including when startup is pending', async () => {+ for (const options of [{ hanging: true }, { pendingExec: true }]) {+ const f = fixture(options);+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, { ...controls, deadlineMs: 30 }),+ code('DEADLINE_EXCEEDED'),+ );+ assert.equal(f.context.container.running, false);+ if (options.pendingExec) {+ f.finishStartup();+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(f.received, []);+ }+ }+});++test('caller cancellation destroys the whole VM; pre-cancellation starts nothing', async () => {+ const f = fixture({ pendingExec: true });+ const controller = new AbortController();+ const pending = new ContainerEvaluationJob(f.context).run(input, {+ ...controls,+ signal: controller.signal,+ });+ while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));+ controller.abort();+ await assert.rejects(pending, code('CANCELLED'));+ assert.equal(f.context.container.running, false);+ const untouched = fixture();+ await assert.rejects(+ new ContainerEvaluationJob(untouched.context).run(input, {+ ...controls,+ signal: controller.signal,+ }),+ code('CANCELLED'),+ );+ assert.deepEqual(untouched.events, []);+});++test('cleanup failure suppresses output and a durable recovery alarm retries destruction', async () => {+ const f = fixture({ failCleanup: true });+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('CLEANUP_FAILED'),+ );+ assert.equal(f.values.get('job').state, 'running');+ assert.ok(Number.isSafeInteger(f.alarmAt));+ f.repairCleanup();+ f.values.get('job').deadlineAt = Date.now() - 1;+ await new ContainerEvaluationJob(f.context).alarm();+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.values.get('job').outcome, 'DEADLINE_EXCEEDED');+ assert.equal(f.alarmAt, undefined);+});++test('cleanup must confirm both stopped state and inspection before releasing output or its alarm', async () => {+ for (const unconfirmedCleanup of ['running', 'inspect-live', 'inspect-error']) {+ const f = fixture({ unconfirmedCleanup });+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('CLEANUP_FAILED'),+ );+ assert.equal(f.values.get('job').state, 'running');+ assert.ok(Number.isSafeInteger(f.alarmAt));+ f.values.get('job').deadlineAt = Date.now() - 1;+ await assert.rejects(new ContainerEvaluationJob(f.context).alarm(), code('CLEANUP_FAILED'));+ assert.equal(f.values.get('job').state, 'running');+ assert.ok(f.alarmAt > Date.now());+ f.repairCleanup();+ await new ContainerEvaluationJob(f.context).alarm();+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.alarmAt, undefined);+ }+});++test('the same cleanup deadline bounds a stalled stopped-state inspection', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] });+ const f = fixture({ unconfirmedCleanup: 'inspect-pending' });+ const pending = new ContainerEvaluationJob(f.context).run(input, controls);+ const rejected = assert.rejects(pending, code('CLEANUP_FAILED'));+ // Let real promise/stream callbacks reach cleanup before advancing the clock.+ await new Promise((resolve) => setImmediate(resolve));+ assert.ok(f.events.includes('destroy'));+ t.mock.timers.tick(5_000);+ await rejected;+ assert.equal(f.values.get('job').state, 'running');+ assert.ok(Number.isSafeInteger(f.alarmAt));+});++test('startup or native process failures are bounded public errors with cleanup', async () => {+ for (const options of [{ startFailure: true }, { exitCode: 1 }]) {+ const f = fixture(options);+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('WORKER_FAILED'),+ );+ assert.equal(f.context.container.running, false);+ }+});++test('durable cancellation fences a child before arrival and survives object reconstruction', async () => {+ const f = fixture();+ const job = new ContainerEvaluationJob(f.context);+ await job.cancel();+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.values.get('job').outcome, 'CANCELLED');+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('JOB_ALREADY_USED'),+ );+ assert.equal(f.events.includes('start'), false);+ assert.equal(f.alarmAt, undefined);+});++test('durable cancellation during the persisted claim cannot start a late VM', async () => {+ const f = fixture();+ const job = new ContainerEvaluationJob(f.context);+ assert.equal(typeof job.cancel, 'function');+ let release;+ const gate = new Promise((resolve) => {+ release = resolve;+ });+ const transaction = f.context.storage.transaction;+ f.context.storage.transaction = (callback) =>+ transaction(async (tx) => {+ await gate;+ return callback(tx);+ });+ const rejected = assert.rejects(job.run(input, controls), code('CANCELLED'));+ const cancelled = job.cancel();+ release();+ await Promise.all([rejected, cancelled]);+ assert.equal(f.events.includes('start'), false);+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.values.get('job').outcome, 'CANCELLED');+ assert.equal(f.alarmAt, undefined);+});++test('durable cancellation waits for confirmed cleanup and prevents late startup input', async () => {+ const f = fixture({ pendingExec: true });+ const job = new ContainerEvaluationJob(f.context);+ assert.equal(typeof job.cancel, 'function');+ let release;+ const gate = new Promise((resolve) => {+ release = resolve;+ });+ const destroy = f.context.container.destroy.bind(f.context.container);+ f.context.container.destroy = async () => {+ await gate;+ await destroy();+ };+ const rejected = assert.rejects(job.run(input, controls), code('CANCELLED'));+ while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));+ let returned = false;+ const cancelled = job.cancel().then(() => {+ returned = true;+ });+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(returned, false);+ assert.equal(f.context.container.running, true);+ assert.equal(f.values.get('job').cancelled, true);+ const repeated = job.cancel();+ const alarm = job.alarm();+ release();+ await Promise.all([rejected, cancelled, repeated, alarm]);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.events.filter((event) => event === 'destroy').length, 1);+ f.finishStartup();+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(f.received, []);+});++test('failed cancellation retains a durable fence and alarm for recovery after eviction', async () => {+ const f = fixture({ pendingExec: true, failCleanup: true });+ const job = new ContainerEvaluationJob(f.context);+ assert.equal(typeof job.cancel, 'function');+ const rejected = assert.rejects(job.run(input, controls), code('CLEANUP_FAILED'));+ while (!f.events.includes('exec')) await new Promise((resolve) => setImmediate(resolve));+ await assert.rejects(job.cancel(), code('CLEANUP_FAILED'));+ await rejected;+ assert.equal(f.values.get('job').state, 'running');+ assert.equal(f.values.get('job').cancelled, true);+ assert.ok(Number.isSafeInteger(f.alarmAt));+ f.repairCleanup();+ await new ContainerEvaluationJob(f.context).alarm();+ assert.equal(f.values.get('job').state, 'finished');+ assert.equal(f.values.get('job').outcome, 'CANCELLED');+ assert.equal(f.context.container.running, false);+ assert.equal(f.alarmAt, undefined);+ await assert.rejects(+ new ContainerEvaluationJob(f.context).run(input, controls),+ code('JOB_ALREADY_USED'),+ );+});++test('repeated cancellation preserves completed work and never restarts or destroys it again', async () => {+ const f = fixture();+ const job = new ContainerEvaluationJob(f.context);+ assert.equal(typeof job.cancel, 'function');+ await job.run(input, controls);+ const previous = structuredClone(f.values.get('job'));+ await Promise.all([job.cancel(), job.cancel()]);+ await new ContainerEvaluationJob(f.context).cancel();+ assert.deepEqual(f.values.get('job'), previous);+ assert.equal(f.events.filter((event) => event === 'start').length, 1);+ assert.equal(f.events.filter((event) => event === 'destroy').length, 1);+});diff --git a/hosting/test/database.mjs b/hosting/test/database.mjsindex 997f0b86..22aaa300 100644--- a/hosting/test/database.mjs+++ b/hosting/test/database.mjs@@ -1,7 +1,17 @@import { readFile } from 'node:fs/promises';export async function migrateAccounts(database) {- for (const file of ['0001_accounts.sql', '0002_login_intents.sql']) {+ for (const file of [+ '0001_accounts.sql',+ '0002_login_intents.sql',+ '0003_browser_sessions.sql',+ '0004_browser_logins.sql',+ '0005_connections.sql',+ '0006_account_actions.sql',+ '0007_browser_login_return.sql',+ '0008_identity_actions.sql',+ '0009_account_deletion.sql',+ ]) {const source = await readFile(new URL(`../migrations/${file}`, import.meta.url), 'utf8');await database.batch(sourcediff --git a/hosting/test/deletion-integration-worker.ts b/hosting/test/deletion-integration-worker.tsnew file mode 100644index 00000000..4df3c550--- /dev/null+++ b/hosting/test/deletion-integration-worker.ts@@ -0,0 +1,32 @@+import { WorkerEntrypoint } from 'cloudflare:workers';+import gateway, { type Env } from '../src/worker';++// No native job is started in this identity/storage fixture. The real admission+// cancellation contract is exercised separately by admission-worker.test.mjs.+export class EmptyCompute extends WorkerEntrypoint<Env> {+ health() {+ return { paused: false, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 1 };+ }+ dispatch(): Response {+ return new Response('Native execution excluded from fixture', { status: 503 });+ }+ async retireTenant(tenant: string): Promise<void> {+ await this.env.ACCOUNTS.prepare(+ 'CREATE TABLE IF NOT EXISTS fixture_retired (tenant TEXT PRIMARY KEY)',+ ).run();+ await this.env.ACCOUNTS.prepare('INSERT OR IGNORE INTO fixture_retired VALUES (?)')+ .bind(tenant)+ .run();+ }+}++// Allows tests to invoke the actual scheduled handler. This file never ships.+export default {+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {+ if (new URL(request.url).pathname === '/fixture/recover') {+ await gateway.scheduled({ cron: '* * * * *', scheduledTime: Date.now(), noRetry() {} }, env);+ return new Response('Recovered');+ }+ return gateway.fetch(request, env, ctx);+ },+};diff --git a/hosting/test/deletion-recovery.test.mjs b/hosting/test/deletion-recovery.test.mjsnew file mode 100644index 00000000..b6d09204--- /dev/null+++ b/hosting/test/deletion-recovery.test.mjs@@ -0,0 +1,123 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';++let deletionPorts;+before(async () => {+ const output = new URL('../../.cache/hosted-deletion-recovery/ports.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/deletion-recovery.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ deletionPorts } = await import(output));+});+const account = `ka_${'a'.repeat(32)}`,+ origin = 'https://kiln.example.com';+const tenant = createHash('sha256')+ .update(JSON.stringify(['kiln-tenant-v1', origin, account]))+ .digest('base64url');++test('deletion binding derives tenancy outside compute and accepts only an exact, complete storage receipt', async () => {+ const calls = [];+ let response = { state: 'purged', pendingWrites: 0, remainingObjects: 0 };+ const env = {+ NATIVE_COMPUTE: { retireTenant: async (value) => calls.push(['compute', value]) },+ TENANTS: {+ getByName: (value) => ({+ async fetch(url, init) {+ calls.push(['storage', value, url, init]);+ return Response.json(response);+ },+ }),+ },+ };+ const ports = deletionPorts(env, origin, {});+ await ports.retireCompute(account);+ assert.equal(await ports.retireStorage(account), true);+ assert.deepEqual(calls, [+ ['compute', tenant],+ ['storage', tenant, 'https://tenant.internal/internal/account-deletion', { method: 'POST' }],+ ]);+ response = { state: 'retiring', pendingWrites: 1, remainingObjects: 1 };+ assert.equal(await ports.retireStorage(account), false);+ for (const invalid of [+ { state: 'purged', pendingWrites: 1, remainingObjects: 0 },+ { state: 'purged', pendingWrites: 0, remainingObjects: 1 },+ { state: 'purged', pendingWrites: 0 },+ { state: 'active', pendingWrites: 0, remainingObjects: 0 },+ { state: 'purged', pendingWrites: 0, remainingObjects: 0, tenant: 'other' },+ 'x'.repeat(2048),+ ]) {+ response = invalid;+ await assert.rejects(ports.retireStorage(account));+ }+ await assert.rejects(ports.retireStorage('invalid-account'));+ await assert.rejects(deletionPorts({ TENANTS: env.TENANTS }, origin, {}).retireCompute(account));+});++test('grant cleanup is bounded to the deleting owner and persists progress only after revocation', async () => {+ const revoked = [],+ cleared = [];+ let known = ['known-grant'],+ listed = [{ id: 'orphan-grant', userId: account }];+ const env = {+ ACCOUNTS: {+ withSession(mode) {+ assert.equal(mode, 'first-primary');+ return {+ prepare(sql) {+ return {+ bind(...args) {+ assert.equal(args[0], account);+ return {+ all: async () => {+ assert.match(sql, /LIMIT 4/);+ return { results: known.map((id) => ({ id })) };+ },+ run: async () => {+ cleared.push(args);+ known = known.filter((id) => id !== args[1]);+ },+ };+ },+ };+ },+ };+ },+ },+ };+ const oauth = {+ listUserGrants: async (user, options) => {+ assert.equal(user, account);+ assert.deepEqual(options, { limit: 4 });+ return { items: listed };+ },+ revokeGrant: async (id, user) => {+ revoked.push([id, user]);+ listed = listed.filter((row) => row.id !== id);+ },+ };+ const ports = deletionPorts(env, origin, oauth);+ assert.equal(await ports.revokeGrants(account), false);+ assert.deepEqual(revoked, [+ ['known-grant', account],+ ['orphan-grant', account],+ ]);+ assert.equal(cleared.length, 2);+ assert.equal(await ports.revokeGrants(account), true);+ listed = [{ id: 'foreign', userId: 'other' }];+ await assert.rejects(ports.revokeGrants(account));+ assert.equal(revoked.length, 2);+ listed = [];+ known = ['failed-grant'];+ oauth.revokeGrant = async () => {+ throw new Error('Injected revocation failure');+ };+ await assert.rejects(ports.revokeGrants(account));+ assert.deepEqual(known, ['failed-grant']);+});diff --git a/hosting/test/deletions-worker.ts b/hosting/test/deletions-worker.tsnew file mode 100644index 00000000..9e6a3cd1--- /dev/null+++ b/hosting/test/deletions-worker.ts@@ -0,0 +1,87 @@+import { D1AccountDeletions } from '../src/account-deletions';+import { serviceFailure } from '../src/http';+import type { BrowserSession } from '../src/browser-sessions';+import type { VerifiedIdentity } from '../src/accounts';++// This synthetic interface supplies verified proofs only for local tests. It is+// not a production route, credential issuer or native execution qualification.+export default {+ async fetch(+ request: Request,+ env: { ACCOUNTS: D1Database },+ ctx: ExecutionContext,+ ): Promise<Response> {+ const database = env.ACCOUNTS;+ const ports = {+ async retireCompute(account: string) {+ await database+ .prepare("INSERT INTO fixture_calls VALUES ('compute',?)")+ .bind(account)+ .run();+ if (await database.prepare("SELECT 1 FROM fixture_faults WHERE name='compute'").first())+ throw new Error('Injected compute cleanup');+ if (+ await database.prepare("SELECT 1 FROM fixture_faults WHERE name='held-compute'").first()+ ) {+ const pending = new Promise<void>((resolve) => setTimeout(resolve, 20_200)).then(+ async () => {+ await database+ .prepare("INSERT INTO fixture_calls VALUES ('compute-returned',?)")+ .bind(account)+ .run();+ },+ );+ // Keep the originating request alive so this fixture proves a real+ // late completion, not just workerd cancelling an abandoned promise.+ ctx.waitUntil(pending);+ await pending;+ }+ if (+ await database.prepare("SELECT 1 FROM fixture_faults WHERE name='lease-takeover'").first()+ )+ await database+ .prepare("UPDATE kiln_deletions SET lease_token='replacement' WHERE account_id=?")+ .bind(account)+ .run();+ },+ async retireStorage(account: string) {+ await database+ .prepare("INSERT INTO fixture_calls VALUES ('storage',?)")+ .bind(account)+ .run();+ if (+ await database.prepare("SELECT 1 FROM fixture_faults WHERE name='storage-error'").first()+ )+ throw new Error('Injected storage failure');+ return !(await database+ .prepare("SELECT 1 FROM fixture_faults WHERE name='storage-pending'")+ .first());+ },+ async revokeGrants(account: string) {+ await database.prepare("INSERT INTO fixture_calls VALUES ('grants',?)").bind(account).run();+ return !(await database+ .prepare("SELECT 1 FROM fixture_faults WHERE name='grants-pending'")+ .first());+ },+ };+ try {+ const now = Number(request.headers.get('x-fixture-now')) || Date.now();+ const jobs = new D1AccountDeletions(database, 'https://kiln.example.com', ports, () => now);+ const path = new URL(request.url).pathname;+ if (path === '/request') {+ const value = (await request.json()) as {+ proof: BrowserSession;+ identity: VerifiedIdentity;+ receipt: string;+ };+ return Response.json(await jobs.request(value.proof, value.identity, value.receipt));+ }+ if (path === '/recover') return Response.json(await jobs.recover());+ if (path === '/status')+ return Response.json(await jobs.status(request.headers.get('x-fixture-receipt')));+ return new Response('Not found', { status: 404 });+ } catch (error) {+ return serviceFailure(error);+ }+ },+};diff --git a/hosting/test/deletions.test.mjs b/hosting/test/deletions.test.mjsnew file mode 100644index 00000000..2fb4d088--- /dev/null+++ b/hosting/test/deletions.test.mjs@@ -0,0 +1,304 @@+import assert from 'node:assert/strict';+import { randomBytes } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { before, after, beforeEach, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';+import { migrateAccounts } from './database.mjs';++let runtime, database;+let now;+before(async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./deletions-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ d1Databases: ['ACCOUNTS'],+ outboundService: () => {+ throw new Error('Unexpected network');+ },+ }),+ );+ database = await runtime.getD1Database('ACCOUNTS');+ await migrateAccounts(database);+ await database.exec(+ 'CREATE TABLE fixture_calls (phase TEXT, account TEXT); CREATE TABLE fixture_faults (name TEXT PRIMARY KEY)',+ );+});+after(async () => runtime?.dispose());+beforeEach(async () => {+ now = Date.now();+ await database.exec(+ 'DELETE FROM fixture_calls; DELETE FROM fixture_faults; DELETE FROM kiln_deletions; DELETE FROM kiln_browser_sessions; DELETE FROM kiln_connections; DELETE FROM kiln_account_events; DELETE FROM kiln_identities; DELETE FROM kiln_accounts',+ );+});+const random = () => randomBytes(32).toString('hex');+const send = (path, init = {}) =>+ runtime.dispatchFetch(`https://fixture.internal${path}`, {+ ...init,+ headers: { 'x-fixture-now': String(now), ...init.headers },+ });+async function owner() {+ const accountId = `ka_${randomBytes(16).toString('hex')}`;+ const identity = { issuer: 'https://github.com', subject: random() };+ const proof = {+ binding: random(),+ accountId,+ accountEpoch: 1,+ authenticatedAt: now,+ expiresAt: now + 100_000,+ csrf: random(),+ };+ await database.batch([+ database.prepare('INSERT INTO kiln_accounts(id,created_at) VALUES (?,?)').bind(accountId, now),+ database+ .prepare('INSERT INTO kiln_identities VALUES (?,?,?,?)')+ .bind(identity.issuer, identity.subject, accountId, now),+ database+ .prepare('INSERT INTO kiln_browser_sessions VALUES (?,?,?,?,?,?,?)')+ .bind(proof.binding, accountId, 1, now, proof.expiresAt, proof.expiresAt, proof.csrf),+ ]);+ return { proof, identity, receipt: random() };+}+const begin = (value) => send('/request', { method: 'POST', body: JSON.stringify(value) });+const status = async (value) =>+ (await send('/status', { headers: { 'x-fixture-receipt': value.receipt } })).json();+const row = (value) =>+ database+ .prepare('SELECT * FROM kiln_deletions WHERE receipt_hash IS NOT NULL AND account_id=?')+ .bind(value.proof.accountId)+ .first();+const account = (value) =>+ database.prepare('SELECT * FROM kiln_accounts WHERE id=?').bind(value.proof.accountId).first();+const calls = async () => (await database.prepare('SELECT * FROM fixture_calls').all()).results;+async function recover() {+ assert.equal((await send('/recover')).status, 200);+}++test('deletion atomically revokes access and persists a private recovery receipt before external work', async () => {+ const a = await owner(),+ b = await owner();+ assert.equal((await begin(a)).status, 200);+ assert.equal((await account(a)).state, 'deleting');+ assert.equal((await account(a)).authorization_epoch, 2);+ assert.equal(+ await database+ .prepare('SELECT 1 FROM kiln_browser_sessions WHERE account_id=?')+ .bind(a.proof.accountId)+ .first(),+ null,+ );+ assert.equal((await account(b)).state, 'active');+ assert.deepEqual(await calls(), []);+ assert.equal((await status(a)).state, 'pending');+ assert.equal((await status(a)).phase, 'compute');+ assert.notEqual((await row(a)).receipt_hash, a.receipt);+ assert.equal((await begin(a)).status, 403);+ assert.equal((await send('/status', { headers: { 'x-fixture-receipt': random() } })).status, 404);+});++test('revocation and recovery intent roll back together on a storage failure', async () => {+ const a = await owner();+ await database.exec(+ "CREATE TRIGGER fail_deletion BEFORE INSERT ON kiln_deletions BEGIN SELECT RAISE(ABORT,'fixture'); END",+ );+ try {+ assert.equal((await begin(a)).status, 503);+ assert.equal((await account(a)).state, 'active');+ assert.equal((await account(a)).authorization_epoch, 1);+ assert.ok(+ await database+ .prepare('SELECT 1 FROM kiln_browser_sessions WHERE account_id=?')+ .bind(a.proof.accountId)+ .first(),+ );+ assert.equal(await row(a), null);+ } finally {+ await database.exec('DROP TRIGGER fail_deletion');+ }+});++test('only an unexpired current browser proof and its freshly verified identity may request deletion', async () => {+ const a = await owner(),+ b = await owner();+ for (const invalid of [+ { ...a, identity: b.identity },+ { ...a, proof: { ...a.proof, accountEpoch: 2 } },+ { ...a, proof: { ...a.proof, binding: b.proof.binding } },+ { ...a, receipt: 'invalid' },+ ])+ assert.equal((await begin(invalid)).status, 403);+ now += 100_001;+ assert.equal((await begin(a)).status, 403);+ assert.equal((await account(a)).state, 'active');+});++test('recovery preserves strict cleanup order, then removes identity records without reactivating the old account', async () => {+ const a = await owner(),+ b = await owner();+ await begin(a);+ await recover();+ assert.equal((await status(a)).state, 'complete');+ assert.equal(await account(a), null);+ assert.equal((await account(b)).state, 'active');+ assert.deepEqual(+ (await calls()).map(({ phase }) => phase),+ ['compute', 'storage', 'grants'],+ );+ assert((await calls()).every(({ account }) => account === a.proof.accountId));+ assert.equal(+ await database+ .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')+ .bind(a.proof.accountId)+ .first(),+ null,+ );+ const receipt = await database+ .prepare("SELECT * FROM kiln_deletions WHERE phase='complete'")+ .first();+ assert.equal(receipt.account_id, null);+ assert.equal(receipt.lease_token, null);+ await recover();+ assert.equal((await calls()).length, 3);+ now += 7 * 86400_000 + 1;+ await recover();+ assert.equal(+ (await send('/status', { headers: { 'x-fixture-receipt': a.receipt } })).status,+ 404,+ );+});++test('unconfirmed compute cleanup prevents storage removal and survives a recovery restart', async () => {+ const a = await owner();+ await begin(a);+ await database.exec("INSERT INTO fixture_faults VALUES ('compute')");+ await recover();+ assert.equal((await status(a)).phase, 'compute');+ assert.deepEqual(+ (await calls()).map(({ phase }) => phase),+ ['compute'],+ );+ assert.equal((await account(a)).state, 'deleting');+ await recover();+ assert.equal((await calls()).length, 1, 'backoff prevents immediate retry storms');+ await database.exec('DELETE FROM fixture_faults');+ now += 60_001;+ await recover();+ assert.equal((await status(a)).state, 'complete');+});++test('incomplete storage or token cleanup never clears identities or claims completion', async () => {+ for (const fault of ['storage-pending', 'storage-error', 'grants-pending']) {+ const a = await owner();+ await begin(a);+ await database.prepare('INSERT INTO fixture_faults VALUES (?)').bind(fault).run();+ await recover();+ assert.equal((await status(a)).state, 'pending');+ assert.equal((await account(a)).state, 'deleting');+ assert.ok(+ await database+ .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')+ .bind(a.proof.accountId)+ .first(),+ );+ await database.exec('DELETE FROM fixture_faults');+ now += 60_001;+ await recover();+ assert.equal((await status(a)).state, 'complete');+ }+});++test('concurrent recovery claims do not double-run a phase and expired leases are recoverable', async () => {+ const a = await owner();+ await begin(a);+ await database+ .prepare('UPDATE kiln_deletions SET lease_token=?,lease_until=?')+ .bind('crashed-worker', now + 60_000)+ .run();+ await recover();+ assert.deepEqual(await calls(), []);+ now += 60_001;+ await Promise.all([recover(), recover(), recover()]);+ assert.equal((await status(a)).state, 'complete');+ assert.deepEqual(+ (await calls()).map(({ phase }) => phase),+ ['compute', 'storage', 'grants'],+ );+});++test('a replaced recovery lease cannot advance or finalize another worker claim', async () => {+ const a = await owner();+ await begin(a);+ await database.exec("INSERT INTO fixture_faults VALUES ('lease-takeover')");+ await recover();+ assert.equal((await status(a)).phase, 'compute');+ assert.equal((await row(a)).lease_token, 'replacement');+ assert.deepEqual(+ (await calls()).map(({ phase }) => phase),+ ['compute'],+ );+ await database.exec('DELETE FROM fixture_faults');+ now += 60_001;+ await recover();+ assert.equal((await status(a)).state, 'complete');+});++test('a timed-out cleanup keeps the deletion pending and its late completion cannot advance it', async () => {+ const a = await owner();+ await begin(a);+ await database.exec("INSERT INTO fixture_faults VALUES ('held-compute')");+ // Exercise the real 20-second production deadline, not a shortened fixture.+ const started = Date.now();+ await recover();+ assert(Date.now() - started < 26_000);+ assert.equal((await status(a)).phase, 'compute');+ assert.equal((await account(a)).state, 'deleting');+ const releasedBy = Date.now() + 2000;+ while (+ !(await calls()).some(({ phase }) => phase === 'compute-returned') &&+ Date.now() < releasedBy+ )+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.deepEqual(+ (await calls()).map(({ phase }) => phase),+ ['compute', 'compute-returned'],+ );+ assert.equal((await status(a)).phase, 'compute');+ await database.exec('DELETE FROM fixture_faults');+ now += 60_001;+ await recover();+ assert.equal((await status(a)).state, 'complete');+});++test('failed final erasure rolls back identity removal and cannot claim completion', async () => {+ const a = await owner();+ await begin(a);+ await database.exec(+ "CREATE TRIGGER prevent_account_delete BEFORE DELETE ON kiln_accounts BEGIN SELECT RAISE(ABORT,'fixture'); END",+ );+ try {+ await recover();+ assert.equal((await status(a)).phase, 'identity');+ assert.equal((await status(a)).state, 'pending');+ assert.equal((await account(a)).state, 'deleting');+ assert.ok(+ await database+ .prepare('SELECT 1 FROM kiln_identities WHERE account_id=?')+ .bind(a.proof.accountId)+ .first(),+ );+ } finally {+ await database.exec('DROP TRIGGER prevent_account_delete');+ }+ now += 60_001;+ await recover();+ assert.equal((await status(a)).state, 'complete');+});diff --git a/hosting/test/deployment-config.test.mjs b/hosting/test/deployment-config.test.mjsnew file mode 100644index 00000000..0104cf60--- /dev/null+++ b/hosting/test/deployment-config.test.mjs@@ -0,0 +1,387 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';+import { resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { createHash } from 'node:crypto';+import { deploymentConfig } from '../scripts/deployment-config.mjs';++function fixture() {+ return {+ account: 'a'.repeat(32),+ prefix: 'kiln-qualification-v1',+ origin: 'https://kiln.instruktlabs.com',+ database: {+ id: '12345678-1234-4234-8234-123456789abc',+ name: 'kiln-qualification-v1-accounts',+ },+ oauthKv: 'b'.repeat(32),+ bucket: 'kiln-qualification-v1-artifacts',+ images: {+ coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,+ software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,+ },+ compute: {+ maxConcurrent: 1,+ tenantPerMinute: 9,+ tenantPerDay: 9,+ globalPerDay: 9,+ globalPerMonth: 9,+ deadlineMs: 120000,+ },+ storage: { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 },+ requestLimits: {+ edge: { namespace: '1001', perMinute: 600 },+ account: { namespace: '1002', perMinute: 120 },+ },+ };+}++test('the complete deployment has separate gateway, storage, admission and three native services', () => {+ const result = deploymentConfig(fixture());+ assert.deepEqual(Object.keys(result.workers).sort(), [+ 'admission',+ 'evaluation',+ 'gateway',+ 'render',+ 'request',+ 'tenant',+ ]);+ const { gateway, tenant, admission, request, evaluation, render } = result.workers;+ assert.deepEqual(gateway.env.ACCOUNTS, { type: 'd1', ...fixture().database });+ assert.deepEqual(gateway.env.OAUTH_KV, { type: 'kv', id: fixture().oauthKv });+ assert.deepEqual(gateway.env.OPERATIONS, {+ type: 'analytics-engine-dataset',+ name: 'kiln_qualification_v1_ops',+ });+ assert.deepEqual(result.wrangler.gateway.analytics_engine_datasets, [+ { binding: 'OPERATIONS', dataset: 'kiln_qualification_v1_ops' },+ ]);+ assert.deepEqual(gateway.env.NATIVE_COMPUTE, {+ type: 'worker',+ worker: admission.name,+ exportName: 'KilnCompute',+ });+ assert.deepEqual(gateway.env.TENANTS, {+ type: 'durable-object',+ worker: tenant.name,+ exportName: 'KilnTenant',+ });+ assert.deepEqual(admission.env.REQUESTS, {+ type: 'durable-object',+ worker: request.name,+ exportName: 'KilnNativeRequest',+ });+ assert.deepEqual(request.env.EVALUATIONS, {+ type: 'durable-object',+ worker: evaluation.name,+ exportName: 'KilnEvaluationJob',+ });+ assert.deepEqual(request.env.RENDERS, {+ type: 'durable-object',+ worker: render.name,+ exportName: 'KilnRenderJob',+ });+ assert.deepEqual(request.env.TENANTS, gateway.env.TENANTS);+ assert.deepEqual(tenant.env.ARTIFACTS, { type: 'r2', name: fixture().bucket });+ assert.deepEqual(gateway.triggers, [{ type: 'scheduled', schedule: '* * * * *' }]);+ assert.equal(gateway.env.PUBLIC_ORIGIN.value, fixture().origin);+ assert.equal(request.env.PUBLIC_ORIGIN.value, fixture().origin);+ assert.equal(admission.env.COMPUTE_GLOBAL_PER_MONTH.value, '9');+ assert.equal(tenant.env.STORAGE_MAX_BYTES.value, '67108864');+});++test('prepared alert queries require an exact dataset and account without enabling delivery', () => {+ const plan = deploymentConfig(fixture()).monitoring;+ assert.equal(plan.configured, false);+ assert.equal(plan.destination, null);+ assert.equal(plan.dataset, 'events.analyticsEngine.kiln_qualification_v1_ops');+ assert.equal(plan.alerts.length, 6);+ for (const alert of plan.alerts) {+ assert(alert.query.startsWith('SELECT COUNT(*) AS value\n'));+ assert(alert.query.includes(`FROM ${plan.dataset}\n`));+ assert(alert.query.includes(`accountTag = '${fixture().account}'`));+ assert(alert.query.includes("timestamp >= NOW() - INTERVAL '5' MINUTE"));+ assert(alert.query.includes("blob1 = 'kiln.ops.v1'"));+ assert(!alert.query.endsWith(';'));+ assert.equal(alert.executionIntervalMinutes, 1);+ assert.equal(alert.repeatIntervalMinutes, 60);+ }+ const heartbeats = plan.alerts.filter((a) => a.name.endsWith('heartbeat'));+ assert.equal(heartbeats.length, 2);+ for (const alert of heartbeats) {+ assert.equal(alert.comparison, '<');+ assert.equal(alert.threshold, 1);+ // An aggregate without GROUP BY retains a zero row for missing heartbeat.+ assert(!alert.query.includes('GROUP BY'));+ }+});++test('configuration contains secret names only and exposes no operator, native or HTTP access', () => {+ const result = deploymentConfig(fixture());+ for (const [role, worker] of Object.entries(result.workers)) {+ assert.equal(worker.workersDev, false);+ assert.equal(worker.previewUrls, false);+ assert.deepEqual(worker.domains, []);+ assert(worker.compatibilityFlags.includes('global_fetch_strictly_public'));+ assert.equal(worker.observability.logs.invocationLogs, false);+ assert.equal(worker.observability.logs.enabled, false);+ assert.equal(worker.observability.traces.enabled, false);+ if (role !== 'gateway') {+ assert.equal(worker.env.OPERATIONS, undefined);+ assert.deepEqual(worker.triggers, []);+ for (const name of Object.keys(worker.env))+ assert(!/ACCOUNTS|OAUTH|GOOGLE|GITHUB/.test(name));+ }+ for (const value of Object.values(worker.env))+ assert.notEqual(value.exportName, 'KilnComputeControl');+ }+ for (const name of [+ 'GOOGLE_CLIENT_ID',+ 'GOOGLE_CLIENT_SECRET',+ 'GITHUB_CLIENT_ID',+ 'GITHUB_CLIENT_SECRET',+ ])+ assert.deepEqual(result.workers.gateway.env[name], { type: 'secret' });+ for (const container of Object.values(result.containers)) {+ assert.equal(container.ssh.enabled, false);+ assert.equal(container.observability.logs.enabled, false);+ assert.equal(container.schedulingPolicy, 'durable-object');+ for (const image of Object.values(container.images))+ assert.match(image.reference, /@sha256:[a-f0-9]{64}$/);+ }+});++test('offline preparation builds actual role-specific bundles and migrations without overwriting evidence', async () => {+ const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));+ const directory = await mkdtemp(resolve(cache, 'deployment-config-test-'));+ assert(directory.startsWith(resolve(cache) + sep));+ try {+ const manifest = resolve(directory, 'manifest.json'),+ output = resolve(directory, 'candidate');+ await writeFile(manifest, JSON.stringify(fixture()));+ const args = [+ fileURLToPath(new URL('../scripts/prepare-deployment.mjs', import.meta.url)),+ '--manifest',+ manifest,+ '--output',+ output,+ ];+ const { stdout } = await promisify(execFile)(process.execPath, args);+ const receipt = JSON.parse(stdout);+ assert.equal(receipt.deployed, false);+ assert.equal(receipt.publicHttp, false);+ assert.equal(receipt.resourcesCreated, false);+ assert.equal(receipt.workers.length, 6);+ assert.equal(receipt.migrations.length, 9);+ assert(receipt.files.some((file) => file.path === 'monitoring-candidate.json'));+ assert.equal(new Set(receipt.files.map((file) => file.path)).size, receipt.files.length);+ for (const file of receipt.files) {+ const bytes = await readFile(resolve(output, file.path));+ assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256);+ assert.equal(bytes.length, file.bytes);+ }+ for (const role of ['gateway', 'tenant', 'admission', 'request', 'evaluation', 'render'])+ assert(receipt.files.some((file) => file.path === `${role}.wrangler.json`));+ for (const worker of receipt.workers) {+ const bytes = await readFile(resolve(output, worker.bundle));+ assert.equal(createHash('sha256').update(bytes).digest('hex'), worker.sha256);+ assert(+ worker.inputs.every(+ (input) => !/(?:^|\/)(?:test|probe)\//.test(input.replaceAll('\\', '/')),+ ),+ );+ if (worker.role !== 'gateway')+ assert(+ !worker.inputs.some((input) => /oauth|\/auth\.ts/.test(input.replaceAll('\\', '/'))),+ );+ const config = JSON.parse(await readFile(resolve(output, `${worker.role}.wrangler.json`)));+ assert.equal(resolve(output, config.main), resolve(output, worker.bundle));+ }+ for (const migration of receipt.migrations)+ assert.equal(+ createHash('sha256')+ .update(await readFile(resolve(output, 'migrations', migration.name)))+ .digest('hex'),+ migration.sha256,+ );+ assert.deepEqual(+ JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),+ receipt,+ );+ await assert.rejects(promisify(execFile)(process.execPath, args));+ assert.deepEqual(+ JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),+ receipt,+ );+ await writeFile(+ manifest,+ JSON.stringify({ ...fixture(), secret: 'unintended-sensitive-input' }),+ );+ await assert.rejects(+ promisify(execFile)(process.execPath, [...args.slice(0, -1), resolve(directory, 'invalid')]),+ (error) => !`${error.stdout}${error.stderr}`.includes('unintended-sensitive-input'),+ );+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test('Wrangler conversion keeps self bindings local and external bindings explicit', () => {+ const result = deploymentConfig(fixture());+ for (const [role, config] of Object.entries(result.wrangler)) {+ const worker = result.workers[role];+ assert.equal(config.account_id, fixture().account);+ assert.deepEqual(config.routes, []);+ assert.equal(config.workers_dev, false);+ assert.equal(config.preview_urls, false);+ for (const binding of config.durable_objects?.bindings ?? []) {+ const target = worker.env[binding.name];+ assert.equal(binding.class_name, target.exportName);+ assert.equal(binding.script_name, target.worker === worker.name ? undefined : target.worker);+ }+ for (const binding of config.services ?? []) {+ assert.equal(binding.service, worker.env[binding.binding].worker);+ assert.equal(binding.entrypoint, worker.env[binding.binding].exportName);+ }+ }+ assert.deepEqual(result.wrangler.gateway.triggers, { crons: ['* * * * *'] });+ assert.equal(result.wrangler.gateway.d1_databases[0].database_id, fixture().database.id);+ assert.equal(result.wrangler.gateway.kv_namespaces[0].id, fixture().oauthKv);+ for (const [role, image] of [+ ['request', 'coordinator'],+ ['evaluation', 'kiln'],+ ['render', 'renderer'],+ ])+ assert.equal(+ result.wrangler[role].containers[0].images[image].image,+ fixture().images[role === 'request' ? 'coordinator' : 'software'],+ );+});++test('gateway limits are explicit, isolated namespaces with one-minute windows', () => {+ const result = deploymentConfig(fixture());+ for (const [role, worker] of Object.entries(result.workers)) {+ for (const [kind, name] of [+ ['edge', 'EDGE_REQUEST_LIMIT'],+ ['account', 'ACCOUNT_REQUEST_LIMIT'],+ ]) {+ if (role !== 'gateway') {+ assert.equal(worker.env[name], undefined);+ continue;+ }+ const policy = fixture().requestLimits[kind];+ assert.deepEqual(worker.env[name], {+ type: 'rate-limit',+ namespace: policy.namespace,+ simple: { limit: policy.perMinute, period: 60 },+ });+ assert.deepEqual(+ result.wrangler.gateway.ratelimits.find((x) => x.name === name),+ {+ name,+ namespace_id: policy.namespace,+ simple: { limit: policy.perMinute, period: 60 },+ },+ );+ }+ }+ for (const mutate of [+ (x) => {+ delete x.requestLimits;+ },+ (x) => {+ x.requestLimits.account.namespace = x.requestLimits.edge.namespace;+ },+ (x) => {+ x.requestLimits.edge.namespace = '0';+ },+ (x) => {+ x.requestLimits.edge.namespace = '1\n';+ },+ (x) => {+ x.requestLimits.edge.namespace = '01';+ },+ (x) => {+ x.requestLimits.edge.namespace = '9007199254740992';+ },+ (x) => {+ x.requestLimits.edge.perMinute = 0;+ },+ (x) => {+ x.requestLimits.edge.perMinute = 1.1;+ },+ (x) => {+ x.requestLimits.edge.perMinute = Infinity;+ },+ (x) => {+ x.requestLimits.edge.period = 10;+ },+ ]) {+ const manifest = fixture();+ mutate(manifest);+ assert.throws(() => deploymentConfig(manifest), /Invalid deployment manifest/);+ }+});++test('unknown fields, secret values, unbounded policies and mutable or foreign images are rejected', () => {+ for (const mutate of [+ (x) => {+ x.secret = 'must-not-be-serialized';+ },+ (x) => {+ x.routes = ['*'];+ },+ (x) => {+ x.compute.unlimited = true;+ },+ (x) => {+ x.database.secret = 'must-not-be-serialized';+ },+ (x) => {+ x.origin += '/';+ },+ (x) => {+ x.origin = 'http://kiln.instruktlabs.com';+ },+ (x) => {+ x.prefix = '../foreign';+ },+ (x) => {+ x.bucket = 'unrelated-assets';+ },+ (x) => {+ x.database.id = '';+ },+ (x) => {+ x.oauthKv = '';+ },+ (x) => {+ x.compute.maxConcurrent = 17;+ },+ (x) => {+ x.compute.deadlineMs = 120001;+ },+ (x) => {+ x.compute.globalPerMonth = Infinity;+ },+ (x) => {+ x.compute.tenantPerDay = 0;+ },+ (x) => {+ x.storage.maxBytes = -1;+ },+ (x) => {+ x.images.coordinator = `${x.images.coordinator.split('@')[0]}:latest`;+ },+ (x) => {+ x.images.software = x.images.software.replace(x.account, '0'.repeat(32));+ },+ ]) {+ const input = fixture();+ mutate(input);+ assert.throws(() => deploymentConfig(input), /Invalid deployment/);+ }+});diff --git a/hosting/test/edge-mcp.test.mjs b/hosting/test/edge-mcp.test.mjsnew file mode 100644index 00000000..9b2c2b98--- /dev/null+++ b/hosting/test/edge-mcp.test.mjs@@ -0,0 +1,193 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { generateEdgeManifest } from '../scripts/edge-manifest.mjs';+import { createKilnToolHost } from '../../dist/mcp-engine.mjs';+import { createPublicTools, hostedInstructions } from '../src/public-tools.ts';++let runtime, manifest;+before(async () => {+ manifest = JSON.parse(+ await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),+ );+ const bundle = await build({+ stdin: {+ contents: `+ import {routeEdgeMcp} from './src/edge-mcp';+ export default {async fetch(request){const routed=await routeEdgeMcp(request);return routed instanceof Response?routed:new Response('compute',{status:599});}};+ `,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ metafile: true,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ assert.equal(+ Object.keys(bundle.metafile?.inputs ?? {}).some((p) => p.includes('mcp-engine')),+ false,+ );+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ outboundService: async () => {+ throw Error('No network');+ },+ }),+ );+});+after(async () => runtime?.dispose());+const meta = {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': { name: 'edge-fixture', version: '1' },+ 'io.modelcontextprotocol/clientCapabilities': {},+};+function request(method, params = {}, modern = true, headers = {}) {+ return runtime.dispatchFetch('https://tenant.internal/mcp', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': modern ? '2026-07-28' : '2025-11-25',+ ...(modern+ ? { 'mcp-method': method, ...(params.name ? { 'mcp-name': params.name } : {}) }+ : {}),+ ...headers,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method,+ params: { ...params, ...(modern ? { _meta: meta } : {}) },+ }),+ });+}+async function message(response) {+ const body = await response.text();+ return response.headers.get('content-type')?.includes('text/event-stream')+ ? body+ .split('\n')+ .filter((l) => l.startsWith('data:'))+ .map((l) => JSON.parse(l.slice(5)))+ .findLast((x) => x.id !== undefined)+ : JSON.parse(body);+}+test('committed metadata is regenerated from the actual native engine protocol', async () => {+ assert.deepEqual(manifest, await generateEdgeManifest());+ assert.equal(manifest.tools.length, 15);+});+test('modern metadata and legacy initialization expose the derived hosted contract without compute', async () => {+ for (const [method, key] of [+ ['tools/list', 'tools'],+ ['resources/list', 'resources'],+ ['resources/templates/list', 'resourceTemplates'],+ ]) {+ const r = await request(method);+ assert.equal(r.status, 200);+ assert.deepEqual(+ (await message(r)).result[key],+ key === 'tools' ? createPublicTools(manifest.tools).tools : manifest[key],+ );+ }+ const discover = await message(await request('server/discover'));+ assert.deepEqual(+ discover.result._meta['io.modelcontextprotocol/serverInfo'],+ manifest.serverInfo,+ );+ const legacy = await request(+ 'initialize',+ {+ protocolVersion: '2025-11-25',+ capabilities: {},+ clientInfo: { name: 'legacy', version: '1' },+ },+ false,+ );+ assert.equal(legacy.status, 200);+ const result = (await message(legacy)).result;+ assert.deepEqual(result.serverInfo, manifest.serverInfo);+ assert.deepEqual(result.capabilities, manifest.capabilities);+ assert.equal(result.instructions, hostedInstructions);+});+test('helper discovery uses the engine service and preserves exact compact results and errors', async () => {+ const native = createKilnToolHost();+ for (const args of [+ {},+ { query: 'wheel spokes' },+ { ids: ['createPart'] },+ { ids: ['shape:capture'] },+ { query: 1 },+ ]) {+ const r = await request('tools/call', { name: 'kiln_discover', arguments: args });+ assert.equal(r.status, 200);+ const actual = (await message(r)).result;+ const expected = await native.callTool('kiln_discover', args, {+ signal: new AbortController().signal,+ });+ assert.deepEqual(actual.content, expected.content);+ assert.equal(actual.isError, expected.isError);+ }+});++test('hosted discovery rejects local-only aliases and hostile keys without echoing private paths', async () => {+ for (const args of [+ { category: 'prop' },+ { 'C:/Users/private/input': true },+ { capabilities: true },+ ]) {+ const result = await message(+ await request('tools/call', { name: 'kiln_discover', arguments: args }),+ );+ assert.equal(result.error.code, -32602);+ assert.doesNotMatch(JSON.stringify(result), /C:\/Users|private\/input/);+ }+});+test('source operations, private resource reads and live host capabilities still require the admitted native path', async () => {+ assert.equal(+ (+ await request('tools/call', {+ name: 'kiln_render',+ arguments: { code: 'function build(){}' },+ })+ ).status,+ 599,+ );+ assert.equal((await request('resources/read', { uri: 'kiln://assets/private' })).status, 599);+ assert.equal(+ (await request('tools/call', { name: 'kiln_capabilities', arguments: {} })).status,+ 599,+ );+});+test('invalid and unknown protocol messages cannot start compute, including forged routing headers', async () => {+ assert.equal((await request('tools/call', { name: 'not_a_tool', arguments: {} })).status, 200);+ const r = await request('tools/list', {}, true, {+ 'mcp-method': 'tools/call',+ 'mcp-name': 'kiln_render',+ });+ assert.notEqual(r.status, 599);+ for (const body of [+ '{',+ '[]',+ JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'kiln_render' } }),+ ]) {+ const invalid = await runtime.dispatchFetch('https://tenant.internal/mcp', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body,+ });+ assert.notEqual(invalid.status, 599);+ }+ assert.equal((await runtime.dispatchFetch('https://tenant.internal/mcp')).status, 405);+});diff --git a/hosting/test/evaluation-request.test.mjs b/hosting/test/evaluation-request.test.mjsnew file mode 100644index 00000000..6f340bec--- /dev/null+++ b/hosting/test/evaluation-request.test.mjs@@ -0,0 +1,214 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';++let handleEvaluationRequest, handleRenderRequest;+before(async () => {+ const output = new URL('../../.cache/hosted-evaluation-request/handler.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/evaluation-request.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ handleEvaluationRequest, handleRenderRequest } = await import(output));+});++function request(options = {}) {+ return new Request(options.url ?? 'http://kiln-evaluator.internal/evaluate', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'content-length': '2',+ 'x-kiln-deadline-ms': '30000',+ 'x-kiln-max-response-bytes': '4096',+ ...options.headers,+ },+ body: options.body ?? '{}',+ duplex: 'half',+ signal: options.signal,+ });+}++test('private rendering admits its own bounds but denies evaluation routes and caller authority', async () => {+ const url = 'http://kiln-renderer.internal/render';+ let calls = 0;+ const job = {+ run: async (bytes, controls) => {+ calls++;+ assert.equal(controls.maxResponseBytes, 20 * 1024 * 1024);+ return bytes;+ },+ };+ const valid = await handleRenderRequest(+ request({ url, headers: { 'x-kiln-max-response-bytes': String(20 * 1024 * 1024) } }),+ job,+ );+ assert.equal(valid.status, 200);+ assert.equal(await valid.text(), '{}');+ for (const options of [+ { url: 'http://kiln-evaluator.internal/evaluate' },+ { headers: { 'x-kiln-deadline-ms': '30001' } },+ { headers: { 'content-length': String(6 * 1024 * 1024 + 1) } },+ { headers: { 'x-kiln-max-response-bytes': String(20 * 1024 * 1024 + 1) } },+ { headers: { 'x-image': 'other' } },+ { headers: { authorization: 'Bearer PRIVATE' } },+ ]) {+ const result = await handleRenderRequest(request({ url, ...options }), job);+ assert(result.status >= 400);+ }+ assert.equal(calls, 1);+});++test('private evaluator forwards only bounded bytes and controls and waits for the job to settle', async () => {+ let entered, finish;+ const started = new Promise((resolve) => {+ entered = resolve;+ });+ const done = new Promise((resolve) => {+ finish = resolve;+ });+ let returned = false;+ const pending = handleEvaluationRequest(request(), {+ executionImage: () => `registry.cloudflare.com/fixture/kiln@sha256:${'a'.repeat(64)}`,+ async run(bytes, controls) {+ assert.equal(new TextDecoder().decode(bytes), '{}');+ assert.ok(controls.deadlineMs > 0 && controls.deadlineMs <= 30000);+ assert.equal(controls.maxResponseBytes, 4096);+ assert.deepEqual(Object.keys(controls).sort(), ['deadlineMs', 'maxResponseBytes', 'signal']);+ entered();+ await done;+ return new TextEncoder().encode('{"opaque":"engine validates this"}');+ },+ }).then((value) => {+ returned = true;+ return value;+ });+ await started;+ assert.equal(returned, false);+ finish();+ const result = await pending;+ assert.equal(result.status, 200);+ assert.equal(result.headers.get('cache-control'), 'no-store');+ assert.equal(result.headers.get('content-type'), 'application/json');+ assert.equal(result.headers.get('x-kiln-execution-image'), `sha256:${'a'.repeat(64)}`);+ const bytes = await result.arrayBuffer();+ assert.equal(Number(result.headers.get('content-length')), bytes.byteLength);+});++test('evaluator output cannot claim its own image identity or omit the host proof', async () => {+ for (const identity of [undefined, 'mutable:latest', `sha256:${'a'.repeat(64)}`]) {+ const result = await handleEvaluationRequest(request(), {+ run: async () => new TextEncoder().encode('{"image":"forged","ok":true}'),+ executionImage: () => identity,+ });+ assert.equal(result.status, 503);+ assert.equal(result.headers.get('x-kiln-execution-image'), null);+ }+ const forged = await handleEvaluationRequest(+ request({ headers: { 'x-kiln-execution-image': `sha256:${'a'.repeat(64)}` } }),+ { run: async () => assert.fail('caller identity must be rejected before execution') },+ );+ assert.equal(forged.status, 400);+});++test('private evaluator rejects authority, route and malformed limits before starting compute', async () => {+ let calls = 0;+ const job = {+ run: async () => {+ calls++;+ throw new Error('must not execute');+ },+ };+ for (const options of [+ { url: 'https://kiln-evaluator.internal/evaluate' },+ { url: 'http://kiln-evaluator.internal/evaluate?tenant=other' },+ { url: 'http://kiln-evaluator.internal/evaluate#fragment' },+ { url: 'http://kiln-evaluator.internal/other' },+ { headers: { authorization: 'Bearer PRIVATE' } },+ { headers: { cookie: 'PRIVATE' } },+ { headers: { 'x-tenant': 'other' } },+ { headers: { 'x-kiln-deadline-ms': '60001' } },+ { headers: { 'x-kiln-deadline-ms': '0' } },+ { headers: { 'x-kiln-deadline-ms': 'NaN' } },+ { headers: { 'x-kiln-max-response-bytes': '8388609' } },+ { headers: { 'content-length': '4194305' } },+ { headers: { 'content-length': '1' } },+ { headers: { 'content-type': 'text/plain' } },+ { body: 'x'.repeat(4 * 1024 * 1024 + 1) },+ { signal: AbortSignal.abort('PRIVATE') },+ ]) {+ const result = await handleEvaluationRequest(request(options), job);+ assert.ok(result.status >= 400, JSON.stringify(options));+ assert.doesNotMatch(await result.text(), /PRIVATE|other/);+ }+ assert.equal(calls, 0);+});++test('private evaluator propagates cancellation without reporting an unconfirmed cleanup as success', async () => {+ const abort = new AbortController();+ let entered, finish;+ const started = new Promise((resolve) => {+ entered = resolve;+ });+ const done = new Promise((resolve) => {+ finish = resolve;+ });+ let executionSignal,+ returned = false;+ const pending = handleEvaluationRequest(request({ signal: abort.signal }), {+ async run(_bytes, controls) {+ executionSignal = controls.signal;+ entered();+ await done;+ throw new Error('PRIVATE_CLEANUP_FAILURE');+ },+ }).then((value) => {+ returned = true;+ return value;+ });+ await started;+ abort.abort('PRIVATE_REASON');+ assert.equal(executionSignal.aborted, true);+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(returned, false);+ finish();+ const response = await pending;+ assert.equal(response.status, 503);+ assert.doesNotMatch(await response.text(), /PRIVATE/);+});++test('private evaluator rechecks output bounds and returns fixed errors for bad job output', async () => {+ for (const output of [new Uint8Array(), new Uint8Array(4097), 'PRIVATE', null]) {+ const response = await handleEvaluationRequest(request(), { run: async () => output });+ assert.equal(response.status, 503);+ assert.doesNotMatch(await response.text(), /PRIVATE/);+ }+});++test('reading a stalled request consumes the evaluation deadline without starting compute', async () => {+ let cancelled = false;+ let calls = 0;+ const body = new ReadableStream({+ cancel() {+ cancelled = true;+ },+ });+ const result = await handleEvaluationRequest(+ request({+ headers: { 'x-kiln-deadline-ms': '25' },+ body,+ }),+ {+ run: async () => {+ calls++;+ return new Uint8Array([1]);+ },+ },+ );+ assert.equal(result.status, 504);+ assert.equal(cancelled, true);+ assert.equal(calls, 0);+});diff --git a/hosting/test/gateway-preflight-worker.ts b/hosting/test/gateway-preflight-worker.tsnew file mode 100644index 00000000..690fa228--- /dev/null+++ b/hosting/test/gateway-preflight-worker.ts@@ -0,0 +1,10 @@+import { DurableObject } from 'cloudflare:workers';+import { runGatewayPreflight, type PreflightEnv } from '../probe/gateway-preflight';++export class PreflightFixture extends DurableObject<PreflightEnv> {+ async run() {+ return JSON.stringify(await runGatewayPreflight(this.ctx.storage, this.env));+ }+}++export default { fetch: () => new Response('Not found', { status: 404 }) };diff --git a/hosting/test/gateway-preflight.test.mjs b/hosting/test/gateway-preflight.test.mjsnew file mode 100644index 00000000..b042a91f--- /dev/null+++ b/hosting/test/gateway-preflight.test.mjs@@ -0,0 +1,308 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { deploymentConfig } from '../scripts/deployment-config.mjs';+import { migrateAccounts } from './database.mjs';++const origin = 'https://kiln-private-qualification.invalid';+const manifest = {+ account: 'a'.repeat(32),+ prefix: 'kiln-preflight-fixture',+ origin,+ database: { id: '11111111-1111-1111-1111-111111111111', name: 'kiln-preflight-fixture-accounts' },+ oauthKv: 'b'.repeat(32),+ bucket: 'kiln-preflight-fixture-artifacts',+ requestLimits: {+ edge: { namespace: '8101', perMinute: 600 },+ account: { namespace: '8102', perMinute: 120 },+ },+ images: {+ coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,+ software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,+ },+ compute: {+ maxConcurrent: 1,+ tenantPerMinute: 9,+ tenantPerDay: 9,+ globalPerDay: 9,+ globalPerMonth: 9,+ deadlineMs: 120000,+ },+ storage: { maxBytes: 1048576, maxObjects: 32, maxGroups: 8 },+};+const configuration = deploymentConfig(manifest);+const bundles = {};+before(async () => {+ for (const [role, entry] of [+ ...Object.entries(configuration.entries),+ ['probe', '../test/gateway-preflight-worker'],+ ]) {+ const result = await build({+ entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ bundles[role] = result.outputFiles[0].text;+ }+});++// Adapt the prepared production topology, not a hand-maintained copy of its links.+// Miniflare does not qualify remote Analytics Engine, Cron or Container images.+function worker(role) {+ const config = configuration.workers[role];+ const result = {+ name: config.name,+ modules: true,+ script: bundles[role],+ compatibilityDate: config.compatibilityDate,+ compatibilityFlags: config.compatibilityFlags,+ bindings: {},+ durableObjects: {},+ serviceBindings: {},+ kvNamespaces: {},+ d1Databases: {},+ r2Buckets: {},+ ratelimits: {},+ outboundService: () => {+ throw new Error('Network forbidden in private fixture');+ },+ };+ for (const [name, binding] of Object.entries(config.env)) {+ switch (binding.type) {+ case 'text':+ result.bindings[name] = binding.value;+ break;+ case 'durable-object':+ result.durableObjects[name] = {+ className: binding.exportName,+ scriptName: binding.worker,+ useSQLite: true,+ };+ break;+ case 'worker':+ result.serviceBindings[name] = { name: binding.worker, entrypoint: binding.exportName };+ break;+ case 'd1':+ result.d1Databases[name] = binding.id;+ break;+ case 'kv':+ result.kvNamespaces[name] = binding.id;+ break;+ case 'r2':+ result.r2Buckets[name] = binding.name;+ break;+ case 'rate-limit':+ result.ratelimits[name] = { namespace_id: binding.namespace, simple: binding.simple };+ break;+ case 'secret':+ case 'analytics-engine-dataset':+ break;+ default:+ assert.fail(`Unhandled binding type: ${binding.type}`);+ }+ }+ // Build Output declares namespace ownership through exports/migrations.+ // Miniflare v4 adaptation declares it through a local binding instead.+ for (const [name, exported] of Object.entries(config.exports))+ if (exported.type === 'durable-object')+ result.durableObjects[`REGISTER_${name}`] = { className: name, useSQLite: true };+ return result;+}+async function fixture(override = {}, fault) {+ const names = Object.fromEntries(+ Object.entries(configuration.workers).map(([role, config]) => [role, config.name]),+ );+ const runtime = new Miniflare(+ convertV4MiniflareOptions({+ workers: [+ {+ name: 'probe',+ modules: true,+ script: bundles.probe,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['global_fetch_strictly_public'],+ durableObjects: {+ RUN: { className: 'PreflightFixture', useSQLite: true },+ TENANTS: { className: 'KilnTenant', scriptName: names.tenant, useSQLite: true },+ },+ serviceBindings: {+ GATEWAY: names.gateway,+ COMPUTE: { name: names.admission, entrypoint: 'KilnCompute' },+ CONTROL: { name: names.admission, entrypoint: 'KilnComputeControl' },+ },+ d1Databases: { ACCOUNTS: manifest.database.id },+ kvNamespaces: { OAUTH_KV: manifest.oauthKv },+ r2Buckets: { ARTIFACTS: manifest.bucket },+ bindings: {+ PUBLIC_ORIGIN: origin,+ QUALIFICATION_MODE: 'isolated-synthetic-v1',+ ...override,+ },+ outboundService: () => {+ throw new Error('External identity providers must not be called');+ },+ },+ ...Object.keys(configuration.entries).map((role) => {+ const value = worker(role);+ if (fault === 'gateway-database' && role === 'gateway')+ value.d1Databases.ACCOUNTS = '22222222-2222-2222-2222-222222222222';+ return value;+ }),+ ],+ }),+ );+ try {+ const database = await runtime.getD1Database('ACCOUNTS', 'probe');+ await migrateAccounts(database);+ const namespace = await runtime.getDurableObjectNamespace('RUN', 'probe');+ const stub = namespace.get(namespace.idFromName('once'));+ return { runtime, database, run: { run: async () => JSON.parse(await stub.run()) } };+ } catch (error) {+ await runtime.dispose();+ throw error;+ }+}++test('private preflight uses real gateway, account authorities, tenant storage and compute control', async () => {+ const f = await fixture();+ try {+ assert.equal((await f.runtime.dispatchFetch('https://probe.invalid')).status, 404);+ const first = await Promise.all([f.run.run(), f.run.run()]);+ const receipt = first.find((value) => value.state === 'finished');+ assert(receipt);+ assert.equal(receipt.state, 'finished');+ assert.equal(receipt.passed, true, JSON.stringify(receipt));+ assert.equal(receipt.computePaused, true);+ assert.deepEqual(+ receipt.results.map(({ name, passed }) => [name, passed]),+ [+ ['fresh-resources', true],+ ['pause-native', true],+ ['metadata', true],+ ['synthetic-accounts', true],+ ['anonymous-denied', true],+ ['edge-discovery', true],+ ['oversized-denied', true],+ ['store-fixture', true],+ ['bearer-isolation', true],+ ['browser-isolation', true],+ ['revoke-connection', true],+ ['revoked-token-denied', true],+ ['other-account-preserved', true],+ ],+ );+ assert.doesNotMatch(+ JSON.stringify(receipt),+ /access_token|refresh_token|cookie|ka_[a-f0-9]|Bearer |source\.kiln|fixture-source/,+ );+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 2,+ );+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first()).n,+ 2,+ );+ assert.equal(+ (+ await f.database+ .prepare("SELECT COUNT(*) AS n FROM kiln_connections WHERE state='revoked'")+ .first()+ ).n,+ 1,+ );+ const before = await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first();+ assert.deepEqual(await f.run.run(), receipt);+ assert.deepEqual(+ await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first(),+ before,+ );+ } finally {+ await f.runtime.dispose();+ }+});++test('a gateway bound to the wrong account database fails at token exchange and never retries provisioning', async () => {+ const f = await fixture({}, 'gateway-database');+ try {+ const first = await f.run.run();+ assert.equal(first.passed, false);+ assert.equal(first.computePaused, true);+ assert.deepEqual(first.results.at(-1), { name: 'synthetic-accounts', passed: false });+ assert.equal(first.results.length, 4);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 1,+ );+ assert.deepEqual(await f.run.run(), first);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 1,+ );+ assert.doesNotMatch(JSON.stringify(first), /token|cookie|ka_[a-f0-9]|SQL|D1_ERROR|Bearer /);+ } finally {+ await f.runtime.dispose();+ }+});++for (const seeded of ['accounts', 'oauth', 'artifacts'])+ test(`preflight refuses nonempty ${seeded} instead of altering existing data`, async () => {+ const f = await fixture();+ try {+ if (seeded === 'accounts')+ await f.database+ .prepare('INSERT INTO kiln_accounts(id,created_at) VALUES (?,0)')+ .bind(`ka_${'f'.repeat(32)}`)+ .run();+ if (seeded === 'oauth')+ await (await f.runtime.getKVNamespace('OAUTH_KV', 'probe')).put(+ 'existing',+ 'do-not-change',+ );+ if (seeded === 'artifacts')+ await (await f.runtime.getR2Bucket('ARTIFACTS', 'probe')).put('existing', 'do-not-change');+ const result = await f.run.run();+ assert.equal(result.passed, false);+ assert.equal(result.results.length, 1);+ assert.equal(result.results[0].name, 'fresh-resources');+ assert.equal(result.results[0].passed, false);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ seeded === 'accounts' ? 1 : 0,+ );+ if (seeded === 'oauth')+ assert.equal(+ await (await f.runtime.getKVNamespace('OAUTH_KV', 'probe')).get('existing'),+ 'do-not-change',+ );+ if (seeded === 'artifacts')+ assert.equal(+ await (await (await f.runtime.getR2Bucket('ARTIFACTS', 'probe')).get('existing')).text(),+ 'do-not-change',+ );+ assert.deepEqual(await f.run.run(), result);+ } finally {+ await f.runtime.dispose();+ }+ });++test('preflight refuses a production origin before accessing account storage', async () => {+ const f = await fixture({ PUBLIC_ORIGIN: 'https://kiln.instruktlabs.com' });+ try {+ const result = await f.run.run();+ assert.equal(result.passed, false);+ assert.equal(result.results.length, 0);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 0,+ );+ } finally {+ await f.runtime.dispose();+ }+});diff --git a/hosting/test/gateway.test.mjs b/hosting/test/gateway.test.mjsnew file mode 100644index 00000000..d215b70b--- /dev/null+++ b/hosting/test/gateway.test.mjs@@ -0,0 +1,234 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { rateLimitBindings } from './rate-limit-bindings.mjs';++let runtime;+const origin = 'https://kiln.example.com',+ user = `ka_${'1'.repeat(32)}`;+const nativeBody = JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'kiln_validate', arguments: { code: 'function build(){}' } },+});+before(async () => {+ const bundle = await build({+ stdin: {+ contents: `+ import {forwardTenant} from './src/gateway';+ import {serviceFailure} from './src/http';+ export default {async fetch(request,bindings){+ const result=async(target,tenant,incoming)=>Response.json({target,tenant,path:new URL(incoming.url).pathname,headers:Object.fromEntries(incoming.headers),body:await incoming.text()});+ const env={ACCOUNT_REQUEST_LIMIT:bindings.ACCOUNT_REQUEST_LIMIT,TENANTS:{getByName:tenant=>({fetch:incoming=>result('storage',tenant,incoming)})}};+ if(!request.headers.has('x-fixture-no-compute'))env.NATIVE_COMPUTE={dispatch:(tenant,incoming)=>result('compute',tenant,incoming)};+ try{return await forwardTenant(request,env,{auth:{userId:'${user}',scope:['kiln:use']}},'${origin}');}catch(e){return serviceFailure(e);}+ }};`,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['global_fetch_strictly_public'],+ ratelimits: rateLimitBindings,+ }),+ );+});+after(async () => runtime?.dispose());++test('authenticated MCP routes only to admission using a trusted account hash and stripped credentials', async () => {+ const response = await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: 'Bearer fixture-secret',+ cookie: 'fixture=secret',+ 'x-tenant': 'other',+ 'mcp-protocol-version': '2025-11-25',+ },+ body: nativeBody,+ });+ assert.equal(response.status, 200);+ const body = await response.json();+ assert.equal(body.target, 'compute');+ assert.equal(body.path, '/mcp');+ assert.equal(body.body, nativeBody);+ assert.equal(+ body.tenant,+ createHash('sha256')+ .update(JSON.stringify(['kiln-tenant-v1', origin, user]))+ .digest('base64url'),+ );+ assert.equal(body.headers.authorization, undefined);+ assert.equal(body.headers.cookie, undefined);+ assert.equal(body.headers['x-tenant'], undefined);+ assert.equal(body.headers['mcp-protocol-version'], '2025-11-25');+});++test('missing compute binding fails closed while artifact downloads remain available without compute admission', async () => {+ const headers = { 'x-fixture-no-compute': '1' };+ assert.equal(+ (+ await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: { ...headers, 'content-type': 'application/json' },+ body: nativeBody,+ })+ ).status,+ 503,+ );+ const download = await runtime.dispatchFetch(`${origin}/mcp/artifacts/${'a'.repeat(32)}`, {+ headers,+ });+ assert.equal(download.status, 200);+ assert.equal((await download.json()).target, 'storage');+});++test('authenticated discovery and malformed messages never call storage or require native admission', async () => {+ for (const [method, params] of [+ ['tools/list', {}],+ ['tools/call', { name: 'kiln_discover', arguments: { query: 'wheel' } }],+ ]) {+ const response = await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: {+ 'x-fixture-no-compute': '1',+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ });+ assert.equal(response.status, 200);+ assert.equal(response.headers.get('cache-control'), 'no-store');+ const text = await response.text();+ assert.ok(!text.includes('"target":"compute"'));+ assert.ok(!text.includes('"target":"storage"'));+ assert.ok(text.includes(method === 'tools/list' ? '"tools":' : '"content":'));+ }+ const malformed = await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },+ body: '{',+ });+ assert.equal(malformed.status, 400);+ assert.equal((await runtime.dispatchFetch(`${origin}/mcp`)).status, 405);+});++async function publicTool(name, args = {}, extraHeaders = {}) {+ return runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2025-11-25',+ ...extraHeaders,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 7,+ method: 'tools/call',+ params: { name, arguments: args },+ }),+ });+}++test('public operations reach only their fixed engine action after credential stripping', async () => {+ for (const [name, args, engine, fixed] of [+ [+ 'kiln_material_create_procedural',+ { draft: { name: 'fixture' } },+ 'kiln_material',+ { action: 'create-procedural' },+ ],+ ['kiln_material_get', { materialId: 'stone' }, 'kiln_material', { action: 'get' }],+ ['kiln_assets_restore', { assetId: 'box' }, 'kiln_assets', { action: 'restore' }],+ ['kiln_renderer_status', {}, 'kiln_renderer', { action: 'status' }],+ ['kiln_capabilities', {}, 'kiln_discover', { capabilities: true }],+ ]) {+ const response = await publicTool(name, args, { authorization: 'Bearer fixture-secret' });+ assert.equal(response.status, 200);+ const forwarded = await response.json();+ assert.equal(forwarded.target, 'compute', name);+ assert.equal(forwarded.headers.authorization, undefined);+ assert.deepEqual(JSON.parse(forwarded.body), {+ jsonrpc: '2.0',+ id: 7,+ method: 'tools/call',+ params: { name: engine, arguments: { ...args, ...fixed } },+ });+ }+});++test('hidden selectors, unrelated fields and routing header mismatches never admit a native job', async () => {+ for (const [name, args, headers] of [+ ['kiln_material', { action: 'get', materialId: 'stone' }],+ ['kiln_assets', { action: 'restore', assetId: 'box' }],+ ['kiln_material_get', { materialId: 'stone', action: 'import' }],+ ['kiln_material_get', { materialId: 'stone', payload: {} }],+ ['kiln_capabilities', { query: 'wheel' }],+ ['kiln_discover', { capabilities: true }],+ [+ 'kiln_renderer_status',+ {},+ { 'mcp-method': 'tools/call', 'mcp-name': 'kiln_renderer_reprobe' },+ ],+ ['kiln_renderer_status', {}, { 'mcp-method': 'tools/list' }],+ ]) {+ const response = await publicTool(name, args, headers);+ const text = await response.text();+ assert.ok(!text.includes('"target":"compute"'), `${name}: ${text}`);+ assert.ok(text.includes('"error":') || text.includes('"isError":true'), text);+ }+});++test('modern operation translation preserves request metadata and rewrites matched routing headers', async () => {+ const name = 'kiln_material_get';+ const metadata = {+ 'io.modelcontextprotocol/protocolVersion': '2026-07-28',+ 'io.modelcontextprotocol/clientInfo': { name: 'public-tools-fixture', version: '1' },+ 'io.modelcontextprotocol/clientCapabilities': {},+ };+ for (const headerName of [name, `=?base64?${Buffer.from(name).toString('base64')}?=`]) {+ const response = await runtime.dispatchFetch(`${origin}/mcp`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ 'mcp-protocol-version': '2026-07-28',+ 'mcp-method': 'tools/call',+ 'mcp-name': headerName,+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'modern-7',+ method: 'tools/call',+ params: {+ name,+ arguments: { materialId: 'stone' },+ _meta: metadata,+ },+ }),+ });+ const forwarded = await response.json();+ assert.equal(forwarded.target, 'compute');+ assert.equal(forwarded.headers['mcp-name'], 'kiln_material');+ assert.equal(forwarded.headers['mcp-method'], 'tools/call');+ const message = JSON.parse(forwarded.body);+ assert.equal(message.id, 'modern-7');+ assert.deepEqual(message.params._meta, metadata);+ assert.deepEqual(message.params.arguments, { materialId: 'stone', action: 'get' });+ }+});diff --git a/hosting/test/http.test.mjs b/hosting/test/http.test.mjsnew file mode 100644index 00000000..1bfcb32b--- /dev/null+++ b/hosting/test/http.test.mjs@@ -0,0 +1,71 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';++let readBounded;+let boundedRequest;+before(async () => {+ const output = new URL('../../.cache/hosted-http-test/http.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/http.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ readBounded, boundedRequest } = await import(output));+});++test('public body admission honors an already cancelled incoming request', async () => {+ const controller = new AbortController();+ controller.abort(new Error('private cancellation reason'));+ const request = new Request('https://kiln.example.com/mcp', {+ method: 'POST',+ body: '{}',+ signal: controller.signal,+ });+ await assert.rejects(+ boundedRequest(request, 32),+ (error) => error.status === 499 && error.message === 'Request cancelled',+ );+});++test('public body reads enforce elapsed time even while chunks keep timers queued', async (t) => {+ let now = 1000;+ t.mock.method(Date, 'now', () => now);+ let pulls = 0;+ let cancelled = false;+ const body = new ReadableStream({+ pull(controller) {+ now += 6000;+ if (++pulls === 100) controller.close();+ else controller.enqueue(new Uint8Array());+ },+ cancel() {+ cancelled = true;+ },+ });+ await assert.rejects(+ readBounded(body, 32),+ (error) => error.status === 408 && error.message === 'Request timed out',+ );+ assert.ok(pulls < 100);+ assert.equal(cancelled, true);+});++test('bounded bodies retain bytes when a stream reuses its read buffer', async () => {+ const shared = new Uint8Array(1);+ let value = 0;+ const body = new ReadableStream(+ {+ pull(controller) {+ if (++value === 4) return controller.close();+ shared[0] = value;+ controller.enqueue(shared);+ },+ },+ { highWaterMark: 0 },+ );+ assert.deepEqual(await readBounded(body, 32), new Uint8Array([1, 2, 3]));+});diff --git a/hosting/test/integrated-probe.test.mjs b/hosting/test/integrated-probe.test.mjsnew file mode 100644index 00000000..1653d74a--- /dev/null+++ b/hosting/test/integrated-probe.test.mjs@@ -0,0 +1,441 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';+import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { resolve, sep } from 'node:path';++let IntegratedBudget, runIntegratedOnce, integratedSource, integratedCases;+before(async () => {+ for (const name of ['integrated-budget', 'integrated-run']) {+ const output = new URL(`../../.cache/integrated-test/${name}.mjs`, import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL(`../probe/${name}.ts`, import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ const value = await import(output);+ if (name === 'integrated-budget') ({ IntegratedBudget } = value);+ else ({ runIntegratedOnce, integratedSource, integratedCases } = value);+ }+});+function storage() {+ const values = new Map();+ let tail = Promise.resolve();+ const api = {+ get: async (k) => structuredClone(values.get(k)),+ put: async (k, v) => {+ values.set(k, structuredClone(v));+ },+ transaction(fn) {+ const p = tail.then(() => fn(api));+ tail = p.catch(() => {});+ return p;+ },+ };+ return api;+}+test('the trial budget never reopens and bounds every kind across retries and reconstruction', async () => {+ const store = storage(),+ budget = new IntegratedBudget(store);+ await assert.rejects(budget.claim('coordinator', 'a'.repeat(64)));+ await budget.open();+ await assert.rejects(budget.open());+ for (const [kind, max] of [+ ['coordinator', 9],+ ['evaluation', 4],+ ['render', 4],+ ]) {+ for (let i = 0; i < max; i++) await budget.claim(kind, i.toString(16).padStart(64, '0'));+ await assert.rejects(budget.claim(kind, 'f'.repeat(64)));+ await assert.rejects(budget.claim(kind, '0'.repeat(64)));+ }+ assert.equal((await budget.status()).claims.length, 17);+ await budget.close();+ await assert.rejects(new IntegratedBudget(store).open());+ await assert.rejects(new IntegratedBudget(store).claim('render', 'e'.repeat(64)));+});+function fixture(failAt) {+ const calls = [],+ evidence = [];+ let paused = false,+ opened = 0,+ closed = 0;+ const ref = `p_${'a'.repeat(64)}`,+ asset = { assetId: 'fixture', revisionId: 'v1' };+ const text = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }] });+ const ports = {+ open: async () => {+ opened++;+ },+ close: async () => {+ closed++;+ },+ pause: async () => {+ paused = true;+ },+ status: async () => ({ activeRequests: 0, pendingCleanup: 0, paused, maxConcurrent: 1 }),+ retain: async (name, bytes) => {+ evidence.push({ name, bytes });+ },+ async dispatch(owner, request) {+ const input = await request.json();+ calls.push({ owner, input });+ const index = calls.length;+ if (index === 10) return new Response('quota', { status: 429 });+ if (index === failAt) return new Response('private failure', { status: 503 });+ let result;+ if (index === 1)+ result = {+ ...text({+ ok: true,+ programRef: ref,+ viewFidelity: { delivered: 'full-material', degraded: false },+ }),+ content: [+ ...text({+ ok: true,+ programRef: ref,+ viewFidelity: { delivered: 'full-material', degraded: false },+ }).content,+ { type: 'image', data: 'cG5n', mimeType: 'image/png' },+ ],+ };+ if (index === 2) result = text({ ok: true, asset });+ if (index === 3) result = text({ ok: true, programRef: ref, asset });+ if (index === 4) result = text({ programRef: ref, code: integratedSource, nextOffset: null });+ if (index === 5) result = text({ ok: true, asset });+ if (index === 6)+ result = {+ contents: [+ { blob: Buffer.from('glTFfixture').toString('base64'), mimeType: 'model/gltf-binary' },+ ],+ };+ if (index === 7)+ result = {+ contents: [+ {+ text: JSON.stringify({+ assetId: 'fixture',+ revisionId: 'v1',+ preview: { fidelity: { delivered: 'full-material', degraded: false } },+ build: { engine: 'fixture-identity' },+ }),+ },+ ],+ };+ if (index === 8) result = { isError: true, content: [{ type: 'text', text: 'not found' }] };+ if (index === 9)+ return Response.json({+ jsonrpc: '2.0',+ id: input.id,+ error: { code: -32603, message: 'not found' },+ });+ return Response.json({ jsonrpc: '2.0', id: input.id, result });+ },+ };+ return {+ ports,+ calls,+ evidence,+ get opened() {+ return opened;+ },+ get closed() {+ return closed;+ },+ get paused() {+ return paused;+ },+ };+}+test('the fixed trial checks fresh-request lifecycle, tenant denial and quota rejection exactly once', async () => {+ const s = storage(),+ f = fixture();+ const first = await runIntegratedOnce(s, f.ports);+ assert.equal(first.passed, true);+ assert.equal(first.results.length, 10);+ assert.equal(f.calls.length, 10);+ assert.equal(f.opened, 1);+ assert.equal(f.closed, 1);+ assert.equal(f.paused, true);+ assert.equal(f.evidence.length, 10);+ assert.deepEqual(+ first.results.map((r) => r.name),+ integratedCases,+ );+ assert.notEqual(f.calls[0].owner, f.calls[7].owner);+ assert.deepEqual(await runIntegratedOnce(s, f.ports), first);+ assert.equal(f.calls.length, 10);+});+test('a failed case stops further requests and still closes the budget and pauses admission', async () => {+ const f = fixture(3),+ result = await runIntegratedOnce(storage(), f.ports);+ assert.equal(result.passed, false);+ assert.equal(f.calls.length, 3);+ assert.equal(f.closed, 1);+ assert.equal(f.paused, true);+ assert(!JSON.stringify(result).includes('private failure'));+});+test('unconfirmed final cleanup cannot produce a passing trial', async () => {+ const f = fixture();+ f.ports.status = async () => ({+ activeRequests: f.paused ? 1 : 0,+ pendingCleanup: f.paused ? 1 : 0,+ paused: f.paused,+ maxConcurrent: 1,+ });+ const result = await runIntegratedOnce(storage(), f.ports);+ assert.equal(result.passed, false);+ assert.equal(result.cleanupConfirmed, false);+});++async function workerFixture() {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('../probe/integrated-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ return new Miniflare({+ ...convertV4MiniflareOptions({+ workers: [+ {+ name: 'private-integration',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports', 'enable_request_signal'],+ durableObjects: Object.fromEntries(+ Object.entries({+ RUN: 'KilnIntegratedRun',+ BUDGET: 'KilnIntegratedBudget',+ ADMISSION: 'KilnAdmission',+ TENANTS: 'KilnTenant',+ REQUESTS: 'IntegratedRequestJob',+ EVALUATIONS: 'IntegratedEvaluationJob',+ RENDERS: 'IntegratedRenderJob',+ }).map(([binding, className]) => [binding, { className, useSQLite: true }]),+ ),+ bindings: {+ PUBLIC_ORIGIN: 'https://kiln.instruktlabs.com',+ STORAGE_MAX_BYTES: '67108864',+ STORAGE_MAX_OBJECTS: '256',+ STORAGE_MAX_GROUPS: '64',+ COMPUTE_MAX_CONCURRENT: '1',+ COMPUTE_TENANT_PER_MINUTE: '9',+ COMPUTE_TENANT_PER_DAY: '9',+ COMPUTE_GLOBAL_PER_DAY: '9',+ COMPUTE_GLOBAL_PER_MONTH: '9',+ COMPUTE_DEADLINE_MS: '120000',+ },+ r2Buckets: ['ARTIFACTS'],+ outboundService: async () => {+ throw new Error('No external network in local trial fixture');+ },+ },+ {+ name: 'operator',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: {+ PROBE: { name: 'private-integration', entrypoint: 'KilnIntegratedControl' },+ },+ durableObjects: {+ REQUESTS: {+ className: 'IntegratedRequestJob',+ scriptName: 'private-integration',+ useSQLite: true,+ },+ },+ script: `export default {async fetch(request,env){+ switch(new URL(request.url).pathname) {+ case '/closed-budget-request': {+ let cancelled=false, denied=false;+ let stopped;+ const cancellation=new Promise(resolve=>{stopped=resolve;});+ const body=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('{}'));},cancel(){cancelled=true;stopped();}});+ const input=new Request('https://tenant.internal/mcp',{method:'POST',body});+ try{await env.REQUESTS.getByName('denied-budget').run('a'.repeat(43),input,Date.now()+60000);}catch{denied=true;}+ let timer;try{await Promise.race([cancellation,new Promise(resolve=>{timer=setTimeout(resolve,1000);})]);}finally{clearTimeout(timer);}+ return Response.json({cancelled,denied});+ }+ case '/status': return Response.json(await env.PROBE.status());+ case '/stop': return Response.json(await env.PROBE.stop());+ case '/run': return Response.json(await env.PROBE.runFixed());+ default: return env.PROBE.fetch(request);+ }+ }};`,+ },+ ],+ }),+ unsafeInspectDurableObjects: true,+ });+}++test('actual private RPC, admission and budget stop at a missing container and persist across eviction', async () => {+ const runtime = await workerFixture();+ try {+ const operator = await runtime.getWorker('operator');+ const rpc = async (path) => (await operator.fetch(`https://operator.invalid/${path}`)).json();+ assert.equal((await runtime.dispatchFetch('https://probe.invalid/run')).status, 404);+ assert.equal((await operator.fetch('https://operator.invalid/arbitrary')).status, 404);+ const first = await rpc('run');+ assert.equal(first.state, 'finished');+ assert.equal(first.passed, false);+ assert.equal(first.cleanupConfirmed, true);+ assert.equal(first.results.length, 1);+ assert.equal(first.results[0].name, 'render');+ assert.equal(first.results[0].status, 503);+ const status = await rpc('status');+ assert.deepEqual(status.admission, {+ paused: true,+ activeRequests: 0,+ pendingCleanup: 0,+ maxConcurrent: 1,+ });+ assert.equal(status.budget.state, 'closed');+ assert.equal(status.budget.claims.length, 1);+ assert.equal(status.budget.claims[0].kind, 'coordinator');+ const bucket = await runtime.getR2Bucket('ARTIFACTS', 'private-integration');+ assert.deepEqual(+ (await bucket.list()).objects.map((o) => o.key),+ ['probe-evidence/render.json'],+ );+ for (const [binding, className, name] of [+ ['RUN', 'KilnIntegratedRun', 'integrated-v1'],+ ['BUDGET', 'KilnIntegratedBudget', 'integrated-v1'],+ ['ADMISSION', 'KilnAdmission', 'global-v1'],+ ]) {+ const ns = await runtime.getDurableObjectNamespace(binding, 'private-integration');+ await runtime.unsafeEvictDurableObject('private-integration', className, {+ id: ns.idFromName(name).toString(),+ });+ }+ assert.deepEqual(await rpc('run'), first);+ assert.deepEqual(await rpc('stop'), status);+ } finally {+ await runtime.dispose();+ }+});++test('operator stop before the trial permanently closes its allowance without admitting a job', async () => {+ const runtime = await workerFixture();+ try {+ const operator = await runtime.getWorker('operator');+ const rpc = async (path) => (await operator.fetch(`https://operator.invalid/${path}`)).json();+ await rpc('stop');+ const result = await rpc('run');+ assert.equal(result.state, 'finished');+ assert.equal(result.passed, false);+ assert.equal(result.cleanupConfirmed, true);+ assert.deepEqual(result.results, []);+ const status = await rpc('status');+ assert.deepEqual(status.budget, { state: 'closed', claims: [] });+ assert.equal(status.admission.activeRequests, 0);+ assert.deepEqual(await rpc('closed-budget-request'), { cancelled: true, denied: true });+ assert.deepEqual((await rpc('status')).budget, status.budget);+ assert.deepEqual(await rpc('run'), result);+ } finally {+ await runtime.dispose();+ }+});++test('the prepared deployment keeps all execution private and pins bounded immutable images', async () => {+ const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));+ const directory = await mkdtemp(resolve(cache, 'integrated-config-test-'));+ assert(directory.startsWith(resolve(cache) + sep));+ try {+ // Metadata fixture only: this does not install, authenticate or invoke cf.+ const metadata = resolve(directory, 'cf-package.json');+ await writeFile(metadata, JSON.stringify({ name: 'cf', version: '1.0.0-beta.12' }));+ const { stdout } = await promisify(execFile)(process.execPath, [+ fileURLToPath(new URL('../scripts/build-integrated-probe.mjs', import.meta.url)),+ '--account',+ '0'.repeat(32),+ '--output',+ directory,+ '--cf-package',+ metadata,+ ]);+ const receipt = JSON.parse(stdout);+ assert.equal(receipt.deployed, false);+ assert.deepEqual(receipt.maxVmStarts, { coordinator: 9, evaluation: 4, render: 4, total: 17 });+ const output = resolve(directory, '.cloudflare/output/v0');+ const worker = JSON.parse(+ await readFile(resolve(output, 'workers/default/worker.config.json')),+ );+ assert.equal(worker.workersDev, false);+ assert.equal(worker.previewUrls, false);+ assert.deepEqual(worker.domains, []);+ assert.deepEqual(worker.triggers, []);+ assert.equal(worker.env.ARTIFACTS.name, 'kiln-private-integrated-v1-evidence');+ assert.equal(worker.env.COMPUTE_MAX_CONCURRENT.value, '1');+ assert.equal(worker.env.COMPUTE_GLOBAL_PER_MONTH.value, '9');+ assert.equal(worker.env.COMPUTE_DEADLINE_MS.value, '120000');+ const wrangler = JSON.parse(await readFile(resolve(directory, 'wrangler.json')));+ assert.equal(wrangler.workers_dev, false);+ assert.equal(wrangler.preview_urls, false);+ assert.deepEqual(wrangler.routes, []);+ assert.equal(wrangler.account_id, '0'.repeat(32));+ assert.equal(+ resolve(directory, wrangler.main),+ resolve(output, 'workers/default/bundle/worker.mjs'),+ );+ assert.deepEqual(wrangler.exports, worker.exports);+ assert.equal(wrangler.durable_objects.bindings.length, 7);+ for (const binding of wrangler.durable_objects.bindings) {+ assert.equal(Object.hasOwn(binding, 'script_name'), false);+ assert.equal(binding.class_name, worker.env[binding.name].exportName);+ }+ assert.deepEqual(wrangler.limits, { cpu_ms: 30000, subrequests: 500 });+ for (const [key, binding] of Object.entries(worker.env))+ if (binding.type === 'text') assert.equal(wrangler.vars[key], binding.value);+ assert.deepEqual(wrangler.r2_buckets, [+ { binding: 'ARTIFACTS', bucket_name: worker.env.ARTIFACTS.name },+ ]);+ assert.equal(+ Object.values(worker.exports).filter((e) => e.type === 'durable-object').length,+ 7,+ );+ for (const [kind, key] of [+ ['coordinator', 'coordinator'],+ ['evaluation', 'kiln'],+ ['render', 'renderer'],+ ]) {+ const container = JSON.parse(+ await readFile(+ resolve(output, `containers/kiln-private-integrated-v1-${kind}/container.config.json`),+ ),+ );+ assert.equal(container.schedulingPolicy, 'durable-object');+ assert.equal(container.ssh.enabled, false);+ assert.equal(container.observability.logs.enabled, false);+ assert.deepEqual(Object.keys(container.images), [key]);+ assert.equal(+ container.images[key].reference,+ kind === 'coordinator' ? receipt.coordinator : receipt.software,+ );+ assert.match(container.images[key].reference, /@sha256:[a-f0-9]{64}$/);+ const deployed = wrangler.containers.find((item) => item.name === container.name);+ assert.equal(deployed.scheduling_policy, 'durable_object');+ assert.equal(deployed.ssh.enabled, false);+ assert.equal(deployed.observability.logs.enabled, false);+ assert.deepEqual(deployed.images, { [key]: { image: container.images[key].reference } });+ }+ assert(+ !receipt.inputs.some((input) =>+ /oauth|\/src\/(?:auth|github|google|browser-|account-)/.test(input.replaceAll('\\', '/')),+ ),+ );+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});diff --git a/hosting/test/lifecycle-config.test.mjs b/hosting/test/lifecycle-config.test.mjsnew file mode 100644index 00000000..440f27a5--- /dev/null+++ b/hosting/test/lifecycle-config.test.mjs@@ -0,0 +1,143 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { mkdtemp, readFile, writeFile, rm, realpath } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { fileURLToPath } from 'node:url';+import { resolve, sep } from 'node:path';+import { lifecycleConfig } from '../probe/lifecycle-config.mjs';+import { deploymentConfig } from '../scripts/deployment-config.mjs';+import { assertLifecycleBoundary } from '../probe/lifecycle-build-boundary.mjs';+import { lifecycleManifest } from './lifecycle-fixture.mjs';++test('private bundles reject unexpected helpers and identity code in native roles', () => {+ for (const role of ['request', 'evaluation', 'render']) {+ assert.throws(() =>+ assertLifecycleBoundary(role, [+ `hosting/probe/lifecycle-${role}-worker.ts`,+ 'hosting/probe/qualification-accounts.ts',+ ]),+ );+ assert.throws(() => assertLifecycleBoundary(role, ['hosting/src/google.ts']));+ }+ for (const path of [+ 'hosting/test/fixture.ts',+ 'hosting/probe/unreviewed-helper.mjs',+ 'hosting/probe/nested/helper.ts',+ ])+ assert.throws(() => assertLifecycleBoundary('operator', [path]));+});++test('offline private lifecycle preparation hashes eight isolated bundles and refuses overwrite', async () => {+ const cache = await realpath(fileURLToPath(new URL('../../.cache/', import.meta.url)));+ const directory = await mkdtemp(resolve(cache, 'lifecycle-candidate-test-'));+ assert((await realpath(directory)).startsWith(cache + sep));+ try {+ const manifest = resolve(directory, 'manifest.json'),+ output = resolve(directory, 'candidate');+ await writeFile(manifest, JSON.stringify(lifecycleManifest));+ const args = [+ fileURLToPath(new URL('../scripts/prepare-deployment.mjs', import.meta.url)),+ '--private-lifecycle',+ '--manifest',+ manifest,+ '--output',+ output,+ ];+ const { stdout } = await promisify(execFile)(process.execPath, args);+ const receipt = JSON.parse(stdout);+ assert.equal(receipt.mode, 'private-lifecycle');+ assert.equal(receipt.workers.length, 8);+ assert.equal(receipt.migrations.length, 9);+ assert.deepEqual(receipt.requiredGatewaySecrets, []);+ assert.equal(receipt.deployed, false);+ assert.equal(receipt.publicHttp, false);+ for (const file of receipt.files) {+ const bytes = await readFile(resolve(output, file.path));+ assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256);+ }+ for (const worker of receipt.workers) {+ const inputs = worker.inputs.join('\n');+ if (worker.role !== 'operator')+ assert.doesNotMatch(inputs, /qualification-accounts|gateway-preflight|lifecycle-run/);+ if (['request', 'evaluation', 'render'].includes(worker.role))+ assert.doesNotMatch(inputs, /oauth|\/auth\.ts/);+ }+ await assert.rejects(promisify(execFile)(process.execPath, args));+ assert.deepEqual(+ JSON.parse(await readFile(resolve(output, 'deployment-receipt.json'))),+ receipt,+ );+ } finally {+ assert((await realpath(directory)).startsWith(cache + sep));+ await rm(directory, { recursive: true });+ }+});+test('private lifecycle configuration preserves production boundaries and binds only native wrappers to its allowance', () => {+ const c = lifecycleConfig(lifecycleManifest),+ base = deploymentConfig(lifecycleManifest);+ assert.equal(Object.keys(c.workers).length, 8);+ for (const role of ['tenant', 'admission']) assert.deepEqual(c.workers[role], base.workers[role]);+ for (const role of ['request', 'evaluation', 'render']) {+ const copy = structuredClone(c.workers[role]);+ assert.equal(copy.env.BUDGET.worker, c.workers.allowance.name);+ assert.equal(copy.env.BUDGET.exportName, 'KilnLifecycleBudget');+ delete copy.env.BUDGET;+ assert.deepEqual(copy, base.workers[role]);+ assert.equal(c.entries[role], `../probe/lifecycle-${role}-worker`);+ assert(!c.workers[role].env.ACCOUNTS);+ }+ assert.equal(c.workers.operator.env.GATEWAY.worker, c.workers.gateway.name);+ assert.equal(c.workers.operator.env.EXPECTED_IMAGE.value, `sha256:${'d'.repeat(64)}`);+ assert.deepEqual(c.workers.operator.env.ACCOUNTS, c.workers.gateway.env.ACCOUNTS);+ assert.deepEqual(c.workers.operator.env.ARTIFACTS, c.workers.tenant.env.ARTIFACTS);+ for (const [role, w] of Object.entries(c.workers)) {+ assert.equal(w.workersDev, false);+ assert.equal(w.previewUrls, false);+ assert.deepEqual(w.domains, []);+ assert.deepEqual(w.triggers, []);+ assert.equal(w.observability.enabled, false);+ assert(!Object.values(w.env).some((binding) => binding.type === 'secret'));+ assert.deepEqual(c.wrangler[role].routes, []);+ }+ assert.deepEqual(c.containers, base.containers);+});+test('private lifecycle configuration refuses production targets and altered execution allowances', () => {+ for (const edit of [+ (m) => {+ m.origin = 'https://kiln.instruktlabs.com';+ },+ (m) => {+ m.prefix = 'kiln-production';+ },+ (m) => {+ m.compute.globalPerDay = 15;+ },+ (m) => {+ m.compute.deadlineMs = 60000;+ },+ (m) => {+ m.storage.maxBytes *= 2;+ },+ (m) => {+ m.requestLimits.edge.perMinute = 601;+ },+ ]) {+ const m = structuredClone(lifecycleManifest);+ edit(m);+ assert.throws(() => lifecycleConfig(m));+ }+});++test('private deployment orders every cross-worker dependency before its caller', () => {+ const c = lifecycleConfig(lifecycleManifest);+ const positions = new Map(c.deployOrder.map((role, index) => [c.workers[role].name, index]));+ for (const worker of Object.values(c.workers))+ for (const binding of Object.values(worker.env))+ if (binding.worker && binding.worker !== worker.name)+ assert(+ positions.get(binding.worker) < positions.get(worker.name),+ `${worker.name} -> ${binding.worker}`,+ );+});diff --git a/hosting/test/lifecycle-fixture.mjs b/hosting/test/lifecycle-fixture.mjsnew file mode 100644index 00000000..6b4dcd3a--- /dev/null+++ b/hosting/test/lifecycle-fixture.mjs@@ -0,0 +1,28 @@+export const lifecycleManifest = {+ account: 'a'.repeat(32),+ prefix: 'kiln-private-lifecycle-v1',+ origin: 'https://kiln-private-qualification.invalid',+ database: {+ id: '11111111-1111-1111-1111-111111111111',+ name: 'kiln-private-lifecycle-v1-accounts',+ },+ oauthKv: 'b'.repeat(32),+ bucket: 'kiln-private-lifecycle-v1-artifacts',+ requestLimits: {+ edge: { namespace: '8201', perMinute: 600 },+ account: { namespace: '8202', perMinute: 120 },+ },+ images: {+ coordinator: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-coordinator@sha256:${'c'.repeat(64)}`,+ software: `registry.cloudflare.com/${'a'.repeat(32)}/kiln-software@sha256:${'d'.repeat(64)}`,+ },+ compute: {+ maxConcurrent: 1,+ tenantPerMinute: 14,+ tenantPerDay: 14,+ globalPerDay: 14,+ globalPerMonth: 14,+ deadlineMs: 120000,+ },+ storage: { maxBytes: 67108864, maxObjects: 256, maxGroups: 64 },+};diff --git a/hosting/test/lifecycle-observer.test.mjs b/hosting/test/lifecycle-observer.test.mjsnew file mode 100644index 00000000..8934b4d8--- /dev/null+++ b/hosting/test/lifecycle-observer.test.mjs@@ -0,0 +1,185 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { readFile } from 'node:fs/promises';++let observer;+before(async () => {+ const output = new URL('../../.cache/lifecycle-observer-test/observer.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/lifecycle-observer.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ observer = (await import(output)).default;+});+const options = { method: 'POST', headers: { 'X-Kiln-Operator': 'private-lifecycle-v1' } };+const invoke = (path, env, init = options) =>+ observer.fetch(new Request(`http://127.0.0.1:8798/${path}`, init), env);++test('observer config stays loopback-only with exactly the fixed private control binding', async () => {+ const config = JSON.parse(+ await readFile(new URL('../probe/lifecycle-observer.wrangler.jsonc', import.meta.url), 'utf8'),+ );+ assert.deepEqual(config.dev, { ip: '127.0.0.1', port: 8798, local_protocol: 'http' });+ assert.equal(config.workers_dev, false);+ assert.equal(config.preview_urls, false);+ assert.deepEqual(config.routes, []);+ assert.deepEqual(config.observability, { enabled: false });+ assert.deepEqual(config.services, [+ {+ binding: 'PROBE',+ service: 'kiln-private-lifecycle-v1-operator',+ entrypoint: 'KilnLifecycleControl',+ remote: true,+ },+ ]);+});++test('loopback observer refuses browser traffic and arbitrary controls without calling RPC', async () => {+ const env = {+ PROBE: new Proxy(+ {},+ {+ get() {+ assert.fail('Unexpected control call');+ },+ },+ ),+ };+ for (const [url, init] of [+ ['http://127.0.0.1:8798/run-fixed', {}],+ ['http://127.0.0.1:8798/run-fixed', { method: 'POST' }],+ ['http://127.0.0.1:8798/run-fixed', { method: 'OPTIONS' }],+ ['http://attacker.invalid:8798/run-fixed', options],+ ['http://127.0.0.1:8799/run-fixed', options],+ ['http://127.0.0.1:8798/run-fixed?restart=1', options],+ ['http://127.0.0.1:8798/arbitrary', options],+ ...['Origin', 'Sec-Fetch-Site'].map((name) => [+ 'http://127.0.0.1:8798/run-fixed',+ { ...options, headers: { ...options.headers, [name]: 'https://attacker.invalid' } },+ ]),+ ])+ assert.equal((await observer.fetch(new Request(url, init), env)).status, 404);+});++test('observer forwards only fixed controls, releases RPC capabilities and sends private JSON', async () => {+ const calls = [],+ disposed = [];+ const env = {+ PROBE: Object.fromEntries(+ ['runFixed', 'status', 'stop'].map((action) => [+ action,+ (...args) => {+ assert.deepEqual(args, []);+ calls.push(action);+ const result = { state: 'finished', passed: true };+ Object.defineProperty(result, Symbol.dispose, {+ value: () => disposed.push(`${action}-result`),+ });+ const work = Promise.resolve(result);+ work[Symbol.dispose] = () => disposed.push(`${action}-promise`);+ return work;+ },+ ]),+ ),+ };+ for (const [path, action] of [+ ['run-fixed', 'runFixed'],+ ['status', 'status'],+ ['stop', 'stop'],+ ]) {+ const response = await invoke(path, env);+ assert.equal(response.status, 200);+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal(response.headers.has('access-control-allow-origin'), false);+ assert.deepEqual(await response.json(), { state: 'finished', passed: true });+ assert.deepEqual(disposed.slice(-2), [`${action}-result`, `${action}-promise`]);+ }+ assert.deepEqual(calls, ['runFixed', 'status', 'stop']);+});++test('observer failures redact RPC errors and never issue another operation', async () => {+ let calls = 0,+ disposed = 0;+ const env = {+ PROBE: {+ runFixed() {+ calls++;+ const work = Promise.reject(new Error('PRIVATE_CREDENTIAL_OR_DOWNLOAD'));+ work[Symbol.dispose] = () => disposed++;+ return work;+ },+ },+ };+ const response = await invoke('run-fixed', env);+ assert.equal(response.status, 502);+ assert.doesNotMatch(await response.text(), /PRIVATE_CREDENTIAL_OR_DOWNLOAD/);+ assert.equal(calls, 1);+ assert.equal(disposed, 1);+});++test('observer cancels uploaded input, passes no arguments and refuses oversized receipts', async () => {+ let cancelled = false,+ disposed = 0;+ const body = new ReadableStream({+ cancel() {+ cancelled = true;+ },+ });+ const result = { unused: 'x'.repeat(128 * 1024) };+ Object.defineProperty(result, Symbol.dispose, { value: () => disposed++ });+ const response = await invoke(+ 'status',+ {+ PROBE: {+ status(...args) {+ assert.deepEqual(args, []);+ return Promise.resolve(result);+ },+ },+ },+ { ...options, body, duplex: 'half' },+ );+ assert.equal(cancelled, true);+ assert.equal(disposed, 1);+ assert.equal(response.status, 502);+ assert((await response.text()).length < 256);+});++test('observation deadlines release capabilities and discard late results without retry', async (t) => {+ t.mock.timers.enable({ apis: ['setTimeout'] });+ for (const [action, path, deadline] of [+ ['status', 'status', 10000],+ ['runFixed', 'run-fixed', 960000],+ ]) {+ let resolve,+ calls = 0,+ disposed = 0;+ const work = new Promise((done) => {+ resolve = done;+ });+ work[Symbol.dispose] = () => disposed++;+ const pending = invoke(path, {+ PROBE: {+ [action]() {+ calls++;+ return work;+ },+ },+ });+ t.mock.timers.tick(deadline);+ const response = await pending;+ assert.equal(response.status, 502);+ assert.equal(disposed, 1);+ const result = { state: 'finished' };+ Object.defineProperty(result, Symbol.dispose, { value: () => disposed++ });+ resolve(result);+ await new Promise((done) => setImmediate(done));+ assert.equal(disposed, 2);+ assert.equal(calls, 1);+ }+});diff --git a/hosting/test/lifecycle-probe.test.mjs b/hosting/test/lifecycle-probe.test.mjsnew file mode 100644index 00000000..8490032d--- /dev/null+++ b/hosting/test/lifecycle-probe.test.mjs@@ -0,0 +1,147 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';++let LifecycleBudget, lifecycleBudget, runLifecycleOnce;+before(async () => {+ for (const name of ['lifecycle-budget', 'lifecycle-run']) {+ const output = new URL(`../../.cache/lifecycle-tests/${name}.mjs`, import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL(`../probe/${name}.ts`, import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ const value = await import(output);+ if (name === 'lifecycle-budget') ({ LifecycleBudget, lifecycleBudget } = value);+ else ({ runLifecycleOnce } = value);+ }+});+function storage() {+ const values = new Map();+ let tail = Promise.resolve();+ const api = {+ get: async (key) => structuredClone(values.get(key)),+ put: async (key, value) => {+ values.set(key, structuredClone(value));+ },+ transaction(fn) {+ const next = tail.then(() => fn(api));+ tail = next.catch(() => {});+ return next;+ },+ };+ return api;+}+test('native lifecycle allowance cannot refund or reopen and bounds concurrent claims', async () => {+ const store = storage(),+ budget = new LifecycleBudget(store);+ await assert.rejects(budget.claim('coordinator', 'a'.repeat(64)));+ await budget.open();+ await assert.rejects(budget.open());+ for (const [kind, maximum] of Object.entries(lifecycleBudget)) {+ const results = await Promise.allSettled(+ Array.from({ length: maximum + 3 }, (_, i) =>+ budget.claim(kind, i.toString(16).padStart(64, '0')),+ ),+ );+ assert.equal(results.filter((result) => result.status === 'fulfilled').length, maximum);+ await assert.rejects(budget.claim(kind, '0'.repeat(64)));+ }+ assert.equal((await budget.status()).claims.length, 22);+ await budget.close();+ const reconstructed = new LifecycleBudget(store);+ await assert.rejects(reconstructed.open());+ await assert.rejects(reconstructed.claim('render', 'f'.repeat(64)));+});+test('closed or malformed native lifecycle allowances fail without allocating a claim', async () => {+ const stopped = new LifecycleBudget(storage());+ await stopped.close();+ await assert.rejects(stopped.open());+ const budget = new LifecycleBudget(storage());+ await budget.open();+ for (const kind of ['other', '__proto__', 'constructor'])+ await assert.rejects(budget.claim(kind, 'a'.repeat(64)));+ for (const id of ['', 'x'.repeat(64), `${'a'.repeat(64)}\n`])+ await assert.rejects(budget.claim('render', id));+ assert.equal((await budget.status()).claims.length, 0);+});+test('an interrupted native lifecycle record does not reopen or resume', async () => {+ const store = storage();+ const previous = { state: 'running', passed: false, results: [] };+ await store.put('native-lifecycle', previous);+ assert.deepEqual(+ await runLifecycleOnce(+ store,+ new Proxy(+ {},+ {+ get() {+ throw new Error('INTERRUPTED_RUN_TOUCHED_PORT');+ },+ },+ ),+ ),+ previous,+ );+});+function fixture() {+ let paused = true,+ calls = 0,+ retained = 0,+ closed = 0;+ const ports = {+ expectedImage: `sha256:${'b'.repeat(64)}`,+ open: async () => {+ paused = false;+ },+ close: async () => {+ closed++;+ },+ pause: async () => {+ paused = true;+ },+ status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0 }),+ mcp: async () => {+ calls++;+ return new Response(new Uint8Array(8 * 1024 * 1024 + 1));+ },+ retain: async () => {+ retained++;+ },+ };+ return { ports, counts: () => ({ paused, calls, retained, closed }) };+}+test('native lifecycle stops before retaining an oversized response and seals admission', async () => {+ const f = fixture(),+ result = await runLifecycleOnce(storage(), f.ports);+ assert.equal(result.passed, false);+ assert.equal(result.admissionIdleAndPaused, true);+ assert.equal(result.results.length, 1);+ assert.deepEqual(f.counts(), { paused: true, calls: 1, retained: 0, closed: 1 });+});+// Exercise the production ten-second evidence deadline, not an injected shorter timeout.+test('a stalled evidence write cannot resume a failed lifecycle after its deadline', {+ timeout: 20000,+}, async () => {+ const f = fixture(),+ store = storage();+ let finish;+ f.ports.mcp = async () => new Response('{}');+ f.ports.retain = () =>+ new Promise((resolve) => {+ finish = resolve;+ });+ const started = Date.now();+ const result = await runLifecycleOnce(store, f.ports);+ assert(Date.now() - started >= 9500);+ assert.equal(result.passed, false);+ assert.equal(result.admissionIdleAndPaused, true);+ assert.equal(result.results.length, 1);+ assert.equal(f.counts().closed, 1);+ finish();+ await Promise.resolve();+ assert.deepEqual(await store.get('native-lifecycle'), result);+});diff --git a/hosting/test/lifecycle-readback.test.mjs b/hosting/test/lifecycle-readback.test.mjsnew file mode 100644index 00000000..52d88524--- /dev/null+++ b/hosting/test/lifecycle-readback.test.mjs@@ -0,0 +1,472 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { createHash } from 'node:crypto';+import { lifecycleConfig } from '../probe/lifecycle-config.mjs';+import { lifecycleManifest } from './lifecycle-fixture.mjs';+import { verifyLifecycleDeployment, planLifecycleCleanup } from '../probe/lifecycle-readback.mjs';++const hash = (value) => createHash('sha256').update(value).digest('hex');+const id = (value) => hash(value).slice(0, 32);+function fixture() {+ const manifest = structuredClone(lifecycleManifest),+ config = lifecycleConfig(manifest);+ const namespaces = Object.values(config.workers).flatMap((w) =>+ Object.entries(w.exports)+ .filter(([, e]) => e.type === 'durable-object')+ .map(([name]) => ({+ id: id(w.name + name),+ script: w.name,+ class: name,+ use_sqlite: true,+ })),+ );+ const ns = (worker, name) => namespaces.find((n) => n.script === worker && n.class === name);+ const bindings = (w) =>+ Object.entries(w.env).map(([name, b]) => {+ switch (b.type) {+ case 'text':+ return { name, type: 'plain_text', text: b.value };+ case 'worker':+ return {+ name,+ type: 'service',+ service: b.worker,+ ...(b.exportName ? { entrypoint: b.exportName } : {}),+ };+ case 'durable-object':+ return {+ name,+ type: 'durable_object_namespace',+ namespace_id: ns(b.worker, b.exportName).id,+ class_name: b.exportName,+ };+ case 'd1':+ return { name, type: 'd1', id: b.id };+ case 'kv':+ return { name, type: 'kv_namespace', namespace_id: b.id };+ case 'r2':+ return { name, type: 'r2_bucket', bucket_name: b.name };+ case 'rate-limit':+ return { name, type: 'ratelimit', namespace_id: b.namespace, simple: b.simple };+ case 'analytics-engine-dataset':+ return { name, type: 'analytics_engine', dataset: b.name };+ default:+ throw new Error('Unexpected fixture binding');+ }+ });+ const workers = Object.fromEntries(+ Object.entries(config.workers).map(([role, w]) => {+ const bytes = Buffer.from(`fixture ${role}`),+ versionId = id(`${role}version`);+ return [+ role,+ {+ worker: {+ id: id(w.name),+ name: w.name,+ subdomain: { enabled: false, previews_enabled: false },+ observability: config.wrangler[role].observability,+ logpush: false,+ tail_consumers: [],+ references: { domains: [], queues: [], dispatch_namespace_outbounds: [] },+ },+ scriptSettings: {+ logpush: false,+ tail_consumers: [],+ observability: structuredClone(config.wrangler[role].observability),+ },+ version: {+ id: versionId,+ main_module: 'worker.mjs',+ modules: [{ name: 'worker.mjs', content_base64: bytes.toString('base64') }],+ bindings: bindings(w),+ exports: w.exports,+ urls: [],+ compatibility_date: w.compatibilityDate,+ compatibility_flags: w.compatibilityFlags,+ limits: config.wrangler[role].limits,+ containers: Object.values(config.containers)+ .filter((c) => Object.values(w.exports).some((e) => e.container === c.name))+ .map((c) => ({+ name: c.name,+ class_name: Object.entries(w.exports).find(([, e]) => e.container === c.name)[0],+ images: Object.fromEntries(+ Object.entries(c.images).map(([k, v]) => [k, v.reference]),+ ),+ })),+ },+ deployments: {+ deployments: [+ {+ id: id(`${role}deployment`),+ versions: [{ version_id: versionId, percentage: 100 }],+ },+ ],+ },+ routes: [],+ schedules: [],+ },+ ];+ }),+ );+ const applications = Object.entries(config.containers).map(([role, c]) => ({+ id: id(c.name),+ account_id: manifest.account,+ name: c.name,+ scheduling_policy: 'durable_object',+ durable_objects: {+ namespace_id: ns(config.workers[role].name, Object.keys(config.workers[role].exports)[0]).id,+ },+ configuration: { wrangler_ssh: { enabled: false } },+ observability: { logs: { enabled: false } },+ health: { instances: { active: 0, starting: 0 } },+ }));+ const migrations = Array.from(+ { length: 9 },+ (_, i) => `${String(i + 1).padStart(4, '0')}_fixture.sql`,+ );+ const receipt = {+ mode: 'private-lifecycle',+ sourceDirty: false,+ sourceCommit: 'e'.repeat(40),+ deployOrder: config.deployOrder,+ images: manifest.images,+ workers: Object.entries(workers).map(([role, w]) => ({+ role,+ name: w.worker.name,+ sha256: hash(Buffer.from(w.version.modules[0].content_base64, 'base64')),+ })),+ migrations: migrations.map((name) => ({ name, sha256: 'f'.repeat(64) })),+ };+ const snapshot = {+ account: manifest.account,+ complete: true,+ workers,+ namespaces,+ applications,+ database: { uuid: manifest.database.id, name: manifest.database.name },+ kv: { id: manifest.oauthKv, title: `${manifest.prefix}-oauth` },+ bucket: { name: manifest.bucket },+ managedDomain: { enabled: false },+ customDomains: { domains: [] },+ migrations,+ };+ return { manifest, receipt, snapshot };+}+function deployed() {+ const f = fixture();+ return { ...f, verified: verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot) };+}+function stopped() {+ const f = deployed();+ const claims = f.verified.applications.map((a) => ({ kind: a.kind, id: hash(a.name) }));+ const instances = f.verified.applications.map((a, i) => ({+ id: claims[i].id,+ application_id: a.id,+ image: Object.values(a.images)[0],+ status: { state: 'stopped' },+ }));+ const status = {+ record: { state: 'finished', passed: true },+ budget: { state: 'closed', claims },+ admission: { paused: true, activeRequests: 0, pendingCleanup: 0 },+ operatorStopped: true,+ alarmAt: null,+ };+ return { ...f, status, instances };+}++test('private deployment readback binds exact deployed code, versions, resources and images', () => {+ const f = deployed();+ assert.equal(f.verified.workers.length, 8);+ assert.equal(f.verified.applications.length, 3);+ assert.equal(f.verified.namespaces.length, 7);+ assert.equal(f.verified.privateConfigurationVerified, true);+ assert.equal(f.verified.sourceCommit, f.receipt.sourceCommit);+ assert.equal(f.verified.database.id, f.manifest.database.id);+});++function disabledProviderSettings(snapshot) {+ for (const entry of Object.values(snapshot.workers)) {+ entry.scriptSettings = { logpush: false, tail_consumers: null, observability: null };+ entry.worker.observability = {+ enabled: false,+ head_sampling_rate: 1,+ redact_query_string: false,+ logs: {+ enabled: false,+ head_sampling_rate: 1,+ invocation_logs: true,+ persist: true,+ destinations: [],+ },+ traces: { enabled: false, head_sampling_rate: 1, persist: true, destinations: [] },+ };+ }+}++test('readback accepts provider-disabled raw observability with inactive CLI defaults', () => {+ const f = fixture();+ disabledProviderSettings(f.snapshot);+ assert.equal(+ verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot).privateConfigurationVerified,+ true,+ );+});++test('readback handles omitted empty collections and the D1 database_id alias', () => {+ const f = fixture();+ delete f.snapshot.workers.allowance.version.bindings;+ delete f.snapshot.workers.gateway.version.exports;+ for (const role of ['gateway', 'operator']) {+ const binding = f.snapshot.workers[role].version.bindings.find((b) => b.type === 'd1');+ binding.database_id = binding.id;+ }+ assert.equal(+ verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot).privateConfigurationVerified,+ true,+ );+ f.snapshot.workers.gateway.version.bindings.find((b) => b.type === 'd1').database_id = 'other';+ assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));+});++test('omitted bindings or exports still fail when the candidate requires them', () => {+ for (const field of ['bindings', 'exports']) {+ const f = fixture();+ delete f.snapshot.workers.request.version[field];+ assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));+ }+});++test('disabled readback requires explicit raw evidence and rejects active or contradictory logging', () => {+ for (const edit of [+ (e) => {+ delete e.scriptSettings;+ },+ (e) => {+ delete e.scriptSettings.observability;+ },+ (e) => {+ delete e.scriptSettings.logpush;+ },+ (e) => {+ delete e.scriptSettings.tail_consumers;+ },+ (e) => {+ e.scriptSettings.logpush = true;+ },+ (e) => {+ e.scriptSettings.tail_consumers = [{ service: 'external' }];+ },+ (e) => {+ e.scriptSettings.observability = { enabled: true };+ },+ (e) => {+ e.worker.observability.enabled = true;+ },+ (e) => {+ e.worker.observability.logs.enabled = true;+ },+ (e) => {+ e.worker.observability.traces.enabled = true;+ },+ (e) => {+ e.worker.observability.logs.destinations = ['external'];+ },+ (e) => {+ e.worker.observability.traces.destinations = ['external'];+ },+ ]) {+ const f = fixture();+ disabledProviderSettings(f.snapshot);+ edit(f.snapshot.workers.gateway);+ assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));+ }+});++test('readback rejects code, public surfaces, stored logs and inactive-version discrepancies', () => {+ for (const edit of [+ (s) => {+ s.workers.gateway.version.modules[0].content_base64 =+ Buffer.from('altered').toString('base64');+ },+ (s) => {+ s.workers.gateway.version.urls.push('https://public.example');+ },+ (s) => {+ s.workers.gateway.worker.subdomain.enabled = true;+ },+ (s) => {+ s.workers.gateway.worker.subdomain.previews_enabled = true;+ },+ (s) => {+ s.workers.gateway.worker.observability.logs.persist = true;+ },+ (s) => {+ s.workers.gateway.worker.observability.enabled = true;+ },+ (s) => {+ s.workers.gateway.worker.tail_consumers.push({ service: 'external' });+ },+ (s) => {+ s.workers.gateway.routes.push({ pattern: '*.example/*' });+ },+ (s) => {+ s.workers.gateway.schedules.push({ cron: '* * * * *' });+ },+ (s) => {+ s.workers.gateway.deployments.deployments[0].versions.push({+ version_id: 'unreviewed',+ percentage: 1,+ });+ },+ (s) => {+ s.workers.gateway.version.limits.cpu_ms = 300000;+ },+ (s) => {+ s.managedDomain.enabled = true;+ },+ (s) => {+ s.customDomains.domains.push({ domain: 'assets.example' });+ },+ (s) => {+ s.complete = false;+ },+ ]) {+ const f = fixture();+ edit(f.snapshot);+ assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));+ }+});++test('readback rejects changed tenancy, unexpected secrets, image drift and incomplete migrations', () => {+ for (const edit of [+ (s) => {+ s.workers.gateway.version.bindings.find((b) => b.name === 'ACCOUNTS').id = 'other';+ },+ (s) => {+ s.workers.request.version.bindings.find((b) => b.name === 'TENANTS').namespace_id = 'other';+ },+ (s) => {+ s.workers.operator.version.bindings.find((b) => b.name === 'GATEWAY').service =+ 'another-worker';+ },+ (s) => {+ s.workers.gateway.version.bindings.push({ name: 'SECRET', type: 'secret_text' });+ },+ (s) => {+ s.workers.gateway.version.bindings.find((b) => b.type === 'ratelimit').simple.limit = 100000;+ },+ (s) => {+ s.workers.render.version.containers[0].images.renderer += '0';+ },+ (s) => {+ s.namespaces[0].script = 'other-owner';+ },+ (s) => {+ s.applications[0].account_id = 'other';+ },+ (s) => {+ s.applications[0].configuration.wrangler_ssh.enabled = true;+ },+ (s) => {+ s.applications[0].health.instances.active = 1;+ },+ (s) => {+ s.bucket.name = 'production';+ },+ (s) => {+ s.kv.id = 'other';+ },+ (s) => {+ s.migrations = [];+ },+ ]) {+ const f = fixture();+ edit(f.snapshot);+ assert.throws(() => verifyLifecycleDeployment(f.manifest, f.receipt, f.snapshot));+ }+});++test('cleanup plans only recorded trial resources in reverse dependency order after verified stop', () => {+ const f = stopped();+ const plan = planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances);+ assert.deepEqual(+ plan.workers.map((w) => w.role),+ f.receipt.deployOrder.toReversed(),+ );+ assert.deepEqual(+ plan.applications.map((a) => a.id).sort(),+ f.verified.applications.map((a) => a.id).sort(),+ );+ assert.equal(plan.database.id, f.manifest.database.id);+ assert.equal(plan.kv.id, f.manifest.oauthKv);+ assert.equal(plan.bucket, f.manifest.bucket);+ assert.equal(plan.registryImages, 'preserve');+ assert.equal(plan.verifiedStoppedInstances, 3);+});++test('cleanup refuses active, unclaimed, foreign or excessive VM records and uncertain stop', () => {+ for (const edit of [+ (f) => {+ f.status.budget.state = 'open';+ },+ (f) => {+ f.status.operatorStopped = false;+ },+ (f) => {+ f.status.alarmAt = Date.now();+ },+ (f) => {+ f.status.record.state = 'running';+ },+ (f) => {+ f.status.admission.pendingCleanup = 1;+ },+ (f) => {+ f.status.admission.activeRequests = 1;+ },+ (f) => {+ f.status.admission.paused = false;+ },+ (f) => {+ f.instances[0].status.state = 'running';+ },+ (f) => {+ f.instances[0].application_id = 'other';+ },+ (f) => {+ f.instances[0].image = 'other';+ },+ (f) => {+ f.instances[0].id = hash('unclaimed');+ },+ (f) => {+ f.instances.push({ ...f.instances[0] });+ },+ (f) => {+ f.status.budget.claims.push(+ ...Array.from({ length: 5 }, (_, i) => ({ kind: 'render', id: hash(String(i)) })),+ );+ },+ (f) => {+ f.verified.database.id = 'production';+ },+ (f) => {+ f.verified.workers[0].name = 'production';+ },+ ]) {+ const f = stopped();+ edit(f);+ assert.throws(() => planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances));+ }+});++test('failed starts need no running VM and failed qualification still permits verified cleanup', () => {+ const f = stopped();+ f.status.record.passed = false;+ f.instances.pop();+ const plan = planLifecycleCleanup(f.manifest, f.verified, f.status, f.instances);+ assert.equal(plan.verifiedStoppedInstances, 2);+ assert.equal(plan.claims, 3);+});diff --git a/hosting/test/lifecycle-worker.test.mjs b/hosting/test/lifecycle-worker.test.mjsnew file mode 100644index 00000000..f1a1788a--- /dev/null+++ b/hosting/test/lifecycle-worker.test.mjs@@ -0,0 +1,312 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { fileURLToPath } from 'node:url';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { lifecycleConfig } from '../probe/lifecycle-config.mjs';+import { lifecycleManifest } from './lifecycle-fixture.mjs';+import { migrateAccounts } from './database.mjs';++const c = lifecycleConfig(lifecycleManifest),+ bundles = {};+before(async () => {+ for (const [role, entry] of Object.entries(c.entries)) {+ const result = await build({+ entryPoints: [fileURLToPath(new URL(`../src/${entry}.ts`, import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ metafile: true,+ });+ bundles[role] = result.outputFiles[0].text;+ const inputs = Object.keys(result.metafile.inputs).join('\n').replaceAll('\\', '/');+ if (role !== 'operator')+ assert.doesNotMatch(inputs, /qualification-accounts|lifecycle-run|gateway-preflight/);+ if (['request', 'evaluation', 'render'].includes(role))+ assert.doesNotMatch(inputs, /oauth|\/src\/(?:auth|google|github|browser-|account-)/);+ }+ bundles.observer = (+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/lifecycle-observer.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ })+ ).outputFiles[0].text;+});+function worker(role) {+ const config = c.workers[role];+ const result = {+ name: config.name,+ modules: true,+ script: bundles[role],+ compatibilityDate: config.compatibilityDate,+ compatibilityFlags: config.compatibilityFlags,+ bindings: {},+ durableObjects: {},+ serviceBindings: {},+ kvNamespaces: {},+ d1Databases: {},+ r2Buckets: {},+ ratelimits: {},+ outboundService: () => {+ throw new Error('No external network in private lifecycle fixture');+ },+ };+ for (const [name, binding] of Object.entries(config.env)) {+ switch (binding.type) {+ case 'text':+ result.bindings[name] = binding.value;+ break;+ case 'durable-object':+ result.durableObjects[name] = {+ className: binding.exportName,+ scriptName: binding.worker,+ useSQLite: true,+ };+ break;+ case 'worker':+ result.serviceBindings[name] = { name: binding.worker, entrypoint: binding.exportName };+ break;+ case 'd1':+ result.d1Databases[name] = binding.id;+ break;+ case 'kv':+ result.kvNamespaces[name] = binding.id;+ break;+ case 'r2':+ result.r2Buckets[name] = binding.name;+ break;+ case 'rate-limit':+ result.ratelimits[name] = { namespace_id: binding.namespace, simple: binding.simple };+ break;+ case 'analytics-engine-dataset':+ break;+ default:+ assert.fail(`Unexpected binding ${binding.type}`);+ }+ }+ for (const [name, exported] of Object.entries(config.exports))+ if (exported.type === 'durable-object')+ result.durableObjects[`REGISTER_${name}`] = { className: name, useSQLite: true };+ return result;+}+async function fixture(fault) {+ const runtime = new Miniflare({+ ...convertV4MiniflareOptions({+ workers: [+ ...Object.keys(c.entries).map((role) => {+ const value = worker(role);+ if (role === 'gateway' && fault === 'database')+ value.d1Databases.ACCOUNTS = '22222222-2222-2222-2222-222222222222';+ if (role === 'operator' && fault === 'uncertain-cleanup')+ value.serviceBindings.CONTROL = { name: 'uncertain-control', entrypoint: 'Control' };+ return value;+ }),+ {+ name: 'uncertain-control',+ modules: true,+ compatibilityDate: '2026-10-06',+ script: `import {WorkerEntrypoint} from 'cloudflare:workers';+ export class Control extends WorkerEntrypoint {+ setPaused(){return {paused:true,activeRequests:1,pendingCleanup:1};}+ }+ export default {fetch(){return new Response('Not found',{status:404});}};`,+ },+ {+ name: 'loopback-observer',+ modules: true,+ compatibilityDate: '2026-10-06',+ script: bundles.observer,+ serviceBindings: {+ PROBE: { name: c.workers.operator.name, entrypoint: 'KilnLifecycleControl' },+ },+ },+ {+ name: 'local-observer',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: {+ PROBE: { name: c.workers.operator.name, entrypoint: 'KilnLifecycleControl' },+ },+ durableObjects: {+ REQUEST: {+ className: 'KilnNativeRequest',+ scriptName: c.workers.request.name,+ useSQLite: true,+ },+ EVALUATION: {+ className: 'KilnEvaluationJob',+ scriptName: c.workers.evaluation.name,+ useSQLite: true,+ },+ RENDER: {+ className: 'KilnRenderJob',+ scriptName: c.workers.render.name,+ useSQLite: true,+ },+ },+ script: `export default {async fetch(request,env){+ switch(new URL(request.url).pathname){+ case '/denied': {+ const outcomes=[];+ for(const name of ['REQUEST','EVALUATION','RENDER']) {+ let cancelled=false,denied=false,done;+ const cancellation=new Promise(resolve=>{done=resolve;});+ const body=new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('{}'));},cancel(){cancelled=true;done();}});+ const input=new Request('https://native.invalid/mcp',{method:'POST',body});+ try {+ const stub=env[name].getByName('closed-budget');+ if(name==='REQUEST') await stub.run('a'.repeat(43),input,Date.now()+60000);+ else await stub.fetch(input);+ } catch { denied=true; }+ let timer;+ try {await Promise.race([cancellation,new Promise(resolve=>{timer=setTimeout(resolve,1000);})]);}+ finally {clearTimeout(timer);}+ outcomes.push({name,cancelled,denied});+ }+ return Response.json(outcomes);+ }+ default: return new Response('Not found',{status:404});+ }+ }};`,+ },+ ],+ }),+ unsafeInspectDurableObjects: true,+ });+ try {+ const name = c.workers.operator.name;+ const database = await runtime.getD1Database('ACCOUNTS', name);+ await migrateAccounts(database);+ const namespace = await runtime.getDurableObjectNamespace('RUN', name);+ const observer = await runtime.getWorker('local-observer');+ const loopback = await runtime.getWorker('loopback-observer');+ const call = async (path) =>+ (+ await (path === 'denied'+ ? observer.fetch('https://observer.invalid/denied')+ : loopback.fetch(`http://127.0.0.1:8798/${path === 'run' ? 'run-fixed' : path}`, {+ method: 'POST',+ headers: { 'X-Kiln-Operator': 'private-lifecycle-v1' },+ }))+ ).json();+ return {+ runtime,+ database,+ namespace,+ run: () => call('run'),+ stop: () => call('stop'),+ status: () => call('status'),+ denied: () => call('denied'),+ };+ } catch (error) {+ await runtime.dispose();+ throw error;+ }+}+test('combined private operator passes the gateway before native admission, seals on missing VM and survives eviction', async () => {+ const f = await fixture();+ try {+ const attempts = await Promise.all([f.run(), f.run()]);+ const first = attempts.find((result) => result.state === 'finished');+ assert(first);+ assert.equal(first.preflight.passed, true, JSON.stringify(first));+ assert.equal(first.native.passed, false);+ assert.equal(first.native.results.length, 1);+ assert.equal(first.native.results[0].name, 'material-create');+ assert.equal(first.native.results[0].status, 503);+ assert.equal(first.passed, false);+ const status = await f.status();+ assert.equal(status.budget.state, 'closed');+ assert.deepEqual(+ status.budget.claims.map((v) => v.kind),+ ['coordinator'],+ );+ assert.equal(status.admission.paused, true);+ assert.equal(status.admission.activeRequests, 0);+ assert.equal(status.admission.pendingCleanup, 0);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 2,+ );+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_connections').first()).n,+ 4,+ );+ assert.doesNotMatch(+ JSON.stringify(first),+ /access_token|refresh_token|cookie|Bearer |ka_[a-f0-9]/,+ );+ await f.runtime.unsafeEvictDurableObject(c.workers.operator.name, 'KilnLifecycleRun', {+ id: f.namespace.idFromName('lifecycle-v1').toString(),+ });+ assert.deepEqual(await f.run(), first);+ assert.deepEqual((await f.status()).budget, status.budget);+ for (const w of Object.values(c.workers)) {+ const bound = await f.runtime.getWorker(w.name);+ if (w.name !== c.workers.gateway.name)+ assert.equal((await bound.fetch('https://private.invalid/run')).status, 404);+ }+ } finally {+ await f.runtime.dispose();+ }+});+test('operator stop before setup cannot provision identities or native work', async () => {+ const f = await fixture();+ try {+ await f.stop();+ const first = await f.run(),+ status = await f.status();+ assert.equal(first.passed, false);+ assert.equal(first.state, 'stopped');+ assert.deepEqual(status.budget, { state: 'closed', claims: [] });+ assert.equal(status.admission.paused, true);+ assert.deepEqual(+ await f.denied(),+ ['REQUEST', 'EVALUATION', 'RENDER'].map((name) => ({ name, cancelled: true, denied: true })),+ );+ assert.deepEqual((await f.status()).budget, status.budget);+ assert.equal(+ (await f.database.prepare('SELECT COUNT(*) AS n FROM kiln_accounts').first()).n,+ 0,+ );+ } finally {+ await f.runtime.dispose();+ }+});+test('failed gateway preflight cannot open the native allowance', async () => {+ const f = await fixture('database');+ try {+ const first = await f.run();+ assert.equal(first.preflight.passed, false);+ assert.equal(first.native, null);+ const status = await f.status();+ assert.deepEqual(status.budget, { state: 'closed', claims: [] });+ assert.equal(status.admission.paused, true);+ assert.deepEqual(await f.run(), first);+ } finally {+ await f.runtime.dispose();+ }+});++test('operator stop retains a recovery alarm when control reports uncertain cleanup', async () => {+ const f = await fixture('uncertain-cleanup');+ try {+ const failed = await f.run();+ assert.equal(failed.passed, false);+ const afterRun = await f.status();+ assert(afterRun.alarmAt > Date.now() && afterRun.alarmAt <= Date.now() + 61000);+ await f.stop();+ const status = await f.status();+ assert(status.alarmAt > Date.now());+ assert.deepEqual(status.budget, { state: 'closed', claims: [] });+ assert.equal(status.operatorStopped, true);+ } finally {+ await f.runtime.dispose();+ }+});diff --git a/hosting/test/native-assets.test.mjs b/hosting/test/native-assets.test.mjsindex e939e375..5146f307 100644--- a/hosting/test/native-assets.test.mjs+++ b/hosting/test/native-assets.test.mjs@@ -96,6 +96,96 @@ const usage = async (owner) =>await namespace.get(namespace.idFromName(owner)).fetch('https://tenant.internal/internal/usage')).json();+test('new saves require matching host proof when configured, while imports preserve original provenance', async () => {+ let proofs = 0;+ const assets = new NativeAssetLibrary({+ fetch: fetchFor('build-proof'),+ executionIdentity: (draft) => {+ proofs++;+ assert.equal(draft.code, source);+ assert.deepEqual(draft.glb, Uint8Array.from(glb));+ return `cloudflare-container:sha256:${'a'.repeat(64)}`;+ },+ });+ const saved = await assets.save('project', {+ name: 'Verified box',+ code: source,+ glb,+ build: { engine: 'source-claimed-forgery', options: {}, warnings: [] },+ });+ assert.equal(proofs, 1);+ assert.equal(saved.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);+ const record = await assets.read('project', saved.assetId, saved.revisionId);+ record.manifest.build.engine = 'imported:unknown-original-host';+ const imported = await assets.import('library', [record]);+ assert.equal(proofs, 1);+ assert.equal(imported[0].build.engine, 'imported:unknown-original-host');+ const before = await usage('build-proof');+ await assert.rejects(assets.save('project', { name: 'Missing build', code: source, glb }));+ const unavailable = new NativeAssetLibrary({+ fetch: fetchFor('build-proof'),+ executionIdentity: () => {+ throw new Error('No verified evaluation');+ },+ });+ await assert.rejects(+ unavailable.save('project', {+ name: 'Missing proof',+ code: source,+ glb,+ build: { engine: 'forged', options: {}, warnings: [] },+ }),+ /verified evaluation/,+ );+ assert.deepEqual(await usage('build-proof'), before);+});++test('native links use server-issued tickets for exact saved revisions and never accept backend URLs', async () => {+ const assets = library('download-links');+ const saved = await assets.save('project', { name: 'Box', code: source, glb });+ const urls = await assets.downloadUrls(+ 'https://kiln.example.com',+ 'project',+ saved.assetId,+ saved.revisionId,+ );+ assert.deepEqual(Object.keys(urls).sort(), ['asset.glb', 'manifest.json', 'source.kiln.js']);+ const uri = new URL(urls['source.kiln.js']);+ assert.equal(uri.origin, 'https://kiln.example.com');+ assert.match(uri.pathname, /^\/downloads\/[a-f0-9]{64}\/source\.kiln\.js$/);+ const read = await namespace+ .getByName('download-links')+ .fetch(`https://tenant.internal/internal${uri.pathname}`);+ assert.equal(read.status, 200);+ assert.equal(await read.text(), source);+ assert.equal(+ (+ await namespace+ .getByName('other-downloads')+ .fetch(`https://tenant.internal/internal${uri.pathname}`)+ ).status,+ 404,+ );+ await assert.rejects(+ assets.downloadUrls('https://evil.example/path', 'project', saved.assetId, saved.revisionId),+ );+ await assert.rejects(+ assets.downloadUrls('https://kiln.example.com', 'foreign', saved.assetId, saved.revisionId),+ );+ for (const invalid of [+ { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['../../secret'] },+ { ticket: `${'a'.repeat(64)}\n`, expiresAt: Date.now() + 600000, files: ['asset.glb'] },+ { ticket: 'a'.repeat(64), expiresAt: 0, files: ['asset.glb'] },+ { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['https://evil.example'] },+ { ticket: 'a'.repeat(64), expiresAt: Date.now() + 600000, files: ['asset.glb', 'asset.glb'] },+ ]) {+ const forged = new NativeAssetLibrary({ fetch: async () => Response.json(invalid) });+ await assert.rejects(+ forged.downloadUrls('https://kiln.example.com', 'project', saved.assetId, saved.revisionId),+ );+ }+});+test('save, revise, reconnect and export preserve exact records and source lineage', async () => {const assets = library('saved');assert.deepEqual(diff --git a/hosting/test/native-build-identity.test.mjs b/hosting/test/native-build-identity.test.mjsnew file mode 100644index 00000000..c7e36da0--- /dev/null+++ b/hosting/test/native-build-identity.test.mjs@@ -0,0 +1,48 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';++let NativeBuildIdentities;+const image = `sha256:${'a'.repeat(64)}`;+before(async () => {+ const output = new URL('../../.cache/native-build-identity-test.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-build-identity.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ NativeBuildIdentities } = await import(output));+});++test('saved identity is bound to exact evaluated source and output, independent of caller buffers', () => {+ const records = new NativeBuildIdentities();+ const glb = new Uint8Array([1, 2, 3]);+ records.record('source', glb, image);+ const draft = { code: 'source', glb: Uint8Array.from(glb), build: { engine: 'forged' } };+ assert.equal(records.forDraft(draft), `cloudflare-container:${image}`);+ glb[0] = 9;+ assert.equal(records.forDraft(draft), `cloudflare-container:${image}`);+ for (const value of [+ { ...draft, glb },+ { ...draft, code: 'other' },+ { ...draft, code: undefined },+ ])+ assert.throws(() => records.forDraft(value), /verified evaluation/i);+ assert.throws(() => new NativeBuildIdentities().forDraft(draft), /verified evaluation/i);+});++test('missing, malformed or conflicting identities cannot be saved and retained proofs are bounded', () => {+ const records = new NativeBuildIdentities();+ for (const identity of [undefined, '', 'latest', `${image}\n`])+ assert.throws(() => records.record('a', new Uint8Array([1]), identity));+ records.record('a', new Uint8Array([1]), image);+ assert.throws(() => records.record('a', new Uint8Array([1]), `sha256:${'b'.repeat(64)}`));+ for (let i = 1; i < 16; i++) records.record(`source-${i}`, new Uint8Array([i]), image);+ assert.throws(() => records.record('overflow', new Uint8Array([100]), image));+ records.record('a', new Uint8Array([1]), image);+ assert.throws(() => records.record('x'.repeat(1024 * 1024 + 1), new Uint8Array([1]), image));+ assert.throws(() => records.record('a', new Uint8Array(4 * 1024 * 1024 + 1), image));+});diff --git a/hosting/test/native-build.test.mjs b/hosting/test/native-build.test.mjsnew file mode 100644index 00000000..2ab3b43f--- /dev/null+++ b/hosting/test/native-build.test.mjs@@ -0,0 +1,48 @@+import assert from 'node:assert/strict';+import { cp, mkdir, mkdtemp, readFile, readdir, rm, symlink } from 'node:fs/promises';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { join, resolve, sep } from 'node:path';+import { test } from 'node:test';++test('native-only build works without checkout engine bundles or SDK files', async () => {+ const cache = fileURLToPath(new URL('../../.cache/', import.meta.url));+ await mkdir(cache, { recursive: true });+ const fixture = await mkdtemp(join(cache, 'native-build-'));+ try {+ const hosting = join(fixture, 'hosting');+ await mkdir(join(hosting, 'scripts'), { recursive: true });+ await cp(new URL('../src/', import.meta.url), join(hosting, 'src'), { recursive: true });+ // The private storage adapter bundles this pure source-reference contract.+ // Neither dist/ nor lib/ exists in the isolated checkout.+ await mkdir(join(fixture, 'src'));+ await cp(+ new URL('../../src/program-store.ts', import.meta.url),+ join(fixture, 'src', 'program-store.ts'),+ );+ for (const name of ['build.mjs', 'build-boundary.mjs', 'edge-manifest.mjs'])+ await cp(new URL(`../scripts/${name}`, import.meta.url), join(hosting, 'scripts', name));+ await symlink(+ fileURLToPath(new URL('../node_modules/', import.meta.url)),+ join(hosting, 'node_modules'),+ 'junction',+ );+ const result = spawnSync(+ process.execPath,+ [join(hosting, 'scripts', 'build.mjs'), '--native-only'],+ { encoding: 'utf8', timeout: 20000 },+ );+ assert.equal(result.status, 0, result.stderr);+ const output = join(fixture, '.cache', 'hosted-worker');+ const entries = await readdir(output);+ assert.equal(entries.filter((name) => name.endsWith('.mjs')).length, 7);+ assert.ok(entries.every((name) => name.startsWith('native-')));+ for (const name of entries.filter((name) => name.endsWith('-build.json'))) {+ const manifest = JSON.parse(await readFile(join(output, name), 'utf8'));+ assert.ok(!manifest.inputs.some((path) => /edge-mcp|mcp-engine|\/lib\//.test(path)));+ }+ } finally {+ assert.ok(resolve(fixture).startsWith(`${resolve(cache)}${sep}native-build-`));+ await rm(fixture, { recursive: true, force: true });+ }+});diff --git a/hosting/test/native-evaluator.test.mjs b/hosting/test/native-evaluator.test.mjsnew file mode 100644index 00000000..906ddf47--- /dev/null+++ b/hosting/test/native-evaluator.test.mjs@@ -0,0 +1,250 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { evaluateEvaluatorRequestV2 } from '../../lib/evaluator/index.js';++const source = 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}';+let createNativeEvaluatorPort;+let handleEvaluationRequest;+const image = `sha256:${'a'.repeat(64)}`;+before(async () => {+ const output = new URL('../../.cache/hosted-native-evaluator/client.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-evaluator.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: {+ '@instruktlabs/kiln/evaluator': fileURLToPath(+ new URL('../../lib/evaluator/index.js', import.meta.url),+ ),+ },+ });+ ({ createNativeEvaluatorPort } = await import(output));+ const handler = new URL('../../.cache/hosted-native-evaluator/handler.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/evaluation-request.ts', import.meta.url))],+ outfile: fileURLToPath(handler),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ handleEvaluationRequest } = await import(handler));+});++test('native evaluation uses the fixed private route and the real versioned engine protocol', async () => {+ let calls = 0;+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ calls++;+ assert.equal(request.url, 'http://kiln-evaluator.internal/evaluate');+ assert.equal(request.method, 'POST');+ assert.equal(request.redirect, 'error');+ assert.equal(request.credentials, 'omit');+ assert.deepEqual([...request.headers.keys()].sort(), [+ 'content-length',+ 'content-type',+ 'x-kiln-deadline-ms',+ 'x-kiln-max-response-bytes',+ ]);+ assert.equal(request.headers.get('x-kiln-deadline-ms'), '60000');+ assert.equal(request.headers.get('x-kiln-max-response-bytes'), String(8 * 1024 * 1024));+ // Fixed trusted fixture, not an isolation assertion. Production runs this in a fresh VM.+ return handleEvaluationRequest(request, {+ executionImage: () => `registry.cloudflare.com/fixture/kiln@${image}`,+ async run(bytes, controls) {+ const input = new TextDecoder().decode(bytes);+ assert.equal(JSON.parse(input).limits.maxGlbBytes, 4 * 1024 * 1024);+ assert.ok(controls.deadlineMs > 0 && controls.deadlineMs <= 60_000);+ assert.equal(controls.maxResponseBytes, 8 * 1024 * 1024);+ return new TextEncoder().encode(await evaluateEvaluatorRequestV2(input));+ },+ });+ },+ });+ const rendered = await port.render(+ source,+ {},+ {+ deadlineMs: 120000,+ maxGlbBytes: 16 * 1024 * 1024,+ maxResponseBytes: 32 * 1024 * 1024,+ },+ );+ assert.equal(calls, 1);+ assert.equal(Buffer.from(rendered.glb).subarray(0, 4).toString(), 'glTF');+ assert.equal(port.executionImage(rendered), image);+ assert.equal(port.executionImage({ ...rendered }), undefined);+});++test('native evaluation requires outside-controller identity with otherwise valid stdout', async () => {+ for (const header of [undefined, 'latest', `sha256:${'A'.repeat(64)}`, `${image}, ${image}`]) {+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ const data = JSON.parse(await evaluateEvaluatorRequestV2(await request.text()));+ return Response.json(data, { headers: header ? { 'x-kiln-execution-image': header } : {} });+ },+ });+ await assert.rejects(port.render(source), (error) => error.code === 'WORKER_FAILED');+ }+});++test('native evaluation rejects forged response identity and invalid UTF-8', async () => {+ const forged = createNativeEvaluatorPort({+ fetch: async (request) => {+ const result = JSON.parse(await evaluateEvaluatorRequestV2(await request.text()));+ result.requestId = 'other-request';+ return Response.json(result, { headers: { 'x-kiln-execution-image': image } });+ },+ });+ await assert.rejects(forged.render(source), (error) => error.code === 'PROTOCOL_ERROR');+ const invalid = createNativeEvaluatorPort({+ fetch: async () =>+ new Response(new Uint8Array([0xff]), {+ headers: { 'x-kiln-execution-image': image },+ }),+ });+ await assert.rejects(invalid.render(source), (error) => error.code === 'WORKER_FAILED');+});++test('native evaluation bounds declared and streamed output and redacts upstream errors', async () => {+ for (const make of [+ () => new Response('PRIVATE_SOURCE_PATH', { status: 503 }),+ () => new Response('private', { headers: { 'content-length': '999999999' } }),+ () => new Response('x'.repeat(2049), { headers: { 'x-kiln-execution-image': image } }),+ ]) {+ const port = createNativeEvaluatorPort({ fetch: async () => make() });+ await assert.rejects(port.render(source, {}, { maxResponseBytes: 2048 }), (error) => {+ assert.doesNotMatch(error.message, /PRIVATE_SOURCE_PATH|private|x{20}/);+ return error.code === 'WORKER_FAILED';+ });+ }+});++test('overlapping evaluations retain their own controller image identity', async () => {+ let started,+ finish,+ calls = 0;+ const ready = new Promise((resolve) => {+ started = resolve;+ });+ const released = new Promise((resolve) => {+ finish = resolve;+ });+ const other = `sha256:${'b'.repeat(64)}`;+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ const first = ++calls === 1;+ const output = new TextEncoder().encode(+ await evaluateEvaluatorRequestV2(await request.text()),+ );+ return new Response(+ new ReadableStream({+ async start(controller) {+ if (first) {+ started();+ await released;+ }+ controller.enqueue(output);+ controller.close();+ },+ }),+ { headers: { 'x-kiln-execution-image': first ? image : other } },+ );+ },+ });+ const first = port.render(source);+ await ready;+ const second = await port.render(source);+ finish();+ assert.equal(port.executionImage(await first), image);+ assert.equal(port.executionImage(second), other);+});++test('native evaluation cancellation reaches a pending response body', async () => {+ const controller = new AbortController();+ let signal,+ cancelled = false,+ started;+ const ready = new Promise((resolve) => {+ started = resolve;+ });+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ signal = request.signal;+ return new Response(+ new ReadableStream({+ pull() {+ started();+ },+ cancel() {+ cancelled = true;+ },+ }),+ { headers: { 'x-kiln-execution-image': image } },+ );+ },+ });+ const pending = port.render(source, {}, { signal: controller.signal });+ await ready;+ controller.abort(new Error('PRIVATE_ABORT_REASON'));+ await assert.rejects(+ pending,+ (error) => error.code === 'CANCELLED' && !error.message.includes('PRIVATE'),+ );+ assert.equal(signal.aborted, true);+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(cancelled, true);+});++test('native evaluation has no local fallback on transport failure or deadline', async () => {+ let lateCancelled = false;+ const deadline = createNativeEvaluatorPort({+ fetch: async () => {+ await new Promise((resolve) => setTimeout(resolve, 80));+ return new Response(+ new ReadableStream({+ cancel() {+ lateCancelled = true;+ },+ }),+ );+ },+ });+ await assert.rejects(+ deadline.render(source, {}, { deadlineMs: 25 }),+ (error) => error.code === 'DEADLINE_EXCEEDED',+ );+ await new Promise((resolve) => setTimeout(resolve, 100));+ assert.equal(lateCancelled, true);+ const failed = createNativeEvaluatorPort({+ fetch: async () => {+ throw new Error('PRIVATE_NETWORK_PATH');+ },+ });+ await assert.rejects(+ failed.render(source),+ (error) => error.code === 'WORKER_FAILED' && !error.message.includes('PRIVATE'),+ );+});++test('invalid controls and already-cancelled calls cannot dispatch native evaluation', async () => {+ let calls = 0;+ const port = createNativeEvaluatorPort({+ fetch: async () => {+ calls++;+ throw new Error('Must not dispatch');+ },+ });+ for (const controls of [+ { deadlineMs: 0 },+ { maxGlbBytes: -1 },+ { maxResponseBytes: NaN },+ { signal: AbortSignal.abort() },+ ])+ await assert.rejects(port.render(source, {}, controls));+ assert.equal(calls, 0);+});diff --git a/hosting/test/native-host-entry.test.mjs b/hosting/test/native-host-entry.test.mjsnew file mode 100644index 00000000..9e6d0dab--- /dev/null+++ b/hosting/test/native-host-entry.test.mjs@@ -0,0 +1,26 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { test } from 'node:test';++test('native host entry rejects invalid public origins before loading its runtime', () => {+ for (const origin of [+ '',+ 'http://kiln.example.com',+ 'https://user:[email protected]',+ 'https://kiln.example.com/path',+ ]) {+ const result = spawnSync(+ process.execPath,+ [fileURLToPath(new URL('../container/serve.mjs', import.meta.url))],+ {+ env: { KILN_PUBLIC_ORIGIN: origin },+ encoding: 'utf8',+ timeout: 5000,+ },+ );+ assert.equal(result.status, 1);+ assert.equal(result.stdout, '');+ assert.equal(result.stderr, 'Kiln native host startup failed.\n');+ }+});diff --git a/hosting/test/native-host.test.mjs b/hosting/test/native-host.test.mjsnew file mode 100644index 00000000..c6f02362--- /dev/null+++ b/hosting/test/native-host.test.mjs@@ -0,0 +1,177 @@+import assert from 'node:assert/strict';+import { request as httpRequest } from 'node:http';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';++let createNativeHttpServer;+before(async () => {+ // Keep the fixture under the private package so Node resolves its pinned adapter.+ const output = new URL(+ '../node_modules/.cache/hosted-native-http-server/host.mjs',+ import.meta.url,+ );+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-host.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ });+ ({ createNativeHttpServer } = await import(output));+});++async function listen(t, handler, options = {}) {+ const server = createNativeHttpServer(handler, options);+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ t.after(async () => {+ await new Promise((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ server.closeAllConnections();+ });+ });+ return server;+}+function request(server, { path = '/mcp', headers = {}, method = 'POST', body = '{}' } = {}) {+ return new Promise((resolve, reject) => {+ const req = httpRequest(+ {+ hostname: '127.0.0.1',+ port: server.address().port,+ path,+ method,+ headers: { host: 'kiln-native.internal', 'content-type': 'application/json', ...headers },+ },+ (res) => {+ const chunks = [];+ res.on('data', (c) => chunks.push(c));+ res.on('end', () =>+ resolve({+ status: res.statusCode,+ headers: res.headers,+ body: Buffer.concat(chunks).toString(),+ }),+ );+ res.on('error', reject);+ },+ );+ req.on('error', reject);+ req.end(body);+ });+}++test('native Node adapter serves the fixed internal origin and a minimal readiness route', async (t) => {+ let calls = 0;+ const server = await listen(t, {+ fetch: async (req) => {+ calls++;+ assert.equal(req.url, 'http://kiln-native.internal/mcp');+ assert.equal(await req.text(), '{}');+ return new Response('ok');+ },+ });+ assert.equal((await request(server)).body, 'ok');+ const ready = await request(server, { path: '/_ready', method: 'GET', body: '' });+ assert.equal(ready.status, 204);+ assert.equal(ready.body, '');+ assert.equal(ready.headers['cache-control'], 'no-store');+ assert.equal(calls, 1);+});++test('native Node adapter refuses foreign Host, absolute paths and oversized inputs before MCP dispatch', async (t) => {+ let calls = 0;+ const server = await listen(t, {+ fetch: async () => {+ calls++;+ return new Response('must not be reached');+ },+ });+ for (const [options, status] of [+ [{ headers: { host: 'attacker.example' } }, 421],+ [{ path: 'http://kiln-native.internal/mcp' }, 404],+ [{ path: '/mcp?token=private' }, 404],+ [{ headers: { 'content-length': String(1024 * 1024 + 1) }, body: '' }, 413],+ ])+ assert.equal((await request(server, options)).status, status);+ // For a chunked flood the SDK exits IncomingMessage's async iterator at the+ // byte cap, which can close the Node socket before its 413 can be delivered.+ const oversized = await request(server, { body: 'x'.repeat(1024 * 1024 + 1) }).catch((error) => {+ assert.equal(error.code, 'ECONNRESET');+ return { status: 'closed' };+ });+ assert.ok(oversized.status === 413 || oversized.status === 'closed');+ assert.equal(calls, 0);+});++test('client disconnect reaches the Fetch handler without exposing its abort reason', async (t) => {+ let entered, aborted;+ const started = new Promise((resolve) => {+ entered = resolve;+ });+ const cancelled = new Promise((resolve) => {+ aborted = resolve;+ });+ const server = await listen(t, {+ fetch: async (req) => {+ req.signal.addEventListener('abort', () => aborted(), { once: true });+ entered();+ await cancelled;+ return new Response('late');+ },+ });+ const req = httpRequest(+ {+ hostname: '127.0.0.1',+ port: server.address().port,+ path: '/mcp',+ method: 'POST',+ headers: { host: 'kiln-native.internal' },+ },+ (res) => res.resume(),+ );+ req.on('error', () => {});+ req.end('{}');+ await started;+ req.destroy();+ await Promise.race([+ cancelled,+ new Promise((_, reject) => {+ const timer = setTimeout(() => reject(Error('Disconnect did not reach host')), 2000);+ timer.unref();+ }),+ ]);+});++test('native Node adapter applies an upload timeout before the Fetch handler starts', async (t) => {+ let calls = 0;+ const server = await listen(+ t,+ {+ fetch: async () => {+ calls++;+ return new Response('unexpected');+ },+ },+ { requestTimeoutMs: 50 },+ );+ const result = await new Promise((resolve) => {+ const req = httpRequest(+ {+ hostname: '127.0.0.1',+ port: server.address().port,+ path: '/mcp',+ method: 'POST',+ headers: { host: 'kiln-native.internal', 'content-length': '20' },+ },+ (res) => {+ res.resume();+ res.on('end', () => resolve(res.statusCode));+ },+ );+ req.on('error', () => resolve('closed'));+ req.write('{');+ });+ assert.ok(result === 408 || result === 'closed');+ assert.equal(calls, 0);+});diff --git a/hosting/test/native-http.test.mjs b/hosting/test/native-http.test.mjsnew file mode 100644index 00000000..03657deb--- /dev/null+++ b/hosting/test/native-http.test.mjs@@ -0,0 +1,119 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';++let NativeHttpClient;+before(async () => {+ const output = new URL('../../.cache/hosted-http-test/client.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-http.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ NativeHttpClient } = await import(output));+});++test('storage retains bytes when the response stream reuses its read buffer', async () => {+ const shared = new Uint8Array(1);+ let value = 0;+ const client = new NativeHttpClient({+ fetch: async () =>+ new Response(+ new ReadableStream(+ {+ pull(controller) {+ if (++value === 4) return controller.close();+ shared[0] = value;+ controller.enqueue(shared);+ },+ },+ { highWaterMark: 0 },+ ),+ ),+ });+ assert.deepEqual(+ await client.bytes('/internal/programs', { limit: 32 }),+ new Uint8Array([1, 2, 3]),+ );+});++test('a continuously readable body cannot starve the storage deadline timer', async (t) => {+ let now = 1000;+ t.mock.method(Date, 'now', () => now);+ let pulls = 0;+ let cancelled = false;+ const client = new NativeHttpClient({+ timeoutMs: 25,+ fetch: async () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ now += 10;+ if (++pulls === 100) controller.close();+ else controller.enqueue(new Uint8Array());+ },+ cancel() {+ cancelled = true;+ },+ }),+ ),+ });+ await assert.rejects(+ client.bytes('/internal/programs', { limit: 32 }),+ (error) => error.status === 504 && error.message === 'Storage request timed out',+ );+ assert.ok(pulls < 100, 'Stop reading even while microtasks prevent timer delivery');+ assert.equal(cancelled, true);+});++test('a response arriving after the deadline cannot bypass it before timers run', async (t) => {+ let now = 1000;+ t.mock.method(Date, 'now', () => now);+ let signal;+ const client = new NativeHttpClient({+ timeoutMs: 25,+ fetch: async (request) => {+ signal = request.signal;+ now += 30;+ return new Response('ok');+ },+ });+ await assert.rejects(+ client.bytes('/internal/programs', { limit: 32 }),+ (error) => error.status === 504 && error.message === 'Storage request timed out',+ );+ assert.equal(signal.aborted, true);+});++test('fixed native services cannot cross routes or forward identity headers', async () => {+ let calls = 0;+ const options = {+ fetch: async () => {+ calls++;+ return new Response('ok');+ },+ };+ const storage = new NativeHttpClient(options);+ const evaluator = new NativeHttpClient(options, 'Evaluator', 'evaluator');+ assert.throws(() => new NativeHttpClient(options, 'Invalid', 'https://example.com'));+ for (const path of ['/evaluate', '//kiln-evaluator.internal/evaluate'])+ await assert.rejects(storage.bytes(path, { limit: 8 }));+ for (const path of [+ '/internal/programs',+ '/evaluate?x=1',+ '/evaluate#x',+ '//example.com/evaluate',+ ])+ await assert.rejects(evaluator.bytes(path, { limit: 8 }));+ for (const header of ['authorization', 'cookie', 'x-tenant', 'x-artifact-name'])+ await assert.rejects(+ evaluator.bytes('/evaluate', { limit: 8, headers: { [header]: 'private' } }),+ );+ await assert.rejects(+ storage.bytes('/internal/programs', { limit: 8, headers: { 'x-kiln-deadline-ms': '25' } }),+ );+ assert.equal(calls, 0);+});diff --git a/hosting/test/native-materials.test.mjs b/hosting/test/native-materials.test.mjsnew file mode 100644index 00000000..4ed643fd--- /dev/null+++ b/hosting/test/native-materials.test.mjs@@ -0,0 +1,282 @@+import assert from 'node:assert/strict';+import { mkdir } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { after, before, test } from 'node:test';+import { build } from 'esbuild';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { createMaterialRecordV1 } from '../../lib/material-library-node.js';++let NativeMaterialLibrary, runtime, namespace, sample;+before(async () => {+ const output = new URL('../../.cache/native-material-test/native-materials.mjs', import.meta.url);+ await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-materials.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: {+ '@instruktlabs/kiln/material-library': fileURLToPath(+ new URL('../../lib/material-library.js', import.meta.url),+ ),+ '@instruktlabs/kiln/material-library/node': fileURLToPath(+ new URL('../../lib/material-library-node.js', import.meta.url),+ ),+ },+ });+ ({ NativeMaterialLibrary } = await import(output));+ const worker = await build({+ entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare({+ ...convertV4MiniflareOptions({+ name: 'native-materials',+ modules: true,+ script: worker.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ r2Buckets: ['ARTIFACTS'],+ durableObjects: { TENANTS: { className: 'KilnTenant', useSQLite: true } },+ bindings: {+ STORAGE_MAX_BYTES: '4194304',+ STORAGE_MAX_OBJECTS: '128',+ STORAGE_MAX_GROUPS: '64',+ },+ outboundService: async () => {+ throw Error('No network');+ },+ }),+ unsafeInspectDurableObjects: true,+ });+ namespace = await runtime.getDurableObjectNamespace('TENANTS');+ sample = await fixture('hosted-stone');+});++function fixture(materialId) {+ return createMaterialRecordV1({+ materialId,+ name: 'Hosted stone',+ tileable: true,+ sources: [+ {+ id: 'authored',+ kind: 'procedural',+ provider: 'Kiln',+ creator: 'Fixture author',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ size: 8,+ usage: 'albedo',+ layers: [+ { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },+ ],+ },+ },+ ],+ });+}+after(async () => runtime?.dispose());+const stub = (owner) => namespace.getByName(owner);+const storage = (owner) => async (request) => {+ assert.equal(new URL(request.url).origin, 'http://kiln-storage.internal');+ assert.equal(request.headers.get('authorization'), null);+ return stub(owner).fetch(+ new Request(`https://tenant.internal${new URL(request.url).pathname}`, request),+ );+};+const library = (owner) => new NativeMaterialLibrary({ fetch: storage(owner) });+const usage = async (owner) =>+ (await stub(owner).fetch('https://tenant.internal/internal/usage')).json();+const read = (lib) => lib.read(sample.manifest.materialId, sample.manifest.revisionId);++test('material import, list and exact reads survive a fresh host and tenant eviction while other accounts are denied', async () => {+ const original = structuredClone(sample);+ assert.deepEqual(await library('persist').import([sample]), [sample.manifest]);+ assert.deepEqual(await library('persist').list(), [sample.manifest]);+ await runtime.unsafeEvictDurableObject('native-materials', 'KilnTenant', {+ id: namespace.idFromName('persist').toString(),+ });+ assert.deepEqual(await read(library('persist')), original);+ await assert.rejects(read(library('foreign')), /not found/);+ assert.equal((await usage('foreign')).objects, 0);+ const count = await usage('persist');+ assert.equal(count.objects, 2);+ assert.equal(count.groups, 1);+ assert.ok(count.metadataBytes > 0);+});++test('concurrent identical imports are idempotent and discard losing staged files', async () => {+ const results = await Promise.all(+ Array.from({ length: 5 }, () => library('race').import([sample])),+ );+ for (const result of results) assert.deepEqual(result, [sample.manifest]);+ assert.deepEqual(await read(library('race')), sample);+ const count = await usage('race');+ assert.equal(count.objects, 2);+ assert.equal(count.groups, 1);+});++test('invalid batches and path identities are rejected before any storage write', async () => {+ let calls = 0;+ const lib = new NativeMaterialLibrary({+ fetch: async (request) => {+ calls++;+ return storage('invalid')(request);+ },+ });+ const bad = await fixture('bad-stone');+ bad.files['baseColor.png'][bad.files['baseColor.png'].length - 1] ^= 1;+ await assert.rejects(lib.import([sample, bad]), /integrity|hash|PNG/);+ for (const [id, revision] of [+ ['../victim', sample.manifest.revisionId],+ [sample.manifest.materialId, `${sample.manifest.revisionId}\n`],+ ])+ await assert.rejects(lib.read(id, revision));+ await assert.rejects(lib.import([]));+ await assert.rejects(lib.import(Array(101).fill(sample)));+ await assert.rejects(lib.import([sample, sample]), /Duplicate/);+ assert.equal(calls, 0);+ assert.equal((await usage('invalid')).objects, 0);+});++test('imports snapshot caller-owned records before asynchronous verification', async () => {+ const input = structuredClone(sample);+ const importing = library('snapshot').import([input]);+ input.manifest.name = 'Mutated caller manifest';+ input.files['baseColor.png'].fill(0);+ assert.deepEqual(await importing, [sample.manifest]);+ assert.deepEqual(await read(library('snapshot')), sample);+});++test('quota failure preserves earlier atomic imports and catalogue paging has no duplicates or omissions', async () => {+ const records = await Promise.all(+ Array.from({ length: 65 }, (_, index) => fixture(`paged-${String(index).padStart(3, '0')}`)),+ );+ const lib = library('paged');+ await assert.rejects(lib.import(records), /quota reached/);+ const manifests = records.slice(0, 64).map((record) => record.manifest);+ assert.deepEqual(await lib.list(), manifests);+ const count = await usage('paged');+ assert.equal(count.groups, 64);+ assert.equal(count.objects, 128);+ // Idempotent reads/imports still work at the storage limit.+ assert.deepEqual(await lib.import([records[0]]), [records[0].manifest]);+});++test('partial staging failure cleans acknowledged files without storing a material', async () => {+ let uploads = 0;+ const lib = new NativeMaterialLibrary({+ fetch: async (request) => {+ if (new URL(request.url).pathname === '/internal/artifacts' && ++uploads === 2)+ return new Response('fixture upload unavailable', { status: 503 });+ return storage('staged-failure')(request);+ },+ });+ await assert.rejects(lib.import([sample]), /unavailable/);+ assert.deepEqual(await library('staged-failure').list(), []);+ assert.equal((await usage('staged-failure')).objects, 0);+});++test('lost commit acknowledgement cannot remove pinned material bytes', async () => {+ const lib = new NativeMaterialLibrary({+ fetch: async (request) => {+ const response = await storage('lost')(request);+ if (new URL(request.url).pathname === '/internal/materials/commit') {+ assert.equal(response.status, 201);+ await response.body?.cancel();+ return new Response('fixture lost acknowledgement', { status: 503 });+ }+ return response;+ },+ });+ await assert.rejects(lib.import([sample]), /unavailable/);+ assert.deepEqual(await read(library('lost')), sample);+ assert.equal((await usage('lost')).objects, 2);+});++test('material retention shares artifact quotas and corrupted objects cannot be read', async () => {+ await library('integrity').import([sample]);+ const db = await runtime.unsafeGetDurableObjectStorage('native-materials', 'KilnTenant', {+ id: namespace.idFromName('integrity').toString(),+ });+ await db.exec('UPDATE artifacts SET expires_at=1');+ await stub('integrity').fetch('https://tenant.internal/internal/maintenance', { method: 'POST' });+ assert.deepEqual(await read(library('integrity')), sample);+ const rows = await db.exec("SELECT object_key FROM artifacts WHERE filename='baseColor.png'");+ await (await runtime.getR2Bucket('ARTIFACTS')).put(rows[0].object_key, 'corrupt');+ await assert.rejects(read(library('integrity')), /integrity|unavailable/);+});++test('material index rejects arbitrary storage keys, extra filenames, foreign file IDs and malformed pagination', async () => {+ await library('indexed').import([sample]);+ const encoded = sample.manifest.revisionId.slice(7);+ const record = await (+ await stub('indexed').fetch(+ `https://tenant.internal/internal/materials/${sample.manifest.materialId}/${encoded}`,+ )+ ).json();+ for (const input of [+ {+ materialId: sample.manifest.materialId,+ revisionId: sample.manifest.revisionId,+ files: record.files,+ key: 'assets/project/victim',+ },+ { materialId: '../victim', revisionId: sample.manifest.revisionId, files: record.files },+ {+ materialId: sample.manifest.materialId,+ revisionId: sample.manifest.revisionId,+ files: { ...record.files, 'asset.glb': record.files['manifest.json'] },+ },+ ])+ assert.equal(+ (+ await stub('indexed').fetch('https://tenant.internal/internal/materials/commit', {+ method: 'POST',+ body: JSON.stringify(input),+ })+ ).status,+ 400,+ );+ assert.equal(+ (+ await stub('foreign-index').fetch('https://tenant.internal/internal/materials/commit', {+ method: 'POST',+ body: JSON.stringify({+ materialId: sample.manifest.materialId,+ revisionId: sample.manifest.revisionId,+ files: record.files,+ }),+ })+ ).status,+ 404,+ );+ assert.equal(+ (+ await stub('indexed').fetch('https://tenant.internal/internal/materials/list', {+ method: 'POST',+ body: JSON.stringify({ after: 'assets/project/elsewhere' }),+ })+ ).status,+ 400,+ );+});diff --git a/hosting/test/native-mcp.test.mjs b/hosting/test/native-mcp.test.mjsindex 67d06346..07831766 100644--- a/hosting/test/native-mcp.test.mjs+++ b/hosting/test/native-mcp.test.mjs@@ -1,19 +1,27 @@import assert from 'node:assert/strict';-import { mkdir } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { mkdir, readFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';import { after, before, test } from 'node:test';import { build } from 'esbuild';import { convertV4MiniflareOptions, Miniflare } from 'miniflare';import { createKilnMcpServer, kilnMcpToolDefs } from '../../dist/mcp-engine.mjs';import { renderGLB } from '../../lib/render.js';+import { evaluateEvaluatorRequestV2 } from '../../lib/evaluator/index.js';+import { encodePng } from '../../lib/views/png.js';const publicOrigin = 'https://kiln.example.com';const source ="function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";let createNativeMcpHandler;let loadNativeMcpRuntime;+let loadContainerMcpRuntime;+let createNativeEvaluatorPort;let runtime;let namespace;+let runIntegratedOnce, integratedSource;+let runLifecycleOnce, lifecycleCases, lifecycleBudget;+let routeEdgeMcp;const handlers = [];before(async () => {const outfile = fileURLToPath(@@ -34,16 +42,37 @@ before(async () => {['assets', 'assets'],['assets/node', 'assets-node'],['material-library/node', 'material-library-node'],+ ['material-library', 'material-library'],+ ['workspace', 'workspace'],['evaluator', 'evaluator/index'],+ ['composer', 'composer/index'],].map(([name, file]) => [`@instruktlabs/kiln/${name}`,fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),]),),});- ({ createNativeMcpHandler, loadNativeMcpRuntime } = await import(+ ({ createNativeMcpHandler, loadNativeMcpRuntime, loadContainerMcpRuntime } = await import(new URL('../../.cache/hosted-mcp-test/native-mcp.mjs', import.meta.url)));+ const evaluatorOutput = new URL(+ '../../.cache/hosted-mcp-test/native-evaluator.mjs',+ import.meta.url,+ );+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-evaluator.ts', import.meta.url))],+ outfile: fileURLToPath(evaluatorOutput),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: {+ '@instruktlabs/kiln/evaluator': fileURLToPath(+ new URL('../../lib/evaluator/index.js', import.meta.url),+ ),+ },+ });+ ({ createNativeEvaluatorPort } = await import(evaluatorOutput));const worker = await build({entryPoints: [fileURLToPath(new URL('../src/tenant-worker.ts', import.meta.url))],bundle: true,@@ -70,6 +99,33 @@ before(async () => {}),);namespace = await runtime.getDurableObjectNamespace('TENANTS');+ const trial = new URL('../../.cache/hosted-mcp-test/integrated-run.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/integrated-run.ts', import.meta.url))],+ outfile: fileURLToPath(trial),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ runIntegratedOnce, integratedSource } = await import(trial));+ const lifecycle = new URL('../../.cache/hosted-mcp-test/lifecycle-run.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/lifecycle-run.ts', import.meta.url))],+ outfile: fileURLToPath(lifecycle),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ runLifecycleOnce, lifecycleCases, lifecycleBudget } = await import(lifecycle));+ const edge = new URL('../../.cache/hosted-mcp-test/edge.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/edge-mcp.ts', import.meta.url))],+ outfile: fileURLToPath(edge),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ routeEdgeMcp } = await import(edge));});after(async () => {for (const handler of handlers) await handler.close();@@ -86,9 +142,10 @@ function host(return renderGLB(code, renderOptions);},},+ viewRenderPort,) {const handler = createNativeMcpHandler(- { createServer: createKilnMcpServer, evaluatorPort: evaluator },+ { createServer: createKilnMcpServer, evaluatorPort: evaluator, viewRenderPort },{publicOrigin,storage: {@@ -161,11 +218,26 @@ async function tool(handler, name, args, options) {test('HTTP serves both protocol eras and exactly the engine registry surface', async () => {const handler = host('protocol');- const expected = kilnMcpToolDefs({ programStore: {}, assetLibrary: {} })+ const expected = kilnMcpToolDefs({+ programStore: {},+ assetLibrary: {},+ materialLibrary: {},+ workspace: {},+ }).map((def) => def.name).sort();const current = await rpc(handler, 'tools/list');assert.deepEqual(current.tools.map((item) => item.name).sort(), expected);+ const manifest = JSON.parse(+ await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),+ );+ assert.deepEqual(current.tools, manifest.tools);+ for (const [method, key] of [+ ['resources/list', 'resources'],+ ['resources/templates/list', 'resourceTemplates'],+ ]) {+ assert.deepEqual((await rpc(handler, method))[key], manifest[key]);+ }assert.equal(current.resultType, 'complete');for (const version of ['2025-03-26', '2025-06-18', '2025-11-25']) {const initialized = await rpc(@@ -175,6 +247,9 @@ test('HTTP serves both protocol eras and exactly the engine registry surface', a{ modern: false },);assert.equal(initialized.protocolVersion, version);+ assert.equal(initialized.instructions, manifest.instructions);+ assert.deepEqual(initialized.serverInfo, manifest.serverInfo);+ assert.deepEqual(initialized.capabilities, manifest.capabilities);const legacy = await rpc(handler,'tools/list',@@ -191,7 +266,21 @@ test('HTTP serves both protocol eras and exactly the engine registry surface', a});test('real HTTP tools validate, render, save, restore and read exact source after reconnect', async () => {- const first = host('lifecycle');+ let evaluations = 0;+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ assert.equal(request.url, 'http://kiln-evaluator.internal/evaluate');+ assert.equal(request.headers.get('authorization'), null);+ const json = await request.text();+ // Fixed trusted fixture only. Actual VM dispatch and cleanup require provider qualification.+ assert.equal(JSON.parse(json).code, source);+ evaluations++;+ return new Response(await evaluateEvaluatorRequestV2(json), {+ headers: { 'x-kiln-execution-image': `sha256:${'a'.repeat(64)}` },+ });+ },+ });+ const first = host('lifecycle', {}, port);const validated = await tool(first, 'kiln_validate', { code: source });const rendered = await rpc(first, 'tools/call', {name: 'kiln_render',@@ -199,11 +288,22 @@ test('real HTTP tools validate, render, save, restore and read exact source afte});assert.equal(rendered.isError, undefined);assert.ok(rendered.content.some((item) => item.type === 'image'));+ assert.ok(evaluations > 0, 'Real MCP render must cross the versioned private transport');const saved = await tool(first, 'kiln_save', {programRef: validated.programRef,collection: 'project',name: 'HTTP box',});+ assert.equal(saved.asset.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);+ assert.match(+ saved.downloadUrls['asset.glb'],+ /^https:\/\/kiln\.example\.com\/downloads\/[a-f0-9]{64}\/asset\.glb$/,+ );+ const link = new URL(saved.downloadUrls['source.kiln.js']);+ const browserBytes = await namespace+ .getByName('lifecycle')+ .fetch(`https://tenant.internal/internal${link.pathname}`);+ assert.equal(await browserBytes.text(), source);await first.close();const second = host('lifecycle');const restored = await tool(second, 'kiln_assets', {@@ -215,6 +315,14 @@ test('real HTTP tools validate, render, save, restore and read exact source afteassert.equal(restored.programRef, validated.programRef);const uri = `kiln://assets/project/${saved.asset.assetId}/${saved.asset.revisionId}/source.kiln.js`;assert.equal((await rpc(second, 'resources/read', { uri })).contents[0].text, source);+ const savedManifest = JSON.parse(+ (+ await rpc(second, 'resources/read', {+ uri: uri.replace('source.kiln.js', 'manifest.json'),+ })+ ).contents[0].text,+ );+ assert.equal(savedManifest.build.engine, `cloudflare-container:sha256:${'a'.repeat(64)}`);const other = await rpc(host('other'), 'tools/call', {name: 'kiln_source',arguments: { programRef: restored.programRef },@@ -223,6 +331,528 @@ test('real HTTP tools validate, render, save, restore and read exact source afteassert.ok(!JSON.stringify(other).includes(source));});+test('render, save, restore and export work with a fresh native host for every MCP request', async () => {+ const owner = 'one-request-per-vm';+ const call = async (name, args) => {+ const handler = host(owner);+ try {+ return await tool(handler, name, args);+ } finally {+ await handler.close();+ }+ };+ const rendered = await call('kiln_render', { code: source, capture: { preset: '1x1' } });+ const saved = await call('kiln_save', {+ programRef: rendered.programRef,+ collection: 'project',+ name: 'Fresh host fixture',+ });+ const restored = await call('kiln_assets', {+ action: 'restore',+ collection: 'project',+ assetId: saved.asset.assetId,+ revisionId: saved.asset.revisionId,+ });+ assert.equal(restored.programRef, rendered.programRef);+ const original = await call('kiln_source', { programRef: restored.programRef });+ assert(JSON.stringify(original).includes('createRoot'));+ const exported = await call('kiln_export', {+ collection: 'project',+ assetId: saved.asset.assetId,+ revisionId: saved.asset.revisionId,+ });+ assert(exported);+});++test('durable materials bind exact revisions across fresh MCP hosts, save their closure and deny foreign accounts', async () => {+ const owner = 'material-lifecycle';+ let evaluations = 0,+ expectedSource;+ const port = createNativeEvaluatorPort({+ fetch: async (request) => {+ const json = await request.text();+ const input = JSON.parse(json);+ assert.equal(input.code, expectedSource);+ assert.equal(input.options.materialResources.records.length, 1);+ evaluations++;+ return new Response(await evaluateEvaluatorRequestV2(json), {+ headers: { 'x-kiln-execution-image': `sha256:${'b'.repeat(64)}` },+ });+ },+ });+ const call = async (name, args, account = owner, raw = false) => {+ const handler = host(account, {}, port);+ try {+ return raw+ ? await rpc(handler, 'tools/call', { name, arguments: args })+ : await tool(handler, name, args);+ } finally {+ await handler.close();+ }+ };+ const created = await call('kiln_material', {+ action: 'create-procedural',+ draft: {+ materialId: 'mcp-stone',+ name: 'MCP stone',+ tileable: true,+ sources: [+ {+ id: 'authored',+ kind: 'procedural',+ provider: 'Kiln',+ creator: 'Fixture author',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ size: 8,+ usage: 'albedo',+ layers: [+ { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed: 17, scale: 4, octaves: 2 },+ ],+ },+ },+ ],+ },+ });+ const { material, portableSpec } = created;+ const { materialId, revisionId } = material;+ assert.equal(+ (await call('kiln_material', { action: 'list' })).materials[0].revisionId,+ revisionId,+ );+ assert.deepEqual(+ (await call('kiln_material', { action: 'get', materialId, revisionId })).material,+ material,+ );+ const materialDependencies = [{ resourceId: materialId, revisionId, sha256: revisionId }];+ expectedSource = `async function build(){const r=createRoot('Root');const m=await compilePortableMaterialSpecV2(${JSON.stringify(portableSpec)});createPart('Body',boxGeo(1,1,1),m,{parent:r});return r;}`;+ const rendered = await call('kiln_render', {+ code: expectedSource,+ materialDependencies,+ capture: { preset: '1x1' },+ });+ const saved = await call('kiln_save', {+ programRef: rendered.programRef,+ materialDependencies,+ collection: 'project',+ name: 'Material box',+ });+ assert.ok(saved.downloadUrls['materials.kiln.json']);+ const path = new URL(saved.downloadUrls['materials.kiln.json']).pathname;+ const closure = await (+ await namespace.getByName(owner).fetch(`https://tenant.internal/internal${path}`)+ ).json();+ assert.deepEqual(closure.records[0].manifest, material);+ const exportResult = await call('kiln_export', {+ collection: 'project',+ assetId: saved.asset.assetId,+ revisionId: saved.asset.revisionId,+ });+ assert(exportResult);+ const before = evaluations;+ const foreign = await call(+ 'kiln_render',+ { code: expectedSource, materialDependencies, capture: { preset: '1x1' } },+ 'material-foreign',+ true,+ );+ assert.equal(foreign.isError, true);+ assert.match(JSON.stringify(foreign), /Locked material unavailable/);+ assert.equal(evaluations, before, 'Foreign material denial occurs before native evaluation');+ assert.deepEqual(+ (await call('kiln_material', { action: 'list' }, 'material-foreign')).materials,+ [],+ );+ // A saved asset's editable closure is independent of the live material library.+ const tenant = namespace.getByName(owner);+ const indexed = await (+ await tenant.fetch(+ `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,+ )+ ).json();+ assert.equal(+ (+ await tenant.fetch(`https://tenant.internal/internal/groups/${indexed.id}`, {+ method: 'DELETE',+ })+ ).status,+ 200,+ );+ assert.deepEqual((await call('kiln_material', { action: 'list' })).materials, []);+ const imported = await call('kiln_import', {+ sourceCollection: 'project',+ collection: 'library',+ assetId: saved.asset.assetId,+ revisionId: saved.asset.revisionId,+ });+ assert.deepEqual(+ (await call('kiln_material', { action: 'get', materialId, revisionId })).material,+ material,+ );+ const originalGlb = await (+ await tenant.fetch(+ `https://tenant.internal/internal${new URL(saved.downloadUrls['asset.glb']).pathname}`,+ )+ ).arrayBuffer();+ const importedGlb = await (+ await tenant.fetch(+ `https://tenant.internal/internal${new URL(imported.downloadUrls['asset.glb']).pathname}`,+ )+ ).arrayBuffer();+ assert.deepEqual(Buffer.from(importedGlb), Buffer.from(originalGlb));+ const rebuilt = await call('kiln_render', {+ programRef: rendered.programRef,+ materialDependencies,+ capture: { preset: '1x1' },+ });+ assert.equal(rebuilt.programRef, rendered.programRef);+});++test('the complete fixed provider sequence matches real fresh-host MCP and private asset contracts', async () => {+ const values = new Map();+ let count = 0,+ paused = false;+ const store = {+ get: async (key) => structuredClone(values.get(key)),+ put: async (key, value) => values.set(key, structuredClone(value)),+ transaction: async (fn) => fn(store),+ };+ const receipts = [];+ const result = await runIntegratedOnce(store, {+ open: async () => {},+ close: async () => {},+ pause: async () => {+ paused = true;+ },+ status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 1 }),+ retain: async (name, bytes) => {+ receipts.push({ name, bytes });+ },+ dispatch: async (owner, request) => {+ if (++count > 9) return new Response('quota', { status: 429 });+ const handler = host(+ owner,+ {},+ {+ render: async (code, options) => {+ assert.equal(code, integratedSource);+ return renderGLB(code, options);+ },+ },+ async (request) => {+ const size = request.size ?? request.width;+ return {+ ok: true,+ rendererId: 'dawn-vulkan:software-fixture',+ viewsPng: (request.viewDirs ?? request.cameras).map(() =>+ encodePng(new Uint8Array(size * size * 3).fill(128), size, size),+ ),+ derivativeFidelity: {+ materialFaithful: true,+ inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,+ },+ };+ },+ );+ const response = await handler.fetch(new Request('http://kiln-native.internal/mcp', request));+ const bytes = await response.arrayBuffer();+ await handler.close();+ return new Response(bytes, { status: response.status, headers: response.headers });+ },+ });+ assert.equal(result.passed, true, JSON.stringify(result));+ assert.equal(result.results.length, 10);+ assert.equal(receipts.length, 10);+});++test('private lifecycle trial qualifies fresh hosts, editable materials, exact downloads and pinned provenance', async () => {+ const values = new Map();+ const store = {+ get: async (key) => structuredClone(values.get(key)),+ put: async (key, value) => values.set(key, structuredClone(value)),+ transaction: async (fn) => fn(store),+ };+ const fixtureOrigin = 'https://kiln-private-qualification.invalid';+ const expectedImage = `sha256:${'b'.repeat(64)}`;+ let calls = 0,+ evaluations = 0,+ renders = 0,+ paused = true,+ opened = 0,+ closed = 0;+ const evidence = [];+ const ownerName = (account) => `full-lifecycle-${account}`;+ const evaluator = createNativeEvaluatorPort({+ fetch: async (request) => {+ const json = await request.text();+ const input = JSON.parse(json);+ assert.equal(input.options.materialResources.records.length, 1);+ assert.equal(+ input.options.materialResources.records[0].manifest.materialId,+ 'qualification-stone',+ );+ evaluations++;+ return new Response(await evaluateEvaluatorRequestV2(json), {+ headers: { 'x-kiln-execution-image': expectedImage },+ });+ },+ });+ const ports = {+ expectedImage,+ open: async () => {+ opened++;+ paused = false;+ },+ close: async () => {+ closed++;+ },+ pause: async () => {+ paused = true;+ },+ status: async () => ({ paused, activeRequests: 0, pendingCleanup: 0 }),+ retain: async (name, bytes) => {+ evidence.push({ name, bytes: Buffer.from(bytes) });+ },+ mcp: async (account, request) => {+ assert.equal(request.headers.get('authorization'), null);+ assert.equal(request.headers.get('cookie'), null);+ const routed = await routeEdgeMcp(request);+ if (routed instanceof Response) return routed;+ if (++calls > lifecycleBudget.coordinator) return new Response('quota', { status: 429 });+ const handler = host(+ ownerName(account),+ { publicOrigin: fixtureOrigin },+ evaluator,+ async (input) => {+ renders++;+ const size = input.size ?? input.width;+ return {+ ok: true,+ rendererId: 'dawn-vulkan:software-fixture',+ viewsPng: (input.viewDirs ?? input.cameras).map(() =>+ encodePng(new Uint8Array(size * size * 3).fill(128), size, size),+ ),+ derivativeFidelity: {+ materialFaithful: true,+ inputGlbSha256: `sha256:${createHash('sha256').update(input.glb).digest('hex')}`,+ },+ };+ },+ );+ const response = await handler.fetch(new Request('http://kiln-native.internal/mcp', routed));+ const bytes = await response.arrayBuffer();+ await handler.close();+ return new Response(bytes, { status: response.status, headers: response.headers });+ },+ download: async (account, path, signal) => {+ if (account === 'anonymous') return new Response(null, { status: 401 });+ return namespace+ .getByName(ownerName(account))+ .fetch(`https://tenant.internal/internal${path}`, { signal });+ },+ dropMaterial: async (materialId, revisionId) => {+ const tenant = namespace.getByName(ownerName('owner'));+ const group = await (+ await tenant.fetch(+ `https://tenant.internal/internal/materials/${materialId}/${revisionId.slice(7)}`,+ )+ ).json();+ assert.equal(+ (+ await tenant.fetch(`https://tenant.internal/internal/groups/${group.id}`, {+ method: 'DELETE',+ })+ ).status,+ 200,+ );+ },+ };+ const result = await runLifecycleOnce(store, ports);+ assert.equal(result.passed, true, JSON.stringify(result));+ assert.equal(result.results.length, 21);+ assert.deepEqual(+ result.results.map((value) => value.name),+ lifecycleCases,+ );+ assert.equal(calls, 15);+ assert.equal(evaluations, 3);+ assert.equal(renders, 3);+ assert.equal(opened, 1);+ assert.equal(closed, 1);+ assert.equal(paused, true);+ assert.equal(+ result.results.find((value) => value.name === 'manifest').savedEngine,+ `cloudflare-container:${expectedImage}`,+ );+ assert.equal(evidence.length, 20);+ assert.deepEqual(await runLifecycleOnce(store, ports), result);+ assert.equal(calls, 15);+ assert.equal(opened, 1);+ assert.equal(closed, 1);+ // Reuse actual engine responses to attack the trial's acceptance checks.+ const recorded = new Map(evidence.map((item) => [item.name, item.bytes]));+ const sourceMessage = JSON.parse(recorded.get('source').toString());+ const source = JSON.parse(+ sourceMessage.result.content.find((item) => item.type === 'text').text,+ ).code;+ const attacks = [+ ['foreign-download', () => Buffer.from(source)],+ ['anonymous-download', () => Buffer.from(source)],+ [+ 'manifest',+ (bytes) => {+ const message = JSON.parse(bytes.toString());+ const manifest = JSON.parse(message.result.contents[0].text);+ manifest.build.engine = 'unverified';+ message.result.contents[0].text = JSON.stringify(manifest);+ return Buffer.from(JSON.stringify(message));+ },+ ],+ [+ 'glb-download',+ (bytes) => {+ const changed = Buffer.from(bytes);+ changed[changed.length - 1] ^= 1;+ return changed;+ },+ ],+ [+ 'foreign-source',+ (bytes) => {+ const message = JSON.parse(bytes.toString());+ message.debug = { source };+ return Buffer.from(JSON.stringify(message));+ },+ ],+ [+ 'foreign-source',+ (bytes) => {+ const message = JSON.parse(bytes.toString());+ message.debug = { text: JSON.stringify({ code: source }) };+ return Buffer.from(JSON.stringify(message));+ },+ ],+ [+ 'foreign-material',+ (bytes) => {+ const message = JSON.parse(bytes.toString());+ const materialMessage = JSON.parse(recorded.get('material-get').toString());+ message.debug = JSON.parse(+ materialMessage.result.content.find((item) => item.type === 'text').text,+ ).material;+ return Buffer.from(JSON.stringify(message));+ },+ ],+ ];+ for (const [failedCase, mutate] of attacks) {+ let index = 0,+ sealed = false,+ halted = false;+ const replayStoreValues = new Map();+ const replayStore = {+ get: async (key) => structuredClone(replayStoreValues.get(key)),+ put: async (key, value) => {+ replayStoreValues.set(key, structuredClone(value));+ },+ transaction: async (fn) => fn(replayStore),+ };+ const response = () => {+ const name = lifecycleCases[index++];+ const original = recorded.get(name);+ assert(original, name);+ const bytes = name === failedCase ? mutate(original) : original;+ return new Response(bytes, {+ status: result.results.find((item) => item.name === name).status,+ headers: { 'cache-control': 'no-store' },+ });+ };+ const failed = await runLifecycleOnce(replayStore, {+ expectedImage,+ open: async () => {},+ close: async () => {+ sealed = true;+ },+ pause: async () => {+ halted = true;+ },+ status: async () => ({ paused: halted, activeRequests: 0, pendingCleanup: 0 }),+ mcp: async () => response(),+ download: async () => response(),+ retain: async () => {},+ dropMaterial: async () => {+ index++;+ },+ });+ assert.equal(failed.passed, false, failedCase);+ assert.equal(failed.results.at(-1).name, failedCase);+ assert.equal(failed.results.at(-1).passed, false);+ assert.equal(index, lifecycleCases.indexOf(failedCase) + 1);+ assert.equal(sealed && halted, true);+ }+});++test('native MCP uses the material-view port and retains truthful CPU fallback', async () => {+ const metal =+ 'function build(){return new THREE.Mesh(boxGeo(1,1,1),pbrMaterial({albedo:0x8899aa,metalness:0.5,roughness:0.5}));}';+ let views = 0;+ const evaluate = {+ render: async (code, options) => {+ assert.equal(code, metal);+ return renderGLB(code, options);+ },+ };+ const handler = host('material', {}, evaluate, async (request, execution) => {+ views++;+ assert(execution.signal);+ assert.equal(execution.signal.aborted, false);+ const size = request.size ?? request.width;+ return {+ ok: true,+ rendererId: 'dawn-vulkan:software-fixture',+ viewsPng: (request.viewDirs ?? request.cameras).map(() =>+ encodePng(new Uint8Array(size * size * 3).fill(128), size, size),+ ),+ derivativeFidelity: {+ materialFaithful: true,+ inputGlbSha256: `sha256:${createHash('sha256').update(request.glb).digest('hex')}`,+ },+ };+ });+ const result = await rpc(handler, 'tools/call', {+ name: 'kiln_render',+ arguments: { code: metal, capture: { preset: '1x1' } },+ });+ assert.equal(result.isError, undefined);+ assert.equal(views, 1);+ assert.ok(result.content.some((value) => value.type === 'image'));+ assert.match(JSON.stringify(result), /full-material/);+ const unavailable = host('material-fallback', {}, evaluate, async () => ({+ ok: false,+ rendererId: 'unavailable',+ error: 'Hosted software rendering is unavailable',+ }));+ const fallback = await rpc(unavailable, 'tools/call', {+ name: 'kiln_render',+ arguments: { code: metal, capture: { preset: '1x1' } },+ });+ assert.equal(fallback.isError, undefined);+ assert.ok(fallback.content.some((value) => value.type === 'image'));+ assert.match(JSON.stringify(fallback), /geometry-flat/);+});+test('native HTTP validates its private route, Origin, body and credentials before engine dispatch', async () => {const handler = host('requests');for (const [url, status] of [@@ -310,6 +940,26 @@ test('production runtime refuses an unqualified host and never selects a trusted);});+test('explicit container runtime loads the installed engine and fails closed when its remote evaluator is unavailable', async () => {+ let calls = 0;+ const runtime = await loadContainerMcpRuntime({+ fetch: async () => {+ calls++;+ throw new Error('PRIVATE_NETWORK_ERROR');+ },+ });+ assert.equal(typeof runtime.createServer, 'function');+ const handler = host('remote-failure', {}, runtime.evaluatorPort);+ const result = await rpc(handler, 'tools/call', {+ name: 'kiln_render',+ arguments: { code: source },+ });+ assert.equal(result.isError, true);+ assert.ok(!result.content.some((item) => item.type === 'image'));+ assert.doesNotMatch(JSON.stringify(result), /PRIVATE_NETWORK_ERROR/);+ assert.ok(calls > 0);+});+test('slow request bodies expire, cancel their stream and release admission', async () => {let cancelled = false;const handler = host('slow-body', { requestTimeoutMs: 30 });diff --git a/hosting/test/native-render.test.mjs b/hosting/test/native-render.test.mjsnew file mode 100644index 00000000..1a3b8e8c--- /dev/null+++ b/hosting/test/native-render.test.mjs@@ -0,0 +1,224 @@+import assert from 'node:assert/strict';+import { before, test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { copyFile } from 'node:fs/promises';+import { spawnSync } from 'node:child_process';+import { renderGLB } from '../../lib/render.js';+import { encodePng } from '../../lib/views/png.js';+import { captureViewPngsViaPort } from '../../lib/views/port.js';++let createNativeRenderPort, encodeRenderRequest, decodeRenderRequest, encodeRenderResult;+let glb;+const rendererId = 'dawn-vulkan:llvmpipe-fixture';+const request = () => ({ glb, viewDirs: [[1, 0.4, 1]], size: 32, backdrop: 'dark' });+const png = () => encodePng(new Uint8Array(32 * 32 * 3).fill(100), 32, 32);+before(async () => {+ const output = new URL('../../.cache/hosted-native-render/native-render.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-render.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: {+ '@instruktlabs/kiln/composer': fileURLToPath(+ new URL('../../lib/composer/index.js', import.meta.url),+ ),+ },+ });+ ({ createNativeRenderPort, encodeRenderRequest, decodeRenderRequest, encodeRenderResult } =+ await import(output));+ ({ glb } = await renderGLB(+ 'function build(){return new THREE.Mesh(boxGeo(1,1,1),gameMaterial(0x8899aa));}',+ ));+});+function success(input, extra = {}) {+ return encodeRenderResult(input, {+ rendererId,+ backend: 'vulkan',+ software: true,+ views: [png()],+ ...extra,+ });+}+test('software transport binds exact GLB bytes and uses only the fixed private route', async () => {+ let calls = 0;+ const port = createNativeRenderPort({+ fetch: async (incoming) => {+ calls++;+ assert.equal(incoming.url, 'http://kiln-renderer.internal/render');+ assert.equal(incoming.redirect, 'error');+ assert.equal(incoming.credentials, 'omit');+ assert.equal(incoming.headers.get('x-kiln-deadline-ms'), '30000');+ assert.equal(incoming.headers.get('authorization'), null);+ const input = decodeRenderRequest(new Uint8Array(await incoming.arrayBuffer()));+ assert.deepEqual(input.request.glb, glb);+ assert.equal(input.request.backdrop, 'dark');+ return new Response(success(input));+ },+ });+ const result = await port(request());+ assert.equal(calls, 1);+ assert.equal(result.ok, true);+ assert.equal(result.rendererId, rendererId);+ assert.deepEqual(result.viewsPng[0], png());+ assert.equal(result.derivativeFidelity.materialFaithful, true);+});+test('camera mode preserves exact cameras, dimensions and presentation identity', async () => {+ const camera = {+ position: [3, 2, 4],+ target: [0, 0, 0],+ up: [0, 1, 0],+ fovDeg: 50,+ aspect: 1,+ near: 0.1,+ far: 100,+ };+ const input = {+ glb,+ cameras: [camera],+ width: 32,+ height: 32,+ lightingPresetId: 'review-neutral-v1',+ };+ const port = createNativeRenderPort({+ fetch: async (req) => {+ const parsed = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));+ assert.deepEqual(parsed.request.cameras, [camera]);+ return new Response(+ success(parsed, {+ cameras: [camera],+ width: 32,+ height: 32,+ lightingPresetId: 'review-neutral-v1',+ }),+ );+ },+ });+ const result = await port(input);+ assert.equal(result.ok, true);+ assert.deepEqual(result.cameras, [camera]);+ assert.equal(result.width, 32);+});+test('input limits reject unknown authority, invalid cameras, excessive pixels and oversized GLBs before transport', async () => {+ let calls = 0;+ const port = createNativeRenderPort({+ fetch: async () => {+ calls++;+ throw Error('must not run');+ },+ });+ for (const value of [+ { ...request(), tenant: 'other' },+ { ...request(), viewDirs: [[0, 0, 0]] },+ { ...request(), size: 2048 },+ { ...request(), viewDirs: Array.from({ length: 12 }, () => [1, 0, 0]), size: 1024 },+ { ...request(), glb: new Uint8Array(4 * 1024 * 1024 + 1) },+ ]) {+ assert.equal((await port(value)).ok, false);+ }+ assert.equal(calls, 0);+ const wire = JSON.parse(new TextDecoder().decode(encodeRenderRequest(request()).bytes));+ for (const value of [+ { ...wire, tenant: 'other' },+ { ...wire, glbBase64: '!!!' },+ { ...wire, options: { ...wire.options, glb: 'replace' } },+ { ...wire, version: 'future' },+ ]) {+ assert.throws(() => decodeRenderRequest(new TextEncoder().encode(JSON.stringify(value))));+ }+});+test('forged result identity, GPU claims, dimensions and excessive output fail closed without echoing diagnostics', async () => {+ for (const change of [+ (r) => ({ ...r, requestId: 'other' }),+ (r) => ({ ...r, inputGlbSha256: `sha256:${'a'.repeat(64)}` }),+ (r) => ({ ...r, software: false }),+ (r) => ({ ...r, viewsBase64: [] }),+ (r) => ({ ...r, viewsBase64: ['!!!!'] }),+ (r) => ({ ...r, unknown: 'PRIVATE_SOURCE' }),+ ]) {+ const port = createNativeRenderPort({+ fetch: async (req) => {+ const input = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));+ return Response.json(change(JSON.parse(new TextDecoder().decode(success(input)))));+ },+ });+ const result = await port(request());+ assert.equal(result.ok, false);+ assert.ok(!JSON.stringify(result).includes('PRIVATE_SOURCE'));+ }+ for (const respond of [+ () => new Response('PRIVATE_PATH', { status: 503 }),+ () => new Response('x', { headers: { 'content-length': '999999999' } }),+ ]) {+ const result = await createNativeRenderPort({ fetch: async () => respond() })(request());+ assert.equal(result.ok, false);+ assert.ok(!JSON.stringify(result).includes('PRIVATE_PATH'));+ }+});+test('the engine still owns PNG validation and failed-render fallback', async () => {+ const port = createNativeRenderPort({+ fetch: async (req) => {+ const input = decodeRenderRequest(new Uint8Array(await req.arrayBuffer()));+ return new Response(success(input, { views: [Buffer.from('invalid PNG')] }));+ },+ });+ const result = await captureViewPngsViaPort(port, glb, 1000, [[1, 0.4, 1]], 32);+ assert.equal(result.ok, false);+});+test('execution cancellation aborts the transport and disposes a late response', async () => {+ let entered,+ finish,+ cancelled = false;+ const started = new Promise((resolve) => {+ entered = resolve;+ });+ const waiting = new Promise((resolve) => {+ finish = resolve;+ });+ let signal;+ const port = createNativeRenderPort({+ fetch: async (req) => {+ signal = req.signal;+ entered();+ return waiting;+ },+ });+ const abort = new AbortController();+ const pending = port(request(), { signal: abort.signal });+ await started;+ abort.abort();+ assert.equal((await pending).ok, false);+ assert.equal(signal.aborted, true);+ finish(+ new Response(+ new ReadableStream({+ cancel() {+ cancelled = true;+ },+ }),+ ),+ );+ await new Promise((resolve) => setImmediate(resolve));+ assert.equal(cancelled, true);+});++test('one-shot renderer rejects malformed input before loading a graphics device', async () => {+ const entry = new URL('../../.cache/hosted-native-render/render.mjs', import.meta.url);+ await copyFile(new URL('../container/render.mjs', import.meta.url), entry);+ for (const input of [+ Buffer.from('{'),+ Buffer.from(encodeRenderRequest({ ...request(), glb: Buffer.from('not a GLB') }).bytes),+ ]) {+ const result = spawnSync(process.execPath, [fileURLToPath(entry)], {+ input,+ timeout: 10000,+ maxBuffer: 1024 * 1024,+ });+ assert.equal(result.status, 1);+ assert.equal(result.stdout.length, 0);+ assert.equal(result.stderr.toString(), 'Kiln software render input or execution failed.\n');+ }+});diff --git a/hosting/test/native-workspace.test.mjs b/hosting/test/native-workspace.test.mjsnew file mode 100644index 00000000..e840f3a1--- /dev/null+++ b/hosting/test/native-workspace.test.mjs@@ -0,0 +1,185 @@+import assert from 'node:assert/strict';+import { mkdir } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { createMaterialRecordV1 } from '../../lib/material-library-node.js';++let NativeMaterialWorkspace, first, second;+before(async () => {+ const output = new URL('../../.cache/native-workspace-test/workspace.mjs', import.meta.url);+ await mkdir(fileURLToPath(new URL('./', output)), { recursive: true });+ await build({+ entryPoints: [fileURLToPath(new URL('../src/native-workspace.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ packages: 'external',+ alias: Object.fromEntries(+ [+ ['workspace', 'workspace'],+ ['material-library', 'material-library'],+ ['material-library/node', 'material-library-node'],+ ].map(([name, file]) => [+ `@instruktlabs/kiln/${name}`,+ fileURLToPath(new URL(`../../lib/${file}.js`, import.meta.url)),+ ]),+ ),+ });+ ({ NativeMaterialWorkspace } = await import(output));+ const create = (seed) =>+ createMaterialRecordV1({+ materialId: 'stone',+ name: 'Stone',+ tileable: true,+ sources: [+ {+ id: 'authored',+ kind: 'procedural',+ provider: 'Kiln',+ creator: 'Test author',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+ },+ ],+ maps: [+ {+ slot: 'baseColor',+ sourceId: 'authored',+ transforms: [],+ procedural: {+ schemaVersion: 2,+ size: 8,+ usage: 'albedo',+ layers: [+ { op: 'noise', colorA: 0x779944, colorB: 0xeeeecc, seed, scale: 4, octaves: 2 },+ ],+ },+ },+ ],+ });+ [first, second] = await Promise.all([create(17), create(18)]);+});+const pin = (record) => ({+ resourceId: record.manifest.materialId,+ revisionId: record.manifest.revisionId,+ sha256: record.manifest.revisionId,+});+const library = {+ read: async (id, rev) => {+ const record = [first, second].find(+ (r) => r.manifest.materialId === id && r.manifest.revisionId === rev,+ );+ if (!record) throw Error('not found');+ return structuredClone(record);+ },+};+const deferred = () => {+ let resolve;+ const promise = new Promise((done) => {+ resolve = done;+ });+ return { promise, resolve };+};++test('material binding stays isolated across overlapping operations and disappears outside them', async () => {+ const workspace = new NativeMaterialWorkspace(library);+ const firstReady = deferred(),+ secondReady = deferred();+ const run = (record, ready, other) =>+ workspace.run({ materialDependencies: [pin(record)] }, async () => {+ ready.resolve();+ await other.promise;+ assert.deepEqual(workspace.current().materialDependencies, [pin(record)]);+ assert.deepEqual(workspace.current().materialResources.records[0].manifest, record.manifest);+ assert.equal(workspace.current().project, undefined);+ return record.manifest.revisionId;+ });+ assert.equal(workspace.current(), undefined);+ const results = await Promise.all([+ run(first, firstReady, secondReady),+ run(second, secondReady, firstReady),+ ]);+ assert.deepEqual(results, [first.manifest.revisionId, second.manifest.revisionId]);+ assert.equal(workspace.current(), undefined);+});++test('nested operations inherit pins, explicitly replace revisions and can select standalone without inherited pins', async () => {+ const workspace = new NativeMaterialWorkspace(library);+ await workspace.run({ materialDependencies: [pin(first)] }, async () => {+ const binding = workspace.current();+ await workspace.run({}, async () => assert.equal(workspace.current(), binding));+ await workspace.run({ materialDependencies: [pin(second)] }, async () => {+ assert.deepEqual(workspace.current().materialDependencies, [pin(second)]);+ });+ await workspace.run({ projectId: null }, async () => {+ assert.deepEqual(workspace.current().materialDependencies, []);+ assert.deepEqual(workspace.current().materialResources.records, []);+ });+ assert.equal(workspace.current(), binding);+ });+});++test('invalid identities, hashes, oversized pin sets and unsupported projects fail before loading material bytes', async () => {+ let reads = 0,+ executions = 0;+ const workspace = new NativeMaterialWorkspace({+ read: async (...args) => {+ reads++;+ return library.read(...args);+ },+ });+ for (const selection of [+ { projectId: 'local-only' },+ { projectRevision: `r_0000000001_${'a'.repeat(64)}` },+ { materialDependencies: [{ ...pin(first), resourceId: '../escape' }] },+ { materialDependencies: [{ ...pin(first), revisionId: `${first.manifest.revisionId}\n` }] },+ {+ materialDependencies: [+ pin(first),+ { ...pin(second), resourceId: 'other', sha256: first.manifest.revisionId },+ ],+ },+ {+ materialDependencies: Array.from({ length: 17 }, (_, i) => ({+ ...pin(first),+ resourceId: `resource-${i}`,+ })),+ },+ ])+ await assert.rejects(+ workspace.run(selection, async () => {+ executions++;+ }),+ );+ assert.equal(reads, 0);+ assert.equal(executions, 0);+});++test('missing and identity-swapped library records cannot enter an evaluation binding', async () => {+ const missing = new NativeMaterialWorkspace({+ read: async () => {+ throw Error('private transport detail');+ },+ });+ await assert.rejects(+ missing.run({ materialDependencies: [pin(first)] }, async () =>+ assert.fail('must not execute'),+ ),+ (error) =>+ /Locked material unavailable/.test(error.message) &&+ !error.message.includes('private transport detail'),+ );+ const swapped = new NativeMaterialWorkspace({ read: async () => second });+ await assert.rejects(+ swapped.run({ materialDependencies: [pin(first)] }, async () =>+ assert.fail('must not execute'),+ ),+ /identity/,+ );+});diff --git a/hosting/test/operations-worker.ts b/hosting/test/operations-worker.tsnew file mode 100644index 00000000..dabe2f01--- /dev/null+++ b/hosting/test/operations-worker.ts@@ -0,0 +1,46 @@+import gateway, { type Env } from '../src/worker';+import { readOperationalHealth } from '../src/operations';++// Captured datapoints and faults are confined to this local fixture.+const points: AnalyticsEngineDataPoint[] = [];+export default {+ async fetch(request: Request, bindings: Env, ctx: ExecutionContext) {+ const url = new URL(request.url);+ const env = {+ ...bindings,+ OPERATIONS: {+ writeDataPoint(point: AnalyticsEngineDataPoint) {+ if (request.headers.has('x-fixture-metrics-failure'))+ throw new Error('private-metrics-error');+ points.push(point);+ },+ },+ NATIVE_COMPUTE: {+ async health() {+ return { paused: false, activeRequests: 0, pendingCleanup: 0, maxConcurrent: 2 };+ },+ },+ } as unknown as Env;+ if (request.headers.has('x-fixture-database-failure'))+ env.ACCOUNTS = {+ withSession() {+ throw new Error('private-database-error');+ },+ } as unknown as D1Database;+ if (url.pathname === '/fixture/points') return Response.json(points.splice(0));+ if (url.pathname === '/fixture/health')+ return Response.json(await readOperationalHealth(env, 1000000));+ if (url.pathname === '/fixture/scheduled') {+ try {+ await gateway.scheduled(+ { cron: '* * * * *', scheduledTime: Date.now(), noRetry() {} },+ env,+ );+ return new Response('ok');+ } catch {+ return new Response('unavailable', { status: 503 });+ }+ }+ return gateway.fetch(request, env, ctx);+ },+};diff --git a/hosting/test/operations.test.mjs b/hosting/test/operations.test.mjsnew file mode 100644index 00000000..3dc51af9--- /dev/null+++ b/hosting/test/operations.test.mjs@@ -0,0 +1,236 @@+import assert from 'node:assert/strict';+import { before, after, test } from 'node:test';+import { build } from 'esbuild';+import { mkdir } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { migrateAccounts } from './database.mjs';+import { rateLimitBindings } from './rate-limit-bindings.mjs';++let recordResponse, recordHealth, readOperationalHealth, runtime, database;+before(async () => {+ const output = new URL('../../.cache/operations-tests/operations.mjs', import.meta.url);+ await mkdir(fileURLToPath(new URL('.', output)), { recursive: true });+ await build({+ entryPoints: [fileURLToPath(new URL('../src/operations.ts', import.meta.url))],+ bundle: true,+ format: 'esm',+ platform: 'node',+ outfile: fileURLToPath(output),+ });+ ({ recordResponse, recordHealth, readOperationalHealth } = await import(output));+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./operations-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['global_fetch_strictly_public'],+ bindings: { PUBLIC_ORIGIN: 'https://kiln.example.com' },+ d1Databases: ['ACCOUNTS'],+ kvNamespaces: ['OAUTH_KV'],+ ratelimits: rateLimitBindings,+ outboundService: () => {+ throw new Error('External I/O forbidden');+ },+ }),+ );+ database = await runtime.getD1Database('ACCOUNTS');+ await migrateAccounts(database);+});+after(async () => runtime?.dispose());+const send = (path, options) => runtime.dispatchFetch(`https://kiln.example.com${path}`, options);+function fixture() {+ const points = [];+ return { points, env: { OPERATIONS: { writeDataPoint: (point) => points.push(point) } } };+}+const healthy = {+ deletion: { pending: 2, oldestPendingMs: 1000, overdue: 0 },+ compute: { paused: false, activeRequests: 1, pendingCleanup: 0, maxConcurrent: 2 },+};+test('response observations emit only a fixed class, validated status and finite elapsed time', () => {+ const f = fixture();+ recordResponse(f.env, '/downloads/private-capability/source.kiln.js', 429, 123.7);+ assert.deepEqual(f.points, [+ { indexes: ['http'], blobs: ['kiln.ops.v1', 'http', 'download', '429'], doubles: [1, 124] },+ ]);+ for (const [path, status, duration] of [+ ['/private-identity', 200, 4],+ ['/oauth/google/callback', 303, 5],+ ])+ recordResponse(f.env, path, status, duration);+ assert(!JSON.stringify(f.points).includes('private'));+ assert.equal(f.points[1].blobs[2], 'other');+ assert.equal(f.points[2].blobs[2], 'callback');+ for (const status of [NaN, Infinity, 200.5, 99, 600]) recordResponse(f.env, '/', status, 1);+ for (const duration of [NaN, Infinity, -1]) recordResponse(f.env, '/', 200, duration);+ assert.equal(f.points.length, 3);+});+test('health observations contain aggregate values only and unknown is never healthy zero', () => {+ const f = fixture();+ recordHealth(+ f.env,+ { ...healthy, account: 'private-identity', exception: 'private-secret' },+ true,+ );+ assert.deepEqual(f.points, [+ {+ indexes: ['health:deletion'],+ blobs: ['kiln.ops.v1', 'health', 'deletion', 'ok'],+ doubles: [1, 2, 1000, 0, 1],+ },+ {+ indexes: ['health:compute'],+ blobs: ['kiln.ops.v1', 'health', 'compute', 'ok'],+ doubles: [1, 0, 1, 0, 2],+ },+ ]);+ recordHealth(f.env, { deletion: null, compute: null }, false);+ assert.deepEqual(f.points[2], {+ indexes: ['health:deletion'],+ blobs: ['kiln.ops.v1', 'health', 'deletion', 'unavailable'],+ doubles: [1, -1, -1, -1, 0],+ });+ assert.deepEqual(f.points[3], {+ indexes: ['health:compute'],+ blobs: ['kiln.ops.v1', 'health', 'compute', 'unavailable'],+ doubles: [1, -1, -1, -1, -1],+ });+ assert(!JSON.stringify(f.points).includes('private'));+});+test('missing or failing telemetry never throws or serializes provider errors', () => {+ for (const env of [+ {},+ {+ OPERATIONS: {+ writeDataPoint() {+ throw new Error('private-secret');+ },+ },+ },+ ]) {+ assert.doesNotThrow(() => recordResponse(env, '/mcp', 200, 12));+ assert.doesNotThrow(() => recordHealth(env, healthy, true));+ }+});+test('a failed compute check does not discard deletion health and vice versa', async () => {+ const database = (value) => ({+ withSession(mode) {+ assert.equal(mode, 'first-primary');+ return {+ prepare() {+ return {+ bind(now, overdueBefore) {+ assert.equal(now, 1000000);+ assert.equal(overdueBefore, 100000);+ return { first: async () => value };+ },+ };+ },+ };+ },+ });+ const env = {+ ACCOUNTS: database(healthy.deletion),+ NATIVE_COMPUTE: {+ health: async () => {+ throw new Error('private-secret');+ },+ },+ };+ assert.deepEqual(await readOperationalHealth(env, 1000000), {+ deletion: healthy.deletion,+ compute: null,+ });+ env.ACCOUNTS = {+ withSession() {+ throw new Error('private-secret');+ },+ };+ env.NATIVE_COMPUTE.health = async () => healthy.compute;+ assert.deepEqual(await readOperationalHealth(env, 1000000), {+ deletion: null,+ compute: healthy.compute,+ });+ env.NATIVE_COMPUTE.health = async () => ({ ...healthy.compute, activeRequests: 'private' });+ assert.deepEqual(await readOperationalHealth(env, 1000000), { deletion: null, compute: null });+});+test('health collection has a bounded deadline and reports stalled reads as unavailable', async () => {+ const env = {+ ACCOUNTS: {+ withSession() {+ throw new Error('offline');+ },+ },+ NATIVE_COMPUTE: { health: () => new Promise(() => {}) },+ };+ assert.deepEqual(await readOperationalHealth(env), { deletion: null, compute: null });+});++test('primary-D1 deletion health counts pending jobs and age without exposing rows or completed receipts', async () => {+ const empty = await (await send('/fixture/health')).json();+ assert.deepEqual(empty.deletion, { pending: 0, oldestPendingMs: 0, overdue: 0 });+ for (const [id, phase, created] of [+ ['private-old', 'storage', 10000],+ ['private-new', 'grants', 999000],+ ['private-completed', 'complete', 1],+ ])+ await database+ .prepare(+ 'INSERT INTO kiln_deletions (id,receipt_hash,phase,created_at,updated_at,retry_at) VALUES (?,?,?,?,?,?)',+ )+ .bind(id, id, phase, created, created, created)+ .run();+ const response = await send('/fixture/health');+ const text = await response.text();+ assert(!text.includes('private'));+ assert.deepEqual(JSON.parse(text).deletion, { pending: 2, oldestPendingMs: 990000, overdue: 1 });+ await database.exec('DELETE FROM kiln_deletions');+});++test('actual gateway emits one sanitized response point and keeps telemetry errors out of responses', async () => {+ for (const broken of [false, true]) {+ const response = await send('/unknown-private-name?code=private-code', {+ headers: {+ authorization: 'Bearer private-token',+ cookie: 'private-cookie',+ ...(broken ? { 'x-fixture-metrics-failure': '1' } : {}),+ },+ });+ assert.equal(response.status, 404);+ assert.equal(await response.text(), 'Not found');+ const points = await (await send('/fixture/points')).json();+ assert.equal(points.length, broken ? 0 : 1);+ if (!broken) {+ assert.deepEqual(points[0].blobs, ['kiln.ops.v1', 'http', 'other', '404']);+ assert.equal(points[0].doubles[0], 1);+ assert(Number.isSafeInteger(points[0].doubles[1]));+ }+ assert(!JSON.stringify(points).includes('private'));+ }+});++test('actual scheduled recovery emits both health components and reports a primary outage as unavailable', async () => {+ assert.equal((await send('/fixture/scheduled')).status, 200);+ let points = await (await send('/fixture/points')).json();+ assert.equal(points.length, 2);+ assert.deepEqual(points[0].doubles, [1, 0, 0, 0, 1]);+ assert.deepEqual(points[1].doubles, [1, 0, 0, 0, 2]);+ assert.equal(+ (await send('/fixture/scheduled', { headers: { 'x-fixture-database-failure': '1' } })).status,+ 503,+ );+ points = await (await send('/fixture/points')).json();+ assert.equal(points[0].blobs[3], 'unavailable');+ assert.deepEqual(points[0].doubles, [1, -1, -1, -1, 0]);+ assert.equal(points[1].blobs[3], 'ok');+ assert(!JSON.stringify(points).includes('private'));+});diff --git a/hosting/test/probe-observation.test.mjs b/hosting/test/probe-observation.test.mjsnew file mode 100644index 00000000..069300c3--- /dev/null+++ b/hosting/test/probe-observation.test.mjs@@ -0,0 +1,58 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';++let observeContainer;+before(async () => {+ const output = new URL('../../.cache/hosted-probe-test/observe.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/observe-container.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ observeContainer } = await import(output));+});++test('probe observation retains only the first failed native operation, never exception text', async () => {+ const actual = {+ start() {+ assert.equal(this, actual);+ },+ async exec() {+ throw new Error('private runtime diagnostic');+ },+ async destroy() {+ throw new Error('later cleanup diagnostic');+ },+ };+ const observed = observeContainer(actual);+ observed.container.start();+ await assert.rejects(observed.container.exec([]));+ await assert.rejects(observed.container.destroy());+ assert.equal(observed.failure(), 'exec');+ assert.equal(JSON.stringify(observed.failure()).includes('private'), false);+});++test('probe fixture substitution retains native exec options and observes synchronous failure', () => {+ const options = { user: '1000:1000', stdin: 'pipe' };+ const observed = observeContainer(+ {+ exec(command, received) {+ assert.deepEqual(command, [+ '/usr/local/bin/node',+ '--input-type=module',+ '-e',+ 'fixed fixture',+ ]);+ assert.equal(received, options);+ throw new Error('native synchronous failure');+ },+ },+ 'fixed fixture',+ );+ assert.throws(() => observed.container.exec(['original'], options));+ assert.equal(observed.failure(), 'exec');+});diff --git a/hosting/test/provider-probe-worker.ts b/hosting/test/provider-probe-worker.tsnew file mode 100644index 00000000..52e70d31--- /dev/null+++ b/hosting/test/provider-probe-worker.ts@@ -0,0 +1,14 @@+import worker, { KilnProbeRun, KilnProbeJob } from '../probe/worker';+export { KilnProbeRun, KilnProbeJob };+export default {+ async fetch(request: Request, _env: unknown, ctx: ExecutionContext) {+ if (new URL(request.url).pathname === '/test-trigger') {+ const bindings = ctx.exports as unknown as {+ KilnProbeRun: DurableObjectNamespace<KilnProbeRun>;+ };+ const runs = bindings.KilnProbeRun;+ return Response.json(await runs.getByName('test').run());+ }+ return worker.fetch();+ },+};diff --git a/hosting/test/provider-probe.test.mjs b/hosting/test/provider-probe.test.mjsnew file mode 100644index 00000000..79e0128f--- /dev/null+++ b/hosting/test/provider-probe.test.mjs@@ -0,0 +1,204 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';++let runProbeOnce;+let probeCases;+test('the manifest qualification has no public route or automatic trigger and pins the proven runtime image', async () => {+ const config = JSON.parse(+ await readFile(new URL('../probe/qualification.wrangler.jsonc', import.meta.url), 'utf8'),+ );+ assert.equal(config.workers_dev, false);+ assert.equal(config.preview_urls, false);+ assert.deepEqual(config.routes, []);+ assert.equal(config.triggers, undefined);+ assert.equal(config.main, './worker.ts');+ assert.equal(config.containers.length, 1);+ assert.equal(config.containers[0].scheduling_policy, 'durable_object');+ assert.equal(config.containers[0].class_name, 'KilnProbeJob');+ assert.equal(config.containers[0].observability.logs.enabled, false);+ assert.equal(+ config.containers[0].images.kiln.image,+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8',+ );+ assert.deepEqual(config.exports, {+ KilnProbeControl: { type: 'worker' },+ KilnProbeRun: { type: 'durable-object', storage: 'sqlite' },+ KilnProbeJob: { type: 'durable-object', storage: 'sqlite' },+ });+});+before(async () => {+ const output = new URL('../../.cache/hosted-probe-test/run-once.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/run-once.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ runProbeOnce, probeCases } = await import(output));+});++function storage() {+ const records = new Map();+ let tail = Promise.resolve();+ const store = {+ async get(key) {+ return structuredClone(records.get(key));+ },+ async put(key, value) {+ records.set(key, structuredClone(value));+ },+ transaction(callback) {+ const result = tail.then(() => callback(store));+ tail = result.catch(() => {});+ return result;+ },+ };+ return store;+}++test('private probe claims its fixed budget once across concurrent and later triggers', async () => {+ const store = storage();+ const called = [];+ const execute = async (name) => {+ called.push(name);+ return { name, passed: true };+ };+ await Promise.all([runProbeOnce(store, execute), runProbeOnce(store, execute)]);+ const final = await runProbeOnce(store, execute);+ // The fixed candidate has four cases. Any new deployment requires its own+ // approval; this code cannot reset the exhausted earlier trial allowance.+ assert.deepEqual(probeCases, ['engine-a', 'network', 'write-marker', 'read-marker']);+ assert.deepEqual(called, probeCases);+ assert.equal(final.state, 'finished');+ assert.equal(final.results.length, 4);+});++test('private probe stops after a failed case and does not spend again on retry', async () => {+ const store = storage();+ let count = 0;+ const execute = async (name) => {+ count++;+ return { name, passed: false, reason: 'CHECK_FAILED' };+ };+ assert.equal((await runProbeOnce(store, execute)).results[0].passed, false);+ await runProbeOnce(store, execute);+ assert.equal(count, 1);+});++test('an interrupted claim is not silently replayed and exceptions do not disclose details', async () => {+ const store = storage();+ await store.put('run', { state: 'running', results: [] });+ await runProbeOnce(store, async () => {+ throw new Error('must never run');+ });+ const failure = await runProbeOnce(storage(), async () => {+ throw new Error('private diagnostic');+ });+ assert.deepEqual(failure.results, [{ name: 'engine-a', passed: false, reason: 'PROBE_FAILED' }]);+});++test('the private Worker exposes no HTTP execution and its loopback namespaces fail closed without a container', async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./provider-probe-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ const runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports'],+ durableObjects: {+ RUN: { className: 'KilnProbeRun', useSQLite: true },+ JOB: { className: 'KilnProbeJob', useSQLite: true },+ },+ outboundService: async () => {+ throw new Error('No external requests');+ },+ }),+ );+ try {+ const denied = await runtime.dispatchFetch('http://localhost/execute', {+ method: 'POST',+ body: '{"code":"arbitrary"}',+ });+ assert.equal(denied.status, 404);+ const first = await (await runtime.dispatchFetch('http://localhost/test-trigger')).json();+ assert.equal(first.state, 'finished');+ assert.deepEqual(first.results, [+ { name: 'engine-a', passed: false, reason: 'CONTAINER_UNAVAILABLE' },+ ]);+ const second = await (await runtime.dispatchFetch('http://localhost/test-trigger')).json();+ assert.deepEqual(second, first);+ } finally {+ await runtime.dispose();+ }+});++test('private service RPC can trigger only the fixed retained probe and exposes no HTTP execution', async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('../probe/worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ const runtime = new Miniflare(+ convertV4MiniflareOptions({+ workers: [+ {+ name: 'private-probe',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports'],+ durableObjects: {+ RUN: { className: 'KilnProbeRun', useSQLite: true },+ JOB: { className: 'KilnProbeJob', useSQLite: true },+ },+ },+ {+ name: 'operator',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: {+ PROBE: { name: 'private-probe', entrypoint: 'KilnProbeControl' },+ },+ script: `export default {+ async fetch(request, env) {+ if (new URL(request.url).pathname === '/denied') return env.PROBE.fetch(request);+ return Response.json(await env.PROBE.runFixed());+ }+ }`,+ },+ ],+ }),+ );+ try {+ const operator = await runtime.getWorker('operator');+ const denied = await operator.fetch('http://localhost/denied', {+ method: 'POST',+ body: '{}',+ });+ assert.equal(denied.status, 404);+ const first = await (await operator.fetch('http://localhost/run')).json();+ assert.deepEqual(first, {+ state: 'finished',+ results: [{ name: 'engine-a', passed: false, reason: 'CONTAINER_UNAVAILABLE' }],+ });+ const second = await (await operator.fetch('http://localhost/run')).json();+ assert.deepEqual(second, first);+ } finally {+ await runtime.dispose();+ }+});diff --git a/hosting/test/public-pages.test.mjs b/hosting/test/public-pages.test.mjsnew file mode 100644index 00000000..8e2f41ff--- /dev/null+++ b/hosting/test/public-pages.test.mjs@@ -0,0 +1,100 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { after, before, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';+import { rateLimitBindings } from './rate-limit-bindings.mjs';++const origin = 'https://kiln.example.com';+let runtime;+let outgoing = 0;+before(async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('../src/worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ ratelimits: rateLimitBindings,+ bindings: { PUBLIC_ORIGIN: origin },+ // Deliberately no accounts, OAuth KV, provider credentials, storage or compute.+ outboundService: async () => {+ outgoing++;+ throw new Error('Public information must not contact another service');+ },+ }),+ );+});+after(async () => runtime?.dispose());++test('home and policy pages are available before sign-in without credentials or storage', async () => {+ for (const path of ['/', '/privacy', '/support', '/terms']) {+ const response = await runtime.dispatchFetch(origin + path);+ assert.equal(response.status, 200, path);+ assert.match(response.headers.get('content-type'), /text\/html/);+ assert.equal(response.headers.get('set-cookie'), null);+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal(response.headers.get('referrer-policy'), 'no-referrer');+ const html = await response.text();+ const nonce = html.match(/<style nonce="([a-f0-9]+)">/)[1];+ const csp = response.headers.get('content-security-policy');+ assert.ok(csp.includes(`style-src 'nonce-${nonce}'`));+ assert.match(csp, /default-src 'none'/);+ assert.match(csp, /frame-ancestors 'none'/);+ assert.doesNotMatch(html, /<script|<iframe|<link[^>]+href="https?:/i);+ for (const link of ['/privacy', '/support', '/terms', '/account'])+ assert.ok(html.includes(`href="${link}"`));+ }+ assert.equal(outgoing, 0);+});++test('public content explains hosted data access, retention, notices and private support', async () => {+ const home = await (await runtime.dispatchFetch(`${origin}/`)).text();+ assert.match(home, /JavaScript/);+ assert.match(home, /free within/i);+ assert.ok(home.includes(`${origin}/mcp`));+ const privacy = await (await runtime.dispatchFetch(`${origin}/privacy`)).text();+ for (const fact of [+ 'Google',+ 'GitHub',+ 'Cloudflare',+ 'seven days',+ '30 days',+ 'three months',+ 'in-app',+ 'retirement records',+ ])+ assert.ok(privacy.includes(fact), fact);+ assert.match(privacy, /support@instruktlabs\.com/);+ const support = await (await runtime.dispatchFetch(`${origin}/support`)).text();+ assert.match(support, /mailto:support@instruktlabs\.com/);+ assert.match(support, /public issues/i);+ assert.match(support, /passwords|tokens/);+});++test('information pages allow HEAD but reject mutation methods and query reflection', async () => {+ for (const path of ['/', '/privacy', '/support', '/terms']) {+ const head = await runtime.dispatchFetch(origin + path, { method: 'HEAD' });+ assert.equal(head.status, 200);+ assert.equal(await head.text(), '');+ const post = await runtime.dispatchFetch(origin + path, {+ method: 'POST',+ body: 'private-value',+ });+ assert.equal(post.status, 405);+ assert.equal(post.headers.get('allow'), 'GET, HEAD');+ const query = await runtime.dispatchFetch(`${origin}${path}?private-value=%3Cscript%3E`);+ assert.equal(query.status, 400);+ assert.doesNotMatch(await query.text(), /private-value|<script>/);+ }+ assert.equal((await runtime.dispatchFetch('https://foreign.example/privacy')).status, 421);+ assert.equal(outgoing, 0);+});diff --git a/hosting/test/public-plugin.test.mjs b/hosting/test/public-plugin.test.mjsnew file mode 100644index 00000000..899ff888--- /dev/null+++ b/hosting/test/public-plugin.test.mjs@@ -0,0 +1,141 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { after, test } from 'node:test';+import { unzipSync } from 'three/addons/libs/fflate.module.js';+import { packagePublicPlugin, validatePublicMetadata } from '../scripts/package-public-plugin.mjs';+import { createPublicTools } from '../src/public-tools.ts';++const repo = fileURLToPath(new URL('../../', import.meta.url));+const temporary = await realpath(await mkdtemp(join(tmpdir(), 'kiln-public-plugin-')));+after(async () => {+ const parent = await realpath(tmpdir());+ assert.ok(temporary.startsWith(parent + sep));+ await rm(temporary, { recursive: true, force: true });+});+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');+const json = async (path) => JSON.parse(await readFile(path, 'utf8'));++test('public draft ZIP has one hosted MCP, complete referenced assets and no local connector dependencies', async () => {+ const output = join(temporary, 'first');+ const receipt = await packagePublicPlugin(output);+ assert.equal(receipt.submissionReady, false);+ assert.ok(receipt.remaining.includes('live-client-review-cases'));+ assert.ok(receipt.remaining.includes('review-account-access'));+ const zip = await readFile(join(output, 'kiln-engine-draft.zip'));+ assert.equal(hash(zip), receipt.archive.sha256);+ const files = unzipSync(zip);+ const manifest = JSON.parse(Buffer.from(files['plugin.json']));+ assert.equal(manifest.name, 'kiln-engine');+ assert.equal(manifest.version, '1.0.0');+ const metadata = manifest.extensions['com.openai'];+ assert.ok(metadata.interface.shortDescription.length <= 30);+ assert.equal(metadata.interface.termsOfServiceURL, 'https://kiln.instruktlabs.com/terms');+ assert.equal(metadata.review.test_cases.positive.length, 5);+ assert.equal(metadata.review.test_cases.negative.length, 3);+ assert.equal(metadata.review.demo_recording_url, undefined, 'do not fabricate a demo URL');+ const mcp = JSON.parse(Buffer.from(files['mcp.json']));+ assert.deepEqual(mcp.mcpServers, {+ kiln: { type: 'streamable-http', url: 'https://kiln.instruktlabs.com/mcp' },+ });+ for (const path of [+ metadata.onboardingSkill,+ metadata.interface.logo,+ metadata.interface.composerIcon,+ ])+ assert.ok(files[path.slice(2)], path);+ const icon = Buffer.from(files['assets/icon.svg']).toString();+ assert.match(icon, /viewBox="0 0 64 64"/);+ assert.match(icon, /scale\(2\)/);+ assert.doesNotMatch(icon, /<script|<foreignObject|href=/);+ assert.ok(files.LICENSE);+ assert.ok(Buffer.from(files['README.md']).toString().includes('not a launched or approved'));+ for (const name of Object.keys(files)) {+ assert.ok(!name.startsWith('/') && !name.includes('..') && !name.includes('\\'));+ assert.ok(+ !/^(?:\.app|\.codex-plugin|\.claude-plugin|hooks|node_modules|src|dist|\.env)/.test(name),+ name,+ );+ assert.ok(!name.endsWith('.exe') && !name.includes('setup-workspace'));+ const bytes = Buffer.from(files[name]);+ assert.deepEqual(bytes, await readFile(join(output, 'plugin', name)));+ assert.equal(hash(bytes), receipt.files[name]);+ }+ assert.deepEqual(await json(join(output, 'receipt.json')), receipt);+});++test('shared references and recipe bytes are retained exactly and archive output is reproducible', async () => {+ const first = await packagePublicPlugin(join(temporary, 'second'));+ const second = await packagePublicPlugin(join(temporary, 'third'));+ assert.equal(first.archive.sha256, second.archive.sha256);+ for (const name of [+ 'program-contract.md',+ 'geometry-recipes.md',+ 'camera-recipes.md',+ 'reusable-frame.kiln.js',+ ]) {+ const original = await readFile(join(repo, 'skills/kiln-author-asset/references', name));+ const bundled = await readFile(+ join(temporary, 'second/plugin/skills/kiln-hosted/references', name),+ );+ assert.deepEqual(bundled, original, name);+ assert.equal(first.sources[`skills/kiln-author-asset/references/${name}`], hash(original));+ }+ const allowed = new Set(['plugin', 'kiln-engine-draft.zip', 'receipt.json']);+ assert.deepEqual(new Set(await readdir(join(temporary, 'second'))), allowed);+});++test('packaging refuses existing output before modifying its files', async () => {+ const output = join(temporary, 'existing');+ await mkdir(output);+ const sentinel = join(output, 'owner.txt');+ await writeFile(sentinel, 'preserve');+ await assert.rejects(packagePublicPlugin(output), /exists/i);+ assert.equal(await readFile(sentinel, 'utf8'), 'preserve');+ assert.deepEqual(await readdir(output), ['owner.txt']);+});++test('public metadata refuses private connectors, credential headers, hidden components and unadvertised review operations', async () => {+ const manifest = await json(join(repo, 'hosting/plugin/plugin.json'));+ const mcp = await json(join(repo, 'hosting/plugin/mcp.json'));+ const cases = await json(join(repo, 'hosting/plugin/review-cases.json'));+ const native = await json(join(repo, 'hosting/src/generated/edge-manifest.json'));+ const names = new Set(createPublicTools(native.tools).tools.map((tool) => tool.name));+ validatePublicMetadata(manifest, mcp, cases, names);+ for (const mutation of [+ (m) => {+ m.apps = './.app.json';+ },+ (m) => {+ m.hooks = './hooks.json';+ },+ (m) => {+ m.mcpServers = { extra: { command: 'npx', args: ['unreviewed'] } };+ },+ (m) => {+ m.extensions['com.openai'].reviewer_credentials = { password: 'fixture-only' };+ },+ (m) => {+ m.extensions['com.openai'].interface.logo = '../outside.svg';+ },+ ]) {+ const changed = structuredClone(manifest);+ mutation(changed);+ assert.throws(() => validatePublicMetadata(changed, mcp, cases, names));+ }+ const tokenHeader = structuredClone(mcp);+ tokenHeader.mcpServers.kiln.headers = { Authorization: 'Bearer fixture-only' };+ assert.throws(+ () => validatePublicMetadata(manifest, tokenHeader, cases, names),+ /private configuration/,+ );+ const unknown = structuredClone(cases);+ unknown.positive[0].tools_triggered = 'kiln_assets';+ assert.throws(+ () => validatePublicMetadata(manifest, mcp, unknown, names),+ /unadvertised operation/,+ );+});diff --git a/hosting/test/public-tools.test.mjs b/hosting/test/public-tools.test.mjsnew file mode 100644index 00000000..f8ae378e--- /dev/null+++ b/hosting/test/public-tools.test.mjs@@ -0,0 +1,83 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { test } from 'node:test';+import { createPublicTools, HOSTED_TOOL_SURFACE, hostedInstructions } from '../src/public-tools.ts';++const { tools: engine } = JSON.parse(+ await readFile(new URL('../src/generated/edge-manifest.json', import.meta.url), 'utf8'),+);++test('every reviewed engine operation has a separate hosted name and registry-derived fields', () => {+ const before = structuredClone(engine);+ const surface = createPublicTools(engine);+ assert.equal(HOSTED_TOOL_SURFACE, 'kiln.hosted-tools.v1');+ assert.equal(surface.tools.length, 26);+ for (const tool of engine) {+ const actions = tool.inputSchema.properties.action?.enum;+ const variants = actions+ ? actions.map((action) => [`${tool.name}_${action.replaceAll('-', '_')}`, { action }])+ : tool.name === 'kiln_discover'+ ? [+ ['kiln_discover', {}],+ ['kiln_capabilities', { capabilities: true }],+ ]+ : [[tool.name, {}]];+ for (const [name, fixed] of variants) {+ const publicTool = surface.tools.find((tool) => tool.name === name);+ assert.ok(publicTool, name);+ assert.deepEqual(surface.resolve(name, {}), { name: tool.name, arguments: fixed });+ assert.equal(publicTool.inputSchema.additionalProperties, false);+ assert.equal(publicTool.inputSchema.properties.action, undefined);+ assert.equal(publicTool.inputSchema.properties.capabilities, undefined);+ for (const [field, schema] of Object.entries(publicTool.inputSchema.properties))+ assert.deepEqual(schema, tool.inputSchema.properties[field], `${name}.${field}`);+ for (const key of ['readOnlyHint', 'destructiveHint', 'openWorldHint'])+ assert.equal(typeof publicTool.annotations[key], 'boolean');+ assert.equal(publicTool.annotations.readOnlyHint, name === 'kiln_discover');+ assert.equal(publicTool.annotations.destructiveHint, false);+ assert.equal(publicTool.annotations.openWorldHint, false);+ }+ if (actions) assert.equal(surface.resolve(tool.name, { action: actions[0] }), undefined);+ }+ assert.deepEqual(engine, before, 'the installed engine manifest must not be mutated');+ assert.doesNotMatch(hostedInstructions, /render-service\/|dist\/|read the matching SKILL/);+});++test('registry drift cannot silently expose an unreviewed operation or drop a mapped input', () => {+ const more = structuredClone(engine);+ more+ .find((tool) => tool.name === 'kiln_material')+ .inputSchema.properties.action.enum.push('delete');+ assert.throws(() => createPublicTools(more), /Unreviewed engine actions/);+ assert.throws(+ () => createPublicTools([...engine, { name: 'new_operation', inputSchema: {} }]),+ /Unreviewed engine tool/,+ );+ assert.throws(() => createPublicTools(engine.slice(1)), /Missing engine tools/);+ const missingField = structuredClone(engine);+ delete missingField.find((tool) => tool.name === 'kiln_material').inputSchema.properties.draft;+ assert.throws(() => createPublicTools(missingField), /Missing engine field/);+ assert.throws(() => createPublicTools([...engine, engine[0]]), /Duplicate engine tool/);+});++test('action selection and argument widening cannot turn reads into another engine operation', () => {+ const surface = createPublicTools(engine);+ for (const name of ['kiln_material_get', 'kiln_assets_get', 'kiln_renderer_status']) {+ for (const args of [+ { action: 'import' },+ { payload: {} },+ JSON.parse('{"__proto__":{"action":"import"}}'),+ ])+ assert.equal(surface.resolve(name, args), undefined);+ }+ for (const name of [+ 'constructor',+ '__proto__',+ 'kiln_material_delete',+ 'kiln_project',+ 'kiln_review',+ ])+ assert.equal(surface.resolve(name, {}), undefined);+ assert.equal(surface.resolve('kiln_discover', { capabilities: true }), undefined);+ assert.equal(surface.resolve('kiln_capabilities', { ids: ['box'] }), undefined);+});diff --git a/hosting/test/rate-limit-bindings.mjs b/hosting/test/rate-limit-bindings.mjsnew file mode 100644index 00000000..dc98e7b5--- /dev/null+++ b/hosting/test/rate-limit-bindings.mjs@@ -0,0 +1,6 @@+// Real local bindings. Ordinary auth/storage fixtures have generous limits so+// unrelated tests stay independent; request-limits.test.mjs tests exhaustion.+export const rateLimitBindings = {+ EDGE_REQUEST_LIMIT: { namespace_id: '1001', simple: { limit: 1000000, period: 60 } },+ ACCOUNT_REQUEST_LIMIT: { namespace_id: '1002', simple: { limit: 1000000, period: 60 } },+};diff --git a/hosting/test/request-job.test.mjs b/hosting/test/request-job.test.mjsnew file mode 100644index 00000000..be43b274--- /dev/null+++ b/hosting/test/request-job.test.mjs@@ -0,0 +1,678 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';++let NativeRequestJob;+before(async () => {+ const output = new URL('../../.cache/hosted-request-test/job.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../src/request-job.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ NativeRequestJob } = await import(output));+});++const tenant = 'a'.repeat(43);+const image = `registry.cloudflare.com/fixture/coordinator@sha256:${'b'.repeat(64)}`;+const request = (extra = {}) =>+ new Request('https://tenant.internal/mcp', {+ method: 'POST',+ body: '{}',+ headers: { 'content-type': 'application/json' },+ ...extra,+ });+const evaluation = () =>+ new Request('http://kiln-evaluator.internal/evaluate', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'content-length': '2',+ 'x-kiln-deadline-ms': '60000',+ 'x-kiln-max-response-bytes': '1024',+ },+ body: '{}',+ });+const deferred = () => {+ let resolve;+ const promise = new Promise((done) => {+ resolve = done;+ });+ return { promise, resolve };+};+const rendering = () =>+ new Request('http://kiln-renderer.internal/render', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'content-length': '2',+ 'x-kiln-deadline-ms': '30000',+ 'x-kiln-max-response-bytes': '20971520',+ },+ body: '{}',+ });+const turn = () => new Promise((resolve) => setImmediate(resolve));++function fixture(options = {}) {+ const values = new Map(),+ events = [],+ children = new Map(),+ storageCalls = [];+ let alarmAt,+ transactionTail = Promise.resolve(),+ failChildren = !!options.failChildren;+ const exited = deferred();+ const storage = {+ async get(key) {+ return structuredClone(values.get(key));+ },+ async put(key, value) {+ values.set(key, structuredClone(value));+ },+ async setAlarm(value) {+ alarmAt = Number(value);+ events.push('alarm');+ },+ async deleteAlarm() {+ alarmAt = undefined;+ },+ transaction(callback) {+ const pending = transactionTail.then(() => callback(storage));+ transactionTail = pending.catch(() => {});+ return pending;+ },+ };+ let job;+ const container = {+ images: { coordinator: options.image ?? image },+ running: false,+ async interceptOutboundHttp(host, binding) {+ events.push(`intercept:${host}`);+ assert(binding);+ await options.intercept?.();+ },+ start(settings) {+ events.push('start');+ this.settings = settings;+ this.running = true;+ },+ monitor() {+ return exited.promise;+ },+ async setInactivityTimeout() {},+ async inspect() {+ return this.running ? { image: options.observedImage ?? image } : null;+ },+ async destroy() {+ events.push('destroy');+ await options.destroy?.();+ this.running = false;+ exited.resolve();+ },+ getTcpPort(port) {+ assert.equal(port, 3000);+ return {+ fetch: async (input) => {+ const req = input instanceof Request ? input : new Request(input);+ if (req.url.endsWith('/_ready')) return new Response(null, { status: 204 });+ events.push('mcp');+ return options.native ? options.native(req, job) : Response.json({ ok: true });+ },+ };+ },+ };+ const ports = {+ publicOrigin: 'https://kiln.example.com',+ storageInterceptor: {},+ evaluationInterceptor: {},+ renderInterceptor: {},+ async storage(owner, req) {+ storageCalls.push({ owner, url: req.url, headers: Object.fromEntries(req.headers) });+ return new Response('source bytes');+ },+ async evaluate(id, req) {+ assert(+ values+ .get('request')+ .children.some((child) => child.id === id && child.kind === 'evaluation'),+ 'child must be durable before dispatch',+ );+ assert.equal(children.has(id), false);+ children.set(id, true);+ events.push(`child:${id}`);+ return options.evaluate ? options.evaluate(id, req) : Response.json({ fixture: true });+ },+ async cancelEvaluation(id) {+ events.push(`cancel:${id}`);+ if (failChildren) throw new Error('PRIVATE_CHILD_FAILURE');+ children.set(id, false);+ },+ async render(id, req) {+ assert(+ values.get('request').children.some((child) => child.id === id && child.kind === 'render'),+ );+ assert.equal(children.has(id), false);+ children.set(id, true);+ events.push(`render:${id}`);+ return options.render ? options.render(id, req) : Response.json({ rendered: true });+ },+ async cancelRender(id) {+ events.push(`cancel-render:${id}`);+ if (failChildren) throw new Error('PRIVATE_RENDER_FAILURE');+ children.set(id, false);+ },+ };+ const context = { storage, container };+ job = new NativeRequestJob(context, ports);+ return {+ job,+ context,+ ports,+ values,+ events,+ children,+ storageCalls,+ get alarmAt() {+ return alarmAt;+ },+ repair() {+ failChildren = false;+ },+ run(req = request()) {+ return job.run(tenant, req, Date.now() + 2000);+ },+ };+}++test('render children are durable, separately routed, and share the parent execution limit', async () => {+ const f = fixture({+ native: async (_, job) => {+ for (let i = 0; i < 8; i++) {+ if (i % 2) await job.evaluateRequest(evaluation());+ else await job.renderRequest(rendering());+ }+ await assert.rejects(job.renderRequest(rendering()), (error) => error.status === 429);+ await assert.rejects(job.evaluateRequest(evaluation()), (error) => error.status === 429);+ return Response.json({ ok: true });+ },+ });+ await f.run();+ const children = f.values.get('request').children;+ assert.equal(new Set(children.map((child) => child.id)).size, 8);+ assert.equal(children.filter((child) => child.kind === 'render').length, 4);+ assert.equal([...f.children.values()].some(Boolean), false);+ for (const child of children) {+ const prefix = child.kind === 'render' ? 'cancel-render:' : 'cancel:';+ assert(f.events.includes(prefix + child.id));+ assert(!f.events.includes((child.kind === 'render' ? 'cancel:' : 'cancel-render:') + child.id));+ }+});++test('a pending render excludes evaluation until its cleanup acknowledgement', async () => {+ const entered = deferred(),+ finish = deferred(),+ renderStarted = deferred(),+ renderFinish = deferred();+ const f = fixture({+ native: async () => {+ entered.resolve();+ await finish.promise;+ return Response.json({ ok: true });+ },+ render: async (_id, req) => {+ assert(Number(req.headers.get('x-kiln-deadline-ms')) <= 2000);+ renderStarted.resolve();+ await renderFinish.promise;+ return Response.json({ ok: true });+ },+ });+ const run = f.run();+ await entered.promise;+ const rendered = f.job.renderRequest(rendering());+ await renderStarted.promise;+ await assert.rejects(f.job.evaluateRequest(evaluation()), (error) => error.status === 429);+ await assert.rejects(f.job.renderRequest(rendering()), (error) => error.status === 429);+ renderFinish.resolve();+ await rendered;+ await f.job.evaluateRequest(evaluation());+ finish.resolve();+ await run;+});++test('render cleanup failure retains parent admission state and recovery routes by persisted kind', async () => {+ const f = fixture({+ failChildren: true,+ native: async (_, job) => {+ await job.renderRequest(rendering());+ return Response.json({ ok: true });+ },+ });+ await assert.rejects(f.run(), (error) => error.code === 'CLEANUP_FAILED');+ assert.equal(f.values.get('request').state, 'closing');+ const child = f.values.get('request').children[0];+ assert.equal(child.kind, 'render');+ f.repair();+ await new NativeRequestJob(f.context, f.ports).alarm();+ assert.equal(f.values.get('request').state, 'finished');+ assert(f.events.includes(`cancel-render:${child.id}`));+ assert(!f.events.includes(`cancel:${child.id}`));+});++test('render route rejects caller-selected authority and fails after parent cancellation', async () => {+ const f = fixture({+ native: async (_, job) => {+ await assert.rejects(job.renderRequest(evaluation()), (error) => error.status === 400);+ await assert.rejects(+ job.renderRequest(new Request(rendering(), { headers: { 'x-tenant': 'other' } })),+ (error) => error.status === 400,+ );+ return Response.json({ ok: true });+ },+ });+ await f.run();+ await assert.rejects(f.job.renderRequest(rendering()));+ assert.equal(f.values.get('request').children.length, 0);+});++test('request host binds storage outside its offline VM and stops the whole job tree before returning', async () => {+ const f = fixture({+ native: async (req, job) => {+ assert.equal(req.url, 'http://kiln-native.internal/mcp');+ assert.equal(req.headers.has('authorization'), false);+ assert.equal(+ await (+ await job.storageRequest(new Request('http://kiln-storage.internal/internal/programs'))+ ).text(),+ 'source bytes',+ );+ await (await job.evaluateRequest(evaluation())).arrayBuffer();+ return Response.json({ ok: true }, { headers: { 'set-cookie': 'PRIVATE_FIXTURE=1' } });+ },+ });+ const result = await f.run();+ assert.deepEqual(await result.json(), { ok: true });+ assert.equal(result.headers.has('set-cookie'), false);+ assert.equal(f.context.container.settings.enableInternet, false);+ assert.deepEqual(f.context.container.settings.env, {+ KILN_PUBLIC_ORIGIN: 'https://kiln.example.com',+ });+ assert.equal(f.context.container.settings.image, image);+ assert.deepEqual(+ f.events.filter((v) => v.startsWith('intercept:')),+ [+ 'intercept:kiln-storage.internal',+ 'intercept:kiln-evaluator.internal',+ 'intercept:kiln-renderer.internal',+ ],+ );+ assert.ok(f.events.indexOf('alarm') < f.events.indexOf('start'));+ assert.deepEqual(f.storageCalls, [+ { owner: tenant, url: 'https://tenant.internal/internal/programs', headers: {} },+ ]);+ assert.equal(f.context.container.running, false);+ assert.equal([...f.children.values()].some(Boolean), false);+ assert.equal(f.values.get('request').state, 'finished');+ assert.equal(f.alarmAt, undefined);+});++test('storage interceptor refuses supplied identity, foreign origins and administrative routes', async () => {+ const entered = deferred(),+ finish = deferred();+ const f = fixture({+ native: async () => {+ entered.resolve();+ await finish.promise;+ return Response.json({ ok: true });+ },+ });+ const run = f.run();+ await entered.promise;+ for (const req of [+ new Request('http://kiln-storage.internal/internal/programs', {+ headers: { 'x-tenant': 'victim' },+ }),+ new Request('http://kiln-storage.internal/internal/programs', {+ headers: { authorization: 'Bearer PRIVATE' },+ }),+ new Request('http://kiln-storage.internal/internal/programs?tenant=victim'),+ new Request('http://attacker.example/internal/programs'),+ new Request('http://kiln-storage.internal/internal/maintenance', { method: 'POST' }),+ new Request('http://kiln-storage.internal/internal/account-deletion', { method: 'POST' }),+ ])+ await assert.rejects(f.job.storageRequest(req));+ assert.equal(f.storageCalls.length, 0);+ finish.resolve();+ await run;+ await assert.rejects(+ f.job.storageRequest(new Request('http://kiln-storage.internal/internal/programs')),+ );+});++test('material storage routes stay bound to the parent tenant and reject arbitrary paths or identity headers', async () => {+ const f = fixture({+ native: async (_req, job) => {+ for (const [path, method] of [+ ['/internal/materials/list', 'POST'],+ ['/internal/materials/commit', 'POST'],+ [`/internal/materials/stone/${'a'.repeat(64)}`, 'GET'],+ ]) {+ const response = await job.storageRequest(+ new Request(`http://kiln-storage.internal${path}`, {+ method,+ ...(method === 'POST'+ ? { body: '{}', headers: { 'content-type': 'application/json' } }+ : {}),+ }),+ );+ await response.text();+ }+ for (const path of [+ '/internal/materials/stone/invalid',+ '/internal/materials/list?tenant=victim',+ '/internal/materials/delete',+ ])+ await assert.rejects(+ job.storageRequest(new Request(`http://kiln-storage.internal${path}`)),+ (error) => error.status === 400,+ );+ await assert.rejects(+ job.storageRequest(+ new Request('http://kiln-storage.internal/internal/materials/list', {+ method: 'POST',+ body: '{}',+ headers: { 'x-kiln-tenant': 'victim' },+ }),+ ),+ (error) => error.status === 400,+ );+ return Response.json({ ok: true });+ },+ });+ await f.run();+ assert.equal(f.storageCalls.length, 3);+ assert(f.storageCalls.every((call) => call.owner === tenant));+});++test('native download ticket issuance stays bound to the active parent tenant without browser redemption authority', async () => {+ const f = fixture({+ native: async (_req, job) => {+ const response = await job.storageRequest(+ new Request('http://kiln-storage.internal/internal/downloads', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ collection: 'project', assetId: 'a_box', revisionId: 'r_one' }),+ }),+ );+ assert.equal(await response.text(), 'source bytes');+ await assert.rejects(+ job.storageRequest(+ new Request(+ `http://kiln-storage.internal/internal/downloads/${'a'.repeat(64)}/asset.glb`,+ ),+ ),+ );+ return Response.json({ ok: true });+ },+ });+ await (await f.run()).arrayBuffer();+ assert.equal(f.storageCalls.length, 1);+ assert.equal(f.storageCalls[0].owner, tenant);+ assert.equal(f.storageCalls[0].url, 'https://tenant.internal/internal/downloads');+ await assert.rejects(+ f.job.storageRequest(+ new Request('http://kiln-storage.internal/internal/downloads', { method: 'POST' }),+ ),+ );+});++test('a cancelled parent refuses a late request after reconstruction without starting a VM', async () => {+ const f = fixture();+ await f.job.cancel();+ const restored = new NativeRequestJob(f.context, f.ports);+ await assert.rejects(restored.run(tenant, request(), Date.now() + 2000));+ assert.equal(f.events.includes('start'), false);+ assert.equal(f.values.get('request').state, 'finished');+});++test('cancellation during interceptor registration prevents late VM startup', async () => {+ const entered = deferred(),+ finish = deferred();+ const f = fixture({+ intercept: async () => {+ entered.resolve();+ await finish.promise;+ },+ });+ const rejected = assert.rejects(f.run());+ await entered.promise;+ await f.job.cancel();+ finish.resolve();+ await rejected;+ await turn();+ assert.equal(f.events.includes('start'), false);+ assert.equal(f.values.get('request').state, 'finished');+});++test('only one child runs at a time and subsequent evaluations get fresh IDs', async () => {+ const entered = deferred(),+ finish = deferred(),+ childStarted = deferred(),+ childFinish = deferred();+ const f = fixture({+ native: async () => {+ entered.resolve();+ await finish.promise;+ return Response.json({ ok: true });+ },+ evaluate: async () => {+ childStarted.resolve();+ await childFinish.promise;+ return Response.json({ ok: true });+ },+ });+ const run = f.run();+ await entered.promise;+ const first = f.job.evaluateRequest(evaluation());+ await childStarted.promise;+ await assert.rejects(f.job.evaluateRequest(evaluation()), (error) => error.status === 429);+ childFinish.resolve();+ await first;+ await f.job.evaluateRequest(evaluation());+ assert.equal(new Set(f.values.get('request').children.map((child) => child.id)).size, 2);+ finish.resolve();+ await run;+ assert.equal([...f.children.values()].some(Boolean), false);+});++test('failed child cleanup suppresses the host response and survives eviction for alarm recovery', async () => {+ const f = fixture({+ failChildren: true,+ native: async (_, job) => {+ await job.evaluateRequest(evaluation());+ return Response.json({ ok: true });+ },+ });+ await assert.rejects(f.run(), (error) => error.code === 'CLEANUP_FAILED');+ assert.notEqual(f.values.get('request').state, 'finished');+ assert.ok(Number.isSafeInteger(f.alarmAt));+ assert.equal(f.context.container.running, false);+ f.repair();+ await new NativeRequestJob(f.context, f.ports).alarm();+ assert.equal(f.values.get('request').state, 'finished');+ assert.equal([...f.children.values()].some(Boolean), false);+ assert.equal(f.alarmAt, undefined);+});++test('a response cannot escape while coordinator destruction is still pending', async () => {+ const entered = deferred(),+ finish = deferred();+ const f = fixture({+ destroy: async () => {+ entered.resolve();+ await finish.promise;+ },+ });+ let returned = false;+ const run = f.run().then((response) => {+ returned = true;+ return response;+ });+ await entered.promise;+ assert.equal(returned, false);+ finish.resolve();+ await run;+ assert.equal(f.context.container.running, false);+});++test('invalid coordinator configuration or forwarded authority starts no VM', async () => {+ for (const [f, req] of [+ [fixture({ image: 'registry.example/coordinator:latest' }), request()],+ [fixture(), request({ headers: { authorization: 'Bearer PRIVATE' } })],+ ]) {+ await assert.rejects(f.run(req));+ assert.equal(f.events.includes('start'), false);+ }+});++test('a durable claim that finishes after the request deadline cannot start compute', async () => {+ const f = fixture();+ const transaction = f.context.storage.transaction;+ let first = true;+ f.context.storage.transaction = (callback) =>+ transaction(async (tx) => {+ if (first) {+ first = false;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ return callback(tx);+ });+ await assert.rejects(+ f.job.run(tenant, request(), Date.now() + 20),+ (error) => error.status === 504,+ );+ assert.equal(f.events.includes('start'), false);+});++test('storage uploads preserve bytes while stripping transport-only headers', async () => {+ const f = fixture({+ native: async (_, job) => {+ await job.storageRequest(+ new Request('http://kiln-storage.internal/internal/programs', {+ method: 'POST',+ headers: {+ 'content-type': 'application/javascript',+ 'content-length': '2',+ host: 'kiln-storage.internal',+ },+ body: '{}',+ }),+ );+ return Response.json({ ok: true });+ },+ });+ f.ports.storage = async (owner, req) => {+ assert.equal(owner, tenant);+ assert.equal(await req.text(), '{}');+ assert.equal(req.headers.has('host'), false);+ return new Response('saved');+ };+ await f.run();+});++test('an unexpected coordinator image is destroyed before it receives the MCP body', async () => {+ const f = fixture({ observedImage: `registry.example/other@sha256:${'c'.repeat(64)}` });+ await assert.rejects(f.run());+ assert.equal(f.events.includes('mcp'), false);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('request').state, 'finished');+});++test('deadline timer expiry stays a timeout when the wall clock is one millisecond behind', async (t) => {+ let now = 1_000_000;+ t.mock.method(Date, 'now', () => now);+ t.mock.timers.enable({ apis: ['setTimeout'] });+ const entered = deferred(),+ result = deferred();+ const f = fixture({+ native: async () => {+ entered.resolve();+ return result.promise;+ },+ });+ const rejected = assert.rejects(+ f.job.run(tenant, request(), now + 50),+ (error) => error.status === 504,+ );+ await entered.promise;+ now += 49;+ t.mock.timers.tick(50);+ await rejected;+ let cancelled = false;+ result.resolve(+ new Response(+ new ReadableStream({+ cancel() {+ cancelled = true;+ },+ }),+ ),+ );+ await turn();+ assert.equal(cancelled, true);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('request').state, 'finished');+});++test('a timed-out native response cannot revive work or leak a late body', async () => {+ const entered = deferred(),+ result = deferred();+ const f = fixture({+ native: async () => {+ entered.resolve();+ return result.promise;+ },+ });+ const rejected = assert.rejects(+ f.job.run(tenant, request(), Date.now() + 50),+ (error) => error.status === 504,+ );+ await entered.promise;+ await rejected;+ let cancelled = false;+ result.resolve(+ new Response(+ new ReadableStream({+ cancel() {+ cancelled = true;+ },+ }),+ ),+ );+ await turn();+ assert.equal(cancelled, true);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('request').state, 'finished');+});++test('one admitted request cannot spawn more than eight child evaluations', async () => {+ const f = fixture({+ native: async (_, job) => {+ for (let i = 0; i < 8; i++) await (await job.evaluateRequest(evaluation())).arrayBuffer();+ await assert.rejects(job.evaluateRequest(evaluation()), (error) => error.status === 429);+ return Response.json({ ok: true });+ },+ });+ await f.run();+ assert.equal(f.values.get('request').children.length, 8);+ assert.equal([...f.children.values()].some(Boolean), false);+});++test('an oversized native response is discarded and coordinator cleanup is still required', async () => {+ const f = fixture({ native: async () => new Response(new Uint8Array(32 * 1024 * 1024 + 1)) });+ await assert.rejects(f.run(), (error) => error.status === 413);+ assert.equal(f.context.container.running, false);+ assert.equal(f.values.get('request').state, 'finished');+});diff --git a/hosting/test/request-limits-worker.ts b/hosting/test/request-limits-worker.tsnew file mode 100644index 00000000..21a6c5fd--- /dev/null+++ b/hosting/test/request-limits-worker.ts@@ -0,0 +1,84 @@+import gateway from '../src/worker';+import { forwardTenant } from '../src/gateway';+import { browserDownload } from '../src/browser-download';+import { D1BrowserSessions } from '../src/browser-sessions';++// Test-only I/O observations and identities. This module never enters production.+let calls = { auth: 0, storage: 0, compute: 0 };+export default {+ async fetch(request: Request, env: Parameters<typeof gateway.fetch>[1], ctx: ExecutionContext) {+ const url = new URL(request.url);+ if (url.pathname === '/fixture/stats') return Response.json(calls);+ if (url.pathname === '/fixture/reset') {+ calls = { auth: 0, storage: 0, compute: 0 };+ return new Response('reset');+ }+ if (url.pathname === '/fixture/session') {+ const session = await new D1BrowserSessions(env.ACCOUNTS, env.PUBLIC_ORIGIN).issue({+ issuer: 'https://github.com',+ subject: await request.text(),+ });+ return Response.json(+ { accountId: session.account.id },+ { headers: { 'set-cookie': session.cookie } },+ );+ }+ if (request.headers.has('x-fixture-ingress')) {+ const forbidden = new Proxy(+ {},+ {+ get() {+ calls.auth++;+ throw new Error('Unexpected auth I/O');+ },+ },+ );+ const deny = {+ async limit() {+ return { success: false };+ },+ };+ const limited = {+ ...env,+ ACCOUNTS: forbidden,+ OAUTH_KV: forbidden,+ EDGE_REQUEST_LIMIT:+ request.headers.get('x-fixture-ingress') === 'missing' ? undefined : deny,+ };+ return gateway.fetch(request, limited as unknown as typeof env, ctx);+ }+ const downstream = {+ ...env,+ TENANTS: {+ getByName() {+ calls.storage++;+ return {+ async fetch() {+ return new Response('saved bytes');+ },+ };+ },+ },+ NATIVE_COMPUTE: {+ async dispatch() {+ calls.compute++;+ return new Response('computed');+ },+ },+ } as unknown as typeof env;+ if (url.pathname === '/fixture/mcp') {+ const incoming = new Request(`${env.PUBLIC_ORIGIN}/mcp`, request);+ return forwardTenant(+ incoming,+ downstream,+ {+ auth: { userId: request.headers.get('x-fixture-account')!, scope: ['kiln:use'] },+ } as Parameters<typeof forwardTenant>[2],+ env.PUBLIC_ORIGIN,+ );+ }+ if (url.pathname.startsWith('/downloads/'))+ return browserDownload(request, downstream, env.PUBLIC_ORIGIN);+ return gateway.fetch(request, env, ctx);+ },+};diff --git a/hosting/test/request-limits.test.mjs b/hosting/test/request-limits.test.mjsnew file mode 100644index 00000000..3fe7b418--- /dev/null+++ b/hosting/test/request-limits.test.mjs@@ -0,0 +1,264 @@+import assert from 'node:assert/strict';+import { test, before, after } from 'node:test';+import { build } from 'esbuild';+import { mkdir } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { Miniflare, convertV4MiniflareOptions } from 'miniflare';+import { migrateAccounts } from './database.mjs';++let limitIngress, limitAccount, runtime;+const origin = 'https://kiln.example.com';+const request = (path, options) => new Request(`${origin}${path}`, options);+const account = `ka_${'a'.repeat(32)}`;+function fixture(outcome = { success: true }) {+ const keys = [];+ const binding = {+ async limit({ key }) {+ keys.push(key);+ if (outcome instanceof Error) throw outcome;+ return outcome;+ },+ };+ return { keys, env: { EDGE_REQUEST_LIMIT: binding, ACCOUNT_REQUEST_LIMIT: binding } };+}+before(async () => {+ const output = new URL('../../.cache/request-limit-tests/limits.mjs', import.meta.url);+ await mkdir(fileURLToPath(new URL('.', output)), { recursive: true });+ await build({+ entryPoints: [fileURLToPath(new URL('../src/request-limits.ts', import.meta.url))],+ bundle: true,+ format: 'esm',+ platform: 'node',+ outfile: fileURLToPath(output),+ });+ ({ limitIngress, limitAccount } = await import(output));+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('./request-limits-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ conditions: ['workerd'],+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare(+ convertV4MiniflareOptions({+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['global_fetch_strictly_public'],+ bindings: { PUBLIC_ORIGIN: origin },+ d1Databases: ['ACCOUNTS'],+ kvNamespaces: ['OAUTH_KV'],+ ratelimits: {+ EDGE_REQUEST_LIMIT: { namespace_id: '1001', simple: { limit: 2, period: 60 } },+ ACCOUNT_REQUEST_LIMIT: { namespace_id: '1002', simple: { limit: 2, period: 60 } },+ },+ outboundService: () => {+ throw new Error('External I/O forbidden');+ },+ }),+ );+ await migrateAccounts(await runtime.getD1Database('ACCOUNTS'));+});+after(async () => runtime?.dispose());++test('all caller variations of one route share a bounded ingress bucket without private data', async () => {+ const f = fixture();+ for (const path of ['/register', '/register?client_id=private-name&code=private-code']) {+ assert.equal(+ await limitIngress(+ request(path, {+ method: 'POST',+ headers: {+ authorization: 'Bearer private-token',+ cookie: 'private-cookie',+ 'x-tenant': 'arbitrary',+ 'cf-connecting-ip': '192.0.2.1',+ },+ body: 'private-source',+ }),+ f.env,+ origin,+ ),+ undefined,+ );+ }+ assert.equal(f.keys.length, 2);+ assert.equal(f.keys[0], f.keys[1]);+ assert(!f.keys.some((key) => /private-|192\.0|arbitrary/.test(key)));+ for (const path of ['/mcp', '/mcp/artifacts/a', '/mcp/artifacts/b?code=secret'])+ await limitIngress(request(path), f.env, origin);+ assert.equal(new Set(f.keys.slice(2)).size, 1);+ assert.notEqual(f.keys[0], f.keys[2]);+ for (const path of ['/oauth/google/callback?state=a', '/oauth/github/callback?state=b'])+ await limitIngress(request(path), f.env, origin);+ assert.equal(f.keys[5], f.keys[6]);+ for (const path of ['/arbitrary-one', '/arbitrary-two', '/oauth/token/anything'])+ await limitIngress(request(path), f.env, origin);+ assert.equal(f.keys[7], f.keys[8]);+ assert.notEqual(f.keys[7], f.keys[9]);+});++test('a stalled limiter fails closed at the real one-second deadline', async () => {+ const f = fixture();+ f.env.EDGE_REQUEST_LIMIT = { limit: () => new Promise(() => {}) };+ const result = await limitIngress(request('/mcp'), f.env, origin);+ assert.equal(result.status, 503);+ assert.equal(await result.text(), 'Service temporarily unavailable');+});++test('gateway refuses exhausted or missing limits before OAuth, database or provider I/O', async () => {+ await runtime.dispatchFetch(`${origin}/fixture/reset`);+ for (const mode of ['deny', 'missing']) {+ for (const path of [+ '/register',+ '/oauth/token',+ '/authorize',+ '/oauth/google/callback',+ '/oauth/github/callback',+ '/account',+ '/account/delete',+ '/downloads/private/file.glb',+ '/mcp',+ '/mcp/artifacts/private',+ '/.well-known/oauth-authorization-server',+ ]) {+ const response = await runtime.dispatchFetch(`${origin}${path}`, {+ headers: {+ 'x-fixture-ingress': mode,+ authorization: 'Bearer private-token',+ cookie: 'private-cookie',+ },+ });+ assert.equal(response.status, mode === 'deny' ? 429 : 503, `${mode} ${path}`);+ }+ }+ assert.deepEqual(await (await runtime.dispatchFetch(`${origin}/fixture/stats`)).json(), {+ auth: 0,+ storage: 0,+ compute: 0,+ });+});++test('real local edge binding exhausts a route bucket without unbounded caller keys', async () => {+ // No auth/storage access for unknown paths; 404 confirms the admitted branch.+ const statuses = [];+ for (let i = 0; i < 3; i++) {+ const response = await runtime.dispatchFetch(`${origin}/unknown-${i}?ignored=${i}`);+ statuses.push(response.status);+ await response.text();+ }+ assert.deepEqual(statuses, [404, 404, 429]);+ const discovery = await runtime.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`);+ assert.equal(discovery.status, 200);+ assert.equal((await discovery.json()).issuer, origin);+});++test('real account binding shares MCP and browser attempts while isolating another account', async () => {+ await runtime.dispatchFetch(`${origin}/fixture/reset`);+ const session = async (subject) => {+ const response = await runtime.dispatchFetch(`${origin}/fixture/session`, {+ method: 'POST',+ body: subject,+ });+ return { ...(await response.json()), cookie: response.headers.get('set-cookie').split(';')[0] };+ };+ const alice = await session('rate-alice'),+ bob = await session('rate-bob');+ const invoke = async (identity, method) =>+ runtime.dispatchFetch(`${origin}/fixture/mcp`, {+ method: 'POST',+ headers: {+ 'x-fixture-account': identity.accountId,+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+ },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method,+ params:+ method === 'tools/call'+ ? { name: 'kiln_validate', arguments: { code: 'function build(){}' } }+ : {},+ }),+ });+ assert.equal((await invoke(alice, 'tools/list')).status, 200);+ const download = (identity) =>+ runtime.dispatchFetch(`${origin}/downloads/${'a'.repeat(64)}/asset.glb`, {+ headers: { cookie: identity.cookie },+ });+ assert.equal((await download(alice)).status, 200);+ const blocked = await invoke(alice, 'tools/call');+ assert.equal(blocked.status, 429);+ assert.equal(blocked.headers.get('retry-after'), '60');+ assert.equal((await download(alice)).status, 429);+ assert.equal((await download(bob)).status, 200);+ assert.deepEqual(await (await runtime.dispatchFetch(`${origin}/fixture/stats`)).json(), {+ auth: 0,+ storage: 2,+ compute: 0,+ });+});++test('ingress rejection cancels the unread body and returns a retryable private response', async () => {+ const f = fixture({ success: false });+ let cancelled = false;+ const body = new ReadableStream({+ cancel() {+ cancelled = true;+ },+ });+ const response = await limitIngress(+ request('/register', { method: 'POST', body, duplex: 'half' }),+ f.env,+ origin,+ );+ assert.equal(response.status, 429);+ assert.equal(response.headers.get('retry-after'), '60');+ assert.equal(response.headers.get('cache-control'), 'no-store');+ assert.equal(cancelled, true);+});++test('missing, broken and malformed limiter results fail closed without exposing their data', async () => {+ for (const outcome of [new Error('private-provider-secret'), {}, { success: 'true' }, null]) {+ const f = fixture(outcome);+ const result = await limitIngress(request('/oauth/token'), f.env, origin);+ assert.equal(result.status, 503);+ assert(!/secret|provider/.test(await result.text()));+ }+ for (const env of [{}, { EDGE_REQUEST_LIMIT: fixture().env.EDGE_REQUEST_LIMIT }])+ assert.equal((await limitIngress(request('/mcp'), env, origin)).status, 503);+});++test('account limits use verified permanent ownership across tokens, apps and network addresses', async () => {+ const f = fixture();+ for (const [path, token, ip] of [+ ['/mcp', 'one', '192.0.2.1'],+ ['/downloads/two/file.glb', 'two', '192.0.2.2'],+ ])+ assert.equal(+ await limitAccount(+ request(path, { headers: { authorization: `Bearer ${token}`, 'cf-connecting-ip': ip } }),+ f.env,+ origin,+ account,+ ),+ undefined,+ );+ assert.equal(f.keys.length, 2);+ assert.equal(f.keys[0], f.keys[1]);+ assert(!f.keys[0].includes(account));+ await limitAccount(request('/mcp'), f.env, origin, `ka_${'b'.repeat(32)}`);+ assert.notEqual(f.keys[0], f.keys[2]);+ await limitAccount(request('/mcp'), f.env, 'https://other.example.com', account);+ assert.notEqual(f.keys[0], f.keys[3]);+ const denied = fixture({ success: false });+ assert.equal((await limitAccount(request('/mcp'), denied.env, origin, account)).status, 429);+ assert.equal(+ (await limitAccount(request('/mcp'), denied.env, origin, 'caller-selected-user')).status,+ 401,+ );+ assert.equal(denied.keys.length, 1);+});diff --git a/hosting/test/request-worker.test.mjs b/hosting/test/request-worker.test.mjsnew file mode 100644index 00000000..fe721db9--- /dev/null+++ b/hosting/test/request-worker.test.mjs@@ -0,0 +1,159 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { after, before, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';++let runtime, namespace;+before(async () => {+ const result = await build({+ stdin: {+ contents: `+ import production from './src/request-worker';+ import {KilnNativeRequest} from './src/request-worker';+ import {DurableObject} from 'cloudflare:workers';+ import {handleRenderRequest} from './src/evaluation-request';+ export * from './src/request-worker';+ export {KilnTenant} from './src/tenant';+ export class RequestFixture extends KilnNativeRequest {+ async fixtureSeed(tenant) { await this.ctx.storage.put('request', {state:'running',tenant,deadlineAt:Date.now()+60000,children:[]}); }+ async fixtureRecord() { return this.ctx.storage.get('request'); }+ async fixtureClose() { const record=await this.ctx.storage.get('request'); await this.ctx.storage.put('request',{...record,state:'finished'}); }+ }+ export class RenderFixture extends DurableObject {+ fetch(request) { return handleRenderRequest(request,{run:async(bytes)=>{+ if(await this.ctx.storage.get('used')) throw Error('duplicate');+ await this.ctx.storage.put('used',true); return bytes;+ }}); }+ async cancel(){await this.ctx.storage.put('cancelled',true);}+ async fixtureRecord(){return {used:await this.ctx.storage.get('used'),cancelled:await this.ctx.storage.get('cancelled')};}+ }+ export default {async fetch(request, env, ctx) {+ const url = new URL(request.url);+ if (url.pathname === '/public') return production.fetch(request);+ const requestId = env.REQUESTS.idFromName(url.searchParams.get('owner')).toString();+ const stub = env.REQUESTS.get(env.REQUESTS.idFromString(requestId));+ if (url.pathname === '/fixture-seed') { await stub.fixtureSeed(await request.text()); return new Response('seeded'); }+ if (url.pathname === '/fixture-record') return Response.json(await stub.fixtureRecord());+ if (url.pathname === '/fixture-close') {await stub.fixtureClose();return new Response('closed');}+ if (url.pathname === '/fixture-render-record') {const record=await stub.fixtureRecord();return Response.json(await env.RENDERS.getByName(record.children.at(-1).id).fixtureRecord());}+ if (url.pathname === '/cancel') { await stub.cancel(); return new Response('cancelled'); }+ const render=url.pathname==='/render';+ const service = render ? ctx.exports.KilnNativeRender({props: {requestId}}) : ctx.exports.KilnNativeStorage({props: {requestId}});+ // The fixture enters through a public test listener; real VM loopback+ // requests do not carry Miniflare's public ingress client-IP header.+ const headers = new Headers(request.headers); headers.delete('cf-connecting-ip');+ return service.fetch(new Request((render?'http://kiln-renderer.internal':'http://kiln-storage.internal')+url.pathname, new Request(request,{headers})));+ }};`,+ resolveDir: fileURLToPath(new URL('../', import.meta.url)),+ loader: 'ts',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ runtime = new Miniflare({+ ...convertV4MiniflareOptions({+ name: 'request-fixture',+ modules: true,+ script: result.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: {+ REQUESTS: { className: 'RequestFixture', useSQLite: true },+ TENANTS: { className: 'KilnTenant', useSQLite: true },+ RENDERS: { className: 'RenderFixture', useSQLite: true },+ },+ bindings: {+ PUBLIC_ORIGIN: 'https://kiln.example.com',+ STORAGE_MAX_BYTES: '1048576',+ STORAGE_MAX_OBJECTS: '32',+ STORAGE_MAX_GROUPS: '8',+ },+ r2Buckets: ['ARTIFACTS'],+ outboundService: async () => {+ throw Error('No external fetch in private fixture');+ },+ }),+ unsafeInspectDurableObjects: true,+ });+ namespace = await runtime.getDurableObjectNamespace('REQUESTS');+});+after(async () => runtime?.dispose());+const send = (owner, path, init) =>+ runtime.dispatchFetch(`https://fixture.invalid${path}?owner=${owner}`, init);+async function active(owner, tenant) {+ assert.equal((await send(owner, '/fixture-seed', { method: 'POST', body: tenant })).status, 200);+}++test('private request Worker exposes no default public service', async () => {+ assert.equal((await send('no-owner', '/public')).status, 404);+});++test('actual loopback props and DO RPC route storage using the outside durable tenant record', async () => {+ await active('alice', 'a'.repeat(43));+ await active('bob', 'b'.repeat(43));+ const source = '// private Alice source\nfunction build(){return createRoot();}';+ const saved = await send('alice', '/internal/programs', {+ method: 'POST',+ headers: { 'content-type': 'application/javascript' },+ body: source,+ });+ assert.equal(saved.status, 201);+ const { programRef } = await saved.json();+ const path = `/internal/programs/${encodeURIComponent(programRef)}`;+ assert.equal(await (await send('alice', path)).text(), source);+ assert.equal((await send('bob', path)).status, 404);+ assert.equal((await send('bob', path, { headers: { 'x-tenant': 'a'.repeat(43) } })).status, 400);+ await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {+ id: namespace.idFromName('alice').toString(),+ });+ assert.equal(await (await send('alice', path)).text(), source);+});++test('actual cancellation RPC writes a persistent pre-arrival fence and rejects storage afterward', async () => {+ assert.equal((await send('cancelled', '/cancel')).status, 200);+ assert.equal((await (await send('cancelled', '/fixture-record')).json()).state, 'finished');+ await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {+ id: namespace.idFromName('cancelled').toString(),+ });+ assert.equal((await send('cancelled', '/internal/programs')).status, 409);+});++test('actual renderer loopback uses host-owned props and a fresh durable child, then acknowledges cancellation', async () => {+ const owner = 'render-owner';+ await active(owner, 'r'.repeat(43));+ const init = {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-kiln-deadline-ms': '30000',+ 'x-kiln-max-response-bytes': '20971520',+ },+ body: '{}',+ };+ const result = await send(owner, '/render', init);+ assert.equal(result.status, 200);+ assert.equal(await result.text(), '{}');+ const record = await (await send(owner, '/fixture-record')).json();+ assert.equal(record.children.length, 1);+ assert.equal(record.children[0].kind, 'render');+ assert.match(record.children[0].id, /^[a-f0-9-]{36}$/);+ assert.equal(record.activeChild, undefined);+ assert.deepEqual(await (await send(owner, '/fixture-render-record')).json(), {+ used: true,+ cancelled: true,+ });+ const forged = await send(owner, '/render', {+ ...init,+ headers: { ...init.headers, 'x-request-id': 'other', 'x-tenant': 'other' },+ });+ assert.equal(forged.status, 400);+ await send(owner, '/fixture-close', { method: 'POST' });+ await runtime.unsafeEvictDurableObject('request-fixture', 'RequestFixture', {+ id: namespace.idFromName(owner).toString(),+ });+ assert.equal((await send(owner, '/render', init)).status, 409);+ assert.equal((await (await send(owner, '/fixture-record')).json()).children.length, 1);+});diff --git a/hosting/test/resilience.test.mjs b/hosting/test/resilience.test.mjsnew file mode 100644index 00000000..2f21daec--- /dev/null+++ b/hosting/test/resilience.test.mjs@@ -0,0 +1,456 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { readFile } from 'node:fs/promises';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';++let runResilienceOnce,+ resilienceCases,+ observeResilience,+ checkResilienceResult,+ ResilienceExecution,+ resilienceImage;+before(async () => {+ for (const module of [+ 'resilience-run',+ 'resilience-observation',+ 'resilience-result',+ 'resilience-execution',+ ]) {+ const output = new URL(`../../.cache/resilience-test/${module}.mjs`, import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL(`../probe/${module}.ts`, import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ const value = await import(output);+ if (module === 'resilience-run') ({ runResilienceOnce, resilienceCases } = value);+ if (module === 'resilience-observation') ({ observeResilience } = value);+ if (module === 'resilience-result') ({ checkResilienceResult } = value);+ if (module === 'resilience-execution') ({ ResilienceExecution, resilienceImage } = value);+ }+});++function runningFixture() {+ const store = storage();+ let alarmAt;+ store.setAlarm = async (time) => {+ alarmAt = time;+ };+ store.deleteAlarm = async () => {+ alarmAt = undefined;+ };+ let exited, stopped, stdout;+ const monitor = new Promise((resolve) => {+ stopped = resolve;+ });+ const exitCode = new Promise((resolve) => {+ exited = resolve;+ });+ const calls = [];+ const container = {+ images: { kiln: resilienceImage },+ running: false,+ start() {+ calls.push('start');+ this.running = true;+ },+ async setInactivityTimeout() {},+ monitor() {+ return monitor;+ },+ async inspect() {+ return this.running ? { image: resilienceImage } : null;+ },+ async exec() {+ calls.push('exec');+ return {+ stdin: new WritableStream({+ write() {+ calls.push('input');+ },+ }),+ stdout: new ReadableStream({+ start(c) {+ stdout = c;+ c.enqueue(new TextEncoder().encode('KILN_PROBE_READY\n'));+ },+ }),+ stderr: new ReadableStream({+ start(c) {+ c.close();+ },+ }),+ exitCode,+ };+ },+ async destroy() {+ calls.push('destroy');+ this.running = false;+ stdout?.close();+ exited(0);+ stopped();+ },+ };+ return { context: { container, storage: store }, calls, alarmAt: () => alarmAt };+}++test('native cancellation begins after readiness, destroys once and retains the outcome', async (t) => {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });+ const f = runningFixture();+ const execution = new ResilienceExecution(f.context);+ const pending = execution.run('native-cancel');+ await new Promise((resolve) => setImmediate(resolve));+ assert.ok(f.calls.includes('input'));+ assert.equal(f.calls.includes('destroy'), false);+ t.mock.timers.tick(251);+ const result = await pending;+ assert.equal(result.passed, true);+ assert.equal(result.reason, 'CANCELLED');+ assert.equal(result.ready, true);+ assert.equal(result.stopped, true);+ assert.deepEqual(await execution.run('native-cancel'), result);+ assert.equal(f.calls.filter((c) => c === 'start').length, 1);+ assert.equal(f.calls.filter((c) => c === 'destroy').length, 1);+ assert.equal(f.alarmAt(), undefined);+});++test('recovery requires the durable deadline callback; a new controller cannot reexecute the claim', async (t) => {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 2_000_000 });+ const f = runningFixture();+ const pending = new ResilienceExecution(f.context).run('alarm-recovery');+ await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(251);+ const waiting = await pending;+ assert.equal(waiting.pendingAlarm, true);+ assert.equal(waiting.passed, false);+ assert.equal(f.context.container.running, true);+ const restarted = new ResilienceExecution(f.context);+ assert.deepEqual(await restarted.run('alarm-recovery'), waiting);+ await restarted.alarm();+ assert.equal((await restarted.read()).passed, false);+ assert.equal(f.context.container.running, true);+ t.mock.timers.tick(15_000);+ await restarted.alarm();+ const recovered = await restarted.read();+ assert.equal(recovered.passed, true);+ assert.equal(recovered.reason, 'ALARM_RECOVERED');+ assert.equal(recovered.stopped, true);+ assert.equal(recovered.pendingAlarm, false);+ assert.equal(f.alarmAt(), undefined);+ assert.equal(f.calls.filter((c) => c === 'start').length, 1);+});++test('operator teardown after missing alarm never converts failure to a qualification pass', async (t) => {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 3_000_000 });+ const f = runningFixture();+ const execution = new ResilienceExecution(f.context);+ const pending = execution.run('alarm-recovery');+ await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(251);+ await pending;+ const stopped = await execution.stopUnconfirmed();+ assert.equal(stopped.passed, false);+ assert.equal(stopped.stopped, true);+ assert.equal(stopped.reason, 'ALARM_NOT_OBSERVED');+ t.mock.timers.tick(15_000);+ // A later real alarm can finish cleanup, but cannot overwrite the failed proof.+ f.context.container.destroy = async () => {+ f.context.container.running = false;+ };+ await execution.alarm();+ assert.deepEqual(await execution.read(), stopped);+});++function storage() {+ const records = new Map();+ let tail = Promise.resolve();+ const result = {+ async get(key) {+ return structuredClone(records.get(key));+ },+ async put(key, value) {+ records.set(key, structuredClone(value));+ },+ transaction(fn) {+ const next = tail.then(() => fn(result));+ tail = next.catch(() => {});+ return next;+ },+ };+ return result;+}++test('resilience allowance is fixed, claimed once and sequential even under concurrent invocations', async () => {+ const store = storage();+ const calls = [];+ let active = 0;+ const execute = async (name) => {+ assert.equal(active++, 0);+ calls.push(name);+ await new Promise((resolve) => setImmediate(resolve));+ active--;+ return { name, passed: true, stopped: true };+ };+ await Promise.all([runResilienceOnce(store, execute), runResilienceOnce(store, execute)]);+ const retained = await runResilienceOnce(store, execute);+ assert.deepEqual(resilienceCases, [+ 'cpu-preview',+ 'software-views',+ 'network',+ 'write-marker',+ 'read-marker',+ 'native-deadline',+ 'native-cancel',+ 'stdout-flood',+ 'stderr-flood',+ 'memory-limit',+ 'alarm-recovery',+ 'engine-after',+ ]);+ assert.deepEqual(calls, resilienceCases);+ assert.equal(retained.state, 'finished');+ assert.equal(retained.results.length, 12);+});++test('failure or interruption never authorizes another batch or exposes arbitrary errors', async () => {+ const store = storage();+ let calls = 0;+ const execute = async () => {+ calls++;+ throw new Error('PRIVATE_DIAGNOSTIC');+ };+ const record = await runResilienceOnce(store, execute);+ assert.deepEqual(record.results, [+ { name: 'cpu-preview', passed: false, reason: 'PROBE_FAILED' },+ ]);+ assert.deepEqual(await runResilienceOnce(store, execute), record);+ assert.equal(calls, 1);+ const interrupted = storage();+ await interrupted.put('run', { state: 'running', results: [] });+ await runResilienceOnce(interrupted, execute);+ assert.equal(calls, 1);+});++test('readiness observes split fixed prefix, preserves bytes and never mistakes partial output for readiness', async () => {+ let ready = 0;+ let received;+ const actual = {+ async exec(command, options) {+ received = { command, options };+ return {+ stdin: null,+ stderr: null,+ stdout: new ReadableStream({+ start(c) {+ for (const chunk of ['KILN_', 'PROBE_READY\n', 'body'])+ c.enqueue(new TextEncoder().encode(chunk));+ c.close();+ },+ }),+ exitCode: Promise.resolve(0),+ };+ },+ };+ const observer = observeResilience(actual, 'fixed script', () => {+ ready++;+ });+ const process = await observer.container.exec(['original'], { user: '1000:1000' });+ assert.equal(await new Response(process.stdout).text(), 'KILN_PROBE_READY\nbody');+ assert.equal(ready, 1);+ assert.equal(observer.ready(), true);+ assert.deepEqual(received.command, [+ '/usr/local/bin/node',+ '--input-type=module',+ '-e',+ 'fixed script',+ ]);+ assert.equal(received.options.user, '1000:1000');+ assert.equal(observer.exitCode(), 0);+ const partial = observeResilience(+ {+ async exec() {+ return {+ stdout: new ReadableStream({+ start(c) {+ c.enqueue(new TextEncoder().encode('KILN_PROBE_'));+ c.close();+ },+ }),+ exitCode: Promise.resolve(0),+ };+ },+ },+ 'fixed',+ () => {+ assert.fail('partial prefix');+ },+ );+ await new Response((await partial.container.exec([])).stdout).text();+ assert.equal(partial.ready(), false);+});++test('destruction fault injection is probe-only and fails once without swallowing subsequent cleanup', async () => {+ let destroyed = 0;+ const observer = observeResilience(+ {+ async destroy() {+ destroyed++;+ },+ },+ 'fixed',+ () => {},+ true,+ );+ await assert.rejects(observer.container.destroy());+ assert.equal(destroyed, 0);+ await observer.container.destroy();+ assert.equal(destroyed, 1);+});++test('failure qualification requires the exact failure, real native readiness and confirmed destruction', async () => {+ const base = { name: 'native-cancel', reason: 'CANCELLED', ready: true, stopped: true };+ assert.equal((await checkResilienceResult(base)).passed, true);+ for (const change of [{ reason: 'WORKER_FAILED' }, { ready: false }, { stopped: false }]) {+ assert.equal((await checkResilienceResult({ ...base, ...change })).passed, false);+ }+ assert.equal(+ (+ await checkResilienceResult({+ name: 'engine-after',+ stopped: true,+ output: new TextEncoder().encode('{"ok":true}'),+ })+ ).passed,+ false,+ );+ assert.equal(+ (+ await checkResilienceResult({+ name: 'memory-limit',+ stopped: true,+ output: new TextEncoder().encode('{"ok":true,"oomKills":0}'),+ })+ ).passed,+ false,+ );+});++test('software proof rejects a truncated PNG even when reported colour counts look valid', async () => {+ const png = Buffer.alloc(24);+ png.set([137, 80, 78, 71]);+ png.writeUInt32BE(128, 16);+ png.writeUInt32BE(128, 20);+ const views = ['neutral', 'dark', 'light'].flatMap((backdrop) =>+ [0, 1].map((index) => ({+ backdrop,+ index,+ red: 100,+ green: 100,+ pngBase64: png.toString('base64'),+ })),+ );+ const output = new TextEncoder().encode(JSON.stringify({ ok: true, software: true, views }));+ assert.equal(+ (await checkResilienceResult({ name: 'software-views', stopped: true, output })).passed,+ false,+ );+});++test('the resilience candidate has no public entry or trigger and pins the stable software image', async () => {+ const config = JSON.parse(+ await readFile(new URL('../probe/resilience.wrangler.jsonc', import.meta.url), 'utf8'),+ );+ assert.equal(config.workers_dev, false);+ assert.equal(config.preview_urls, false);+ assert.deepEqual(config.routes, []);+ assert.equal(config.triggers, undefined);+ assert.equal(config.main, './resilience-worker.ts');+ assert.equal(config.containers.length, 1);+ assert.equal(config.containers[0].scheduling_policy, 'durable_object');+ assert.equal(config.containers[0].class_name, 'KilnResilienceJob');+ assert.equal(config.containers[0].images.kiln.image, resilienceImage);+ assert.equal(config.containers[0].observability.logs.enabled, false);+ assert.deepEqual(config.exports, {+ KilnResilienceControl: { type: 'worker' },+ KilnResilienceRun: { type: 'durable-object', storage: 'sqlite' },+ KilnResilienceJob: { type: 'durable-object', storage: 'sqlite' },+ });+});++test('unknown cases and wrong images are rejected before a native job can start', async () => {+ const f = runningFixture();+ const execution = new ResilienceExecution(f.context);+ await assert.rejects(execution.run('arbitrary-code'));+ f.context.container.images.kiln = 'wrong';+ assert.deepEqual(await execution.run('cpu-preview'), {+ name: 'cpu-preview',+ passed: false,+ reason: 'IMAGE_UNAVAILABLE',+ });+ assert.deepEqual(f.calls, []);+ assert.equal(await f.context.storage.get('probe'), undefined);+});++test('real Worker RPC admits only the fixed retained batch and denies HTTP execution', async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL('../probe/resilience-worker.ts', import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ const runtime = new Miniflare(+ convertV4MiniflareOptions({+ workers: [+ {+ name: 'private-resilience',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ compatibilityFlags: ['enable_ctx_exports'],+ durableObjects: {+ RUN: { className: 'KilnResilienceRun', useSQLite: true },+ JOB: { className: 'KilnResilienceJob', useSQLite: true },+ },+ outboundService: async () => {+ throw new Error('No network');+ },+ },+ {+ name: 'operator',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: {+ PROBE: { name: 'private-resilience', entrypoint: 'KilnResilienceControl' },+ },+ script: `export default { async fetch(request,env){if(new URL(request.url).pathname==='/denied')return env.PROBE.fetch(request);return Response.json(await env.PROBE.runFixed({code:'arbitrary source is ignored'}));} }`,+ },+ ],+ }),+ );+ try {+ const worker = await runtime.getWorker('private-resilience');+ const operator = await runtime.getWorker('operator');+ assert.equal(+ (await worker.fetch('http://localhost/execute', { method: 'POST', body: '{}' })).status,+ 404,+ );+ assert.equal(+ (await operator.fetch('http://localhost/denied', { method: 'POST', body: '{}' })).status,+ 404,+ );+ const first = await (await operator.fetch('http://localhost/run')).json();+ assert.deepEqual(first, {+ state: 'finished',+ results: [{ name: 'cpu-preview', passed: false, reason: 'CONTAINER_UNAVAILABLE' }],+ });+ assert.deepEqual(await (await operator.fetch('http://localhost/run')).json(), first);+ } finally {+ await runtime.dispose();+ }+});diff --git a/hosting/test/startup-diagnostic.test.mjs b/hosting/test/startup-diagnostic.test.mjsnew file mode 100644index 00000000..5c753d99--- /dev/null+++ b/hosting/test/startup-diagnostic.test.mjs@@ -0,0 +1,438 @@+import assert from 'node:assert/strict';+import { fileURLToPath } from 'node:url';+import { before, test } from 'node:test';+import { build } from 'esbuild';+import { convertV4MiniflareOptions, Miniflare } from 'miniflare';++let ManagedStartupDiagnostic;+before(async () => {+ const output = new URL('../../.cache/startup-diagnostic-test/diagnostic.mjs', import.meta.url);+ await build({+ entryPoints: [fileURLToPath(new URL('../probe/startup-diagnostic.ts', import.meta.url))],+ outfile: fileURLToPath(output),+ bundle: true,+ format: 'esm',+ platform: 'node',+ });+ ({ ManagedStartupDiagnostic } = await import(output));+});++function fixture(options = {}) {+ const records = new Map();+ const calls = [];+ let tail = Promise.resolve();+ let alarmAt;+ let cleanupFails = options.cleanupFails ?? false;+ let finishMonitor;+ let failMonitor;+ const monitor = new Promise((resolve, reject) => {+ finishMonitor = resolve;+ failMonitor = reject;+ });+ const output = new TextEncoder().encode(+ options.output ?? JSON.stringify({ version: 'v24.20.0', uid: 0, gid: 0 }),+ );+ const stream = (bytes) =>+ new ReadableStream({+ start(controller) {+ controller.enqueue(bytes);+ controller.close();+ },+ });+ const container = {+ images: options.images ?? {},+ running: false,+ start(settings) {+ calls.push('start');+ this.settings = settings;+ this.running = true;+ if (options.startFails) throw new Error('private startup details');+ },+ monitor() {+ calls.push('monitor');+ if (options.monitorThrows) throw new Error('private synchronous monitor details');+ return monitor;+ },+ async setInactivityTimeout(ms) {+ calls.push('inactivity');+ this.inactivity = ms;+ },+ async exec(command, settings) {+ calls.push('exec');+ this.command = command;+ this.execSettings = settings;+ if (options.monitorFails) {+ failMonitor(new Error('private monitor details'));+ return new Promise(() => {});+ }+ if (options.execFails) throw new Error('private exec details');+ if (options.hang) return new Promise(() => {});+ return {+ stdout: stream(output),+ stderr: stream(new TextEncoder().encode(options.stderr ?? '')),+ exitCode: Promise.resolve(options.exitCode ?? 0),+ };+ },+ async inspect() {+ calls.push('inspect');+ if (!this.running) return null;+ return { image: options.image ?? this.settings.image };+ },+ async destroy() {+ calls.push('destroy');+ if (options.cleanupHangs) return new Promise(() => {});+ if (cleanupFails) throw new Error('private cleanup details');+ this.running = false;+ if (options.cleanupMonitorFails) failMonitor(new Error('private teardown details'));+ else finishMonitor();+ },+ };+ const storage = {+ async get(key) {+ return structuredClone(records.get(key));+ },+ async put(key, value) {+ records.set(key, structuredClone(value));+ },+ async setAlarm(value) {+ alarmAt = Number(value);+ calls.push('alarm');+ },+ async deleteAlarm() {+ alarmAt = undefined;+ },+ transaction(callback) {+ const operation = tail.then(() => callback(storage));+ tail = operation.catch(() => {});+ return operation;+ },+ };+ return {+ context: { container: options.absent ? undefined : container, storage },+ records,+ calls,+ container,+ get alarmAt() {+ return alarmAt;+ },+ repairCleanup() {+ cleanupFails = false;+ },+ };+}++test('managed control runs one fixed command offline and retains phase and destruction evidence', async () => {+ const f = fixture();+ const probe = new ManagedStartupDiagnostic(f.context);+ const result = await probe.run();+ assert.equal(result.passed, true);+ assert.equal(result.state, 'finished');+ assert.equal(result.stopped, true);+ assert.deepEqual(result.runtime, { version: 'v24.20.0', uid: 0, gid: 0 });+ assert.equal(f.container.settings.image, 'cloudflare/debian-trixie');+ assert.equal(f.container.settings.enableInternet, false);+ assert.equal(f.container.settings.instance, 'standard-2');+ assert.deepEqual(f.container.settings.entrypoint, ['sleep', 'infinity']);+ assert.deepEqual(f.container.command.slice(0, 2), ['/usr/local/bin/node', '--eval']);+ assert.equal(f.container.command.join(' ').includes('kiln'), false);+ assert.equal(f.calls.indexOf('alarm') < f.calls.indexOf('start'), true);+ assert.equal(f.container.running, false);+ assert.equal(f.alarmAt, undefined);+ for (const operation of ['start', 'exec', 'inspect', 'output', 'destroy', 'stopped']) {+ assert.ok(result.phases.some((p) => p.operation === operation && p.event === 'completed'));+ }+ assert.deepEqual(await probe.run(), result);+ assert.equal(f.calls.filter((x) => x === 'start').length, 1);+});++test('concurrent invocations cannot start another instance or change the fixed command', async () => {+ const f = fixture();+ await Promise.all([+ new ManagedStartupDiagnostic(f.context).run('untrusted command'),+ new ManagedStartupDiagnostic(f.context).run('new id'),+ ]);+ assert.equal(f.calls.filter((x) => x === 'start').length, 1);+ assert.equal(f.container.command.join(' ').includes('untrusted'), false);+});++test('missing binding and provider failure produce bounded metadata without private error text', async () => {+ for (const options of [+ { absent: true },+ { startFails: true },+ { execFails: true },+ { monitorFails: true },+ { monitorThrows: true },+ ]) {+ const f = fixture(options);+ const result = await new ManagedStartupDiagnostic(f.context).run();+ assert.equal(result.state, 'finished');+ assert.equal(result.passed, false);+ assert.equal(JSON.stringify(result).includes('private'), false);+ assert.equal(result.stopped, true);+ if (options.execFails) assert.equal(result.reason, 'EXEC_FAILED');+ if (options.monitorFails || options.monitorThrows) {+ assert.equal(result.reason, 'MONITOR_FAILED');+ assert.ok(+ result.phases.some(+ (p) => p.operation === 'monitor' && p.event === 'failed' && !p.duringCleanup,+ ),+ );+ }+ }+});++test('a monitor rejection caused by destruction is marked as cleanup, not startup failure', async () => {+ const f = fixture({ cleanupMonitorFails: true });+ const result = await new ManagedStartupDiagnostic(f.context).run();+ assert.equal(result.passed, true);+ assert.ok(+ result.phases.some((p) => p.operation === 'monitor' && p.event === 'failed' && p.duringCleanup),+ );+});++test('unexpected identity, process failure and output floods fail without retaining process output', async () => {+ for (const options of [+ { image: 'other-image' },+ { output: 'private process output' },+ { output: 'x'.repeat(1025) },+ { stderr: 'private stderr' },+ { exitCode: 2 },+ { output: JSON.stringify({ version: 'v22.23.3', uid: 0, gid: 0 }) },+ ]) {+ const f = fixture(options);+ const result = await new ManagedStartupDiagnostic(f.context).run();+ assert.equal(result.passed, false);+ assert.equal(result.stopped, true);+ assert.equal(JSON.stringify(result).includes('private'), false);+ assert.equal(f.container.running, false);+ }+});++test('failed cleanup retains a durable recovery alarm and never retries execution', async () => {+ const f = fixture({ cleanupFails: true });+ const result = await new ManagedStartupDiagnostic(f.context).run();+ assert.equal(result.passed, false);+ assert.equal(result.stopped, false);+ assert.equal(result.cleanupRequired, true);+ assert.ok(f.alarmAt > Date.now());+ f.repairCleanup();+ await new ManagedStartupDiagnostic(f.context).alarm();+ const recovered = await new ManagedStartupDiagnostic(f.context).run();+ assert.equal(recovered.passed, false);+ assert.equal(recovered.stopped, true);+ assert.equal(recovered.cleanupRequired, false);+ assert.equal(f.alarmAt, undefined);+ assert.equal(f.calls.filter((x) => x === 'start').length, 1);+});++test('deadline stops a hung command and a fresh controller can clean an interrupted claim', async (t) => {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 1_000_000 });+ const f = fixture({ hang: true });+ const pending = new ManagedStartupDiagnostic(f.context).run();+ while (!f.calls.includes('exec')) await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(60_001);+ const result = await pending;+ assert.equal(result.reason, 'DEADLINE_EXCEEDED');+ assert.equal(result.stopped, true);+ assert.equal(f.container.running, false);++ const interrupted = fixture();+ interrupted.container.running = true;+ await interrupted.context.storage.put('startup', {+ state: 'running',+ passed: false,+ claimedAt: 1_000_000,+ deadlineAt: 1_060_000,+ phases: [],+ cleanupRequired: true,+ stopped: false,+ });+ await new ManagedStartupDiagnostic(interrupted.context).alarm();+ const retained = await new ManagedStartupDiagnostic(interrupted.context).run();+ assert.equal(retained.reason, 'DEADLINE_EXCEEDED');+ assert.equal(retained.stopped, true);+ assert.equal(interrupted.calls.includes('exec'), false);+});++test('cleanup itself is bounded and preserves recovery without granting a second invocation', async (t) => {+ t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 2_000_000 });+ const f = fixture({ cleanupHangs: true });+ const pending = new ManagedStartupDiagnostic(f.context).run();+ while (!f.calls.includes('destroy')) await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(5_001);+ const result = await pending;+ assert.equal(result.passed, false);+ assert.equal(result.reason, 'CLEANUP_FAILED');+ assert.equal(result.cleanupRequired, true);+ assert.equal(result.stopped, false);+ assert.equal(f.alarmAt, Date.now() + 30_000);+ assert.deepEqual(await new ManagedStartupDiagnostic(f.context).run(), result);+ assert.equal(f.calls.filter((x) => x === 'start').length, 1);+});++test('configured control uses only a pinned Cloudflare image from its host binding', async () => {+ const image = `registry.cloudflare.com/${'a'.repeat(32)}/kiln-startup-control@sha256:${'b'.repeat(64)}`;+ const f = fixture({ images: { control: image } });+ const result = await new ManagedStartupDiagnostic(f.context, 'configured').run();+ assert.equal(result.passed, true);+ assert.equal(f.container.settings.image, image);+ assert.equal(f.container.settings.enableInternet, false);+ for (const invalid of [+ undefined,+ '',+ 'cloudflare/debian-trixie',+ 'node:24.20.0-trixie-slim',+ image.replace(/@sha256:.*/, ':latest'),+ ]) {+ const denied = fixture({ images: { control: invalid } });+ const failed = await new ManagedStartupDiagnostic(denied.context, 'configured').run();+ assert.equal(failed.reason, 'IMAGE_UNAVAILABLE');+ assert.equal(failed.passed, false);+ assert.equal(denied.calls.includes('start'), false);+ assert.equal(denied.calls.includes('exec'), false);+ }+});++test('configured control verifies the running image independently of the selected reference', async () => {+ const image = `registry.cloudflare.com/${'a'.repeat(32)}/kiln-startup-control@sha256:${'b'.repeat(64)}`;+ const f = fixture({ images: { control: image }, image: 'cloudflare/debian-trixie' });+ const result = await new ManagedStartupDiagnostic(f.context, 'configured').run();+ assert.equal(result.passed, false);+ assert.equal(result.reason, 'INSPECT_FAILED');+ assert.equal(result.stopped, true);+});++test('Kiln-image control selects its exact original image and numeric identity without importing Kiln', async () => {+ const image =+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a';+ const output = JSON.stringify({ version: 'v22.23.3', uid: 1000, gid: 1000 });+ const f = fixture({ images: { control: image }, output });+ const result = await new ManagedStartupDiagnostic(f.context, 'kiln').run();+ assert.equal(result.passed, true);+ assert.equal(f.container.settings.image, image);+ assert.equal(f.container.execSettings.user, '1000:1000');+ assert.deepEqual(f.container.command, [+ '/usr/local/bin/node',+ '--eval',+ 'process.stdout.write(JSON.stringify({version:process.version,uid:process.getuid(),gid:process.getgid()}))',+ ]);+ for (const runtime of [+ { version: 'v24.20.0', uid: 1000, gid: 1000 },+ { version: 'v22.23.3', uid: 0, gid: 0 },+ ]) {+ const mismatch = fixture({ images: { control: image }, output: JSON.stringify(runtime) });+ assert.equal(+ (await new ManagedStartupDiagnostic(mismatch.context, 'kiln').run()).reason,+ 'OUTPUT_FAILED',+ );+ }+ const substituted = fixture({+ images: { control: image.replace('69aff70b', 'ffffffff') },+ output,+ });+ assert.equal(+ (await new ManagedStartupDiagnostic(substituted.context, 'kiln').run()).reason,+ 'IMAGE_UNAVAILABLE',+ );+ assert.equal(substituted.calls.includes('start'), false);+});++test('Kiln platform-manifest control preserves runtime identity and rejects the original index', async () => {+ const image =+ 'registry.cloudflare.com/56adffd40534f7fe110fc661a40bbf53/kiln-evaluation@sha256:db79551579a9abd33f7589a4da4d57947364ddf3dd37b79f766e202f2703edc8';+ const output = JSON.stringify({ version: 'v22.23.3', uid: 1000, gid: 1000 });+ const f = fixture({ images: { control: image }, output });+ const diagnostic = new ManagedStartupDiagnostic(f.context, 'kiln-manifest');+ const result = await diagnostic.run();+ assert.equal(result.passed, true);+ assert.equal(result.stopped, true);+ assert.equal(f.container.settings.image, image);+ assert.equal(f.container.execSettings.user, '1000:1000');+ assert.equal(f.container.settings.enableInternet, false);+ assert.deepEqual(await diagnostic.run(), result);+ assert.equal(f.calls.filter((call) => call === 'start').length, 1);+ for (const digest of [+ '69aff70b4f0f80d2ff13549f4b55b1053fc1d8a6e25a00168ac4078a2ebd7b8a',+ 'a'.repeat(64),+ ]) {+ const mismatch = fixture({+ images: { control: image.replace(/sha256:.*/, `sha256:${digest}`) },+ output,+ });+ assert.equal(+ (await new ManagedStartupDiagnostic(mismatch.context, 'kiln-manifest').run()).reason,+ 'IMAGE_UNAVAILABLE',+ );+ assert.equal(mismatch.calls.includes('start'), false);+ }+ for (const runtime of [+ { version: 'v24.20.0', uid: 1000, gid: 1000 },+ { version: 'v22.23.3', uid: 0, gid: 0 },+ ]) {+ const mismatch = fixture({ images: { control: image }, output: JSON.stringify(runtime) });+ assert.equal(+ (await new ManagedStartupDiagnostic(mismatch.context, 'kiln-manifest').run()).reason,+ 'OUTPUT_FAILED',+ );+ }+});++for (const [entryFile, className, entrypoint] of [+ ['startup-worker.ts', 'KilnManagedStartupJob', 'KilnStartupControl'],+ ['custom-startup-worker.ts', 'KilnCustomStartupJob', 'KilnCustomStartupControl'],+ ['kiln-startup-worker.ts', 'KilnImageStartupJob', 'KilnImageStartupControl'],+ ['manifest-startup-worker.ts', 'KilnManifestStartupJob', 'KilnManifestStartupControl'],+]) {+ test(`${entryFile} uses its private binding, denies HTTP and retains a missing-container result`, async () => {+ const bundle = await build({+ entryPoints: [fileURLToPath(new URL(`../probe/${entryFile}`, import.meta.url))],+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'browser',+ external: ['cloudflare:workers'],+ });+ const runtime = new Miniflare(+ convertV4MiniflareOptions({+ workers: [+ {+ name: 'diagnostic',+ modules: true,+ script: bundle.outputFiles[0].text,+ compatibilityDate: '2026-10-06',+ durableObjects: { STARTUP_JOB: { className, useSQLite: true } },+ },+ {+ name: 'operator',+ modules: true,+ compatibilityDate: '2026-10-06',+ serviceBindings: { DIAGNOSTIC: { name: 'diagnostic', entrypoint } },+ script: `export default {+ async fetch(request, env) {+ if (new URL(request.url).pathname === '/denied') return env.DIAGNOSTIC.fetch(request);+ return Response.json(await env.DIAGNOSTIC.runFixed());+ }+ }`,+ },+ ],+ }),+ );+ try {+ const diagnostic = await runtime.getWorker('diagnostic');+ assert.equal(+ (await diagnostic.fetch('http://localhost/run-fixed', { method: 'POST', body: '{}' }))+ .status,+ 404,+ );+ const operator = await runtime.getWorker('operator');+ assert.equal((await operator.fetch('http://localhost/denied')).status, 404);+ const first = await (await operator.fetch('http://localhost/run')).json();+ assert.equal(first.passed, false);+ assert.equal(first.reason, 'ISOLATION_UNAVAILABLE');+ assert.equal(first.stopped, true);+ assert.deepEqual(await (await operator.fetch('http://localhost/run')).json(), first);+ } finally {+ await runtime.dispose();+ }+ });+}diff --git a/hosting/test/storage-fault-worker.ts b/hosting/test/storage-fault-worker.tsindex 45180b46..1bc8dfd5 100644--- a/hosting/test/storage-fault-worker.ts+++ b/hosting/test/storage-fault-worker.ts@@ -6,19 +6,38 @@ import { serviceFailure } from '../src/http';// acknowledgement or reject deletion, while SQLite inspection controls faults.export class StorageFaultFixture extends DurableObject<{ ARTIFACTS: R2Bucket }> {private readonly artifacts: ArtifactStore;+ private held = new Map<string, () => void>();+ private heldOnce = new Set<string>();constructor(ctx: DurableObjectState, env: { ARTIFACTS: R2Bucket }) {super(ctx, env);ctx.storage.sql.exec('CREATE TABLE IF NOT EXISTS faults (name TEXT PRIMARY KEY)');const fault = (name: string) =>ctx.storage.sql.exec('SELECT 1 FROM faults WHERE name = ?', name).toArray().length > 0;+ const hold = (name: string) => {+ this.heldOnce.add(name);+ return new Promise<void>((resolve) => this.held.set(name, resolve));+ };+ const heldOnce = this.heldOnce;const bucket = new Proxy(env.ARTIFACTS, {get(target, key) {if (key === 'put')return async (...args: Parameters<R2Bucket['put']>) => {+ if (fault('hold-put')) {+ // The provider has accepted the bytes, but its commit can arrive+ // after our request deadline. This test control never ships.+ args[1] = await new Response(args[1]).arrayBuffer();+ await hold('put');+ }const result = await target.put(...args);if (fault('slow-ack')) await new Promise((resolve) => setTimeout(resolve, 1500));return result;};+ if (key === 'list')+ return async (...args: Parameters<R2Bucket['list']>) => {+ const result = await target.list(...args);+ if (fault('hold-list') && !heldOnce.has('list')) await hold('list');+ return result;+ };if (key === 'delete')return async (...args: Parameters<R2Bucket['delete']>) => {if (fault('delete-failure')) throw new Error('Injected deletion failure');@@ -32,7 +51,7 @@ export class StorageFaultFixture extends DurableObject<{ ARTIFACTS: R2Bucket }>this.artifacts = new ArtifactStore(ctx,bucket,- { maxBytes: 1024 * 1024, maxObjects: 32, maxGroups: 8 },+ { maxBytes: 1024 * 1024, maxObjects: 64, maxGroups: 8 },() =>fault('ticking-clock') ? ++fixtureClock : Date.now() + (fault('aged') ? 16 * 60 * 1000 : 0),500,@@ -44,6 +63,23 @@ export class StorageFaultFixture extends DurableObject<{ ARTIFACTS: R2Bucket }>async fetch(request: Request): Promise<Response> {try {const path = new URL(request.url).pathname;+ if (path === '/held') return Response.json([...this.held.keys()]);+ if (path.startsWith('/release/')) {+ const name = path.slice('/release/'.length);+ this.held.get(name)?.();+ this.held.delete(name);+ return new Response('Released');+ }+ if (path === '/retire') return Response.json(await this.artifacts.retire());+ if (path === '/status')+ return Response.json({+ ...this.artifacts.retirementStatus(),+ alarm: await this.ctx.storage.getAlarm(),+ });+ if (path === '/run-alarm') {+ await this.alarm();+ return new Response('Alarm finished');+ }if (path === '/upload-short' || path === '/upload-large' || path === '/upload-negative') {const headers = new Headers(request.headers);headers.set(diff --git a/hosting/test/storage-fault.test.mjs b/hosting/test/storage-fault.test.mjsindex 3ad4290c..30262fa2 100644--- a/hosting/test/storage-fault.test.mjs+++ b/hosting/test/storage-fault.test.mjs@@ -54,6 +54,135 @@ const upload = (owner, path = '/upload') =>},});const prefix = (owner) => `tenants/${namespace.idFromName(owner)}/artifacts/`;+const status = async (owner) => (await send(owner, '/status')).json();+async function until(predicate) {+ const deadline = Date.now() + 4000;+ while (!(await predicate())) {+ assert(Date.now() < deadline, 'Fixture did not reach the expected state');+ await delay(10);+ }+}++test('retirement waits for a late write and maintenance preserves its durable evidence', async () => {+ const owner = 'retire-late-put';+ const db = await database(owner);+ await db.exec("INSERT INTO faults VALUES ('hold-put')");+ const pending = upload(owner);+ try {+ await until(async () => (await (await send(owner, '/held')).json()).includes('put'));+ assert.equal((await pending).status, 502);+ assert.equal((await send(owner, '/sweep')).status, 200);+ assert.equal((await status(owner)).remainingObjects, 1, 'retain unresolved write metadata');+ const retired = await (await send(owner, '/retire')).json();+ assert.equal(retired.state, 'retiring');+ assert.equal(retired.pendingWrites, 1);+ assert.equal((await upload(owner)).status, 410);+ await send(owner, '/release/put');+ await until(async () => (await status(owner)).pendingWrites === 0);+ await send(owner, '/run-alarm');+ assert.deepEqual(await status(owner), {+ state: 'purged',+ pendingWrites: 0,+ remainingObjects: 0,+ alarm: null,+ });+ assert.equal(+ (await (await runtime.getR2Bucket('ARTIFACTS')).list({ prefix: prefix(owner) })).objects+ .length,+ 0,+ );+ } finally {+ await send(owner, '/release/put');+ await pending;+ }+});++test('failed retirement stays denied across eviction and retries deletion before clearing its alarm', async () => {+ const owner = 'retire-failed-delete';+ const db = await database(owner);+ const record = await (await upload(owner)).json();+ await db.exec("INSERT INTO faults VALUES ('delete-failure')");+ assert.equal((await send(owner, '/retire')).status, 503);+ assert.equal((await status(owner)).state, 'retiring');+ assert.equal((await status(owner)).remainingObjects, 1);+ assert.notEqual((await status(owner)).alarm, null);+ await runtime.unsafeEvictDurableObject('faults', 'StorageFaultFixture', {+ id: namespace.idFromName(owner).toString(),+ });+ assert.equal((await upload(owner)).status, 410);+ assert.equal((await send(owner, `/download/${record.id}`)).status, 404);+ await db.exec('DELETE FROM faults');+ assert.equal((await send(owner, '/run-alarm')).status, 200);+ assert.deepEqual(await status(owner), {+ state: 'purged',+ pendingWrites: 0,+ remainingObjects: 0,+ alarm: null,+ });+});++test('retirement recovers a lost put acknowledgement only from matching committed bytes', async () => {+ for (const committed of [false, true]) {+ const owner = `retire-lost-ack-${committed}`;+ const db = await database(owner);+ const record = await (await upload(owner)).json();+ await db.exec("UPDATE artifacts SET state='uploading',created_at=1");+ await db.exec('INSERT INTO artifact_writes VALUES (?)', record.id);+ if (!committed)+ await (await runtime.getR2Bucket('ARTIFACTS')).delete(prefix(owner) + record.id);+ await runtime.unsafeEvictDurableObject('faults', 'StorageFaultFixture', {+ id: namespace.idFromName(owner).toString(),+ });+ const result = await (await send(owner, '/retire')).json();+ assert.equal(result.state, committed ? 'purged' : 'retiring');+ assert.equal(result.pendingWrites, committed ? 0 : 1);+ assert.equal((await upload(owner)).status, 410);+ if (!committed) assert.notEqual((await status(owner)).alarm, null);+ }+});++test('an older maintenance pass cannot recreate metadata or alarms after retirement', async () => {+ const owner = 'retire-maintenance-race';+ const db = await database(owner);+ await db.exec("INSERT INTO faults VALUES ('hold-list')");+ const pending = send(owner, '/sweep');+ try {+ await until(async () => (await (await send(owner, '/held')).json()).includes('list'));+ assert.equal((await (await send(owner, '/retire')).json()).state, 'purged');+ await send(owner, '/release/list');+ assert.equal((await pending).status, 200);+ assert.equal((await db.exec('SELECT COUNT(*) AS n FROM maintenance'))[0].n, 0);+ assert.equal((await status(owner)).alarm, null);+ } finally {+ await send(owner, '/release/list');+ await pending;+ }+});++test('an unresolved write batch cannot indefinitely block retention of other expired files', async () => {+ const owner = 'retention-pending-batch';+ const db = await database(owner);+ const record = await (await upload(owner)).json();+ for (let i = 0; i < 32; i++) {+ const id = randomBytes(16).toString('hex');+ await db.exec(+ "INSERT INTO artifacts SELECT ?,?,sha256,bytes,filename,media_type,1,1,'uploading' FROM artifacts WHERE id=?",+ id,+ prefix(owner) + id,+ record.id,+ );+ await db.exec('INSERT INTO artifact_writes VALUES (?)', id);+ }+ await send(owner, '/sweep');+ await db.exec('UPDATE artifacts SET expires_at=1 WHERE id=?', record.id);+ assert.equal((await send(owner, '/sweep')).status, 200);+ assert.equal(+ await (await runtime.getR2Bucket('ARTIFACTS')).head(prefix(owner) + record.id),+ null,+ );+ assert.equal((await status(owner)).pendingWrites, 32);+ assert.equal((await status(owner)).remainingObjects, 32);+});test('unsaved retention uses one creation instant even when the clock advances', async () => {const db = await database('retention-clock');diff --git a/hosting/test/storage.test.mjs b/hosting/test/storage.test.mjsindex 06658957..95c7ff01 100644--- a/hosting/test/storage.test.mjs+++ b/hosting/test/storage.test.mjs@@ -64,7 +64,110 @@ const save = (owner, key, files, metadata = {}) =>});const get = (owner, id) => send(owner, `/mcp/artifacts/${id}`);const sweep = (owner) => send(owner, '/internal/maintenance', { method: 'POST' });+const retire = (owner) => send(owner, '/internal/account-deletion', { method: 'POST' });const usage = async (owner) => (await send(owner, '/internal/usage')).json();++test('account storage retirement erases saved and unsaved bytes while preserving another tenant', async () => {+ const owner = 'retire-account',+ other = 'retire-account-other';+ const saved = (await upload(owner)).record,+ unsaved = (await upload(owner, Buffer.from('unsaved'))).record;+ const foreign = (await upload(other)).record;+ assert.equal(+ (+ await save(+ owner,+ 'library/saved/revision',+ { 'asset.glb': saved.id },+ { name: 'Private title' },+ )+ ).status,+ 201,+ );+ const response = await retire(owner);+ assert.equal(response.status, 200);+ assert.equal((await response.json()).state, 'purged');+ for (const path of [+ '/internal/usage',+ '/internal/programs',+ `/mcp/artifacts/${saved.id}`,+ `/mcp/artifacts/${unsaved.id}`,+ ])+ assert.equal((await send(owner, path)).status, 410);+ assert.equal((await upload(owner)).response.status, 410);+ assert.equal(+ (await save(owner, 'library/recreate/revision', { 'asset.glb': saved.id })).status,+ 410,+ );+ const bucket = await runtime.getR2Bucket('ARTIFACTS');+ assert.equal(+ (await bucket.list({ prefix: `tenants/${namespace.idFromName(owner)}/artifacts/` })).objects+ .length,+ 0,+ );+ assert.equal((await get(other, foreign.id)).status, 200);+ const db = await database(owner);+ for (const table of ['saved_groups', 'group_files', 'artifacts', 'asset_download_tickets'])+ assert.equal((await db.exec(`SELECT COUNT(*) AS n FROM ${table}`))[0].n, 0);+ await runtime.unsafeEvictDurableObject('tenant', 'KilnTenant', {+ id: namespace.idFromName(owner).toString(),+ });+ assert.equal((await upload(owner)).response.status, 410);+ assert.equal((await (await retire(owner)).json()).state, 'purged');+});++test('retirement removes every orphan in bounded prefix-only batches', async () => {+ const owner = 'retire-orphans';+ await send(owner, '/internal/usage');+ const bucket = await runtime.getR2Bucket('ARTIFACTS');+ const prefix = `tenants/${namespace.idFromName(owner)}/artifacts/`;+ for (let i = 0; i < 105; i++) await bucket.put(`${prefix}orphan-${i}`, 'discard');+ const foreign = `tenants/${namespace.idFromName('retire-orphans-other')}/artifacts/other`;+ await bucket.put(foreign, 'keep');+ const first = await (await retire(owner)).json();+ assert.equal(first.state, 'retiring');+ assert.equal((await bucket.list({ prefix })).objects.length, 5);+ assert.equal((await (await retire(owner)).json()).state, 'purged');+ assert.equal(await (await bucket.get(foreign)).text(), 'keep');+});++test('storage retirement rejects identity selectors, bodies and unsupported methods before any mutation', async () => {+ const owner = 'retire-invalid';+ for (const init of [+ { method: 'GET' },+ { method: 'DELETE' },+ { method: 'POST', headers: { authorization: 'Bearer attacker' } },+ { method: 'POST', headers: { 'x-tenant-id': 'other' } },+ { method: 'POST', headers: { cookie: 'session=attacker' } },+ { method: 'POST', body: '{}' },+ ]) {+ assert.equal((await send(owner, '/internal/account-deletion', init)).status, 400);+ assert.equal((await send(owner, '/internal/usage')).status, 200);+ }+});++test('download ticket revocation commits in the same retirement transaction as the storage deny', async () => {+ const owner = 'retire-atomic-tickets';+ const record = (await upload(owner)).record;+ const group = await (await save(owner, 'saved/revision', { 'asset.glb': record.id })).json();+ const db = await database(owner);+ await db.exec(+ 'INSERT INTO asset_download_tickets VALUES (?,?,?,0)',+ 'synthetic-ticket',+ group.id,+ Date.now() + 600_000,+ );+ await db.exec(+ "CREATE TRIGGER retirement_fault BEFORE UPDATE ON artifacts BEGIN SELECT RAISE(ABORT,'injected'); END",+ );+ assert.equal((await retire(owner)).status, 503);+ assert.equal((await send(owner, '/internal/usage')).status, 200);+ assert.equal((await db.exec('SELECT COUNT(*) AS n FROM asset_download_tickets'))[0].n, 1);+ assert.equal((await get(owner, record.id)).status, 200);+ await db.exec('DROP TRIGGER retirement_fault');+ assert.equal((await (await retire(owner)).json()).state, 'purged');+ assert.equal((await db.exec('SELECT COUNT(*) AS n FROM asset_download_tickets'))[0].n, 0);+});async function database(owner) {return runtime.unsafeGetDurableObjectStorage('tenant', 'KilnTenant', {id: namespace.idFromName(owner).toString(),@@ -81,6 +184,14 @@ test('private tenant worker has no public upload or download route', async () =>).status,404,);+ assert.equal(+ (+ await runtime.dispatchFetch('https://anything.example/internal/account-deletion', {+ method: 'POST',+ })+ ).status,+ 404,+ );});test('uploaded bytes are immutable, tenant-private and downloadable with exact metadata', async () => {diff --git a/hosting/test/worker.ts b/hosting/test/worker.tsindex 0fd3bc0b..5bac2d0f 100644--- a/hosting/test/worker.ts+++ b/hosting/test/worker.ts@@ -1,4 +1,4 @@-import { DurableObject } from 'cloudflare:workers';+import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';export { default } from '../src/worker';// This test-only backend records routing and transport data. It never evaluates@@ -13,3 +13,10 @@ export class TestTenant extends DurableObject {});}}++// Auth tests observe routing only. Actual admission/compute has separate fixtures.+export class TestCompute extends WorkerEntrypoint<{ TENANTS: DurableObjectNamespace }> {+ dispatch(tenant: string, request: Request): Promise<Response> {+ return this.env.TENANTS.getByName(tenant).fetch(request);+ }+}diff --git a/hosting/tsconfig.json b/hosting/tsconfig.jsonindex 7be393f5..cb505152 100644--- a/hosting/tsconfig.json+++ b/hosting/tsconfig.json@@ -3,7 +3,7 @@"target": "ES2022","module": "ESNext","moduleResolution": "Bundler",- "lib": ["ES2022"],+ "lib": ["ES2022", "ESNext.Disposable"],"types": ["@cloudflare/workers-types"],"strict": true,"noEmit": true,diff --git a/hosting/tsconfig.native.json b/hosting/tsconfig.native.jsonindex 48e2185c..9fcf0d3a 100644--- a/hosting/tsconfig.native.json+++ b/hosting/tsconfig.native.json@@ -6,9 +6,12 @@"paths": {"@instruktlabs/kiln/assets": ["../lib/assets.d.ts"],"@instruktlabs/kiln/assets/node": ["../lib/assets-node.d.ts"],+ "@instruktlabs/kiln/material-library": ["../lib/material-library.d.ts"],+ "@instruktlabs/kiln/workspace": ["../lib/workspace.d.ts"],"@instruktlabs/kiln/material-library/node": ["../lib/material-library-node.d.ts"],"@instruktlabs/kiln/evaluator": ["../lib/evaluator/index.d.ts"],- "@instruktlabs/kiln/tools": ["../lib/tools/registry.d.ts"]+ "@instruktlabs/kiln/tools": ["../lib/tools/registry.d.ts"],+ "@instruktlabs/kiln/composer": ["../lib/composer/index.d.ts"]}},"include": ["src/native-*.ts"],diff --git a/hosting/tsconfig.probe.json b/hosting/tsconfig.probe.jsonnew file mode 100644index 00000000..b4db479d--- /dev/null+++ b/hosting/tsconfig.probe.json@@ -0,0 +1,5 @@+{+ "extends": "./tsconfig.json",+ "include": ["probe/**/*.ts", "src/container-job.ts"],+ "exclude": []+}diff --git a/plugins/kiln-engine.release.json b/plugins/kiln-engine.release.jsonnew file mode 100644index 00000000..431dad8f--- /dev/null+++ b/plugins/kiln-engine.release.json@@ -0,0 +1,4 @@+{+ "version": "1.0.1",+ "engineVersion": "1.0.0"+}diff --git a/plugins/kiln-engine/.claude-plugin/icon.png b/plugins/kiln-engine/.claude-plugin/icon.pngnew file mode 100644index 00000000..f380acc0Binary files /dev/null and b/plugins/kiln-engine/.claude-plugin/icon.png differdiff --git a/plugins/kiln-engine/.claude-plugin/plugin.json b/plugins/kiln-engine/.claude-plugin/plugin.jsonindex 57737b31..e364d499 100644--- a/plugins/kiln-engine/.claude-plugin/plugin.json+++ b/plugins/kiln-engine/.claude-plugin/plugin.json@@ -1,9 +1,10 @@{"name": "kiln-engine",- "version": "1.0.0",+ "version": "1.0.1","description": "Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.","author": {- "name": "Instrukt Labs"+ "name": "Instrukt Labs",+ "email": "[email protected]"},"homepage": "https://github.com/instruktlabs/kiln","repository": "https://github.com/instruktlabs/kiln",@@ -14,5 +15,10 @@"gltf","asset-generation","gamedev"- ]+ ],+ "icon": "./.claude-plugin/icon.png",+ "documentationUrl": "https://github.com/instruktlabs/kiln/tree/main/plugins/kiln-engine",+ "supportUrl": "https://github.com/instruktlabs/kiln/blob/main/plugins/kiln-engine/README.md#support-and-security",+ "privacyPolicyUrl": "https://github.com/instruktlabs/kiln/blob/main/docs/local-plugin-privacy.md",+ "termsOfServiceUrl": "https://github.com/instruktlabs/kiln/blob/main/LICENSE"}diff --git a/plugins/kiln-engine/PRIVACY.md b/plugins/kiln-engine/PRIVACY.mdnew file mode 100644index 00000000..4fba8ceb--- /dev/null+++ b/plugins/kiln-engine/PRIVACY.md@@ -0,0 +1,83 @@+# Kiln local plugin privacy++Draft for owner review before directory submission. Updated 7 October 2026.++This notice covers the `kiln-engine` local plugin maintained by Instrukt Labs and+the local workspace it sets up. It does not cover the separate hosted Kiln service+or your coding assistant's account and conversation history. The local plugin does+not require a Kiln account, an email address, payment details or a model API key.++## What stays on your computer++Setup reads its public package/version pin, locates Node and npm, and checks the+workspace and runtime directories you select. It installs the engine in a persistent+data directory outside the plugin cache. Paths can contain your device account+name; paths, package identity and file hashes appear in local configuration,+installation records and command results returned to your assistant.++Your workspace and configured asset libraries hold authored JavaScript, material+files, asset names, metadata, previews and GLBs. Local tools read and write the+work you ask them to handle and return requested source, images and results to+your coding assistant. Avoid putting personal or confidential information in a+source file, asset name or tool argument unless you intend your assistant to see it.++The local plugin does not send these assets to an Instrukt Labs service or add+analytics reporting. Your assistant can send prompts and tool results to its own+provider. That processing, and any assistant history or backups, follows the+assistant's settings and privacy policy. Kiln does not control those copies.++## Network access and other services++- Installing or updating the marketplace/plugin contacts GitHub through your+ coding assistant or Git. Setup downloads the exact engine version and its+ dependencies through npm using `https://registry.npmjs.org`. Those services+ receive download requests and ordinary connection information, including your+ IP address. No asset upload is part of setup.+- npm runs with lifecycle scripts, audit and funding requests disabled. It can+ still use your existing npm configuration and inherited environment, including+ registry authentication you already configured. Kiln does not request an npm+ login or registry token for this public package, copy credentials into the+ plugin, or promise to strip npm's normal credential configuration. npm also+ writes to its normal cache and log directories.+- CPU rendering is local. An optional local render service stays on your machine.+ If you explicitly configure a renderer on another machine, Kiln sends the GLB+ and capture settings to that chosen endpoint and uses its configured+ authentication. Review that operator's privacy and retention practices first.+- Opening documentation, filing a GitHub issue or contacting support uses the+ service you choose. Information in a public issue is public; it is not private+ telemetry from your local workspace.++Relevant service policies: [npm](https://docs.npmjs.com/policies/privacy/),+[GitHub](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement),+[Claude](https://www.anthropic.com/legal/privacy) and+[OpenAI](https://openai.com/policies/privacy-policy/). Other assistants and optional+renderer operators provide their own policies.++## Retention and deletion++Local source, saved assets, runtime installations and workspace configuration+remain until you delete them. Uninstalling the plugin removes neither your assets+nor its separately installed engine. Plugin updates also leave existing+workspaces on their installed engine until you request a managed upgrade.++There is no automatic seven-day expiry for local work; that is a separate hosted+service policy. Remove selected local work using Kiln's library controls or your+filesystem, and manage independent exports, backups, npm caches and assistant+histories through their respective applications. Preserve copies you want before+deleting a workspace or runtime.++## Support and security++Contact [[email protected]](mailto:[email protected]) for privacy+questions, deletion requests concerning information you sent to support, or+private security reports. Support receives only what you send, including your+email address and message. Support mail is forwarded through Cloudflare to the+maintainer's Google inbox; see [Cloudflare's privacy policy](https://www.cloudflare.com/privacypolicy/)+and [Google's privacy policy](https://policies.google.com/privacy). We use support+correspondence to handle the request; this is not an automatic local-plugin alert+or a mailing-list signup.++Do not send passwords, tokens, recovery codes or private assets with a bug report.+Sanitize logs and paths before posting publicly. Instrukt Labs cannot remotely+access or erase your local workspace, your assistant's copies or a renderer+operator's records through this plugin.diff --git a/plugins/kiln-engine/README.md b/plugins/kiln-engine/README.mdindex 8c76de9f..494f4131 100644--- a/plugins/kiln-engine/README.md+++ b/plugins/kiln-engine/README.md@@ -1,25 +1,90 @@# Kiln Engine local plugin-Version 1.0.0, published by Instrukt Labs under the MIT license.+Plugin version 1.0.1, maintained by Instrukt Labs under the MIT license.+This plugin installs engine 1.0.0.-Ask your coding agent to set up a Kiln workspace. The setup skill installs-`@instruktlabs/[email protected]` with npm and creates a separate asset workspace.-Use a supported Node.js installation with npm; no Bun, engine clone or separate-model API key is required. The workspace's START.md explains how to reopen it.+Set up a persistent Kiln workspace for Claude Code or Codex, then create and revise+editable 3D assets with your coding agent. Use a supported Node.js installation+with npm. No Bun, engine checkout, Kiln account or separate model API key is needed.+The plugin requires a local shell and filesystem; Claude chat and Cowork are not+supported by this local bundle.-The plugin registers setup only. The workspace supplies the authoring skills-and one local MCP server, `kiln_workspace`. Open Claude Code in that workspace;-launch Codex there with `node codex.mjs`. Accept the host's ordinary trust prompts-and verify live tool discovery before authoring.+## Install++For Claude Code:++```sh+claude plugin marketplace add instruktlabs/kiln+claude plugin install kiln-engine@instruktlabs+```++For Codex:++```sh+codex plugin marketplace add instruktlabs/kiln+codex plugin add kiln-engine@instruktlabs+```++Restart or reload your coding agent's plugins as its installation message directs.+Then ask it to set up a Kiln workspace. The maintained setup skill runs this+plugin's `bin/kiln-setup-workspace.mjs` with Node, installs+`@instruktlabs/[email protected]` and creates a separate asset workspace.++The plugin registers setup only. The workspace supplies authoring skills and one+local MCP server, `kiln_workspace`. Open Claude Code in that workspace; launch+Codex there with `node codex.mjs`. Follow `START.md`, accept the host's ordinary+trust prompts and verify live tool discovery before authoring.++## Three setup examples++1. **Create:** “Set up a new Kiln workspace in an empty directory outside this+ checkout, using my current coding agent. Verify its tools before I author an+ asset.” The installer downloads the pinned engine when needed, creates the+ selected workspace and keeps its engine in a separate runtime store. npm also+ uses its normal cache and log directories.+2. **Check:** “Check my existing Kiln workspace without changing it.” The helper's+ `--check` mode reports whether managed files and the installed engine are+ current. A missing runtime is reported without installing one.+3. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,+ saved assets and customizations.” Stop the workspace's harness session first.+ The helper's `--upgrade` mode uses the pinned engine and refuses conflicts+ rather than replacing customized managed files.The engine installation and your assets stay outside the disposable plugin cache.-Plugin removal or updating its cached files does not delete them. An existing-workspace remains on its installed engine until an explicit managed upgrade.-Read [setup and upgrade guidance](skills/kiln-setup-workspace/references/plugin-install.md).+Removing or updating the plugin does not delete them. Existing workspaces stay on+their installed engine until an explicit managed upgrade. Read the+[setup and upgrade guide](skills/kiln-setup-workspace/references/plugin-install.md)+for paths, repair and failure recovery.++## Execution and network access++The setup skill asks your coding agent to execute a bundled Node installer. That+installer runs npm with lifecycle scripts disabled and invokes Kiln's workspace+generator. It does this before the workspace MCP server exists; it does not+silently install a global MCP server or grant itself shell permissions.++Marketplace installation and updates contact `https://github.com`. First engine+installation and dependency downloads use `https://registry.npmjs.org`. npm can+use your existing npm configuration and environment. No npm login or token is+required for this public package. Normal local asset work does not upload your+assets to Instrukt Labs. Tool results can enter your coding assistant's model+context; its provider handles those copies.++CPU rendering is local. Material appearance needs a compatible local renderer or+one you explicitly configure on another machine; a remote renderer receives the+GLB and requested capture settings. Follow the setup skill's renderer checks.+The separate hosted Kiln integration has its own authentication and privacy notice.++## Support and security++Send private security or privacy questions to+[[email protected]](mailto:[email protected]). Never include+passwords, tokens, recovery codes or private assets in public issues. For a normal+bug report, provide the plugin and engine versions, operating system and a small+sanitized reproduction at [GitHub issues](https://github.com/instruktlabs/kiln/issues).-CPU rendering is available locally. Material appearance requires a qualified-renderer; follow the setup skill's renderer checks rather than assuming GPU support.-Hosted ChatGPT access is a separate integration, and this local bundle is not a-public OpenAI directory submission.+If setup fails, retain the error, check Node/npm and network access, and follow the+setup guide. Do not delete an unfamiliar runtime or another installer's lock.-[Source and issues](https://github.com/instruktlabs/kiln)+[Local privacy notice](PRIVACY.md) · [MIT license](LICENSE) ·+[Source](https://github.com/instruktlabs/kiln)diff --git a/plugins/kiln-engine/scripts/setup-workspace.mjs b/plugins/kiln-engine/bin/kiln-setup-workspace.mjsold mode 100644new mode 100755similarity index 97%rename from plugins/kiln-engine/scripts/setup-workspace.mjsrename to plugins/kiln-engine/bin/kiln-setup-workspace.mjsindex e0c774ab..c8386a00--- a/plugins/kiln-engine/scripts/setup-workspace.mjs+++ b/plugins/kiln-engine/bin/kiln-setup-workspace.mjs@@ -323,7 +323,7 @@ if (const options = parseSetupArguments(process.argv.slice(2));if (options.help)console.log(- 'Usage: node scripts/setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node scripts/setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',+ 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',);else {const result = await setupPluginWorkspace(options);diff --git a/plugins/kiln-engine/package-provenance.json b/plugins/kiln-engine/package-provenance.jsonindex 34e81b73..ef2cc81f 100644--- a/plugins/kiln-engine/package-provenance.json+++ b/plugins/kiln-engine/package-provenance.json@@ -1,15 +1,21 @@{"schemaVersion": 1,"kind": "kiln-local-plugin",+ "pluginVersion": "1.0.1","engineVersion": "1.0.0",+ "executables": [+ "bin/kiln-setup-workspace.mjs"+ ],"files": {- ".claude-plugin/plugin.json": "sha256:c40c7eafed4c0822faef83178633f3bf3449311220f709d5155aed4a9c74cd6b",+ ".claude-plugin/icon.png": "sha256:b4b651c402793b7e27cab780f04b14f80daec6d0cd5b7e4e90313930581a54e9",+ ".claude-plugin/plugin.json": "sha256:1c9a759df304878ca9b730b1c317fea48f07840e4cc38ae68b2a9d5a6670f8b4",+ "bin/kiln-setup-workspace.mjs": "sha256:31cd8c0b1028b8df487b7b333655d0dd5e456ae8d7dcadad687557dd3202cf3e","LICENSE": "sha256:cdba278ebf1d6de618869936226bf03be4887179c128efc7aaa13d22034826a5",- "plugin.json": "sha256:f80ecc90d141adf45e5fadfe5092c325e9174f02b364c1e0059cd5bd345eaaf1",- "README.md": "sha256:3a9482e4e8e47b8ef7fb27d2d880253397a7f903b7ccdd64794995fd3075d2dd",+ "plugin.json": "sha256:a877b48b4ddad084cc8ddffd819a7f091bd00991306f62753e5576a034490b2b",+ "PRIVACY.md": "sha256:4bd5eb34e9a936a2356aca8633c0f1bceeccb320b161dd47abbe608170fd2cd4",+ "README.md": "sha256:c71f9b9c2dd7cb56b87ca4dce454de128e3da8812b27d06275a7d4db35b5d689","runtime.json": "sha256:18129a1d310c468aeba0966792940242f0359ab14c41a4c9ef240310d07d3bd2",- "scripts/setup-workspace.mjs": "sha256:0936f482a213706cf1576da11e57d40993b90f42b486f262e55d38d8d27b2e4d",- "skills/kiln-setup-workspace/references/plugin-install.md": "sha256:84f4ce4c9620aae1e6b37a6a04f5c874feae507c9e7a2f24fe62e48bbe6c09bd",- "skills/kiln-setup-workspace/SKILL.md": "sha256:9dbcb66514e21ea11b097bb1cd4b27b616834ded3e8182ea804f370add37a69f"+ "skills/kiln-setup-workspace/references/plugin-install.md": "sha256:a8e1758d851b8d52f3b9266c27be05d25134f10257501f8d8c7429e8687935e2",+ "skills/kiln-setup-workspace/SKILL.md": "sha256:7101b92d34c478e63d4cd96183cfebd383c7134883ab758a2c93d883f7066c5b"}}diff --git a/plugins/kiln-engine/plugin.json b/plugins/kiln-engine/plugin.jsonindex 699c644a..48fbd22f 100644--- a/plugins/kiln-engine/plugin.json+++ b/plugins/kiln-engine/plugin.json@@ -1,10 +1,11 @@{"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name": "kiln-engine",- "version": "1.0.0",+ "version": "1.0.1","description": "Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.","author": {- "name": "Instrukt Labs"+ "name": "Instrukt Labs",+ "email": "[email protected]"},"homepage": "https://github.com/instruktlabs/kiln","repository": "https://github.com/instruktlabs/kiln",@@ -23,6 +24,10 @@"shortDescription": "Create editable 3D assets in a local workspace","longDescription": "Install the pinned Kiln engine and set up a workspace with local MCP tools and maintained authoring skills. Your coding agent supplies the model.","developerName": "Instrukt Labs",+ "websiteURL": "https://github.com/instruktlabs/kiln/tree/main/plugins/kiln-engine",+ "supportURL": "https://github.com/instruktlabs/kiln/blob/main/plugins/kiln-engine/README.md#support-and-security",+ "privacyPolicyURL": "https://github.com/instruktlabs/kiln/blob/main/docs/local-plugin-privacy.md",+ "termsOfServiceURL": "https://github.com/instruktlabs/kiln/blob/main/LICENSE","category": "Developer Tools","capabilities": ["Read",@@ -30,7 +35,8 @@],"defaultPrompt": ["Set up a Kiln workspace for this coding agent.",- "Check and upgrade my existing Kiln workspace."+ "Check my existing Kiln workspace without changing it.",+ "Upgrade my managed Kiln workspace while preserving my assets."]}}diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.mdindex 2f0aef1c..b1e637f9 100644--- a/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/SKILL.md@@ -18,7 +18,7 @@ Do not author assets inside the engine checkout. The authoring skills assume a w## Create the workspace-When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `scripts/setup-workspace.mjs`. Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.Choose an absolute path to an empty directory outside the checkout.diff --git a/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md b/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.mdindex 09df1184..c3f933f7 100644--- a/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md+++ b/plugins/kiln-engine/skills/kiln-setup-workspace/references/plugin-install.md@@ -4,19 +4,24 @@ The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creaan asset workspace. It carries setup guidance and a small installer; the engine,source stores and authored assets live outside the plugin cache. It needs asupported Node.js installation with npm, network access for first installation,-and no separate model API key.+and no separate model API key. Use it in Claude Code or Codex; it requires a local+shell and persistent filesystem and is not a Claude chat or Cowork plugin.Resolve the plugin root from this installed skill's absolute path: it is twodirectories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and-`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are+`bin/kiln-setup-workspace.mjs` exist there. Do not assume plugin path variables areavailable in an ordinary shell, and do not substitute an engine checkout.+Plugin version 1.0.0 used `scripts/setup-workspace.mjs`; if using that older+installation, confirm and use that file instead. Plugin and engine versions are+independent. `runtime.json` always names the exact engine to install.+For a fresh workspace, use an absolute empty destination outside both the pluginand its runtime data directory. Select `claude` or `codex` from the current hostor the user's stated choice:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex```The installer verifies the package name and exact version from `runtime.json`.@@ -43,8 +48,8 @@ For an existing managed workspace, stop its harness session and run the newplugin's helper with `--check`, then `--upgrade` when an update is intended:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --check+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --upgrade```Check is read-only and reports a missing pinned engine without installing it.diff --git a/scripts/package-local-plugin.mjs b/scripts/package-local-plugin.mjsindex 425306ac..1487e96b 100644--- a/scripts/package-local-plugin.mjs+++ b/scripts/package-local-plugin.mjs@@ -1,11 +1,20 @@#!/usr/bin/env nodeimport { createHash } from 'node:crypto';-import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';+import { chmod, lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');const json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);+const executable = 'bin/kiln-setup-workspace.mjs';+const repositoryUrl = 'https://github.com/instruktlabs/kiln';+const listingLinks = {+ documentationUrl: `${repositoryUrl}/tree/main/plugins/kiln-engine`,+ supportUrl: `${repositoryUrl}/blob/main/plugins/kiln-engine/README.md#support-and-security`,+ privacyPolicyUrl: `${repositoryUrl}/blob/main/docs/local-plugin-privacy.md`,+ termsOfServiceUrl: `${repositoryUrl}/blob/main/LICENSE`,+};+const exactVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:rc|dev)\.(0|[1-9]\d*))?$/;async function inventory(directory, prefix = '') {const files = new Map();@@ -29,19 +38,21 @@ async function inventory(directory, prefix = '') {async function expectedFiles() {const pkg = JSON.parse(await readFile(join(repo, 'package.json'), 'utf8'));- if (- pkg.name !== '@instruktlabs/kiln' ||- !/^\d+\.\d+\.\d+(?:-(?:rc|dev)\.\d+)?$/.test(pkg.version)- )+ if (pkg.name !== '@instruktlabs/kiln' || !exactVersion.test(pkg.version))throw new Error('The local plugin requires the exact Kiln release identity.');+ const release = JSON.parse(+ await readFile(join(repo, 'plugins/kiln-engine.release.json'), 'utf8'),+ );+ if (!exactVersion.test(release.version) || release.engineVersion !== pkg.version)+ throw new Error('The local plugin needs its own exact version and the current engine pin.');const identity = {name: 'kiln-engine',- version: pkg.version,+ version: release.version,description:'Set up a local Kiln workspace to create, inspect and revise editable 3D assets with Claude Code or Codex.',- author: { name: 'Instrukt Labs' },- homepage: 'https://github.com/instruktlabs/kiln',- repository: 'https://github.com/instruktlabs/kiln',+ author: { name: 'Instrukt Labs', email: '[email protected]' },+ homepage: repositoryUrl,+ repository: repositoryUrl,license: 'MIT',keywords: ['3d', 'glb', 'gltf', 'asset-generation', 'gamedev'],};@@ -56,11 +67,16 @@ async function expectedFiles() {longDescription:'Install the pinned Kiln engine and set up a workspace with local MCP tools and maintained authoring skills. Your coding agent supplies the model.',developerName: 'Instrukt Labs',+ websiteURL: listingLinks.documentationUrl,+ supportURL: listingLinks.supportUrl,+ privacyPolicyURL: listingLinks.privacyPolicyUrl,+ termsOfServiceURL: listingLinks.termsOfServiceUrl,category: 'Developer Tools',capabilities: ['Read', 'Write'],defaultPrompt: ['Set up a Kiln workspace for this coding agent.',- 'Check and upgrade my existing Kiln workspace.',+ 'Check my existing Kiln workspace without changing it.',+ 'Upgrade my managed Kiln workspace while preserving my assets.',],},},@@ -68,13 +84,15 @@ async function expectedFiles() {};const files = new Map([['plugin.json', json(portable)],- ['.claude-plugin/plugin.json', json(identity)],- ['runtime.json', json({ name: pkg.name, version: pkg.version })],- ['LICENSE', await readFile(join(repo, 'LICENSE'))],[- 'scripts/setup-workspace.mjs',- await readFile(join(repo, 'scripts/setup-plugin-workspace.mjs')),+ '.claude-plugin/plugin.json',+ json({ ...identity, icon: './.claude-plugin/icon.png', ...listingLinks }),],+ ['.claude-plugin/icon.png', await readFile(join(repo, 'assets/branding/kiln-512.png'))],+ ['runtime.json', json({ name: pkg.name, version: pkg.version })],+ ['LICENSE', await readFile(join(repo, 'LICENSE'))],+ ['PRIVACY.md', await readFile(join(repo, 'docs/local-plugin-privacy.md'))],+ [executable, await readFile(join(repo, 'scripts/setup-plugin-workspace.mjs'))],]);for (const [name, bytes] of await inventory(join(repo, 'skills/kiln-setup-workspace'),@@ -89,7 +107,97 @@ async function expectedFiles() {files.set('README.md',Buffer.from(- `# Kiln Engine local plugin\n\n${development}Version ${pkg.version}, published by Instrukt Labs under the MIT license.\n\nAsk your coding agent to set up a Kiln workspace. The setup skill installs\n\`${pkg.name}@${pkg.version}\` with npm and creates a separate asset workspace.\nUse a supported Node.js installation with npm; no Bun, engine clone or separate\nmodel API key is required. The workspace's START.md explains how to reopen it.\n\nThe plugin registers setup only. The workspace supplies the authoring skills\nand one local MCP server, \`kiln_workspace\`. Open Claude Code in that workspace;\nlaunch Codex there with \`node codex.mjs\`. Accept the host's ordinary trust prompts\nand verify live tool discovery before authoring.\n\nThe engine installation and your assets stay outside the disposable plugin cache.\nPlugin removal or updating its cached files does not delete them. An existing\nworkspace remains on its installed engine until an explicit managed upgrade.\nRead [setup and upgrade guidance](skills/kiln-setup-workspace/references/plugin-install.md).\n\nCPU rendering is available locally. Material appearance requires a qualified\nrenderer; follow the setup skill's renderer checks rather than assuming GPU support.\nHosted ChatGPT access is a separate integration, and this local bundle is not a\npublic OpenAI directory submission.\n\n[Source and issues](https://github.com/instruktlabs/kiln)\n`,+ `# Kiln Engine local plugin++${development}Plugin version ${release.version}, maintained by Instrukt Labs under the MIT license.+This plugin installs engine ${pkg.version}.++Set up a persistent Kiln workspace for Claude Code or Codex, then create and revise+editable 3D assets with your coding agent. Use a supported Node.js installation+with npm. No Bun, engine checkout, Kiln account or separate model API key is needed.+The plugin requires a local shell and filesystem; Claude chat and Cowork are not+supported by this local bundle.++## Install++For Claude Code:++\`\`\`sh+claude plugin marketplace add instruktlabs/kiln+claude plugin install kiln-engine@instruktlabs+\`\`\`++For Codex:++\`\`\`sh+codex plugin marketplace add instruktlabs/kiln+codex plugin add kiln-engine@instruktlabs+\`\`\`++Restart or reload your coding agent's plugins as its installation message directs.+Then ask it to set up a Kiln workspace. The maintained setup skill runs this+plugin's \`bin/kiln-setup-workspace.mjs\` with Node, installs+\`${pkg.name}@${pkg.version}\` and creates a separate asset workspace.++The plugin registers setup only. The workspace supplies authoring skills and one+local MCP server, \`kiln_workspace\`. Open Claude Code in that workspace; launch+Codex there with \`node codex.mjs\`. Follow \`START.md\`, accept the host's ordinary+trust prompts and verify live tool discovery before authoring.++## Three setup examples++1. **Create:** “Set up a new Kiln workspace in an empty directory outside this+ checkout, using my current coding agent. Verify its tools before I author an+ asset.” The installer downloads the pinned engine when needed, creates the+ selected workspace and keeps its engine in a separate runtime store. npm also+ uses its normal cache and log directories.+2. **Check:** “Check my existing Kiln workspace without changing it.” The helper's+ \`--check\` mode reports whether managed files and the installed engine are+ current. A missing runtime is reported without installing one.+3. **Upgrade:** “Upgrade my managed Kiln workspace while preserving my sources,+ saved assets and customizations.” Stop the workspace's harness session first.+ The helper's \`--upgrade\` mode uses the pinned engine and refuses conflicts+ rather than replacing customized managed files.++The engine installation and your assets stay outside the disposable plugin cache.+Removing or updating the plugin does not delete them. Existing workspaces stay on+their installed engine until an explicit managed upgrade. Read the+[setup and upgrade guide](skills/kiln-setup-workspace/references/plugin-install.md)+for paths, repair and failure recovery.++## Execution and network access++The setup skill asks your coding agent to execute a bundled Node installer. That+installer runs npm with lifecycle scripts disabled and invokes Kiln's workspace+generator. It does this before the workspace MCP server exists; it does not+silently install a global MCP server or grant itself shell permissions.++Marketplace installation and updates contact \`https://github.com\`. First engine+installation and dependency downloads use \`https://registry.npmjs.org\`. npm can+use your existing npm configuration and environment. No npm login or token is+required for this public package. Normal local asset work does not upload your+assets to Instrukt Labs. Tool results can enter your coding assistant's model+context; its provider handles those copies.++CPU rendering is local. Material appearance needs a compatible local renderer or+one you explicitly configure on another machine; a remote renderer receives the+GLB and requested capture settings. Follow the setup skill's renderer checks.+The separate hosted Kiln integration has its own authentication and privacy notice.++## Support and security++Send private security or privacy questions to+[[email protected]](mailto:[email protected]). Never include+passwords, tokens, recovery codes or private assets in public issues. For a normal+bug report, provide the plugin and engine versions, operating system and a small+sanitized reproduction at [GitHub issues](https://github.com/instruktlabs/kiln/issues).++If setup fails, retain the error, check Node/npm and network access, and follow the+setup guide. Do not delete an unfamiliar runtime or another installer's lock.++[Local privacy notice](PRIVACY.md) · [MIT license](LICENSE) ·+[Source](https://github.com/instruktlabs/kiln)+`,),);const hashes = Object.fromEntries(@@ -102,11 +210,13 @@ async function expectedFiles() {json({schemaVersion: 1,kind: 'kiln-local-plugin',+ pluginVersion: release.version,engineVersion: pkg.version,+ executables: [executable],files: hashes,}),);- return { files, version: pkg.version };+ return { files, version: release.version };}export async function packageLocalPlugin(destination, options = {}) {@@ -122,6 +232,11 @@ export async function packageLocalPlugin(destination, options = {}) {throw new Error(`Local plugin is stale: ${changed.join(', ')}. Generate a fresh bundle and review its changes.`,);+ if (+ process.platform !== 'win32' &&+ ((await lstat(join(directory, executable))).mode & 0o111) !== 0o111+ )+ throw new Error(`Local plugin entry must be executable: ${executable}`);return { directory, version, files: files.size - 1, current: true };}// Refuse both populated and empty existing destinations, including symlinks.@@ -136,6 +251,7 @@ export async function packageLocalPlugin(destination, options = {}) {for (const [name, bytes] of files) {await mkdir(dirname(join(directory, name)), { recursive: true });await writeFile(join(directory, name), bytes, { flag: 'wx' });+ if (name === executable) await chmod(join(directory, name), 0o755);}return { directory, version, files: files.size - 1 };}diff --git a/scripts/package-local-plugin.test.mjs b/scripts/package-local-plugin.test.mjsindex 0c690680..bf5e9455 100644--- a/scripts/package-local-plugin.test.mjs+++ b/scripts/package-local-plugin.test.mjs@@ -1,8 +1,20 @@import { afterEach, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';import { createHash } from 'node:crypto';-import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';+import {+ chmod,+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ realpath,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, resolve, sep } from 'node:path';+import { PNG } from 'pngjs';import { packageLocalPlugin } from './package-local-plugin.mjs';const roots = [];@@ -20,20 +32,29 @@ async function destination() {}const readJson = async (file) => JSON.parse(await readFile(file, 'utf8'));-test('local plugin has portable and Claude identities pinned to the engine', async () => {+test('local plugin versions independently while retaining its exact engine pin', async () => {const directory = await destination();await packageLocalPlugin(directory);const pkg = await readJson(resolve('package.json'));+ const release = await readJson(resolve('plugins/kiln-engine.release.json'));const portable = await readJson(join(directory, 'plugin.json'));const claude = await readJson(join(directory, '.claude-plugin/plugin.json'));expect(portable.$schema).toBe('https://agent-plugins.org/schemas/1.0.0/plugin.schema.json');expect(portable).toMatchObject({name: 'kiln-engine',- version: pkg.version,+ version: release.version,author: { name: 'Instrukt Labs' },});expect(claude.name).toBe(portable.name);expect(claude.version).toBe(portable.version);+ expect(claude.icon).toBe('./.claude-plugin/icon.png');+ expect(claude.privacyPolicyUrl).toBe(+ 'https://github.com/instruktlabs/kiln/blob/main/docs/local-plugin-privacy.md',+ );+ expect(portable.extensions['com.openai'].interface.privacyPolicyURL).toBe(+ claude.privacyPolicyUrl,+ );+ expect(release.engineVersion).toBe(pkg.version);expect(await readJson(join(directory, 'runtime.json'))).toEqual({name: pkg.name,version: pkg.version,@@ -41,6 +62,11 @@ test('local plugin has portable and Claude identities pinned to the engine', asyexpect(portable.extensions['com.openai'].interface.displayName).toBe('Kiln Engine');expect(portable.mcpServers).toBeUndefined();expect(claude.mcpServers).toBeUndefined();+ const icon = await readFile(join(directory, '.claude-plugin/icon.png'));+ const decoded = PNG.sync.read(icon);+ expect(decoded.width).toBe(512);+ expect(decoded.height).toBe(512);+ expect(icon.length).toBeLessThan(2 * 1024 * 1024);});test('bundle registers setup alone and keeps its complete maintained reference and helper', async () => {@@ -52,9 +78,12 @@ test('bundle registers setup alone and keeps its complete maintained reference aawait readFile(resolve('skills/kiln-setup-workspace', file), 'utf8'),);}- expect(await readFile(join(directory, 'scripts/setup-workspace.mjs'), 'utf8')).toBe(+ expect(await readFile(join(directory, 'bin/kiln-setup-workspace.mjs'), 'utf8')).toBe(await readFile(resolve('scripts/setup-plugin-workspace.mjs'), 'utf8'),);+ expect(await readFile(join(directory, 'PRIVACY.md'), 'utf8')).toBe(+ await readFile(resolve('docs/local-plugin-privacy.md'), 'utf8'),+ );const entries = await readdir(directory);for (const excluded of ['src',@@ -68,10 +97,40 @@ test('bundle registers setup alone and keeps its complete maintained reference a'AGENTS.md','package.json','hooks',+ 'scripts',])expect(entries).not.toContain(excluded);});+test('the shipped executable runs outside the checkout and is executable on POSIX', async () => {+ const directory = await destination();+ await packageLocalPlugin(directory);+ const script = join(directory, 'bin/kiln-setup-workspace.mjs');+ expect((await readFile(script, 'utf8')).startsWith('#!/usr/bin/env node\n')).toBe(true);+ const run = spawnSync(process.execPath, [script, '--help'], {+ cwd: directory,+ encoding: 'utf8',+ timeout: 10000,+ windowsHide: true,+ });+ expect(run.error).toBeUndefined();+ expect(run.status).toBe(0);+ expect(run.stdout).toContain('bin/kiln-setup-workspace.mjs');+ if (process.platform !== 'win32') {+ expect((await stat(script)).mode & 0o111).toBe(0o111);+ const direct = spawnSync(script, ['--help'], {+ cwd: directory,+ encoding: 'utf8',+ timeout: 10000,+ });+ expect(direct.error).toBeUndefined();+ expect(direct.status).toBe(0);+ expect(direct.stdout).toBe(run.stdout);+ await chmod(script, 0o644);+ await expect(packageLocalPlugin(directory, { check: true })).rejects.toThrow('executable');+ }+});+test('bundle retains an exact inventory and deterministic hashes', async () => {const first = await destination();const second = await destination();@@ -80,6 +139,10 @@ test('bundle retains an exact inventory and deterministic hashes', async () => {const receipt = await readJson(join(first, 'package-provenance.json'));expect(receipt.kind).toBe('kiln-local-plugin');expect(receipt.engineVersion).toBe((await readJson(resolve('package.json'))).version);+ expect(receipt.pluginVersion).toBe(+ (await readJson(resolve('plugins/kiln-engine.release.json'))).version,+ );+ expect(receipt.executables).toEqual(['bin/kiln-setup-workspace.mjs']);expect(Object.keys(receipt.files).length).toBe(result.files);for (const [file, digest] of Object.entries(receipt.files)) {expect(digest).toBe(@@ -87,9 +150,7 @@ test('bundle retains an exact inventory and deterministic hashes', async () => {.update(await readFile(join(first, file))).digest('hex')}`,);- expect(await readFile(join(first, file), 'utf8')).toBe(- await readFile(join(second, file), 'utf8'),- );+ expect(await readFile(join(first, file))).toEqual(await readFile(join(second, file)));}});diff --git a/scripts/setup-plugin-workspace.mjs b/scripts/setup-plugin-workspace.mjsindex e0c774ab..c8386a00 100644--- a/scripts/setup-plugin-workspace.mjs+++ b/scripts/setup-plugin-workspace.mjs@@ -323,7 +323,7 @@ if (const options = parseSetupArguments(process.argv.slice(2));if (options.help)console.log(- 'Usage: node scripts/setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node scripts/setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',+ 'Usage: node bin/kiln-setup-workspace.mjs <directory> [--harness claude|codex] [--skills compose,batch]\n node bin/kiln-setup-workspace.mjs <managed-workspace> --check|--upgrade|--repair\nOptions: --data-dir <persistent-directory>, --archive <qualification.tgz>, --npm-cli <npm-cli.js>',);else {const result = await setupPluginWorkspace(options);diff --git a/scripts/setup-plugin-workspace.test.mjs b/scripts/setup-plugin-workspace.test.mjsindex 7c353ebe..efef88f1 100644--- a/scripts/setup-plugin-workspace.test.mjs+++ b/scripts/setup-plugin-workspace.test.mjs@@ -216,7 +216,7 @@ test('CLI check returns failure for workspace drift without running an installatjoin(runtime, 'scripts/create-workspace.mjs'),'export async function createWorkspace() { return {status:"update-required"}; }',);- const script = join(f.options.pluginRoot, 'scripts/setup-workspace.mjs');+ const script = join(f.options.pluginRoot, 'bin/kiln-setup-workspace.mjs');await mkdir(dirname(script));await cp(new URL('./setup-plugin-workspace.mjs', import.meta.url), script);const result = spawnSync(diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 20ae75da..101cedbd 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -230,13 +230,14 @@ try {'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',);assert.equal(portablePlugin.name, 'kiln-engine');- assert.equal(portablePlugin.version, pkg.version);- assert.equal((await pluginJson('.claude-plugin/plugin.json')).version, pkg.version);+ assert.equal((await pluginJson('.claude-plugin/plugin.json')).version, portablePlugin.version);assert.deepEqual(await pluginJson('runtime.json'), { name: pkg.name, version: pkg.version });assert.deepEqual(await readdir(join(plugin, 'skills')), ['kiln-setup-workspace']);const pluginReceipt = await pluginJson('package-provenance.json');assert.equal(pluginReceipt.kind, 'kiln-local-plugin');assert.equal(pluginReceipt.engineVersion, pkg.version);+ // Published plugin 1.0.0 coupled these versions; newer plugin-only revisions do not.+ assert.equal(portablePlugin.version, pluginReceipt.pluginVersion ?? pkg.version);for (const [name, digest] of Object.entries(pluginReceipt.files))assert.equal(`sha256:${sha(await readFile(join(plugin, name)))}`,diff --git a/skills/kiln-setup-workspace/SKILL.md b/skills/kiln-setup-workspace/SKILL.mdindex 2f0aef1c..b1e637f9 100644--- a/skills/kiln-setup-workspace/SKILL.md+++ b/skills/kiln-setup-workspace/SKILL.md@@ -18,7 +18,7 @@ Do not author assets inside the engine checkout. The authoring skills assume a w## Create the workspace-When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `scripts/setup-workspace.mjs`. Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.+When this skill comes from the **Kiln Engine local plugin**, its plugin root contains `runtime.json` and `bin/kiln-setup-workspace.mjs` (plugin 1.0.0 used `scripts/setup-workspace.mjs`). Follow [plugin installation and upgrades](references/plugin-install.md) to install the pinned engine and configure a separate workspace. Do not run the checkout command below from a plugin cache. The plugin registers setup only; the workspace supplies its authoring skills and `kiln_workspace` server.Choose an absolute path to an empty directory outside the checkout.diff --git a/skills/kiln-setup-workspace/references/plugin-install.md b/skills/kiln-setup-workspace/references/plugin-install.mdindex 09df1184..c3f933f7 100644--- a/skills/kiln-setup-workspace/references/plugin-install.md+++ b/skills/kiln-setup-workspace/references/plugin-install.md@@ -4,19 +4,24 @@ The local `kiln-engine` plugin installs Kiln's exact pinned npm version and creaan asset workspace. It carries setup guidance and a small installer; the engine,source stores and authored assets live outside the plugin cache. It needs asupported Node.js installation with npm, network access for first installation,-and no separate model API key.+and no separate model API key. Use it in Claude Code or Codex; it requires a local+shell and persistent filesystem and is not a Claude chat or Cowork plugin.Resolve the plugin root from this installed skill's absolute path: it is twodirectories above `skills/kiln-setup-workspace`. Confirm `runtime.json` and-`scripts/setup-workspace.mjs` exist there. Do not assume plugin path variables are+`bin/kiln-setup-workspace.mjs` exist there. Do not assume plugin path variables areavailable in an ordinary shell, and do not substitute an engine checkout.+Plugin version 1.0.0 used `scripts/setup-workspace.mjs`; if using that older+installation, confirm and use that file instead. Plugin and engine versions are+independent. `runtime.json` always names the exact engine to install.+For a fresh workspace, use an absolute empty destination outside both the pluginand its runtime data directory. Select `claude` or `codex` from the current hostor the user's stated choice:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --harness codex+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --harness codex```The installer verifies the package name and exact version from `runtime.json`.@@ -43,8 +48,8 @@ For an existing managed workspace, stop its harness session and run the newplugin's helper with `--check`, then `--upgrade` when an update is intended:```sh-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --check-node "/absolute/plugin/scripts/setup-workspace.mjs" "/absolute/my-assets" --upgrade+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --check+node "/absolute/plugin/bin/kiln-setup-workspace.mjs" "/absolute/my-assets" --upgrade```Check is read-only and reports a missing pinned engine without installing it.