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
feat(budget): separate declared material limits from optional advice (#176)
Matt Kissingera5390ef05255
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ac04a20..a35ec41a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -102,6 +102,14 @@ does not publish a package.`viewFidelity`, so a CPU preview is never read as material evidence. Existing files arenever replaced. `exportMaterialMaps` and `createMaterialMapExport` from`material-library/node` do the same for hosts; `--out` and MCP are unchanged.+- Material measurements no longer read as a budget nobody declared. Without a material+ limit, receipts list `materialAdvice[]` beside `budget` and QA reports `observe`+ findings `MATERIAL_TEXTURE_RESOLUTION_ADVICE`, `MATERIAL_IMAGE_COUNT_ADVICE`,+ `MATERIAL_DECODED_MEMORY_ADVICE` and `MATERIAL_BLEND_AREA_ADVICE` (formerly `*_BUDGET`+ warnings) against the `web.portable.v1/standard` reference tier, worded as optional+ 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)).## 1.4.0 (2026-10-23)diff --git a/docs/delivery-contract.md b/docs/delivery-contract.mdindex 1dd72ce9..26761edd 100644--- a/docs/delivery-contract.md+++ b/docs/delivery-contract.md@@ -61,7 +61,16 @@ attribute names, so shaders read `_edge` and `_cavity`.stores them, before any consumer batching, so each child of a `repeatInstances` groupcounts. Beside the measured `draws`, the LOD0 tier reports `instancedDraws`: the drawsthe three runtime target leaves after batching each group into one instanced draw.- It is informational and never changes the tier's status.+ It is informational and never changes the tier's status. Optional+ material limits are `images`, `decodedBytes` (RGBA8, before mips) and `materialTier`,+ which adopts a reference tier's image count, decoded bytes, image size and+ blended-area figures; explicit limits override the tier. They report in+ `budget.materials` and count toward `budget.status`.+- With no material limit declared, receipts compare the GLB with the+ `web.portable.v1/standard` reference tier and list any figure passed in+ `materialAdvice[]` beside `budget`, with matching `observe` QA findings+ (`MATERIAL_*_ADVICE`). These are optimization notes, never a requirement, and a+ declared material limit replaces them.- `definePalette(colors, { threshold? })` stores scene extras `kilnPaletteV1`. Eachmaterial drawn by a visible node is compared by its base colour factor in CIELAB(CIE 1976 delta E, default threshold 10). Off-palette materials becomediff --git a/docs/geometry.md b/docs/geometry.mdindex da7ec9fd..0ea84968 100644--- a/docs/geometry.md+++ b/docs/geometry.md@@ -531,6 +531,12 @@ batched export would meet; raise the cap or note the difference instead. The resis `budget: { status, tiers }` in render results, `kiln_render` and CLI receipts. Itis advisory; `kiln render --strict-budget` exits 1 when a tier fails.+Material limits are declared the same way: `defineBudget({ images: 6 })`,+`decodedBytes`, or `materialTier: 'web.portable.v1/hero'` for a reference tier's+figures. They report in `budget.materials`. Without one, `materialAdvice` notes+compare the textures with the `web.portable.v1/standard` reference tier; they are+optional optimization advice, not a budget, so keep textures that carry the look.+## Joint discovery and resource counts`describeAssembly(root).joints` finds validated articulated joints, wheel-spin pivots,diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.mdindex f5955bff..7dbf18d7 100644--- a/skills/kiln-qa-asset/SKILL.md+++ b/skills/kiln-qa-asset/SKILL.md@@ -29,7 +29,10 @@ numeric child locators in the authored build root; use the retained source's chiorder to find a failure, since a failed build has no exported inspection artifact.An open card, cloth sheet or intentionally open shell can be valid for its purpose.Keep budget and palette observations separate from requirements explicitly requested-by the user; strict budget enforcement is opt-in.+by the user; strict budget enforcement is opt-in. `materialAdvice` notes and+`MATERIAL_*_ADVICE` findings compare textures with a reference tier when no material+limit is declared: they are optional advice, so do not strip textures that carry the+look to clear them.An intentional boundary can use `markOpenShell(part, 'specific reason')`. Read theoverlap report's acknowledgment and reason; this is an explicit measurement limit,diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snapindex 4602df5f..5d6a528f 100644--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap@@ -863,13 +863,18 @@ geometryDiagnostics(geometry: BufferGeometry, tolerance?: number)// tolerance and scale. Open boundaries are valid for sheets; closed edges do not certify a// self-intersection-free solid.// e.g. const topology = geometryDiagnostics(shell);-defineBudget(spec: { triangles: number | { LOD0, LOD1, ... }, draws?: number }, target?: Object3D)- // Declares a triangle budget (one number for LOD0, or per LOD tier) and an optional LOD0- // draw-call budget. Receipts report budget: { status, tiers: [{ tier, declared, measured,- // status }] } measured from the GLB. Advisory: never QA acceptance.+defineBudget(spec: { triangles?: number | { LOD0, LOD1, ... }, draws?: number, images?: number, decodedBytes?: number, materialTier?: 'web.portable.v1/standard' | ... }, target?: Object3D)+ // Declares a triangle budget (one number for LOD0, or per LOD tier), an optional LOD0+ // draw-call budget, and optional material limits: images, decodedBytes (RGBA8), or+ // materialTier, which adopts a reference tier's image count, decoded bytes, image size and+ // blended-area figures. Receipts report budget: { status, tiers, materials? } measured from+ // the GLB. Without a material limit, receipts carry materialAdvice notes against+ // web.portable.v1/standard instead: optional, never a requirement. Advisory: never QA+ // acceptance.// NOTE: Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching- // defineLod levels.- // e.g. defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });+ // defineLod levels. Material notes are not a budget: do not remove textures that carry the+ // look to clear them.+ // e.g. defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3, images: 6 });definePalette(colors: string[], opts?: { threshold?: 10 }, target?: Object3D)// Declares the asset palette (1..64 hex colours). Receipts list every drawn material whose// base colour is farther than threshold (CIE76 delta E, default 10) from the nearest entry asdiff --git a/src/__tests__/material-advice.test.ts b/src/__tests__/material-advice.test.tsnew file mode 100644index 00000000..30c17192--- /dev/null+++ b/src/__tests__/material-advice.test.ts@@ -0,0 +1,154 @@+/**+ * Material measurements keep declared budgets apart from optional advice (#176).+ *+ * With no material limit declared, the reference profile's figures are optimization notes:+ * `observe` QA findings and `materialAdvice[]` beside `budget`, never budget wording. A+ * `defineBudget({ images, decodedBytes, materialTier })` declaration is measured in+ * `budget.materials`, counts toward `budget.status` (and so `--strict-budget`), and replaces+ * the notes.+ */+import { describe, expect, test } from 'bun:test';+import { defineBudget, evaluateBudget } from '../budget';+import { AuthoringDiagnosticError } from '../evaluator/authoring-diagnostic';+import type { MaterialMetricsV1 } from '../material-metrics';+import { renderGLBInProcess } from '../render';++// One material with five maps: one image over the four-image web.portable.v1/standard figure.+const textured = (budget: string) => `+const meta = { name: 'FiveMaps', category: 'prop' };+async function build() {+ const root = createRoot('FiveMaps');+ const albedo = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'albedo', name: 'Albedo', layers: [{ op: 'noise', colorA: 0x102030, colorB: 0x8090a0, scale: 2 }] });+ const normal = normalMapFromHeight(albedo, { name: 'Normal' });+ const mr = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'metallicRoughness', name: 'MetallicRoughness', layers: [{ op: 'checker', colorA: 0x0040c0, colorB: 0x00c040, squares: 2 }] });+ const ao = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'occlusion', name: 'Occlusion', layers: [{ op: 'solid', color: 0x808080 }] });+ const emissive = proceduralTexture({ schemaVersion: 2, size: 8, usage: 'emissive', name: 'Emissive', layers: [{ op: 'stripes', colorA: 0x00ffff, colorB: 0x000000, count: 2 }] });+ root.add(createPart('Body', copyGeometry(boxGeo(1, 1, 1)), pbrMaterial({ albedo, normal, metallicRoughness: mr, aoMap: ao, emissive }), {}));+ ${budget}+ return root;+}+`;++const materialFindings = (report: unknown) =>+ Object.values(+ (+ report as {+ dimensions: Record<+ string,+ { findings: { code: string; disposition: string; message: string }[] }+ >;+ }+ ).dimensions,+ )+ .flatMap((dimension) => dimension.findings)+ .filter((finding) => finding.code.startsWith('MATERIAL_'));++const metrics = (over: Partial<MaterialMetricsV1>): MaterialMetricsV1 =>+ ({+ imageCount: 0,+ maxImageDimension: 0,+ decodedImageBytesRgba8: 0,+ blendedSurfaceAreaRatio: 0,+ images: [],+ ...over,+ }) as MaterialMetricsV1;++describe('defineBudget material limits', () => {+ test('declares images, decodedBytes or a reference tier without triangles', () => {+ expect(defineBudget({ images: 6 })).toEqual({+ schemaVersion: 1,+ triangles: {},+ materials: { images: 6 },+ });+ expect(defineBudget({ triangles: 900, decodedBytes: 4_000_000 })).toEqual({+ schemaVersion: 1,+ triangles: { LOD0: 900 },+ materials: { decodedBytes: 4_000_000 },+ });+ // A tier adopts every figure of that reference tier; explicit limits override it.+ expect(defineBudget({ materialTier: 'web.portable.v1/hero', images: 10 })).toEqual({+ schemaVersion: 1,+ triangles: {},+ materials: {+ tier: 'web.portable.v1/hero',+ images: 10,+ decodedBytes: 128 * 1024 * 1024,+ imageSize: 4096,+ blendedAreaRatio: 0.35,+ },+ });+ for (const bad of [+ {},+ { images: 0 },+ { images: 2.5 },+ { decodedBytes: -1 },+ { materialTier: 'web.portable.v1/huge' },+ { materialTier: 'standard' },+ ])+ expect(() => defineBudget(bad as never)).toThrow(AuthoringDiagnosticError);+ });++ test('measures declared material limits and folds them into the status', () => {+ const declaration = defineBudget({ triangles: 100, images: 4, decodedBytes: 1000 });+ const report = evaluateBudget(+ declaration,+ { triangles: 12, draws: 1 },+ [],+ metrics({ imageCount: 5, decodedImageBytesRgba8: 800 }),+ );+ expect(report.materials).toEqual([+ { limit: 'images', declared: 4, measured: 5, status: 'fail' },+ { limit: 'decodedBytes', declared: 1000, measured: 800, status: 'pass' },+ ]);+ expect(report.tiers.map((tier) => tier.status)).toEqual(['pass']);+ expect(report.status).toBe('fail');+ });+});++describe('render material notes', () => {+ test('an unbudgeted textured asset gets observe notes, not budget warnings', async () => {+ const result = await renderGLBInProcess(textured(''));+ const findings = materialFindings(result.meta.qaReport);+ expect(findings.map((finding) => [finding.code, finding.disposition])).toEqual([+ ['MATERIAL_IMAGE_COUNT_ADVICE', 'observe'],+ ]);+ const manifest = result.integrationManifest;+ expect(manifest.budget).toBeUndefined();+ expect(manifest.materialAdvice).toHaveLength(1);+ const [advice] = manifest.materialAdvice!;+ expect(advice).toMatchObject({+ code: 'MATERIAL_IMAGE_COUNT_ADVICE',+ disposition: 'advisory',+ reference: 'web.portable.v1/standard',+ measurement: { name: 'imageCount', actual: 5, reference: 4, unit: 'images' },+ });+ // Notes never read as a cap the author must meet.+ for (const text of [advice!.message, findings[0]!.message]) {+ expect(text).not.toMatch(/\bbudget\b|exceed|allows/i);+ expect(text).toMatch(/not a requirement/);+ expect(text).toMatch(/defineBudget/);+ }+ });++ test('a declared image budget replaces the notes and is measured', async () => {+ const passing = await renderGLBInProcess(textured('defineBudget({ images: 6 });'));+ expect(materialFindings(passing.meta.qaReport)).toEqual([]);+ expect(passing.integrationManifest.materialAdvice).toBeUndefined();+ expect(passing.integrationManifest.budget).toEqual({+ status: 'pass',+ tiers: [],+ materials: [{ limit: 'images', declared: 6, measured: 5, status: 'pass' }],+ });++ const failing = await renderGLBInProcess(textured('defineBudget({ images: 3 });'));+ expect(failing.integrationManifest.budget).toMatchObject({+ status: 'fail',+ materials: [{ limit: 'images', declared: 3, measured: 5, status: 'fail' }],+ });+ // A declared budget stays advisory for QA acceptance.+ expect(materialFindings(failing.meta.qaReport)).toEqual([]);+ expect((failing.meta.qaReport as { acceptance: string }).acceptance).toBe(+ (passing.meta.qaReport as { acceptance: string }).acceptance,+ );+ });+});diff --git a/src/__tests__/material-metrics.test.ts b/src/__tests__/material-metrics.test.tsindex 87058773..9c25119b 100644--- a/src/__tests__/material-metrics.test.ts+++ b/src/__tests__/material-metrics.test.ts@@ -6,7 +6,7 @@ import * as THREE from 'three';import { applyMaterialRecipeV1 } from '../material-recipe-runtime';import {collectMaterialMetricsV1,- evaluateMaterialBudgetV1,+ adviseMaterialsV1,materialBudgetProfileForQaProfile,type MaterialMetricsV1,} from '../material-metrics';@@ -137,27 +137,27 @@ describe('MAT-018 advisory texture budgets', () => {};expect(materialBudgetProfileForQaProfile('vehicle.mobile')).toBe('mobile.portable.v1');expect(materialBudgetProfileForQaProfile('architecture.default')).toBe('web.portable.v1');- const warnings = evaluateMaterialBudgetV1(over, {+ const warnings = adviseMaterialsV1(over, {profile: 'web.portable.v1',tier: 'standard',});expect(warnings.map((warning) => warning.code)).toEqual([- 'MATERIAL_TEXTURE_RESOLUTION_BUDGET',- 'MATERIAL_IMAGE_COUNT_BUDGET',- 'MATERIAL_DECODED_MEMORY_BUDGET',- 'MATERIAL_BLEND_AREA_BUDGET',+ 'MATERIAL_TEXTURE_RESOLUTION_ADVICE',+ 'MATERIAL_IMAGE_COUNT_ADVICE',+ 'MATERIAL_DECODED_MEMORY_ADVICE',+ 'MATERIAL_BLEND_AREA_ADVICE',]);- expect(warnings.every((warning) => warning.disposition === 'warn')).toBe(true);+ expect(warnings.every((warning) => warning.disposition === 'advisory')).toBe(true);expect(- warnings.every((warning) => warning.measurement.actual > warning.measurement.threshold),+ warnings.every((warning) => warning.measurement.actual > warning.measurement.reference),).toBe(true);- expect(warnings.map((warning) => warning.advice).join(' ')).toMatch(/Downscale.*atlas.*MASK/is);+ expect(warnings.map((warning) => warning.advice).join(' ')).toMatch(/downscale.*atlas.*MASK/is);expect(warnings.map((warning) => warning.message).join(' ')).toMatch(/8192px.*9 images.*256\.00 MiB.*80\.0%/s,);});- test('names the BLEND materials that drive the blend-area budget', () => {+ test('names the BLEND materials that drive the blend-area note', () => {const document = new Document();const buffer = document.createBuffer();const scene = document.createScene('Scene');@@ -189,19 +189,19 @@ describe('MAT-018 advisory texture budgets', () => {{ name: 'Smoke', area: 1, ratio: 1 / 31 },{ name: 'material-5', area: 1, ratio: 1 / 31 },]);- const warnings = evaluateMaterialBudgetV1(metrics, {+ const warnings = adviseMaterialsV1(metrics, {profile: 'web.portable.v1',tier: 'standard',});expect(warnings.map((warning) => [warning.code, warning.disposition])).toEqual([- ['MATERIAL_BLEND_AREA_BUDGET', 'warn'],+ ['MATERIAL_BLEND_AREA_ADVICE', 'advisory'],]);expect(warnings[0]!.message).toBe(- 'Blended primitive surface area is 48.4% (15.000 of 31.000 square asset units); the budget is 15.0%. Largest BLEND materials by share of surface area: "Glass" 29.0%, "Water" 12.9%, "Smoke" 3.2%, and 1 more.',+ 'Blended primitive surface area is 48.4% (15.000 of 31.000 square asset units); the reference figure is 15.0%. Largest BLEND materials by share of surface area: "Glass" 29.0%, "Water" 12.9%, "Smoke" 3.2%, and 1 more. This is an optimization note from the web.portable.v1/standard reference profile, not a requirement; keep what carries the look. To make a limit binding, declare defineBudget({ materialTier: \'web.portable.v1/standard\' }).',);});- test('stays advisory and quiet within the selected budget', async () => {+ test('stays quiet within the reference tier', async () => {const measured = await materialGalleryMetrics();const metrics = {...measured,@@ -209,7 +209,7 @@ describe('MAT-018 advisory texture budgets', () => {blendedSurfaceAreaRatio: 0.3,};expect(- evaluateMaterialBudgetV1(metrics, {+ adviseMaterialsV1(metrics, {profile: 'web.portable.v1',tier: 'hero',}),diff --git a/src/budget.ts b/src/budget.tsindex 71d69295..352b71e0 100644--- a/src/budget.ts+++ b/src/budget.ts@@ -8,15 +8,41 @@* tier never changes QA acceptance; only CLI `--strict-budget` turns it into an exit code.*/import type * as THREE from 'three';-import type { BudgetReportV1, BudgetTierV1, LevelOfDetailChainV1 } from './contracts/integration';+import type {+ BudgetReportV1,+ BudgetTierV1,+ LevelOfDetailChainV1,+ MaterialBudgetCheckV1,+} from './contracts/integration';import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';+import {+ MATERIAL_BUDGET_PROFILES_V1,+ type MaterialBudgetLimitsV1,+ type MaterialMetricsV1,+ type MaterialReferenceTier,+} from './material-metrics';/** Where a declaration lives: root userData until export, then default-scene extras. */export const KILN_BUDGET_KEY = 'kilnBudgetV1';export interface BudgetSpecV1 {- triangles: number | Record<string, number>;+ triangles?: number | Record<string, number>;draws?: number;+ /** Maximum embedded images. */+ images?: number;+ /** Maximum decoded RGBA8 image bytes, before mip overhead. */+ decodedBytes?: number;+ /** Adopt every figure of a reference tier, such as `web.portable.v1/standard`. */+ materialTier?: MaterialReferenceTier;+}++/** Declared material limits; a tier's figures are resolved into the fields it sets. */+export interface MaterialBudgetDeclarationV1 {+ tier?: MaterialReferenceTier;+ images?: number;+ decodedBytes?: number;+ imageSize?: number;+ blendedAreaRatio?: number;}export interface BudgetDeclarationV1 {@@ -25,8 +51,13 @@ export interface BudgetDeclarationV1 {triangles: Record<string, number>;/** Maximum LOD0 draw calls. */draws?: number;+ materials?: MaterialBudgetDeclarationV1;}+/** True when a declaration replaces the reference-profile material notes. */+export const declaresMaterialLimits = (declaration: BudgetDeclarationV1 | undefined): boolean =>+ declaration?.materials !== undefined;+/** The report when no budget was declared. */export const noBudget = (): BudgetReportV1 => ({ status: 'none', tiers: [] });@@ -40,14 +71,78 @@ const count = (label: string, value: unknown): number => {return value as number;};+const SPEC_SHAPE =+ '{ triangles?: number | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }';++const ratio = (label: string, value: unknown): number => {+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 1)+ fail(`${label} must be a number in (0, 1], got ${String(value)}.`);+ return value as number;+};++/** A reference tier's figures; explicit limits in `value` override them. */+function materialLimits(value: Record<string, unknown>): MaterialBudgetDeclarationV1 | undefined {+ const tierName = value.materialTier;+ const materials: MaterialBudgetDeclarationV1 = {};+ if (tierName !== undefined) {+ const [profile, tier] = typeof tierName === 'string' ? tierName.split('/') : [];+ const figures = (+ MATERIAL_BUDGET_PROFILES_V1 as Partial<+ Record<string, Partial<Record<string, MaterialBudgetLimitsV1>>>+ >+ )[profile ?? '']?.[tier ?? ''];+ if (!figures)+ fail(+ `materialTier must be one of ${Object.entries(MATERIAL_BUDGET_PROFILES_V1)+ .flatMap(([p, tiers]) => Object.keys(tiers).map((t) => `${p}/${t}`))+ .join(', ')}, got ${JSON.stringify(tierName)}.`,+ );+ Object.assign(materials, {+ tier: tierName as MaterialReferenceTier,+ images: figures!.maxImageCount,+ decodedBytes: figures!.maxDecodedBytesRgba8,+ imageSize: figures!.maxImageDimension,+ blendedAreaRatio: figures!.maxBlendedSurfaceAreaRatio,+ });+ }+ if (value.images !== undefined) materials.images = count('images', value.images);+ if (value.decodedBytes !== undefined)+ materials.decodedBytes = count('decodedBytes', value.decodedBytes);+ return Object.keys(materials).length ? materials : undefined;+}++/** A stored declaration's resolved material limits, as `materialLimits` wrote them. */+function storedMaterials(value: unknown): MaterialBudgetDeclarationV1 {+ if (!value || typeof value !== 'object' || Array.isArray(value)) fail('materials is malformed.');+ const stored = value as Record<string, unknown>;+ const materials: MaterialBudgetDeclarationV1 = {};+ for (const key of Object.keys(stored))+ if (!['tier', 'images', 'decodedBytes', 'imageSize', 'blendedAreaRatio'].includes(key))+ fail(`unknown materials field ${JSON.stringify(key)}.`);+ if (stored.tier !== undefined) materials.tier = stored.tier as MaterialReferenceTier;+ if (stored.images !== undefined) materials.images = count('images', stored.images);+ if (stored.decodedBytes !== undefined)+ materials.decodedBytes = count('decodedBytes', stored.decodedBytes);+ if (stored.imageSize !== undefined) materials.imageSize = count('imageSize', stored.imageSize);+ if (stored.blendedAreaRatio !== undefined)+ materials.blendedAreaRatio = ratio('blendedAreaRatio', stored.blendedAreaRatio);+ return materials;+}+/** Validate a spec into its detached declaration. Tier keys are LOD0, LOD1, ... */export function normalizeBudget(spec: unknown): BudgetDeclarationV1 {- if (!spec || typeof spec !== 'object' || Array.isArray(spec))- fail('spec must be { triangles: number | { LOD0, LOD1, ... }, draws? }.');+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) fail(`spec must be ${SPEC_SHAPE}.`);const value = spec as Record<string, unknown>;+ // `materials` and an empty `triangles` record are the stored form a GLB carries back.+ const stored = value.schemaVersion !== undefined;+ const allowed = ['triangles', 'draws', 'images', 'decodedBytes', 'materialTier', 'schemaVersion'];for (const key of Object.keys(value))- if (key !== 'triangles' && key !== 'draws' && key !== 'schemaVersion')+ if (!allowed.includes(key) && !(stored && key === 'materials'))fail(`unknown field ${JSON.stringify(key)}.`);+ const materials =+ stored && value.materials !== undefined+ ? storedMaterials(value.materials)+ : materialLimits(value);const triangles: Record<string, number> = {};if (typeof value.triangles === 'number') triangles.LOD0 = count('triangles', value.triangles);else if (@@ -56,13 +151,17 @@ export function normalizeBudget(spec: unknown): BudgetDeclarationV1 {!Array.isArray(value.triangles)) {const entries = Object.entries(value.triangles as Record<string, unknown>);- if (entries.length === 0) fail('triangles needs at least one tier.');+ if (entries.length === 0 && !(stored && (materials || value.draws !== undefined)))+ fail('triangles needs at least one tier.');for (const [tier, limit] of entries) {if (!/^LOD(0|[1-9][0-9]?)$/.test(tier))fail(`triangles tier ${JSON.stringify(tier)} must be named LOD0, LOD1, ...`);triangles[tier] = count(`triangles.${tier}`, limit);}- } else fail('triangles must be a positive integer or a record of LOD tiers.');+ } else if (value.triangles !== undefined)+ fail('triangles must be a positive integer or a record of LOD tiers.');+ else if (value.draws === undefined && !materials)+ fail(`spec must declare triangles, draws or a material limit: ${SPEC_SHAPE}.`);const ordered = Object.fromEntries(Object.entries(triangles).sort(([a], [b]) => Number(a.slice(3)) - Number(b.slice(3))),);@@ -70,6 +169,7 @@ export function normalizeBudget(spec: unknown): BudgetDeclarationV1 {schemaVersion: 1,triangles: ordered,...(value.draws === undefined ? {} : { draws: count('draws', value.draws) }),+ ...(materials ? { materials } : {}),};}@@ -107,6 +207,7 @@ export function evaluateBudget(declaration: BudgetDeclarationV1,measuredLod0: { triangles: number; draws: number; instancedDraws?: number },chains: readonly LevelOfDetailChainV1[],+ material?: MaterialMetricsV1,): BudgetReportV1 {// Reported beside draws, never judged (#200).const instanced =@@ -147,5 +248,38 @@ export function evaluateBudget(measured: { triangles: measuredLod0.triangles, draws: measuredLod0.draws, ...instanced },status: measuredLod0.draws <= declaration.draws ? 'pass' : 'fail',});- return { status: tiers.every((tier) => tier.status === 'pass') ? 'pass' : 'fail', tiers };+ const materials = material ? evaluateMaterialLimits(declaration, material) : [];+ const pass = [...tiers, ...materials].every((entry) => entry.status === 'pass');+ return {+ status: pass ? 'pass' : 'fail',+ tiers,+ ...(materials.length ? { materials } : {}),+ };+}++/** Each declared material limit against the written GLB's material metrics. */+function evaluateMaterialLimits(+ declaration: BudgetDeclarationV1,+ metrics: MaterialMetricsV1,+): MaterialBudgetCheckV1[] {+ const declared = declaration.materials ?? {};+ const measured: Record<MaterialBudgetCheckV1['limit'], number> = {+ images: metrics.imageCount,+ decodedBytes: metrics.decodedImageBytesRgba8,+ imageSize: metrics.maxImageDimension,+ blendedAreaRatio: metrics.blendedSurfaceAreaRatio,+ };+ return (Object.keys(measured) as MaterialBudgetCheckV1['limit'][]).flatMap((limit) => {+ const value = declared[limit];+ return value === undefined+ ? []+ : [+ {+ limit,+ declared: value,+ measured: measured[limit],+ status: measured[limit] <= value ? ('pass' as const) : ('fail' as const),+ },+ ];+ });}diff --git a/src/cli.ts b/src/cli.tsindex c397d8aa..29980676 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -350,6 +350,9 @@ async function emit(? { vertexAttributes: result.integrationManifest.vertexAttributes }: {}),budget: result.integrationManifest.budget ?? { status: 'none', tiers: [] },+ ...(result.integrationManifest.materialAdvice+ ? { materialAdvice: result.integrationManifest.materialAdvice }+ : {}),...(result.integrationManifest.palette ? { palette: result.integrationManifest.palette } : {}),artifactGlbSha256: result.artifactGlbSha256,glbBytes: result.glb.length,@@ -401,8 +404,16 @@ async function emit(`${tier.tier} ${tier.measured.triangles}/${tier.declared.triangles ?? '-'} tris${tier.declared.draws === undefined ? '' : ` ${tier.measured.draws}/${tier.declared.draws} draws`} ${tier.status}`,).join('; ');- log(` budget ${budget.status} ${tiers}`);+ const materials = (budget.materials ?? [])+ .map((check) => `${check.limit} ${check.measured}/${check.declared} ${check.status}`)+ .join('; ');+ log(` budget ${budget.status} ${[tiers, materials].filter(Boolean).join('; ')}`);}+ // Reference-tier material notes: optional advice, never a declared budget.+ for (const note of result.integrationManifest.materialAdvice ?? [])+ log(+ ` material note (advisory, ${note.reference}) ${note.measurement.name} ${note.measurement.actual}; reference ${note.measurement.reference}`,+ );// A declared palette: advisory, off-palette materials farthest first.const palette = result.integrationManifest.palette;if (palette)diff --git a/src/contracts/integration.ts b/src/contracts/integration.tsindex 5806aeb1..630b5297 100644--- a/src/contracts/integration.ts+++ b/src/contracts/integration.ts@@ -146,11 +146,47 @@ export interface BudgetTierV1 {status: 'pass' | 'fail';}+/**+ * Optional optimization advice measured against a reference profile tier when the asset+ * declares no material limit. Never a requirement and never QA acceptance; a+ * `defineBudget` material limit replaces it.+ */+export interface MaterialAdviceV1 {+ code:+ | 'MATERIAL_TEXTURE_RESOLUTION_ADVICE'+ | 'MATERIAL_IMAGE_COUNT_ADVICE'+ | 'MATERIAL_DECODED_MEMORY_ADVICE'+ | 'MATERIAL_BLEND_AREA_ADVICE';+ disposition: 'advisory';+ /** The reference profile tier, such as `web.portable.v1/standard`. */+ reference: string;+ message: string;+ measurement: {+ name: string;+ actual: number;+ /** The reference tier's figure: a comparison point, not a cap. */+ reference: number;+ unit: 'px' | 'images' | 'bytes' | 'ratio';+ };+ advice: string;+}++/** One declared material limit against the written GLB. */+export interface MaterialBudgetCheckV1 {+ /** `images` count, `decodedBytes` RGBA8, `imageSize` longest edge px, `blendedAreaRatio`. */+ limit: 'images' | 'decodedBytes' | 'imageSize' | 'blendedAreaRatio';+ declared: number;+ measured: number;+ status: 'pass' | 'fail';+}+/** A `defineBudget` declaration against the bytes. Advisory: never QA acceptance. */export interface BudgetReportV1 {- /** `none` when no budget was declared; `fail` when any tier fails. */+ /** `none` when no budget was declared; `fail` when any tier or material limit fails. */status: 'pass' | 'fail' | 'none';tiers: BudgetTierV1[];+ /** Declared material limits, when the declaration has any. */+ materials?: MaterialBudgetCheckV1[];}/** One drawn material whose base colour is off the declared palette. */@@ -226,6 +262,9 @@ export interface IntegrationManifestV1 {ports?: DeliveryPortV1[];/** The declared budget measured against these bytes, when source declared one. */budget?: BudgetReportV1;+ /** Optional optimization notes against a reference profile tier, when no material limit+ * was declared and a figure is passed. Never a requirement. */+ materialAdvice?: MaterialAdviceV1[];/** The declared palette against the drawn materials, when source declared one. */palette?: PaletteReportV1;/** Custom vertex attributes (`_EDGE`, `_CAVITY`) grouped by name and parameters. */diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.tsindex b1ab908e..ed7eb758 100644--- a/src/discovery/helper-specs.ts+++ b/src/discovery/helper-specs.ts@@ -291,14 +291,15 @@ const PRIMITIVES: HelperSpec[] = [{name: 'defineBudget',signature:- 'defineBudget(spec: { triangles: number | { LOD0, LOD1, ... }, draws?: number }, target?: Object3D)',- returns: '{ schemaVersion: 1, triangles: { LOD0, ... }, draws? } (the normalised declaration)',+ "defineBudget(spec: { triangles?: number | { LOD0, LOD1, ... }, draws?: number, images?: number, decodedBytes?: number, materialTier?: 'web.portable.v1/standard' | ... }, target?: Object3D)",+ returns:+ '{ schemaVersion: 1, triangles: { LOD0, ... }, draws?, materials? } (the normalised declaration)',category: 'utility',description:- 'Declares a triangle budget (one number for LOD0, or per LOD tier) and an optional LOD0 draw-call budget. Receipts report budget: { status, tiers: [{ tier, declared, measured, status }] } measured from the GLB. Advisory: never QA acceptance.',- example: 'defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 });',+ "Declares a triangle budget (one number for LOD0, or per LOD tier), an optional LOD0 draw-call budget, and optional material limits: images, decodedBytes (RGBA8), or materialTier, which adopts a reference tier's image count, decoded bytes, image size and blended-area figures. Receipts report budget: { status, tiers, materials? } measured from the GLB. Without a material limit, receipts carry materialAdvice notes against web.portable.v1/standard instead: optional, never a requirement. Advisory: never QA acceptance.",+ example: 'defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3, images: 6 });',promptNotes:- 'Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels.',+ 'Only when the brief states a budget. Call once; tiers are LOD0, LOD1, ... matching defineLod levels. Material notes are not a budget: do not remove textures that carry the look to clear them.',},{name: 'definePalette',diff --git a/src/material-metrics.ts b/src/material-metrics.tsindex 8a9cb9b9..e23a97d5 100644--- a/src/material-metrics.ts+++ b/src/material-metrics.ts@@ -1,6 +1,9 @@-/** Deterministic material/texture metrics and advisory tier/profile budgets. */+/** Deterministic material/texture metrics and reference profile tiers for advice. */import type { Accessor, Document, Material, Node, Primitive, Texture } from '@gltf-transform/core';+import type { MaterialAdviceV1 } from './contracts/integration';++export type { MaterialAdviceV1 };export interface MaterialImageMetricV1 {name: string;@@ -54,24 +57,14 @@ export interface MaterialBudgetLimitsV1 {maxBlendedSurfaceAreaRatio: number;}-export interface MaterialBudgetWarningV1 {- code:- | 'MATERIAL_TEXTURE_RESOLUTION_BUDGET'- | 'MATERIAL_IMAGE_COUNT_BUDGET'- | 'MATERIAL_DECODED_MEMORY_BUDGET'- | 'MATERIAL_BLEND_AREA_BUDGET';- disposition: 'warn';+/** A reference profile tier, such as `web.portable.v1/standard`. */+export type MaterialReferenceTier = `${MaterialBudgetProfileId}/${MaterialAssetTier}`;++/** The tier the render path compares undeclared material costs against. */+export const DEFAULT_MATERIAL_REFERENCE: {profile: MaterialBudgetProfileId;tier: MaterialAssetTier;- message: string;- measurement: {- name: string;- actual: number;- threshold: number;- unit: 'px' | 'images' | 'bytes' | 'ratio';- };- advice: string;-}+} = Object.freeze({ profile: 'web.portable.v1', tier: 'standard' });export const MATERIAL_BUDGET_PROFILES_V1: Readonly<Record<MaterialBudgetProfileId, Readonly<Record<MaterialAssetTier, MaterialBudgetLimitsV1>>>@@ -298,65 +291,71 @@ export function materialBudgetProfileForQaProfile(qaProfile: string): MaterialBu: 'web.portable.v1';}-/** Advisory-only budget evaluation with measured costs and concrete remediation. */-export function evaluateMaterialBudgetV1(+/** Says what a note is and how to make the limit binding; ends every advice message. */+const noteSuffix = (reference: MaterialReferenceTier, declare: string): string =>+ ` This is an optimization note from the ${reference} reference profile, not a requirement; keep what carries the look. To make a limit binding, declare defineBudget(${declare}).`;++/**+ * Compare measured material costs with a reference profile tier. Each result is optional+ * advice with concrete remediation, for assets that declared no material limit.+ */+export function adviseMaterialsV1(metrics: MaterialMetricsV1,options: { profile: MaterialBudgetProfileId; tier: MaterialAssetTier },-): MaterialBudgetWarningV1[] {+): MaterialAdviceV1[] {const limits = MATERIAL_BUDGET_PROFILES_V1[options.profile][options.tier];- const warnings: MaterialBudgetWarningV1[] = [];+ const reference: MaterialReferenceTier = `${options.profile}/${options.tier}`;+ const tierDeclaration = `{ materialTier: '${reference}' }`;+ const advice: MaterialAdviceV1[] = [];if (metrics.maxImageDimension > limits.maxImageDimension) {const offenders = metrics.images.filter((image) => image.maxDimension > limits.maxImageDimension).map((image) => `${image.name} ${image.width}x${image.height}`).join(', ');- warnings.push({- code: 'MATERIAL_TEXTURE_RESOLUTION_BUDGET',- disposition: 'warn',- profile: options.profile,- tier: options.tier,- message: `Maximum image dimension is ${metrics.maxImageDimension}px; ${options.profile}/${options.tier} allows ${limits.maxImageDimension}px. Offenders: ${offenders}.`,+ advice.push({+ code: 'MATERIAL_TEXTURE_RESOLUTION_ADVICE',+ disposition: 'advisory',+ reference,+ message: `Largest image edge is ${metrics.maxImageDimension}px; the reference figure is ${limits.maxImageDimension}px. Larger: ${offenders}.${noteSuffix(reference, tierDeclaration)}`,measurement: {name: 'maxImageDimension',actual: metrics.maxImageDimension,- threshold: limits.maxImageDimension,+ reference: limits.maxImageDimension,unit: 'px',},- advice: `Downscale the named images so their longest edge is at most ${limits.maxImageDimension}px; preserve aspect ratio and rerun glTF validation.`,+ advice: `To reduce it, downscale the named images so their longest edge is at most ${limits.maxImageDimension}px; preserve aspect ratio and rerun glTF validation.`,});}if (metrics.imageCount > limits.maxImageCount) {- warnings.push({- code: 'MATERIAL_IMAGE_COUNT_BUDGET',- disposition: 'warn',- profile: options.profile,- tier: options.tier,- message: `${metrics.imageCount} images exceed the ${limits.maxImageCount}-image ${options.profile}/${options.tier} budget.`,+ advice.push({+ code: 'MATERIAL_IMAGE_COUNT_ADVICE',+ disposition: 'advisory',+ reference,+ message: `${metrics.imageCount} images; the reference figure is ${limits.maxImageCount}.${noteSuffix(reference, '{ images }')}`,measurement: {name: 'imageCount',actual: metrics.imageCount,- threshold: limits.maxImageCount,+ reference: limits.maxImageCount,unit: 'images',},advice:- 'Reuse approved resource IDs, remove unused images, or atlas compatible same-color-space slots; never atlas normal/data maps into an sRGB image.',+ 'To reduce it, reuse approved resource IDs, remove unused images, or atlas compatible same-color-space slots; never atlas normal/data maps into an sRGB image.',});}if (metrics.decodedImageBytesRgba8 > limits.maxDecodedBytesRgba8) {const scale = Math.sqrt(limits.maxDecodedBytesRgba8 / metrics.decodedImageBytesRgba8);- warnings.push({- code: 'MATERIAL_DECODED_MEMORY_BUDGET',- disposition: 'warn',- profile: options.profile,- tier: options.tier,- message: `Decoded RGBA8 image memory is ${mib(metrics.decodedImageBytesRgba8)}; ${options.profile}/${options.tier} allows ${mib(limits.maxDecodedBytesRgba8)} before mip overhead.`,+ advice.push({+ code: 'MATERIAL_DECODED_MEMORY_ADVICE',+ disposition: 'advisory',+ reference,+ message: `Decoded RGBA8 image memory is ${mib(metrics.decodedImageBytesRgba8)}; the reference figure is ${mib(limits.maxDecodedBytesRgba8)} before mip overhead.${noteSuffix(reference, '{ decodedBytes }')}`,measurement: {name: 'decodedImageBytesRgba8',actual: metrics.decodedImageBytesRgba8,- threshold: limits.maxDecodedBytesRgba8,+ reference: limits.maxDecodedBytesRgba8,unit: 'bytes',},- advice: `Downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`,+ advice: `To reduce it, downscale image width and height by approximately ${(Math.min(1, scale) * 100).toFixed(0)}% in aggregate, then verify small details and alpha cutouts remain legible.`,});}if (metrics.blendedSurfaceAreaRatio > limits.maxBlendedSurfaceAreaRatio) {@@ -372,21 +371,20 @@ export function evaluateMaterialBudgetV1(const drivers = named.length? ` Largest BLEND materials by share of surface area: ${named.join(', ')}${more}.`: '';- warnings.push({- code: 'MATERIAL_BLEND_AREA_BUDGET',- disposition: 'warn',- profile: options.profile,- tier: options.tier,- message: `Blended primitive surface area is ${(metrics.blendedSurfaceAreaRatio * 100).toFixed(1)}% (${metrics.blendedSurfaceArea.toFixed(3)} of ${metrics.totalSurfaceArea.toFixed(3)} square asset units); the budget is ${(limits.maxBlendedSurfaceAreaRatio * 100).toFixed(1)}%.${drivers}`,+ advice.push({+ code: 'MATERIAL_BLEND_AREA_ADVICE',+ disposition: 'advisory',+ reference,+ message: `Blended primitive surface area is ${(metrics.blendedSurfaceAreaRatio * 100).toFixed(1)}% (${metrics.blendedSurfaceArea.toFixed(3)} of ${metrics.totalSurfaceArea.toFixed(3)} square asset units); the reference figure is ${(limits.maxBlendedSurfaceAreaRatio * 100).toFixed(1)}%.${drivers}${noteSuffix(reference, tierDeclaration)}`,measurement: {name: 'blendedSurfaceAreaRatio',actual: metrics.blendedSurfaceAreaRatio,- threshold: limits.maxBlendedSurfaceAreaRatio,+ reference: limits.maxBlendedSurfaceAreaRatio,unit: 'ratio',},advice:- 'Use MASK for binary cutouts such as foliage, reduce layered transparent surfaces, and reserve BLEND for genuinely translucent glass/effects.',+ 'To reduce it, use MASK for binary cutouts such as foliage, reduce layered transparent surfaces, and reserve BLEND for genuinely translucent glass/effects.',});}- return warnings;+ return advice;}diff --git a/src/qa/requirements-run.ts b/src/qa/requirements-run.tsindex 235efcf1..5dd25332 100644--- a/src/qa/requirements-run.ts+++ b/src/qa/requirements-run.ts@@ -54,10 +54,10 @@ import {type RequirementsQaFinding,} from './requirements-report';import type { QaFinding } from './types';-import { gltfReportFindings } from './run';+import { gltfReportFindings, materialAdviceFinding } from './run';import type { KhronosGltfValidationReport } from './gltf';import type { InstanceabilityReport } from '../metrics';-import type { MaterialMetricsV1, MaterialBudgetWarningV1 } from '../material-metrics';+import type { MaterialMetricsV1, MaterialAdviceV1 } from '../material-metrics';const registry = new QaRegistry([...UNIVERSAL_QA_RULES,@@ -411,20 +411,10 @@ export async function appendRequirementsFinalQa(instanceability?: InstanceabilityReport,metricsError?: string,material?: MaterialMetricsV1,- warnings: readonly MaterialBudgetWarningV1[] = [],+ materialAdvice: readonly MaterialAdviceV1[] = [],): Promise<AssetRequirementsQaReportV2> {const gltfFindings = gltfReportFindings(gltf, report.qaProfile);- const findings: QaFinding[] = [- ...gltfFindings,- ...warnings.map((w) => ({- code: w.code,- disposition: 'warn' as const,- dimension: 'runtimeCost' as const,- profile: `${w.profile}.${w.tier}`,- message: `${w.message} ${w.advice}`,- measurement: w.measurement,- })),- ];+ const findings: QaFinding[] = [...gltfFindings, ...materialAdvice.map(materialAdviceFinding)];if (metricsError)findings.push({code: 'RUNTIME_COST_METRICS_FAILED',diff --git a/src/qa/run.ts b/src/qa/run.tsindex 435d241d..8a0ab26c 100644--- a/src/qa/run.ts+++ b/src/qa/run.ts@@ -30,7 +30,7 @@ import { UNIVERSAL_QA_RULES } from './universal';import { HOST_VALIDATION_QA_RULE } from './validation-profile';import type { KhronosGltfValidationReport } from './gltf';import type { KhronosGltfIssue } from './gltf';-import type { MaterialBudgetWarningV1, MaterialMetricsV1 } from '../material-metrics';+import type { MaterialAdviceV1, MaterialMetricsV1 } from '../material-metrics';export const DETERMINISTIC_QA_REGISTRY = new QaRegistry([...UNIVERSAL_QA_RULES,@@ -172,27 +172,31 @@ export function appendRuntimeCostQa(});}-/** Attach portable material metrics and advisory budget findings to runtimeCost+/** A reference-tier optimization note as an `observe` runtimeCost finding: never a warning. */+export const materialAdviceFinding = (advice: MaterialAdviceV1): QaFinding => ({+ code: advice.code,+ disposition: 'observe',+ dimension: 'runtimeCost',+ profile: advice.reference,+ message: `${advice.message} ${advice.advice}`,+ measurement: {+ name: advice.measurement.name,+ actual: advice.measurement.actual,+ expected: advice.measurement.reference,+ unit: advice.measurement.unit,+ },+});++/** Attach portable material metrics and optional material notes to runtimeCost* without collapsing them into the independent instanceability grade. */export function appendMaterialMetricsQa(intent: AssetIntentV1,report: AssetQaReportV1,materialMetrics: MaterialMetricsV1,- budgetWarnings: readonly MaterialBudgetWarningV1[] = [],+ materialAdvice: readonly MaterialAdviceV1[] = [],): AssetQaReportV1 {const findings = Object.values(report.dimensions).flatMap((dimension) => dimension.findings);- findings.push(- ...budgetWarnings.map(- (warning): QaFinding => ({- code: warning.code,- disposition: 'warn',- dimension: 'runtimeCost',- profile: `${warning.profile}.${warning.tier}`,- message: `${warning.message} ${warning.advice}`,- measurement: warning.measurement,- }),- ),- );+ findings.push(...materialAdvice.map(materialAdviceFinding));const evaluatedDimensions = Object.entries(report.dimensions).filter(([, dimension]) => dimension.status !== 'notEvaluated').map(([dimension]) => dimension as keyof AssetQaReportV1['dimensions']);diff --git a/src/render.ts b/src/render.tsindex fc78e015..27a3d1d3 100644--- a/src/render.ts+++ b/src/render.ts@@ -85,7 +85,13 @@ import {SANDBOX_DECLARATIONS,type SandboxDeclarations,} from './primitives';-import { evaluateBudget, KILN_BUDGET_KEY, normalizeBudget, readBudgetDeclaration } from './budget';+import {+ declaresMaterialLimits,+ evaluateBudget,+ KILN_BUDGET_KEY,+ normalizeBudget,+ readBudgetDeclaration,+} from './budget';import {evaluatePalette,KILN_PALETTE_KEY,@@ -118,8 +124,10 @@ import {} from './qa/gltf';import { AssetQaBlockedError, qaBlockingEnabled, qaPolicyFromEnv } from './qa/run';import {+ adviseMaterialsV1,collectMaterialMetricsV1,- evaluateMaterialBudgetV1,+ DEFAULT_MATERIAL_REFERENCE,+ type MaterialAdviceV1,type MaterialMetricsV1,} from './material-metrics';import {@@ -308,6 +316,7 @@ export async function inspectGlbIntegration(budgetDeclaration?.draws === undefined? undefined: await (await import('./runtime-three')).instancedDrawEstimate(doc);+ const materialMetrics = collectMaterialMetricsV1(doc);const budget = budgetDeclaration? evaluateBudget(budgetDeclaration,@@ -317,8 +326,13 @@ export async function inspectGlbIntegration(...(instancedDraws === undefined ? {} : { instancedDraws }),},levelsOfDetail,+ materialMetrics,): undefined;+ // Reference-tier notes only where the author declared no material limit of their own.+ const materialAdvice = declaresMaterialLimits(budgetDeclaration)+ ? []+ : adviseMaterialsV1(materialMetrics, DEFAULT_MATERIAL_REFERENCE);const paletteDeclaration = readPaletteDeclaration((scene.getExtras() as Record<string, unknown>)[KILN_PALETTE_KEY],);@@ -367,6 +381,7 @@ export async function inspectGlbIntegration(...(delivery.kit ? { kit: delivery.kit } : {}),...(delivery.ports.length ? { ports: delivery.ports } : {}),...(budget ? { budget } : {}),+ ...(materialAdvice.length ? { materialAdvice } : {}),...(palette ? { palette } : {}),...(vertexAttributes.length ? { vertexAttributes } : {}),...(delivery.diagnostics.length ? { deliveryDiagnostics: delivery.diagnostics } : {}),@@ -1991,13 +2006,17 @@ export async function renderSceneToGLB(}let materialMetrics: MaterialMetricsV1 | undefined;- let materialBudgetWarnings = [] as ReturnType<typeof evaluateMaterialBudgetV1>;+ let materialAdvice: MaterialAdviceV1[] = [];try {materialMetrics = collectMaterialMetricsV1(doc);- materialBudgetWarnings = evaluateMaterialBudgetV1(materialMetrics, {- profile: 'web.portable.v1',- tier: 'standard',- });+ // A declared material limit is measured in the budget receipt instead of these notes.+ const declaration = readBudgetDeclaration(+ (doc.getRoot().getDefaultScene()?.getExtras() as Record<string, unknown> | undefined)?.[+ KILN_BUDGET_KEY+ ],+ );+ if (!declaresMaterialLimits(declaration))+ materialAdvice = adviseMaterialsV1(materialMetrics, DEFAULT_MATERIAL_REFERENCE);} catch (error) {warnings.push(`material metrics failed: ${error instanceof Error ? error.message : String(error)}`,@@ -2023,7 +2042,7 @@ export async function renderSceneToGLB(instanceability,metricsError,materialMetrics,- materialBudgetWarnings,+ materialAdvice,);if (qaReport.disposition === 'block') {const blocked = new AssetQaBlockedError(qaReport, 'final-glb', gltfValidation);diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 1ccf1668..77bee8e5 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -1079,6 +1079,9 @@ export interface KilnRenderViewsResult extends PartPreview {/** The defineBudget declaration measured against the written GLB; `none` when undeclared.* Advisory: never QA acceptance. */budget?: import('../contracts').BudgetReportV1;+ /** Optional material notes against a reference tier when no material limit was declared:+ * advice, never a requirement. */+ materialAdvice?: import('../contracts').MaterialAdviceV1[];/** Post-dedup instanceability grade (informational): how cheap to render at scale. */instanceability?: { grade: string; summary: string };/** Structured deterministic report; five dimensions remain separate. */@@ -1127,10 +1130,18 @@ function levelsOfDetailField(}/** The hidden subtrees the headline leaves out, when the GLB has any. */-/** The declared budget against the bytes, or status none: always present on a render. */-function budgetField(rendered: RenderResult): { budget?: import('../contracts').BudgetReportV1 } {+/** The declared budget against the bytes, or status none: always present on a render. Optional+ * reference-tier material notes sit beside it, apart from anything declared. */+function budgetField(rendered: RenderResult): {+ budget?: import('../contracts').BudgetReportV1;+ materialAdvice?: import('../contracts').MaterialAdviceV1[];+} {if (!rendered.integrationManifest) return {};- return { budget: rendered.integrationManifest.budget ?? { status: 'none', tiers: [] } };+ const advice = rendered.integrationManifest.materialAdvice;+ return {+ budget: rendered.integrationManifest.budget ?? { status: 'none', tiers: [] },+ ...(advice?.length ? { materialAdvice: advice } : {}),+ };}function hiddenNodesField(rendered: RenderResult): { hiddenNodes?: HiddenNodeV1[] } {