Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
Record a material revision's parent (#310) (#319)
Matthew Kissinger0468a19bea96
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f2b772e0..8c79276a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,14 @@ does not publish a package.was reported as invalid input. [Large assets](docs/runtime.md#large-assets) gives the measuredsizes and the supported routes.+- Material revisions can record their parent (#310). `parentRevision` on a V1 or V2 draft, or+ `kiln material procedural --parent <sha256:revision>`, must name a saved revision of the same+ `materialId`; `get`, `list` and the `kiln.material-maps.v1` sidecar report it, and it survives+ export and import. It is optional, and the key is omitted when absent, so existing records keep+ their revision ids. A record that carries it is refused by an engine older than this one, whose+ manifest schema is strict.+||||||| cde4dfe+## 1.6.0 (2026-10-27)- `kiln_export_to` takes `textures: 'manifest'`, so an MCP author can act on the texturediff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 24d81e52..bc014081 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -5402,6 +5402,7 @@ var init_material_library = __esm(() => {schemaVersion: z5.literal(1),materialId: materialLibraryIdSchema,revisionId: materialLibraryHashSchema,+ parentRevision: materialLibraryHashSchema.optional(),name: z5.string().min(1).max(200),tags: z5.array(z5.string().min(1).max(80)).max(30),tileable: z5.boolean(),@@ -5436,6 +5437,7 @@ var init_material_library = __esm(() => {}).strict();proceduralMaterialDraftSchema = z5.object({materialId: materialLibraryIdSchema,+ parentRevision: materialLibraryHashSchema.optional().describe("The saved revision of this materialId that this one replaces."),name: z5.string().min(1).max(200),tags: z5.array(z5.string().min(1).max(80)).max(30).optional(),tileable: z5.boolean(),@@ -11951,6 +11953,7 @@ async function createMaterialRecordV1(draft) {assertMaterialJson(draft, true);exactKeys(draft, ["materialId",+ "parentRevision","name","tags","tileable",@@ -12036,6 +12039,7 @@ async function createMaterialRecordV1(draft) {schemaVersion: 1,materialId: draft.materialId,revisionId: `sha256:${"0".repeat(64)}`,+ ...draft.parentRevision ? { parentRevision: draft.parentRevision } : {},name: draft.name,tags: draft.tags ?? [],tileable: draft.tileable,@@ -12541,6 +12545,7 @@ async function createMaterialRecordV2(draft, options) {exactKeys(draft, ["schemaVersion","materialId",+ "parentRevision","name","tags","tileable",@@ -47622,18 +47627,33 @@ import { z as z18 } from "zod";init_material_library();init_material_library_node();init_texture_atlas_contract();+async function assertMaterialParent(draft, library) {+ if (!draft.parentRevision)+ return;+ try {+ if (library.readManifest)+ await library.readManifest(draft.materialId, draft.parentRevision);+ else+ await library.read(draft.materialId, draft.parentRevision);+ } catch (error) {+ if (error.code !== "ENOENT")+ throw error;+ throw new Error(`parentRevision ${draft.parentRevision} is not a saved revision of material ${draft.materialId}. A parent must be an existing revision of the same materialId; list materials to see their revision IDs.`);+ }+}async function createProceduralMaterialRecord(value, library) {assertMaterialJson(value);if (new TextEncoder().encode(JSON.stringify(value)).length > MATERIAL_LIBRARY_LIMITS.maxManifestBytes)throw new Error("Material draft exceeds size limit");if (!value || typeof value !== "object" || Array.isArray(value))throw new Error("Material draft must be a JSON object");- if (!Object.hasOwn(value, "schemaVersion"))- return {- record: await createMaterialRecordV1(proceduralMaterialDraftSchema.parse(value)),- dependencies: []- };+ if (!Object.hasOwn(value, "schemaVersion")) {+ const draft = proceduralMaterialDraftSchema.parse(value);+ await assertMaterialParent(draft, library);+ return { record: await createMaterialRecordV1(draft), dependencies: [] };+ }const draft = proceduralMaterialDraftV2Schema.parse(value);+ await assertMaterialParent(draft, library);const pins = new Map;for (const map of draft.maps) {if (!map.atlas)@@ -48250,6 +48270,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {materials: records.filter((item) => !input.tag || item.tags.includes(input.tag)).map((item) => ({materialId: item.materialId,revisionId: item.revisionId,+ ...item.parentRevision ? { parentRevision: item.parentRevision } : {},name: item.name,tags: item.tags,tileable: item.tileable,diff --git a/dist/build.json b/dist/build.jsonindex 52fe46f2..571c18f0 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:4ff999db48a5006d64f0096ee79b20cde90f3b7f06b60d7b78c9dc3df5a003fe"+ "bundleHash": "sha256:967e226a32b2f5d0ae2ac29ca0c5643c95557f8549d5aef4dc4f637354e2dc2f"},"agent-run": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:96990900a3c234510266ede086ac3ebf6a45c51c81d96c4b84b03eec22f4b65e"+ "bundleHash": "sha256:8068bed2f4ff84cc3b45d6fbc1b1216414d26c138f3ce412422dd310d0f20aac"},"agent-providers": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:4c8f00a36bcc57be3ff7afb3df03646ffebdc355e7bb42478112aa2ac4c1319f"},"cli": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:83ff97904661d473bc277f71559b8d7b2249bd4e44e8cea9521cdb3284057e0f"+ "bundleHash": "sha256:13b8c3cf6cc9fafeec5507fd2c25c2bcbcd313bae3dabd765657d9e6de2e1c0d"},"engine": {- "identity": "sha256:0268860fa83feaa1e05d48b00e3728e179dc2b918ee9d9020fb6859420422d9a",+ "identity": "sha256:882ffe5778be825607fabf93b4a3737dbeab95994b459d7f2a34f007266eb21d","engineVersion": "1.6.0","toolchain": "[email protected]",- "sourceHash": "3d9e1479522e3e16c943648452671998735be0e538724ac38b0b89044a832e49",+ "sourceHash": "241ce0a2373f40a575d9adc1f859760a2a1b5ecdbe939ef260cb2c2c5d4d9089","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:0ee07bed9654201eb4071a9bc0c5d9c815f0c7420acf2aa8ca3faf162e7a48aa"+ "bundleHash": "sha256:2800fce549841e9f2105a78e5fdf1ca992ed815c1d747c1301b99361c9b7a9fb"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex cd15345e..a12dedaf 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -4643,6 +4643,7 @@ var init_material_library = __esm(() => {schemaVersion: z5.literal(1),materialId: materialLibraryIdSchema,revisionId: materialLibraryHashSchema,+ parentRevision: materialLibraryHashSchema.optional(),name: z5.string().min(1).max(200),tags: z5.array(z5.string().min(1).max(80)).max(30),tileable: z5.boolean(),@@ -4677,6 +4678,7 @@ var init_material_library = __esm(() => {}).strict();proceduralMaterialDraftSchema = z5.object({materialId: materialLibraryIdSchema,+ parentRevision: materialLibraryHashSchema.optional().describe("The saved revision of this materialId that this one replaces."),name: z5.string().min(1).max(200),tags: z5.array(z5.string().min(1).max(80)).max(30).optional(),tileable: z5.boolean(),@@ -40955,6 +40957,7 @@ async function createMaterialMapExport(record, options) {material: {materialId: id,revisionId: manifest.revisionId,+ ...manifest.parentRevision ? { parentRevision: manifest.parentRevision } : {},name: manifest.name,tileable: manifest.tileable,...manifest.physicalSizeMeters ? { physicalSizeMeters: { ...manifest.physicalSizeMeters } } : {},@@ -41074,6 +41077,7 @@ async function createMaterialRecordV1(draft) {assertMaterialJson(draft, true);exactKeys(draft, ["materialId",+ "parentRevision","name","tags","tileable",@@ -41159,6 +41163,7 @@ async function createMaterialRecordV1(draft) {schemaVersion: 1,materialId: draft.materialId,revisionId: `sha256:${"0".repeat(64)}`,+ ...draft.parentRevision ? { parentRevision: draft.parentRevision } : {},name: draft.name,tags: draft.tags ?? [],tileable: draft.tileable,@@ -41800,6 +41805,7 @@ async function createMaterialRecordV2(draft, options) {exactKeys(draft, ["schemaVersion","materialId",+ "parentRevision","name","tags","tileable",@@ -51611,18 +51617,33 @@ async function listAssetCatalog(library) {}// src/material-authoring-node.ts+async function assertMaterialParent(draft, library) {+ if (!draft.parentRevision)+ return;+ try {+ if (library.readManifest)+ await library.readManifest(draft.materialId, draft.parentRevision);+ else+ await library.read(draft.materialId, draft.parentRevision);+ } catch (error) {+ if (error.code !== "ENOENT")+ throw error;+ throw new Error(`parentRevision ${draft.parentRevision} is not a saved revision of material ${draft.materialId}. A parent must be an existing revision of the same materialId; list materials to see their revision IDs.`);+ }+}async function createProceduralMaterialRecord(value, library) {assertMaterialJson(value);if (new TextEncoder().encode(JSON.stringify(value)).length > MATERIAL_LIBRARY_LIMITS.maxManifestBytes)throw new Error("Material draft exceeds size limit");if (!value || typeof value !== "object" || Array.isArray(value))throw new Error("Material draft must be a JSON object");- if (!Object.hasOwn(value, "schemaVersion"))- return {- record: await createMaterialRecordV1(proceduralMaterialDraftSchema.parse(value)),- dependencies: []- };+ if (!Object.hasOwn(value, "schemaVersion")) {+ const draft = proceduralMaterialDraftSchema.parse(value);+ await assertMaterialParent(draft, library);+ return { record: await createMaterialRecordV1(draft), dependencies: [] };+ }const draft = proceduralMaterialDraftV2Schema.parse(value);+ await assertMaterialParent(draft, library);const pins = new Map;for (const map of draft.maps) {if (!map.atlas)@@ -52185,6 +52206,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {materials: records.filter((item) => !input.tag || item.tags.includes(input.tag)).map((item) => ({materialId: item.materialId,revisionId: item.revisionId,+ ...item.parentRevision ? { parentRevision: item.parentRevision } : {},name: item.name,tags: item.tags,tileable: item.tileable,@@ -57759,6 +57781,14 @@ async function inputFile(path, limit) {async function jsonFile(path, limit) {return JSON.parse((await inputFile(path, limit)).toString("utf8").replace(/^\uFEFF/, ""));}+function withParentFlag(draft, parent) {+ if (!parent || !draft || typeof draft !== "object" || Array.isArray(draft))+ return draft;+ const stated = draft.parentRevision;+ if (stated !== undefined && stated !== parent)+ throw new Error(`--parent ${parent} disagrees with the draft's parentRevision ${String(stated)}`);+ return { ...draft, parentRevision: parent };+}async function exportMaterialMapsCommand(materials, positional, flags) {const integer = (name) => {const value = flags[name];@@ -57837,7 +57867,7 @@ async function projectMain(argv) {"material:presets": ["tag"],"material:create-preset": ["file"],"material:get": [],- "material:procedural": ["file"],+ "material:procedural": ["file", "parent"],"material:import": ["file"],"material:export": ["out", "maps", "size", "repeat", "tiles", "render"]};@@ -57967,7 +57997,7 @@ async function projectMain(argv) {throw new Error(`material ${action} requires --file`);const input = await jsonFile(flags.file, action === "procedural" ? MATERIAL_LIBRARY_LIMITS.maxManifestBytes : 24 * 1024 * 1024);if (action === "procedural") {- const { record, dependencies } = await createProceduralMaterialRecord(input, materials);+ const { record, dependencies } = await createProceduralMaterialRecord(withParentFlag(input, flags.parent), materials);output = {materials: await materials.import([record], dependencies.length ? { materials: dependencies } : undefined)};@@ -57992,7 +58022,7 @@ MATERIALSkiln material create-preset --file <preset-options.json>kiln material listkiln material get <id> <sha256:revision>- kiln material procedural --file <procedural-material-draft.json>+ kiln material procedural --file <procedural-material-draft.json> [--parent <sha256:revision>]kiln material import --file <portable-material-payload.json>kiln material export <id> <sha256:revision> --out <portable-material-payload.json>kiln material export <id> <sha256:revision> --maps <dir> --size <px> [--repeat <metres>]diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 2d26cd54..e5f71392 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -33119,6 +33119,7 @@ var init_material_library = __esm(() => {schemaVersion: z6.literal(1),materialId: materialLibraryIdSchema,revisionId: materialLibraryHashSchema,+ parentRevision: materialLibraryHashSchema.optional(),name: z6.string().min(1).max(200),tags: z6.array(z6.string().min(1).max(80)).max(30),tileable: z6.boolean(),@@ -33153,6 +33154,7 @@ var init_material_library = __esm(() => {}).strict();proceduralMaterialDraftSchema = z6.object({materialId: materialLibraryIdSchema,+ parentRevision: materialLibraryHashSchema.optional().describe("The saved revision of this materialId that this one replaces."),name: z6.string().min(1).max(200),tags: z6.array(z6.string().min(1).max(80)).max(30).optional(),tileable: z6.boolean(),diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 2ac744f3..bb50dcc3 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -2110,6 +2110,7 @@ var init_material_library = __esm(() => {schemaVersion: z2.literal(1),materialId: materialLibraryIdSchema,revisionId: materialLibraryHashSchema,+ parentRevision: materialLibraryHashSchema.optional(),name: z2.string().min(1).max(200),tags: z2.array(z2.string().min(1).max(80)).max(30),tileable: z2.boolean(),@@ -2144,6 +2145,7 @@ var init_material_library = __esm(() => {}).strict();proceduralMaterialDraftSchema = z2.object({materialId: materialLibraryIdSchema,+ parentRevision: materialLibraryHashSchema.optional().describe("The saved revision of this materialId that this one replaces."),name: z2.string().min(1).max(200),tags: z2.array(z2.string().min(1).max(80)).max(30).optional(),tileable: z2.boolean(),@@ -5950,6 +5952,7 @@ async function createMaterialRecordV1(draft) {assertMaterialJson(draft, true);exactKeys(draft, ["materialId",+ "parentRevision","name","tags","tileable",@@ -6035,6 +6038,7 @@ async function createMaterialRecordV1(draft) {schemaVersion: 1,materialId: draft.materialId,revisionId: `sha256:${"0".repeat(64)}`,+ ...draft.parentRevision ? { parentRevision: draft.parentRevision } : {},name: draft.name,tags: draft.tags ?? [],tileable: draft.tileable,@@ -6676,6 +6680,7 @@ async function createMaterialRecordV2(draft, options) {exactKeys(draft, ["schemaVersion","materialId",+ "parentRevision","name","tags","tileable",@@ -51929,18 +51934,33 @@ import { z as z20 } from "zod";init_material_library();init_material_library_node();init_texture_atlas_contract();+async function assertMaterialParent(draft, library) {+ if (!draft.parentRevision)+ return;+ try {+ if (library.readManifest)+ await library.readManifest(draft.materialId, draft.parentRevision);+ else+ await library.read(draft.materialId, draft.parentRevision);+ } catch (error) {+ if (error.code !== "ENOENT")+ throw error;+ throw new Error(`parentRevision ${draft.parentRevision} is not a saved revision of material ${draft.materialId}. A parent must be an existing revision of the same materialId; list materials to see their revision IDs.`);+ }+}async function createProceduralMaterialRecord(value, library) {assertMaterialJson(value);if (new TextEncoder().encode(JSON.stringify(value)).length > MATERIAL_LIBRARY_LIMITS.maxManifestBytes)throw new Error("Material draft exceeds size limit");if (!value || typeof value !== "object" || Array.isArray(value))throw new Error("Material draft must be a JSON object");- if (!Object.hasOwn(value, "schemaVersion"))- return {- record: await createMaterialRecordV1(proceduralMaterialDraftSchema.parse(value)),- dependencies: []- };+ if (!Object.hasOwn(value, "schemaVersion")) {+ const draft = proceduralMaterialDraftSchema.parse(value);+ await assertMaterialParent(draft, library);+ return { record: await createMaterialRecordV1(draft), dependencies: [] };+ }const draft = proceduralMaterialDraftV2Schema.parse(value);+ await assertMaterialParent(draft, library);const pins = new Map;for (const map of draft.maps) {if (!map.atlas)@@ -52557,6 +52577,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {materials: records.filter((item) => !input.tag || item.tags.includes(input.tag)).map((item) => ({materialId: item.materialId,revisionId: item.revisionId,+ ...item.parentRevision ? { parentRevision: item.parentRevision } : {},name: item.name,tags: item.tags,tileable: item.tileable,diff --git a/docs/material-library.md b/docs/material-library.mdindex 48e420cf..55ac9957 100644--- a/docs/material-library.md+++ b/docs/material-library.md@@ -69,6 +69,14 @@ to MCP `create-procedural`. These paths need no imports from internal `dist/` fior extra TypeScript loader. The public host APIs below are for a configured TypeScripttoolchain; ordinary Node cannot directly execute TypeScript inside `node_modules`.+A new revision of an existing material can name the revision it replaces: `parentRevision` in the+draft, or `material procedural --file draft.json --parent sha256:...`. It must be a saved revision of+the same `materialId`. The field is optional, and the revision hash covers it when it is present, so+a record without it keeps its id and the same draft with and without a parent are two revisions.+`get`, `list` and the `material export --maps` sidecar report it. It survives export and import, and+import does not require the parent to be in the receiving library. Revisions have no other order, so+this is the only statement that one supersedes another.+`list` returns compact summaries and accepts a `tag`. `get` requires `materialId` and `revisionId`and returns provenance plus a code-ready `portableSpec`. `create-procedural` accepts an editabledraft using the same bounded layer recipes as the existing procedural compiler. Opt-indiff --git a/src/material-authoring-node.ts b/src/material-authoring-node.tsindex 5bb16dde..0e5dd6bd 100644--- a/src/material-authoring-node.ts+++ b/src/material-authoring-node.ts@@ -16,6 +16,26 @@ import {import { canonicalizeTextureAtlasSpecV1 } from './texture-atlas-contract';import type { MaterialMapPinV1 } from './pinned-material-map';+/**+ * A save names a parent the library holds; import does not, as asset import does not. The record+ * builders cannot check this because they have no library.+ */+async function assertMaterialParent(+ draft: { materialId: string; parentRevision?: string | undefined },+ library: MaterialLibrary,+): Promise<void> {+ if (!draft.parentRevision) return;+ try {+ if (library.readManifest) await library.readManifest(draft.materialId, draft.parentRevision);+ else await library.read(draft.materialId, draft.parentRevision);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ throw new Error(+ `parentRevision ${draft.parentRevision} is not a saved revision of material ${draft.materialId}. A parent must be an existing revision of the same materialId; list materials to see their revision IDs.`,+ );+ }+}+export async function createProceduralMaterialRecord(value: unknown,library: MaterialLibrary,@@ -28,13 +48,14 @@ export async function createProceduralMaterialRecord(throw new Error('Material draft exceeds size limit');if (!value || typeof value !== 'object' || Array.isArray(value))throw new Error('Material draft must be a JSON object');- if (!Object.hasOwn(value, 'schemaVersion'))- return {- record: await createMaterialRecordV1(proceduralMaterialDraftSchema.parse(value)),- dependencies: [],- };+ if (!Object.hasOwn(value, 'schemaVersion')) {+ const draft = proceduralMaterialDraftSchema.parse(value);+ await assertMaterialParent(draft, library);+ return { record: await createMaterialRecordV1(draft), dependencies: [] };+ }const draft = proceduralMaterialDraftV2Schema.parse(value);+ await assertMaterialParent(draft, library);const pins = new Map<string, MaterialMapPinV1>();for (const map of draft.maps) {if (!map.atlas) continue;diff --git a/src/material-library-node.ts b/src/material-library-node.tsindex 153e25d7..ddd69644 100644--- a/src/material-library-node.ts+++ b/src/material-library-node.ts@@ -81,6 +81,7 @@ export type MaterialMapDraftV1 = MapDraftCommon &);export interface MaterialDraftV1 {materialId: string;+ parentRevision?: MaterialManifestV1['parentRevision'];name: string;tags?: string[];tileable: boolean;@@ -146,6 +147,7 @@ export async function createMaterialRecordV1(draft: MaterialDraftV1): Promise<MaassertMaterialJson(draft, true);exactKeys(draft, ['materialId',+ 'parentRevision','name','tags','tileable',@@ -246,6 +248,7 @@ export async function createMaterialRecordV1(draft: MaterialDraftV1): Promise<MaschemaVersion: 1,materialId: draft.materialId,revisionId: `sha256:${'0'.repeat(64)}`,+ ...(draft.parentRevision ? { parentRevision: draft.parentRevision } : {}),name: draft.name,tags: draft.tags ?? [],tileable: draft.tileable,@@ -1083,6 +1086,7 @@ export async function createMaterialRecordV2(exactKeys(draft, ['schemaVersion','materialId',+ 'parentRevision','name','tags','tileable',diff --git a/src/material-library.ts b/src/material-library.tsindex 7ea74314..c1dae328 100644--- a/src/material-library.ts+++ b/src/material-library.ts@@ -228,6 +228,7 @@ export const materialManifestSchema = zschemaVersion: z.literal(1),materialId: materialLibraryIdSchema,revisionId: materialLibraryHashSchema,+ parentRevision: materialLibraryHashSchema.optional(),name: z.string().min(1).max(200),tags: z.array(z.string().min(1).max(80)).max(30),tileable: z.boolean(),@@ -277,6 +278,9 @@ export type MaterialMapV1 = MaterialManifestV1['maps'][number];export const proceduralMaterialDraftSchema = z.object({materialId: materialLibraryIdSchema,+ parentRevision: materialLibraryHashSchema+ .optional()+ .describe('The saved revision of this materialId that this one replaces.'),name: z.string().min(1).max(200),tags: z.array(z.string().min(1).max(80)).max(30).optional(),tileable: z.boolean(),diff --git a/src/material-map-export-node.ts b/src/material-map-export-node.tsindex cc96a7f3..3c7800cb 100644--- a/src/material-map-export-node.ts+++ b/src/material-map-export-node.ts@@ -81,6 +81,7 @@ export interface MaterialMapExportSidecarV1 {material: {materialId: string;revisionId: string;+ parentRevision?: string;name: string;tileable: boolean;physicalSizeMeters?: { width: number; height: number };@@ -535,6 +536,7 @@ export async function createMaterialMapExport(material: {materialId: id,revisionId: manifest.revisionId,+ ...(manifest.parentRevision ? { parentRevision: manifest.parentRevision } : {}),name: manifest.name,tileable: manifest.tileable,...(manifest.physicalSizeMetersdiff --git a/src/material-parent-revision.test.ts b/src/material-parent-revision.test.tsnew file mode 100644index 00000000..81897603--- /dev/null+++ b/src/material-parent-revision.test.ts@@ -0,0 +1,230 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createProceduralMaterialRecord } from './material-authoring-node';+import {+ createMaterialLibraryPayload,+ createMaterialRecordV1,+ createMaterialRecordV2,+ decodeMaterialLibraryPayload,+ FileMaterialLibrary,+} from './material-library-node';+import { exportMaterialMaps } from './material-map-export-node';+import { createKilnMaterialDef } from './tools/materials';++const procedural = (seed: number) => ({+ schemaVersion: 2 as const,+ size: 8,+ usage: 'albedo' as const,+ layers: [{ op: 'noise' as const, colorA: 0xddddcc, colorB: 0xeeeecc, seed }],+});+const source = {+ id: 'authored',+ kind: 'procedural' as const,+ provider: 'Kiln',+ creator: 'Test author',+ license: {+ spdx: 'CC0-1.0',+ url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ attribution: '',+ },+ originalFiles: [],+};+const v1 = (materialId = 'iron', seed = 1) => ({+ materialId,+ name: 'Iron',+ tileable: true,+ sources: [source],+ maps: [+ {+ slot: 'baseColor' as const,+ sourceId: 'authored',+ transforms: [],+ procedural: procedural(seed),+ },+ ],+});+const v2 = (materialId = 'iron', seed = 1) => ({+ schemaVersion: 2 as const,+ materialId,+ name: 'Iron',+ tileable: true,+ sources: [source],+ maps: [+ {+ slot: 'baseColor' as const,+ sourceId: 'authored',+ transforms: [],+ sampler: { minFilter: 'nearest', magFilter: 'nearest', wrapS: 'repeat', wrapT: 'repeat' },+ procedural: procedural(seed),+ },+ ],+});++let root: string;+let store: FileMaterialLibrary;+beforeAll(async () => {+ root = await mkdtemp(join(tmpdir(), 'kiln-material-parent-'));+ store = new FileMaterialLibrary(join(root, 'materials'));+});+afterAll(() => rm(root, { recursive: true, force: true }));++async function save(draft: unknown, library = store) {+ const { record } = await createProceduralMaterialRecord(draft, library);+ const [manifest] = await library.import([record]);+ return manifest!;+}++describe.each([+ ['V1', v1],+ ['V2', v2],+])('%s material lineage (#310)', (_name, draft) => {+ test('a draft without a parent stores no key, so its revision id is what it was', async () => {+ const manifest = await save(draft('plain'));+ expect(manifest).not.toHaveProperty('parentRevision');+ });++ test('the parent is stored, read back and covered by the revision hash', async () => {+ const parent = await save(draft('iron', 1));+ const child = await save({ ...draft('iron', 2), parentRevision: parent.revisionId });+ expect(child.parentRevision).toBe(parent.revisionId);+ const read = await store.read('iron', child.revisionId);+ expect(read.manifest.parentRevision).toBe(parent.revisionId);+ const orphan = await save(draft('iron', 2));+ expect(orphan.revisionId).not.toBe(child.revisionId);+ });++ test('a parent that does not exist is refused by name', async () => {+ await expect(+ save({ ...draft('iron', 3), parentRevision: `sha256:${'a'.repeat(64)}` }),+ ).rejects.toThrow(/parentRevision/);+ });++ test("another material's revision is refused by name", async () => {+ const other = await save(draft('copper', 1));+ await expect(save({ ...draft('iron', 4), parentRevision: other.revisionId })).rejects.toThrow(+ /parentRevision.*iron/,+ );+ });++ test('a malformed parent is refused', async () => {+ await expect(save({ ...draft('iron', 5), parentRevision: 'latest' })).rejects.toThrow();+ });++ test('the parent survives export and import into a store that lacks it', async () => {+ const parent = await save(draft('tin', 1));+ const child = await save({ ...draft('tin', 2), parentRevision: parent.revisionId });+ const payload = await createMaterialLibraryPayload([await store.read('tin', child.revisionId)]);+ const receiving = new FileMaterialLibrary(join(root, `receiving-${_name}`));+ const [imported] = await receiving.import(+ await decodeMaterialLibraryPayload(JSON.parse(JSON.stringify(payload))),+ );+ expect(imported!.revisionId).toBe(child.revisionId);+ expect(imported!.parentRevision).toBe(parent.revisionId);+ await expect(receiving.read('tin', parent.revisionId)).rejects.toThrow();+ });+});++describe('where a material parent is reported (#310)', () => {+ test('the pure record builders accept the field', async () => {+ const parentRevision = `sha256:${'b'.repeat(64)}` as const;+ const legacy = await createMaterialRecordV1({ ...v1(), parentRevision });+ expect(legacy.manifest.parentRevision).toBe(parentRevision);+ const current = await createMaterialRecordV2({ ...v2(), parentRevision });+ expect(current.manifest.parentRevision).toBe(parentRevision);+ });++ test('kiln_material create, get and list report it', async () => {+ const library = new FileMaterialLibrary(join(root, 'tool'));+ const tool = createKilnMaterialDef(library);+ const first = (await tool.run({ action: 'create-procedural', draft: v1('steel', 1) })) as {+ material: { revisionId: string };+ };+ const second = (await tool.run({+ action: 'create-procedural',+ draft: { ...v1('steel', 2), parentRevision: first.material.revisionId },+ })) as { material: { revisionId: string; parentRevision: string } };+ expect(second.material.parentRevision).toBe(first.material.revisionId);+ const got = (await tool.run({+ action: 'get',+ materialId: 'steel',+ revisionId: second.material.revisionId,+ })) as { material: { parentRevision: string } };+ expect(got.material.parentRevision).toBe(first.material.revisionId);+ const { materials } = (await tool.run({ action: 'list' })) as {+ materials: { revisionId: string; parentRevision?: string }[];+ };+ const summary = (id: string) => materials.find((item) => item.revisionId === id)!;+ expect(summary(second.material.revisionId).parentRevision).toBe(first.material.revisionId);+ expect(summary(first.material.revisionId)).not.toHaveProperty('parentRevision');+ });++ test('the map export sidecar names it, and omits it for a root revision', async () => {+ const parent = await save(v1('zinc', 1));+ const child = await save({ ...v1('zinc', 2), parentRevision: parent.revisionId });+ const out = join(root, 'maps');+ const childExport = await exportMaterialMaps(await store.read('zinc', child.revisionId), {+ outDir: join(out, 'child'),+ size: 8,+ repeatMeters: 1,+ });+ expect(childExport.sidecar.material.parentRevision).toBe(parent.revisionId);+ const written = JSON.parse(await readFile(join(out, 'child', 'zinc.maps.json'), 'utf8'));+ expect(written.material.parentRevision).toBe(parent.revisionId);+ const rootExport = await exportMaterialMaps(await store.read('zinc', parent.revisionId), {+ outDir: join(out, 'root'),+ size: 8,+ repeatMeters: 1,+ });+ expect(rootExport.sidecar.material).not.toHaveProperty('parentRevision');+ });+});++// Measured at ~1.5 s per CLI start under load; each test runs several.+describe('kiln material procedural --parent (#310)', () => {+ const cli = join(import.meta.dir, 'cli.ts');+ const run = (cwd: string, ...args: string[]) =>+ spawnSync('bun', [cli, 'material', ...args], {+ cwd,+ encoding: 'utf8',+ env: { ...process.env, KILN_WORKSPACE: cwd },+ });++ test('sets the parent, and refuses one that disagrees with the draft', async () => {+ const cwd = join(root, 'cli');+ await mkdir(cwd, { recursive: true });+ const first = join(cwd, 'first.json');+ const second = join(cwd, 'second.json');+ await writeFile(first, JSON.stringify(v1('lead', 1)));+ await writeFile(second, JSON.stringify(v1('lead', 2)));+ const parent = run(cwd, 'procedural', '--file', first);+ expect(parent.status, parent.stderr).toBe(0);+ const parentRevision = JSON.parse(parent.stdout).materials[0].revisionId;++ const unknown = run(+ cwd,+ 'procedural',+ '--file',+ second,+ '--parent',+ `sha256:${'c'.repeat(64)}`,+ );+ expect(unknown.status).toBe(1);+ expect(unknown.stderr).toContain('parentRevision');++ const child = run(cwd, 'procedural', '--file', second, '--parent', parentRevision);+ expect(child.status, child.stderr).toBe(0);+ expect(JSON.parse(child.stdout).materials[0].parentRevision).toBe(parentRevision);++ const disagreeing = join(cwd, 'disagreeing.json');+ await writeFile(+ disagreeing,+ JSON.stringify({ ...v1('lead', 3), parentRevision: `sha256:${'d'.repeat(64)}` }),+ );+ const conflict = run(cwd, 'procedural', '--file', disagreeing, '--parent', parentRevision);+ expect(conflict.status).toBe(1);+ expect(conflict.stderr).toContain('--parent');+ }, 60_000);+});diff --git a/src/project-cli.ts b/src/project-cli.tsindex 9b6a0b2c..d3c38408 100644--- a/src/project-cli.ts+++ b/src/project-cli.ts@@ -34,7 +34,7 @@ MATERIALSkiln material create-preset --file <preset-options.json>kiln material listkiln material get <id> <sha256:revision>- kiln material procedural --file <procedural-material-draft.json>+ kiln material procedural --file <procedural-material-draft.json> [--parent <sha256:revision>]kiln material import --file <portable-material-payload.json>kiln material export <id> <sha256:revision> --out <portable-material-payload.json>kiln material export <id> <sha256:revision> --maps <dir> --size <px> [--repeat <metres>]@@ -91,6 +91,17 @@ async function jsonFile(path: string, limit: number): Promise<unknown> {}/** `material export --maps`: a strict decimal reading, then the SDK's own range checks. */+/** `--parent` sets a draft's parent, as `kiln save --parent` does; it never overrides a different one. */+function withParentFlag(draft: unknown, parent: string | undefined): unknown {+ if (!parent || !draft || typeof draft !== 'object' || Array.isArray(draft)) return draft;+ const stated = (draft as { parentRevision?: unknown }).parentRevision;+ if (stated !== undefined && stated !== parent)+ throw new Error(+ `--parent ${parent} disagrees with the draft's parentRevision ${String(stated)}`,+ );+ return { ...draft, parentRevision: parent };+}+async function exportMaterialMapsCommand(materials: FileWorkspace['materials'],positional: readonly string[],@@ -177,7 +188,7 @@ export async function projectMain(argv: readonly string[]): Promise<number> {'material:presets': ['tag'],'material:create-preset': ['file'],'material:get': [],- 'material:procedural': ['file'],+ 'material:procedural': ['file', 'parent'],'material:import': ['file'],'material:export': ['out', 'maps', 'size', 'repeat', 'tiles', 'render'],};@@ -325,7 +336,10 @@ export async function projectMain(argv: readonly string[]): Promise<number> {action === 'procedural' ? MATERIAL_LIBRARY_LIMITS.maxManifestBytes : 24 * 1024 * 1024,);if (action === 'procedural') {- const { record, dependencies } = await createProceduralMaterialRecord(input, materials);+ const { record, dependencies } = await createProceduralMaterialRecord(+ withParentFlag(input, flags.parent),+ materials,+ );output = {materials: await materials.import([record],diff --git a/src/tools/materials.ts b/src/tools/materials.tsindex beea3524..09b844d1 100644--- a/src/tools/materials.ts+++ b/src/tools/materials.ts@@ -209,6 +209,7 @@ export function createKilnMaterialDef(.map((item) => ({materialId: item.materialId,revisionId: item.revisionId,+ ...(item.parentRevision ? { parentRevision: item.parentRevision } : {}),name: item.name,tags: item.tags,tileable: item.tileable,