Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

fix: stop the CLI exiting 0 in silence, and create output directories (#67)

Matthew Kissingerb108a84ba251
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f77f9029..adc70806 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,23 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## `kiln` commands no longer exit 0 in silence under Bun — 2026-09-11
+
+- Under Bun, a CLI command could exit 0 having written nothing at all: no output,
+ no error, no rejection. `kiln save` did it reproducibly under load. The command
+ was not failing, it was still running -- Bun does not register the in-flight work
+ as an active resource, so the event loop went idle and the process exited before
+ `main()` settled. Every entry point was exposed, the generated workspace
+ `kiln.mjs` launcher included, because all of them await `main()` and then set
+ `process.exitCode`. `main` now holds the process open for its own duration.
+ Node was unaffected in practice, but the guard is runtime-agnostic.
+- Every CLI destination now creates the directories leading to it. `--out` and
+ `--views` failed with a bare `ENOENT` on a missing parent, and failed *after*
+ the build had run and printed a `programRef` -- a successful render followed by
+ an error naming a path but not the directory as the thing to fix. Covers
+ `render --out`, `render --views`, `generate`, `source <ref> --out` and
+ `export --out`.
+
## Usable from a bare clone by any harness; isolate honored on GPU — 2026-09-10
- A bare clone is now usable by claude, codex, opencode, hermes and agy. The root
diff --git a/dist/build.json b/dist/build.json
index 1bb63106..e7adc587 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"mcp": {
- "identity": "sha256:eb5d210afab12a40858499e43f506e45de70a30cbd3ad6359c2719f9984e9d96",
+ "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "01118f4cc332bae8b434ad341e5b779c269924c9915e4681b833159cfa757f2b",
+ "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -30,10 +30,10 @@
"bundleHash": "sha256:d3e0c45fdf10b553dbef69024deb044f9c08ba45b517aec784dc8c4a2f1c386b"
},
"cli": {
- "identity": "sha256:eb5d210afab12a40858499e43f506e45de70a30cbd3ad6359c2719f9984e9d96",
+ "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "01118f4cc332bae8b434ad341e5b779c269924c9915e4681b833159cfa757f2b",
+ "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -55,13 +55,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:c13978dd2923e85c847bb4cd904075a82affcfbb9669f5c61eeb22844677ae23"
+ "bundleHash": "sha256:2858b8cab4cce9fb30685743240b257dddd185daa0611bba07645ec153fb6e61"
},
"worker": {
- "identity": "sha256:eb5d210afab12a40858499e43f506e45de70a30cbd3ad6359c2719f9984e9d96",
+ "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "01118f4cc332bae8b434ad341e5b779c269924c9915e4681b833159cfa757f2b",
+ "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -86,10 +86,10 @@
"bundleHash": "sha256:bb463f3b33b7474ed8f2c0626fa4bde8c64101182b11aac042491f7077e6cbdd"
},
"agent-run": {
- "identity": "sha256:eb5d210afab12a40858499e43f506e45de70a30cbd3ad6359c2719f9984e9d96",
+ "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "01118f4cc332bae8b434ad341e5b779c269924c9915e4681b833159cfa757f2b",
+ "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
@@ -114,10 +114,10 @@
"bundleHash": "sha256:2fcd14c02e8a8b168396623ca851f206529b2e5559eb87162ed4de3c699d73ee"
},
"agent-providers": {
- "identity": "sha256:eb5d210afab12a40858499e43f506e45de70a30cbd3ad6359c2719f9984e9d96",
+ "identity": "sha256:45ff66bf867485e6947f30d223952116c72f65b6aea46284ce91b108c4b7b95d",
"engineVersion": "0.6.0",
"toolchain": "[email protected]",
- "sourceHash": "01118f4cc332bae8b434ad341e5b779c269924c9915e4681b833159cfa757f2b",
+ "sourceHash": "bd990580f49abed4fe90d0dc8fa753d08970d18d5c1ddb1380eea928cb106e01",
"dependencyHash": "50096a04c37058e201c3d5234a0babeae5531f941f07f5dbf11ee733f04ce2e8",
"dependencies": {
"@gltf-transform/core": "^4.4.1",
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 80afd3aa..d717ba09 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -17,6 +17,15 @@ var __export = (target, all) => {
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
+// src/cli-output.ts
+import { mkdir } from "node:fs/promises";
+import { dirname } from "node:path";
+async function prepareDestination(path) {
+ await mkdir(dirname(path), { recursive: true });
+ return path;
+}
+var init_cli_output = () => {};
+
// src/evaluator/authoring-diagnostic.ts
function authoringDiagnosticAdvice(diagnostic) {
if (diagnostic === "UNBOUND_VARIABLE")
@@ -26681,7 +26690,7 @@ var init_program_store = __esm(() => {
});
// src/program-store-node.ts
-import { link, lstat, mkdir, readFile as readFile2, readdir, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
+import { link, lstat, mkdir as mkdir2, readFile as readFile2, readdir, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { join as join3, resolve } from "node:path";
@@ -26755,7 +26764,7 @@ class FileProgramStore {
if (ref.startsWith("p_"))
return ref;
const directory = join3(this.directory, "refs");
- await mkdir(directory, { recursive: true });
+ await mkdir2(directory, { recursive: true });
for (const handle of shortProgramRefCandidates(ref)) {
const owner = await this.readHandle(handle);
if (owner === ref)
@@ -26782,7 +26791,7 @@ class FileProgramStore {
}
async put(code) {
const ref = await programReference(code);
- await mkdir(this.directory, { recursive: true });
+ await mkdir2(this.directory, { recursive: true });
const target = join3(this.directory, `${ref.slice(7)}.js`);
const temporary = join3(this.directory, `.write-${randomUUID()}`);
await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });
@@ -26974,7 +26983,7 @@ var init_build_cache = __esm(() => {
// src/build-cache-node.ts
import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";
import {
- mkdir as mkdir2,
+ mkdir as mkdir3,
readFile as readFile3,
readdir as readdir2,
rename,
@@ -27024,7 +27033,7 @@ class FileBuildCache {
const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest2(payload) });
if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))
return;
- await mkdir2(this.directory, { recursive: true });
+ await mkdir3(this.directory, { recursive: true });
const temporary = join4(this.directory, `.write-${randomUUID2()}`);
await writeFile3(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });
try {
@@ -27066,7 +27075,7 @@ var init_build_cache_node = __esm(() => {
import { createHash as createHash9 } from "node:crypto";
import { readFile as readFile4, readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
import { createRequire as createRequire2 } from "node:module";
-import { dirname, join as join5, relative } from "node:path";
+import { dirname as dirname2, join as join5, relative } from "node:path";
async function installedRuntimeIdentity(root, limits = {}) {
let bytes = 0;
let files = 0;
@@ -27126,13 +27135,13 @@ async function installedRuntimeIdentity(root, limits = {}) {
throw new Error(`Cannot resolve installed dependency ${name}.`);
}
}
- let directory = dirname(found);
+ let directory = dirname2(found);
for (;; ) {
try {
if ((await manifest(directory)).name === name)
return await realpath(directory);
} catch {}
- const next = dirname(directory);
+ const next = dirname2(directory);
if (next === directory)
throw new Error(`Cannot identify installed dependency ${name}.`);
directory = next;
@@ -27211,7 +27220,7 @@ var digest3 = (bytes) => createHash9("sha256").update(bytes).digest("hex"), comp
var init_runtime_identity = () => {};
// src/local-runtime.ts
-import { dirname as dirname2, join as join6, resolve as resolve3 } from "node:path";
+import { dirname as dirname3, join as join6, resolve as resolve3 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
function integer2(env, name, fallback, min, max) {
const value = env[name] === undefined ? fallback : Number(env[name]);
@@ -27333,7 +27342,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
}
const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;
const store = context.programStore;
- const directory = resolve3(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname2(store.directory) : ".kiln", "cache", "builds"));
+ const directory = resolve3(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname3(store.directory) : ".kiln", "cache", "builds"));
context.buildCache = new FileBuildCache(directory, cacheBytes);
context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({
execution: context.localExecution,
@@ -29953,8 +29962,8 @@ __export(exports_assets_node, {
});
import { createHash as createHash11, randomUUID as randomUUID3 } from "node:crypto";
import { readFileSync as readFileSync2 } from "node:fs";
-import { lstat as lstat2, mkdir as mkdir3, readFile as readFile6, readdir as readdir4, realpath as realpath2, rename as rename2, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
-import { dirname as dirname3, join as join7, relative as relative2, resolve as resolve4, sep } from "node:path";
+import { lstat as lstat2, mkdir as mkdir4, readFile as readFile6, readdir as readdir4, realpath as realpath2, rename as rename2, rm as rm2, writeFile as writeFile4 } from "node:fs/promises";
+import { dirname as dirname4, join as join7, relative as relative2, resolve as resolve4, sep } from "node:path";
async function verifyAssetRecord(record5) {
for (const [name, info] of Object.entries(record5.manifest.files)) {
const bytes = record5.files[name];
@@ -29982,7 +29991,7 @@ class FileAssetLibrary {
}
async path(collection, ...parts) {
const root = this.directory(collection);
- await mkdir3(root, { recursive: true });
+ await mkdir4(root, { recursive: true });
const canonical3 = await realpath2(root);
let path = root;
for (const part of parts) {
@@ -30092,10 +30101,10 @@ class FileAssetLibrary {
for (const record5 of records) {
const { manifest, files } = record5;
const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);
- const parent = dirname3(dest);
- await mkdir3(parent, { recursive: true });
+ const parent = dirname4(dest);
+ await mkdir4(parent, { recursive: true });
const stage = join7(parent, `.write-${randomUUID3()}`);
- await mkdir3(stage);
+ await mkdir4(stage);
try {
for (const [name, bytes] of Object.entries(files))
await writeFile4(join7(stage, name), bytes, { flag: "wx" });
@@ -30120,7 +30129,7 @@ class FileAssetLibrary {
}
}
function collectionConfigPath(env = process.env) {
- const workspace = env.KILN_PROGRAM_STORE ? dirname3(dirname3(resolve4(env.KILN_PROGRAM_STORE))) : process.cwd();
+ const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve4(env.KILN_PROGRAM_STORE))) : process.cwd();
return join7(workspace, ".kiln", "collections.json");
}
function localAssetLibrary(env = process.env) {
@@ -30140,7 +30149,7 @@ function localAssetLibrary(env = process.env) {
if (error.code !== "ENOENT")
throw error;
}
- const workspace = dirname3(dirname3(config));
+ const workspace = dirname4(dirname4(config));
return new FileAssetLibrary({ project: join7(workspace, "assets", "kiln") });
}
var digest4 = (bytes) => `sha256:${createHash11("sha256").update(bytes).digest("hex")}`;
@@ -30151,10 +30160,10 @@ var init_assets_node = __esm(() => {
// src/asset-viewer.ts
import { createServer } from "node:http";
import { readFile as readFile7 } from "node:fs/promises";
-import { dirname as dirname4, join as join8 } from "node:path";
+import { dirname as dirname5, join as join8 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
async function startAssetViewer(library, options = {}) {
- const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join8(dirname4(fileURLToPath4(import.meta.url)), "..", "dist", "viewer") : join8(dirname4(fileURLToPath4(import.meta.url)), "viewer"));
+ const staticDirectory = options.staticDirectory ?? (import.meta.url.endsWith(".ts") ? join8(dirname5(fileURLToPath4(import.meta.url)), "..", "dist", "viewer") : join8(dirname5(fileURLToPath4(import.meta.url)), "viewer"));
const server = createServer(async (req, res) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "no-referrer");
@@ -30247,8 +30256,8 @@ __export(exports_asset_cli, {
assetMain: () => assetMain,
ASSET_USAGE: () => ASSET_USAGE
});
-import { readFile as readFile8, writeFile as writeFile5, stat as stat4, mkdir as mkdir4, rename as rename3 } from "node:fs/promises";
-import { basename, resolve as resolve5, dirname as dirname5 } from "node:path";
+import { readFile as readFile8, writeFile as writeFile5, stat as stat4, mkdir as mkdir5, rename as rename3 } from "node:fs/promises";
+import { basename, resolve as resolve5, dirname as dirname6 } from "node:path";
import { randomUUID as randomUUID4 } from "node:crypto";
async function assetMain(argv) {
const command = argv[0];
@@ -30310,7 +30319,7 @@ async function assetMain(argv) {
throw new Error("Collection name already points to another directory");
roots[name] = resolve5(directory);
const path = collectionConfigPath();
- await mkdir4(dirname5(path), { recursive: true });
+ await mkdir5(dirname6(path), { recursive: true });
const temporary = `${path}.${randomUUID4()}.tmp`;
await writeFile5(temporary, JSON.stringify(roots, null, 2), { flag: "wx" });
await rename3(temporary, path);
@@ -30366,7 +30375,7 @@ async function assetMain(argv) {
const bytes = format === "bundle" ? encodeAssetBundle([record5]) : record5.files[format === "glb" ? "asset.glb" : "source.kiln.js"];
if (!bytes)
throw new Error("Source unavailable");
- await writeFile5(resolve5(flags.out), bytes, { flag: "wx" });
+ await writeFile5(await prepareDestination(resolve5(flags.out)), bytes, { flag: "wx" });
console.log(`Saved ${resolve5(flags.out)}`);
}
} else if (command === "import") {
@@ -30418,12 +30427,14 @@ var init_asset_cli = __esm(() => {
init_program_store_node();
init_program_store();
init_registry2();
+ init_cli_output();
init_local_runtime();
init_cli_render_mode();
init_asset_viewer();
});
// src/cli.ts
+init_cli_output();
init_local_runtime();
init_registry2();
init_cli_render_mode();
@@ -30569,7 +30580,7 @@ async function emit(code, args, context) {
console.log(` build ${result.buildCache.hit ? "reused" : "created"} ${result.buildCache.key}`);
const out = args.out ?? (args.views ? undefined : "out.glb");
if (out) {
- await writeFile6(resolvePath(out), result.glb);
+ await writeFile6(await prepareDestination(resolvePath(out)), result.glb);
console.log(` ${out} ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
} else {
console.log(` ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
@@ -30601,7 +30612,7 @@ async function emit(code, args, context) {
const media = def.media?.(output);
if (!media)
throw new Error("kiln_render returned no image");
- await writeFile6(resolvePath(args.views), media.png);
+ await writeFile6(await prepareDestination(resolvePath(args.views)), media.png);
console.log(` ${args.views} (${describeDrawnBy(output, context)})`);
}
}
@@ -30661,7 +30672,7 @@ async function cmdGenerate(args) {
const outPath = args.out ?? "out.glb";
await emit(run2.code, { ...args, out: outPath }, context);
const source = outPath.replace(/\.glb$/i, ".kiln.js");
- await writeFile6(resolvePath(source), run2.code, "utf8");
+ await writeFile6(await prepareDestination(resolvePath(source)), run2.code, "utf8");
console.log(` ${source} (the program — edit and re-render it)`);
return 0;
}
@@ -30673,7 +30684,10 @@ async function cmdSource(args) {
if (input.startsWith("sha256:") || programRefPattern.test(input)) {
const code = await store.get(input);
if (args.out) {
- await writeFile6(resolvePath(args.out), code, { encoding: "utf8", flag: "wx" });
+ await writeFile6(await prepareDestination(resolvePath(args.out)), code, {
+ encoding: "utf8",
+ flag: "wx"
+ });
console.log(`Saved ${input} to ${args.out}`);
} else
process.stdout.write(code);
@@ -30684,7 +30698,20 @@ async function cmdSource(args) {
}
return 0;
}
-async function main(argv) {
+async function withProcessAlive(run2) {
+ const held = setInterval(() => {
+ return;
+ }, 1 << 30);
+ try {
+ return await run2();
+ } finally {
+ clearInterval(held);
+ }
+}
+function main(argv) {
+ return withProcessAlive(() => runMain(argv));
+}
+async function runMain(argv) {
if (["save", "collections", "assets", "asset", "export", "import", "view"].includes(argv[0] ?? "")) {
try {
return await (await Promise.resolve().then(() => (init_asset_cli(), exports_asset_cli))).assetMain(argv);
@@ -30747,6 +30774,7 @@ if (isDirectCliEntry()) {
});
}
export {
+ withProcessAlive,
parseArgs,
main
};
diff --git a/docs/plans/repo-size-and-r2-migration-2026-09-10.md b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
index 54abb36f..4229e234 100644
--- a/docs/plans/repo-size-and-r2-migration-2026-09-10.md
+++ b/docs/plans/repo-size-and-r2-migration-2026-09-10.md
@@ -1018,12 +1018,43 @@ End users are not affected: every shipped launcher and manifest invokes `node`
plugin manifests use bare `node`. Contributors are, because `AGENTS.md`
documents Bun as the toolchain.
+### Root cause, found 2026-09-11
+
+Neither suspect in 8.1 was right. The `save` path does not exit early and does not
+fail: it never finishes. Under contention the command is still running when Bun's
+event loop goes idle, `beforeExit` fires, and the process exits 0 having written
+nothing. A preload that traced `process.exitCode` inside the child settled it --
+every failing run reached `exit` with `exitCode` still `undefined`, so the `.then`
+on `main()` had never run, while the one passing run in the same batch showed
+`exitCode=0`. Adding a single `setInterval` in a preload, changing nothing else,
+turned 8 silent failures into 8 full 2,062-byte successes that simply took longer.
+
+What Bun is failing to count is still open. `process.getActiveResourcesInfo()`
+returns `[]` throughout, but that says nothing either way -- Bun implements it as a
+stub that always returns `[]` (oven-sh/bun#24538), so it is not evidence. `sharp`
+was the obvious suspect, being the one native dependency on this path, and it is
+innocent: a pending `sharp` operation holds Bun open exactly as it holds Node
+open, checked directly. Identifying the primitive is worth a bounded look, because
+it would say whether other hosts are exposed; it does not gate the fix, which is
+correct whatever the primitive turns out to be.
+
+So this is not a `save` bug, an evaluator bug, or a flush race. It is the CLI
+entry contract. Every entry -- `isDirectCliEntry`, the generated workspace
+`kiln.mjs` launcher, `assetMain` through `main` -- awaits `main()` and then sets
+`process.exitCode`, which assumes the runtime keeps the process alive while that
+promise is pending. Node does in practice; Bun does not. The fix wraps `main`
+itself in `withProcessAlive`, a ref'd far-future timer cleared in a `finally`, so
+it costs no wakeups and covers every call site rather than one. Measured on the
+same 8-way concurrent repro that produced 7-of-8 silent failures before: 8 of 8
+full output after. The load-sensitive `src/asset-cli.test.ts` went from 3 failures
+in 6 concurrent runs to 6 of 6 passing.
+
| ID | Task | State |
| --- | --- | --- |
-| 8.1 | Find where the `save` path exits early under Bun without a diagnostic. The store write succeeds, so the divergence is after program import; suspect the in-process evaluator or an output flush racing process exit | Pending |
-| 8.2 | Decide whether the CLI should refuse to exit 0 having produced no output at all, independent of the Bun cause. A silent success is the part that made this look like flakiness for so long | Pending |
-| 8.3 | Point `src/asset-cli.test.ts` at an interpreter that reflects how the CLI actually ships, or assert non-empty stdout before parsing so the failure names the real cause | Pending |
-| 8.4 | Re-check the other two intermittent tests against this finding; a shared `spawnSync` under Bun may explain more than one of them | Pending |
+| 8.1 | Find where the `save` path exits early under Bun without a diagnostic | Done -- it does not exit early; `main()` never settles and Bun exits the idle loop at 0. Fixed by `withProcessAlive` in `src/cli.ts` |
+| 8.2 | Decide whether the CLI should refuse to exit 0 having produced no output at all, independent of the Bun cause | DECIDED: no. The silent-success shape is now structurally unreachable from this cause, and a blanket "no stdout means nonzero" rule would be a guess layered over a fixed defect -- it would have to assume every command is obliged to print, which is a contract the CLI has never stated. The guard belongs in the test that reads the output, not in the command that produces it. Closed |
+| 8.3 | Point `src/asset-cli.test.ts` at an interpreter that reflects how the CLI actually ships, or assert non-empty stdout before parsing so the failure names the real cause | Done -- asserts non-empty stdout before `JSON.parse`. Left on Bun deliberately: Bun is the documented toolchain, so the test should keep exercising the runtime that exposed this |
+| 8.4 | Re-check the other two intermittent tests against this finding | Done, and the hypothesis does not hold. `shipping proxy forwards actual PNGs ...` in `scripts/evaluation/observe-shipping.test.mjs` passed 8 of 8 under the same concurrency that reproduced the `save` failure on demand, and its entry is event-driven with a live child-process handle rather than an awaited `main()`, so it cannot reach this state. That test's intermittency is still unexplained; it is not this defect |
## Phase 9 -- Review surfaces that misreport a correct asset
@@ -1056,6 +1087,6 @@ independently verified; 9.2 is the one that looks like the same bug class as 9.1
| 9.3 | `viewFidelity.exactArtifact` reported `false` on every render, including ones where the run independently hashed `inputGlbSha256` equal to both the exported GLB and the saved `asset.glb`. Either the flag means something narrower than its name, or it is wrong. Pending; whichever it is, a model cannot use a fidelity flag whose false value carries no meaning |
| 9.4 | `kiln_screenshot_animation` requires a `clip` name and `frameTimes` normalized to 0..1, and neither is stated in the author skill or the camera recipes. The run guessed the clip name from its own `createClip` call and hit a validation error on seconds-valued frame times. Pending; a documentation gap, not a defect |
| 9.5 | `arrayRadial` count semantics are not inferable from the signature plus the example: whether the source mesh survives as the copy at index 0 had to be deduced from a mesh count. Pending; documentation |
-| 9.6 | CLI `--out` does not create parent directories, failing with a bare `ENOENT` *after* the build succeeded and printed a `programRef`. Invisible from the README, whose example writes into the cwd. Pending; decide between `mkdir -p` and an error that names the directory |
+| 9.6 | CLI `--out` does not create parent directories, failing with a bare `ENOENT` *after* the build succeeded and printed a `programRef`. Invisible from the README, whose example writes into the cwd | Done 2026-09-11 -- `prepareDestination` in `src/cli-output.ts`, applied at every CLI destination: `render --out`, `render --views`, `generate`, `source <ref> --out` and `export --out`. Guarded by `src/__tests__/cli-out-directories.test.ts` |
| 9.7 | The MCP server resolves the render service once before its first connection, so a service started afterwards is invisible until the session restarts, while the CLI picks it up on the next call. Re-probe lazily when a render needs PBR and no port is attached, with a short negative cache -- the probe's `absent` path is a refused localhost connection. Pending; collapses the guidance to "start it whenever" and deletes the restart caveat from the workspace guide and the setup skill. Not folded into the Phase 7 documentation commit because `captureViewsViaPort` owns the deadline and degrade policy and the change deserves its own TDD |
| 9.8 | Narrow the generated per-harness configuration to suppress user-level skills and MCP servers where each harness supports it. The blind run inherited roughly twenty unrelated skills and four unrelated servers. This is the only option that reduces inherited context rather than reporting it, and it needs vendor documentation per harness first: configuration that validates and silently does nothing is the `${PLUGIN_ROOT}` failure class. Pending |
diff --git a/src/__tests__/cli-entry.test.ts b/src/__tests__/cli-entry.test.ts
index 2e5b9cda..7c0d0483 100644
--- a/src/__tests__/cli-entry.test.ts
+++ b/src/__tests__/cli-entry.test.ts
@@ -54,3 +54,46 @@ it('executes a Node CLI symlink once and stays inert when imported', async () =>
await rm(directory, { recursive: true, force: true });
}
}, 20000);
+
+it('holds the process open until a command settles, instead of exiting 0 in silence', async () => {
+ // A CLI entry that awaits `main()` and then sets `process.exitCode` assumes the
+ // runtime keeps the process alive while that promise is pending. It does not.
+ // When the in-flight work is not registered as an active resource the loop goes
+ // idle, `beforeExit` fires, and the process exits 0 having written nothing --
+ // the exact shape of the `kiln save` failure that read as a flaky test. Drive
+ // the boundary with a promise that never settles and owns no handle: unheld,
+ // that process exits immediately; held, it cannot.
+ const base = resolve(import.meta.dir, '../../tmp');
+ await mkdir(base, { recursive: true });
+ const directory = await mkdtemp(join(base, 'cli-alive-'));
+ try {
+ // Import the module under test by URL so the child runs the shipped entry.
+ const cli = pathToFileURL(resolve(import.meta.dir, '../cli.ts')).href;
+ const script = join(directory, 'held.mjs');
+ await writeFile(
+ script,
+ `const { withProcessAlive } = await import(${JSON.stringify(cli)});\n` +
+ `process.on('exit', () => process.stdout.write('EXITED'));\n` +
+ `await withProcessAlive(() => new Promise(() => {}));\n`,
+ );
+ const child = Bun.spawn([process.execPath, script], { stdout: 'pipe', stderr: 'pipe' });
+ const exited = await Promise.race([
+ child.exited.then(() => 'exited' as const),
+ new Promise<'alive'>((done) => setTimeout(() => done('alive'), 1500)),
+ ]);
+ child.kill();
+ expect(exited).toBe('alive');
+
+ const settles = join(directory, 'settles.mjs');
+ await writeFile(
+ settles,
+ `const { withProcessAlive } = await import(${JSON.stringify(cli)});\n` +
+ `process.stdout.write(await withProcessAlive(async () => 'DONE'));\n`,
+ );
+ const clean = Bun.spawnSync([process.execPath, settles], { stdout: 'pipe', stderr: 'pipe' });
+ expect(clean.exitCode).toBe(0);
+ expect(clean.stdout.toString()).toBe('DONE');
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}, 20000);
diff --git a/src/__tests__/cli-out-directories.test.ts b/src/__tests__/cli-out-directories.test.ts
new file mode 100644
index 00000000..66036e66
--- /dev/null
+++ b/src/__tests__/cli-out-directories.test.ts
@@ -0,0 +1,59 @@
+import { expect, it } from 'bun:test';
+import { mkdtemp, mkdir, rm, stat } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+
+/**
+ * Every CLI path that takes a destination must create the directories leading to
+ * it. Failing on a missing parent is expensive out of proportion to the mistake:
+ * the build has already run and already printed a `programRef`, so the operator
+ * sees a successful render followed by a bare ENOENT and no artifact, with
+ * nothing naming the parent directory as the thing to fix. The README's example
+ * writes into the working directory, which is why this never showed up there.
+ */
+it('creates the directories leading to every CLI destination', async () => {
+ const base = resolve(import.meta.dir, '../../tmp');
+ await mkdir(base, { recursive: true });
+ const directory = await mkdtemp(join(base, 'cli-out-dirs-'));
+ const cli = resolve(import.meta.dir, '../cli.ts');
+ const example = resolve(import.meta.dir, '../../examples/crate.kiln.js');
+ const run = (args: string[]) =>
+ Bun.spawnSync([process.execPath, cli, ...args], {
+ cwd: directory,
+ env: {
+ ...process.env,
+ KILN_RENDER: 'cpu',
+ KILN_EVALUATOR_MODE: 'in-process',
+ KILN_PROGRAM_STORE: join(directory, '.kiln', 'programs'),
+ KILN_COLLECTIONS: JSON.stringify({ project: join(directory, 'collection') }),
+ },
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ const wrote = async (path: string) => (await stat(path)).size > 0;
+ try {
+ const glb = join(directory, 'render', 'deep', 'crate.glb');
+ const views = join(directory, 'views', 'deep', 'sheet.png');
+ const rendered = run(['render', example, '--out', glb, '--views', views]);
+ expect(rendered.stderr.toString()).toBe('');
+ expect(rendered.exitCode).toBe(0);
+ expect(await wrote(glb)).toBe(true);
+ expect(await wrote(views)).toBe(true);
+
+ const retained = run(['source', example]);
+ expect(retained.exitCode).toBe(0);
+ const programRef = retained.stdout.toString().trim();
+ expect(programRef).toMatch(/^p_/);
+ const copy = join(directory, 'source', 'deep', 'crate.kiln.js');
+ expect(run(['source', programRef, '--out', copy]).exitCode).toBe(0);
+ expect(await wrote(copy)).toBe(true);
+
+ const saved = run(['save', programRef, '--name', 'Crate', '--render', 'cpu']);
+ expect(saved.exitCode).toBe(0);
+ const asset = JSON.parse(saved.stdout.toString()).asset;
+ const bundle = join(directory, 'export', 'deep', 'crate.zip');
+ expect(run(['export', asset.assetId, asset.revisionId, '--out', bundle]).exitCode).toBe(0);
+ expect(await wrote(bundle)).toBe(true);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+}, 60000);
diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.ts
index 8229f6fb..ea181e40 100644
--- a/src/asset-cli.test.ts
+++ b/src/asset-cli.test.ts
@@ -31,6 +31,11 @@ test('CLI saves, exports, imports, and restores a revision across independent st
'cpu',
]);
expect(saved.status).toBe(0);
+ // Name the failure. A `save` that exits 0 with empty stdout is the silent
+ // early-exit this suite mistook for flakiness for weeks; assert the output
+ // exists before parsing, so a regression reports the command rather than a
+ // JSON syntax error several frames away from the cause.
+ expect(saved.stdout.length).toBeGreaterThan(0);
const asset = JSON.parse(saved.stdout).asset;
const file = join(root, 'crate.zip');
expect(run('first', ['export', asset.assetId, asset.revisionId, '--out', file]).status).toBe(0);
diff --git a/src/asset-cli.ts b/src/asset-cli.ts
index 21623752..c5a1bb17 100644
--- a/src/asset-cli.ts
+++ b/src/asset-cli.ts
@@ -6,6 +6,7 @@ import { ASSET_LIMIT, assetIdSchema, decodeAssetBundle, encodeAssetBundle } from
import { localProgramStore } from './program-store-node';
import { programRefPattern, retainProgram } from './program-store';
import { createKilnProgramToolRegistry } from './tools/registry';
+import { prepareDestination } from './cli-output';
import { createPackagedLocalToolContext } from './local-runtime';
import { buildRenderPort, resolveRenderMode } from './cli-render-mode';
import { startAssetViewer } from './asset-viewer';
@@ -156,7 +157,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {
? encodeAssetBundle([record])
: record.files[format === 'glb' ? 'asset.glb' : 'source.kiln.js'];
if (!bytes) throw new Error('Source unavailable');
- await writeFile(resolve(flags.out), bytes, { flag: 'wx' });
+ await writeFile(await prepareDestination(resolve(flags.out)), bytes, { flag: 'wx' });
console.log(`Saved ${resolve(flags.out)}`);
}
} else if (command === 'import') {
diff --git a/src/cli-output.ts b/src/cli-output.ts
new file mode 100644
index 00000000..f859ab09
--- /dev/null
+++ b/src/cli-output.ts
@@ -0,0 +1,18 @@
+import { mkdir } from 'node:fs/promises';
+import { dirname } from 'node:path';
+
+/**
+ * Prepare the directories leading to a CLI destination.
+ *
+ * A destination the operator named is a statement of intent, not an assertion
+ * that the path already exists. Refusing a missing parent is expensive out of
+ * proportion to the mistake: by the time the CLI writes, the build has run and a
+ * `programRef` is already on stdout, so the operator sees a successful render
+ * followed by a bare ENOENT, with nothing in the message naming the parent
+ * directory as the thing to fix. `recursive` also makes this a no-op for the
+ * common case where the directory is already there.
+ */
+export async function prepareDestination(path: string): Promise<string> {
+ await mkdir(dirname(path), { recursive: true });
+ return path;
+}
diff --git a/src/cli.ts b/src/cli.ts
index ab108183..d65b6b23 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -8,6 +8,7 @@ import { open, readFile, writeFile } from 'node:fs/promises';
import { realpathSync } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
+import { prepareDestination } from './cli-output';
import { createPackagedLocalToolContext } from './local-runtime';
import { createKilnProgramToolRegistry, type KilnToolContext } from './tools/registry';
import { fileURLToPath } from 'node:url';
@@ -174,7 +175,7 @@ async function emit(code: string, args: Args, context: KilnToolContext): Promise
// `--views sheet.png` alone should not litter the working directory.
const out = args.out ?? (args.views ? undefined : 'out.glb');
if (out) {
- await writeFile(resolvePath(out), result.glb);
+ await writeFile(await prepareDestination(resolvePath(out)), result.glb);
console.log(` ${out} ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
} else {
console.log(` ${result.tris} tris ${(result.glb.length / 1024).toFixed(1)} KB`);
@@ -208,7 +209,7 @@ async function emit(code: string, args: Args, context: KilnToolContext): Promise
}
const media = def.media?.(output);
if (!media) throw new Error('kiln_render returned no image');
- await writeFile(resolvePath(args.views), media.png);
+ await writeFile(await prepareDestination(resolvePath(args.views)), media.png);
// Report what actually drew the pixels, not what was configured. The engine
// routes to the port only when the scene needs PBR shading, so a GPU that was
// available and correctly skipped must not be reported as if it had drawn.
@@ -294,7 +295,7 @@ async function cmdGenerate(args: Args): Promise<number> {
await emit(run.code, { ...args, out: outPath }, context);
const source = outPath.replace(/\.glb$/i, '.kiln.js');
- await writeFile(resolvePath(source), run.code, 'utf8');
+ await writeFile(await prepareDestination(resolvePath(source)), run.code, 'utf8');
console.log(` ${source} (the program — edit and re-render it)`);
return 0;
}
@@ -307,7 +308,10 @@ async function cmdSource(args: Args): Promise<number> {
if (input.startsWith('sha256:') || programRefPattern.test(input)) {
const code = await store.get(input);
if (args.out) {
- await writeFile(resolvePath(args.out), code, { encoding: 'utf8', flag: 'wx' });
+ await writeFile(await prepareDestination(resolvePath(args.out)), code, {
+ encoding: 'utf8',
+ flag: 'wx',
+ });
console.log(`Saved ${input} to ${args.out}`);
} else process.stdout.write(code);
} else {
@@ -318,7 +322,33 @@ async function cmdSource(args: Args): Promise<number> {
return 0;
}
-export async function main(argv: readonly string[]): Promise<number> {
+/**
+ * Hold the process open until `run()` settles.
+ *
+ * Every CLI entry awaits `main()` and then sets `process.exitCode`, which assumes
+ * the runtime keeps the process alive while that promise is pending. It does not.
+ * The loop can go idle while the command is still running: `beforeExit` fires and
+ * the process exits 0 having written nothing. Bun reaches that state under load --
+ * concurrent `kiln save` runs exit 0 with empty stdout, no stderr and no
+ * rejection, which is why it read as a flaky test rather than a broken command. A
+ * ref'd timer far in the future costs no wakeups and closes the hole for every
+ * runtime and every entry, the generated workspace launcher included, because it
+ * wraps `main` itself rather than one call site.
+ */
+export async function withProcessAlive<T>(run: () => Promise<T>): Promise<T> {
+ const held = setInterval(() => undefined, 1 << 30);
+ try {
+ return await run();
+ } finally {
+ clearInterval(held);
+ }
+}
+
+export function main(argv: readonly string[]): Promise<number> {
+ return withProcessAlive(() => runMain(argv));
+}
+
+async function runMain(argv: readonly string[]): Promise<number> {
if (
['save', 'collections', 'assets', 'asset', 'export', 'import', 'view'].includes(argv[0] ?? '')
) {