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.

10.0 KB
Raw Blame
import { readFile, mkdir } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { imageRecord } from './generate-commons.mjs';
import { readJson, writeJson, writeMirrorFile, upsertBy, sha256Hex } from './media-pins.mjs';
import { ASSET_BASE, verifyArchive, verifyBytes } from './mirror-core.mjs';

const site = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const commons = process.env.KILN_COMMONS_DIR;
if (!commons) throw new Error('Set KILN_COMMONS_DIR');
const data = join(site, 'src/data');
const mirror = process.env.KILN_ASSET_MIRROR ?? join(site, '.cache/round-4/mirror');
const review = join(commons, 'engine-work/local-v09-review/revision2-20260930');
const bundle = join(review, 'vehicles-runtime-final');
const inputs = await readJson(join(review, 'inputs/vehicles-final-inputs.json'));
const catalog = await readJson(join(review, 'inputs/vehicles-r3.json'));
const inventory = await readJson(join(bundle, 'delivery.json'));
const intake = await readJson(join(bundle, 'intake.json'));
const measurements = JSON.parse(verifyBytes(await readFile(join(bundle, 'measurements.json')), intake.measurements, 'final measurements'));
if (inventory.release !== 'r4-local-review' || sha256Hex(await readFile(join(bundle, 'delivery.json'))) !== intake.deliverySha256) throw new Error('Final bundle identity mismatch');
if (sha256Hex(await readFile(join(review, 'inputs/vehicles-final-inputs.json'))) !== intake.inputsSha256) throw new Error('Final inputs changed');
for (const file of inputs.documents) verifyBytes(await readFile(file.path), file, file.path);
const prefix = `packs/vehicles/${inventory.release}`;
const archivePath = `${prefix}/generic-road-vehicles-runtime.zip`;
let manifest = await readJson(join(data, 'mirror-manifest.json'));
const plan = await readJson(join(data, 'commons-build.json'));
const pin = async (path, bytes) => {
  const record = await writeMirrorFile(mirror, path, bytes);
  manifest.files = upsertBy(manifest.files, 'path', record);
  return record;
};
for (const [member, expected] of Object.entries(inventory.files)) await pin(`${prefix}/${member}`, verifyBytes(await readFile(join(bundle, member)), expected, member));
await pin(`${prefix}/delivery.json`, await readFile(join(bundle, 'delivery.json')));
const zip = verifyBytes(await readFile(join(bundle, 'generic-road-vehicles-runtime.zip')), intake.archive, 'final runtime archive');
verifyArchive(zip, 'delivery');
const zipPin = await pin(archivePath, zip);
plan.archives = [...new Set([...plan.archives, archivePath])];
for (const asset of catalog.assets) {
  const saved = inventory.assets.find((entry) => entry.slug === asset.slug);
  const input = inputs.assets.find((entry) => entry.slug === asset.slug);
  if (!saved || !input || saved.previousDeliveryRevision !== asset.revisionId) throw new Error(`Missing or divergent ${asset.slug}`);
  const measured = measurements[asset.slug];
  const savedManifest = JSON.parse(verifyBytes(await readFile(join(input.directory, 'manifest.json')), input.files['manifest.json'], `${asset.slug} manifest`));
  const source = verifyBytes(await readFile(join(input.directory, 'source.kiln.js')), input.files['source.kiln.js'], `${asset.slug} source`);
  const preview = verifyBytes(await readFile(join(input.directory, 'preview.png')), input.files['preview.png'], `${asset.slug} preview`);
  const editable = verifyBytes(await readFile(join(input.directory, 'editable.zip')), input.files['editable.zip'], `${asset.slug} editable`);
  const parsed = verifyArchive(editable, 'editable');
  if (parsed.manifest.revisionId !== saved.revisionId || parsed.manifest.assetId !== asset.assetId) throw new Error(`Editable identity mismatch: ${asset.slug}`);
  asset.runtimeDownload = { ...asset.runtimeDownload, ...inventory.files[saved.model], path: `${prefix}/${saved.model}`, url: `${ASSET_BASE}${prefix}/${saved.model}`, archive: archivePath };
  asset.licence = { ...asset.licence, ...inventory.files[saved.licence], path: `${prefix}/${saved.licence}`, url: `${ASSET_BASE}${prefix}/${saved.licence}`, statesDeliveredGlbSha256: asset.runtimeDownload.sha256 };
  plan.models = upsertBy(plan.models, 'output', { path: asset.runtimeDownload.path, output: asset.modelPath.slice(1), bytes: asset.runtimeDownload.bytes, sha256: asset.runtimeDownload.sha256 });
  const editablePin = await pin(`${prefix}/editable/${asset.slug}-editable.zip`, editable);
  const previewPin = await pin(`media/vehicles/${inventory.release}/review/${asset.slug}.png`, preview);
  const size = await sharp(preview).metadata();
  asset.reviewImage = { ...imageRecord(previewPin.path, size.width, size.height, `Saved review views of ${asset.name}.`), sourceRevisionId: saved.revisionId, exactRevision: true, fidelity: savedManifest.preview?.fidelity };
  asset.poster = { ...asset.poster, exactRevision: false, revisionQualification: 'Earlier preserved revision; the current revision poster is pending.' };
  const priorRevision = asset.revisionId;
  asset.parentRevision = saved.parentRevision;
  asset.revisionId = saved.revisionId;
  asset.canonicalGlb = saved.canonical;
  const drawn = measured.drawnByPlainLoader;
  const parts = [...measured.tiers[0].parts, ...measured.wheels.flatMap((wheel) => wheel.parts)];
  asset.metrics = { triangles: drawn.triangles, meshes: parts.length, materials: drawn.materials.length, bounds: drawn.bounds.size, boundsMin: drawn.bounds.min, boundsMax: drawn.bounds.max, clips: measured.animations, partPaths: parts };
  asset.tiers = measured.tiers.map((tier, index) => ({ ...asset.tiers[index], bodyTriangles: tier.bodyTriangles, wheelTriangles: tier.wheelTriangles, triangles: tier.triangles, wheelsShown: tier.wheelsShown, bounds: tier.bounds.size, coverageBelow: tier.coverageBelow, distanceMetres: tier.distanceMetres, parts: tier.parts.length, materials: tier.materials }));
  asset.tierLinks = { form: measured.form, culledBelow: measured.culledBelow, culledDistanceMetres: measured.culledDistanceMetres, wheelsHiddenAtLastTier: measured.wheelsHiddenAtLastTier, wheelsHiddenBeyondMetres: measured.wheelsHiddenBeyondMetres };
  asset.sourceSha256 = sha256Hex(source);
  asset.editableDownload = { ...asset.editableDownload, ...editablePin, url: `${ASSET_BASE}${editablePin.path}`, glbForm: 'MSFT_lod' };
  for (const revision of [...saved.savedChain].reverse().filter((entry) => entry.revisionId !== priorRevision)) {
    if (asset.revisions.some((entry) => entry.revisionId === revision.revisionId)) continue;
    const attribution = inputs.revisionRuns[revision.revisionId];
    const runPin = inputs.documents.find((file) => file.path === attribution?.authorRunPath);
    if (!runPin) throw new Error(`No sealed author run for ${asset.slug}/${revision.revisionId}`);
    const runBytes = verifyBytes(await readFile(runPin.path), runPin, runPin.path);
    const run = JSON.parse(runBytes);
    if (run.status !== 'completed' || run.processExitCode !== 0) throw new Error(`Author run is not complete: ${asset.slug}`);
    const record = { stage: attribution.stage, request: 'owner-review-2', revisionId: revision.revisionId, parentRevisionId: revision.parentRevision, savedAt: revision.createdAt, brief: revision.description, model: 'GPT-6 Astra', modelId: run.requestedModel, savedModelLabel: revision.attribution.model, requestedEffort: run.requestedEffort, confirmedEffort: null, harness: run.harness, harnessVersion: run.harnessVersion, confirmation: run.attributionNote ?? run.source, run: { stage: run.stage, label: run.label, status: run.status, stop: run.stop, startedAt: run.startedAt, endedAt: run.endedAt, receiptSha256: sha256Hex(runBytes), invocationSha256: run.sessionRecordSha256 } };
    asset.revisions.push(record);
    asset.provenance.history.push(record);
  }
  asset.provenance.refinementModels = [...new Set([...asset.provenance.refinementModels, 'GPT-6 Astra'])];
  asset.review = { status: 'awaiting-owner-review', ownerAccepted: false, scope: `${input.change}. Preserved parent revisions retain their historical review records; acceptance of this revision is pending.`, correction: `${asset.name}: ${input.change}; awaiting owner review.`, recordedAt: '2026-10-01', source: 'Local owner review 2 sealed author handoff and exact saved revision manifests' };
  const sourceMember = Object.keys(parsed.files).find((path) => path.endsWith('/source.kiln.js'));
  if (!sourceMember) throw new Error(`No editable source: ${asset.slug}`);
  plan.sources = upsertBy(plan.sources, 'output', { archive: editablePin.path, member: sourceMember, output: asset.sourcePath.slice(1), bytes: source.length, sha256: asset.sourceSha256 });
  plan.archives = [...new Set([...plan.archives, editablePin.path])];
  plan.images = upsertBy(plan.images, 'inputPath', asset.reviewImage);
}
catalog.release = inventory.release;
catalog.downloads = [{ ...catalog.downloads[0], ...zipPin, path: archivePath, url: `${ASSET_BASE}${archivePath}` }];
catalog.ownerReview = { acceptedAssets: 0, total: 6, status: 'awaiting-owner-review', date: '2026-10-01', statement: 'All six preserved child revisions await owner review. Hatchback, sedan and SUV have front and rear lamp repairs. Pickup, box truck and bus preserve their geometry and now declare standard LODs in their saved source masters.', source: 'Local owner review 2', awaiting: catalog.assets.map((asset) => asset.slug) };
catalog.licenceNote = 'Each licence text names the exact saved revision, canonical GLB and delivered runtime hash. The runtime adds wheel-cull links at the final body tier while preserving geometry and pivots. Prior revisions remain preserved under CC0-1.0.';
await writeJson(join(data, 'packs/vehicles.json'), catalog);
await writeJson(join(data, 'commons-build.json'), plan);
await writeJson(join(data, 'mirror-manifest.json'), manifest);
await mkdir(join(review, 'vehicles-site-intake-final'), { recursive: true });
await writeJson(join(review, 'vehicles-site-intake-final/catalog.json'), catalog);
console.log(JSON.stringify({ release: catalog.release, assets: catalog.assets.length, pendingOwnerReview: catalog.ownerReview.awaiting, next: 'Capture exact revision posters, then rebuild and qualify the integrated site.' }));