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(site): store Holodeck downloads at content-addressed keys (#267) (#268)

Matthew Kissingerfc52fc0d2217
diff --git a/packs/holodeck/README.md b/packs/holodeck/README.md
index 61dba7d2..47fd2a9c 100644
--- a/packs/holodeck/README.md
+++ b/packs/holodeck/README.md
@@ -63,8 +63,18 @@ node scripts/stage-holodeck.mjs --upload-list --mirror .localdata/holodeck-deliv
A store is a workspace's `assets/kiln` directory. `KILN_PACKAGE_DIR` is an installed
`@instruktlabs/kiln` package; its runtime export profile writes the runtime GLBs and metadata,
-and staging verifies they keep the canonical binary. Staging writes are immutable: changed
-bytes need a new release ID in `holodeck-spec.mjs`. Nothing here uploads anything.
+and staging verifies they keep the canonical binary. Nothing here uploads anything.
+
+Downloads are stored once, at content-addressed keys: `packs/holodeck/objects/<sha256>/<file>`,
+where the folder is the file's SHA-256 and the file keeps its readable name, such as
+`cove-hearth.glb` or `holodeck-cove-runtime.zip`. A release reuses the key of every file whose
+bytes it keeps: an asset whose revision is unchanged, and a pack whose members and README are
+unchanged. Pack READMEs name neither the release nor the exporter version; they give
+`HOLODECK_IMPORT_KILN` from `holodeck-spec.mjs` as the oldest Kiln that imports the bundles.
+Keys are immutable, so different bytes at an existing key are refused.
+
+`published.json` records every object the asset host has served back. The upload list leaves
+those out and names only new objects; one recorded with different bytes is refused.
### Add a new committed example
@@ -101,12 +111,18 @@ revision approval records, and record any new asset review separately and honest
## Publish
-After release approval, upload the listed objects to the asset host, then build and deploy
-the site as described in [site/DEPLOYMENT.md](../../site/DEPLOYMENT.md):
+After release approval, upload the listed objects to the asset host, record what it served
+back, then build and deploy the site as described in [site/DEPLOYMENT.md](../../site/DEPLOYMENT.md):
```sh
node scripts/publish-assets.mjs .localdata/holodeck-delivery .localdata/holodeck-delivery/holodeck-upload-list.json
node scripts/publish-assets.mjs .localdata/holodeck-delivery .localdata/holodeck-delivery/holodeck-upload-list.json --upload --oauth
```
-The first command verifies the list offline; the second uploads and reads back every object.
+```sh
+node scripts/stage-holodeck.mjs --record-published .localdata/holodeck-delivery/holodeck-upload-list.json.published.json
+```
+
+The first command verifies the list offline; the second uploads and reads back every object;
+the third adds the objects read back to `published.json`. Commit `published.json` with the
+release's site data.
diff --git a/site/scripts/holodeck-spec.mjs b/site/scripts/holodeck-spec.mjs
index 90fa1a3d..1d748e31 100644
--- a/site/scripts/holodeck-spec.mjs
+++ b/site/scripts/holodeck-spec.mjs
@@ -6,6 +6,11 @@
export const HOLODECK_ID = 'holodeck';
export const HOLODECK_RELEASE = 'holodeck-20261024-01';
+/**
+ * The oldest Kiln that imports the packs' revision bundles, named in each pack README. Raise it only when the bundle
+ * format needs a newer Kiln: a value that followed every Kiln release would change every pack ZIP and its key.
+ */
+export const HOLODECK_IMPORT_KILN = '1.4.0';
export const HOLODECK_PACKS = [
{
diff --git a/site/scripts/holodeck.test.ts b/site/scripts/holodeck.test.ts
index 42d62f1f..fb0639ee 100644
--- a/site/scripts/holodeck.test.ts
+++ b/site/scripts/holodeck.test.ts
@@ -12,7 +12,7 @@ import { HOLODECK_SITE } from '../src/lib/config';
import { buildGallery } from '../src/lib/gallery';
import { holodeckScenes, holodeckWorldUrl } from '../src/lib/holodeck';
import { HOLODECK_APPROVAL, HOLODECK_ASSETS, HOLODECK_PACKS, holodeckApproved, holodeckSlug } from './holodeck-spec.mjs';
-import { holodeckPrefix } from './stage-holodeck.mjs';
+import { HOLODECK_OBJECTS } from './stage-holodeck.mjs';
import { ASSET_BASE } from './mirror-core.mjs';
import { applyRigPosters } from './rig-posters-core.mjs';
@@ -86,13 +86,15 @@ test('catalog assets name the selected revisions under CC0', async () => {
});
test('every staged download and viewer model is pinned for the asset host at its own URL', () => {
- const prefix = holodeckPrefix(catalog.release);
+ // Releases staged before content addressing keep their release paths until the next staging replaces them.
+ const legacy = `packs/holodeck/${catalog.release}/`;
const downloads = [
...catalog.assets.flatMap((asset) => [asset.runtimeModelDownload, asset.runtimeDownload, asset.editableDownload]),
...catalog.packs.flatMap((pack) => pack.downloads),
];
for (const download of downloads) {
- expect(download.path.startsWith(prefix)).toBe(true);
+ const name = download.path.split('/').at(-1);
+ expect(download.path === `${HOLODECK_OBJECTS}${download.sha256}/${name}` || download.path.startsWith(legacy)).toBe(true);
expect(download.url).toBe(ASSET_BASE + download.path);
expect(pins.get(download.path)).toEqual({ path: download.path, bytes: download.bytes, sha256: download.sha256 });
}
diff --git a/site/scripts/stage-holodeck.mjs b/site/scripts/stage-holodeck.mjs
index f96bf5fb..a0c1e727 100644
--- a/site/scripts/stage-holodeck.mjs
+++ b/site/scripts/stage-holodeck.mjs
@@ -7,7 +7,7 @@ import { buildDeliveryArchive, isSavedMaterialDependency, revisionBundle } from
import { readJson, writeJson } from './media-pins.mjs';
import { ASSET_BASE, assetPath, hashBytes, verifyArchive, verifyBytes } from './mirror-core.mjs';
import { applyRigPosters } from './rig-posters-core.mjs';
-import { HOLODECK_ASSETS, HOLODECK_ID, HOLODECK_PACKS, HOLODECK_PLANNED, holodeckApproved } from './holodeck-spec.mjs';
+import { HOLODECK_ASSETS, HOLODECK_ID, HOLODECK_IMPORT_KILN, HOLODECK_PACKS, HOLODECK_PLANNED, holodeckApproved } from './holodeck-spec.mjs';
import { materialClosure, metricsOf, verifyRuntimeProfile } from './stage-cabin-woods.mjs';
/**
@@ -18,17 +18,26 @@ import { materialClosure, metricsOf, verifyRuntimeProfile } from './stage-cabin-
* node scripts/stage-holodeck.mjs --kiln KILN_PACKAGE_DIR --mirror .localdata/holodeck-delivery \
* --store island-trial=DIR --store holodeck-assets=DIR --store courtyard-plaza=DIR --store tropical-island=DIR
* node scripts/stage-holodeck.mjs --upload-list --mirror .localdata/holodeck-delivery
+ * node scripts/stage-holodeck.mjs --record-published .localdata/holodeck-delivery/holodeck-upload-list.json.published.json
*
- * Generated downloads go to the ignored mirror under `packs/holodeck/<release>/` and are pinned in
- * `src/data/mirror-manifest.json` for the asset host; lightweight sources and manifests are kept in
- * `packs/holodeck/sources/`. Nothing is uploaded or published.
+ * Generated downloads go to the ignored mirror at content-addressed keys, `packs/holodeck/objects/<sha256>/<file>`,
+ * shared by every release that keeps their bytes, and are pinned in `src/data/mirror-manifest.json` for the asset
+ * host; lightweight sources and manifests are kept in `packs/holodeck/sources/`. `packs/holodeck/published.json`
+ * records the objects the asset host has served back, so the upload list names only new ones. Nothing is uploaded
+ * or published.
*/
const SITE = resolve(import.meta.dirname, '..');
const PACKS_ROOT = resolve(SITE, '../packs/holodeck');
const json = (bytes) => JSON.parse(bytes.toString('utf8'));
const strip = (sha) => sha.replace(/^sha256:/, '');
-export const holodeckPrefix = (release) => `packs/${HOLODECK_ID}/${release}/`;
+const PUBLISHED = join(PACKS_ROOT, 'published.json');
+export const HOLODECK_OBJECTS = `packs/${HOLODECK_ID}/objects/`;
+/** A download's key: its SHA-256 names the folder and the file keeps its readable name, so equal bytes share a key. */
+export function holodeckObjectPath(name, bytes) {
+ if (assetPath(name).includes('/')) throw new Error(`Object names are single files: ${name}`);
+ return `${HOLODECK_OBJECTS}${hashBytes(bytes)}/${name}`;
+}
export const HOLODECK_OMISSION = 'Earlier revisions are omitted by choice: this pack delivers the final version only. The parent revision identifier is kept as provenance.';
export function holodeckLicence() {
@@ -73,30 +82,31 @@ async function writeImmutable(root, path, bytes) {
const target = join(root, assetPath(path));
try {
const prior = await readFile(target);
- if (!prior.equals(bytes)) throw new Error(`Existing staged file differs; use a new release: ${path}`);
+ if (!prior.equals(bytes)) throw new Error(`Existing staged object differs from its content address: ${path}`);
return;
} catch (error) { if (error.code !== 'ENOENT') throw error; }
await mkdir(dirname(target), { recursive: true });
await writeFile(target, bytes);
}
-export async function stageHolodeck({ kiln, mirror, stores, selectionFile = join(PACKS_ROOT, 'selection.json'), site = SITE, packsRoot = PACKS_ROOT, exporter = runtimeExport }) {
+export async function stageHolodeck({ kiln, mirror, stores, selectionFile = join(PACKS_ROOT, 'selection.json'), site = SITE, packsRoot = PACKS_ROOT, exporter = runtimeExport, packs: packSpecs = HOLODECK_PACKS, presentations = HOLODECK_ASSETS, approved = holodeckApproved }) {
if (!kiln || !mirror || !stores || !Object.keys(stores).length) throw new Error('Explicit Kiln package, mirror and stores are required');
const selection = json(await readFile(selectionFile));
if (selection.schemaVersion !== 1 || selection.licence !== 'CC0-1.0' || !/^[a-z0-9-]+$/.test(selection.release)) throw new Error('Invalid Holodeck selection');
const kilnVersion = json(await readFile(join(kiln, 'package.json'))).version;
- const release = selection.release, prefix = holodeckPrefix(release);
+ const release = selection.release;
const licence = holodeckLicence(), cc0 = await readFile(join(packsRoot, 'LICENSES/CC0-1.0.txt'));
- const output = new Map(), lightweight = new Map(), staged = {};
- const add = (path, bytes) => {
- const full = prefix + assetPath(path);
- if (output.has(full)) throw new Error(`Duplicate staged output: ${full}`);
- output.set(full, Buffer.from(bytes));
- return { path: full, url: ASSET_BASE + full, bytes: bytes.length, sha256: hashBytes(bytes) };
+ const output = new Map(), names = new Set(), lightweight = new Map(), staged = {};
+ const add = (name, bytes) => {
+ if (names.has(name)) throw new Error(`Duplicate staged output: ${name}`);
+ names.add(name);
+ const path = holodeckObjectPath(name, bytes);
+ output.set(path, Buffer.from(bytes));
+ return { path, url: ASSET_BASE + path, bytes: bytes.length, sha256: hashBytes(bytes) };
};
for (const [slug, chosen] of Object.entries(selection.assets)) {
- const presentation = HOLODECK_ASSETS[slug];
+ const presentation = presentations[slug];
if (!presentation) throw new Error(`No gallery presentation for ${slug}`);
if (!stores[chosen.store]) throw new Error(`No --store given for ${chosen.store}`);
const revisionDir = join(stores[chosen.store], chosen.assetId, 'revisions', chosen.revisionId);
@@ -144,24 +154,25 @@ export async function stageHolodeck({ kiln, mirror, stores, selectionFile = join
collection: chosen.collection, assetId: manifest.assetId, revisionId: manifest.revisionId,
...(manifest.parentRevision ? { parentRevision: manifest.parentRevision } : {}),
sourcePath: `packs/holodeck/sources/${identity}/source.kiln.js`, sourceSha256: entry.sourceSha256,
- runtimeModelDownload: add(`models/${slug}.glb`, runtime),
- runtimeDownload: add(`runtime/${slug}.zip`, buildDeliveryArchive({ profile: 'runtime', group: HOLODECK_ID, assets: [entry], files: runtimeFiles })),
- editableDownload: add(`editable/${slug}.zip`, editable),
+ runtimeModelDownload: add(`${slug}.glb`, runtime),
+ runtimeDownload: add(`${slug}-runtime.zip`, buildDeliveryArchive({ profile: 'runtime', group: HOLODECK_ID, assets: [entry], files: runtimeFiles })),
+ editableDownload: add(`${slug}-editable.zip`, editable),
poster: null,
metrics: metricsOf(canonical, manifest),
- review: holodeckApproved(slug, manifest.revisionId) ? { ownerAccepted: true, status: 'accepted' } : { ownerAccepted: false, status: 'awaiting-owner-review' },
+ review: approved(slug, manifest.revisionId) ? { ownerAccepted: true, status: 'accepted' } : { ownerAccepted: false, status: 'awaiting-owner-review' },
historyScope: 'selected-only',
},
};
}
const packs = [];
- for (const spec of HOLODECK_PACKS) {
+ for (const spec of packSpecs) {
const chosen = selection.packs[spec.id];
if (!chosen || chosen.assets.length !== spec.expectedAssets) throw new Error(`${spec.id}: the selection does not hold ${spec.expectedAssets} assets`);
const members = chosen.assets.map((slug) => staged[slug]);
const inventory = members.map((member) => member.entry);
- const readme = Buffer.from(`${spec.name} (Holodeck scene pack, ${release})\n\n${spec.description}\n\nRuntime assets: GLBs under models/ with Kiln runtime metadata sidecars. They need no Kiln install.\nFull Kiln assets: each ZIP under revisions/ is a standard Kiln revision bundle (model, exact source, editing manifest and preview). Import one with node kiln.mjs import revision.zip, using Kiln ${kilnVersion} or later. These are final versions only: earlier revisions are omitted by choice, and each parent revision identifier is kept as provenance (delivery.json lists them under omittedParents).\n\nAsset licence: CC0-1.0 (LICENSE.txt, LICENSES/CC0-1.0.txt).\n`);
+ // Neither the release nor the staging exporter appears here, so an unchanged pack keeps its bytes and its key.
+ const readme = Buffer.from(`${spec.name} (Holodeck scene pack)\n\n${spec.description}\n\nRuntime assets: GLBs under models/ with Kiln runtime metadata sidecars. They need no Kiln install.\nFull Kiln assets: each ZIP under revisions/ is a standard Kiln revision bundle (model, exact source, editing manifest and preview). Import one with node kiln.mjs import revision.zip, using Kiln ${HOLODECK_IMPORT_KILN} or later. These are final versions only: earlier revisions are omitted by choice, and each parent revision identifier is kept as provenance (delivery.json lists them under omittedParents).\n\nAsset licence: CC0-1.0 (LICENSE.txt, LICENSES/CC0-1.0.txt).\n`);
const runtimeMembers = { 'LICENSE.txt': licence, 'LICENSES/CC0-1.0.txt': cc0, 'README.txt': readme };
const editableMembers = { 'LICENSE.txt': licence, 'LICENSES/CC0-1.0.txt': cc0, 'README.txt': readme };
for (const member of members) {
@@ -195,7 +206,7 @@ export async function stageHolodeck({ kiln, mirror, stores, selectionFile = join
}
for (const [path, bytes] of output) await writeImmutable(mirror, path, bytes);
for (const [path, bytes] of lightweight) { const target = join(packsRoot, path); await mkdir(dirname(target), { recursive: true }); await writeFile(target, bytes); }
- // A new release replaces every earlier unpublished Holodeck download pin; posters are pinned separately.
+ // Pins follow the current catalog: objects it no longer uses are unpinned, never deleted. Posters are pinned separately.
const kept = pins.files.filter((record) => !record.path.startsWith(`packs/${HOLODECK_ID}/`) || output.has(record.path));
const pinned = new Set(kept.map((record) => record.path));
await writeJson(manifestFile, { ...pins, files: [...kept, ...[...output].filter(([path]) => !pinned.has(path)).map(([path, bytes]) => ({ path, bytes: bytes.length, sha256: hashBytes(bytes) }))] });
@@ -216,18 +227,53 @@ export async function stageHolodeck({ kiln, mirror, stores, selectionFile = join
return { catalog, files: output.size, bytes: [...output.values()].reduce((sum, bytes) => sum + bytes.length, 0) };
}
-/** The pinned Holodeck objects (downloads and posters) as a publish-assets.mjs upload list, each verified in the mirror. */
-export async function holodeckUploadList({ mirror, site = SITE }) {
+const readLedger = async (ledger) => {
+ try { return new Map((await readJson(ledger)).objects.map((record) => [record.path, record])); }
+ catch (error) { if (error.code === 'ENOENT') return new Map(); throw error; }
+};
+const sameObject = (a, b) => a.sha256 === b.sha256 && a.bytes === b.bytes;
+
+/**
+ * The catalog's objects (downloads and posters) that the asset host has not yet served back, as a publish-assets.mjs
+ * upload list, each verified in the mirror. Objects recorded in the published ledger are left out.
+ */
+export async function holodeckUploadList({ mirror, site = SITE, ledger = PUBLISHED }) {
const catalog = await readJson(join(site, 'src/data/holodeck.json'));
- // Posters stay valid across releases that keep a model's bytes, so they are listed by what the catalog uses.
- const posters = new Set(catalog.assets.map((asset) => asset.poster?.inputPath).filter(Boolean));
- const records = (await readJson(join(site, 'src/data/mirror-manifest.json'))).files.filter((record) => record.path.startsWith(holodeckPrefix(catalog.release)) || posters.has(record.path));
- for (const record of records) verifyBytes(await readFile(join(mirror, assetPath(record.path))), record, record.path);
const missingPosters = catalog.assets.filter((asset) => !asset.poster).map((asset) => asset.slug);
if (missingPosters.length) throw new Error(`Render the Holodeck posters before listing uploads: ${missingPosters.join(', ')}`);
+ const used = new Set([
+ ...catalog.assets.flatMap((asset) => [asset.runtimeModelDownload.path, asset.runtimeDownload.path, asset.editableDownload.path, asset.poster.inputPath]),
+ ...catalog.packs.flatMap((pack) => pack.downloads.map((download) => download.path)),
+ ]);
+ const pins = new Map((await readJson(join(site, 'src/data/mirror-manifest.json'))).files.map((record) => [record.path, record]));
+ const published = await readLedger(ledger);
+ const records = [];
+ for (const path of used) {
+ const record = pins.get(path);
+ if (!record) throw new Error(`The catalog uses an unpinned object: ${path}`);
+ const prior = published.get(path);
+ if (prior && !sameObject(prior, record)) throw new Error(`The asset host holds different bytes at ${path}`);
+ if (!prior) records.push(record);
+ }
+ for (const record of records) verifyBytes(await readFile(join(mirror, assetPath(record.path))), record, record.path);
return records;
}
+/** Record the objects a publish-assets.mjs receipt read back from the asset host in the published ledger. */
+export async function recordHolodeckPublished({ receipt, ledger = PUBLISHED }) {
+ const published = await readLedger(ledger);
+ let added = 0;
+ for (const file of (await readJson(receipt)).files) {
+ const record = { path: assetPath(file.path), bytes: file.bytes, sha256: file.sha256 };
+ if (typeof file.verifiedUrl !== 'string' || !file.verifiedUrl.startsWith(ASSET_BASE + record.path + '?')) throw new Error(`${record.path} was not read back from the asset host`);
+ const prior = published.get(record.path);
+ if (prior && !sameObject(prior, record)) throw new Error(`The ledger already holds different bytes at ${record.path}`);
+ if (!prior) { published.set(record.path, record); added++; }
+ }
+ await writeJson(ledger, { schemaVersion: 1, objects: [...published.values()].sort((a, b) => a.path.localeCompare(b.path, 'en')) });
+ return { added, objects: published.size };
+}
+
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const args = process.argv.slice(2), options = { stores: {} };
const uploadList = args.includes('--upload-list');
@@ -237,9 +283,12 @@ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.m
if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}`);
if (flag === '--store') { const [name, dir] = value.split(/=(.*)/s); options.stores[name] = await realpath(dir); }
else if (['--kiln', '--mirror'].includes(flag)) options[flag.slice(2)] = resolve(value);
+ else if (flag === '--record-published') options.receipt = resolve(value);
else throw new Error(`Unknown option ${flag}`);
}
- if (uploadList) {
+ if (options.receipt) {
+ console.log(JSON.stringify(await recordHolodeckPublished({ receipt: options.receipt }), null, 2));
+ } else if (uploadList) {
const records = await holodeckUploadList(options);
const file = join(options.mirror, 'holodeck-upload-list.json');
await writeFile(file, JSON.stringify(records, null, 2) + '\n');
diff --git a/site/scripts/stage-holodeck.test.ts b/site/scripts/stage-holodeck.test.ts
new file mode 100644
index 00000000..43b19ba8
--- /dev/null
+++ b/site/scripts/stage-holodeck.test.ts
@@ -0,0 +1,154 @@
+import { afterEach, expect, test } from 'bun:test';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { hashBytes, verifyArchive } from './mirror-core.mjs';
+import { holodeckObjectPath, holodeckUploadList, recordHolodeckPublished, stageHolodeck } from './stage-holodeck.mjs';
+
+const directories: string[] = [];
+afterEach(async () => { for (const d of directories.splice(0)) await rm(d, { recursive: true, force: true }); });
+
+const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jzVkAAAAASUVORK5CYII=', 'base64');
+const seal = (bytes: Buffer) => ({ bytes: bytes.length, sha256: hashBytes(bytes) });
+const put = async (path: string, data: Buffer | string) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, data); };
+
+function triangleGlb(name: string, extras?: Record<string, unknown>) {
+ const bin = Buffer.alloc(44); for (const [i, v] of [0, 0, 0, 1, 0, 0, 0, 1, 0].entries()) bin.writeFloatLE(v, i * 4); for (let i = 0; i < 3; i++) bin.writeUInt16LE(i, 36 + i * 2);
+ const document = { asset: { version: '2.0', ...(extras ? { extras } : {}) }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ name, mesh: 0 }], meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }], materials: [{}], accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] }, { bufferView: 1, componentType: 5123, count: 3, type: 'SCALAR' }], buffers: [{ byteLength: 44 }], bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }, { buffer: 0, byteOffset: 36, byteLength: 6 }] };
+ const raw = Buffer.from(JSON.stringify(document)); const json = Buffer.alloc(Math.ceil(raw.length / 4) * 4, 32); raw.copy(json);
+ const b = Buffer.alloc(28 + json.length + bin.length); b.write('glTF'); b.writeUInt32LE(2, 4); b.writeUInt32LE(b.length, 8); b.writeUInt32LE(json.length, 12); b.write('JSON', 16); json.copy(b, 20); b.writeUInt32LE(bin.length, 20 + json.length); b.write('BIN\0', 24 + json.length); bin.copy(b, 28 + json.length); return b;
+}
+
+const SLUGS = ['shell', 'palm', 'lantern'] as const;
+const ids = (slug: string) => { const c = (SLUGS.indexOf(slug as never) + 1).toString(16); return { assetId: 'a_' + c.repeat(32), revisionId: 'r_' + c.repeat(32) }; };
+const presentations = Object.fromEntries(SLUGS.map((slug) => [slug, { name: slug, description: `A ${slug}.`, category: 'prop' }]));
+
+/** A Kiln store holding one saved revision per slug, and a fake runtime export that keeps the canonical binary. */
+async function fixture() {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-holodeck-stage-')); directories.push(root);
+ const store = join(root, 'store'), site = join(root, 'site'), packsRoot = join(root, 'packs'), mirror = join(root, 'mirror');
+ const runtimes: Record<string, { glb: Buffer; metadata: Buffer }> = {};
+ const assets: Record<string, unknown> = {};
+ for (const slug of SLUGS) {
+ const { assetId, revisionId } = ids(slug);
+ const canonical = triangleGlb(slug), source = Buffer.from(`const meta={name:'${slug}'};function build(){return createRoot('${slug}');}`);
+ const files = { 'asset.glb': canonical, 'source.kiln.js': source, 'preview.png': png };
+ const manifest = Buffer.from(JSON.stringify({ version: 'kiln.asset.v1', assetId, revisionId, name: slug, tags: [], createdAt: '2026-10-24T00:00:00.000Z', editable: true, files: Object.fromEntries(Object.entries(files).map(([name, bytes]) => [name, { bytes: bytes.length, sha256: 'sha256:' + hashBytes(bytes) }])) }));
+ const dir = join(store, assetId, 'revisions', revisionId);
+ await put(join(dir, 'manifest.json'), manifest);
+ for (const [name, bytes] of Object.entries(files)) await put(join(dir, name), bytes);
+ const metadata = Buffer.from(JSON.stringify({ version: 'kiln.runtime-metadata.v1', source: { assetId, revisionId, glbSha256: 'sha256:' + hashBytes(canonical), sourceSha256: 'sha256:' + hashBytes(source) } }));
+ runtimes[slug] = { glb: triangleGlb(slug, { kilnProvenanceV1: { version: 'kiln.provenance.v1', profile: 'runtime', metadata: { uri: `${slug}.kiln-metadata.json`, sha256: 'sha256:' + hashBytes(metadata) } } }), metadata };
+ assets[slug] = { store: 'fixture', collection: 'project', assetId, revisionId, manifest: seal(manifest), canonical: seal(canonical), source: seal(source), placements: [] };
+ }
+ await put(join(packsRoot, 'LICENSES/CC0-1.0.txt'), 'CC0 1.0 Universal (fixture)\n');
+ await put(join(site, 'src/data/mirror-manifest.json'), JSON.stringify({ files: [] }));
+ await put(join(site, 'src/data/commons-build.json'), JSON.stringify({ viewerModels: [] }));
+ await put(join(root, 'kiln/package.json'), JSON.stringify({ version: '9.9.9' }));
+ const exporter = async ({ slug }: { slug: string }) => runtimes[slug];
+ return { root, store, site, packsRoot, mirror, assets, exporter, kiln: join(root, 'kiln') };
+}
+
+type Fixture = Awaited<ReturnType<typeof fixture>>;
+const PACK = (id: string, expectedAssets: number) => ({ id, scene: id, name: id, description: `The ${id} pack.`, expectedAssets });
+
+/** Stage one release: each pack lists its slugs, and every slug records the packs that place it. */
+async function stageRelease(f: Fixture, release: string, packs: Record<string, string[]>) {
+ const assets = JSON.parse(JSON.stringify(f.assets));
+ for (const [pack, slugs] of Object.entries(packs)) for (const slug of slugs) assets[slug].placements.push({ pack });
+ const used = Object.fromEntries(Object.entries(assets).filter(([, record]: [string, any]) => record.placements.length));
+ const selectionFile = join(f.root, `selection-${release}.json`);
+ await put(selectionFile, JSON.stringify({ schemaVersion: 1, release, licence: 'CC0-1.0', versions: 'final-only', packs: Object.fromEntries(Object.entries(packs).map(([id, slugs]) => [id, { assets: slugs, source: { kind: 'fixture' } }])), assets: used }));
+ return stageHolodeck({ kiln: f.kiln, mirror: f.mirror, stores: { fixture: f.store }, selectionFile, site: f.site, packsRoot: f.packsRoot, exporter: f.exporter, packs: Object.entries(packs).map(([id, slugs]) => PACK(id, slugs.length)), presentations, approved: () => true });
+}
+
+/** Record a poster per staged model, as scripts/rig-posters.mjs does, then stage again so the catalog shows them. */
+async function stageWithPosters(f: Fixture, release: string, packs: Record<string, string[]>) {
+ const { catalog } = await stageRelease(f, release, packs);
+ const posters: Record<string, unknown> = {};
+ const pins = JSON.parse(await readFile(join(f.site, 'src/data/mirror-manifest.json'), 'utf8'));
+ for (const asset of catalog.assets) {
+ const path = `media/rig/review-neutral-v1/holodeck/${asset.slug}.png`;
+ await put(join(f.mirror, path), png);
+ if (!pins.files.some((record: { path: string }) => record.path === path)) pins.files.push({ path, ...seal(png) });
+ posters[`holodeck:${asset.slug}`] = { path, width: 1, height: 1, assetId: asset.assetId, revisionId: asset.revisionId, glb: { bytes: asset.runtimeModelDownload.bytes, sha256: asset.runtimeModelDownload.sha256 } };
+ }
+ await put(join(f.site, 'src/data/mirror-manifest.json'), JSON.stringify(pins));
+ await put(join(f.site, 'src/data/rig-posters.json'), JSON.stringify({ posters }));
+ return (await stageRelease(f, release, packs)).catalog;
+}
+
+const downloads = (catalog: any) => [
+ ...catalog.assets.flatMap((asset: any) => [asset.runtimeModelDownload, asset.runtimeDownload, asset.editableDownload]),
+ ...catalog.packs.flatMap((pack: any) => pack.downloads),
+];
+
+test('downloads live at content-addressed keys that keep a readable file name', async () => {
+ const f = await fixture();
+ const { catalog } = await stageRelease(f, 'holodeck-fixture-01', { 'holodeck-cove': ['shell', 'palm'] });
+ const shell = catalog.assets.find((asset: any) => asset.slug === 'shell');
+ expect(shell.runtimeModelDownload.path).toBe(`packs/holodeck/objects/${shell.runtimeModelDownload.sha256}/shell.glb`);
+ expect(shell.runtimeDownload.path).toMatch(/^packs\/holodeck\/objects\/[0-9a-f]{64}\/shell-runtime\.zip$/);
+ expect(shell.editableDownload.path).toMatch(/^packs\/holodeck\/objects\/[0-9a-f]{64}\/shell-editable\.zip$/);
+ for (const download of downloads(catalog)) {
+ const name = download.path.split('/').at(-1);
+ expect(download.path).toBe(holodeckObjectPath(name, await readFile(join(f.mirror, download.path))));
+ expect(download.url).toBe('https://assets.kilnstudio.tools/' + download.path);
+ }
+ expect(catalog.release).toBe('holodeck-fixture-01');
+ expect(catalog.packs[0].downloads.map((d: any) => d.path.split('/').at(-1))).toEqual(['holodeck-cove-runtime.zip', 'holodeck-cove-editable.zip']);
+});
+
+test('a new release reuses every unchanged object and adds only what changed', async () => {
+ const f = await fixture();
+ const first = (await stageRelease(f, 'holodeck-fixture-01', { 'holodeck-cove': ['shell', 'palm'], 'holodeck-tide': ['palm'] })).catalog;
+ // The next release adds a scene that shares the palm: palm gains a pack, but its bytes and the old packs' bytes do not change.
+ const second = (await stageRelease(f, 'holodeck-fixture-02', { 'holodeck-cove': ['shell', 'palm'], 'holodeck-tide': ['palm'], 'holodeck-winter': ['palm', 'lantern'] })).catalog;
+ const before = new Set(downloads(first).map((download: any) => download.path));
+ const added = downloads(second).filter((download: any) => !before.has(download.path)).map((download: any) => download.path.split('/').at(-1)).sort();
+ expect(added).toEqual(['holodeck-winter-editable.zip', 'holodeck-winter-runtime.zip', 'lantern-editable.zip', 'lantern-runtime.zip', 'lantern.glb']);
+ expect(second.assets.find((asset: any) => asset.slug === 'palm').packs).toEqual(['holodeck-cove', 'holodeck-tide', 'holodeck-winter']);
+ // Pack READMEs name neither the release nor the exporter that staged it, so they stay byte-identical across releases.
+ const readme = Buffer.from(verifyArchive(await readFile(join(f.mirror, second.packs[0].downloads[0].path))).files['README.txt']).toString();
+ expect(readme).not.toContain('holodeck-fixture');
+ expect(readme).not.toContain('9.9.9');
+ // Pins and viewer models follow the current catalog, and every pinned object is in the mirror.
+ const pins = JSON.parse(await readFile(join(f.site, 'src/data/mirror-manifest.json'), 'utf8')).files.map((record: any) => record.path).sort();
+ expect(pins).toEqual([...new Set(downloads(second).map((download: any) => download.path))].sort());
+ const plan = JSON.parse(await readFile(join(f.site, 'src/data/commons-build.json'), 'utf8'));
+ expect(plan.viewerModels.sort()).toEqual(second.assets.map((asset: any) => asset.runtimeModelDownload.path).sort());
+});
+
+test('the upload list holds only objects the asset host has not verified', async () => {
+ const f = await fixture();
+ const ledger = join(f.packsRoot, 'published.json');
+ const first = await stageWithPosters(f, 'holodeck-fixture-01', { 'holodeck-cove': ['shell', 'palm'] });
+ const initial = await holodeckUploadList({ mirror: f.mirror, site: f.site, ledger });
+ expect(initial).toHaveLength(downloads(first).length + first.assets.length);
+ // publish-assets.mjs writes this receipt after reading every object back from the host.
+ const receipt = { files: initial.map((record: any) => ({ ...record, url: 'https://assets.kilnstudio.tools/' + record.path, verifiedUrl: 'https://assets.kilnstudio.tools/' + record.path + '?__kiln_publish=x', uploaded: true })) };
+ await put(join(f.root, 'receipt.json'), JSON.stringify(receipt));
+ expect((await recordHolodeckPublished({ receipt: join(f.root, 'receipt.json'), ledger })).added).toBe(initial.length);
+ expect(await holodeckUploadList({ mirror: f.mirror, site: f.site, ledger })).toEqual([]);
+
+ await stageWithPosters(f, 'holodeck-fixture-02', { 'holodeck-cove': ['shell', 'palm'], 'holodeck-winter': ['palm', 'lantern'] });
+ const next = await holodeckUploadList({ mirror: f.mirror, site: f.site, ledger });
+ expect(next.map((record: any) => record.path.split('/').at(-1)).sort()).toEqual(['holodeck-winter-editable.zip', 'holodeck-winter-runtime.zip', 'lantern-editable.zip', 'lantern-runtime.zip', 'lantern.glb', 'lantern.png']);
+ // Recording the same publication again changes nothing.
+ expect((await recordHolodeckPublished({ receipt: join(f.root, 'receipt.json'), ledger })).added).toBe(0);
+});
+
+test('immutable keys refuse different bytes in the mirror, the ledger and the receipt', async () => {
+ const f = await fixture();
+ const ledger = join(f.packsRoot, 'published.json');
+ const catalog = await stageWithPosters(f, 'holodeck-fixture-01', { 'holodeck-cove': ['shell'] });
+ const model = catalog.assets[0].runtimeModelDownload;
+ // A receipt entry that was never read back from the host is not evidence of publication.
+ await put(join(f.root, 'unverified.json'), JSON.stringify({ files: [{ path: model.path, bytes: model.bytes, sha256: model.sha256, uploaded: true }] }));
+ await expect(recordHolodeckPublished({ receipt: join(f.root, 'unverified.json'), ledger })).rejects.toThrow('read back');
+ await put(ledger, JSON.stringify({ schemaVersion: 1, objects: [{ path: model.path, bytes: model.bytes, sha256: '0'.repeat(64) }] }));
+ await expect(holodeckUploadList({ mirror: f.mirror, site: f.site, ledger })).rejects.toThrow('different bytes');
+ await rm(ledger);
+ await writeFile(join(f.mirror, model.path), Buffer.from('tampered'));
+ await expect(stageRelease(f, 'holodeck-fixture-02', { 'holodeck-cove': ['shell'] })).rejects.toThrow('differs');
+});