Skip to content

armgit / kiln

Public Imported from GitHub
0

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

feat(save): report geometry deltas against the parent revision (#245)

Matt Kissingere527d2a80e29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a35ec41a..56fbaa85 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -110,6 +110,17 @@ does not publish a package.
advice. `defineBudget` gains `images`, `decodedBytes` and `materialTier`, measured in
`budget.materials` and covered by `--strict-budget`; `triangles` is now optional when
another limit is declared ([#176](https://github.com/instruktlabs/kiln/issues/176)).
+- Report geometry deltas against the parent revision on save
+ ([#245](https://github.com/instruktlabs/kiln/issues/245)). A `kiln_save` (and
+ `kiln save --parent`) with `parentRevision` now returns `comparison`: the drawn
+ triangle, vertex, draw-call and material counts as `parent`, `child` and `delta`, the
+ drawn bounds sizes and their delta, and `geometryIdentical`, a hash of the sorted drawn
+ world-space triangles at float32 precision that ignores node, primitive and vertex
+ order, with `uvIdentical` when the geometry matches. Merging four primitives into one
+ without moving a vertex now reads as identical geometry with three fewer draws instead
+ of only a changed part. A comparison that cannot be made reports `unavailable` and
+ never fails the save. `kiln_inspect` compare (and `kiln_edit` preservation) gain the
+ same `counts`, `geometryIdentical`, `uvIdentical` and `boundsDelta`. No input changed.
## 1.4.0 (2026-10-23)
diff --git a/docs/cameras.md b/docs/cameras.md
index 96b9b882..25a73781 100644
--- a/docs/cameras.md
+++ b/docs/cameras.md
@@ -119,7 +119,9 @@ frame, or fewer phases or parts per call).
`kiln_inspect` accepts `compare: {programRef: OLD_REF, offset: 0, limit: 50}`
alongside the current source/reference and camera controls. It reports exact
exported static geometry, material, rest-transform and bounds changes with GLB
-hashes. Follow `comparison.nextOffset` to read every change. Both revisions use
+hashes, the drawn triangle, vertex, draw-call and material `counts`, `boundsDelta`, and
+`geometryIdentical`, which ignores node and primitive order, so a merge that moves no
+vertex reads as identical. Follow `comparison.nextOffset` to read every change. Both revisions use
current host settings; comparison does not certify intent, animation or physical
fit. Unsupported or ambiguous structures fail explicitly. See
[the comparison workflow and limits](../skills/kiln-refine-asset/references/revision-and-views.md#compare-exported-revisions).
diff --git a/docs/collections.md b/docs/collections.md
index 961a9bfd..b2b4e6bd 100644
--- a/docs/collections.md
+++ b/docs/collections.md
@@ -100,6 +100,10 @@ by default. There is no automatic deletion or disk quota for saved collections.
4. In a later session, use `kiln_assets` with `action: "restore"`, collection,
assetId and revisionId. Use the returned programRef with `kiln_source`/`kiln_edit`.
5. Save a child with the same assetId and `parentRevision` equal to the base revision.
+ The result's `comparison` gives the drawn triangle, vertex, draw-call and material
+ counts as `parent`, `child` and `delta`, the drawn bounds sizes and their delta, and
+ `geometryIdentical` (plus `uvIdentical` when it is true). See
+ [the comparison fields](../skills/kiln-refine-asset/references/revision-and-views.md#compare-exported-revisions).
Every save is immutable. A child does not update or delete its parent, and concurrent children are
retained as separate branch tips. The viewer exposes the revision selector and branch count, while
diff --git a/docs/tools-operations.md b/docs/tools-operations.md
index 75182080..a766fd1f 100644
--- a/docs/tools-operations.md
+++ b/docs/tools-operations.md
@@ -1185,7 +1185,7 @@ Import complete normalized material records and embedded PNGs. Does not fetch UR
## kiln_save
-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.
+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, and the result comparison gives triangle, vertex, draw and material deltas, the bounds delta and geometryIdentical against the parent. Returns downloadable resources; draft renders never populate collections.
<details>
<summary>Input JSON Schema</summary>
diff --git a/docs/tools.md b/docs/tools.md
index a2ebf758..c053b2c8 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -1576,7 +1576,7 @@ Read persisted Kiln observation history, pin an operation against normal retenti
## kiln_save
-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.
+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, and the result comparison gives triangle, vertex, draw and material deltas, the bounds delta and geometryIdentical against the parent. Returns downloadable resources; draft renders never populate collections.
<details>
<summary>Input JSON Schema</summary>
diff --git a/skills/kiln-refine-asset/SKILL.md b/skills/kiln-refine-asset/SKILL.md
index b639d75e..8e788480 100644
--- a/skills/kiln-refine-asset/SKILL.md
+++ b/skills/kiln-refine-asset/SKILL.md
@@ -21,7 +21,7 @@ When given a retained `programRef`, read it with `kiln_source`; the host owns it
For a collection asset, first call `kiln_assets` with `action: "restore"`, `collection`, `assetId`, and `revisionId`. This imports its exact source into the current program store and returns a fresh `programRef`. A downloaded ZIP can be imported with `node kiln.mjs import bundle.zip`. A binary-only GLB has no source to restore.
-For a collection asset, after reviewing the change, use `kiln_save` to create an immutable child revision with the new `programRef`, the original `assetId`, and `parentRevision` set to the exact revision you started from. Preserve the collection, name, relevant tags, and known model/harness attribution; describe the change. Pass the `backdrop` the accepted sheet used when it was not the default, so the preview matches what you reviewed. Never replace or delete the base: its prior revision remains intact, and concurrent children remain visible as branches. Return the new revision's download resources; copying to a different collection does not make a live link.
+For a collection asset, after reviewing the change, use `kiln_save` to create an immutable child revision with the new `programRef`, the original `assetId`, and `parentRevision` set to the exact revision you started from. Preserve the collection, name, relevant tags, and known model/harness attribution; describe the change. Pass the `backdrop` the accepted sheet used when it was not the default, so the preview matches what you reviewed. Never replace or delete the base: its prior revision remains intact, and concurrent children remain visible as branches. The save's `comparison` gives triangle, vertex, draw and material deltas against the parent and `geometryIdentical`; cite them when you describe the change. Return the new revision's download resources; copying to a different collection does not make a live link.
For CLI request files and image exports, use [revision commands](references/revision-cli.md).
diff --git a/skills/kiln-refine-asset/references/revision-and-views.md b/skills/kiln-refine-asset/references/revision-and-views.md
index 81121a68..a83d04fe 100644
--- a/skills/kiln-refine-asset/references/revision-and-views.md
+++ b/skills/kiln-refine-asset/references/revision-and-views.md
@@ -35,6 +35,21 @@ nodes appear as removed and added. The summary includes unchanged nodes, while
the paged list includes changes only. Copy `nextOffset` into `compare.offset` to
continue; null means there are no more entries.
+`comparison.counts` gives the drawn `triangles`, `vertices`, `drawCalls` and
+`materials` as `before`, `after` and `delta`, counted as render metrics count
+them; `boundsDelta` subtracts the before bounds from the after bounds.
+`geometryIdentical` compares the drawn world-space triangles as float32
+coordinates, sorted, so node, primitive, vertex and triangle order do not count
+but winding does: merging parts into fewer primitives without moving a vertex
+reads as identical even though the merged nodes appear as removed and added.
+`uvIdentical`, present only when the geometry is identical, adds `TEXCOORD_0` at
+each corner. There is no tolerance; normals, vertex colours, skin weights and
+morph targets are not part of the hash. A child save with
+`parentRevision` returns the same counts as `comparison.counts` with `parent`,
+`child` and `delta`, the drawn bounds sizes with their delta, and
+`geometryIdentical`; it never fails the save, and reports `unavailable` when the
+revisions cannot be counted. Per-node changes still need `kiln_inspect` compare.
+
To check components an edit must preserve without paging through unrelated
changes, add `compare.paths: [PROTECTED_ROOT_PATH]` (up to 12 distinct paths).
`comparison.subtrees` always summarizes every node in each selected subtree,
diff --git a/src/revision-comparison.test.ts b/src/revision-comparison.test.ts
index 23fdcfd3..d836ccd1 100644
--- a/src/revision-comparison.test.ts
+++ b/src/revision-comparison.test.ts
@@ -1,7 +1,8 @@
import { expect, test } from 'bun:test';
import { Document } from '@gltf-transform/core';
import { createGltfIO } from './gltf-io';
-import { compareRevisionGlbs } from './revision-comparison';
+import { EXTMeshGPUInstancing, KHRNodeVisibility } from '@gltf-transform/extensions';
+import { compareRevisionGlbs, compareRevisionTotals } from './revision-comparison';
import { loadGlbReviewScene } from './views/glb';
import { listCameraSubjects } from './views/camera';
import { renderGLBInProcess as render } from './render';
@@ -266,3 +267,89 @@ test('hiding a part is a visibility change, and bounds count what draws', async
expect(result.before.bounds!.max[1]).toBeCloseTo(3.1, 6);
expect(result.after.bounds!.max[1]).toBeCloseTo(1, 6);
});
+
+/** One unit quad drawn four ways: the drawn world-space triangles are what count. */
+async function quads(
+ form: 'list' | 'strip' | 'flipped' | 'instanced' | 'hidden-extra',
+): Promise<Uint8Array> {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const accessor = (
+ type: 'VEC3' | 'SCALAR',
+ array: Float32Array<ArrayBuffer> | Uint16Array<ArrayBuffer>,
+ ) => doc.createAccessor().setType(type).setArray(array).setBuffer(buffer);
+ const scene = doc.createScene('Quads');
+ const corners = (x: number) => [x, 0, 0, x + 1, 0, 0, x, 1, 0, x + 1, 1, 0];
+ const listed = (x: number, order: number[]) =>
+ doc
+ .createPrimitive()
+ .setAttribute('POSITION', accessor('VEC3', new Float32Array(corners(x))))
+ .setIndices(accessor('SCALAR', new Uint16Array(order)));
+ if (form === 'strip') {
+ // Both quads baked into one strip each; strips alternate winding, as glTF defines.
+ const mesh = doc.createMesh();
+ for (const x of [1, 3])
+ mesh.addPrimitive(
+ doc
+ .createPrimitive()
+ .setMode(5)
+ .setAttribute('POSITION', accessor('VEC3', new Float32Array(corners(x)))),
+ );
+ scene.addChild(doc.createNode('Strip').setMesh(mesh));
+ } else if (form === 'instanced') {
+ const extension = doc.createExtension(EXTMeshGPUInstancing);
+ const mesh = doc.createMesh().addPrimitive(listed(0, [0, 1, 2, 2, 1, 3]));
+ scene.addChild(
+ doc
+ .createNode('Copies')
+ .setMesh(mesh)
+ .setExtension(
+ 'EXT_mesh_gpu_instancing',
+ extension
+ .createInstancedMesh()
+ .setAttribute('TRANSLATION', accessor('VEC3', new Float32Array([1, 0, 0, 3, 0, 0]))),
+ ),
+ );
+ } else {
+ // Two nodes, each a local quad at the origin moved into place by its translation.
+ for (const [index, x] of [3, 1].entries()) {
+ const order = form === 'flipped' && index === 0 ? [0, 2, 1, 2, 3, 1] : [1, 2, 0, 1, 3, 2];
+ scene.addChild(
+ doc
+ .createNode(`Quad${x}`)
+ .setTranslation([x, 0, 0])
+ .setMesh(doc.createMesh().addPrimitive(listed(0, order))),
+ );
+ }
+ if (form === 'hidden-extra') {
+ const extension = doc.createExtension(KHRNodeVisibility);
+ scene.addChild(
+ doc
+ .createNode('Hidden')
+ .setMesh(doc.createMesh().addPrimitive(listed(7, [0, 1, 2])))
+ .setExtension('KHR_node_visibility', extension.createVisibility().setVisible(false)),
+ );
+ }
+ }
+ return createGltfIO().writeBinary(doc);
+}
+
+test('geometry identity ignores node, primitive, mode, instancing and triangle order but not winding', async () => {
+ const list = await quads('list');
+ for (const form of ['strip', 'instanced', 'hidden-extra'] as const) {
+ const compared = await compareRevisionTotals(list, await quads(form));
+ expect(compared.geometryIdentical, form).toBe(true);
+ expect(compared.counts.triangles, form).toEqual({ before: 4, after: 4, delta: 0 });
+ expect(compared.boundsDelta, form).toEqual({ min: [0, 0, 0], max: [0, 0, 0], size: [0, 0, 0] });
+ }
+ const strip = await compareRevisionTotals(list, await quads('strip'));
+ expect(strip.counts.vertices).toEqual({ before: 8, after: 8, delta: 0 });
+ expect(strip.counts.drawCalls).toEqual({ before: 2, after: 2, delta: 0 });
+ // Neither revision has TEXCOORD_0, so their corners agree.
+ expect(strip.uvIdentical).toBe(true);
+ const flipped = await compareRevisionTotals(list, await quads('flipped'));
+ expect(flipped.geometryIdentical).toBe(false);
+ expect(flipped.uvIdentical).toBeUndefined();
+ const instanced = await compareRevisionTotals(list, await quads('instanced'));
+ expect(instanced.counts.drawCalls).toEqual({ before: 2, after: 1, delta: -1 });
+});
diff --git a/src/revision-comparison.ts b/src/revision-comparison.ts
index f891ccd2..f4fa1907 100644
--- a/src/revision-comparison.ts
+++ b/src/revision-comparison.ts
@@ -1,14 +1,16 @@
import {
type Accessor,
+ type Document,
type Material,
type Node,
type Primitive,
PropertyType,
} from '@gltf-transform/core';
-import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
-import { Box3, Matrix4, Vector3 } from 'three';
+import { ALL_EXTENSIONS, type InstancedMesh } from '@gltf-transform/extensions';
+import { Box3, Matrix4, Quaternion, Vector3 } from 'three';
import { createGltfIO, type Lod, MSFT_LOD } from './gltf-io';
-import { isHiddenGltfNode } from './metrics';
+import { collectGlbMetrics, isHiddenGltfNode } from './metrics';
+import { drawnSceneBounds } from './node-visibility';
type Bounds = { min: number[]; max: number[]; size: number[] } | null;
type Field = 'geometry' | 'material' | 'transform' | 'bounds' | 'visibility';
@@ -79,6 +81,272 @@ async function digest(bytes: Uint8Array) {
return `sha256:${[...hash].map((b) => b.toString(16).padStart(2, '0')).join('')}`;
}
+/** What one revision draws, counted the way render metrics count it. */
+export interface RevisionTotals {
+ triangles: number;
+ /** POSITION entries of every drawn primitive, once per placement and GPU instance. */
+ vertices: number;
+ drawCalls: number;
+ materials: number;
+ bounds: Bounds;
+ /** Content hash of the drawn world-space triangles; see `drawnGeometryDigests`. */
+ geometry: string;
+ /** The same triangles with the TEXCOORD_0 value at each corner. */
+ uv: string;
+}
+
+/** Placement matrices of a drawn mesh node: its world matrix, once per GPU instance. */
+function placements(node: Node): Matrix4[] {
+ const world = new Matrix4().fromArray(node.getWorldMatrix());
+ const instances = node.getExtension<InstancedMesh>('EXT_mesh_gpu_instancing');
+ if (!instances) return [world];
+ const translation = instances.getAttribute('TRANSLATION');
+ const rotation = instances.getAttribute('ROTATION');
+ const scale = instances.getAttribute('SCALE');
+ const count = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ return Array.from({ length: count }, (_, i) =>
+ world
+ .clone()
+ .multiply(
+ new Matrix4().compose(
+ new Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]),
+ new Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]),
+ new Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]),
+ ),
+ ),
+ );
+}
+
+/** Corner indices of a triangle-mode primitive as glTF orders them, or null for points/lines. */
+function triangleCorners(mode: number, count: number): number[] | null {
+ const corners: number[] = [];
+ if (mode === 4) for (let i = 0; i + 2 < count; i += 3) corners.push(i, i + 1, i + 2);
+ else if (mode === 5)
+ for (let i = 0; i + 2 < count; i++)
+ corners.push(...(i % 2 ? [i + 1, i, i + 2] : [i, i + 1, i + 2]));
+ else if (mode === 6) for (let i = 1; i + 1 < count; i++) corners.push(i, i + 1, 0);
+ else return null;
+ return corners;
+}
+
+/** Floats per triangle record: three corners of position (9), TEXCOORD_0 (6) and a UV flag. */
+const RECORD = 16;
+const exact = (value: number) => Math.fround(value) + 0; // float32, and -0 reads as 0
+
+function compareRecords(data: Float32Array, a: number, b: number) {
+ for (let k = 0; k < RECORD; k++) {
+ const d = data[a + k]! - data[b + k]!;
+ if (d) return d;
+ }
+ return 0;
+}
+
+/** Order two starting corners of one triangle: positions [0, 9), then UVs [9, 15). */
+function compareRotations(corner: Float32Array, r: number, s: number) {
+ for (const [offset, width] of [
+ [0, 3],
+ [9, 2],
+ ] as const)
+ for (let c = 0; c < 3; c++)
+ for (let k = 0; k < width; k++) {
+ const d =
+ corner[offset + ((c + r) % 3) * width + k]! - corner[offset + ((c + s) % 3) * width + k]!;
+ if (d) return d;
+ }
+ return 0;
+}
+
+/**
+ * Two content hashes of what a revision draws, independent of node, primitive, vertex and
+ * triangle order. Each drawn triangle is taken to world space (node world matrix and GPU
+ * instance, float64), each corner rounded to float32 exactly as glTF stores positions, then
+ * rotated (never reflected, so winding counts) to start at its smallest corner; the sorted
+ * triangles are hashed. No tolerance: equal means the same float32 world coordinates, so a
+ * merge that bakes transforms with different float rounding can read as a change, while one
+ * that keeps the same coordinates in fewer primitives reads as identical. Points and lines
+ * are hashed per primitive. The second hash adds TEXCOORD_0 at each corner. Normals, colours,
+ * skin weights and morph targets are not hashed; materials are counted separately.
+ */
+async function drawnGeometryDigests(doc: Document) {
+ const drawn: { primitive: Primitive; matrices: Matrix4[] }[] = [];
+ const visit = (node: Node): void => {
+ if (isHiddenGltfNode(node)) return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const matrices = placements(node);
+ for (const primitive of mesh.listPrimitives()) drawn.push({ primitive, matrices });
+ }
+ for (const child of node.listChildren()) visit(child);
+ };
+ for (const scene of doc.getRoot().listScenes())
+ for (const node of scene.listChildren()) visit(node);
+ let triangles = 0;
+ let vertices = 0;
+ for (const { primitive, matrices } of drawn) {
+ const position = primitive.getAttribute('POSITION');
+ const count = primitive.getIndices()?.getCount() ?? position?.getCount() ?? 0;
+ vertices += (position?.getCount() ?? 0) * matrices.length;
+ triangles += ((triangleCorners(primitive.getMode(), count)?.length ?? 0) / 3) * matrices.length;
+ // The per-node comparison's budget, counted the same way: one visit per triangle corner.
+ if (vertices > MAX_VERTICES || triangles * 3 > MAX_VERTICES)
+ throw new Error('Revision comparison exceeds 2,000,000 placed vertices.');
+ }
+ const data = new Float32Array(triangles * RECORD);
+ const others: string[] = [];
+ const point = new Vector3();
+ const element = [0, 0, 0];
+ const texcoord = [0, 0];
+ const corner = new Float32Array(15);
+ let written = 0;
+ for (const { primitive, matrices } of drawn) {
+ const position = primitive.getAttribute('POSITION');
+ if (!position) continue;
+ const uv = primitive.getAttribute('TEXCOORD_0');
+ const indices = primitive.getIndices();
+ const count = indices?.getCount() ?? position.getCount();
+ const corners = triangleCorners(primitive.getMode(), count);
+ const vertexAt = (i: number) => indices?.getScalar(i) ?? i;
+ for (const matrix of matrices) {
+ const world = (vertex: number) => {
+ position.getElement(vertex, element);
+ point.fromArray(element).applyMatrix4(matrix);
+ if (!Number.isFinite(point.x + point.y + point.z))
+ throw new Error('Revision comparison requires finite positions and valid indices.');
+ return point;
+ };
+ if (!corners) {
+ const sequence = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ const p = world(vertexAt(i));
+ sequence.set([exact(p.x), exact(p.y), exact(p.z)], i * 3);
+ }
+ others.push(`${primitive.getMode()}:${await digest(new Uint8Array(sequence.buffer))}`);
+ continue;
+ }
+ for (let t = 0; t < corners.length; t += 3) {
+ for (let c = 0; c < 3; c++) {
+ const vertex = vertexAt(corners[t + c]!);
+ const p = world(vertex);
+ corner[c * 3] = exact(p.x);
+ corner[c * 3 + 1] = exact(p.y);
+ corner[c * 3 + 2] = exact(p.z);
+ const value = uv ? uv.getElement(vertex, texcoord) : [0, 0];
+ corner[9 + c * 2] = exact(value[0]!);
+ corner[10 + c * 2] = exact(value[1]!);
+ }
+ // Start at the smallest corner sequence, positions first, then UVs.
+ let best = 0;
+ for (const r of [1, 2]) if (compareRotations(corner, r, best) < 0) best = r;
+ const at = written * RECORD;
+ for (let c = 0; c < 3; c++) {
+ const from = (c + best) % 3;
+ data.set(corner.subarray(from * 3, from * 3 + 3), at + c * 3);
+ data.set(corner.subarray(9 + from * 2, 11 + from * 2), at + 9 + c * 2);
+ }
+ data[at + 15] = uv ? 1 : 0;
+ written++;
+ }
+ }
+ }
+ const order = new Uint32Array(written).map((_, i) => i);
+ order.sort((a, b) => compareRecords(data, a * RECORD, b * RECORD));
+ const positions = new Float32Array(written * 9);
+ const sorted = new Float32Array(written * RECORD);
+ order.forEach((record, i) => {
+ positions.set(data.subarray(record * RECORD, record * RECORD + 9), i * 9);
+ sorted.set(data.subarray(record * RECORD, (record + 1) * RECORD), i * RECORD);
+ });
+ const tail = new TextEncoder().encode(`|${others.sort().join(',')}`);
+ const joined = (bytes: Float32Array) => {
+ const out = new Uint8Array(bytes.byteLength + tail.byteLength);
+ out.set(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));
+ out.set(tail, bytes.byteLength);
+ return out;
+ };
+ return {
+ vertices,
+ geometry: await digest(joined(positions)),
+ uv: await digest(joined(sorted)),
+ };
+}
+
+/** Render-metric counts, drawn bounds and geometry hashes of one revision's document. */
+export async function revisionTotals(doc: Document): Promise<RevisionTotals> {
+ const metrics = collectGlbMetrics(doc);
+ const { vertices, geometry, uv } = await drawnGeometryDigests(doc);
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ const drawnBounds = scene ? drawnSceneBounds(scene) : null;
+ const box =
+ drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite)
+ ? new Box3(new Vector3(...drawnBounds.min), new Vector3(...drawnBounds.max))
+ : new Box3();
+ return {
+ triangles: metrics.triangles,
+ vertices,
+ drawCalls: metrics.drawCalls,
+ materials: metrics.uniqueMaterials,
+ bounds: bounds(box),
+ geometry,
+ uv,
+ };
+}
+
+type Count = 'triangles' | 'vertices' | 'drawCalls' | 'materials';
+const COUNTS: Count[] = ['triangles', 'vertices', 'drawCalls', 'materials'];
+
+/** Each count before and after with its signed delta, and whether drawn geometry matches. */
+export function totalsDelta(before: RevisionTotals, after: RevisionTotals) {
+ const counts = Object.fromEntries(
+ COUNTS.map((key) => [
+ key,
+ { before: before[key], after: after[key], delta: after[key] - before[key] },
+ ]),
+ ) as Record<Count, { before: number; after: number; delta: number }>;
+ const geometryIdentical = before.geometry === after.geometry;
+ return {
+ counts,
+ geometryIdentical,
+ // Corners only correspond when the triangles do; a UV verdict on changed geometry
+ // would be a guess.
+ ...(geometryIdentical ? { uvIdentical: before.uv === after.uv } : {}),
+ boundsDelta: boundsDelta(before.bounds, after.bounds),
+ };
+}
+
+function boundsDelta(before: Bounds, after: Bounds) {
+ if (!before || !after) return null;
+ const minus = (a: number[], b: number[]) => a.map((value, i) => value - b[i]!);
+ return {
+ min: minus(after.min, before.min),
+ max: minus(after.max, before.max),
+ size: minus(after.size, before.size),
+ };
+}
+
+/** Read a saved or evaluated GLB for counting; self-contained only, never fetching. */
+async function readComparisonDocument(bytes: Uint8Array) {
+ if (bytes.byteLength > MAX_GLB_BYTES) throw new Error('Revision comparison GLB exceeds 64 MiB.');
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(bytes);
+ if (
+ json.json.buffers?.some((b) => b.uri && !json.resources[b.uri]) ||
+ json.json.images?.some((i) => i.uri)
+ )
+ throw new Error('Revision comparison requires embedded GLB resources.');
+ return io.readJSON(json);
+}
+
+/**
+ * The counts, bounds and geometry identity of a child revision against its parent, without
+ * the per-node match `compareRevisionGlbs` needs: any GLB a save accepts can be counted,
+ * including repeated sibling names.
+ */
+export async function compareRevisionTotals(parent: Uint8Array, child: Uint8Array) {
+ const before = await revisionTotals(await readComparisonDocument(parent));
+ const after = await revisionTotals(await readComparisonDocument(child));
+ return { before, after, ...totalsDelta(before, after) };
+}
+
async function snapshot(bytes: Uint8Array) {
if (bytes.byteLength > MAX_GLB_BYTES) throw new Error('Revision comparison GLB exceeds 64 MiB.');
const io = createGltfIO();
@@ -224,7 +492,15 @@ async function snapshot(bytes: Uint8Array) {
});
}
}
- return { parts, animation, scenePath, bounds: bounds(box), glbSha256: await digest(bytes) };
+ return {
+ parts,
+ animation,
+ scenePath,
+ bounds: bounds(box),
+ // Counted on the same document; the bounds are the ones this comparison reports.
+ totals: { ...(await revisionTotals(doc)), bounds: bounds(box) },
+ glbSha256: await digest(bytes),
+ };
}
function accessorEqual(a: Accessor | null, b: Accessor | null) {
@@ -389,7 +665,7 @@ export async function compareRevisionGlbs(
return {
version: 'kiln.revision-comparison.v1' as const,
scope:
- 'Exact exported static mesh data and rest transforms; named hierarchy paths. MSFT_lod lower levels are compared at the path they take beside LOD0, and bounds are LOD0 only. A KHR_node_visibility flag is compared as visibility; the bounds of a part are where it draws when shown, and the bounds of its ancestors count only what draws. Animation channels are reported separately. Metadata (including LOD switch thresholds), visual equivalence, intent and physical fit are not assessed.',
+ 'Exact exported static mesh data and rest transforms; named hierarchy paths. MSFT_lod lower levels are compared at the path they take beside LOD0, and bounds are LOD0 only. A KHR_node_visibility flag is compared as visibility; the bounds of a part are where it draws when shown, and the bounds of its ancestors count only what draws. Animation channels are reported separately. counts are the drawn triangles, vertices, draw calls and materials render metrics report; geometryIdentical compares the sorted drawn world-space triangles at float32 precision, so node, primitive and vertex order do not count; uvIdentical adds TEXCOORD_0 when the geometry is identical. Normals, colours, skin weights and morph targets are not in the geometry hash. Metadata (including LOD switch thresholds), visual equivalence, intent and physical fit are not assessed.',
animation: {
scope:
'Exact exported channel target, interpolation, key times and values, matched by clip name and node path. Renames are add/remove. Equivalent motions may have different key data; metadata and playback behavior are not assessed.',
@@ -406,6 +682,7 @@ export async function compareRevisionGlbs(
},
after: { glbSha256: current.glbSha256, bounds: current.bounds, scenePath: current.scenePath },
summary,
+ ...totalsDelta(previous.totals, current.totals),
...(subtrees
? {
subtrees: subtrees.map(({ key, ...subtree }) => ({
diff --git a/src/tools/__tests__/save-comparison.test.ts b/src/tools/__tests__/save-comparison.test.ts
new file mode 100644
index 00000000..ca6141bf
--- /dev/null
+++ b/src/tools/__tests__/save-comparison.test.ts
@@ -0,0 +1,196 @@
+/**
+ * Issue #245: a child save reports what changed against its parent revision.
+ *
+ * The Holodeck dogfood (October 2026) merged four frond primitives into one. Positions,
+ * indices and UVs stayed byte-identical, yet the only signal was a part `changed`; the agent
+ * proved equality with its own GLB comparison. A save with `parentRevision` now carries the
+ * triangle, vertex, draw and material counts of both revisions, the bounds delta and whether
+ * the drawn world-space triangles are the same.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Document } from '@gltf-transform/core';
+import { FileAssetLibrary } from '../../assets-node';
+import { createGltfIO } from '../../gltf-io';
+import { trustedInProcessEvaluatorPortV2 } from '../../evaluator';
+import { MemoryProgramStore, retainProgram } from '../../program-store';
+import { createKilnProgramToolRegistry, type KilnInspectResult } from '../registry';
+
+/** Four fronds, one part each: four nodes, four draws, one shared material. */
+const PARENT =
+ "const meta = { name: 'Fronds', category: 'prop' };\n" +
+ 'function build() {\n' +
+ " const root = createRoot('Fronds');\n" +
+ " const leaf = gameMaterial('#3a7a3a');\n" +
+ " for (let i = 0; i < 4; i++) createPart('Frond' + i, boxGeo(0.25, 1, 0.05), leaf, { parent: root, position: [i * 0.5, 0.5, 0] });\n" +
+ ' return root;\n' +
+ '}\n';
+
+/** The same four fronds merged into one primitive: the geometry is translated, not changed. */
+const merged = (shift = 0, uvShift = 0) =>
+ "const meta = { name: 'Fronds', category: 'prop' };\n" +
+ 'function build() {\n' +
+ " const root = createRoot('Fronds');\n" +
+ " const leaf = gameMaterial('#3a7a3a');\n" +
+ ' const parts = [3, 1, 2, 0].map((i) => boxGeo(0.25, 1, 0.05).clone().translate(i * 0.5, 0.5, 0));\n' +
+ ` parts[0].attributes.position.setY(0, parts[0].attributes.position.getY(0) + ${shift});\n` +
+ ` parts[0].attributes.uv.setX(0, parts[0].attributes.uv.getX(0) + ${uvShift});\n` +
+ " const names = ['position', 'normal', 'uv'];\n" +
+ ' const merged = new THREE.BufferGeometry();\n' +
+ ' for (const name of names) {\n' +
+ ' const size = parts[0].attributes[name].itemSize;\n' +
+ ' merged.setAttribute(name, new THREE.Float32BufferAttribute(parts.flatMap((p) => [...p.attributes[name].array]), size));\n' +
+ ' }\n' +
+ ' const index = [];\n' +
+ ' let base = 0;\n' +
+ ' for (const p of parts) { for (const v of p.index.array) index.push(v + base); base += p.attributes.position.count; }\n' +
+ ' merged.setIndex(index);\n' +
+ " createPart('Fronds', merged, leaf, { parent: root });\n" +
+ ' return root;\n' +
+ '}\n';
+
+let root: string;
+let registry: ReturnType<typeof createKilnProgramToolRegistry>;
+let programStore: MemoryProgramStore;
+
+beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'kiln-save-comparison-'));
+ programStore = new MemoryProgramStore();
+ registry = createKilnProgramToolRegistry({
+ evaluatorPort: trustedInProcessEvaluatorPortV2,
+ programStore,
+ assetLibrary: new FileAssetLibrary({ project: root }),
+ });
+});
+
+afterAll(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+
+const tool = (name: string) => registry.find((definition) => definition.name === name)!;
+
+interface SaveResult {
+ asset: { assetId: string; revisionId: string };
+ comparison?: Record<string, unknown> & {
+ counts?: Record<string, { parent: number; child: number; delta: number }>;
+ bounds?: { parent: unknown; child: unknown; delta: { size: number[] } | null };
+ geometryIdentical?: boolean;
+ uvIdentical?: boolean;
+ };
+}
+
+async function saveChild(code: string) {
+ const parent = (await tool('kiln_save').run({
+ programRef: await retainProgram(programStore, PARENT),
+ name: 'Fronds',
+ })) as SaveResult;
+ const child = (await tool('kiln_save').run({
+ programRef: await retainProgram(programStore, code),
+ name: 'Fronds',
+ assetId: parent.asset.assetId,
+ parentRevision: parent.asset.revisionId,
+ })) as SaveResult;
+ return { parent, child };
+}
+
+test('a save without a parent carries no comparison', async () => {
+ const { parent } = await saveChild(PARENT);
+ expect(parent.comparison).toBeUndefined();
+}, 60_000);
+
+test('a merge-only child save reports equal geometry with fewer draws', async () => {
+ const { child } = await saveChild(merged());
+ const comparison = child.comparison!;
+ expect(comparison).toBeDefined();
+ expect(comparison.counts).toEqual({
+ triangles: { parent: 48, child: 48, delta: 0 },
+ vertices: { parent: 96, child: 96, delta: 0 },
+ drawCalls: { parent: 4, child: 1, delta: -3 },
+ materials: { parent: 1, child: 1, delta: 0 },
+ });
+ expect(comparison.bounds!.delta!.size).toEqual([0, 0, 0]);
+ expect(comparison.geometryIdentical).toBe(true);
+ expect(comparison.uvIdentical).toBe(true);
+ // 349 characters when written: counts, not per-node pages.
+ expect(JSON.stringify(comparison).length).toBeLessThanOrEqual(500);
+}, 60_000);
+
+test('a moved vertex reads as a geometry change', async () => {
+ const { child } = await saveChild(merged(0.125));
+ expect(child.comparison!.geometryIdentical).toBe(false);
+ expect(child.comparison!.counts!.triangles).toEqual({ parent: 48, child: 48, delta: 0 });
+}, 60_000);
+
+test('equal geometry with a changed UV corner reads as a UV change only', async () => {
+ const { child } = await saveChild(merged(0, 0.25));
+ expect(child.comparison!.geometryIdentical).toBe(true);
+ expect(child.comparison!.uvIdentical).toBe(false);
+}, 60_000);
+
+test('a parent that cannot be compared leaves the comparison unavailable, not the save', async () => {
+ // A binary-only parent whose one triangle names a vertex its positions do not have.
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const primitive = doc
+ .createPrimitive()
+ .setAttribute(
+ 'POSITION',
+ doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]))
+ .setBuffer(buffer),
+ )
+ .setIndices(
+ doc
+ .createAccessor()
+ .setType('SCALAR')
+ .setArray(new Uint16Array([0, 1, 5]))
+ .setBuffer(buffer),
+ );
+ doc
+ .createScene()
+ .addChild(doc.createNode('Broken').setMesh(doc.createMesh().addPrimitive(primitive)));
+ // Its build record is a real save's, so only the GLB stands in the way.
+ const library = new FileAssetLibrary({ project: root });
+ const { parent: saved } = await saveChild(PARENT);
+ const { manifest } = await library.read('project', saved.asset.assetId, saved.asset.revisionId);
+ const parent = await library.save('project', {
+ name: 'Fronds',
+ glb: await createGltfIO().writeBinary(doc),
+ build: manifest.build!,
+ });
+ const child = (await tool('kiln_save').run({
+ programRef: await retainProgram(programStore, merged()),
+ name: 'Fronds',
+ assetId: parent.assetId,
+ parentRevision: parent.revisionId,
+ })) as SaveResult & { ok: boolean };
+ expect(child.ok).toBe(true);
+ expect(child.comparison).toEqual({
+ unavailable:
+ 'Parent comparison unavailable: Revision comparison requires finite positions and valid indices.',
+ });
+}, 60_000);
+
+test('kiln_inspect compare carries the same counts and geometry identity', async () => {
+ const before = await retainProgram(programStore, PARENT);
+ const output = (await tool('kiln_inspect').run({
+ code: merged(),
+ compare: { programRef: before },
+ image: false,
+ })) as KilnInspectResult;
+ expect(output.ok).toBe(true);
+ const comparison = output.comparison! as unknown as Record<string, unknown>;
+ expect(comparison['counts']).toEqual({
+ triangles: { before: 48, after: 48, delta: 0 },
+ vertices: { before: 96, after: 96, delta: 0 },
+ drawCalls: { before: 4, after: 1, delta: -3 },
+ materials: { before: 1, after: 1, delta: 0 },
+ });
+ expect(comparison['geometryIdentical']).toBe(true);
+ expect(comparison['uvIdentical']).toBe(true);
+ expect((comparison['boundsDelta'] as { size: number[] }).size).toEqual([0, 0, 0]);
+}, 60_000);
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 77bee8e5..5fc4d510 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -35,6 +35,7 @@ import {
captureRecordInput,
} from './capture-input';
import {
+ COMPACT_DECIMALS,
compactEditResult,
compactReviewResult,
type DetailOptions,
@@ -2804,6 +2805,50 @@ export async function newestRevision(
return newest[0]!.revisionId;
}
+const roundCompact = (value: number) => Number(value.toFixed(COMPACT_DECIMALS));
+
+/**
+ * What a child save changed against its parent revision (#245): triangle, vertex, draw and
+ * material counts as parent, child and delta, the drawn bounds sizes and delta, and whether
+ * the drawn world-space triangles are identical whatever their node, primitive or vertex
+ * order. Per-node changes stay with `kiln_inspect` compare; a silhouette or image delta stays
+ * a review question. A comparison that cannot be made never fails the save.
+ */
+async function parentRevisionComparison(
+ parent: Uint8Array | undefined,
+ child: Uint8Array,
+): Promise<Record<string, unknown>> {
+ try {
+ if (!parent) throw new Error('the parent revision has no asset.glb.');
+ const { compareRevisionTotals } = await import('../revision-comparison');
+ const compared = await compareRevisionTotals(parent, child);
+ const size = (bounds: typeof compared.before.bounds) => bounds?.size.map(roundCompact) ?? null;
+ return {
+ counts: Object.fromEntries(
+ Object.entries(compared.counts).map(([key, count]) => [
+ key,
+ { parent: count.before, child: count.after, delta: count.delta },
+ ]),
+ ),
+ bounds: {
+ parent: size(compared.before.bounds),
+ child: size(compared.after.bounds),
+ delta: compared.boundsDelta && {
+ min: compared.boundsDelta.min.map(roundCompact),
+ max: compared.boundsDelta.max.map(roundCompact),
+ size: compared.boundsDelta.size.map(roundCompact),
+ },
+ },
+ geometryIdentical: compared.geometryIdentical,
+ ...(compared.uvIdentical === undefined ? {} : { uvIdentical: compared.uvIdentical }),
+ };
+ } catch (error) {
+ return {
+ unavailable: `Parent comparison unavailable: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
/** Build one current-policy revision for ordinary save or explicit migration. */
export async function buildProgramAssetDraft(
code: string,
@@ -2997,7 +3042,7 @@ export function createKilnAssetDefs(
{
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.',
+ '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, and the result comparison gives triangle, vertex, draw and material deltas, the bounds delta and geometryIdentical against the parent. Returns downloadable resources; draft renders never populate collections.',
inputSchema: saveInput,
run: async (raw) => {
const { backdrop, ...input } = saveInput.parse(raw);
@@ -3007,22 +3052,26 @@ export function createKilnAssetDefs(
...context,
requirements: activeRequirements.binding,
};
+ let parent: import('../assets').AssetRecord | undefined;
if (input.assetId && input.parentRevision) {
- const previous = await readSavedRevision(
+ parent = await readSavedRevision(
target,
input.collection,
input.assetId,
input.parentRevision,
listCall(input.collection),
);
- assertSavedRequirementsAuthorized(previous.manifest, activeRequirements);
+ assertSavedRequirementsAuthorized(parent.manifest, activeRequirements);
}
const code = await context.programStore!.get(input.programRef);
- const asset = await target.save(input.collection, {
- ...input,
- ...(await buildProgramAssetDraft(code, callContext, backdrop)),
- });
- return links(input.collection, asset);
+ const draft = await buildProgramAssetDraft(code, callContext, backdrop);
+ const asset = await target.save(input.collection, { ...input, ...draft });
+ return {
+ ...(await links(input.collection, asset)),
+ ...(parent
+ ? { comparison: await parentRevisionComparison(parent.files['asset.glb'], draft.glb) }
+ : {}),
+ };
},
},
{
diff --git a/src/tools/review-detail.ts b/src/tools/review-detail.ts
index 8e24ca16..ff68ba8f 100644
--- a/src/tools/review-detail.ts
+++ b/src/tools/review-detail.ts
@@ -637,7 +637,8 @@ export const LEAN_DIFF = 2000;
export const COMPACT_COMPARISON_CHANGES = 12;
/**
- * A static comparison as the counts, the artifact before and after, and each
+ * A static comparison as the node and draw counts, whether the drawn geometry is identical,
+ * the bounds delta, the artifact before and after, and each
* change as its path, status and changed fields. The bounds of every change and
* the scope prose belong to `full`: they were 7,191 of the 20,069 characters of
* a live compact edit and 32,443 of a 38,952-character compact kiln_inspect
@@ -646,7 +647,19 @@ export const COMPACT_COMPARISON_CHANGES = 12;
*/
function compactComparison(comparison: Json, hint: string, limit?: number): Json {
const out: Json = {};
- for (const key of ['programRef', 'version', 'units', 'summary', 'before', 'after', 'subtrees'])
+ for (const key of [
+ 'programRef',
+ 'version',
+ 'units',
+ 'summary',
+ 'counts',
+ 'geometryIdentical',
+ 'uvIdentical',
+ 'boundsDelta',
+ 'before',
+ 'after',
+ 'subtrees',
+ ])
if (comparison[key] !== undefined) out[key] = comparison[key];
if (isRecord(comparison.animation)) {
const { scope: _scope, ...animation } = comparison.animation;