@plasius/asset-contracts 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -0
- package/README.md +200 -0
- package/dist/index.cjs +4632 -75
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1243 -1
- package/dist/index.d.ts +1243 -1
- package/dist/index.js +4468 -58
- package/dist/index.js.map +1 -1
- package/docs/adrs/adr-0005-path-only-private-artifact-prevention-gates.md +82 -0
- package/docs/adrs/adr-0006-pvox-model-resolution-contracts.md +168 -0
- package/docs/adrs/adr-0007-hosted-oidc-package-publication.md +41 -0
- package/docs/adrs/index.md +3 -0
- package/docs/tdrs/index.md +1 -0
- package/docs/tdrs/tdr-0003-pvox-validation-and-confirmation-binding.md +208 -0
- package/legal/CLA.md +5 -2
- package/package.json +15 -6
- package/src/index.ts +3 -0
- package/src/pvox-hash-preimage.ts +1074 -0
- package/src/pvox-model-resolution-schema.ts +1041 -0
- package/src/pvox-model-resolution.ts +3244 -0
- package/legal/CLA-REGISTRY.csv +0 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/asset-version.ts","../src/model-resolution.ts"],"sourcesContent":["import {\n GPU_SHADER_STORE_FEATURE_FLAG,\n GPU_SHADER_STYLE_SELECTION_CAPABILITY,\n SHADER_VALIDATION_EVIDENCE_VERSION,\n SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,\n SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,\n canonicalizeGpuContract,\n computeSha256,\n parseGpuInterfaceManifest,\n parseJsonBytes,\n parseModelGpuCompatibilityDescriptor,\n parseShaderStyleProfileManifest,\n parseShaderVersionManifest,\n} from \"@plasius/gpu-shader\";\nimport type {\n GpuInterfaceManifest,\n GpuInterfaceRef,\n ModelGpuCompatibilityDescriptor,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n Sha256Hex,\n} from \"@plasius/gpu-shader\";\nimport {\n assertAssetVersion,\n assertImmutableAssetVersion,\n} from \"./asset-version.js\";\n\nexport const ASSET_CONTRACTS_PACKAGE = \"@plasius/asset-contracts\";\n\nexport {\n assertAssetVersion,\n assertImmutableAssetVersion,\n};\nexport * from \"./model-resolution.js\";\nexport {\n GPU_SHADER_STORE_FEATURE_FLAG,\n GPU_SHADER_STYLE_SELECTION_CAPABILITY,\n};\nexport type {\n GpuInterfaceManifest,\n GpuInterfaceRef,\n ModelGpuCompatibilityDescriptor,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n Sha256Hex,\n};\nexport const UNIFIED_ASSET_PIPELINE_FEATURE_FLAG_ID = \"asset.pipeline.unified-ai-assets.enabled\";\nexport const ASSET_PIPELINE_MCP_CAPABILITY = \"asset.pipeline.mcp.manage\";\nexport const ASSET_PIPELINE_REVIEW_CAPABILITY = \"asset.pipeline.review.approve\";\n\n/** Canonical content type required for immutable WebGPU shader modules. */\nexport const ASSET_WGSL_CONTENT_TYPE = \"text/wgsl; charset=utf-8\" as const;\n/** Canonical content type for JSON lifecycle artifacts. */\nexport const ASSET_JSON_CONTENT_TYPE = \"application/json\" as const;\n\n/** Closed asset categories supported by the unified model-storage lifecycle. */\nexport const ASSET_KINDS = Object.freeze([\n \"model\",\n \"gpu-interface\",\n \"shader\",\n \"shader-style-profile\",\n \"shader-validation-evidence\",\n] as const);\n\n/** Legacy and GPU-specific roles for files inside one immutable asset version. */\nexport const ASSET_FILE_ROLES = Object.freeze([\n \"model\",\n \"binary\",\n \"texture\",\n \"manifest\",\n \"screenshot\",\n \"metadata\",\n \"wgsl\",\n \"gpu-interface-manifest\",\n \"shader-manifest\",\n \"shader-style-profile-manifest\",\n \"shader-validation-evidence\",\n \"shader-validation-attestation\",\n \"shader-qualification-fixture\",\n \"shader-compile-unit-inventory\",\n \"shader-matrix\",\n] as const);\n\nexport const ASSET_JOB_STATES = Object.freeze([\n \"requested\",\n \"intake-uploaded\",\n \"validated\",\n \"processing\",\n \"processed\",\n \"rendering-review\",\n \"reviewed\",\n \"awaiting-approval\",\n \"approved\",\n \"promoting\",\n \"promoted\",\n \"rejected\",\n \"failed\",\n \"rolled-back\",\n] as const);\n\nexport const ASSET_SOURCE_ADAPTERS = Object.freeze([\n \"local-import\",\n \"ai-generate\",\n \"ai-modify\",\n \"texture-regenerate\",\n \"processor-retry\",\n] as const);\n\nexport const ASSET_SCREENSHOT_KINDS = Object.freeze([\n \"hero\",\n \"front\",\n \"back\",\n \"left\",\n \"right\",\n \"top\",\n \"material-closeup\",\n \"wireframe-density\",\n \"normal-debug\",\n \"lod-comparison\",\n \"collision-proxy\",\n \"scale-reference\",\n] as const);\n\nexport const ASSET_REVIEW_SEVERITIES = Object.freeze([\n \"info\",\n \"warning\",\n \"blocking\",\n] as const);\n\nexport const ASSET_PROMOTION_OUTCOMES = Object.freeze([\n \"promoted\",\n \"rolled-back\",\n] as const);\n\nexport type AssetJobState = typeof ASSET_JOB_STATES[number];\nexport type AssetSourceAdapter = typeof ASSET_SOURCE_ADAPTERS[number];\nexport type AssetScreenshotKind = typeof ASSET_SCREENSHOT_KINDS[number];\nexport type AssetReviewSeverity = typeof ASSET_REVIEW_SEVERITIES[number];\nexport type AssetPromotionOutcome = typeof ASSET_PROMOTION_OUTCOMES[number];\nexport type AssetKind = typeof ASSET_KINDS[number];\nexport type AssetFileRole = typeof ASSET_FILE_ROLES[number];\n\nexport interface AssetFileDescriptor {\n readonly path: string;\n readonly byteLength: number;\n readonly sha256: string;\n readonly contentType: string;\n readonly role: AssetFileRole;\n /** Required only for WGSL files; binds the Blob path to one shader module. */\n readonly moduleId?: string;\n}\n\nexport interface AssetManifest {\n /** Omitted only by legacy callers created before typed asset lifecycles. */\n readonly assetKind?: AssetKind;\n readonly assetId: string;\n readonly version: string;\n readonly entrypoint: string;\n readonly files: readonly AssetFileDescriptor[];\n readonly sourceAdapter: AssetSourceAdapter;\n readonly createdAt: string;\n}\n\n/** Asset manifest with a required discriminator while legacy manifests remain valid. */\nexport interface TypedAssetManifest<K extends AssetKind> extends AssetManifest {\n readonly assetKind: K;\n}\n\n/** Model asset extended with its reflected GPU ABI and discoverable default style. */\nexport interface ModelAssetManifest extends TypedAssetManifest<\"model\"> {\n readonly gpuInterface: GpuInterfaceRef;\n readonly modelAbiHash: Sha256Hex;\n readonly providedSemantics: readonly string[];\n readonly defaultStyleProfile: ShaderStyleProfileRef | null;\n}\n\n/** Input permits a model to omit its default style while preserving explicit null output. */\nexport type ModelAssetManifestInput = Omit<ModelAssetManifest, \"defaultStyleProfile\"> & {\n readonly defaultStyleProfile?: ShaderStyleProfileRef | null;\n};\n\n/** Lifecycle envelope for one generated GPU-interface manifest. */\nexport interface GpuInterfaceAssetManifest extends TypedAssetManifest<\"gpu-interface\"> {\n readonly gpuInterfaceManifest: GpuInterfaceManifest;\n}\n\n/** Lifecycle envelope for one exact, independently versioned WGSL shader. */\nexport interface ShaderAssetManifest extends TypedAssetManifest<\"shader\"> {\n readonly shaderManifest: ShaderVersionManifest;\n}\n\n/** Lifecycle envelope for a profile that pins exact shader versions by render role. */\nexport interface ShaderStyleProfileAssetManifest extends TypedAssetManifest<\"shader-style-profile\"> {\n readonly styleProfileManifest: ShaderStyleProfileManifest;\n}\n\n/** Lifecycle envelope for universal matrix evidence and its external attestation reference. */\nexport interface ShaderValidationEvidenceAssetManifest extends TypedAssetManifest<\"shader-validation-evidence\"> {\n readonly validationEvidence: ShaderValidationEvidenceRef;\n}\n\n/** Post-storage inputs used to construct a non-self-referential interface ref. */\nexport interface GpuInterfaceRefInput {\n readonly manifest: GpuInterfaceManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Post-storage inputs used to construct a non-self-referential shader ref. */\nexport interface ShaderVersionRefInput {\n readonly manifest: ShaderVersionManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Post-storage inputs used to construct a non-self-referential style ref. */\nexport interface ShaderStyleProfileRefInput {\n readonly manifest: ShaderStyleProfileManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Exact bytes supplied to a typed storage/promotion validation boundary. */\nexport interface GpuAssetFileValidationInput {\n readonly manifest: GpuAssetManifest;\n readonly files: ReadonlyMap<string, Uint8Array>;\n}\n\n/** All schema-driven GPU asset envelopes accepted by the storage pipeline. */\nexport type GpuAssetManifest =\n | ModelAssetManifest\n | GpuInterfaceAssetManifest\n | ShaderAssetManifest\n | ShaderStyleProfileAssetManifest\n | ShaderValidationEvidenceAssetManifest;\n\nexport interface AssetScreenshotPlanItem {\n readonly kind: AssetScreenshotKind;\n readonly label: string;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface AssetReviewFinding {\n readonly severity: AssetReviewSeverity;\n readonly code: string;\n readonly message: string;\n readonly artifactPath?: string;\n readonly evidenceUri?: string;\n}\n\nexport interface AssetReviewReport {\n readonly assetId: string;\n readonly version: string;\n readonly passed: boolean;\n readonly findings: readonly AssetReviewFinding[];\n readonly reviewedAt: string;\n}\n\nexport interface AssetJobRecord {\n readonly jobId: string;\n readonly assetId: string;\n readonly version: string;\n readonly state: AssetJobState;\n readonly sourceAdapter: AssetSourceAdapter;\n readonly requestedAt: string;\n readonly requestedBy: string;\n readonly featureFlagId: string;\n readonly requiredCapability?: string;\n}\n\nexport interface AssetPromotionRecord<TManifest extends AssetManifest = AssetManifest> {\n readonly promotionId: string;\n readonly jobId: string;\n readonly assetId: string;\n readonly version: string;\n readonly sourceAdapter: AssetSourceAdapter;\n readonly outcome: AssetPromotionOutcome;\n readonly manifest: TManifest;\n readonly reviewReport: AssetReviewReport;\n readonly approvedBy: string;\n readonly approvedAt: string;\n readonly promotedAt: string;\n readonly runtimeChannel: string;\n readonly runtimeManifestUri: string;\n readonly rollbackOfVersion?: string;\n}\n\nconst ASSET_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst TOKEN_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._:-]{0,127}$/u;\nconst ASSET_MANIFEST_KEYS = Object.freeze([\n \"assetKind\",\n \"assetId\",\n \"version\",\n \"entrypoint\",\n \"files\",\n \"sourceAdapter\",\n \"createdAt\",\n] as const);\n\nexport function isAssetId(value: unknown): value is string {\n return typeof value === \"string\" && ASSET_ID_PATTERN.test(value);\n}\n\nexport function normalizeAssetId(value: string): string {\n return value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, \"-\").replace(/^-+|-+$/gu, \"\");\n}\n\nexport function assertAssetId(value: unknown): string {\n if (!isAssetId(value)) {\n throw new Error(\"Asset id must use lowercase kebab-case letters and numbers.\");\n }\n return value;\n}\n\nexport function isAssetSourceAdapter(value: unknown): value is AssetSourceAdapter {\n return ASSET_SOURCE_ADAPTERS.includes(value as AssetSourceAdapter);\n}\n\nexport function isAssetKind(value: unknown): value is AssetKind {\n return ASSET_KINDS.includes(value as AssetKind);\n}\n\nexport function isAssetFileRole(value: unknown): value is AssetFileRole {\n return ASSET_FILE_ROLES.includes(value as AssetFileRole);\n}\n\nexport function isAssetJobState(value: unknown): value is AssetJobState {\n return ASSET_JOB_STATES.includes(value as AssetJobState);\n}\n\nexport function isAssetPromotionOutcome(value: unknown): value is AssetPromotionOutcome {\n return ASSET_PROMOTION_OUTCOMES.includes(value as AssetPromotionOutcome);\n}\n\nexport function createAssetFileDescriptor(input: AssetFileDescriptor): AssetFileDescriptor {\n assertRelativeAssetPath(input.path, \"Asset file path\");\n if (!Number.isInteger(input.byteLength) || input.byteLength < 0) {\n throw new Error(\"Asset file byteLength must be a non-negative integer.\");\n }\n if (!SHA256_PATTERN.test(input.sha256)) {\n throw new Error(\"Asset file sha256 must be a lowercase 64-character digest.\");\n }\n if (!input.contentType || input.contentType.trim() !== input.contentType) {\n throw new Error(\"Asset file contentType must be a non-empty canonical value.\");\n }\n if (!isAssetFileRole(input.role)) {\n throw new Error(\"Asset file role is not supported.\");\n }\n if (input.role === \"wgsl\") {\n assertGpuToken(input.moduleId, \"Asset WGSL file moduleId\");\n } else if (input.moduleId !== undefined) {\n throw new Error(\"Asset file moduleId is allowed only for WGSL files.\");\n }\n return Object.freeze({ ...input });\n}\n\nexport function createAssetManifest<TManifest extends AssetManifest>(input: TManifest): TManifest {\n if (input.assetKind !== undefined) {\n throw new Error(\"Typed assets require their specialized manifest factory.\");\n }\n return createBaseAssetManifest(input);\n}\n\nfunction createBaseAssetManifest<TManifest extends AssetManifest>(input: TManifest): TManifest {\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n if (input.assetKind !== undefined && !isAssetKind(input.assetKind)) {\n throw new Error(\"Asset manifest assetKind is not supported.\");\n }\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset manifest sourceAdapter is not supported.\");\n }\n assertRelativeAssetPath(input.entrypoint, \"Asset manifest entrypoint\");\n const files = input.files.map(createAssetFileDescriptor);\n const filePaths = new Set(files.map((file) => file.path));\n if (filePaths.size !== files.length) {\n throw new Error(\"Asset manifest file paths must be unique.\");\n }\n return Object.freeze({\n ...input,\n files: Object.freeze(files),\n }) as TManifest;\n}\n\n/**\n * Creates a model lifecycle manifest whose CPU-side ABI metadata is validated\n * against the canonical GPU-interface reference.\n */\nexport function createModelAssetManifest(input: ModelAssetManifestInput): ModelAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"gpuInterface\",\n \"modelAbiHash\",\n \"providedSemantics\",\n \"defaultStyleProfile\",\n ], \"ModelAssetManifest\");\n const base = createTypedAssetBase(input, \"model\", \"model\");\n assertAllowedFileRoles(base, [\n \"model\",\n \"binary\",\n \"texture\",\n \"manifest\",\n \"screenshot\",\n \"metadata\",\n ]);\n const descriptor = parseModelGpuCompatibilityDescriptor({\n modelId: base.assetId,\n version: base.version,\n gpuInterface: input.gpuInterface,\n modelAbiHash: input.modelAbiHash,\n providedSemantics: input.providedSemantics,\n defaultStyleProfile: input.defaultStyleProfile ?? null,\n });\n assertModelGpuCompatibilityVersions(descriptor);\n return Object.freeze({\n ...base,\n gpuInterface: descriptor.gpuInterface,\n modelAbiHash: descriptor.modelAbiHash,\n providedSemantics: descriptor.providedSemantics,\n defaultStyleProfile: descriptor.defaultStyleProfile,\n });\n}\n\n/** Creates a lifecycle envelope around a strictly parsed reflected interface. */\nexport function createGpuInterfaceAssetManifest(\n input: GpuInterfaceAssetManifest,\n): GpuInterfaceAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"gpuInterfaceManifest\",\n ], \"GpuInterfaceAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"gpu-interface\",\n \"gpu-interface-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"gpu-interface-manifest\"]);\n assertRoleCount(base, \"gpu-interface-manifest\", 1);\n const gpuInterfaceManifest = parseGpuInterfaceManifest(input.gpuInterfaceManifest);\n assertImmutableAssetVersion(gpuInterfaceManifest.interfaceVersion);\n assertDomainIdentity(\n base,\n gpuInterfaceManifest.interfaceId,\n gpuInterfaceManifest.interfaceVersion,\n \"GPU interface\",\n );\n return Object.freeze({ ...base, gpuInterfaceManifest });\n}\n\n/**\n * Creates a shader lifecycle envelope and proves that its complete WGSL file\n * set matches the module digests and sizes in the strict shader manifest.\n */\nexport function createShaderAssetManifest(input: ShaderAssetManifest): ShaderAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"shaderManifest\",\n ], \"ShaderAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader\",\n \"shader-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"shader-manifest\", \"wgsl\"]);\n assertRoleCount(base, \"shader-manifest\", 1);\n const shaderManifest = parseShaderVersionManifest(input.shaderManifest);\n assertShaderManifestVersions(shaderManifest);\n assertDomainIdentity(base, shaderManifest.shaderId, shaderManifest.version, \"Shader\");\n assertShaderModuleFiles(base.files, shaderManifest);\n return Object.freeze({ ...base, shaderManifest });\n}\n\n/** Creates a profile lifecycle envelope with exact immutable shader references. */\nexport function createShaderStyleProfileAssetManifest(\n input: ShaderStyleProfileAssetManifest,\n): ShaderStyleProfileAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"styleProfileManifest\",\n ], \"ShaderStyleProfileAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader-style-profile\",\n \"shader-style-profile-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"shader-style-profile-manifest\"]);\n assertRoleCount(base, \"shader-style-profile-manifest\", 1);\n const styleProfileManifest = parseShaderStyleProfileManifest(input.styleProfileManifest);\n assertStyleProfileManifestVersions(styleProfileManifest);\n assertDomainIdentity(base, styleProfileManifest.profileId, styleProfileManifest.version, \"Style profile\");\n return Object.freeze({ ...base, styleProfileManifest });\n}\n\n/**\n * Creates the storage envelope for qualification evidence. Full evidence-byte,\n * bundle, provenance, and Cartesian-coverage verification remains an admission\n * concern in `@plasius/gpu-shader/testing`.\n */\nexport function createShaderValidationEvidenceAssetManifest(\n input: ShaderValidationEvidenceAssetManifest,\n): ShaderValidationEvidenceAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"validationEvidence\",\n ], \"ShaderValidationEvidenceAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader-validation-evidence\",\n \"shader-validation-evidence\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\n \"shader-validation-evidence\",\n \"shader-validation-attestation\",\n \"shader-qualification-fixture\",\n \"shader-compile-unit-inventory\",\n \"shader-matrix\",\n \"metadata\",\n ]);\n assertRoleCount(base, \"shader-validation-evidence\", 1);\n const validationEvidence = createShaderValidationEvidenceRef(input.validationEvidence);\n if (!isAssetId(validationEvidence.evidenceId) || validationEvidence.evidenceId !== base.assetId) {\n throw new Error(\"Shader validation evidence identity must match the asset identity.\");\n }\n const evidenceFile = requireEntrypoint(base, \"shader-validation-evidence\");\n if (evidenceFile.sha256 !== validationEvidence.sha256) {\n throw new Error(\"Shader validation evidence file digest must match its evidence reference.\");\n }\n const attestationFiles = base.files.filter((file) => file.role === \"shader-validation-attestation\");\n if (attestationFiles.length !== 1\n || attestationFiles[0]?.sha256 !== validationEvidence.attestationRef.sha256\n || attestationFiles[0]?.contentType !== ASSET_JSON_CONTENT_TYPE) {\n throw new Error(\"Shader validation evidence must include its exact attestation file.\");\n }\n return Object.freeze({ ...base, validationEvidence });\n}\n\n/** Strictly validates and freezes a supported universal or additive evidence reference. */\nexport function createShaderValidationEvidenceRef(\n input: ShaderValidationEvidenceRef,\n): ShaderValidationEvidenceRef {\n const value = assertRecord(input, \"ShaderValidationEvidenceRef\");\n assertExactKeys(value, [\n \"evidenceId\",\n \"uri\",\n \"sha256\",\n \"matrixId\",\n \"matrixVersion\",\n \"matrixSha256\",\n \"attestationRef\",\n ], \"ShaderValidationEvidenceRef\");\n const attestation = assertRecord(value.attestationRef, \"ShaderValidationEvidenceRef.attestationRef\");\n assertExactKeys(attestation, [\"uri\", \"sha256\"], \"ShaderValidationEvidenceRef.attestationRef\");\n const result: ShaderValidationEvidenceRef = {\n evidenceId: assertGpuToken(value.evidenceId, \"Shader validation evidence id\"),\n uri: assertImmutableHttpsUri(value.uri, \"Shader validation evidence uri\"),\n sha256: assertSha256(value.sha256, \"Shader validation evidence sha256\"),\n matrixId: assertGpuToken(value.matrixId, \"Shader validation evidence matrixId\"),\n matrixVersion: assertImmutableAssetVersion(value.matrixVersion),\n matrixSha256: assertSha256(value.matrixSha256, \"Shader validation evidence matrixSha256\"),\n attestationRef: Object.freeze({\n uri: assertImmutableHttpsUri(attestation.uri, \"Shader validation evidence attestation uri\"),\n sha256: assertSha256(attestation.sha256, \"Shader validation evidence attestation sha256\"),\n }),\n };\n const supportedUniversal = SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n result.matrixId === policy.matrixId\n && result.matrixVersion === policy.matrixVersion\n && result.matrixSha256 === policy.matrixSha256);\n const supportedAdditive = SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n result.matrixId === policy.matrixId\n && result.matrixVersion === policy.matrixVersion\n && result.matrixSha256 === policy.matrixSha256);\n if (!supportedUniversal && !supportedAdditive) {\n throw new Error(\"Shader validation evidence must target a supported WebGPU matrix policy.\");\n }\n if (result.uri === result.attestationRef.uri || result.sha256 === result.attestationRef.sha256) {\n throw new Error(\"Shader validation evidence and attestation identities must be distinct.\");\n }\n return Object.freeze(result);\n}\n\n/** Constructs an exact interface reference after immutable manifest bytes exist. */\nexport async function createGpuInterfaceRef(input: GpuInterfaceRefInput): Promise<GpuInterfaceRef> {\n assertImmutableAssetVersion(input.manifest.interfaceVersion);\n const manifest = parseGpuInterfaceManifest(input.manifest);\n assertAssetId(manifest.interfaceId);\n assertImmutableAssetVersion(manifest.interfaceVersion);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"GPU interface\");\n return Object.freeze({\n interfaceId: manifest.interfaceId,\n interfaceVersion: manifest.interfaceVersion,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"GPU interface manifest uri\"),\n manifestSha256,\n interfaceAbiHash: manifest.interfaceAbiHash,\n modelAbiHash: manifest.modelAbiHash,\n });\n}\n\n/** Constructs an exact shader-version reference after immutable manifest bytes exist. */\nexport async function createShaderVersionRef(input: ShaderVersionRefInput): Promise<ShaderVersionRef> {\n assertImmutableAssetVersion(input.manifest.version);\n const manifest = parseShaderVersionManifest(input.manifest);\n assertAssetId(manifest.shaderId);\n assertShaderManifestVersions(manifest);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"Shader\");\n return Object.freeze({\n shaderId: manifest.shaderId,\n version: manifest.version,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"Shader manifest uri\"),\n manifestSha256,\n });\n}\n\n/** Constructs an exact style-profile reference after immutable manifest bytes exist. */\nexport async function createShaderStyleProfileRef(\n input: ShaderStyleProfileRefInput,\n): Promise<ShaderStyleProfileRef> {\n assertImmutableAssetVersion(input.manifest.version);\n const manifest = parseShaderStyleProfileManifest(input.manifest);\n assertAssetId(manifest.profileId);\n assertStyleProfileManifestVersions(manifest);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"Style profile\");\n return Object.freeze({\n profileId: manifest.profileId,\n version: manifest.version,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"Style profile manifest uri\"),\n manifestSha256,\n });\n}\n\n/** Revalidates any typed GPU asset envelope at a storage or promotion boundary. */\nexport function createGpuAssetManifest(input: GpuAssetManifest): GpuAssetManifest {\n switch (input.assetKind) {\n case \"model\":\n return createModelAssetManifest(input);\n case \"gpu-interface\":\n return createGpuInterfaceAssetManifest(input);\n case \"shader\":\n return createShaderAssetManifest(input);\n case \"shader-style-profile\":\n return createShaderStyleProfileAssetManifest(input);\n case \"shader-validation-evidence\":\n return createShaderValidationEvidenceAssetManifest(input);\n default:\n throw new Error(\"GPU asset manifest assetKind is not supported.\");\n }\n}\n\n/**\n * Digest-verifies a complete typed asset version and binds canonical JSON\n * entrypoint bytes to the validated interface, shader, or profile object.\n */\nexport async function validateGpuAssetFiles(\n input: GpuAssetFileValidationInput,\n): Promise<GpuAssetManifest> {\n const manifest = createGpuAssetManifest(input.manifest);\n if (input.files.size !== manifest.files.length) {\n throw new Error(\"GPU asset validation requires exactly the declared file set.\");\n }\n for (const path of input.files.keys()) {\n if (!manifest.files.some((file) => file.path === path)) {\n throw new Error(`GPU asset validation received undeclared file ${path}.`);\n }\n }\n await Promise.all(manifest.files.map(async (file) => {\n const bytes = input.files.get(file.path);\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`GPU asset validation is missing bytes for ${file.path}.`);\n }\n if (bytes.byteLength !== file.byteLength) {\n throw new Error(`GPU asset file ${file.path} byte length differs from its descriptor.`);\n }\n if (await computeSha256(bytes) !== file.sha256) {\n throw new Error(`GPU asset file ${file.path} digest differs from its descriptor.`);\n }\n if (file.contentType === ASSET_JSON_CONTENT_TYPE) {\n assertCanonicalJsonBytes(bytes, `GPU asset file ${file.path}`);\n } else if (file.role === \"wgsl\") {\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new Error(`GPU asset WGSL file ${file.path} is not valid UTF-8.`, { cause });\n }\n }\n }));\n\n const entrypointBytes = input.files.get(manifest.entrypoint);\n if (!(entrypointBytes instanceof Uint8Array)) {\n throw new Error(\"GPU asset validation is missing entrypoint bytes.\");\n }\n const expectedDomainManifest = domainManifestForAsset(manifest);\n if (expectedDomainManifest !== null) {\n const parsedEntrypoint = parseJsonBytes(entrypointBytes, \"GPU asset manifest entrypoint\");\n if (canonicalizeGpuContract(parsedEntrypoint) !== canonicalizeGpuContract(expectedDomainManifest)) {\n throw new Error(\"GPU asset entrypoint bytes differ from the validated domain manifest.\");\n }\n } else if (manifest.assetKind === \"shader-validation-evidence\") {\n assertEvidenceEntrypointIdentity(\n parseJsonBytes(entrypointBytes, \"Shader validation evidence entrypoint\"),\n manifest.validationEvidence,\n );\n }\n return manifest;\n}\n\nexport function createStandardScreenshotPlan(\n width = 1600,\n height = 1000\n): readonly AssetScreenshotPlanItem[] {\n return Object.freeze(\n ASSET_SCREENSHOT_KINDS.map((kind) =>\n Object.freeze({\n kind,\n label: kind.replace(/-/gu, \" \"),\n width,\n height,\n })\n )\n );\n}\n\nexport function createAssetReviewReport(input: AssetReviewReport): AssetReviewReport {\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n return Object.freeze({\n ...input,\n findings: Object.freeze(input.findings.map((finding) => Object.freeze({ ...finding }))),\n });\n}\n\nexport function createAssetJobRecord(input: AssetJobRecord): AssetJobRecord {\n assertToken(input.jobId, \"Asset job id\");\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n if (!isAssetJobState(input.state)) {\n throw new Error(\"Asset job state is not supported.\");\n }\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset job sourceAdapter is not supported.\");\n }\n assertRequiredString(input.requestedAt, \"Asset job requestedAt\");\n assertRequiredString(input.requestedBy, \"Asset job requestedBy\");\n assertToken(input.featureFlagId, \"Asset job featureFlagId\");\n if (input.requiredCapability !== undefined) {\n assertToken(input.requiredCapability, \"Asset job requiredCapability\");\n }\n return Object.freeze({ ...input });\n}\n\nexport function createAssetPromotionRecord<TManifest extends AssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n): AssetPromotionRecord<TManifest> {\n if (input.manifest.assetKind !== undefined) {\n throw new Error(\"Typed GPU assets require createGpuAssetPromotionRecord with the complete file bytes.\");\n }\n return createValidatedPromotionRecord(input, createAssetManifest(input.manifest));\n}\n\n/** Digest-verifies and promotes a typed GPU asset without a generic-factory bypass. */\nexport async function createGpuAssetPromotionRecord<TManifest extends GpuAssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n files: ReadonlyMap<string, Uint8Array>,\n): Promise<AssetPromotionRecord<TManifest>> {\n const manifest = await validateGpuAssetFiles({ manifest: input.manifest, files }) as TManifest;\n assertTypedRuntimeManifestUri(manifest, input.runtimeManifestUri);\n return createValidatedPromotionRecord(input, manifest);\n}\n\nfunction createValidatedPromotionRecord<TManifest extends AssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n manifest: TManifest,\n): AssetPromotionRecord<TManifest> {\n const assertPromotionVersion = manifest.assetKind === undefined\n ? assertAssetVersion\n : assertImmutableAssetVersion;\n assertToken(input.promotionId, \"Asset promotion id\");\n assertToken(input.jobId, \"Asset promotion job id\");\n assertAssetId(input.assetId);\n assertPromotionVersion(input.version);\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset promotion sourceAdapter is not supported.\");\n }\n if (!isAssetPromotionOutcome(input.outcome)) {\n throw new Error(\"Asset promotion outcome is not supported.\");\n }\n\n if (manifest.assetId !== input.assetId || manifest.version !== input.version) {\n throw new Error(\"Asset promotion manifest must match the promoted asset id and version.\");\n }\n\n const reviewReport = createAssetReviewReport(input.reviewReport);\n if (reviewReport.assetId !== input.assetId || reviewReport.version !== input.version) {\n throw new Error(\"Asset promotion reviewReport must match the promoted asset id and version.\");\n }\n\n assertRequiredString(input.approvedBy, \"Asset promotion approvedBy\");\n assertRequiredString(input.approvedAt, \"Asset promotion approvedAt\");\n assertRequiredString(input.promotedAt, \"Asset promotion promotedAt\");\n assertRequiredString(input.runtimeChannel, \"Asset promotion runtimeChannel\");\n assertRequiredString(input.runtimeManifestUri, \"Asset promotion runtimeManifestUri\");\n if (input.rollbackOfVersion !== undefined) {\n assertPromotionVersion(input.rollbackOfVersion);\n }\n\n return Object.freeze({\n ...input,\n manifest,\n reviewReport,\n });\n}\n\nfunction createTypedAssetBase<K extends AssetKind>(\n input: AssetManifest,\n assetKind: K,\n entrypointRole: AssetFileRole,\n entrypointContentType?: string,\n): TypedAssetManifest<K> {\n if (input.assetKind !== assetKind) {\n throw new Error(`Asset manifest assetKind must be ${assetKind}.`);\n }\n assertImmutableAssetVersion(input.version);\n const base = createBaseAssetManifest({\n assetKind,\n assetId: input.assetId,\n version: input.version,\n entrypoint: input.entrypoint,\n files: input.files,\n sourceAdapter: input.sourceAdapter,\n createdAt: input.createdAt,\n });\n const entrypoint = requireEntrypoint(base, entrypointRole);\n if (entrypointContentType !== undefined && entrypoint.contentType !== entrypointContentType) {\n throw new Error(`Asset manifest ${entrypointRole} entrypoint must use ${entrypointContentType}.`);\n }\n return base;\n}\n\nfunction requireEntrypoint(\n manifest: AssetManifest,\n expectedRole: AssetFileRole,\n): AssetFileDescriptor {\n const matches = manifest.files.filter((file) => file.path === manifest.entrypoint);\n if (matches.length !== 1 || matches[0]?.role !== expectedRole) {\n throw new Error(`Asset manifest entrypoint must identify exactly one ${expectedRole} file.`);\n }\n return matches[0];\n}\n\nfunction assertDomainIdentity(\n manifest: AssetManifest,\n domainId: string,\n domainVersion: string,\n label: string,\n): void {\n if (!isAssetId(domainId) || domainId !== manifest.assetId || domainVersion !== manifest.version) {\n throw new Error(`${label} identity and version must match the lifecycle asset identity and version.`);\n }\n}\n\nfunction assertGpuInterfaceRefVersion(ref: GpuInterfaceRef): void {\n assertImmutableAssetVersion(ref.interfaceVersion);\n}\n\nfunction assertShaderEvidenceVersion(ref: ShaderValidationEvidenceRef): void {\n assertImmutableAssetVersion(ref.matrixVersion);\n}\n\nfunction assertShaderManifestVersions(manifest: ShaderVersionManifest): void {\n assertImmutableAssetVersion(manifest.version);\n assertGpuInterfaceRefVersion(manifest.gpuInterface);\n for (const compatibleInterface of manifest.compatibleModelInterfaces) {\n assertImmutableAssetVersion(compatibleInterface.interfaceVersion);\n }\n assertShaderEvidenceVersion(manifest.validationEvidence);\n for (const scopedEvidence of manifest.additionalValidationEvidence) {\n assertShaderEvidenceVersion(scopedEvidence.evidence);\n }\n}\n\nfunction assertStyleProfileManifestVersions(manifest: ShaderStyleProfileManifest): void {\n assertImmutableAssetVersion(manifest.version);\n for (const role of manifest.roles) {\n assertImmutableAssetVersion(role.shader.version);\n }\n for (const compatibleInterface of manifest.compatibleModelInterfaces) {\n assertImmutableAssetVersion(compatibleInterface.interfaceVersion);\n }\n for (const scope of manifest.requiredValidationScopes) {\n assertImmutableAssetVersion(scope.matrixVersion);\n }\n}\n\nfunction assertModelGpuCompatibilityVersions(descriptor: ModelGpuCompatibilityDescriptor): void {\n assertImmutableAssetVersion(descriptor.version);\n assertGpuInterfaceRefVersion(descriptor.gpuInterface);\n if (descriptor.defaultStyleProfile !== null) {\n assertImmutableAssetVersion(descriptor.defaultStyleProfile.version);\n }\n}\n\nfunction assertShaderModuleFiles(\n files: readonly AssetFileDescriptor[],\n shaderManifest: ShaderVersionManifest,\n): void {\n const moduleFiles = files.filter((file) => file.role === \"wgsl\");\n const moduleFileIds = new Set(moduleFiles.map((file) => file.moduleId));\n if (moduleFiles.length !== shaderManifest.modules.length\n || moduleFileIds.size !== moduleFiles.length) {\n throw new Error(\"Shader asset must contain exactly one uniquely mapped WGSL file per shader module.\");\n }\n for (const module of shaderManifest.modules) {\n const file = moduleFiles.find((candidate) => candidate.moduleId === module.moduleId);\n if (!file\n || file.sha256 !== module.sha256\n || file.byteLength !== module.byteLength\n || file.contentType !== module.contentType) {\n throw new Error(\"Shader asset WGSL module files must exactly match the shader manifest module IDs, digests, sizes, and content types.\");\n }\n const moduleUri = new URL(module.uri);\n const pathSuffix = `/${file.path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (!moduleUri.pathname.endsWith(pathSuffix)) {\n throw new Error(\"Shader module URI paths must identify their mapped immutable WGSL asset files.\");\n }\n }\n}\n\nfunction assertAllowedFileRoles(\n manifest: AssetManifest,\n allowedRoles: readonly AssetFileRole[],\n): void {\n const allowed = new Set(allowedRoles);\n const unexpected = manifest.files.find((file) => !allowed.has(file.role));\n if (unexpected) {\n throw new Error(`${manifest.assetKind ?? \"legacy\"} assets do not allow ${unexpected.role} files.`);\n }\n}\n\nfunction domainManifestForAsset(\n manifest: GpuAssetManifest,\n): GpuInterfaceManifest | ShaderVersionManifest | ShaderStyleProfileManifest | null {\n switch (manifest.assetKind) {\n case \"gpu-interface\":\n return manifest.gpuInterfaceManifest;\n case \"shader\":\n return manifest.shaderManifest;\n case \"shader-style-profile\":\n return manifest.styleProfileManifest;\n case \"model\":\n case \"shader-validation-evidence\":\n return null;\n }\n}\n\nfunction assertTypedRuntimeManifestUri(manifest: GpuAssetManifest, value: string): void {\n const runtimeUri = new URL(assertImmutableHttpsUri(value, \"GPU asset runtimeManifestUri\"));\n if (manifest.assetKind === \"shader-validation-evidence\") {\n if (runtimeUri.href !== manifest.validationEvidence.uri) {\n throw new Error(\"Evidence promotion URI must equal its exact validation-evidence URI.\");\n }\n return;\n }\n if (manifest.assetKind === \"model\") return;\n\n const entrypointSuffix = `/${manifest.entrypoint.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (!runtimeUri.pathname.endsWith(entrypointSuffix)) {\n throw new Error(\"Typed GPU promotion URI must identify the validated manifest entrypoint.\");\n }\n if (manifest.assetKind === \"shader\") {\n const runtimeDirectory = runtimeUri.pathname.slice(0, -entrypointSuffix.length);\n for (const module of manifest.shaderManifest.modules) {\n const moduleUri = new URL(module.uri);\n const moduleFile = manifest.files.find((file) =>\n file.role === \"wgsl\" && file.moduleId === module.moduleId);\n if (!moduleFile) {\n throw new Error(`Shader module ${module.moduleId} has no mapped WGSL file.`);\n }\n const moduleSuffix = `/${moduleFile.path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (moduleUri.origin !== runtimeUri.origin\n || moduleUri.pathname.slice(0, -moduleSuffix.length) !== runtimeDirectory) {\n throw new Error(\"Shader module and manifest URIs must share one immutable version root.\");\n }\n }\n }\n}\n\nfunction assertEvidenceEntrypointIdentity(\n value: unknown,\n ref: ShaderValidationEvidenceRef,\n): void {\n const evidence = assertRecord(value, \"Shader validation evidence entrypoint\");\n if (evidence.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION\n || evidence.evidenceId !== ref.evidenceId\n || evidence.status !== \"passed\") {\n throw new Error(\"Shader validation evidence bytes do not identify passing declared evidence.\");\n }\n const matrixRef = assertRecord(evidence.matrixRef, \"Shader validation evidence matrixRef\");\n if (matrixRef.matrixId !== ref.matrixId\n || matrixRef.version !== ref.matrixVersion\n || matrixRef.sha256 !== ref.matrixSha256) {\n throw new Error(\"Shader validation evidence bytes differ from the declared matrix identity.\");\n }\n const counts = assertRecord(evidence.counts, \"Shader validation evidence counts\");\n const compileUnits = counts.compileUnits as number;\n const cells = counts.cells as number;\n const expectedResults = counts.expectedResults as number;\n if (!Number.isSafeInteger(compileUnits)\n || !Number.isSafeInteger(cells)\n || !Number.isSafeInteger(expectedResults)\n || !Number.isSafeInteger(counts.passedResults)\n || compileUnits <= 0\n || cells <= 0\n || expectedResults !== compileUnits * cells\n || counts.passedResults !== expectedResults) {\n throw new Error(\"Shader validation evidence bytes do not declare complete passing result counts.\");\n }\n}\n\nfunction assertCanonicalJsonBytes(bytes: Uint8Array, fieldName: string): void {\n const value = parseJsonBytes(bytes, fieldName);\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n if (canonicalizeGpuContract(value) !== text) {\n throw new Error(`${fieldName} must use canonical JSON serialization.`);\n }\n}\n\nasync function bindDomainManifestBytes(\n bytes: Uint8Array,\n manifest: GpuInterfaceManifest | ShaderVersionManifest | ShaderStyleProfileManifest,\n fieldName: string,\n): Promise<Sha256Hex> {\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`${fieldName} manifest bytes must be a Uint8Array.`);\n }\n assertCanonicalJsonBytes(bytes, `${fieldName} manifest`);\n const parsed = parseJsonBytes(bytes, `${fieldName} manifest`);\n if (canonicalizeGpuContract(parsed) !== canonicalizeGpuContract(manifest)) {\n throw new Error(`${fieldName} manifest bytes differ from the supplied manifest.`);\n }\n return computeSha256(bytes);\n}\n\nfunction assertRoleCount(\n manifest: AssetManifest,\n role: AssetFileRole,\n expectedCount: number,\n): void {\n if (manifest.files.filter((file) => file.role === role).length !== expectedCount) {\n throw new Error(`Asset manifest must contain exactly ${expectedCount} ${role} file(s).`);\n }\n}\n\nfunction assertExactKeys(\n value: object,\n allowed: readonly string[],\n fieldName: string,\n): void {\n const allowedSet = new Set(allowed);\n const unexpected = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unexpected.length > 0) {\n throw new Error(`${fieldName} contains unsupported fields: ${unexpected.join(\", \")}.`);\n }\n}\n\nfunction assertRecord(value: unknown, fieldName: string): Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`${fieldName} must be an object.`);\n }\n return value as Readonly<Record<string, unknown>>;\n}\n\nfunction assertSha256(value: unknown, fieldName: string): Sha256Hex {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a lowercase 64-character digest.`);\n }\n return value as Sha256Hex;\n}\n\nfunction assertGpuToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\"\n || value.length === 0\n || value.length > 160\n || !/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u.test(value)\n || value.includes(\"..\")) {\n throw new Error(`${fieldName} must be a safe GPU contract token.`);\n }\n return value;\n}\n\nfunction assertRelativeAssetPath(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\"\n || value.length === 0\n || value.length > 1024\n || value.startsWith(\"/\")\n || value.includes(\"\\\\\")\n || value.includes(\":\")\n || value.includes(\"%\")\n || value.includes(\"..\")\n || value.includes(\"?\")\n || value.includes(\"#\")\n || value.trim() !== value\n || value.split(\"/\").some((segment) => segment.length === 0 || segment === \".\")\n || [...value].some((character) => character.charCodeAt(0) <= 0x1f)) {\n throw new Error(`${fieldName} must be a normalized relative POSIX path without traversal or a URI scheme.`);\n }\n return value;\n}\n\nfunction assertImmutableHttpsUri(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > 2048) {\n throw new Error(`${fieldName} must be an absolute immutable asset URI.`);\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch (cause) {\n throw new Error(`${fieldName} must be an absolute immutable asset URI.`, { cause });\n }\n if (parsed.protocol !== \"https:\" || parsed.username || parsed.password || parsed.hash) {\n throw new Error(`${fieldName} must be credential-free HTTPS without a fragment.`);\n }\n const queryKeys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());\n const forbidden = new Set([\n \"sig\",\n \"se\",\n \"sp\",\n \"sv\",\n \"spr\",\n \"st\",\n \"skoid\",\n \"sktid\",\n \"skt\",\n \"ske\",\n \"sks\",\n \"skv\",\n ]);\n if (queryKeys.some((key) => forbidden.has(key)) || new Set(queryKeys).size !== queryKeys.length) {\n throw new Error(`${fieldName} must not contain SAS credentials or duplicate query parameters.`);\n }\n if (parsed.href !== value) {\n throw new Error(`${fieldName} must use canonical URL serialization.`);\n }\n return value;\n}\n\nfunction assertToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !TOKEN_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a non-empty token up to 128 characters.`);\n }\n return value;\n}\n\nfunction assertRequiredString(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return value;\n}\n","const ASSET_VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;\n\nconst MUTABLE_VERSION_ALIASES = new Set([\n \"latest\",\n \"current\",\n \"stable\",\n \"preview\",\n \"default\",\n \"production\",\n \"canary\",\n \"next\",\n \"head\",\n \"main\",\n]);\n\nconst X_WILDCARD_SEGMENT_PATTERN = /^(?:[vV])?[xX](?:\\.|-|$)|\\.[xX](?:\\.|-|$)/u;\nconst IMMUTABLE_VERSION_ERROR_MESSAGE =\n \"Immutable asset version must be an exact token up to 128 characters; mutable aliases, ranges, wildcards, and URLs are not allowed.\";\n\n/**\n * Validates the legacy asset-version token grammar.\n *\n * This intentionally permits workflow labels such as `latest`; callers that\n * identify immutable assets must use {@link assertImmutableAssetVersion}.\n */\nexport function assertAssetVersion(value: unknown): string {\n if (typeof value !== \"string\" || !ASSET_VERSION_PATTERN.test(value)) {\n throw new Error(\"Asset version must be a non-empty token up to 128 characters.\");\n }\n return value;\n}\n\n/**\n * Validates an immutable, reproducible asset version.\n *\n * The error is deliberately constant and does not interpolate untrusted input,\n * keeping diagnostics stable and bounded at storage and runtime boundaries.\n */\nexport function assertImmutableAssetVersion(value: unknown): string {\n if (typeof value !== \"string\"\n || !ASSET_VERSION_PATTERN.test(value)\n || MUTABLE_VERSION_ALIASES.has(value.toLowerCase())\n || X_WILDCARD_SEGMENT_PATTERN.test(value)) {\n throw new Error(IMMUTABLE_VERSION_ERROR_MESSAGE);\n }\n return value;\n}\n","import { assertImmutableAssetVersion } from \"./asset-version.js\";\n\n/** Version identifier carried by every top-level model-resolution contract. */\nexport const MODEL_RESOLUTION_CONTRACT_VERSION = \"2026-07-12.v1\" as const;\n\n/** Maximum request revision accepted by the v1 contract. */\nexport const MODEL_REQUEST_MAX_REVISION = 3 as const;\n\n/** Assurance thresholds used by every model ranker calibration. */\nexport const MODEL_MATCH_ASSURANCE_THRESHOLDS = Object.freeze({\n high: 0.75,\n low: 0.5,\n} as const);\n\n/** Stable assurance bands for catalog and provider matches. */\nexport const MODEL_MATCH_ASSURANCE_BANDS = Object.freeze([\n \"high\",\n \"low\",\n \"none\",\n] as const);\n\n/** Evidence available to the ranker when it produced a match assessment. */\nexport const MODEL_RANKER_EVIDENCE_MODES = Object.freeze([\n \"text-only\",\n \"vision\",\n \"multimodal\",\n \"exact-identifier\",\n] as const);\n\n/** Audit reason added when a text-only ranker is capped below its raw score band. */\nexport const MODEL_TEXT_ONLY_ASSURANCE_CEILING_REASON_CODE = \"text-only-assurance-ceiling\" as const;\n\n/** Audit reason added when another declared ranker ceiling lowers assurance. */\nexport const MODEL_RANKER_ASSURANCE_CEILING_REASON_CODE = \"ranker-assurance-ceiling\" as const;\n\n/** Authenticated original views required before a candidate can be confirmed. */\nexport const MODEL_CONFIRMATION_VIEW_KINDS = Object.freeze([\n \"front\",\n \"left\",\n \"top\",\n \"isometric\",\n] as const);\n\n/** Required width and height for authenticated confirmation originals. */\nexport const MODEL_CONFIRMATION_VIEW_SIZE_PX = 1024 as const;\n\n/** Exact asynchronous model-resolution states shared with orchestration packages. */\nexport const MODEL_RESOLUTION_STATES = Object.freeze([\n \"searching-catalog\",\n \"searching-providers\",\n \"awaiting-provider-auth\",\n \"quarantining\",\n \"processing\",\n \"rendering\",\n \"evaluating\",\n \"awaiting-rights-review\",\n \"awaiting-confirmation\",\n \"promoting\",\n \"completed\",\n \"unresolved\",\n \"failed\",\n \"cancelled\",\n] as const);\n\n/** Canonical runtime model kinds. */\nexport const MODEL_ASSET_KINDS = Object.freeze([\"leaf\", \"assembly\"] as const);\n\n/** Stable origins for catalog, provider, and future generated candidates. */\nexport const MODEL_PROVENANCE_KINDS = Object.freeze([\n \"catalog\",\n \"provider\",\n \"generated\",\n] as const);\n\n/** Fail-closed rights states used before confirmation or promotion. */\nexport const MODEL_RIGHTS_STATUSES = Object.freeze([\n \"allowed\",\n \"attribution-required\",\n \"quarantined\",\n \"blocked\",\n] as const);\n\n/** Canonical output coordinate system for processed models. */\nexport const CANONICAL_MODEL_COORDINATE_SYSTEM = Object.freeze({\n unit: \"metre\",\n upAxis: \"Y\",\n forwardAxis: \"-Z\",\n origin: \"floor-centred\",\n outwardFaceWinding: \"counter-clockwise\",\n} as const);\n\n/** Fail-closed v1 runtime limits; callers may only tighten these values. */\nexport const STATIC_WORLD_V1_MODEL_POLICY = Object.freeze({\n id: \"static-world-v1\",\n maxTriangles: 1_000_000,\n maxBytes: 100 * 1024 * 1024,\n maxTextureBytes: 64 * 1024 * 1024,\n maxTextureDimensionPx: 4096,\n maxPartitionCellMetres: 32,\n} as const);\n\n/** Independent attestations required before a semantic confirmation can proceed. */\nexport const MODEL_CANDIDATE_HARD_GATE_KINDS = Object.freeze([\n \"malware-scan\",\n \"technical-validation\",\n \"human-review\",\n \"accessibility-review\",\n] as const);\n\n/** Stable reason returned by the disabled Phase 1 generator port. */\nexport const MODEL_GENERATOR_DISABLED_REASON_CODE = \"phase-1-generator-disabled\" as const;\n\n/** Match assurance derived from score and the independent hard-constraint gate. */\nexport type ModelMatchAssurance = typeof MODEL_MATCH_ASSURANCE_BANDS[number];\n\n/** Evidence family retained with each ranker assessment. */\nexport type ModelRankerEvidenceMode = typeof MODEL_RANKER_EVIDENCE_MODES[number];\n\n/** A required confirmation-view identifier. */\nexport type ModelConfirmationViewKind = typeof MODEL_CONFIRMATION_VIEW_KINDS[number];\n\n/** A state in the asynchronous model-resolution lifecycle. */\nexport type ModelResolutionState = typeof MODEL_RESOLUTION_STATES[number];\n\n/** Whether an immutable asset is a single leaf or a composed assembly. */\nexport type ModelAssetKind = typeof MODEL_ASSET_KINDS[number];\n\n/** Where a candidate originated. */\nexport type ModelProvenanceKind = typeof MODEL_PROVENANCE_KINDS[number];\n\n/** Rights eligibility applied before human confirmation. */\nexport type ModelRightsStatus = typeof MODEL_RIGHTS_STATUSES[number];\n\n/** One independent non-semantic confirmation gate. */\nexport type ModelCandidateHardGateKind = typeof MODEL_CANDIDATE_HARD_GATE_KINDS[number];\n\n/** Required/optional/forbidden policy for LOD or collision requirements. */\nexport type ModelRequirementPolicy = \"required\" | \"optional\" | \"forbidden\";\n\n/** Whether runtime packaging must remain single, may partition, or must partition. */\nexport type ModelPartitionPolicy = \"single\" | \"allowed\" | \"required\";\n\n/** A canonical three-dimensional vector. */\nexport type ModelVector3 = readonly [number, number, number];\n\n/** A canonical quaternion in x/y/z/w order. */\nexport type ModelQuaternion = readonly [number, number, number, number];\n\n/** Axis-aligned bounds expressed in metres. */\nexport interface ModelBoundsMetres {\n readonly min: ModelVector3;\n readonly max: ModelVector3;\n}\n\n/** Width, height, and depth expressed in metres. */\nexport interface ModelDimensionsMetres {\n readonly width: number;\n readonly height: number;\n readonly depth: number;\n}\n\n/** Hard request constraints that must pass independently of semantic rank. */\nexport interface ModelHardConstraints {\n readonly boundsMetres?: ModelBoundsMetres;\n readonly dimensionsMetres?: ModelDimensionsMetres;\n readonly maxTriangles?: number;\n readonly maxBytes?: number;\n readonly maxTextureBytes?: number;\n readonly maxTextureDimensionPx?: number;\n readonly maxPartitionCellMetres?: number;\n readonly lod?: ModelRequirementPolicy;\n readonly collision?: ModelRequirementPolicy;\n readonly partition?: ModelPartitionPolicy;\n}\n\n/** Soft ranking preferences that may improve score but never bypass hard constraints. */\nexport interface ModelSoftPreferences {\n readonly category?: string;\n readonly style?: string;\n readonly materials?: readonly string[];\n readonly colors?: readonly string[];\n readonly era?: string;\n readonly condition?: string;\n readonly tags?: readonly string[];\n}\n\n/** Immutable normalized natural-language request for a model. */\nexport interface ModelRequestSpec {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly policyProfileId: typeof STATIC_WORLD_V1_MODEL_POLICY.id;\n readonly query: string;\n readonly revision: number;\n readonly locale?: string;\n readonly rankerId?: string;\n readonly hardConstraints: ModelHardConstraints;\n readonly softPreferences: ModelSoftPreferences;\n readonly exclusions: readonly string[];\n}\n\n/** Versioned ranker and calibration evidence attached to an assessment. */\nexport interface ModelRankerRef {\n readonly id: string;\n readonly version: string;\n readonly calibrationId: string;\n readonly calibrationVersion: string;\n readonly evidenceMode: ModelRankerEvidenceMode;\n readonly assuranceCeiling: ModelMatchAssurance;\n}\n\n/** Immutable model match assessment with a derived assurance band. */\nexport interface ModelMatchAssessment {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly score: number;\n readonly assurance: ModelMatchAssurance;\n readonly hardConstraintPass: boolean;\n readonly exactMatch: boolean;\n readonly reasonCodes: readonly string[];\n readonly ranker: ModelRankerRef;\n readonly fidelityWarnings: readonly string[];\n readonly request: ModelRequestSpec;\n readonly candidateId: string;\n readonly candidateContentHash: string;\n}\n\n/** Deterministic result of comparing one normalized request with one candidate. */\nexport interface ModelHardConstraintEvaluation {\n readonly pass: boolean;\n readonly reasonCodes: readonly string[];\n}\n\n/** Runtime facts used to evaluate request constraints. */\nexport interface ModelTechnicalProfile {\n readonly boundsMetres: ModelBoundsMetres;\n readonly dimensionsMetres: ModelDimensionsMetres;\n readonly triangleCount: number;\n readonly byteLength: number;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n readonly lodCount: number;\n readonly hasCollision: boolean;\n readonly partitionCount: number;\n readonly partitionCellMetres: number;\n}\n\n/** Attribution content used by accessible model acknowledgements. */\nexport interface ModelAttribution {\n readonly title: string;\n readonly creator: string;\n readonly notice: string;\n readonly sourcePageUri?: string;\n}\n\n/** Fail-closed rights assessment for a candidate. */\nexport interface ModelRightsAssessment {\n readonly decisionId: string;\n readonly decisionToken: string;\n readonly policyId: string;\n readonly policyVersion: string;\n readonly sourceId: string;\n readonly sourceAssetId: string;\n readonly sourceContentHash: string;\n readonly status: ModelRightsStatus;\n readonly licenseId: string;\n readonly evidencePageUri: string;\n readonly attribution?: ModelAttribution;\n readonly reviewedAt: string;\n}\n\n/** Public-safe provenance without download or signed staging URLs. */\nexport interface ModelProvenance {\n readonly kind: ModelProvenanceKind;\n readonly sourceId: string;\n readonly sourceAssetId: string;\n readonly sourcePageUri?: string;\n readonly contentHash: string;\n readonly capturedAt: string;\n}\n\n/** Immutable promoted model reference safe for player-facing responses. */\nexport interface ModelAssetRef {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly assetId: string;\n readonly version: string;\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly runtimeManifestUri: string;\n}\n\n/** Existing promoted candidate identity. */\nexport interface ExistingModelCandidateAssetRef {\n readonly disposition: \"existing\";\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly asset: ModelAssetRef;\n}\n\n/** Staged proposal identity without exposing its private resource location. */\nexport interface ProposedModelCandidateAssetRef {\n readonly disposition: \"proposed\";\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly proposalId: string;\n}\n\n/** Candidate identity before or after catalog promotion. */\nexport type ModelCandidateAssetRef =\n | ExistingModelCandidateAssetRef\n | ProposedModelCandidateAssetRef;\n\n/** Authenticated square original used during mandatory human confirmation. */\nexport interface ModelConfirmationView {\n readonly kind: ModelConfirmationViewKind;\n readonly imageUri: string;\n readonly sha256: string;\n readonly contentType: \"image/png\";\n readonly width: typeof MODEL_CONFIRMATION_VIEW_SIZE_PX;\n readonly height: typeof MODEL_CONFIRMATION_VIEW_SIZE_PX;\n}\n\n/** Deterministic renderer/camera attestation covering the exact four-view pack. */\nexport interface ModelRenderEvidence {\n readonly renderId: string;\n readonly rendererId: string;\n readonly rendererVersion: string;\n readonly settingsId: string;\n readonly settingsVersion: string;\n readonly processingManifestId: string;\n readonly sourceContentHash: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly renderedAt: string;\n readonly attestationToken: string;\n}\n\n/** Versioned, signed evidence for a non-semantic confirmation gate. */\nexport interface ModelCandidateHardGateEvidence {\n readonly kind: ModelCandidateHardGateKind;\n readonly outcome: \"passed\" | \"blocked\";\n readonly validatorId: string;\n readonly validatorVersion: string;\n readonly subjectContentHash: string;\n readonly reasonCodes: readonly string[];\n readonly evaluatedAt: string;\n readonly attestationToken: string;\n}\n\n/** Exact four-view confirmation tuple in canonical order. */\nexport type ModelConfirmationViews = readonly [\n ModelConfirmationView,\n ModelConfirmationView,\n ModelConfirmationView,\n ModelConfirmationView,\n];\n\n/** Immutable candidate returned by catalog/provider/generator resolution. */\nexport interface ModelCandidate {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly assetRef: ModelCandidateAssetRef;\n readonly match: ModelMatchAssessment;\n readonly provenance: ModelProvenance;\n readonly rights: ModelRightsAssessment;\n readonly technicalProfile: ModelTechnicalProfile;\n readonly processingManifest: ModelProcessingManifest;\n readonly views: ModelConfirmationViews;\n readonly renderEvidence: ModelRenderEvidence;\n readonly hardGates: readonly ModelCandidateHardGateEvidence[];\n readonly confirmationToken: string;\n readonly confirmationRequired: true;\n}\n\n/** Public-safe resource reference used by processing evidence. */\nexport interface ModelResourceRef {\n readonly uri: string;\n readonly byteLength: number;\n readonly sha256: string;\n readonly contentType: string;\n}\n\n/** Adaptive LOD level; LOD0 is always present and up to LOD3 may follow. */\nexport type ModelLodLevel = 0 | 1 | 2 | 3;\n\n/** Processed resource and triangle evidence for one LOD level. */\nexport interface ModelLodRecord {\n readonly level: ModelLodLevel;\n readonly resource: ModelResourceRef;\n readonly triangleCount: number;\n readonly geometricErrorMetres: number;\n}\n\n/** Collision representation emitted by processing. */\nexport type ModelCollisionKind =\n | \"none\"\n | \"box\"\n | \"convex-hull\"\n | \"triangle-mesh\"\n | \"compound\";\n\n/** Collision evidence, with a resource for every non-empty collision kind. */\nexport interface ModelCollisionRecord {\n readonly kind: ModelCollisionKind;\n readonly resource?: ModelResourceRef;\n}\n\n/** Canonical transform for an assembly child. */\nexport interface ModelTransform {\n readonly translationMetres: ModelVector3;\n readonly rotationQuaternion: ModelQuaternion;\n readonly scale: ModelVector3;\n}\n\n/** Candidate-scoped immutable reference for a not-yet-promoted derived leaf. */\nexport interface StagedModelAssemblyChildRef {\n readonly disposition: \"staged-derived\";\n readonly derivedId: string;\n readonly kind: \"leaf\";\n readonly contentHash: string;\n readonly processingManifestUri: string;\n}\n\n/** Catalog or staged-derived leaf identity accepted in an assembly closure. */\nexport type ModelAssemblyChildAssetRef = ModelAssetRef | StagedModelAssemblyChildRef;\n\n/** Immutable child reference, optional hierarchy parent, and local transform. */\nexport interface ModelAssemblyChild {\n readonly instanceId: string;\n readonly parentInstanceId?: string;\n readonly assetRef: ModelAssemblyChildAssetRef;\n readonly transform: ModelTransform;\n}\n\n/** Severity for conversion diagnostics and fidelity losses. */\nexport type ModelDiagnosticSeverity = \"info\" | \"warning\" | \"blocking\";\n\n/** Structured diagnostic emitted by a converter. */\nexport interface ModelConverterDiagnostic {\n readonly severity: ModelDiagnosticSeverity;\n readonly code: string;\n readonly message: string;\n}\n\n/** Explicit semantic loss recorded during conversion. */\nexport interface ModelConversionLoss {\n readonly code: string;\n readonly severity: ModelDiagnosticSeverity;\n readonly message: string;\n}\n\n/** Converter identity, hashes, diagnostics, and loss evidence. */\nexport interface ModelConverterEvidence {\n readonly id: string;\n readonly version: string;\n readonly sourceFormat: string;\n readonly targetFormat: string;\n readonly sourceContentHash: string;\n readonly outputContentHash: string;\n readonly diagnostics: readonly ModelConverterDiagnostic[];\n readonly losses: readonly ModelConversionLoss[];\n}\n\n/** Fidelity aspect assessed after conversion. */\nexport type ModelFidelityAspect =\n | \"geometry\"\n | \"materials\"\n | \"textures\"\n | \"rigging\"\n | \"animation\"\n | \"metadata\";\n\n/** Fidelity result for a converted aspect. */\nexport type ModelFidelityOutcome = \"preserved\" | \"approximated\" | \"lost\";\n\n/** Structured fidelity evidence suitable for review. */\nexport interface ModelFidelityEvidence {\n readonly aspect: ModelFidelityAspect;\n readonly outcome: ModelFidelityOutcome;\n readonly message: string;\n readonly evidenceResource?: ModelResourceRef;\n}\n\n/** Signed category-policy decision requiring a collision proxy or allowing none. */\nexport interface ModelCollisionPolicyEvidence {\n readonly profileId: string;\n readonly profileVersion: string;\n readonly disposition: \"proxy-required\" | \"none-allowed\";\n readonly category: string;\n readonly decisionToken: string;\n}\n\n/** Signed fidelity-policy result that independently gates semantic assurance. */\nexport interface ModelFidelityGateEvidence {\n readonly profileId: string;\n readonly profileVersion: string;\n readonly outcome: \"passed\" | \"low-only\" | \"blocked\";\n readonly requiredAspects: readonly [\"geometry\", \"materials\", \"textures\"];\n readonly evaluatedAt: string;\n readonly decisionToken: string;\n}\n\n/** Canonical, immutable model-processing manifest. */\nexport interface ModelProcessingManifest {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly manifestId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly closureHash: string;\n readonly coordinateSystem: typeof CANONICAL_MODEL_COORDINATE_SYSTEM;\n readonly technicalProfile: ModelTechnicalProfile;\n readonly lods: readonly ModelLodRecord[];\n readonly collision: ModelCollisionRecord;\n readonly collisionPolicy: ModelCollisionPolicyEvidence;\n readonly children: readonly ModelAssemblyChild[];\n readonly converter: ModelConverterEvidence;\n readonly fidelityEvidence: readonly ModelFidelityEvidence[];\n readonly fidelityGate: ModelFidelityGateEvidence;\n readonly processedAt: string;\n}\n\n/** Immutable evidence that one requester confirmed one exact candidate render pack. */\nexport interface ModelCandidateConfirmation {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly confirmationId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly confirmationToken: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly confirmedBy: string;\n readonly confirmedAt: string;\n readonly semanticRiskAccepted: boolean;\n}\n\n/** Backend-issued receipt binding one staged proposal closure to its final catalog identity. */\nexport interface ModelPromotionReceipt {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly promotionId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly proposalId: string;\n readonly confirmationId: string;\n readonly processingManifestId: string;\n readonly processingContentHash: string;\n readonly closureHash: string;\n readonly finalAssetRef: ModelAssetRef;\n readonly promotedAt: string;\n readonly publicationToken: string;\n}\n\n/** Immutable record for one asynchronous model-resolution request. */\nexport interface ModelResolution {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly request: ModelRequestSpec;\n readonly attempts: number;\n readonly state: ModelResolutionState;\n readonly candidates: readonly ModelCandidate[];\n readonly bestCandidate?: ModelCandidate;\n readonly confirmation?: ModelCandidateConfirmation;\n readonly promotionReceipt?: ModelPromotionReceipt;\n readonly refinementQuestions: readonly string[];\n readonly finalAssetRef?: ModelAssetRef;\n readonly stateReasonCode?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/** Bounded compute and output budgets accepted by a generator port. */\nexport interface ModelGeneratorBudgets {\n readonly maxDurationMs: number;\n readonly maxTriangles: number;\n readonly maxBytes: number;\n readonly maxTextureBytes: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Normalized request passed to a model generator implementation. */\nexport interface ModelGeneratorRequest {\n readonly generationId: string;\n readonly request: ModelRequestSpec;\n readonly budgets: ModelGeneratorBudgets;\n readonly seed: string;\n readonly deadline: string;\n}\n\n/** Disabled Phase 1 generator result. */\nexport interface DisabledModelGeneratorResult {\n readonly status: \"disabled\";\n readonly generationId: string;\n readonly reasonCode: typeof MODEL_GENERATOR_DISABLED_REASON_CODE;\n}\n\n/** Versioned generator identity retained with source-bundle evidence. */\nexport interface ModelGeneratorIdentity {\n readonly id: string;\n readonly version: string;\n}\n\n/** Bounded internal artifacts emitted for normal ingestion by an enabled generator. */\nexport type ModelGeneratorArtifactRole =\n | \"model-entrypoint\"\n | \"model-dependency\"\n | \"binary\"\n | \"texture\"\n | \"metadata\";\n\n/** One generated artifact and its closed ingestion role. */\nexport interface ModelGeneratorArtifact extends ModelResourceRef {\n readonly role: ModelGeneratorArtifactRole;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Measured generator use checked against the invocation budgets. */\nexport interface ModelGeneratorUsage {\n readonly durationMs: number;\n readonly triangleCount: number;\n readonly byteLength: number;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Request-bound source bundle submitted to the normal quarantine and ingestion path. */\nexport interface ModelGeneratorSourceBundle {\n readonly bundleId: string;\n readonly generationId: string;\n readonly entrypointUri: string;\n readonly artifacts: readonly ModelGeneratorArtifact[];\n readonly generator: ModelGeneratorIdentity;\n readonly generatedAt: string;\n readonly seed: string;\n readonly context: ModelGeneratorRequest;\n readonly usage: ModelGeneratorUsage;\n}\n\n/** Successful generator result consumed by the normal processing pipeline. */\nexport interface GeneratedModelGeneratorResult {\n readonly status: \"generated\";\n readonly generationId: string;\n readonly sourceBundle: ModelGeneratorSourceBundle;\n}\n\n/** Stable reasons an enabled generator may be temporarily or permanently unavailable. */\nexport type ModelGeneratorUnavailableReason =\n | \"capacity-unavailable\"\n | \"provider-unavailable\"\n | \"authentication-required\"\n | \"rate-limited\"\n | \"unsupported-request\";\n\n/** Stable generator execution or output-validation failure reasons. */\nexport type ModelGeneratorFailureReason =\n | \"provider-failed\"\n | \"invalid-generator-output\"\n | \"internal-failure\";\n\n/** Stable reasons a generator invocation ended without producing an output. */\nexport type ModelGeneratorCancellationReason =\n | \"caller-aborted\"\n | \"deadline-exceeded\"\n | \"superseded\"\n | \"service-shutdown\";\n\ninterface ModelGeneratorTerminalEvidence {\n readonly generationId: string;\n readonly retryable: boolean;\n readonly occurredAt: string;\n readonly diagnosticId?: string;\n}\n\n/** Request-bound unavailable outcome with stable retryability. */\nexport interface UnavailableModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"unavailable\";\n readonly reasonCode: ModelGeneratorUnavailableReason;\n}\n\n/** Request-bound failed outcome without raw provider error disclosure. */\nexport interface FailedModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"failed\";\n readonly reasonCode: ModelGeneratorFailureReason;\n}\n\n/** Request-bound cancellation outcome. */\nexport interface CancelledModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"cancelled\";\n readonly reasonCode: ModelGeneratorCancellationReason;\n}\n\n/** Name of one bounded generator resource dimension. */\nexport type ModelGeneratorBudgetName = keyof ModelGeneratorBudgets;\n\n/** Exact observed value that exceeded one invocation budget. */\nexport interface ModelGeneratorBudgetViolation {\n readonly budget: ModelGeneratorBudgetName;\n readonly limit: number;\n readonly observed: number;\n}\n\n/** Fail-closed outcome carrying no partial source bundle. */\nexport interface BudgetExceededModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"budget-exceeded\";\n readonly reasonCode: \"generator-budget-exceeded\";\n readonly retryable: false;\n readonly violations: readonly ModelGeneratorBudgetViolation[];\n}\n\n/** Stable result union shared by disabled Phase 1 and future enabled generators. */\nexport type ModelGeneratorResult =\n | DisabledModelGeneratorResult\n | GeneratedModelGeneratorResult\n | UnavailableModelGeneratorResult\n | FailedModelGeneratorResult\n | CancelledModelGeneratorResult\n | BudgetExceededModelGeneratorResult;\n\n/** Optional cancellation context for generator calls. */\nexport interface ModelGeneratorCallOptions {\n readonly signal?: AbortSignal;\n}\n\n/** Generator boundary; Phase 1 supplies only a disabled implementation. */\nexport interface ModelGeneratorPort {\n readonly enabled: boolean;\n generate(\n input: ModelGeneratorRequest,\n options?: ModelGeneratorCallOptions,\n ): Promise<ModelGeneratorResult>;\n}\n\nconst ASSET_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;\nconst TOKEN_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._:-]{0,127}$/u;\nconst CONFIRMATION_TOKEN_PATTERN = /^[0-9A-Za-z_-]{32,256}$/u;\nconst OPAQUE_SOURCE_ASSET_ID_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,255}$/u;\nconst MODEL_PATH_SEGMENT_PATTERN = /^[0-9A-Za-z._~-]+$/u;\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst CONTENT_TYPE_PATTERN = /^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/iu;\nconst URL_LIKE_PATTERN = /(?:https?:\\/\\/|\\bwww\\.)/iu;\nconst ENCODED_PATH_PATTERN = /%(?:2e|2f|5c|25)/iu;\nconst MAX_QUERY_LENGTH = 512;\nconst MAX_TEXT_LENGTH = 512;\nconst MAX_LIST_LENGTH = 32;\nconst MAX_CANDIDATES = 50;\nconst MAX_ATTEMPTS = 100;\nconst MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES = 1e-6;\nconst MODEL_MATCH_ASSURANCE_ORDER: Readonly<Record<ModelMatchAssurance, number>> = Object.freeze({\n none: 0,\n low: 1,\n high: 2,\n});\n\nfunction deepFreeze<T>(value: T): T {\n if (value !== null && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child);\n }\n Object.freeze(value);\n }\n return value;\n}\n\nfunction assertRecord(value: unknown, fieldName: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${fieldName} must be an object.`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${fieldName} must be a plain object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction assertAllowedKeys(\n record: Record<string, unknown>,\n allowedKeys: readonly string[],\n fieldName: string,\n): void {\n const unexpected = Object.keys(record).find((key) => !allowedKeys.includes(key));\n if (unexpected !== undefined) {\n throw new Error(`${fieldName} contains unexpected field ${unexpected}.`);\n }\n}\n\nfunction assertContractVersion(record: Record<string, unknown>, fieldName: string): void {\n if (\n record.contractVersion !== undefined\n && record.contractVersion !== MODEL_RESOLUTION_CONTRACT_VERSION\n ) {\n throw new Error(`${fieldName} contractVersion is not supported.`);\n }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n return [...value].some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 31 || codePoint === 127;\n });\n}\n\nfunction requiredString(\n value: unknown,\n fieldName: string,\n maxLength = MAX_TEXT_LENGTH,\n): string {\n if (typeof value !== \"string\") {\n throw new Error(`${fieldName} must be a string.`);\n }\n const normalized = value.trim().replace(/\\s+/gu, \" \");\n if (normalized.length === 0 || normalized.length > maxLength || hasControlCharacters(normalized)) {\n throw new Error(`${fieldName} must be a non-empty bounded string.`);\n }\n return normalized;\n}\n\nfunction optionalString(\n value: unknown,\n fieldName: string,\n maxLength = MAX_TEXT_LENGTH,\n): string | undefined {\n return value === undefined ? undefined : requiredString(value, fieldName, maxLength);\n}\n\nfunction assertNoDirectUrl(value: string, fieldName: string): void {\n if (URL_LIKE_PATTERN.test(value)) {\n throw new Error(`${fieldName} must not contain a direct URL.`);\n }\n}\n\nfunction requiredToken(value: unknown, fieldName: string): string {\n const token = requiredString(value, fieldName, 128);\n if (!TOKEN_PATTERN.test(token)) {\n throw new Error(`${fieldName} must be a token up to 128 characters.`);\n }\n return token;\n}\n\nfunction requiredModelPathSegment(value: unknown, fieldName: string): string {\n const segment = requiredString(value, fieldName, 128);\n if (\n !MODEL_PATH_SEGMENT_PATTERN.test(segment)\n || segment === \".\"\n || segment === \"..\"\n ) {\n throw new Error(`${fieldName} must be a canonical model URI path segment.`);\n }\n return segment;\n}\n\nfunction requiredAttestationToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !CONFIRMATION_TOKEN_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a bounded opaque signed token.`);\n }\n return value;\n}\n\nfunction requiredSha256(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a lowercase 64-character sha256 digest.`);\n }\n return value;\n}\n\nfunction requiredInteger(\n value: unknown,\n fieldName: string,\n minimum: number,\n maximum: number,\n): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new Error(`${fieldName} must be an integer between ${minimum} and ${maximum}.`);\n }\n return value as number;\n}\n\nfunction requiredFiniteNumber(\n value: unknown,\n fieldName: string,\n minimum: number,\n maximum = Number.MAX_VALUE,\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < minimum || value > maximum) {\n throw new Error(`${fieldName} must be a finite number between ${minimum} and ${maximum}.`);\n }\n return value;\n}\n\nfunction requiredBoolean(value: unknown, fieldName: string): boolean {\n if (typeof value !== \"boolean\") {\n throw new Error(`${fieldName} must be a boolean.`);\n }\n return value;\n}\n\nfunction requiredTimestamp(value: unknown, fieldName: string): string {\n const timestamp = requiredString(value, fieldName, 64);\n const parsed = new Date(timestamp);\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/u.test(timestamp) || Number.isNaN(parsed.getTime())) {\n throw new Error(`${fieldName} must be a valid UTC RFC3339 timestamp.`);\n }\n const withoutSuffix = timestamp.slice(0, -1);\n const [wholeSeconds, fractionalSeconds = \"\"] = withoutSuffix.split(\".\");\n const canonicalInput = `${wholeSeconds}.${fractionalSeconds.padEnd(3, \"0\")}Z`;\n const canonicalTimestamp = parsed.toISOString();\n if (canonicalTimestamp !== canonicalInput) {\n throw new Error(`${fieldName} must be a valid UTC RFC3339 timestamp.`);\n }\n return canonicalTimestamp;\n}\n\nfunction requiredEnum<T extends string>(\n value: unknown,\n values: readonly T[],\n fieldName: string,\n): T {\n if (typeof value !== \"string\" || !values.includes(value as T)) {\n throw new Error(`${fieldName} is not supported.`);\n }\n return value as T;\n}\n\nfunction stringList(\n value: unknown,\n fieldName: string,\n options: { readonly tokens?: boolean; readonly maxItems?: number } = {},\n): readonly string[] {\n if (!Array.isArray(value)) {\n throw new Error(`${fieldName} must be an array.`);\n }\n const maxItems = options.maxItems ?? MAX_LIST_LENGTH;\n if (value.length > maxItems) {\n throw new Error(`${fieldName} must contain at most ${maxItems} items.`);\n }\n const items = value.map((item, index) => {\n const normalized = options.tokens\n ? requiredToken(item, `${fieldName}[${index}]`)\n : requiredString(item, `${fieldName}[${index}]`, 128);\n assertNoDirectUrl(normalized, `${fieldName}[${index}]`);\n return normalized;\n });\n const normalizedKeys = new Set(items.map((item) => item.toLocaleLowerCase(\"en-GB\")));\n if (normalizedKeys.size !== items.length) {\n throw new Error(`${fieldName} must not contain duplicate values.`);\n }\n return items;\n}\n\nfunction requiredVector3(value: unknown, fieldName: string, positive = false): ModelVector3 {\n if (!Array.isArray(value) || value.length !== 3) {\n throw new Error(`${fieldName} must contain exactly three numbers.`);\n }\n return [\n requiredFiniteNumber(value[0], `${fieldName}[0]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n requiredFiniteNumber(value[1], `${fieldName}[1]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n requiredFiniteNumber(value[2], `${fieldName}[2]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n ];\n}\n\nfunction createBounds(value: unknown, fieldName: string): ModelBoundsMetres {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"min\", \"max\"], fieldName);\n const min = requiredVector3(record.min, `${fieldName}.min`);\n const max = requiredVector3(record.max, `${fieldName}.max`);\n if (min.some((axis, index) => axis >= max[index]!)) {\n throw new Error(`${fieldName} min axes must be lower than max axes.`);\n }\n return { min, max };\n}\n\nfunction createDimensions(value: unknown, fieldName: string): ModelDimensionsMetres {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"width\", \"height\", \"depth\"], fieldName);\n return {\n width: requiredFiniteNumber(record.width, `${fieldName}.width`, Number.EPSILON),\n height: requiredFiniteNumber(record.height, `${fieldName}.height`, Number.EPSILON),\n depth: requiredFiniteNumber(record.depth, `${fieldName}.depth`, Number.EPSILON),\n };\n}\n\nfunction assertModelUri(value: unknown, fieldName: string): string {\n const uri = requiredString(value, fieldName, 2048);\n const canonicalPrefix = \"mcp://models/\";\n if (\n !uri.startsWith(canonicalPrefix)\n || uri.includes(\"\\\\\")\n || uri.includes(\"?\")\n || uri.includes(\"#\")\n || ENCODED_PATH_PATTERN.test(uri)\n ) {\n throw new Error(\n `${fieldName} must be a canonical traversal-free mcp://models URI without query or fragment.`,\n );\n }\n const rawSegments = uri.slice(canonicalPrefix.length).split(\"/\");\n if (\n rawSegments.length === 0\n || rawSegments.some((segment) =>\n segment.length === 0\n || segment === \".\"\n || segment === \"..\"\n || !MODEL_PATH_SEGMENT_PATTERN.test(segment))\n ) {\n throw new Error(`${fieldName} must be a canonical traversal-free mcp://models URI.`);\n }\n let parsed: URL;\n try {\n parsed = new URL(uri);\n } catch {\n throw new Error(`${fieldName} must be a valid mcp://models URI.`);\n }\n if (\n parsed.protocol !== \"mcp:\"\n || parsed.hostname !== \"models\"\n || parsed.port.length > 0\n || parsed.username.length > 0\n || parsed.password.length > 0\n || parsed.search.length > 0\n || parsed.hash.length > 0\n ) {\n throw new Error(`${fieldName} must be a credential-free mcp://models URI.`);\n }\n if (parsed.href !== uri) {\n throw new Error(`${fieldName} must use canonical mcp://models serialization.`);\n }\n return uri;\n}\n\nfunction isPrivateHostname(hostname: string): boolean {\n const lowerHostname = hostname.toLowerCase();\n if (lowerHostname.endsWith(\".\")) {\n return true;\n }\n const normalized = lowerHostname.replace(/^\\[|\\]$/gu, \"\");\n if (\n normalized === \"localhost\"\n || normalized.endsWith(\".localhost\")\n || normalized.endsWith(\".local\")\n || normalized.endsWith(\".internal\")\n || normalized.endsWith(\".lan\")\n || normalized.endsWith(\".home\")\n || normalized.endsWith(\".arpa\")\n || normalized.endsWith(\".nip.io\")\n || normalized.endsWith(\".sslip.io\")\n || normalized === \"localtest.me\"\n || normalized.endsWith(\".localtest.me\")\n ) {\n return true;\n }\n if (normalized.includes(\":\")) {\n if (\n normalized === \"::\"\n || normalized === \"::1\"\n || normalized.startsWith(\"::ffff:\")\n || normalized.startsWith(\"fc\")\n || normalized.startsWith(\"fd\")\n || /^(?:fe8|fe9|fea|feb)/u.test(normalized)\n || normalized.startsWith(\"ff\")\n || normalized.startsWith(\"2001:db8:\")\n ) {\n return true;\n }\n const firstHextet = Number.parseInt(normalized.split(\":\", 1)[0] ?? \"\", 16);\n return !Number.isInteger(firstHextet) || firstHextet < 0x2000 || firstHextet > 0x3fff;\n }\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/u.exec(normalized);\n if (!match) {\n return !normalized.includes(\".\");\n }\n const octets = match.slice(1).map(Number);\n return octets.some((octet) => octet > 255)\n || octets[0] === 0\n || octets[0] === 10\n || (octets[0] === 100 && (octets[1] ?? 0) >= 64 && (octets[1] ?? 0) <= 127)\n || octets[0] === 127\n || (octets[0] === 169 && octets[1] === 254)\n || (octets[0] === 172 && (octets[1] ?? 0) >= 16 && (octets[1] ?? 0) <= 31)\n || (octets[0] === 192 && octets[1] === 0 && octets[2] === 0)\n || (octets[0] === 192 && octets[1] === 0 && octets[2] === 2)\n || (octets[0] === 192 && octets[1] === 168)\n || (octets[0] === 198 && (octets[1] === 18 || octets[1] === 19))\n || (octets[0] === 198 && octets[1] === 51 && octets[2] === 100)\n || (octets[0] === 203 && octets[1] === 0 && octets[2] === 113)\n || (octets[0] ?? 0) >= 224;\n}\n\nfunction assertPublicPageUri(value: unknown, fieldName: string): string {\n const uri = requiredString(value, fieldName, 2048);\n let parsed: URL;\n try {\n parsed = new URL(uri);\n } catch {\n throw new Error(`${fieldName} must be a valid public HTTPS page URI.`);\n }\n if (\n parsed.protocol !== \"https:\"\n || parsed.username.length > 0\n || parsed.password.length > 0\n || parsed.hostname.length === 0\n || uri.includes(\"?\")\n || uri.includes(\"#\")\n || isPrivateHostname(parsed.hostname)\n ) {\n throw new Error(`${fieldName} must be a credential-free public HTTPS page URI.`);\n }\n return uri;\n}\n\nfunction assetId(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !ASSET_ID_PATTERN.test(value)) {\n throw new Error(`${fieldName} must use lowercase kebab-case letters and numbers.`);\n }\n return value;\n}\n\nfunction assetVersion(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !VERSION_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a non-empty version token up to 128 characters.`);\n }\n return value;\n}\n\nfunction opaqueSourceAssetId(value: unknown, fieldName = \"ModelProvenance.sourceAssetId\"): string {\n if (typeof value !== \"string\" || !OPAQUE_SOURCE_ASSET_ID_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be an opaque bounded token.`);\n }\n return value;\n}\n\nfunction createHardConstraints(value: unknown): ModelHardConstraints {\n const record = value === undefined\n ? {}\n : assertRecord(value, \"ModelRequestSpec.hardConstraints\");\n assertAllowedKeys(record, [\n \"boundsMetres\",\n \"dimensionsMetres\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n \"maxPartitionCellMetres\",\n \"lod\",\n \"collision\",\n \"partition\",\n ], \"ModelRequestSpec.hardConstraints\");\n const result: {\n boundsMetres?: ModelBoundsMetres;\n dimensionsMetres?: ModelDimensionsMetres;\n maxTriangles?: number;\n maxBytes?: number;\n maxTextureBytes?: number;\n maxTextureDimensionPx?: number;\n maxPartitionCellMetres?: number;\n lod?: ModelRequirementPolicy;\n collision?: ModelRequirementPolicy;\n partition?: ModelPartitionPolicy;\n } = {\n maxTriangles: STATIC_WORLD_V1_MODEL_POLICY.maxTriangles,\n maxBytes: STATIC_WORLD_V1_MODEL_POLICY.maxBytes,\n maxTextureBytes: STATIC_WORLD_V1_MODEL_POLICY.maxTextureBytes,\n maxTextureDimensionPx: STATIC_WORLD_V1_MODEL_POLICY.maxTextureDimensionPx,\n maxPartitionCellMetres: STATIC_WORLD_V1_MODEL_POLICY.maxPartitionCellMetres,\n lod: \"optional\",\n collision: \"optional\",\n partition: \"allowed\",\n };\n if (record.boundsMetres !== undefined) {\n result.boundsMetres = createBounds(record.boundsMetres, \"ModelRequestSpec.hardConstraints.boundsMetres\");\n }\n if (record.dimensionsMetres !== undefined) {\n result.dimensionsMetres = createDimensions(record.dimensionsMetres, \"ModelRequestSpec.hardConstraints.dimensionsMetres\");\n }\n if (record.maxTriangles !== undefined) {\n result.maxTriangles = requiredInteger(\n record.maxTriangles,\n \"ModelRequestSpec.hardConstraints.maxTriangles\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTriangles,\n );\n }\n if (record.maxBytes !== undefined) {\n result.maxBytes = requiredInteger(\n record.maxBytes,\n \"ModelRequestSpec.hardConstraints.maxBytes\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxBytes,\n );\n }\n if (record.maxTextureBytes !== undefined) {\n result.maxTextureBytes = requiredInteger(\n record.maxTextureBytes,\n \"ModelRequestSpec.hardConstraints.maxTextureBytes\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTextureBytes,\n );\n }\n if (record.maxTextureDimensionPx !== undefined) {\n result.maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelRequestSpec.hardConstraints.maxTextureDimensionPx\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTextureDimensionPx,\n );\n }\n if (record.maxPartitionCellMetres !== undefined) {\n result.maxPartitionCellMetres = requiredFiniteNumber(\n record.maxPartitionCellMetres,\n \"ModelRequestSpec.hardConstraints.maxPartitionCellMetres\",\n Number.EPSILON,\n STATIC_WORLD_V1_MODEL_POLICY.maxPartitionCellMetres,\n );\n }\n if (record.lod !== undefined) {\n result.lod = requiredEnum(record.lod, [\"required\", \"optional\", \"forbidden\"] as const, \"ModelRequestSpec.hardConstraints.lod\");\n }\n if (record.collision !== undefined) {\n result.collision = requiredEnum(record.collision, [\"required\", \"optional\", \"forbidden\"] as const, \"ModelRequestSpec.hardConstraints.collision\");\n }\n if (record.partition !== undefined) {\n result.partition = requiredEnum(record.partition, [\"single\", \"allowed\", \"required\"] as const, \"ModelRequestSpec.hardConstraints.partition\");\n }\n if (record.maxTextureBytes === undefined && result.maxBytes !== undefined) {\n result.maxTextureBytes = Math.min(result.maxTextureBytes ?? result.maxBytes, result.maxBytes);\n }\n if (\n result.maxBytes !== undefined\n && result.maxTextureBytes !== undefined\n && result.maxTextureBytes > result.maxBytes\n ) {\n throw new Error(\"ModelRequestSpec hardConstraints maxTextureBytes must not exceed maxBytes.\");\n }\n if (result.boundsMetres !== undefined && result.dimensionsMetres !== undefined) {\n const boundsDimensions = result.boundsMetres.max.map(\n (axis, index) => axis - result.boundsMetres!.min[index]!,\n );\n const suppliedDimensions = [\n result.dimensionsMetres.width,\n result.dimensionsMetres.height,\n result.dimensionsMetres.depth,\n ];\n if (boundsDimensions.some((axis, index) =>\n Math.abs(axis - suppliedDimensions[index]!) > Math.max(1e-6, Math.abs(axis) * 1e-6))) {\n throw new Error(\"ModelRequestSpec hardConstraints dimensionsMetres must match boundsMetres.\");\n }\n }\n return result;\n}\n\nfunction createSoftPreferences(value: unknown): ModelSoftPreferences {\n if (value === undefined) {\n return {};\n }\n const record = assertRecord(value, \"ModelRequestSpec.softPreferences\");\n assertAllowedKeys(record, [\n \"category\",\n \"style\",\n \"materials\",\n \"colors\",\n \"era\",\n \"condition\",\n \"tags\",\n ], \"ModelRequestSpec.softPreferences\");\n const result: {\n category?: string;\n style?: string;\n materials?: readonly string[];\n colors?: readonly string[];\n era?: string;\n condition?: string;\n tags?: readonly string[];\n } = {};\n for (const field of [\"category\", \"style\", \"era\", \"condition\"] as const) {\n const normalized = optionalString(record[field], `ModelRequestSpec.softPreferences.${field}`, 80);\n if (normalized !== undefined) {\n assertNoDirectUrl(normalized, `ModelRequestSpec.softPreferences.${field}`);\n result[field] = normalized;\n }\n }\n for (const field of [\"materials\", \"colors\", \"tags\"] as const) {\n if (record[field] !== undefined) {\n result[field] = stringList(record[field], `ModelRequestSpec.softPreferences.${field}`);\n }\n }\n return result;\n}\n\n/** Validate and normalize an unknown model request payload. */\nexport function createModelRequestSpec(input: unknown): ModelRequestSpec {\n const record = assertRecord(input, \"ModelRequestSpec\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"policyProfileId\",\n \"query\",\n \"revision\",\n \"locale\",\n \"rankerId\",\n \"hardConstraints\",\n \"softPreferences\",\n \"exclusions\",\n ], \"ModelRequestSpec\");\n assertContractVersion(record, \"ModelRequestSpec\");\n if (\n record.policyProfileId !== undefined\n && record.policyProfileId !== STATIC_WORLD_V1_MODEL_POLICY.id\n ) {\n throw new Error(\"ModelRequestSpec.policyProfileId must be static-world-v1.\");\n }\n const query = requiredString(record.query, \"ModelRequestSpec.query\", MAX_QUERY_LENGTH);\n assertNoDirectUrl(query, \"ModelRequestSpec.query\");\n const revision = requiredInteger(\n record.revision,\n `ModelRequestSpec revision (maximum ${MODEL_REQUEST_MAX_REVISION})`,\n 0,\n MODEL_REQUEST_MAX_REVISION,\n );\n let locale: string | undefined;\n if (record.locale !== undefined) {\n const requestedLocale = requiredString(record.locale, \"ModelRequestSpec.locale\", 64);\n try {\n [locale] = Intl.getCanonicalLocales(requestedLocale);\n } catch {\n throw new Error(\"ModelRequestSpec.locale must be a valid BCP 47 locale.\");\n }\n if (locale === undefined) {\n throw new Error(\"ModelRequestSpec.locale must be a valid BCP 47 locale.\");\n }\n }\n const rankerId = record.rankerId === undefined\n ? undefined\n : requiredToken(record.rankerId, \"ModelRequestSpec.rankerId\");\n const result: ModelRequestSpec = {\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n policyProfileId: STATIC_WORLD_V1_MODEL_POLICY.id,\n query,\n revision,\n ...(locale === undefined ? {} : { locale }),\n ...(rankerId === undefined ? {} : { rankerId }),\n hardConstraints: createHardConstraints(record.hardConstraints),\n softPreferences: createSoftPreferences(record.softPreferences),\n exclusions: record.exclusions === undefined\n ? []\n : stringList(record.exclusions, \"ModelRequestSpec.exclusions\"),\n };\n return deepFreeze(result);\n}\n\nfunction deriveRawModelMatchAssurance(score: number, exactMatch: boolean): ModelMatchAssurance {\n if (exactMatch || score >= MODEL_MATCH_ASSURANCE_THRESHOLDS.high) {\n return \"high\";\n }\n if (score >= MODEL_MATCH_ASSURANCE_THRESHOLDS.low) {\n return \"low\";\n }\n return \"none\";\n}\n\n/** Derive an assurance band while independently failing closed on hard constraints. */\nexport function classifyModelMatchAssurance(\n score: number,\n hardConstraintPass: boolean,\n evidenceMode: ModelRankerEvidenceMode,\n exactMatch: boolean,\n assuranceCeiling: ModelMatchAssurance,\n): ModelMatchAssurance {\n requiredFiniteNumber(score, \"Model match score\", 0, 1);\n requiredBoolean(hardConstraintPass, \"Model match hardConstraintPass\");\n requiredEnum(evidenceMode, MODEL_RANKER_EVIDENCE_MODES, \"Model match evidenceMode\");\n requiredBoolean(exactMatch, \"Model match exactMatch\");\n requiredEnum(assuranceCeiling, MODEL_MATCH_ASSURANCE_BANDS, \"Model match assuranceCeiling\");\n if (evidenceMode === \"text-only\" && exactMatch) {\n throw new Error(\"Model match exactMatch must be false for text-only evidence.\");\n }\n if (evidenceMode === \"text-only\" && assuranceCeiling === \"high\") {\n throw new Error(\"Model match text-only assuranceCeiling must be low or none.\");\n }\n if (evidenceMode === \"exact-identifier\" && !exactMatch) {\n throw new Error(\"Model match exact-identifier evidence requires exactMatch true.\");\n }\n if (evidenceMode !== \"exact-identifier\" && evidenceMode !== \"text-only\" && exactMatch) {\n throw new Error(\"Model match exactMatch requires exact-identifier evidence.\");\n }\n if (!hardConstraintPass) {\n return \"none\";\n }\n const rawAssurance = deriveRawModelMatchAssurance(score, exactMatch);\n return MODEL_MATCH_ASSURANCE_ORDER[rawAssurance] <= MODEL_MATCH_ASSURANCE_ORDER[assuranceCeiling]\n ? rawAssurance\n : assuranceCeiling;\n}\n\nfunction createRankerRef(value: unknown): ModelRankerRef {\n const record = assertRecord(value, \"ModelMatchAssessment.ranker\");\n assertAllowedKeys(record, [\n \"id\",\n \"version\",\n \"calibrationId\",\n \"calibrationVersion\",\n \"evidenceMode\",\n \"assuranceCeiling\",\n ], \"ModelMatchAssessment.ranker\");\n return {\n id: requiredToken(record.id, \"ModelMatchAssessment.ranker.id\"),\n version: assetVersion(record.version, \"ModelMatchAssessment.ranker.version\"),\n calibrationId: requiredToken(record.calibrationId, \"ModelMatchAssessment.ranker.calibrationId\"),\n calibrationVersion: assetVersion(record.calibrationVersion, \"ModelMatchAssessment.ranker.calibrationVersion\"),\n evidenceMode: requiredEnum(\n record.evidenceMode,\n MODEL_RANKER_EVIDENCE_MODES,\n \"ModelMatchAssessment.ranker.evidenceMode\",\n ),\n assuranceCeiling: requiredEnum(\n record.assuranceCeiling,\n MODEL_MATCH_ASSURANCE_BANDS,\n \"ModelMatchAssessment.ranker.assuranceCeiling\",\n ),\n };\n}\n\n/** Validate and freeze an unknown match assessment payload. */\nexport function createModelMatchAssessment(input: unknown): ModelMatchAssessment {\n const record = assertRecord(input, \"ModelMatchAssessment\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"score\",\n \"assurance\",\n \"hardConstraintPass\",\n \"exactMatch\",\n \"reasonCodes\",\n \"ranker\",\n \"fidelityWarnings\",\n \"request\",\n \"candidateId\",\n \"candidateContentHash\",\n ], \"ModelMatchAssessment\");\n assertContractVersion(record, \"ModelMatchAssessment\");\n const score = requiredFiniteNumber(record.score, \"ModelMatchAssessment.score\", 0, 1);\n const hardConstraintPass = requiredBoolean(record.hardConstraintPass, \"ModelMatchAssessment.hardConstraintPass\");\n const exactMatch = requiredBoolean(record.exactMatch, \"ModelMatchAssessment.exactMatch\");\n const ranker = createRankerRef(record.ranker);\n const request = createModelRequestSpec(record.request);\n if (request.rankerId !== undefined && request.rankerId !== ranker.id) {\n throw new Error(\"ModelMatchAssessment ranker.id must match the caller-selected request rankerId.\");\n }\n if (record.assurance !== undefined) {\n requiredEnum(record.assurance, MODEL_MATCH_ASSURANCE_BANDS, \"ModelMatchAssessment.assurance\");\n }\n let reasonCodes = stringList(record.reasonCodes, \"ModelMatchAssessment.reasonCodes\", {\n tokens: true,\n });\n if (!hardConstraintPass && reasonCodes.length === 0) {\n throw new Error(\"ModelMatchAssessment.reasonCodes must explain a failed hard constraint.\");\n }\n const assurance = classifyModelMatchAssurance(\n score,\n hardConstraintPass,\n ranker.evidenceMode,\n exactMatch,\n ranker.assuranceCeiling,\n );\n const rawAssurance = deriveRawModelMatchAssurance(score, exactMatch);\n if (\n hardConstraintPass\n && MODEL_MATCH_ASSURANCE_ORDER[assurance] < MODEL_MATCH_ASSURANCE_ORDER[rawAssurance]\n ) {\n const ceilingReason = ranker.evidenceMode === \"text-only\"\n ? MODEL_TEXT_ONLY_ASSURANCE_CEILING_REASON_CODE\n : MODEL_RANKER_ASSURANCE_CEILING_REASON_CODE;\n if (!reasonCodes.includes(ceilingReason)) {\n if (reasonCodes.length >= MAX_LIST_LENGTH) {\n throw new Error(\n `ModelMatchAssessment.reasonCodes must contain at most ${MAX_LIST_LENGTH} items including the assurance ceiling reason.`,\n );\n }\n reasonCodes = [...reasonCodes, ceilingReason];\n }\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n score,\n assurance,\n hardConstraintPass,\n exactMatch,\n reasonCodes,\n ranker,\n fidelityWarnings: stringList(record.fidelityWarnings ?? [], \"ModelMatchAssessment.fidelityWarnings\"),\n request,\n candidateId: requiredToken(record.candidateId, \"ModelMatchAssessment.candidateId\"),\n candidateContentHash: requiredSha256(\n record.candidateContentHash,\n \"ModelMatchAssessment.candidateContentHash\",\n ),\n });\n}\n\n/** Validate and freeze technical facts about a processed candidate. */\nexport function createModelTechnicalProfile(input: unknown): ModelTechnicalProfile {\n const record = assertRecord(input, \"ModelTechnicalProfile\");\n assertAllowedKeys(record, [\n \"boundsMetres\",\n \"dimensionsMetres\",\n \"triangleCount\",\n \"byteLength\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n \"lodCount\",\n \"hasCollision\",\n \"partitionCount\",\n \"partitionCellMetres\",\n ], \"ModelTechnicalProfile\");\n const boundsMetres = createBounds(record.boundsMetres, \"ModelTechnicalProfile.boundsMetres\");\n const dimensionsMetres = createDimensions(record.dimensionsMetres, \"ModelTechnicalProfile.dimensionsMetres\");\n const derivedDimensions = boundsMetres.max.map((axis, index) => axis - boundsMetres.min[index]!) as [number, number, number];\n const suppliedDimensions = [dimensionsMetres.width, dimensionsMetres.height, dimensionsMetres.depth];\n if (derivedDimensions.some((axis, index) => Math.abs(axis - suppliedDimensions[index]!) > Math.max(1e-6, Math.abs(axis) * 1e-6))) {\n throw new Error(\"ModelTechnicalProfile dimensionsMetres must match boundsMetres.\");\n }\n const byteLength = requiredInteger(record.byteLength, \"ModelTechnicalProfile.byteLength\", 1, Number.MAX_SAFE_INTEGER);\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n \"ModelTechnicalProfile.textureByteLength\",\n 0,\n Number.MAX_SAFE_INTEGER,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelTechnicalProfile.maxTextureDimensionPx\",\n 0,\n 32_768,\n );\n if (textureByteLength > byteLength) {\n throw new Error(\"ModelTechnicalProfile.textureByteLength must not exceed model byteLength.\");\n }\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(\n \"ModelTechnicalProfile textureless models require textureByteLength and maxTextureDimensionPx to both be zero.\",\n );\n }\n return deepFreeze({\n boundsMetres,\n dimensionsMetres,\n triangleCount: requiredInteger(record.triangleCount, \"ModelTechnicalProfile.triangleCount\", 1, 1_000_000_000),\n byteLength,\n textureByteLength,\n maxTextureDimensionPx,\n lodCount: requiredInteger(record.lodCount, \"ModelTechnicalProfile.lodCount\", 1, 4),\n hasCollision: requiredBoolean(record.hasCollision, \"ModelTechnicalProfile.hasCollision\"),\n partitionCount: requiredInteger(record.partitionCount, \"ModelTechnicalProfile.partitionCount\", 1, 10_000),\n partitionCellMetres: requiredFiniteNumber(\n record.partitionCellMetres,\n \"ModelTechnicalProfile.partitionCellMetres\",\n Number.EPSILON,\n 1_000_000,\n ),\n });\n}\n\nfunction createAttribution(value: unknown): ModelAttribution {\n const record = assertRecord(value, \"ModelRightsAssessment.attribution\");\n assertAllowedKeys(record, [\"title\", \"creator\", \"notice\", \"sourcePageUri\"], \"ModelRightsAssessment.attribution\");\n const sourcePageUri = record.sourcePageUri === undefined\n ? undefined\n : assertPublicPageUri(record.sourcePageUri, \"ModelRightsAssessment.attribution.sourcePageUri\");\n return {\n title: requiredString(record.title, \"ModelRightsAssessment.attribution.title\", 256),\n creator: requiredString(record.creator, \"ModelRightsAssessment.attribution.creator\", 256),\n notice: requiredString(record.notice, \"ModelRightsAssessment.attribution.notice\", 512),\n ...(sourcePageUri === undefined ? {} : { sourcePageUri }),\n };\n}\n\n/** Validate and freeze rights and attribution evidence. */\nexport function createModelRightsAssessment(input: unknown): ModelRightsAssessment {\n const record = assertRecord(input, \"ModelRightsAssessment\");\n assertAllowedKeys(record, [\n \"decisionId\",\n \"decisionToken\",\n \"policyId\",\n \"policyVersion\",\n \"sourceId\",\n \"sourceAssetId\",\n \"sourceContentHash\",\n \"status\",\n \"licenseId\",\n \"evidencePageUri\",\n \"attribution\",\n \"reviewedAt\",\n ], \"ModelRightsAssessment\");\n const status = requiredEnum(record.status, MODEL_RIGHTS_STATUSES, \"ModelRightsAssessment.status\");\n const attribution = record.attribution === undefined ? undefined : createAttribution(record.attribution);\n if (status === \"attribution-required\" && attribution === undefined) {\n throw new Error(\"ModelRightsAssessment attribution is required for attribution-required rights.\");\n }\n if (status === \"attribution-required\" && attribution?.sourcePageUri === undefined) {\n throw new Error(\"ModelRightsAssessment attribution-required rights require a public attribution sourcePageUri.\");\n }\n return deepFreeze({\n decisionId: requiredToken(record.decisionId, \"ModelRightsAssessment.decisionId\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelRightsAssessment.decisionToken\",\n ),\n policyId: requiredToken(record.policyId, \"ModelRightsAssessment.policyId\"),\n policyVersion: assetVersion(record.policyVersion, \"ModelRightsAssessment.policyVersion\"),\n sourceId: requiredToken(record.sourceId, \"ModelRightsAssessment.sourceId\"),\n sourceAssetId: opaqueSourceAssetId(record.sourceAssetId, \"ModelRightsAssessment.sourceAssetId\"),\n sourceContentHash: requiredSha256(\n record.sourceContentHash,\n \"ModelRightsAssessment.sourceContentHash\",\n ),\n status,\n licenseId: requiredToken(record.licenseId, \"ModelRightsAssessment.licenseId\"),\n evidencePageUri: assertPublicPageUri(record.evidencePageUri, \"ModelRightsAssessment.evidencePageUri\"),\n ...(attribution === undefined ? {} : { attribution }),\n reviewedAt: requiredTimestamp(record.reviewedAt, \"ModelRightsAssessment.reviewedAt\"),\n });\n}\n\n/** Validate public-safe catalog, provider, or generated provenance. */\nexport function createModelProvenance(input: unknown): ModelProvenance {\n const record = assertRecord(input, \"ModelProvenance\");\n assertAllowedKeys(record, [\n \"kind\",\n \"sourceId\",\n \"sourceAssetId\",\n \"sourcePageUri\",\n \"contentHash\",\n \"capturedAt\",\n ], \"ModelProvenance\");\n const kind = requiredEnum(record.kind, MODEL_PROVENANCE_KINDS, \"ModelProvenance kind\");\n const sourceAssetId = opaqueSourceAssetId(record.sourceAssetId);\n const sourcePageUri = record.sourcePageUri === undefined\n ? undefined\n : assertPublicPageUri(record.sourcePageUri, \"ModelProvenance.sourcePageUri\");\n if (kind === \"provider\" && sourcePageUri === undefined) {\n throw new Error(\"ModelProvenance provider provenance requires sourcePageUri.\");\n }\n if (kind === \"generated\" && sourcePageUri !== undefined) {\n throw new Error(\"ModelProvenance generated provenance must not include sourcePageUri.\");\n }\n return deepFreeze({\n kind,\n sourceId: requiredToken(record.sourceId, \"ModelProvenance.sourceId\"),\n sourceAssetId,\n ...(sourcePageUri === undefined ? {} : { sourcePageUri }),\n contentHash: requiredSha256(record.contentHash, \"ModelProvenance.contentHash\"),\n capturedAt: requiredTimestamp(record.capturedAt, \"ModelProvenance.capturedAt\"),\n });\n}\n\n/** Validate and freeze an immutable player-safe model asset reference. */\nexport function createModelAssetRef(input: unknown): ModelAssetRef {\n const record = assertRecord(input, \"ModelAssetRef\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"assetId\",\n \"version\",\n \"kind\",\n \"contentHash\",\n \"runtimeManifestUri\",\n ], \"ModelAssetRef\");\n assertContractVersion(record, \"ModelAssetRef\");\n const validatedAssetId = assetId(record.assetId, \"ModelAssetRef.assetId\");\n const validatedVersion = assertImmutableAssetVersion(record.version);\n const runtimeManifestUri = assertModelUri(record.runtimeManifestUri, \"ModelAssetRef.runtimeManifestUri\");\n const expectedManifestUri = `mcp://models/catalog/${validatedAssetId}/versions/${validatedVersion}/manifest`;\n if (runtimeManifestUri !== expectedManifestUri) {\n throw new Error(\n \"ModelAssetRef.runtimeManifestUri must exactly match the assetId/version catalog identity.\",\n );\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n assetId: validatedAssetId,\n version: validatedVersion,\n kind: requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelAssetRef.kind\"),\n contentHash: requiredSha256(record.contentHash, \"ModelAssetRef.contentHash\"),\n runtimeManifestUri,\n });\n}\n\nfunction createCandidateAssetRef(value: unknown): ModelCandidateAssetRef {\n const record = assertRecord(value, \"ModelCandidate.assetRef\");\n const disposition = requiredEnum(record.disposition, [\"existing\", \"proposed\"], \"ModelCandidate.assetRef.disposition\");\n if (disposition === \"existing\") {\n assertAllowedKeys(record, [\"disposition\", \"asset\", \"kind\", \"contentHash\"], \"ModelCandidate.assetRef\");\n const asset = createModelAssetRef(record.asset);\n if (record.kind !== undefined && record.kind !== asset.kind) {\n throw new Error(\"ModelCandidate existing assetRef kind must match asset.\");\n }\n if (record.contentHash !== undefined && record.contentHash !== asset.contentHash) {\n throw new Error(\"ModelCandidate existing assetRef contentHash must match asset.\");\n }\n return {\n disposition,\n kind: asset.kind,\n contentHash: asset.contentHash,\n asset,\n };\n }\n assertAllowedKeys(record, [\"disposition\", \"proposalId\", \"kind\", \"contentHash\"], \"ModelCandidate.assetRef\");\n return {\n disposition,\n proposalId: requiredToken(record.proposalId, \"ModelCandidate.assetRef.proposalId\"),\n kind: requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelCandidate.assetRef.kind\"),\n contentHash: requiredSha256(record.contentHash, \"ModelCandidate.assetRef.contentHash\"),\n };\n}\n\nfunction createConfirmationView(value: unknown, index: number): ModelConfirmationView {\n const fieldName = `ModelCandidate.views[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"kind\", \"imageUri\", \"sha256\", \"contentType\", \"width\", \"height\"], fieldName);\n const width = requiredInteger(record.width, `${fieldName}.width`, MODEL_CONFIRMATION_VIEW_SIZE_PX, MODEL_CONFIRMATION_VIEW_SIZE_PX);\n const height = requiredInteger(record.height, `${fieldName}.height`, MODEL_CONFIRMATION_VIEW_SIZE_PX, MODEL_CONFIRMATION_VIEW_SIZE_PX);\n if (record.contentType !== \"image/png\") {\n throw new Error(`${fieldName}.contentType must be image/png.`);\n }\n return {\n kind: requiredEnum(record.kind, MODEL_CONFIRMATION_VIEW_KINDS, `${fieldName}.kind`),\n imageUri: assertModelUri(record.imageUri, `${fieldName}.imageUri`),\n sha256: requiredSha256(record.sha256, `${fieldName}.sha256`),\n contentType: \"image/png\",\n width: width as typeof MODEL_CONFIRMATION_VIEW_SIZE_PX,\n height: height as typeof MODEL_CONFIRMATION_VIEW_SIZE_PX,\n };\n}\n\nfunction createConfirmationViews(\n value: unknown,\n resolutionId: string,\n candidateId: string,\n): ModelConfirmationViews {\n if (!Array.isArray(value) || value.length !== MODEL_CONFIRMATION_VIEW_KINDS.length) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const views = value.map(createConfirmationView);\n const byKind = new Map(views.map((view) => [view.kind, view]));\n if (byKind.size !== MODEL_CONFIRMATION_VIEW_KINDS.length) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const ordered = MODEL_CONFIRMATION_VIEW_KINDS.map((kind) => byKind.get(kind));\n if (ordered.some((view) => view === undefined)) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const confirmedViews = ordered as ModelConfirmationView[];\n if (new Set(confirmedViews.map((view) => view.imageUri)).size !== confirmedViews.length) {\n throw new Error(\"Model candidate confirmation views must use unique resources.\");\n }\n for (const view of confirmedViews) {\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/${view.kind}.png`;\n if (view.imageUri !== expectedUri) {\n throw new Error(\n \"Model candidate confirmation view resources must be scoped to the resolution, candidate, and view kind.\",\n );\n }\n }\n return [ordered[0]!, ordered[1]!, ordered[2]!, ordered[3]!];\n}\n\nfunction createRenderEvidence(\n value: unknown,\n manifest: ModelProcessingManifest,\n views: ModelConfirmationViews,\n): ModelRenderEvidence {\n const record = assertRecord(value, \"ModelCandidate.renderEvidence\");\n assertAllowedKeys(record, [\n \"renderId\",\n \"rendererId\",\n \"rendererVersion\",\n \"settingsId\",\n \"settingsVersion\",\n \"processingManifestId\",\n \"sourceContentHash\",\n \"viewSha256s\",\n \"renderedAt\",\n \"attestationToken\",\n ], \"ModelCandidate.renderEvidence\");\n if (record.processingManifestId !== manifest.manifestId) {\n throw new Error(\"ModelCandidate.renderEvidence.processingManifestId must match processingManifest.\");\n }\n if (record.sourceContentHash !== manifest.lods[0]?.resource.sha256) {\n throw new Error(\"ModelCandidate.renderEvidence.sourceContentHash must match canonical LOD0.\");\n }\n if (!Array.isArray(record.viewSha256s) || record.viewSha256s.length !== 4) {\n throw new Error(\"ModelCandidate.renderEvidence.viewSha256s must contain four ordered hashes.\");\n }\n const viewSha256s = record.viewSha256s.map((digest, index) =>\n requiredSha256(digest, `ModelCandidate.renderEvidence.viewSha256s[${index}]`));\n if (viewSha256s.some((digest, index) => digest !== views[index]?.sha256)) {\n throw new Error(\"ModelCandidate.renderEvidence view hashes must match the candidate view pack.\");\n }\n const renderedAt = requiredTimestamp(record.renderedAt, \"ModelCandidate.renderEvidence.renderedAt\");\n if (Date.parse(renderedAt) < Date.parse(manifest.processedAt)) {\n throw new Error(\"ModelCandidate.renderEvidence.renderedAt must not precede processing.\");\n }\n return {\n renderId: requiredToken(record.renderId, \"ModelCandidate.renderEvidence.renderId\"),\n rendererId: requiredToken(record.rendererId, \"ModelCandidate.renderEvidence.rendererId\"),\n rendererVersion: assetVersion(record.rendererVersion, \"ModelCandidate.renderEvidence.rendererVersion\"),\n settingsId: requiredToken(record.settingsId, \"ModelCandidate.renderEvidence.settingsId\"),\n settingsVersion: assetVersion(record.settingsVersion, \"ModelCandidate.renderEvidence.settingsVersion\"),\n processingManifestId: manifest.manifestId,\n sourceContentHash: manifest.contentHash,\n viewSha256s: [viewSha256s[0]!, viewSha256s[1]!, viewSha256s[2]!, viewSha256s[3]!],\n renderedAt,\n attestationToken: requiredAttestationToken(\n record.attestationToken,\n \"ModelCandidate.renderEvidence.attestationToken\",\n ),\n };\n}\n\nfunction createCandidateHardGates(\n value: unknown,\n provenance: ModelProvenance,\n manifest: ModelProcessingManifest,\n): readonly ModelCandidateHardGateEvidence[] {\n if (!Array.isArray(value) || value.length !== MODEL_CANDIDATE_HARD_GATE_KINDS.length) {\n throw new Error(\"ModelCandidate.hardGates must contain every required independent hard gate.\");\n }\n const gates = value.map((item, index): ModelCandidateHardGateEvidence => {\n const fieldName = `ModelCandidate.hardGates[${index}]`;\n const record = assertRecord(item, fieldName);\n assertAllowedKeys(record, [\n \"kind\",\n \"outcome\",\n \"validatorId\",\n \"validatorVersion\",\n \"subjectContentHash\",\n \"reasonCodes\",\n \"evaluatedAt\",\n \"attestationToken\",\n ], fieldName);\n const kind = requiredEnum(record.kind, MODEL_CANDIDATE_HARD_GATE_KINDS, `${fieldName}.kind`);\n const subjectContentHash = requiredSha256(record.subjectContentHash, `${fieldName}.subjectContentHash`);\n const expectedHash = kind === \"malware-scan\"\n ? provenance.contentHash\n : manifest.closureHash;\n if (subjectContentHash !== expectedHash) {\n throw new Error(`${fieldName}.subjectContentHash must match the gate subject.`);\n }\n const outcome = requiredEnum(record.outcome, [\"passed\", \"blocked\"] as const, `${fieldName}.outcome`);\n const reasonCodes = stringList(record.reasonCodes ?? [], `${fieldName}.reasonCodes`, { tokens: true });\n if (outcome === \"blocked\" && reasonCodes.length === 0) {\n throw new Error(`${fieldName}.reasonCodes must explain a blocked hard gate.`);\n }\n return {\n kind,\n outcome,\n validatorId: requiredToken(record.validatorId, `${fieldName}.validatorId`),\n validatorVersion: assetVersion(record.validatorVersion, `${fieldName}.validatorVersion`),\n subjectContentHash,\n reasonCodes,\n evaluatedAt: requiredTimestamp(record.evaluatedAt, `${fieldName}.evaluatedAt`),\n attestationToken: requiredAttestationToken(record.attestationToken, `${fieldName}.attestationToken`),\n };\n });\n if (new Set(gates.map((gate) => gate.kind)).size !== MODEL_CANDIDATE_HARD_GATE_KINDS.length) {\n throw new Error(\"ModelCandidate.hardGates must contain each required gate exactly once.\");\n }\n if (new Set(gates.map((gate) => gate.attestationToken)).size !== gates.length) {\n throw new Error(\"ModelCandidate hard gate attestation tokens must be unique.\");\n }\n const byKind = new Map(gates.map((gate) => [gate.kind, gate]));\n return MODEL_CANDIDATE_HARD_GATE_KINDS.map((kind) => byKind.get(kind)!);\n}\n\n/** Validate and deeply freeze a model candidate from unknown JavaScript input. */\nexport function createModelCandidate(input: unknown): ModelCandidate {\n const record = assertRecord(input, \"ModelCandidate\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"resolutionId\",\n \"candidateId\",\n \"assetRef\",\n \"match\",\n \"provenance\",\n \"rights\",\n \"technicalProfile\",\n \"processingManifest\",\n \"views\",\n \"renderEvidence\",\n \"hardGates\",\n \"confirmationToken\",\n \"confirmationRequired\",\n ], \"ModelCandidate\");\n assertContractVersion(record, \"ModelCandidate\");\n if (record.confirmationRequired !== undefined && record.confirmationRequired !== true) {\n throw new Error(\"ModelCandidate confirmationRequired must always be true.\");\n }\n if (typeof record.confirmationToken !== \"string\" || !CONFIRMATION_TOKEN_PATTERN.test(record.confirmationToken)) {\n throw new Error(\"ModelCandidate confirmationToken must be a bounded opaque token.\");\n }\n const resolutionId = requiredModelPathSegment(record.resolutionId, \"ModelCandidate.resolutionId\");\n const candidateId = requiredModelPathSegment(record.candidateId, \"ModelCandidate.candidateId\");\n const assetRef = createCandidateAssetRef(record.assetRef);\n const technicalProfile = createModelTechnicalProfile(record.technicalProfile);\n const processingManifest = createModelProcessingManifest(record.processingManifest);\n if (\n processingManifest.resolutionId !== resolutionId\n ||\n processingManifest.candidateId !== candidateId\n || processingManifest.kind !== assetRef.kind\n || processingManifest.contentHash !== assetRef.contentHash\n || JSON.stringify(processingManifest.technicalProfile) !== JSON.stringify(technicalProfile)\n ) {\n throw new Error(\n \"ModelCandidate processingManifest must match candidateId, asset kind/contentHash, and technicalProfile.\",\n );\n }\n const match = createModelMatchAssessment(record.match);\n if (match.candidateId !== candidateId || match.candidateContentHash !== assetRef.contentHash) {\n throw new Error(\"ModelCandidate match assessment must bind candidateId and candidate contentHash.\");\n }\n const hardConstraintEvaluation = evaluateNormalizedModelHardConstraints(\n match.request,\n technicalProfile,\n );\n if (match.hardConstraintPass !== hardConstraintEvaluation.pass) {\n throw new Error(\n \"ModelCandidate match hardConstraintPass must match deterministic evaluation.\",\n );\n }\n if (\n hardConstraintEvaluation.reasonCodes.some(\n (reasonCode) => !match.reasonCodes.includes(reasonCode),\n )\n ) {\n throw new Error(\n \"ModelCandidate match reasonCodes must include every failed hard constraint.\",\n );\n }\n const provenance = createModelProvenance(record.provenance);\n if (provenance.contentHash !== processingManifest.converter.sourceContentHash) {\n throw new Error(\"ModelCandidate provenance contentHash must match converter sourceContentHash.\");\n }\n const rights = createModelRightsAssessment(record.rights);\n if (\n rights.sourceId !== provenance.sourceId\n || rights.sourceAssetId !== provenance.sourceAssetId\n || rights.sourceContentHash !== provenance.contentHash\n ) {\n throw new Error(\"ModelCandidate rights decision must bind the exact provenance source and content hash.\");\n }\n if (processingManifest.fidelityGate.outcome === \"low-only\") {\n if (\n match.assurance === \"high\"\n || !match.reasonCodes.includes(\"fidelity-low-only\")\n || match.fidelityWarnings.length === 0\n ) {\n throw new Error(\"ModelCandidate low-only fidelity must cap assurance at low and include fidelity evidence.\");\n }\n }\n if (\n processingManifest.fidelityGate.outcome === \"blocked\"\n && !match.reasonCodes.includes(\"fidelity-blocked\")\n ) {\n throw new Error(\"ModelCandidate blocked fidelity must be recorded in match reasonCodes.\");\n }\n const views = createConfirmationViews(record.views, resolutionId, candidateId);\n const renderEvidence = createRenderEvidence(record.renderEvidence, processingManifest, views);\n const hardGates = createCandidateHardGates(record.hardGates, provenance, processingManifest);\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n resolutionId,\n candidateId,\n assetRef,\n match,\n provenance,\n rights,\n technicalProfile,\n processingManifest,\n views,\n renderEvidence,\n hardGates,\n confirmationToken: record.confirmationToken,\n confirmationRequired: true,\n });\n}\n\n/** Return whether a candidate may enter mandatory human confirmation. */\nexport function isModelCandidateConfirmable(candidate: ModelCandidate): boolean {\n const blockingEvidence = [\n ...candidate.processingManifest.converter.diagnostics,\n ...candidate.processingManifest.converter.losses,\n ].some((evidence) => evidence.severity === \"blocking\");\n return candidate.confirmationRequired\n && candidate.match.hardConstraintPass\n && candidate.match.assurance !== \"none\"\n && (candidate.rights.status === \"allowed\" || candidate.rights.status === \"attribution-required\")\n && !blockingEvidence\n && candidate.processingManifest.fidelityGate.outcome !== \"blocked\"\n && candidate.hardGates.length === MODEL_CANDIDATE_HARD_GATE_KINDS.length\n && candidate.hardGates.every((gate) => gate.outcome === \"passed\")\n && candidate.views.length === MODEL_CONFIRMATION_VIEW_KINDS.length;\n}\n\n/** Validate a requester confirmation against one exact candidate and resolution. */\nexport function createModelCandidateConfirmation(\n input: unknown,\n expectedCandidate: ModelCandidate,\n expectedResolutionId: string,\n): ModelCandidateConfirmation {\n const record = assertRecord(input, \"ModelCandidateConfirmation\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"confirmationId\",\n \"resolutionId\",\n \"candidateId\",\n \"confirmationToken\",\n \"viewSha256s\",\n \"confirmedBy\",\n \"confirmedAt\",\n \"semanticRiskAccepted\",\n ], \"ModelCandidateConfirmation\");\n assertContractVersion(record, \"ModelCandidateConfirmation\");\n const candidate = createModelCandidate(expectedCandidate);\n const resolutionId = requiredModelPathSegment(\n expectedResolutionId,\n \"ModelCandidateConfirmation expected resolutionId\",\n );\n if (candidate.resolutionId !== resolutionId) {\n throw new Error(\n \"ModelCandidateConfirmation expected candidate must belong to the expected resolutionId.\",\n );\n }\n if (record.resolutionId !== resolutionId) {\n throw new Error(\"ModelCandidateConfirmation.resolutionId must match the expected resolutionId.\");\n }\n if (record.candidateId !== candidate.candidateId) {\n throw new Error(\"ModelCandidateConfirmation.candidateId must match the confirmed candidate.\");\n }\n if (\n typeof record.confirmationToken !== \"string\"\n || !CONFIRMATION_TOKEN_PATTERN.test(record.confirmationToken)\n || record.confirmationToken !== candidate.confirmationToken\n ) {\n throw new Error(\"ModelCandidateConfirmation.confirmationToken must match the signed candidate token.\");\n }\n if (!Array.isArray(record.viewSha256s) || record.viewSha256s.length !== 4) {\n throw new Error(\"ModelCandidateConfirmation.viewSha256s must contain the ordered four candidate view hashes.\");\n }\n const viewSha256s = record.viewSha256s.map((value, index) =>\n requiredSha256(value, `ModelCandidateConfirmation.viewSha256s[${index}]`));\n const expectedHashes = candidate.views.map((view) => view.sha256);\n if (viewSha256s.some((digest, index) => digest !== expectedHashes[index])) {\n throw new Error(\"ModelCandidateConfirmation view hashes must match the ordered candidate views.\");\n }\n if (!isModelCandidateConfirmable(candidate)) {\n throw new Error(\"ModelCandidateConfirmation candidate is not confirmable because a hard review gate is blocking.\");\n }\n const semanticRiskAccepted = requiredBoolean(\n record.semanticRiskAccepted,\n \"ModelCandidateConfirmation.semanticRiskAccepted\",\n );\n if (candidate.match.assurance === \"low\" && !semanticRiskAccepted) {\n throw new Error(\"ModelCandidateConfirmation low assurance requires explicit semantic risk acceptance.\");\n }\n if (candidate.match.assurance === \"high\" && semanticRiskAccepted) {\n throw new Error(\"ModelCandidateConfirmation high assurance must not record a semantic risk override.\");\n }\n const confirmedBy = requiredString(record.confirmedBy, \"ModelCandidateConfirmation.confirmedBy\", 256);\n assertNoDirectUrl(confirmedBy, \"ModelCandidateConfirmation.confirmedBy\");\n const confirmedAt = requiredTimestamp(\n record.confirmedAt,\n \"ModelCandidateConfirmation.confirmedAt\",\n );\n const latestEvidenceTime = Math.max(\n Date.parse(candidate.provenance.capturedAt),\n Date.parse(candidate.rights.reviewedAt),\n Date.parse(candidate.processingManifest.processedAt),\n Date.parse(candidate.processingManifest.fidelityGate.evaluatedAt),\n Date.parse(candidate.renderEvidence.renderedAt),\n ...candidate.hardGates.map((gate) => Date.parse(gate.evaluatedAt)),\n );\n if (Date.parse(confirmedAt) < latestEvidenceTime) {\n throw new Error(\n \"ModelCandidateConfirmation.confirmedAt must not precede the candidate evidence required for confirmation.\",\n );\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n confirmationId: requiredToken(record.confirmationId, \"ModelCandidateConfirmation.confirmationId\"),\n resolutionId,\n candidateId: candidate.candidateId,\n confirmationToken: candidate.confirmationToken,\n viewSha256s: [viewSha256s[0]!, viewSha256s[1]!, viewSha256s[2]!, viewSha256s[3]!],\n confirmedBy,\n confirmedAt,\n semanticRiskAccepted,\n });\n}\n\n/** Validate and freeze a public-safe processing resource reference. */\nexport function createModelResourceRef(input: unknown): ModelResourceRef {\n const record = assertRecord(input, \"ModelResourceRef\");\n assertAllowedKeys(record, [\"uri\", \"byteLength\", \"sha256\", \"contentType\"], \"ModelResourceRef\");\n const contentType = requiredString(record.contentType, \"ModelResourceRef.contentType\", 128);\n if (!CONTENT_TYPE_PATTERN.test(contentType)) {\n throw new Error(\"ModelResourceRef.contentType must be a valid media type.\");\n }\n return deepFreeze({\n uri: assertModelUri(record.uri, \"ModelResourceRef.uri\"),\n byteLength: requiredInteger(record.byteLength, \"ModelResourceRef.byteLength\", 1, Number.MAX_SAFE_INTEGER),\n sha256: requiredSha256(record.sha256, \"ModelResourceRef.sha256\"),\n contentType,\n });\n}\n\nfunction createLodRecord(value: unknown, index: number): ModelLodRecord {\n const fieldName = `ModelProcessingManifest.lods[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"level\", \"resource\", \"triangleCount\", \"geometricErrorMetres\"], fieldName);\n const resource = createModelResourceRef(record.resource);\n if (resource.contentType !== \"model/gltf-binary\") {\n throw new Error(`${fieldName}.resource.contentType must be model/gltf-binary for canonical GLB output.`);\n }\n return {\n level: requiredInteger(record.level, `${fieldName}.level`, 0, 3) as ModelLodLevel,\n resource,\n triangleCount: requiredInteger(record.triangleCount, `${fieldName}.triangleCount`, 1, 1_000_000_000),\n geometricErrorMetres: requiredFiniteNumber(\n record.geometricErrorMetres,\n `${fieldName}.geometricErrorMetres`,\n 0,\n 1_000_000,\n ),\n };\n}\n\nfunction createCollisionRecord(value: unknown): ModelCollisionRecord {\n const record = assertRecord(value, \"ModelProcessingManifest.collision\");\n assertAllowedKeys(record, [\"kind\", \"resource\"], \"ModelProcessingManifest.collision\");\n const kind = requiredEnum(\n record.kind,\n [\"none\", \"box\", \"convex-hull\", \"triangle-mesh\", \"compound\"],\n \"ModelProcessingManifest.collision.kind\",\n );\n if (kind === \"none\") {\n if (record.resource !== undefined) {\n throw new Error(\"ModelProcessingManifest collision kind none must not include a resource.\");\n }\n return { kind };\n }\n if (record.resource === undefined) {\n throw new Error(\"ModelProcessingManifest non-empty collision kinds require a resource.\");\n }\n const resource = createModelResourceRef(record.resource);\n if (resource.contentType !== \"model/gltf-binary\") {\n throw new Error(\"ModelProcessingManifest collision resources must be model/gltf-binary GLBs.\");\n }\n return { kind, resource };\n}\n\nfunction createTransform(value: unknown, fieldName: string): ModelTransform {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"translationMetres\", \"rotationQuaternion\", \"scale\"], fieldName);\n const translationMetres = requiredVector3(record.translationMetres, `${fieldName}.translationMetres`);\n if (!Array.isArray(record.rotationQuaternion) || record.rotationQuaternion.length !== 4) {\n throw new Error(`${fieldName}.rotationQuaternion must contain exactly four numbers.`);\n }\n const rotationQuaternion: ModelQuaternion = [\n requiredFiniteNumber(record.rotationQuaternion[0], `${fieldName}.rotationQuaternion[0]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[1], `${fieldName}.rotationQuaternion[1]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[2], `${fieldName}.rotationQuaternion[2]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[3], `${fieldName}.rotationQuaternion[3]`, -1, 1),\n ];\n const magnitude = Math.hypot(...rotationQuaternion);\n if (Math.abs(magnitude - 1) > 1e-4) {\n throw new Error(`${fieldName}.rotationQuaternion must be normalized.`);\n }\n return {\n translationMetres,\n rotationQuaternion,\n scale: requiredVector3(record.scale, `${fieldName}.scale`, true),\n };\n}\n\nfunction createAssemblyChildAssetRef(\n value: unknown,\n resolutionId: string,\n candidateId: string,\n fieldName: string,\n): ModelAssemblyChildAssetRef {\n const record = assertRecord(value, fieldName);\n if (record.disposition !== \"staged-derived\") {\n const catalogRef = createModelAssetRef(value);\n if (catalogRef.kind !== \"leaf\") {\n throw new Error(\"ModelProcessingManifest v1 assembly child assetRef values must be leaf assets.\");\n }\n return catalogRef;\n }\n assertAllowedKeys(record, [\n \"disposition\",\n \"derivedId\",\n \"kind\",\n \"contentHash\",\n \"processingManifestUri\",\n ], fieldName);\n if (record.kind !== \"leaf\") {\n throw new Error(\"ModelProcessingManifest staged-derived child assetRef kind must be leaf.\");\n }\n const derivedId = requiredModelPathSegment(record.derivedId, `${fieldName}.derivedId`);\n const processingManifestUri = assertModelUri(\n record.processingManifestUri,\n `${fieldName}.processingManifestUri`,\n );\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/children/${derivedId}/manifest`;\n if (processingManifestUri !== expectedUri) {\n throw new Error(`${fieldName}.processingManifestUri must match the staged child identity.`);\n }\n return {\n disposition: \"staged-derived\",\n derivedId,\n kind: \"leaf\",\n contentHash: requiredSha256(record.contentHash, `${fieldName}.contentHash`),\n processingManifestUri,\n };\n}\n\nfunction createAssemblyChild(\n value: unknown,\n index: number,\n resolutionId: string,\n candidateId: string,\n): ModelAssemblyChild {\n const fieldName = `ModelProcessingManifest.children[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"instanceId\", \"parentInstanceId\", \"assetRef\", \"transform\"], fieldName);\n const instanceId = requiredToken(record.instanceId, `${fieldName}.instanceId`);\n const parentInstanceId = record.parentInstanceId === undefined\n ? undefined\n : requiredToken(record.parentInstanceId, `${fieldName}.parentInstanceId`);\n const childAssetRef = createAssemblyChildAssetRef(\n record.assetRef,\n resolutionId,\n candidateId,\n `${fieldName}.assetRef`,\n );\n return {\n instanceId,\n ...(parentInstanceId === undefined ? {} : { parentInstanceId }),\n assetRef: childAssetRef,\n transform: createTransform(record.transform, `${fieldName}.transform`),\n };\n}\n\nfunction createDiagnostic(\n value: unknown,\n fieldName: string,\n): ModelConverterDiagnostic {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"severity\", \"code\", \"message\"], fieldName);\n return {\n severity: requiredEnum(record.severity, [\"info\", \"warning\", \"blocking\"], `${fieldName}.severity`),\n code: requiredToken(record.code, `${fieldName}.code`),\n message: requiredString(record.message, `${fieldName}.message`, 1024),\n };\n}\n\nfunction createConverterEvidence(value: unknown): ModelConverterEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.converter\");\n assertAllowedKeys(record, [\n \"id\",\n \"version\",\n \"sourceFormat\",\n \"targetFormat\",\n \"sourceContentHash\",\n \"outputContentHash\",\n \"diagnostics\",\n \"losses\",\n ], \"ModelProcessingManifest.converter\");\n if (!Array.isArray(record.diagnostics) || record.diagnostics.length > 100) {\n throw new Error(\"ModelProcessingManifest.converter.diagnostics must be a bounded array.\");\n }\n if (!Array.isArray(record.losses) || record.losses.length > 100) {\n throw new Error(\"ModelProcessingManifest.converter.losses must be a bounded array.\");\n }\n return {\n id: requiredToken(record.id, \"ModelProcessingManifest.converter.id\"),\n version: assetVersion(record.version, \"ModelProcessingManifest.converter.version\"),\n sourceFormat: requiredToken(record.sourceFormat, \"ModelProcessingManifest.converter.sourceFormat\"),\n targetFormat: requiredToken(record.targetFormat, \"ModelProcessingManifest.converter.targetFormat\"),\n sourceContentHash: requiredSha256(record.sourceContentHash, \"ModelProcessingManifest.converter.sourceContentHash\"),\n outputContentHash: requiredSha256(record.outputContentHash, \"ModelProcessingManifest.converter.outputContentHash\"),\n diagnostics: record.diagnostics.map((item, index) =>\n createDiagnostic(item, `ModelProcessingManifest.converter.diagnostics[${index}]`)),\n losses: record.losses.map((item, index) =>\n createDiagnostic(item, `ModelProcessingManifest.converter.losses[${index}]`)),\n };\n}\n\nfunction createFidelityEvidence(value: unknown, index: number): ModelFidelityEvidence {\n const fieldName = `ModelProcessingManifest.fidelityEvidence[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"aspect\", \"outcome\", \"message\", \"evidenceResource\"], fieldName);\n const evidenceResource = record.evidenceResource === undefined\n ? undefined\n : createModelResourceRef(record.evidenceResource);\n return {\n aspect: requiredEnum(\n record.aspect,\n [\"geometry\", \"materials\", \"textures\", \"rigging\", \"animation\", \"metadata\"],\n `${fieldName}.aspect`,\n ),\n outcome: requiredEnum(record.outcome, [\"preserved\", \"approximated\", \"lost\"], `${fieldName}.outcome`),\n message: requiredString(record.message, `${fieldName}.message`, 1024),\n ...(evidenceResource === undefined ? {} : { evidenceResource }),\n };\n}\n\nfunction createCollisionPolicyEvidence(\n value: unknown,\n collision: ModelCollisionRecord,\n): ModelCollisionPolicyEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.collisionPolicy\");\n assertAllowedKeys(record, [\n \"profileId\",\n \"profileVersion\",\n \"disposition\",\n \"category\",\n \"decisionToken\",\n ], \"ModelProcessingManifest.collisionPolicy\");\n const disposition = requiredEnum(\n record.disposition,\n [\"proxy-required\", \"none-allowed\"] as const,\n \"ModelProcessingManifest.collisionPolicy.disposition\",\n );\n if (\n (collision.kind === \"none\" && disposition !== \"none-allowed\")\n || (collision.kind !== \"none\" && disposition !== \"proxy-required\")\n ) {\n throw new Error(\"ModelProcessingManifest collisionPolicy must explicitly authorize collision none or require a proxy.\");\n }\n return {\n profileId: requiredToken(record.profileId, \"ModelProcessingManifest.collisionPolicy.profileId\"),\n profileVersion: assetVersion(\n record.profileVersion,\n \"ModelProcessingManifest.collisionPolicy.profileVersion\",\n ),\n disposition,\n category: requiredToken(record.category, \"ModelProcessingManifest.collisionPolicy.category\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelProcessingManifest.collisionPolicy.decisionToken\",\n ),\n };\n}\n\nfunction createFidelityGateEvidence(\n value: unknown,\n fidelityEvidence: readonly ModelFidelityEvidence[],\n converter: ModelConverterEvidence,\n): ModelFidelityGateEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.fidelityGate\");\n assertAllowedKeys(record, [\n \"profileId\",\n \"profileVersion\",\n \"outcome\",\n \"requiredAspects\",\n \"evaluatedAt\",\n \"decisionToken\",\n ], \"ModelProcessingManifest.fidelityGate\");\n const expectedAspects = [\"geometry\", \"materials\", \"textures\"] as const;\n if (\n !Array.isArray(record.requiredAspects)\n || record.requiredAspects.length !== expectedAspects.length\n || record.requiredAspects.some((aspect, index) => aspect !== expectedAspects[index])\n ) {\n throw new Error(\"ModelProcessingManifest.fidelityGate.requiredAspects must be geometry, materials, textures.\");\n }\n const byAspect = new Map(fidelityEvidence.map((evidence) => [evidence.aspect, evidence]));\n if (expectedAspects.some((aspect) => !byAspect.has(aspect))) {\n throw new Error(\"ModelProcessingManifest fidelityEvidence must cover geometry, materials, and textures.\");\n }\n const hasBlockingConverterEvidence = [\n ...converter.diagnostics,\n ...converter.losses,\n ].some((evidence) => evidence.severity === \"blocking\");\n const geometryLost = byAspect.get(\"geometry\")?.outcome === \"lost\";\n const hasWarningLoss = converter.losses.some((loss) => loss.severity === \"warning\");\n const hasUnresolvedFidelity = expectedAspects.some(\n (aspect) => byAspect.get(aspect)?.outcome !== \"preserved\",\n ) || hasWarningLoss;\n const derivedOutcome: ModelFidelityGateEvidence[\"outcome\"] =\n hasBlockingConverterEvidence || geometryLost\n ? \"blocked\"\n : hasUnresolvedFidelity\n ? \"low-only\"\n : \"passed\";\n const outcome = requiredEnum(\n record.outcome,\n [\"passed\", \"low-only\", \"blocked\"] as const,\n \"ModelProcessingManifest.fidelityGate.outcome\",\n );\n if (outcome !== derivedOutcome) {\n throw new Error(\"ModelProcessingManifest fidelityGate outcome must match converter and fidelity evidence.\");\n }\n return {\n profileId: requiredToken(record.profileId, \"ModelProcessingManifest.fidelityGate.profileId\"),\n profileVersion: assetVersion(record.profileVersion, \"ModelProcessingManifest.fidelityGate.profileVersion\"),\n outcome,\n requiredAspects: expectedAspects,\n evaluatedAt: requiredTimestamp(record.evaluatedAt, \"ModelProcessingManifest.fidelityGate.evaluatedAt\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelProcessingManifest.fidelityGate.decisionToken\",\n ),\n };\n}\n\nfunction assertCoordinateSystem(value: unknown): void {\n if (value === undefined) {\n return;\n }\n const record = assertRecord(value, \"ModelProcessingManifest.coordinateSystem\");\n assertAllowedKeys(record, [\n \"unit\",\n \"upAxis\",\n \"forwardAxis\",\n \"origin\",\n \"outwardFaceWinding\",\n ], \"ModelProcessingManifest.coordinateSystem\");\n if (\n record.unit !== CANONICAL_MODEL_COORDINATE_SYSTEM.unit\n || record.upAxis !== CANONICAL_MODEL_COORDINATE_SYSTEM.upAxis\n || record.forwardAxis !== CANONICAL_MODEL_COORDINATE_SYSTEM.forwardAxis\n || record.origin !== CANONICAL_MODEL_COORDINATE_SYSTEM.origin\n || record.outwardFaceWinding !== CANONICAL_MODEL_COORDINATE_SYSTEM.outwardFaceWinding\n ) {\n throw new Error(\n \"ModelProcessingManifest.coordinateSystem must be metres, Y-up, -Z forward, floor-centred, and counter-clockwise outward.\",\n );\n }\n}\n\nfunction assertCandidateResourceScope(\n uri: string,\n resolutionId: string,\n candidateId: string,\n fieldName: string,\n): void {\n const expectedPrefix = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/`;\n if (!uri.startsWith(expectedPrefix)) {\n throw new Error(`${fieldName} must be scoped to resolution ${resolutionId} and candidate ${candidateId}.`);\n }\n}\n\nfunction assertAssemblyHierarchy(children: readonly ModelAssemblyChild[]): void {\n const byId = new Map(children.map((child) => [child.instanceId, child]));\n for (const child of children) {\n if (child.parentInstanceId === undefined) {\n continue;\n }\n if (child.parentInstanceId === child.instanceId) {\n throw new Error(\"ModelProcessingManifest assembly children must not parent themselves.\");\n }\n if (!byId.has(child.parentInstanceId)) {\n throw new Error(\"ModelProcessingManifest assembly parentInstanceId values must reference existing children.\");\n }\n }\n const maximumDepth = 16;\n for (const child of children) {\n const visited = new Set<string>();\n let current: ModelAssemblyChild | undefined = child;\n let depth = 0;\n while (current?.parentInstanceId !== undefined) {\n if (visited.has(current.instanceId)) {\n throw new Error(\"ModelProcessingManifest assembly hierarchy must not contain cycles.\");\n }\n visited.add(current.instanceId);\n depth += 1;\n if (depth > maximumDepth) {\n throw new Error(`ModelProcessingManifest assembly hierarchy depth must not exceed ${maximumDepth}.`);\n }\n current = byId.get(current.parentInstanceId);\n }\n }\n}\n\n/** Validate and deeply freeze a canonical processing manifest. */\nexport function createModelProcessingManifest(input: unknown): ModelProcessingManifest {\n const record = assertRecord(input, \"ModelProcessingManifest\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"manifestId\",\n \"resolutionId\",\n \"candidateId\",\n \"kind\",\n \"contentHash\",\n \"closureHash\",\n \"coordinateSystem\",\n \"technicalProfile\",\n \"lods\",\n \"collision\",\n \"collisionPolicy\",\n \"children\",\n \"converter\",\n \"fidelityEvidence\",\n \"fidelityGate\",\n \"processedAt\",\n ], \"ModelProcessingManifest\");\n assertContractVersion(record, \"ModelProcessingManifest\");\n const resolutionId = requiredModelPathSegment(\n record.resolutionId,\n \"ModelProcessingManifest.resolutionId\",\n );\n const candidateId = requiredModelPathSegment(\n record.candidateId,\n \"ModelProcessingManifest.candidateId\",\n );\n assertCoordinateSystem(record.coordinateSystem);\n const kind = requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelProcessingManifest.kind\");\n const contentHash = requiredSha256(record.contentHash, \"ModelProcessingManifest.contentHash\");\n const closureHash = requiredSha256(record.closureHash, \"ModelProcessingManifest.closureHash\");\n if (kind === \"leaf\" && closureHash !== contentHash) {\n throw new Error(\"ModelProcessingManifest leaf closureHash must match contentHash.\");\n }\n const technicalProfile = createModelTechnicalProfile(record.technicalProfile);\n const [minimumX, minimumY, minimumZ] = technicalProfile.boundsMetres.min;\n const [maximumX, , maximumZ] = technicalProfile.boundsMetres.max;\n if (\n Math.abs(minimumY) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n || Math.abs((minimumX + maximumX) / 2) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n || Math.abs((minimumZ + maximumZ) / 2) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n ) {\n throw new Error(\n \"ModelProcessingManifest floor-centred origin requires minY and the X/Z bounds centre to be zero.\",\n );\n }\n if (!Array.isArray(record.lods) || record.lods.length < 1 || record.lods.length > 4) {\n throw new Error(\"ModelProcessingManifest.lods must contain one to four adaptive levels beginning with LOD0.\");\n }\n const lods = record.lods.map(createLodRecord);\n for (const [index, lod] of lods.entries()) {\n if (lod.level !== index) {\n throw new Error(\"ModelProcessingManifest LOD levels must be contiguous and begin with LOD0.\");\n }\n if (index > 0 && lod.triangleCount > lods[index - 1]!.triangleCount) {\n throw new Error(\"ModelProcessingManifest LOD triangle counts must be monotonic non-increasing.\");\n }\n if (index > 0 && lod.geometricErrorMetres < lods[index - 1]!.geometricErrorMetres) {\n throw new Error(\"ModelProcessingManifest LOD geometric error must be monotonic non-decreasing.\");\n }\n if (index === 0 && lod.geometricErrorMetres !== 0) {\n throw new Error(\"ModelProcessingManifest LOD0 geometric error must be zero.\");\n }\n if (index > 0 && lod.triangleCount > Math.floor(lods[index - 1]!.triangleCount * 0.7)) {\n throw new Error(\"ModelProcessingManifest retained LODs must reduce the preceding level by at least 30%.\");\n }\n if (index > 0 && lod.triangleCount < 512) {\n throw new Error(\"ModelProcessingManifest retained LODs must contain at least 512 triangles.\");\n }\n }\n if (new Set(lods.map((lod) => lod.resource.uri)).size !== lods.length) {\n throw new Error(\"ModelProcessingManifest LOD resources must be unique.\");\n }\n if (new Set(lods.map((lod) => lod.resource.sha256)).size !== lods.length) {\n throw new Error(\"ModelProcessingManifest LOD resource sha256 hashes must be unique.\");\n }\n if (technicalProfile.lodCount !== lods.length) {\n throw new Error(\"ModelProcessingManifest technicalProfile.lodCount must match lods.\");\n }\n if (technicalProfile.triangleCount !== lods[0]!.triangleCount) {\n throw new Error(\"ModelProcessingManifest technicalProfile.triangleCount must match LOD0.\");\n }\n if (\n lods[0]!.resource.sha256 !== contentHash\n || lods[0]!.resource.byteLength !== technicalProfile.byteLength\n ) {\n throw new Error(\n \"ModelProcessingManifest LOD0 sha256/byteLength must match contentHash and technicalProfile.byteLength.\",\n );\n }\n for (const [index, lod] of lods.entries()) {\n assertCandidateResourceScope(\n lod.resource.uri,\n resolutionId,\n candidateId,\n `ModelProcessingManifest.lods[${index}].resource`,\n );\n }\n const collision = createCollisionRecord(record.collision);\n const collisionPolicy = createCollisionPolicyEvidence(record.collisionPolicy, collision);\n if (technicalProfile.hasCollision !== (collision.kind !== \"none\")) {\n throw new Error(\"ModelProcessingManifest technicalProfile.hasCollision must match collision evidence.\");\n }\n if (\n collision.resource !== undefined\n && lods.some((lod) =>\n lod.resource.uri === collision.resource?.uri\n || lod.resource.sha256 === collision.resource?.sha256)\n ) {\n throw new Error(\"ModelProcessingManifest collision evidence must be separate and distinct from LOD resources.\");\n }\n if (collision.resource !== undefined) {\n assertCandidateResourceScope(\n collision.resource.uri,\n resolutionId,\n candidateId,\n \"ModelProcessingManifest.collision.resource\",\n );\n }\n if (!Array.isArray(record.children) || record.children.length > 256) {\n throw new Error(\"ModelProcessingManifest.children must be a bounded array.\");\n }\n const children = record.children.map((child, index) =>\n createAssemblyChild(child, index, resolutionId, candidateId));\n if (kind === \"leaf\" && children.length !== 0) {\n throw new Error(\"ModelProcessingManifest leaf models must not contain assembly children.\");\n }\n if (kind === \"leaf\" && technicalProfile.partitionCount !== 1) {\n throw new Error(\"ModelProcessingManifest leaf models must have exactly one partition.\");\n }\n if (kind === \"assembly\" && children.length === 0) {\n throw new Error(\"ModelProcessingManifest assembly models require at least one child.\");\n }\n if (new Set(children.map((child) => child.instanceId)).size !== children.length) {\n throw new Error(\"ModelProcessingManifest assembly instanceId values must be unique.\");\n }\n assertAssemblyHierarchy(children);\n const converter = createConverterEvidence(record.converter);\n if (converter.targetFormat !== \"glb\") {\n throw new Error(\"ModelProcessingManifest converter.targetFormat must be glb.\");\n }\n if (converter.outputContentHash !== contentHash) {\n throw new Error(\"ModelProcessingManifest converter outputContentHash must match contentHash.\");\n }\n if (!Array.isArray(record.fidelityEvidence) || record.fidelityEvidence.length > 100) {\n throw new Error(\"ModelProcessingManifest.fidelityEvidence must be a bounded array.\");\n }\n const fidelityEvidence = record.fidelityEvidence.map(createFidelityEvidence);\n if (new Set(fidelityEvidence.map((evidence) => evidence.aspect)).size !== fidelityEvidence.length) {\n throw new Error(\"ModelProcessingManifest fidelity evidence aspects must be unique.\");\n }\n for (const [index, evidence] of fidelityEvidence.entries()) {\n if (evidence.evidenceResource !== undefined) {\n assertCandidateResourceScope(\n evidence.evidenceResource.uri,\n resolutionId,\n candidateId,\n `ModelProcessingManifest.fidelityEvidence[${index}].evidenceResource`,\n );\n }\n }\n const fidelityGate = createFidelityGateEvidence(record.fidelityGate, fidelityEvidence, converter);\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n manifestId: requiredToken(record.manifestId, \"ModelProcessingManifest.manifestId\"),\n resolutionId,\n candidateId,\n kind,\n contentHash,\n closureHash,\n coordinateSystem: CANONICAL_MODEL_COORDINATE_SYSTEM,\n technicalProfile,\n lods,\n collision,\n collisionPolicy,\n children,\n converter,\n fidelityEvidence,\n fidelityGate,\n processedAt: requiredTimestamp(record.processedAt, \"ModelProcessingManifest.processedAt\"),\n });\n}\n\nfunction modelCandidateEquivalent(left: ModelCandidate, right: ModelCandidate): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction finalAssetMatchesCandidate(\n finalAssetRef: ModelAssetRef,\n candidate: ModelCandidate,\n): boolean {\n if (\n finalAssetRef.kind !== candidate.assetRef.kind\n || finalAssetRef.contentHash !== candidate.assetRef.contentHash\n ) {\n return false;\n }\n if (candidate.assetRef.disposition === \"proposed\") {\n return true;\n }\n return finalAssetRef.assetId === candidate.assetRef.asset.assetId\n && finalAssetRef.version === candidate.assetRef.asset.version\n && finalAssetRef.runtimeManifestUri === candidate.assetRef.asset.runtimeManifestUri;\n}\n\nfunction createModelPromotionReceipt(\n input: unknown,\n resolutionId: string,\n candidate: ModelCandidate,\n confirmation: ModelCandidateConfirmation,\n finalAssetRef: ModelAssetRef,\n): ModelPromotionReceipt {\n if (candidate.assetRef.disposition !== \"proposed\") {\n throw new Error(\"ModelPromotionReceipt is only valid for a staged proposed candidate.\");\n }\n const record = assertRecord(input, \"ModelPromotionReceipt\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"promotionId\",\n \"resolutionId\",\n \"candidateId\",\n \"proposalId\",\n \"confirmationId\",\n \"processingManifestId\",\n \"processingContentHash\",\n \"closureHash\",\n \"finalAssetRef\",\n \"promotedAt\",\n \"publicationToken\",\n ], \"ModelPromotionReceipt\");\n assertContractVersion(record, \"ModelPromotionReceipt\");\n if (\n record.resolutionId !== resolutionId\n || record.candidateId !== candidate.candidateId\n || record.proposalId !== candidate.assetRef.proposalId\n || record.confirmationId !== confirmation.confirmationId\n || record.processingManifestId !== candidate.processingManifest.manifestId\n || record.processingContentHash !== candidate.processingManifest.contentHash\n || record.closureHash !== candidate.processingManifest.closureHash\n ) {\n throw new Error(\"ModelPromotionReceipt must bind the exact proposal, confirmation, manifest, and closure.\");\n }\n const receiptAssetRef = createModelAssetRef(record.finalAssetRef);\n if (JSON.stringify(receiptAssetRef) !== JSON.stringify(finalAssetRef)) {\n throw new Error(\"ModelPromotionReceipt.finalAssetRef must match the completed finalAssetRef.\");\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n promotionId: requiredToken(record.promotionId, \"ModelPromotionReceipt.promotionId\"),\n resolutionId,\n candidateId: candidate.candidateId,\n proposalId: candidate.assetRef.proposalId,\n confirmationId: confirmation.confirmationId,\n processingManifestId: candidate.processingManifest.manifestId,\n processingContentHash: candidate.processingManifest.contentHash,\n closureHash: candidate.processingManifest.closureHash,\n finalAssetRef: receiptAssetRef,\n promotedAt: requiredTimestamp(record.promotedAt, \"ModelPromotionReceipt.promotedAt\"),\n publicationToken: requiredAttestationToken(\n record.publicationToken,\n \"ModelPromotionReceipt.publicationToken\",\n ),\n });\n}\n\nfunction numbersApproximatelyEqual(left: number, right: number): boolean {\n return Math.abs(left - right) <= Math.max(1e-6, Math.abs(left) * 1e-6);\n}\n\nfunction evaluateNormalizedModelHardConstraints(\n request: ModelRequestSpec,\n profile: ModelTechnicalProfile,\n): ModelHardConstraintEvaluation {\n const constraints = request.hardConstraints;\n const reasonCodes: string[] = [];\n if (\n constraints.boundsMetres !== undefined\n && (\n constraints.boundsMetres.min.some((axis, index) =>\n !numbersApproximatelyEqual(axis, profile.boundsMetres.min[index]!))\n || constraints.boundsMetres.max.some((axis, index) =>\n !numbersApproximatelyEqual(axis, profile.boundsMetres.max[index]!))\n )\n ) {\n reasonCodes.push(\"bounds-mismatch\");\n }\n if (\n constraints.dimensionsMetres !== undefined\n && ![\n [constraints.dimensionsMetres.width, profile.dimensionsMetres.width],\n [constraints.dimensionsMetres.height, profile.dimensionsMetres.height],\n [constraints.dimensionsMetres.depth, profile.dimensionsMetres.depth],\n ].every(([expected, actual]) => numbersApproximatelyEqual(expected!, actual!))\n ) {\n reasonCodes.push(\"dimensions-mismatch\");\n }\n if (constraints.maxTriangles !== undefined && profile.triangleCount > constraints.maxTriangles) {\n reasonCodes.push(\"triangle-budget-exceeded\");\n }\n if (constraints.maxBytes !== undefined && profile.byteLength > constraints.maxBytes) {\n reasonCodes.push(\"model-byte-budget-exceeded\");\n }\n if (\n constraints.maxTextureBytes !== undefined\n && profile.textureByteLength > constraints.maxTextureBytes\n ) {\n reasonCodes.push(\"texture-byte-budget-exceeded\");\n }\n if (\n constraints.maxTextureDimensionPx !== undefined\n && profile.maxTextureDimensionPx > constraints.maxTextureDimensionPx\n ) {\n reasonCodes.push(\"texture-dimension-budget-exceeded\");\n }\n if (\n constraints.maxPartitionCellMetres !== undefined\n && profile.partitionCellMetres > constraints.maxPartitionCellMetres\n ) {\n reasonCodes.push(\"partition-cell-budget-exceeded\");\n }\n if (\n (constraints.lod === \"required\" && profile.lodCount < 2)\n || (constraints.lod === \"forbidden\" && profile.lodCount !== 1)\n ) {\n reasonCodes.push(\"lod-policy-failed\");\n }\n if (\n (constraints.collision === \"required\" && !profile.hasCollision)\n || (constraints.collision === \"forbidden\" && profile.hasCollision)\n ) {\n reasonCodes.push(\"collision-policy-failed\");\n }\n if (\n (constraints.partition === \"single\" && profile.partitionCount !== 1)\n || (constraints.partition === \"required\" && profile.partitionCount < 2)\n ) {\n reasonCodes.push(\"partition-policy-failed\");\n }\n return deepFreeze({ pass: reasonCodes.length === 0, reasonCodes });\n}\n\n/**\n * Deterministically evaluate a normalized request against technical facts before\n * constructing a full candidate.\n */\nexport function evaluateModelHardConstraintsForProfile(\n requestInput: ModelRequestSpec,\n profileInput: ModelTechnicalProfile,\n): ModelHardConstraintEvaluation {\n const request = createModelRequestSpec(requestInput);\n const profile = createModelTechnicalProfile(profileInput);\n return evaluateNormalizedModelHardConstraints(request, profile);\n}\n\n/** Deterministically evaluate every normalized request hard constraint against a candidate. */\nexport function evaluateModelHardConstraints(\n requestInput: ModelRequestSpec,\n candidateInput: ModelCandidate,\n): ModelHardConstraintEvaluation {\n const request = createModelRequestSpec(requestInput);\n const candidate = createModelCandidate(candidateInput);\n return evaluateModelHardConstraintsForProfile(request, candidate.technicalProfile);\n}\n\n/** Return whether an unknown value is an exact resolution state. */\nexport function isModelResolutionState(value: unknown): value is ModelResolutionState {\n return typeof value === \"string\" && MODEL_RESOLUTION_STATES.includes(value as ModelResolutionState);\n}\n\n/** Validate and deeply freeze an asynchronous model-resolution record. */\nexport function createModelResolution(input: unknown): ModelResolution {\n const record = assertRecord(input, \"ModelResolution\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"resolutionId\",\n \"request\",\n \"attempts\",\n \"state\",\n \"candidates\",\n \"bestCandidate\",\n \"confirmation\",\n \"promotionReceipt\",\n \"refinementQuestions\",\n \"finalAssetRef\",\n \"stateReasonCode\",\n \"createdAt\",\n \"updatedAt\",\n ], \"ModelResolution\");\n assertContractVersion(record, \"ModelResolution\");\n const resolutionId = requiredModelPathSegment(record.resolutionId, \"ModelResolution.resolutionId\");\n const request = createModelRequestSpec(record.request);\n const createdAt = requiredTimestamp(record.createdAt, \"ModelResolution.createdAt\");\n const updatedAt = requiredTimestamp(record.updatedAt, \"ModelResolution.updatedAt\");\n if (Date.parse(updatedAt) < Date.parse(createdAt)) {\n throw new Error(\"ModelResolution.updatedAt must not precede createdAt.\");\n }\n const state = requiredEnum(record.state, MODEL_RESOLUTION_STATES, \"ModelResolution.state\");\n if (!Array.isArray(record.candidates) || record.candidates.length > MAX_CANDIDATES) {\n throw new Error(`ModelResolution.candidates must contain at most ${MAX_CANDIDATES} items.`);\n }\n const candidates = record.candidates.map(createModelCandidate);\n if (new Set(candidates.map((candidate) => candidate.candidateId)).size !== candidates.length) {\n throw new Error(\"ModelResolution candidateId values must be unique.\");\n }\n if (new Set(candidates.map((candidate) => candidate.confirmationToken)).size !== candidates.length) {\n throw new Error(\"ModelResolution candidate confirmationToken values must be unique.\");\n }\n for (const candidate of candidates) {\n if (candidate.resolutionId !== resolutionId) {\n throw new Error(\"ModelResolution candidates must be scoped to the resolutionId.\");\n }\n if (JSON.stringify(candidate.match.request) !== JSON.stringify(request)) {\n throw new Error(\"ModelResolution candidate match assessments must bind the immutable request revision.\");\n }\n const evaluation = evaluateModelHardConstraints(request, candidate);\n if (candidate.match.hardConstraintPass !== evaluation.pass) {\n throw new Error(\"ModelResolution candidate hardConstraintPass must match deterministic evaluation.\");\n }\n if (evaluation.reasonCodes.some((reasonCode) => !candidate.match.reasonCodes.includes(reasonCode))) {\n throw new Error(\"ModelResolution candidate match reasonCodes must include every failed hard constraint.\");\n }\n const evidenceTimes = [\n candidate.provenance.capturedAt,\n candidate.rights.reviewedAt,\n candidate.processingManifest.processedAt,\n candidate.processingManifest.fidelityGate.evaluatedAt,\n candidate.renderEvidence.renderedAt,\n ...candidate.hardGates.map((gate) => gate.evaluatedAt),\n ];\n if (evidenceTimes.some((timestamp) => Date.parse(timestamp) > Date.parse(updatedAt))) {\n throw new Error(\"ModelResolution candidate evidence timestamps must not exceed updatedAt.\");\n }\n }\n let bestCandidate: ModelCandidate | undefined;\n if (record.bestCandidate !== undefined) {\n const requestedBest = createModelCandidate(record.bestCandidate);\n bestCandidate = candidates.find((candidate) => candidate.candidateId === requestedBest.candidateId);\n if (bestCandidate === undefined || !modelCandidateEquivalent(bestCandidate, requestedBest)) {\n throw new Error(\"ModelResolution.bestCandidate must exactly match a candidate.\");\n }\n }\n if ([\"awaiting-confirmation\", \"promoting\", \"completed\"].includes(state) && bestCandidate === undefined) {\n throw new Error(`ModelResolution ${state} state requires bestCandidate.`);\n }\n if (\n [\"awaiting-confirmation\", \"promoting\", \"completed\"].includes(state)\n && bestCandidate !== undefined\n && !isModelCandidateConfirmable(bestCandidate)\n ) {\n throw new Error(\n `ModelResolution ${state} bestCandidate must pass hard, assurance, rights, and view gates.`,\n );\n }\n let confirmation: ModelCandidateConfirmation | undefined;\n if (record.confirmation !== undefined) {\n if (bestCandidate === undefined) {\n throw new Error(\"ModelResolution confirmation requires bestCandidate.\");\n }\n confirmation = createModelCandidateConfirmation(record.confirmation, bestCandidate, resolutionId);\n if (\n Date.parse(confirmation.confirmedAt) < Date.parse(createdAt)\n || Date.parse(confirmation.confirmedAt) > Date.parse(updatedAt)\n ) {\n throw new Error(\"ModelResolution confirmation.confirmedAt must fall between createdAt and updatedAt.\");\n }\n }\n if ([\"promoting\", \"completed\"].includes(state) && confirmation === undefined) {\n throw new Error(`ModelResolution ${state} state requires confirmation evidence.`);\n }\n if (state === \"awaiting-confirmation\" && confirmation !== undefined) {\n throw new Error(\"ModelResolution awaiting-confirmation state must not already contain confirmation evidence.\");\n }\n if (\n confirmation !== undefined\n && ![\"promoting\", \"completed\", \"failed\", \"cancelled\"].includes(state)\n ) {\n throw new Error(`ModelResolution confirmation evidence is not allowed in ${state} state.`);\n }\n const refinementQuestions = record.refinementQuestions === undefined\n ? []\n : stringList(record.refinementQuestions, \"ModelResolution.refinementQuestions\", { maxItems: 3 });\n const stateReasonCode = record.stateReasonCode === undefined\n ? undefined\n : requiredToken(record.stateReasonCode, \"ModelResolution.stateReasonCode\");\n if (\n [\"failed\", \"cancelled\", \"unresolved\"].includes(state)\n && stateReasonCode === undefined\n ) {\n throw new Error(`ModelResolution ${state} state requires stateReasonCode.`);\n }\n if (\n state === \"awaiting-confirmation\"\n && bestCandidate?.match.assurance === \"low\"\n && refinementQuestions.length === 0\n ) {\n throw new Error(\"ModelResolution low-assurance bestCandidate requires refinementQuestions.\");\n }\n const finalAssetRef = record.finalAssetRef === undefined\n ? undefined\n : createModelAssetRef(record.finalAssetRef);\n if (state === \"completed\" && finalAssetRef === undefined) {\n throw new Error(\"ModelResolution completed state requires finalAssetRef.\");\n }\n if (state !== \"completed\" && finalAssetRef !== undefined) {\n throw new Error(\"ModelResolution finalAssetRef is only allowed for completed state.\");\n }\n if (\n finalAssetRef !== undefined\n && bestCandidate !== undefined\n && !finalAssetMatchesCandidate(finalAssetRef, bestCandidate)\n ) {\n throw new Error(\"ModelResolution finalAssetRef must match bestCandidate kind, hash, and immutable identity.\");\n }\n let promotionReceipt: ModelPromotionReceipt | undefined;\n if (record.promotionReceipt !== undefined) {\n if (\n state !== \"completed\"\n || bestCandidate === undefined\n || confirmation === undefined\n || finalAssetRef === undefined\n ) {\n throw new Error(\"ModelResolution promotionReceipt is only allowed for a completed staged promotion.\");\n }\n promotionReceipt = createModelPromotionReceipt(\n record.promotionReceipt,\n resolutionId,\n bestCandidate,\n confirmation,\n finalAssetRef,\n );\n if (\n Date.parse(promotionReceipt.promotedAt) < Date.parse(confirmation.confirmedAt)\n || Date.parse(promotionReceipt.promotedAt) > Date.parse(updatedAt)\n ) {\n throw new Error(\"ModelResolution promotionReceipt.promotedAt must follow confirmation and not exceed updatedAt.\");\n }\n }\n if (\n state === \"completed\"\n && bestCandidate?.assetRef.disposition === \"proposed\"\n && promotionReceipt === undefined\n ) {\n throw new Error(\"ModelResolution completed proposed candidates require a promotionReceipt.\");\n }\n if (bestCandidate?.assetRef.disposition === \"existing\" && promotionReceipt !== undefined) {\n throw new Error(\"ModelResolution existing catalog selections must not include a promotionReceipt.\");\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n resolutionId,\n request,\n attempts: requiredInteger(record.attempts, \"ModelResolution.attempts\", 1, MAX_ATTEMPTS),\n state,\n candidates,\n ...(bestCandidate === undefined ? {} : { bestCandidate }),\n ...(confirmation === undefined ? {} : { confirmation }),\n ...(promotionReceipt === undefined ? {} : { promotionReceipt }),\n refinementQuestions,\n ...(finalAssetRef === undefined ? {} : { finalAssetRef }),\n ...(stateReasonCode === undefined ? {} : { stateReasonCode }),\n createdAt,\n updatedAt,\n });\n}\n\nfunction createGeneratorSeed(value: unknown, fieldName: string): string {\n const seed = requiredString(value, fieldName, 128);\n if (seed.length < 8) {\n throw new Error(`${fieldName} must contain at least eight characters.`);\n }\n assertNoDirectUrl(seed, fieldName);\n return seed;\n}\n\n/** Validate and normalize an unknown generator request. */\nexport function createModelGeneratorRequest(input: unknown): ModelGeneratorRequest {\n const record = assertRecord(input, \"ModelGeneratorRequest\");\n assertAllowedKeys(record, [\n \"generationId\",\n \"request\",\n \"budgets\",\n \"seed\",\n \"deadline\",\n ], \"ModelGeneratorRequest\");\n const budgets = assertRecord(record.budgets, \"ModelGeneratorRequest.budgets\");\n assertAllowedKeys(budgets, [\n \"maxDurationMs\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n ], \"ModelGeneratorRequest.budgets\");\n const seed = createGeneratorSeed(record.seed, \"ModelGeneratorRequest.seed\");\n const maxBytes = requiredInteger(\n budgets.maxBytes,\n \"ModelGeneratorRequest budget maxBytes\",\n 1,\n 10_000_000_000,\n );\n const maxTextureBytes = requiredInteger(\n budgets.maxTextureBytes,\n \"ModelGeneratorRequest budget maxTextureBytes\",\n 1,\n 10_000_000_000,\n );\n if (maxTextureBytes > maxBytes) {\n throw new Error(\"ModelGeneratorRequest maxTextureBytes must not exceed maxBytes.\");\n }\n return deepFreeze({\n generationId: requiredModelPathSegment(record.generationId, \"ModelGeneratorRequest.generationId\"),\n request: createModelRequestSpec(record.request),\n budgets: {\n maxDurationMs: requiredInteger(budgets.maxDurationMs, \"ModelGeneratorRequest budget maxDurationMs\", 1, 300_000),\n maxTriangles: requiredInteger(budgets.maxTriangles, \"ModelGeneratorRequest budget maxTriangles\", 1, 10_000_000),\n maxBytes,\n maxTextureBytes,\n maxTextureDimensionPx: requiredInteger(budgets.maxTextureDimensionPx, \"ModelGeneratorRequest budget maxTextureDimensionPx\", 1, 32_768),\n },\n seed,\n deadline: requiredTimestamp(record.deadline, \"ModelGeneratorRequest.deadline\"),\n });\n}\n\nconst MODEL_GENERATOR_ARTIFACT_ROLES = [\n \"model-entrypoint\",\n \"model-dependency\",\n \"binary\",\n \"texture\",\n \"metadata\",\n] as const;\n\nconst MODEL_GENERATOR_BUDGET_NAMES = [\n \"maxDurationMs\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n] as const;\n\nconst MODEL_GENERATOR_REASON_RETRYABILITY: Readonly<Record<string, boolean>> = Object.freeze({\n \"capacity-unavailable\": true,\n \"provider-unavailable\": true,\n \"authentication-required\": true,\n \"rate-limited\": true,\n \"unsupported-request\": false,\n \"provider-failed\": true,\n \"invalid-generator-output\": false,\n \"internal-failure\": true,\n \"caller-aborted\": false,\n \"deadline-exceeded\": true,\n superseded: false,\n \"service-shutdown\": true,\n});\n\nfunction assertGeneratorRetryability(reasonCode: string, retryable: boolean): void {\n if (MODEL_GENERATOR_REASON_RETRYABILITY[reasonCode] !== retryable) {\n throw new Error(`ModelGeneratorResult retryable must match stable reason ${reasonCode}.`);\n }\n}\n\nfunction createModelGeneratorArtifact(value: unknown, index: number): ModelGeneratorArtifact {\n const fieldName = `ModelGeneratorResult.sourceBundle.artifacts[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\n \"uri\",\n \"byteLength\",\n \"sha256\",\n \"contentType\",\n \"role\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n ], fieldName);\n const resource = createModelResourceRef({\n uri: record.uri,\n byteLength: record.byteLength,\n sha256: record.sha256,\n contentType: record.contentType,\n });\n const role = requiredEnum(record.role, MODEL_GENERATOR_ARTIFACT_ROLES, `${fieldName}.role`);\n const compatibleContentTypes: Readonly<Record<ModelGeneratorArtifactRole, readonly string[]>> = {\n \"model-entrypoint\": [\"model/gltf-binary\", \"model/gltf+json\"],\n \"model-dependency\": [\"model/gltf-binary\", \"model/gltf+json\"],\n binary: [\"application/octet-stream\"],\n texture: [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/ktx2\"],\n metadata: [\"application/json\"],\n };\n if (!compatibleContentTypes[role].includes(resource.contentType.toLowerCase())) {\n throw new Error(`${fieldName}.contentType is not compatible with artifact role ${role}.`);\n }\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n `${fieldName}.textureByteLength`,\n 0,\n resource.byteLength,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n `${fieldName}.maxTextureDimensionPx`,\n 0,\n 32_768,\n );\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(`${fieldName} texture bytes and dimensions must both be zero or both positive.`);\n }\n if (role === \"texture\" && textureByteLength !== resource.byteLength) {\n throw new Error(`${fieldName} standalone texture bytes must equal artifact byteLength.`);\n }\n if ([\"binary\", \"metadata\"].includes(role) && textureByteLength !== 0) {\n throw new Error(`${fieldName} non-model metadata/binary artifacts must not claim embedded textures.`);\n }\n return { ...resource, role, textureByteLength, maxTextureDimensionPx };\n}\n\nfunction createModelGeneratorUsage(value: unknown): ModelGeneratorUsage {\n const record = assertRecord(value, \"ModelGeneratorResult.sourceBundle.usage\");\n assertAllowedKeys(record, [\n \"durationMs\",\n \"triangleCount\",\n \"byteLength\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n ], \"ModelGeneratorResult.sourceBundle.usage\");\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n \"ModelGeneratorResult.sourceBundle.usage.textureByteLength\",\n 0,\n Number.MAX_SAFE_INTEGER,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelGeneratorResult.sourceBundle.usage.maxTextureDimensionPx\",\n 0,\n 32_768,\n );\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(\"ModelGeneratorResult texture usage bytes and dimensions must both be zero or both positive.\");\n }\n return {\n durationMs: requiredInteger(record.durationMs, \"ModelGeneratorResult.sourceBundle.usage.durationMs\", 0, 300_000),\n triangleCount: requiredInteger(record.triangleCount, \"ModelGeneratorResult.sourceBundle.usage.triangleCount\", 1, 10_000_000),\n byteLength: requiredInteger(record.byteLength, \"ModelGeneratorResult.sourceBundle.usage.byteLength\", 1, Number.MAX_SAFE_INTEGER),\n textureByteLength,\n maxTextureDimensionPx,\n };\n}\n\nfunction createGeneratorTerminalEvidence(\n record: Record<string, unknown>,\n expected: ModelGeneratorRequest,\n): ModelGeneratorTerminalEvidence {\n const generationId = requiredModelPathSegment(record.generationId, \"ModelGeneratorResult.generationId\");\n if (generationId !== expected.generationId) {\n throw new Error(\"ModelGeneratorResult.generationId must match the generator request.\");\n }\n const diagnosticId = record.diagnosticId === undefined\n ? undefined\n : requiredToken(record.diagnosticId, \"ModelGeneratorResult.diagnosticId\");\n return {\n generationId,\n retryable: requiredBoolean(record.retryable, \"ModelGeneratorResult.retryable\"),\n occurredAt: requiredTimestamp(record.occurredAt, \"ModelGeneratorResult.occurredAt\"),\n ...(diagnosticId === undefined ? {} : { diagnosticId }),\n };\n}\n\n/** Validate and deeply freeze a request-bound generator outcome. */\nexport function createModelGeneratorResult(\n input: unknown,\n expectedRequest: ModelGeneratorRequest,\n): ModelGeneratorResult {\n const expected = createModelGeneratorRequest(expectedRequest);\n const record = assertRecord(input, \"ModelGeneratorResult\");\n const status = requiredEnum(record.status, [\n \"disabled\",\n \"generated\",\n \"unavailable\",\n \"failed\",\n \"cancelled\",\n \"budget-exceeded\",\n ] as const, \"ModelGeneratorResult.status\");\n const generationId = requiredModelPathSegment(record.generationId, \"ModelGeneratorResult.generationId\");\n if (generationId !== expected.generationId) {\n throw new Error(\"ModelGeneratorResult.generationId must match the generator request.\");\n }\n if (status === \"disabled\") {\n assertAllowedKeys(record, [\"status\", \"generationId\", \"reasonCode\"], \"ModelGeneratorResult\");\n if (record.reasonCode !== MODEL_GENERATOR_DISABLED_REASON_CODE) {\n throw new Error(\n `ModelGeneratorResult.reasonCode must be ${MODEL_GENERATOR_DISABLED_REASON_CODE}.`,\n );\n }\n return deepFreeze({\n status,\n generationId,\n reasonCode: MODEL_GENERATOR_DISABLED_REASON_CODE,\n });\n }\n\n if (status === \"generated\") {\n assertAllowedKeys(record, [\"status\", \"generationId\", \"sourceBundle\"], \"ModelGeneratorResult\");\n const sourceBundle = assertRecord(record.sourceBundle, \"ModelGeneratorResult.sourceBundle\");\n assertAllowedKeys(sourceBundle, [\n \"bundleId\",\n \"generationId\",\n \"entrypointUri\",\n \"artifacts\",\n \"generator\",\n \"generatedAt\",\n \"seed\",\n \"context\",\n \"usage\",\n ], \"ModelGeneratorResult.sourceBundle\");\n const bundleId = requiredModelPathSegment(sourceBundle.bundleId, \"ModelGeneratorResult.sourceBundle.bundleId\");\n const bundleGenerationId = requiredModelPathSegment(\n sourceBundle.generationId,\n \"ModelGeneratorResult.sourceBundle.generationId\",\n );\n if (bundleId !== generationId || bundleGenerationId !== generationId) {\n throw new Error(\"ModelGeneratorResult source bundle identifiers must match generationId.\");\n }\n if (!Array.isArray(sourceBundle.artifacts) || sourceBundle.artifacts.length < 1 || sourceBundle.artifacts.length > 32) {\n throw new Error(\"ModelGeneratorResult.sourceBundle.artifacts must contain one to 32 internal resources.\");\n }\n const artifacts = sourceBundle.artifacts.map(createModelGeneratorArtifact);\n if (new Set(artifacts.map((artifact) => artifact.uri)).size !== artifacts.length) {\n throw new Error(\"ModelGeneratorResult.sourceBundle.artifacts must have unique URIs.\");\n }\n const namespace = `mcp://models/generations/${generationId}/source/`;\n if (artifacts.some((artifact) => !artifact.uri.startsWith(namespace))) {\n throw new Error(\"ModelGeneratorResult artifacts must remain inside the generation source namespace.\");\n }\n const entrypointUri = assertModelUri(sourceBundle.entrypointUri, \"ModelGeneratorResult.sourceBundle.entrypointUri\");\n const entrypointArtifacts = artifacts.filter((artifact) => artifact.role === \"model-entrypoint\");\n if (\n entrypointArtifacts.length !== 1\n || entrypointArtifacts[0]?.uri !== entrypointUri\n || !artifacts.some((artifact) => artifact.uri === entrypointUri)\n ) {\n throw new Error(\"ModelGeneratorResult source bundle requires exactly one model-entrypoint matching entrypointUri.\");\n }\n const generator = assertRecord(sourceBundle.generator, \"ModelGeneratorResult.sourceBundle.generator\");\n assertAllowedKeys(generator, [\"id\", \"version\"], \"ModelGeneratorResult.sourceBundle.generator\");\n const generatedAt = requiredTimestamp(sourceBundle.generatedAt, \"ModelGeneratorResult.sourceBundle.generatedAt\");\n if (Date.parse(generatedAt) > Date.parse(expected.deadline)) {\n throw new Error(\"ModelGeneratorResult generatedAt must not exceed the request deadline.\");\n }\n const seed = createGeneratorSeed(sourceBundle.seed, \"ModelGeneratorResult.sourceBundle.seed\");\n if (seed !== expected.seed) {\n throw new Error(\"ModelGeneratorResult source bundle seed must match the generator request.\");\n }\n const context = createModelGeneratorRequest(sourceBundle.context);\n if (JSON.stringify(context) !== JSON.stringify(expected)) {\n throw new Error(\"ModelGeneratorResult source bundle context must exactly match the generator request.\");\n }\n const usage = createModelGeneratorUsage(sourceBundle.usage);\n const aggregateBytes = artifacts.reduce((total, artifact) => total + artifact.byteLength, 0);\n const textureBytes = artifacts.reduce(\n (total, artifact) => total + artifact.textureByteLength,\n 0,\n );\n const maxTextureDimensionPx = Math.max(\n 0,\n ...artifacts.map((artifact) => artifact.maxTextureDimensionPx),\n );\n if (!Number.isSafeInteger(aggregateBytes) || usage.byteLength !== aggregateBytes) {\n throw new Error(\"ModelGeneratorResult usage.byteLength must equal aggregate artifact bytes.\");\n }\n if (usage.textureByteLength !== textureBytes) {\n throw new Error(\"ModelGeneratorResult usage.textureByteLength must equal texture artifact bytes.\");\n }\n if (usage.maxTextureDimensionPx !== maxTextureDimensionPx) {\n throw new Error(\"ModelGeneratorResult usage.maxTextureDimensionPx must equal measured artifact texture dimensions.\");\n }\n if (\n usage.durationMs > expected.budgets.maxDurationMs\n || usage.triangleCount > expected.budgets.maxTriangles\n || usage.byteLength > expected.budgets.maxBytes\n || usage.textureByteLength > expected.budgets.maxTextureBytes\n || usage.maxTextureDimensionPx > expected.budgets.maxTextureDimensionPx\n ) {\n throw new Error(\"ModelGeneratorResult generated usage exceeds the request budget.\");\n }\n return deepFreeze({\n status,\n generationId,\n sourceBundle: {\n bundleId,\n generationId,\n entrypointUri,\n artifacts,\n generator: {\n id: requiredToken(generator.id, \"ModelGeneratorResult.sourceBundle.generator.id\"),\n version: assetVersion(generator.version, \"ModelGeneratorResult.sourceBundle.generator.version\"),\n },\n generatedAt,\n seed,\n context,\n usage,\n },\n });\n }\n\n const terminalAllowedKeys = [\n \"status\",\n \"generationId\",\n \"reasonCode\",\n \"retryable\",\n \"occurredAt\",\n \"diagnosticId\",\n ] as const;\n if (status === \"budget-exceeded\") {\n assertAllowedKeys(record, [...terminalAllowedKeys, \"violations\"], \"ModelGeneratorResult\");\n if (record.reasonCode !== \"generator-budget-exceeded\" || record.retryable !== false) {\n throw new Error(\"ModelGeneratorResult budget-exceeded must use its fixed reasonCode and retryable false.\");\n }\n if (!Array.isArray(record.violations) || record.violations.length < 1 || record.violations.length > 5) {\n throw new Error(\"ModelGeneratorResult budget violations must contain one to five entries.\");\n }\n const violations = record.violations.map((value, index): ModelGeneratorBudgetViolation => {\n const fieldName = `ModelGeneratorResult.violations[${index}]`;\n const violation = assertRecord(value, fieldName);\n assertAllowedKeys(violation, [\"budget\", \"limit\", \"observed\"], fieldName);\n const budget = requiredEnum(violation.budget, MODEL_GENERATOR_BUDGET_NAMES, `${fieldName}.budget`);\n const limit = requiredInteger(violation.limit, `${fieldName}.limit`, 0, Number.MAX_SAFE_INTEGER);\n const observed = requiredInteger(violation.observed, `${fieldName}.observed`, 0, Number.MAX_SAFE_INTEGER);\n if (limit !== expected.budgets[budget] || observed <= limit) {\n throw new Error(`${fieldName} limit must match the request budget and observed must exceed it.`);\n }\n return { budget, limit, observed };\n });\n if (new Set(violations.map((violation) => violation.budget)).size !== violations.length) {\n throw new Error(\"ModelGeneratorResult budget violation names must be unique.\");\n }\n const terminal = createGeneratorTerminalEvidence(record, expected);\n return deepFreeze({\n status,\n ...terminal,\n reasonCode: \"generator-budget-exceeded\",\n retryable: false,\n violations,\n });\n }\n\n assertAllowedKeys(record, terminalAllowedKeys, \"ModelGeneratorResult\");\n const terminal = createGeneratorTerminalEvidence(record, expected);\n if (status === \"unavailable\") {\n const reasonCode = requiredEnum(record.reasonCode, [\n \"capacity-unavailable\",\n \"provider-unavailable\",\n \"authentication-required\",\n \"rate-limited\",\n \"unsupported-request\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n }\n if (status === \"failed\") {\n const reasonCode = requiredEnum(record.reasonCode, [\n \"provider-failed\",\n \"invalid-generator-output\",\n \"internal-failure\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n }\n const reasonCode = requiredEnum(record.reasonCode, [\n \"caller-aborted\",\n \"deadline-exceeded\",\n \"superseded\",\n \"service-shutdown\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n}\n\n/** Create the fail-closed Phase 1 generator port; it never performs generation. */\nexport function createDisabledModelGeneratorPort(): ModelGeneratorPort {\n return Object.freeze({\n enabled: false,\n async generate(\n input: ModelGeneratorRequest,\n options: ModelGeneratorCallOptions = {},\n ): Promise<DisabledModelGeneratorResult> {\n if (options.signal !== undefined) {\n if (typeof options.signal.throwIfAborted !== \"function\") {\n throw new Error(\"ModelGeneratorPort signal must be an AbortSignal.\");\n }\n options.signal.throwIfAborted();\n }\n const request = createModelGeneratorRequest(input);\n return deepFreeze({\n status: \"disabled\",\n generationId: request.generationId,\n reasonCode: MODEL_GENERATOR_DISABLED_REASON_CODE,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,QAAM,YAAY,oBAAI,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,MAAI,UAAU,KAAK,CAAC,QAAQ,UAAU,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,SAAS,UAAU,QAAQ;AAC/F,UAAM,IAAI,MAAM,GAAG,SAAS,kEAAkE;AAAA,EAChG;AACA,MAAI,OAAO,SAAS,OAAO;AACzB,UAAM,IAAI,MAAM,GAAG,SAAS,wCAAwC;AAAA,EACtE;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAgB,WAA2B;AAC9D,MAAI,OAAO,UAAU,YAAY,CAACC,eAAc,KAAK,KAAK,GAAG;AAC3D,UAAM,IAAI,MAAM,GAAG,SAAS,kDAAkD;AAAA,EAChF;AACA,SAAO;AACT;AAEA,SAAS,qBAAqB,OAAgB,WAA2B;AACvE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,GAAG;AAC1D,UAAM,IAAI,MAAM,GAAG,SAAS,8BAA8B;AAAA,EAC5D;AACA,SAAO;AACT;","names":["terminal","reasonCode","ASSET_ID_PATTERN","SHA256_PATTERN","TOKEN_PATTERN","assertRecord","module"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/asset-version.ts","../src/model-resolution.ts","../src/pvox-hash-preimage.ts","../src/pvox-model-resolution.ts","../src/pvox-model-resolution-schema.ts"],"sourcesContent":["import {\n GPU_SHADER_STORE_FEATURE_FLAG,\n GPU_SHADER_STYLE_SELECTION_CAPABILITY,\n SHADER_VALIDATION_EVIDENCE_VERSION,\n SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES,\n SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES,\n canonicalizeGpuContract,\n computeSha256,\n parseGpuInterfaceManifest,\n parseJsonBytes,\n parseModelGpuCompatibilityDescriptor,\n parseShaderStyleProfileManifest,\n parseShaderVersionManifest,\n} from \"@plasius/gpu-shader\";\nimport type {\n GpuInterfaceManifest,\n GpuInterfaceRef,\n ModelGpuCompatibilityDescriptor,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n Sha256Hex,\n} from \"@plasius/gpu-shader\";\nimport {\n assertAssetVersion,\n assertImmutableAssetVersion,\n} from \"./asset-version.js\";\n\nexport const ASSET_CONTRACTS_PACKAGE = \"@plasius/asset-contracts\";\n\nexport {\n assertAssetVersion,\n assertImmutableAssetVersion,\n};\nexport * from \"./model-resolution.js\";\nexport * from \"./pvox-hash-preimage.js\";\nexport * from \"./pvox-model-resolution.js\";\nexport * from \"./pvox-model-resolution-schema.js\";\nexport {\n GPU_SHADER_STORE_FEATURE_FLAG,\n GPU_SHADER_STYLE_SELECTION_CAPABILITY,\n};\nexport type {\n GpuInterfaceManifest,\n GpuInterfaceRef,\n ModelGpuCompatibilityDescriptor,\n ShaderStyleProfileManifest,\n ShaderStyleProfileRef,\n ShaderValidationEvidenceRef,\n ShaderVersionManifest,\n ShaderVersionRef,\n Sha256Hex,\n};\nexport const UNIFIED_ASSET_PIPELINE_FEATURE_FLAG_ID = \"asset.pipeline.unified-ai-assets.enabled\";\nexport const ASSET_PIPELINE_MCP_CAPABILITY = \"asset.pipeline.mcp.manage\";\nexport const ASSET_PIPELINE_REVIEW_CAPABILITY = \"asset.pipeline.review.approve\";\n\n/** Canonical content type required for immutable WebGPU shader modules. */\nexport const ASSET_WGSL_CONTENT_TYPE = \"text/wgsl; charset=utf-8\" as const;\n/** Canonical content type for JSON lifecycle artifacts. */\nexport const ASSET_JSON_CONTENT_TYPE = \"application/json\" as const;\n\n/** Closed asset categories supported by the unified model-storage lifecycle. */\nexport const ASSET_KINDS = Object.freeze([\n \"model\",\n \"gpu-interface\",\n \"shader\",\n \"shader-style-profile\",\n \"shader-validation-evidence\",\n] as const);\n\n/** Legacy and GPU-specific roles for files inside one immutable asset version. */\nexport const ASSET_FILE_ROLES = Object.freeze([\n \"model\",\n \"binary\",\n \"texture\",\n \"manifest\",\n \"screenshot\",\n \"metadata\",\n \"wgsl\",\n \"gpu-interface-manifest\",\n \"shader-manifest\",\n \"shader-style-profile-manifest\",\n \"shader-validation-evidence\",\n \"shader-validation-attestation\",\n \"shader-qualification-fixture\",\n \"shader-compile-unit-inventory\",\n \"shader-matrix\",\n] as const);\n\nexport const ASSET_JOB_STATES = Object.freeze([\n \"requested\",\n \"intake-uploaded\",\n \"validated\",\n \"processing\",\n \"processed\",\n \"rendering-review\",\n \"reviewed\",\n \"awaiting-approval\",\n \"approved\",\n \"promoting\",\n \"promoted\",\n \"rejected\",\n \"failed\",\n \"rolled-back\",\n] as const);\n\nexport const ASSET_SOURCE_ADAPTERS = Object.freeze([\n \"local-import\",\n \"ai-generate\",\n \"ai-modify\",\n \"texture-regenerate\",\n \"processor-retry\",\n] as const);\n\nexport const ASSET_SCREENSHOT_KINDS = Object.freeze([\n \"hero\",\n \"front\",\n \"back\",\n \"left\",\n \"right\",\n \"top\",\n \"material-closeup\",\n \"wireframe-density\",\n \"normal-debug\",\n \"lod-comparison\",\n \"collision-proxy\",\n \"scale-reference\",\n] as const);\n\nexport const ASSET_REVIEW_SEVERITIES = Object.freeze([\n \"info\",\n \"warning\",\n \"blocking\",\n] as const);\n\nexport const ASSET_PROMOTION_OUTCOMES = Object.freeze([\n \"promoted\",\n \"rolled-back\",\n] as const);\n\nexport type AssetJobState = typeof ASSET_JOB_STATES[number];\nexport type AssetSourceAdapter = typeof ASSET_SOURCE_ADAPTERS[number];\nexport type AssetScreenshotKind = typeof ASSET_SCREENSHOT_KINDS[number];\nexport type AssetReviewSeverity = typeof ASSET_REVIEW_SEVERITIES[number];\nexport type AssetPromotionOutcome = typeof ASSET_PROMOTION_OUTCOMES[number];\nexport type AssetKind = typeof ASSET_KINDS[number];\nexport type AssetFileRole = typeof ASSET_FILE_ROLES[number];\n\nexport interface AssetFileDescriptor {\n readonly path: string;\n readonly byteLength: number;\n readonly sha256: string;\n readonly contentType: string;\n readonly role: AssetFileRole;\n /** Required only for WGSL files; binds the Blob path to one shader module. */\n readonly moduleId?: string;\n}\n\nexport interface AssetManifest {\n /** Omitted only by legacy callers created before typed asset lifecycles. */\n readonly assetKind?: AssetKind;\n readonly assetId: string;\n readonly version: string;\n readonly entrypoint: string;\n readonly files: readonly AssetFileDescriptor[];\n readonly sourceAdapter: AssetSourceAdapter;\n readonly createdAt: string;\n}\n\n/** Asset manifest with a required discriminator while legacy manifests remain valid. */\nexport interface TypedAssetManifest<K extends AssetKind> extends AssetManifest {\n readonly assetKind: K;\n}\n\n/** Model asset extended with its reflected GPU ABI and discoverable default style. */\nexport interface ModelAssetManifest extends TypedAssetManifest<\"model\"> {\n readonly gpuInterface: GpuInterfaceRef;\n readonly modelAbiHash: Sha256Hex;\n readonly providedSemantics: readonly string[];\n readonly defaultStyleProfile: ShaderStyleProfileRef | null;\n}\n\n/** Input permits a model to omit its default style while preserving explicit null output. */\nexport type ModelAssetManifestInput = Omit<ModelAssetManifest, \"defaultStyleProfile\"> & {\n readonly defaultStyleProfile?: ShaderStyleProfileRef | null;\n};\n\n/** Lifecycle envelope for one generated GPU-interface manifest. */\nexport interface GpuInterfaceAssetManifest extends TypedAssetManifest<\"gpu-interface\"> {\n readonly gpuInterfaceManifest: GpuInterfaceManifest;\n}\n\n/** Lifecycle envelope for one exact, independently versioned WGSL shader. */\nexport interface ShaderAssetManifest extends TypedAssetManifest<\"shader\"> {\n readonly shaderManifest: ShaderVersionManifest;\n}\n\n/** Lifecycle envelope for a profile that pins exact shader versions by render role. */\nexport interface ShaderStyleProfileAssetManifest extends TypedAssetManifest<\"shader-style-profile\"> {\n readonly styleProfileManifest: ShaderStyleProfileManifest;\n}\n\n/** Lifecycle envelope for universal matrix evidence and its external attestation reference. */\nexport interface ShaderValidationEvidenceAssetManifest extends TypedAssetManifest<\"shader-validation-evidence\"> {\n readonly validationEvidence: ShaderValidationEvidenceRef;\n}\n\n/** Post-storage inputs used to construct a non-self-referential interface ref. */\nexport interface GpuInterfaceRefInput {\n readonly manifest: GpuInterfaceManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Post-storage inputs used to construct a non-self-referential shader ref. */\nexport interface ShaderVersionRefInput {\n readonly manifest: ShaderVersionManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Post-storage inputs used to construct a non-self-referential style ref. */\nexport interface ShaderStyleProfileRefInput {\n readonly manifest: ShaderStyleProfileManifest;\n readonly manifestBytes: Uint8Array;\n readonly manifestUri: string;\n}\n\n/** Exact bytes supplied to a typed storage/promotion validation boundary. */\nexport interface GpuAssetFileValidationInput {\n readonly manifest: GpuAssetManifest;\n readonly files: ReadonlyMap<string, Uint8Array>;\n}\n\n/** All schema-driven GPU asset envelopes accepted by the storage pipeline. */\nexport type GpuAssetManifest =\n | ModelAssetManifest\n | GpuInterfaceAssetManifest\n | ShaderAssetManifest\n | ShaderStyleProfileAssetManifest\n | ShaderValidationEvidenceAssetManifest;\n\nexport interface AssetScreenshotPlanItem {\n readonly kind: AssetScreenshotKind;\n readonly label: string;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface AssetReviewFinding {\n readonly severity: AssetReviewSeverity;\n readonly code: string;\n readonly message: string;\n readonly artifactPath?: string;\n readonly evidenceUri?: string;\n}\n\nexport interface AssetReviewReport {\n readonly assetId: string;\n readonly version: string;\n readonly passed: boolean;\n readonly findings: readonly AssetReviewFinding[];\n readonly reviewedAt: string;\n}\n\nexport interface AssetJobRecord {\n readonly jobId: string;\n readonly assetId: string;\n readonly version: string;\n readonly state: AssetJobState;\n readonly sourceAdapter: AssetSourceAdapter;\n readonly requestedAt: string;\n readonly requestedBy: string;\n readonly featureFlagId: string;\n readonly requiredCapability?: string;\n}\n\nexport interface AssetPromotionRecord<TManifest extends AssetManifest = AssetManifest> {\n readonly promotionId: string;\n readonly jobId: string;\n readonly assetId: string;\n readonly version: string;\n readonly sourceAdapter: AssetSourceAdapter;\n readonly outcome: AssetPromotionOutcome;\n readonly manifest: TManifest;\n readonly reviewReport: AssetReviewReport;\n readonly approvedBy: string;\n readonly approvedAt: string;\n readonly promotedAt: string;\n readonly runtimeChannel: string;\n readonly runtimeManifestUri: string;\n readonly rollbackOfVersion?: string;\n}\n\nconst ASSET_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst TOKEN_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._:-]{0,127}$/u;\nconst ASSET_MANIFEST_KEYS = Object.freeze([\n \"assetKind\",\n \"assetId\",\n \"version\",\n \"entrypoint\",\n \"files\",\n \"sourceAdapter\",\n \"createdAt\",\n] as const);\n\nexport function isAssetId(value: unknown): value is string {\n return typeof value === \"string\" && ASSET_ID_PATTERN.test(value);\n}\n\nexport function normalizeAssetId(value: string): string {\n return value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, \"-\").replace(/^-+|-+$/gu, \"\");\n}\n\nexport function assertAssetId(value: unknown): string {\n if (!isAssetId(value)) {\n throw new Error(\"Asset id must use lowercase kebab-case letters and numbers.\");\n }\n return value;\n}\n\nexport function isAssetSourceAdapter(value: unknown): value is AssetSourceAdapter {\n return ASSET_SOURCE_ADAPTERS.includes(value as AssetSourceAdapter);\n}\n\nexport function isAssetKind(value: unknown): value is AssetKind {\n return ASSET_KINDS.includes(value as AssetKind);\n}\n\nexport function isAssetFileRole(value: unknown): value is AssetFileRole {\n return ASSET_FILE_ROLES.includes(value as AssetFileRole);\n}\n\nexport function isAssetJobState(value: unknown): value is AssetJobState {\n return ASSET_JOB_STATES.includes(value as AssetJobState);\n}\n\nexport function isAssetPromotionOutcome(value: unknown): value is AssetPromotionOutcome {\n return ASSET_PROMOTION_OUTCOMES.includes(value as AssetPromotionOutcome);\n}\n\nexport function createAssetFileDescriptor(input: AssetFileDescriptor): AssetFileDescriptor {\n assertRelativeAssetPath(input.path, \"Asset file path\");\n if (!Number.isInteger(input.byteLength) || input.byteLength < 0) {\n throw new Error(\"Asset file byteLength must be a non-negative integer.\");\n }\n if (!SHA256_PATTERN.test(input.sha256)) {\n throw new Error(\"Asset file sha256 must be a lowercase 64-character digest.\");\n }\n if (!input.contentType || input.contentType.trim() !== input.contentType) {\n throw new Error(\"Asset file contentType must be a non-empty canonical value.\");\n }\n if (!isAssetFileRole(input.role)) {\n throw new Error(\"Asset file role is not supported.\");\n }\n if (input.role === \"wgsl\") {\n assertGpuToken(input.moduleId, \"Asset WGSL file moduleId\");\n } else if (input.moduleId !== undefined) {\n throw new Error(\"Asset file moduleId is allowed only for WGSL files.\");\n }\n return Object.freeze({ ...input });\n}\n\nexport function createAssetManifest<TManifest extends AssetManifest>(input: TManifest): TManifest {\n if (input.assetKind !== undefined) {\n throw new Error(\"Typed assets require their specialized manifest factory.\");\n }\n return createBaseAssetManifest(input);\n}\n\nfunction createBaseAssetManifest<TManifest extends AssetManifest>(input: TManifest): TManifest {\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n if (input.assetKind !== undefined && !isAssetKind(input.assetKind)) {\n throw new Error(\"Asset manifest assetKind is not supported.\");\n }\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset manifest sourceAdapter is not supported.\");\n }\n assertRelativeAssetPath(input.entrypoint, \"Asset manifest entrypoint\");\n const files = input.files.map(createAssetFileDescriptor);\n const filePaths = new Set(files.map((file) => file.path));\n if (filePaths.size !== files.length) {\n throw new Error(\"Asset manifest file paths must be unique.\");\n }\n return Object.freeze({\n ...input,\n files: Object.freeze(files),\n }) as TManifest;\n}\n\n/**\n * Creates a model lifecycle manifest whose CPU-side ABI metadata is validated\n * against the canonical GPU-interface reference.\n */\nexport function createModelAssetManifest(input: ModelAssetManifestInput): ModelAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"gpuInterface\",\n \"modelAbiHash\",\n \"providedSemantics\",\n \"defaultStyleProfile\",\n ], \"ModelAssetManifest\");\n const base = createTypedAssetBase(input, \"model\", \"model\");\n assertAllowedFileRoles(base, [\n \"model\",\n \"binary\",\n \"texture\",\n \"manifest\",\n \"screenshot\",\n \"metadata\",\n ]);\n const descriptor = parseModelGpuCompatibilityDescriptor({\n modelId: base.assetId,\n version: base.version,\n gpuInterface: input.gpuInterface,\n modelAbiHash: input.modelAbiHash,\n providedSemantics: input.providedSemantics,\n defaultStyleProfile: input.defaultStyleProfile ?? null,\n });\n assertModelGpuCompatibilityVersions(descriptor);\n return Object.freeze({\n ...base,\n gpuInterface: descriptor.gpuInterface,\n modelAbiHash: descriptor.modelAbiHash,\n providedSemantics: descriptor.providedSemantics,\n defaultStyleProfile: descriptor.defaultStyleProfile,\n });\n}\n\n/** Creates a lifecycle envelope around a strictly parsed reflected interface. */\nexport function createGpuInterfaceAssetManifest(\n input: GpuInterfaceAssetManifest,\n): GpuInterfaceAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"gpuInterfaceManifest\",\n ], \"GpuInterfaceAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"gpu-interface\",\n \"gpu-interface-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"gpu-interface-manifest\"]);\n assertRoleCount(base, \"gpu-interface-manifest\", 1);\n const gpuInterfaceManifest = parseGpuInterfaceManifest(input.gpuInterfaceManifest);\n assertImmutableAssetVersion(gpuInterfaceManifest.interfaceVersion);\n assertDomainIdentity(\n base,\n gpuInterfaceManifest.interfaceId,\n gpuInterfaceManifest.interfaceVersion,\n \"GPU interface\",\n );\n return Object.freeze({ ...base, gpuInterfaceManifest });\n}\n\n/**\n * Creates a shader lifecycle envelope and proves that its complete WGSL file\n * set matches the module digests and sizes in the strict shader manifest.\n */\nexport function createShaderAssetManifest(input: ShaderAssetManifest): ShaderAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"shaderManifest\",\n ], \"ShaderAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader\",\n \"shader-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"shader-manifest\", \"wgsl\"]);\n assertRoleCount(base, \"shader-manifest\", 1);\n const shaderManifest = parseShaderVersionManifest(input.shaderManifest);\n assertShaderManifestVersions(shaderManifest);\n assertDomainIdentity(base, shaderManifest.shaderId, shaderManifest.version, \"Shader\");\n assertShaderModuleFiles(base.files, shaderManifest);\n return Object.freeze({ ...base, shaderManifest });\n}\n\n/** Creates a profile lifecycle envelope with exact immutable shader references. */\nexport function createShaderStyleProfileAssetManifest(\n input: ShaderStyleProfileAssetManifest,\n): ShaderStyleProfileAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"styleProfileManifest\",\n ], \"ShaderStyleProfileAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader-style-profile\",\n \"shader-style-profile-manifest\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\"shader-style-profile-manifest\"]);\n assertRoleCount(base, \"shader-style-profile-manifest\", 1);\n const styleProfileManifest = parseShaderStyleProfileManifest(input.styleProfileManifest);\n assertStyleProfileManifestVersions(styleProfileManifest);\n assertDomainIdentity(base, styleProfileManifest.profileId, styleProfileManifest.version, \"Style profile\");\n return Object.freeze({ ...base, styleProfileManifest });\n}\n\n/**\n * Creates the storage envelope for qualification evidence. Full evidence-byte,\n * bundle, provenance, and Cartesian-coverage verification remains an admission\n * concern in `@plasius/gpu-shader/testing`.\n */\nexport function createShaderValidationEvidenceAssetManifest(\n input: ShaderValidationEvidenceAssetManifest,\n): ShaderValidationEvidenceAssetManifest {\n assertExactKeys(input, [\n ...ASSET_MANIFEST_KEYS,\n \"validationEvidence\",\n ], \"ShaderValidationEvidenceAssetManifest\");\n const base = createTypedAssetBase(\n input,\n \"shader-validation-evidence\",\n \"shader-validation-evidence\",\n ASSET_JSON_CONTENT_TYPE,\n );\n assertAllowedFileRoles(base, [\n \"shader-validation-evidence\",\n \"shader-validation-attestation\",\n \"shader-qualification-fixture\",\n \"shader-compile-unit-inventory\",\n \"shader-matrix\",\n \"metadata\",\n ]);\n assertRoleCount(base, \"shader-validation-evidence\", 1);\n const validationEvidence = createShaderValidationEvidenceRef(input.validationEvidence);\n if (!isAssetId(validationEvidence.evidenceId) || validationEvidence.evidenceId !== base.assetId) {\n throw new Error(\"Shader validation evidence identity must match the asset identity.\");\n }\n const evidenceFile = requireEntrypoint(base, \"shader-validation-evidence\");\n if (evidenceFile.sha256 !== validationEvidence.sha256) {\n throw new Error(\"Shader validation evidence file digest must match its evidence reference.\");\n }\n const attestationFiles = base.files.filter((file) => file.role === \"shader-validation-attestation\");\n if (attestationFiles.length !== 1\n || attestationFiles[0]?.sha256 !== validationEvidence.attestationRef.sha256\n || attestationFiles[0]?.contentType !== ASSET_JSON_CONTENT_TYPE) {\n throw new Error(\"Shader validation evidence must include its exact attestation file.\");\n }\n return Object.freeze({ ...base, validationEvidence });\n}\n\n/** Strictly validates and freezes a supported universal or additive evidence reference. */\nexport function createShaderValidationEvidenceRef(\n input: ShaderValidationEvidenceRef,\n): ShaderValidationEvidenceRef {\n const value = assertRecord(input, \"ShaderValidationEvidenceRef\");\n assertExactKeys(value, [\n \"evidenceId\",\n \"uri\",\n \"sha256\",\n \"matrixId\",\n \"matrixVersion\",\n \"matrixSha256\",\n \"attestationRef\",\n ], \"ShaderValidationEvidenceRef\");\n const attestation = assertRecord(value.attestationRef, \"ShaderValidationEvidenceRef.attestationRef\");\n assertExactKeys(attestation, [\"uri\", \"sha256\"], \"ShaderValidationEvidenceRef.attestationRef\");\n const result: ShaderValidationEvidenceRef = {\n evidenceId: assertGpuToken(value.evidenceId, \"Shader validation evidence id\"),\n uri: assertImmutableHttpsUri(value.uri, \"Shader validation evidence uri\"),\n sha256: assertSha256(value.sha256, \"Shader validation evidence sha256\"),\n matrixId: assertGpuToken(value.matrixId, \"Shader validation evidence matrixId\"),\n matrixVersion: assertImmutableAssetVersion(value.matrixVersion),\n matrixSha256: assertSha256(value.matrixSha256, \"Shader validation evidence matrixSha256\"),\n attestationRef: Object.freeze({\n uri: assertImmutableHttpsUri(attestation.uri, \"Shader validation evidence attestation uri\"),\n sha256: assertSha256(attestation.sha256, \"Shader validation evidence attestation sha256\"),\n }),\n };\n const supportedUniversal = SUPPORTED_STABLE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n result.matrixId === policy.matrixId\n && result.matrixVersion === policy.matrixVersion\n && result.matrixSha256 === policy.matrixSha256);\n const supportedAdditive = SUPPORTED_ADDITIVE_WEBGPU_MATRIX_POLICIES.some((policy) =>\n result.matrixId === policy.matrixId\n && result.matrixVersion === policy.matrixVersion\n && result.matrixSha256 === policy.matrixSha256);\n if (!supportedUniversal && !supportedAdditive) {\n throw new Error(\"Shader validation evidence must target a supported WebGPU matrix policy.\");\n }\n if (result.uri === result.attestationRef.uri || result.sha256 === result.attestationRef.sha256) {\n throw new Error(\"Shader validation evidence and attestation identities must be distinct.\");\n }\n return Object.freeze(result);\n}\n\n/** Constructs an exact interface reference after immutable manifest bytes exist. */\nexport async function createGpuInterfaceRef(input: GpuInterfaceRefInput): Promise<GpuInterfaceRef> {\n assertImmutableAssetVersion(input.manifest.interfaceVersion);\n const manifest = parseGpuInterfaceManifest(input.manifest);\n assertAssetId(manifest.interfaceId);\n assertImmutableAssetVersion(manifest.interfaceVersion);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"GPU interface\");\n return Object.freeze({\n interfaceId: manifest.interfaceId,\n interfaceVersion: manifest.interfaceVersion,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"GPU interface manifest uri\"),\n manifestSha256,\n interfaceAbiHash: manifest.interfaceAbiHash,\n modelAbiHash: manifest.modelAbiHash,\n });\n}\n\n/** Constructs an exact shader-version reference after immutable manifest bytes exist. */\nexport async function createShaderVersionRef(input: ShaderVersionRefInput): Promise<ShaderVersionRef> {\n assertImmutableAssetVersion(input.manifest.version);\n const manifest = parseShaderVersionManifest(input.manifest);\n assertAssetId(manifest.shaderId);\n assertShaderManifestVersions(manifest);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"Shader\");\n return Object.freeze({\n shaderId: manifest.shaderId,\n version: manifest.version,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"Shader manifest uri\"),\n manifestSha256,\n });\n}\n\n/** Constructs an exact style-profile reference after immutable manifest bytes exist. */\nexport async function createShaderStyleProfileRef(\n input: ShaderStyleProfileRefInput,\n): Promise<ShaderStyleProfileRef> {\n assertImmutableAssetVersion(input.manifest.version);\n const manifest = parseShaderStyleProfileManifest(input.manifest);\n assertAssetId(manifest.profileId);\n assertStyleProfileManifestVersions(manifest);\n const manifestSha256 = await bindDomainManifestBytes(input.manifestBytes, manifest, \"Style profile\");\n return Object.freeze({\n profileId: manifest.profileId,\n version: manifest.version,\n manifestUri: assertImmutableHttpsUri(input.manifestUri, \"Style profile manifest uri\"),\n manifestSha256,\n });\n}\n\n/** Revalidates any typed GPU asset envelope at a storage or promotion boundary. */\nexport function createGpuAssetManifest(input: GpuAssetManifest): GpuAssetManifest {\n switch (input.assetKind) {\n case \"model\":\n return createModelAssetManifest(input);\n case \"gpu-interface\":\n return createGpuInterfaceAssetManifest(input);\n case \"shader\":\n return createShaderAssetManifest(input);\n case \"shader-style-profile\":\n return createShaderStyleProfileAssetManifest(input);\n case \"shader-validation-evidence\":\n return createShaderValidationEvidenceAssetManifest(input);\n default:\n throw new Error(\"GPU asset manifest assetKind is not supported.\");\n }\n}\n\n/**\n * Digest-verifies a complete typed asset version and binds canonical JSON\n * entrypoint bytes to the validated interface, shader, or profile object.\n */\nexport async function validateGpuAssetFiles(\n input: GpuAssetFileValidationInput,\n): Promise<GpuAssetManifest> {\n const manifest = createGpuAssetManifest(input.manifest);\n if (input.files.size !== manifest.files.length) {\n throw new Error(\"GPU asset validation requires exactly the declared file set.\");\n }\n for (const path of input.files.keys()) {\n if (!manifest.files.some((file) => file.path === path)) {\n throw new Error(`GPU asset validation received undeclared file ${path}.`);\n }\n }\n await Promise.all(manifest.files.map(async (file) => {\n const bytes = input.files.get(file.path);\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`GPU asset validation is missing bytes for ${file.path}.`);\n }\n if (bytes.byteLength !== file.byteLength) {\n throw new Error(`GPU asset file ${file.path} byte length differs from its descriptor.`);\n }\n if (await computeSha256(bytes) !== file.sha256) {\n throw new Error(`GPU asset file ${file.path} digest differs from its descriptor.`);\n }\n if (file.contentType === ASSET_JSON_CONTENT_TYPE) {\n assertCanonicalJsonBytes(bytes, `GPU asset file ${file.path}`);\n } else if (file.role === \"wgsl\") {\n try {\n new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new Error(`GPU asset WGSL file ${file.path} is not valid UTF-8.`, { cause });\n }\n }\n }));\n\n const entrypointBytes = input.files.get(manifest.entrypoint);\n if (!(entrypointBytes instanceof Uint8Array)) {\n throw new Error(\"GPU asset validation is missing entrypoint bytes.\");\n }\n const expectedDomainManifest = domainManifestForAsset(manifest);\n if (expectedDomainManifest !== null) {\n const parsedEntrypoint = parseJsonBytes(entrypointBytes, \"GPU asset manifest entrypoint\");\n if (canonicalizeGpuContract(parsedEntrypoint) !== canonicalizeGpuContract(expectedDomainManifest)) {\n throw new Error(\"GPU asset entrypoint bytes differ from the validated domain manifest.\");\n }\n } else if (manifest.assetKind === \"shader-validation-evidence\") {\n assertEvidenceEntrypointIdentity(\n parseJsonBytes(entrypointBytes, \"Shader validation evidence entrypoint\"),\n manifest.validationEvidence,\n );\n }\n return manifest;\n}\n\nexport function createStandardScreenshotPlan(\n width = 1600,\n height = 1000\n): readonly AssetScreenshotPlanItem[] {\n return Object.freeze(\n ASSET_SCREENSHOT_KINDS.map((kind) =>\n Object.freeze({\n kind,\n label: kind.replace(/-/gu, \" \"),\n width,\n height,\n })\n )\n );\n}\n\nexport function createAssetReviewReport(input: AssetReviewReport): AssetReviewReport {\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n return Object.freeze({\n ...input,\n findings: Object.freeze(input.findings.map((finding) => Object.freeze({ ...finding }))),\n });\n}\n\nexport function createAssetJobRecord(input: AssetJobRecord): AssetJobRecord {\n assertToken(input.jobId, \"Asset job id\");\n assertAssetId(input.assetId);\n assertAssetVersion(input.version);\n if (!isAssetJobState(input.state)) {\n throw new Error(\"Asset job state is not supported.\");\n }\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset job sourceAdapter is not supported.\");\n }\n assertRequiredString(input.requestedAt, \"Asset job requestedAt\");\n assertRequiredString(input.requestedBy, \"Asset job requestedBy\");\n assertToken(input.featureFlagId, \"Asset job featureFlagId\");\n if (input.requiredCapability !== undefined) {\n assertToken(input.requiredCapability, \"Asset job requiredCapability\");\n }\n return Object.freeze({ ...input });\n}\n\nexport function createAssetPromotionRecord<TManifest extends AssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n): AssetPromotionRecord<TManifest> {\n if (input.manifest.assetKind !== undefined) {\n throw new Error(\"Typed GPU assets require createGpuAssetPromotionRecord with the complete file bytes.\");\n }\n return createValidatedPromotionRecord(input, createAssetManifest(input.manifest));\n}\n\n/** Digest-verifies and promotes a typed GPU asset without a generic-factory bypass. */\nexport async function createGpuAssetPromotionRecord<TManifest extends GpuAssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n files: ReadonlyMap<string, Uint8Array>,\n): Promise<AssetPromotionRecord<TManifest>> {\n const manifest = await validateGpuAssetFiles({ manifest: input.manifest, files }) as TManifest;\n assertTypedRuntimeManifestUri(manifest, input.runtimeManifestUri);\n return createValidatedPromotionRecord(input, manifest);\n}\n\nfunction createValidatedPromotionRecord<TManifest extends AssetManifest>(\n input: AssetPromotionRecord<TManifest>,\n manifest: TManifest,\n): AssetPromotionRecord<TManifest> {\n const assertPromotionVersion = manifest.assetKind === undefined\n ? assertAssetVersion\n : assertImmutableAssetVersion;\n assertToken(input.promotionId, \"Asset promotion id\");\n assertToken(input.jobId, \"Asset promotion job id\");\n assertAssetId(input.assetId);\n assertPromotionVersion(input.version);\n if (!isAssetSourceAdapter(input.sourceAdapter)) {\n throw new Error(\"Asset promotion sourceAdapter is not supported.\");\n }\n if (!isAssetPromotionOutcome(input.outcome)) {\n throw new Error(\"Asset promotion outcome is not supported.\");\n }\n\n if (manifest.assetId !== input.assetId || manifest.version !== input.version) {\n throw new Error(\"Asset promotion manifest must match the promoted asset id and version.\");\n }\n\n const reviewReport = createAssetReviewReport(input.reviewReport);\n if (reviewReport.assetId !== input.assetId || reviewReport.version !== input.version) {\n throw new Error(\"Asset promotion reviewReport must match the promoted asset id and version.\");\n }\n\n assertRequiredString(input.approvedBy, \"Asset promotion approvedBy\");\n assertRequiredString(input.approvedAt, \"Asset promotion approvedAt\");\n assertRequiredString(input.promotedAt, \"Asset promotion promotedAt\");\n assertRequiredString(input.runtimeChannel, \"Asset promotion runtimeChannel\");\n assertRequiredString(input.runtimeManifestUri, \"Asset promotion runtimeManifestUri\");\n if (input.rollbackOfVersion !== undefined) {\n assertPromotionVersion(input.rollbackOfVersion);\n }\n\n return Object.freeze({\n ...input,\n manifest,\n reviewReport,\n });\n}\n\nfunction createTypedAssetBase<K extends AssetKind>(\n input: AssetManifest,\n assetKind: K,\n entrypointRole: AssetFileRole,\n entrypointContentType?: string,\n): TypedAssetManifest<K> {\n if (input.assetKind !== assetKind) {\n throw new Error(`Asset manifest assetKind must be ${assetKind}.`);\n }\n assertImmutableAssetVersion(input.version);\n const base = createBaseAssetManifest({\n assetKind,\n assetId: input.assetId,\n version: input.version,\n entrypoint: input.entrypoint,\n files: input.files,\n sourceAdapter: input.sourceAdapter,\n createdAt: input.createdAt,\n });\n const entrypoint = requireEntrypoint(base, entrypointRole);\n if (entrypointContentType !== undefined && entrypoint.contentType !== entrypointContentType) {\n throw new Error(`Asset manifest ${entrypointRole} entrypoint must use ${entrypointContentType}.`);\n }\n return base;\n}\n\nfunction requireEntrypoint(\n manifest: AssetManifest,\n expectedRole: AssetFileRole,\n): AssetFileDescriptor {\n const matches = manifest.files.filter((file) => file.path === manifest.entrypoint);\n if (matches.length !== 1 || matches[0]?.role !== expectedRole) {\n throw new Error(`Asset manifest entrypoint must identify exactly one ${expectedRole} file.`);\n }\n return matches[0];\n}\n\nfunction assertDomainIdentity(\n manifest: AssetManifest,\n domainId: string,\n domainVersion: string,\n label: string,\n): void {\n if (!isAssetId(domainId) || domainId !== manifest.assetId || domainVersion !== manifest.version) {\n throw new Error(`${label} identity and version must match the lifecycle asset identity and version.`);\n }\n}\n\nfunction assertGpuInterfaceRefVersion(ref: GpuInterfaceRef): void {\n assertImmutableAssetVersion(ref.interfaceVersion);\n}\n\nfunction assertShaderEvidenceVersion(ref: ShaderValidationEvidenceRef): void {\n assertImmutableAssetVersion(ref.matrixVersion);\n}\n\nfunction assertShaderManifestVersions(manifest: ShaderVersionManifest): void {\n assertImmutableAssetVersion(manifest.version);\n assertGpuInterfaceRefVersion(manifest.gpuInterface);\n for (const compatibleInterface of manifest.compatibleModelInterfaces) {\n assertImmutableAssetVersion(compatibleInterface.interfaceVersion);\n }\n assertShaderEvidenceVersion(manifest.validationEvidence);\n for (const scopedEvidence of manifest.additionalValidationEvidence) {\n assertShaderEvidenceVersion(scopedEvidence.evidence);\n }\n}\n\nfunction assertStyleProfileManifestVersions(manifest: ShaderStyleProfileManifest): void {\n assertImmutableAssetVersion(manifest.version);\n for (const role of manifest.roles) {\n assertImmutableAssetVersion(role.shader.version);\n }\n for (const compatibleInterface of manifest.compatibleModelInterfaces) {\n assertImmutableAssetVersion(compatibleInterface.interfaceVersion);\n }\n for (const scope of manifest.requiredValidationScopes) {\n assertImmutableAssetVersion(scope.matrixVersion);\n }\n}\n\nfunction assertModelGpuCompatibilityVersions(descriptor: ModelGpuCompatibilityDescriptor): void {\n assertImmutableAssetVersion(descriptor.version);\n assertGpuInterfaceRefVersion(descriptor.gpuInterface);\n if (descriptor.defaultStyleProfile !== null) {\n assertImmutableAssetVersion(descriptor.defaultStyleProfile.version);\n }\n}\n\nfunction assertShaderModuleFiles(\n files: readonly AssetFileDescriptor[],\n shaderManifest: ShaderVersionManifest,\n): void {\n const moduleFiles = files.filter((file) => file.role === \"wgsl\");\n const moduleFileIds = new Set(moduleFiles.map((file) => file.moduleId));\n if (moduleFiles.length !== shaderManifest.modules.length\n || moduleFileIds.size !== moduleFiles.length) {\n throw new Error(\"Shader asset must contain exactly one uniquely mapped WGSL file per shader module.\");\n }\n for (const module of shaderManifest.modules) {\n const file = moduleFiles.find((candidate) => candidate.moduleId === module.moduleId);\n if (!file\n || file.sha256 !== module.sha256\n || file.byteLength !== module.byteLength\n || file.contentType !== module.contentType) {\n throw new Error(\"Shader asset WGSL module files must exactly match the shader manifest module IDs, digests, sizes, and content types.\");\n }\n const moduleUri = new URL(module.uri);\n const pathSuffix = `/${file.path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (!moduleUri.pathname.endsWith(pathSuffix)) {\n throw new Error(\"Shader module URI paths must identify their mapped immutable WGSL asset files.\");\n }\n }\n}\n\nfunction assertAllowedFileRoles(\n manifest: AssetManifest,\n allowedRoles: readonly AssetFileRole[],\n): void {\n const allowed = new Set(allowedRoles);\n const unexpected = manifest.files.find((file) => !allowed.has(file.role));\n if (unexpected) {\n throw new Error(`${manifest.assetKind ?? \"legacy\"} assets do not allow ${unexpected.role} files.`);\n }\n}\n\nfunction domainManifestForAsset(\n manifest: GpuAssetManifest,\n): GpuInterfaceManifest | ShaderVersionManifest | ShaderStyleProfileManifest | null {\n switch (manifest.assetKind) {\n case \"gpu-interface\":\n return manifest.gpuInterfaceManifest;\n case \"shader\":\n return manifest.shaderManifest;\n case \"shader-style-profile\":\n return manifest.styleProfileManifest;\n case \"model\":\n case \"shader-validation-evidence\":\n return null;\n }\n}\n\nfunction assertTypedRuntimeManifestUri(manifest: GpuAssetManifest, value: string): void {\n const runtimeUri = new URL(assertImmutableHttpsUri(value, \"GPU asset runtimeManifestUri\"));\n if (manifest.assetKind === \"shader-validation-evidence\") {\n if (runtimeUri.href !== manifest.validationEvidence.uri) {\n throw new Error(\"Evidence promotion URI must equal its exact validation-evidence URI.\");\n }\n return;\n }\n if (manifest.assetKind === \"model\") return;\n\n const entrypointSuffix = `/${manifest.entrypoint.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (!runtimeUri.pathname.endsWith(entrypointSuffix)) {\n throw new Error(\"Typed GPU promotion URI must identify the validated manifest entrypoint.\");\n }\n if (manifest.assetKind === \"shader\") {\n const runtimeDirectory = runtimeUri.pathname.slice(0, -entrypointSuffix.length);\n for (const module of manifest.shaderManifest.modules) {\n const moduleUri = new URL(module.uri);\n const moduleFile = manifest.files.find((file) =>\n file.role === \"wgsl\" && file.moduleId === module.moduleId);\n if (!moduleFile) {\n throw new Error(`Shader module ${module.moduleId} has no mapped WGSL file.`);\n }\n const moduleSuffix = `/${moduleFile.path.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n if (moduleUri.origin !== runtimeUri.origin\n || moduleUri.pathname.slice(0, -moduleSuffix.length) !== runtimeDirectory) {\n throw new Error(\"Shader module and manifest URIs must share one immutable version root.\");\n }\n }\n }\n}\n\nfunction assertEvidenceEntrypointIdentity(\n value: unknown,\n ref: ShaderValidationEvidenceRef,\n): void {\n const evidence = assertRecord(value, \"Shader validation evidence entrypoint\");\n if (evidence.contractVersion !== SHADER_VALIDATION_EVIDENCE_VERSION\n || evidence.evidenceId !== ref.evidenceId\n || evidence.status !== \"passed\") {\n throw new Error(\"Shader validation evidence bytes do not identify passing declared evidence.\");\n }\n const matrixRef = assertRecord(evidence.matrixRef, \"Shader validation evidence matrixRef\");\n if (matrixRef.matrixId !== ref.matrixId\n || matrixRef.version !== ref.matrixVersion\n || matrixRef.sha256 !== ref.matrixSha256) {\n throw new Error(\"Shader validation evidence bytes differ from the declared matrix identity.\");\n }\n const counts = assertRecord(evidence.counts, \"Shader validation evidence counts\");\n const compileUnits = counts.compileUnits as number;\n const cells = counts.cells as number;\n const expectedResults = counts.expectedResults as number;\n if (!Number.isSafeInteger(compileUnits)\n || !Number.isSafeInteger(cells)\n || !Number.isSafeInteger(expectedResults)\n || !Number.isSafeInteger(counts.passedResults)\n || compileUnits <= 0\n || cells <= 0\n || expectedResults !== compileUnits * cells\n || counts.passedResults !== expectedResults) {\n throw new Error(\"Shader validation evidence bytes do not declare complete passing result counts.\");\n }\n}\n\nfunction assertCanonicalJsonBytes(bytes: Uint8Array, fieldName: string): void {\n const value = parseJsonBytes(bytes, fieldName);\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n if (canonicalizeGpuContract(value) !== text) {\n throw new Error(`${fieldName} must use canonical JSON serialization.`);\n }\n}\n\nasync function bindDomainManifestBytes(\n bytes: Uint8Array,\n manifest: GpuInterfaceManifest | ShaderVersionManifest | ShaderStyleProfileManifest,\n fieldName: string,\n): Promise<Sha256Hex> {\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`${fieldName} manifest bytes must be a Uint8Array.`);\n }\n assertCanonicalJsonBytes(bytes, `${fieldName} manifest`);\n const parsed = parseJsonBytes(bytes, `${fieldName} manifest`);\n if (canonicalizeGpuContract(parsed) !== canonicalizeGpuContract(manifest)) {\n throw new Error(`${fieldName} manifest bytes differ from the supplied manifest.`);\n }\n return computeSha256(bytes);\n}\n\nfunction assertRoleCount(\n manifest: AssetManifest,\n role: AssetFileRole,\n expectedCount: number,\n): void {\n if (manifest.files.filter((file) => file.role === role).length !== expectedCount) {\n throw new Error(`Asset manifest must contain exactly ${expectedCount} ${role} file(s).`);\n }\n}\n\nfunction assertExactKeys(\n value: object,\n allowed: readonly string[],\n fieldName: string,\n): void {\n const allowedSet = new Set(allowed);\n const unexpected = Object.keys(value).filter((key) => !allowedSet.has(key));\n if (unexpected.length > 0) {\n throw new Error(`${fieldName} contains unsupported fields: ${unexpected.join(\", \")}.`);\n }\n}\n\nfunction assertRecord(value: unknown, fieldName: string): Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`${fieldName} must be an object.`);\n }\n return value as Readonly<Record<string, unknown>>;\n}\n\nfunction assertSha256(value: unknown, fieldName: string): Sha256Hex {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a lowercase 64-character digest.`);\n }\n return value as Sha256Hex;\n}\n\nfunction assertGpuToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\"\n || value.length === 0\n || value.length > 160\n || !/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u.test(value)\n || value.includes(\"..\")) {\n throw new Error(`${fieldName} must be a safe GPU contract token.`);\n }\n return value;\n}\n\nfunction assertRelativeAssetPath(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\"\n || value.length === 0\n || value.length > 1024\n || value.startsWith(\"/\")\n || value.includes(\"\\\\\")\n || value.includes(\":\")\n || value.includes(\"%\")\n || value.includes(\"..\")\n || value.includes(\"?\")\n || value.includes(\"#\")\n || value.trim() !== value\n || value.split(\"/\").some((segment) => segment.length === 0 || segment === \".\")\n || [...value].some((character) => character.charCodeAt(0) <= 0x1f)) {\n throw new Error(`${fieldName} must be a normalized relative POSIX path without traversal or a URI scheme.`);\n }\n return value;\n}\n\nfunction assertImmutableHttpsUri(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > 2048) {\n throw new Error(`${fieldName} must be an absolute immutable asset URI.`);\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch (cause) {\n throw new Error(`${fieldName} must be an absolute immutable asset URI.`, { cause });\n }\n if (parsed.protocol !== \"https:\" || parsed.username || parsed.password || parsed.hash) {\n throw new Error(`${fieldName} must be credential-free HTTPS without a fragment.`);\n }\n const queryKeys = [...parsed.searchParams.keys()].map((key) => key.toLowerCase());\n const forbidden = new Set([\n \"sig\",\n \"se\",\n \"sp\",\n \"sv\",\n \"spr\",\n \"st\",\n \"skoid\",\n \"sktid\",\n \"skt\",\n \"ske\",\n \"sks\",\n \"skv\",\n ]);\n if (queryKeys.some((key) => forbidden.has(key)) || new Set(queryKeys).size !== queryKeys.length) {\n throw new Error(`${fieldName} must not contain SAS credentials or duplicate query parameters.`);\n }\n if (parsed.href !== value) {\n throw new Error(`${fieldName} must use canonical URL serialization.`);\n }\n return value;\n}\n\nfunction assertToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !TOKEN_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a non-empty token up to 128 characters.`);\n }\n return value;\n}\n\nfunction assertRequiredString(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return value;\n}\n","const ASSET_VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;\n\nconst MUTABLE_VERSION_ALIASES = new Set([\n \"latest\",\n \"current\",\n \"stable\",\n \"preview\",\n \"default\",\n \"production\",\n \"canary\",\n \"next\",\n \"head\",\n \"main\",\n]);\n\nconst X_WILDCARD_SEGMENT_PATTERN = /^(?:[vV])?[xX](?:\\.|-|$)|\\.[xX](?:\\.|-|$)/u;\nconst IMMUTABLE_VERSION_ERROR_MESSAGE =\n \"Immutable asset version must be an exact token up to 128 characters; mutable aliases, ranges, wildcards, and URLs are not allowed.\";\n\n/**\n * Validates the legacy asset-version token grammar.\n *\n * This intentionally permits workflow labels such as `latest`; callers that\n * identify immutable assets must use {@link assertImmutableAssetVersion}.\n */\nexport function assertAssetVersion(value: unknown): string {\n if (typeof value !== \"string\" || !ASSET_VERSION_PATTERN.test(value)) {\n throw new Error(\"Asset version must be a non-empty token up to 128 characters.\");\n }\n return value;\n}\n\n/**\n * Validates an immutable, reproducible asset version.\n *\n * The error is deliberately constant and does not interpolate untrusted input,\n * keeping diagnostics stable and bounded at storage and runtime boundaries.\n */\nexport function assertImmutableAssetVersion(value: unknown): string {\n if (typeof value !== \"string\"\n || !ASSET_VERSION_PATTERN.test(value)\n || MUTABLE_VERSION_ALIASES.has(value.toLowerCase())\n || X_WILDCARD_SEGMENT_PATTERN.test(value)) {\n throw new Error(IMMUTABLE_VERSION_ERROR_MESSAGE);\n }\n return value;\n}\n","import { assertImmutableAssetVersion } from \"./asset-version.js\";\n\n/** Version identifier carried by every top-level model-resolution contract. */\nexport const MODEL_RESOLUTION_CONTRACT_VERSION = \"2026-07-12.v1\" as const;\n\n/** Maximum request revision accepted by the v1 contract. */\nexport const MODEL_REQUEST_MAX_REVISION = 3 as const;\n\n/** Assurance thresholds used by every model ranker calibration. */\nexport const MODEL_MATCH_ASSURANCE_THRESHOLDS = Object.freeze({\n high: 0.75,\n low: 0.5,\n} as const);\n\n/** Stable assurance bands for catalog and provider matches. */\nexport const MODEL_MATCH_ASSURANCE_BANDS = Object.freeze([\n \"high\",\n \"low\",\n \"none\",\n] as const);\n\n/** Evidence available to the ranker when it produced a match assessment. */\nexport const MODEL_RANKER_EVIDENCE_MODES = Object.freeze([\n \"text-only\",\n \"vision\",\n \"multimodal\",\n \"exact-identifier\",\n] as const);\n\n/** Audit reason added when a text-only ranker is capped below its raw score band. */\nexport const MODEL_TEXT_ONLY_ASSURANCE_CEILING_REASON_CODE = \"text-only-assurance-ceiling\" as const;\n\n/** Audit reason added when another declared ranker ceiling lowers assurance. */\nexport const MODEL_RANKER_ASSURANCE_CEILING_REASON_CODE = \"ranker-assurance-ceiling\" as const;\n\n/** Authenticated original views required before a candidate can be confirmed. */\nexport const MODEL_CONFIRMATION_VIEW_KINDS = Object.freeze([\n \"front\",\n \"left\",\n \"top\",\n \"isometric\",\n] as const);\n\n/** Required width and height for authenticated confirmation originals. */\nexport const MODEL_CONFIRMATION_VIEW_SIZE_PX = 1024 as const;\n\n/** Exact asynchronous model-resolution states shared with orchestration packages. */\nexport const MODEL_RESOLUTION_STATES = Object.freeze([\n \"searching-catalog\",\n \"searching-providers\",\n \"awaiting-provider-auth\",\n \"quarantining\",\n \"processing\",\n \"rendering\",\n \"evaluating\",\n \"awaiting-rights-review\",\n \"awaiting-confirmation\",\n \"promoting\",\n \"completed\",\n \"unresolved\",\n \"failed\",\n \"cancelled\",\n] as const);\n\n/** Canonical runtime model kinds. */\nexport const MODEL_ASSET_KINDS = Object.freeze([\"leaf\", \"assembly\"] as const);\n\n/** Stable origins for catalog, provider, and future generated candidates. */\nexport const MODEL_PROVENANCE_KINDS = Object.freeze([\n \"catalog\",\n \"provider\",\n \"generated\",\n] as const);\n\n/** Fail-closed rights states used before confirmation or promotion. */\nexport const MODEL_RIGHTS_STATUSES = Object.freeze([\n \"allowed\",\n \"attribution-required\",\n \"quarantined\",\n \"blocked\",\n] as const);\n\n/** Canonical output coordinate system for processed models. */\nexport const CANONICAL_MODEL_COORDINATE_SYSTEM = Object.freeze({\n unit: \"metre\",\n upAxis: \"Y\",\n forwardAxis: \"-Z\",\n origin: \"floor-centred\",\n outwardFaceWinding: \"counter-clockwise\",\n} as const);\n\n/** Fail-closed v1 runtime limits; callers may only tighten these values. */\nexport const STATIC_WORLD_V1_MODEL_POLICY = Object.freeze({\n id: \"static-world-v1\",\n maxTriangles: 1_000_000,\n maxBytes: 100 * 1024 * 1024,\n maxTextureBytes: 64 * 1024 * 1024,\n maxTextureDimensionPx: 4096,\n maxPartitionCellMetres: 32,\n} as const);\n\n/** Independent attestations required before a semantic confirmation can proceed. */\nexport const MODEL_CANDIDATE_HARD_GATE_KINDS = Object.freeze([\n \"malware-scan\",\n \"technical-validation\",\n \"human-review\",\n \"accessibility-review\",\n] as const);\n\n/** Stable reason returned by the disabled Phase 1 generator port. */\nexport const MODEL_GENERATOR_DISABLED_REASON_CODE = \"phase-1-generator-disabled\" as const;\n\n/** Match assurance derived from score and the independent hard-constraint gate. */\nexport type ModelMatchAssurance = typeof MODEL_MATCH_ASSURANCE_BANDS[number];\n\n/** Evidence family retained with each ranker assessment. */\nexport type ModelRankerEvidenceMode = typeof MODEL_RANKER_EVIDENCE_MODES[number];\n\n/** A required confirmation-view identifier. */\nexport type ModelConfirmationViewKind = typeof MODEL_CONFIRMATION_VIEW_KINDS[number];\n\n/** A state in the asynchronous model-resolution lifecycle. */\nexport type ModelResolutionState = typeof MODEL_RESOLUTION_STATES[number];\n\n/** Whether an immutable asset is a single leaf or a composed assembly. */\nexport type ModelAssetKind = typeof MODEL_ASSET_KINDS[number];\n\n/** Where a candidate originated. */\nexport type ModelProvenanceKind = typeof MODEL_PROVENANCE_KINDS[number];\n\n/** Rights eligibility applied before human confirmation. */\nexport type ModelRightsStatus = typeof MODEL_RIGHTS_STATUSES[number];\n\n/** One independent non-semantic confirmation gate. */\nexport type ModelCandidateHardGateKind = typeof MODEL_CANDIDATE_HARD_GATE_KINDS[number];\n\n/** Required/optional/forbidden policy for LOD or collision requirements. */\nexport type ModelRequirementPolicy = \"required\" | \"optional\" | \"forbidden\";\n\n/** Whether runtime packaging must remain single, may partition, or must partition. */\nexport type ModelPartitionPolicy = \"single\" | \"allowed\" | \"required\";\n\n/** A canonical three-dimensional vector. */\nexport type ModelVector3 = readonly [number, number, number];\n\n/** A canonical quaternion in x/y/z/w order. */\nexport type ModelQuaternion = readonly [number, number, number, number];\n\n/** Axis-aligned bounds expressed in metres. */\nexport interface ModelBoundsMetres {\n readonly min: ModelVector3;\n readonly max: ModelVector3;\n}\n\n/** Width, height, and depth expressed in metres. */\nexport interface ModelDimensionsMetres {\n readonly width: number;\n readonly height: number;\n readonly depth: number;\n}\n\n/** Hard request constraints that must pass independently of semantic rank. */\nexport interface ModelHardConstraints {\n readonly boundsMetres?: ModelBoundsMetres;\n readonly dimensionsMetres?: ModelDimensionsMetres;\n readonly maxTriangles?: number;\n readonly maxBytes?: number;\n readonly maxTextureBytes?: number;\n readonly maxTextureDimensionPx?: number;\n readonly maxPartitionCellMetres?: number;\n readonly lod?: ModelRequirementPolicy;\n readonly collision?: ModelRequirementPolicy;\n readonly partition?: ModelPartitionPolicy;\n}\n\n/** Soft ranking preferences that may improve score but never bypass hard constraints. */\nexport interface ModelSoftPreferences {\n readonly category?: string;\n readonly style?: string;\n readonly materials?: readonly string[];\n readonly colors?: readonly string[];\n readonly era?: string;\n readonly condition?: string;\n readonly tags?: readonly string[];\n}\n\n/** Immutable normalized natural-language request for a model. */\nexport interface ModelRequestSpec {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly policyProfileId: typeof STATIC_WORLD_V1_MODEL_POLICY.id;\n readonly query: string;\n readonly revision: number;\n readonly locale?: string;\n readonly rankerId?: string;\n readonly hardConstraints: ModelHardConstraints;\n readonly softPreferences: ModelSoftPreferences;\n readonly exclusions: readonly string[];\n}\n\n/** Versioned ranker and calibration evidence attached to an assessment. */\nexport interface ModelRankerRef {\n readonly id: string;\n readonly version: string;\n readonly calibrationId: string;\n readonly calibrationVersion: string;\n readonly evidenceMode: ModelRankerEvidenceMode;\n readonly assuranceCeiling: ModelMatchAssurance;\n}\n\n/** Immutable model match assessment with a derived assurance band. */\nexport interface ModelMatchAssessment {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly score: number;\n readonly assurance: ModelMatchAssurance;\n readonly hardConstraintPass: boolean;\n readonly exactMatch: boolean;\n readonly reasonCodes: readonly string[];\n readonly ranker: ModelRankerRef;\n readonly fidelityWarnings: readonly string[];\n readonly request: ModelRequestSpec;\n readonly candidateId: string;\n readonly candidateContentHash: string;\n}\n\n/** Deterministic result of comparing one normalized request with one candidate. */\nexport interface ModelHardConstraintEvaluation {\n readonly pass: boolean;\n readonly reasonCodes: readonly string[];\n}\n\n/** Runtime facts used to evaluate request constraints. */\nexport interface ModelTechnicalProfile {\n readonly boundsMetres: ModelBoundsMetres;\n readonly dimensionsMetres: ModelDimensionsMetres;\n readonly triangleCount: number;\n readonly byteLength: number;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n readonly lodCount: number;\n readonly hasCollision: boolean;\n readonly partitionCount: number;\n readonly partitionCellMetres: number;\n}\n\n/** Attribution content used by accessible model acknowledgements. */\nexport interface ModelAttribution {\n readonly title: string;\n readonly creator: string;\n readonly notice: string;\n readonly sourcePageUri?: string;\n}\n\n/** Fail-closed rights assessment for a candidate. */\nexport interface ModelRightsAssessment {\n readonly decisionId: string;\n readonly decisionToken: string;\n readonly policyId: string;\n readonly policyVersion: string;\n readonly sourceId: string;\n readonly sourceAssetId: string;\n readonly sourceContentHash: string;\n readonly status: ModelRightsStatus;\n readonly licenseId: string;\n readonly evidencePageUri: string;\n readonly attribution?: ModelAttribution;\n readonly reviewedAt: string;\n}\n\n/** Public-safe provenance without download or signed staging URLs. */\nexport interface ModelProvenance {\n readonly kind: ModelProvenanceKind;\n readonly sourceId: string;\n readonly sourceAssetId: string;\n readonly sourcePageUri?: string;\n readonly contentHash: string;\n readonly capturedAt: string;\n}\n\n/** Immutable promoted model reference safe for player-facing responses. */\nexport interface ModelAssetRef {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly assetId: string;\n readonly version: string;\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly runtimeManifestUri: string;\n}\n\n/** Existing promoted candidate identity. */\nexport interface ExistingModelCandidateAssetRef {\n readonly disposition: \"existing\";\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly asset: ModelAssetRef;\n}\n\n/** Staged proposal identity without exposing its private resource location. */\nexport interface ProposedModelCandidateAssetRef {\n readonly disposition: \"proposed\";\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly proposalId: string;\n}\n\n/** Candidate identity before or after catalog promotion. */\nexport type ModelCandidateAssetRef =\n | ExistingModelCandidateAssetRef\n | ProposedModelCandidateAssetRef;\n\n/** Authenticated square original used during mandatory human confirmation. */\nexport interface ModelConfirmationView {\n readonly kind: ModelConfirmationViewKind;\n readonly imageUri: string;\n readonly sha256: string;\n readonly contentType: \"image/png\";\n readonly width: typeof MODEL_CONFIRMATION_VIEW_SIZE_PX;\n readonly height: typeof MODEL_CONFIRMATION_VIEW_SIZE_PX;\n}\n\n/** Deterministic renderer/camera attestation covering the exact four-view pack. */\nexport interface ModelRenderEvidence {\n readonly renderId: string;\n readonly rendererId: string;\n readonly rendererVersion: string;\n readonly settingsId: string;\n readonly settingsVersion: string;\n readonly processingManifestId: string;\n readonly sourceContentHash: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly renderedAt: string;\n readonly attestationToken: string;\n}\n\n/** Versioned, signed evidence for a non-semantic confirmation gate. */\nexport interface ModelCandidateHardGateEvidence {\n readonly kind: ModelCandidateHardGateKind;\n readonly outcome: \"passed\" | \"blocked\";\n readonly validatorId: string;\n readonly validatorVersion: string;\n readonly subjectContentHash: string;\n readonly reasonCodes: readonly string[];\n readonly evaluatedAt: string;\n readonly attestationToken: string;\n}\n\n/** Exact four-view confirmation tuple in canonical order. */\nexport type ModelConfirmationViews = readonly [\n ModelConfirmationView,\n ModelConfirmationView,\n ModelConfirmationView,\n ModelConfirmationView,\n];\n\n/** Immutable candidate returned by catalog/provider/generator resolution. */\nexport interface ModelCandidate {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly assetRef: ModelCandidateAssetRef;\n readonly match: ModelMatchAssessment;\n readonly provenance: ModelProvenance;\n readonly rights: ModelRightsAssessment;\n readonly technicalProfile: ModelTechnicalProfile;\n readonly processingManifest: ModelProcessingManifest;\n readonly views: ModelConfirmationViews;\n readonly renderEvidence: ModelRenderEvidence;\n readonly hardGates: readonly ModelCandidateHardGateEvidence[];\n readonly confirmationToken: string;\n readonly confirmationRequired: true;\n}\n\n/** Public-safe resource reference used by processing evidence. */\nexport interface ModelResourceRef {\n readonly uri: string;\n readonly byteLength: number;\n readonly sha256: string;\n readonly contentType: string;\n}\n\n/** Adaptive LOD level; LOD0 is always present and up to LOD3 may follow. */\nexport type ModelLodLevel = 0 | 1 | 2 | 3;\n\n/** Processed resource and triangle evidence for one LOD level. */\nexport interface ModelLodRecord {\n readonly level: ModelLodLevel;\n readonly resource: ModelResourceRef;\n readonly triangleCount: number;\n readonly geometricErrorMetres: number;\n}\n\n/** Collision representation emitted by processing. */\nexport type ModelCollisionKind =\n | \"none\"\n | \"box\"\n | \"convex-hull\"\n | \"triangle-mesh\"\n | \"compound\";\n\n/** Collision evidence, with a resource for every non-empty collision kind. */\nexport interface ModelCollisionRecord {\n readonly kind: ModelCollisionKind;\n readonly resource?: ModelResourceRef;\n}\n\n/** Canonical transform for an assembly child. */\nexport interface ModelTransform {\n readonly translationMetres: ModelVector3;\n readonly rotationQuaternion: ModelQuaternion;\n readonly scale: ModelVector3;\n}\n\n/** Candidate-scoped immutable reference for a not-yet-promoted derived leaf. */\nexport interface StagedModelAssemblyChildRef {\n readonly disposition: \"staged-derived\";\n readonly derivedId: string;\n readonly kind: \"leaf\";\n readonly contentHash: string;\n readonly processingManifestUri: string;\n}\n\n/** Catalog or staged-derived leaf identity accepted in an assembly closure. */\nexport type ModelAssemblyChildAssetRef = ModelAssetRef | StagedModelAssemblyChildRef;\n\n/** Immutable child reference, optional hierarchy parent, and local transform. */\nexport interface ModelAssemblyChild {\n readonly instanceId: string;\n readonly parentInstanceId?: string;\n readonly assetRef: ModelAssemblyChildAssetRef;\n readonly transform: ModelTransform;\n}\n\n/** Severity for conversion diagnostics and fidelity losses. */\nexport type ModelDiagnosticSeverity = \"info\" | \"warning\" | \"blocking\";\n\n/** Structured diagnostic emitted by a converter. */\nexport interface ModelConverterDiagnostic {\n readonly severity: ModelDiagnosticSeverity;\n readonly code: string;\n readonly message: string;\n}\n\n/** Explicit semantic loss recorded during conversion. */\nexport interface ModelConversionLoss {\n readonly code: string;\n readonly severity: ModelDiagnosticSeverity;\n readonly message: string;\n}\n\n/** Converter identity, hashes, diagnostics, and loss evidence. */\nexport interface ModelConverterEvidence {\n readonly id: string;\n readonly version: string;\n readonly sourceFormat: string;\n readonly targetFormat: string;\n readonly sourceContentHash: string;\n readonly outputContentHash: string;\n readonly diagnostics: readonly ModelConverterDiagnostic[];\n readonly losses: readonly ModelConversionLoss[];\n}\n\n/** Fidelity aspect assessed after conversion. */\nexport type ModelFidelityAspect =\n | \"geometry\"\n | \"materials\"\n | \"textures\"\n | \"rigging\"\n | \"animation\"\n | \"metadata\";\n\n/** Fidelity result for a converted aspect. */\nexport type ModelFidelityOutcome = \"preserved\" | \"approximated\" | \"lost\";\n\n/** Structured fidelity evidence suitable for review. */\nexport interface ModelFidelityEvidence {\n readonly aspect: ModelFidelityAspect;\n readonly outcome: ModelFidelityOutcome;\n readonly message: string;\n readonly evidenceResource?: ModelResourceRef;\n}\n\n/** Signed category-policy decision requiring a collision proxy or allowing none. */\nexport interface ModelCollisionPolicyEvidence {\n readonly profileId: string;\n readonly profileVersion: string;\n readonly disposition: \"proxy-required\" | \"none-allowed\";\n readonly category: string;\n readonly decisionToken: string;\n}\n\n/** Signed fidelity-policy result that independently gates semantic assurance. */\nexport interface ModelFidelityGateEvidence {\n readonly profileId: string;\n readonly profileVersion: string;\n readonly outcome: \"passed\" | \"low-only\" | \"blocked\";\n readonly requiredAspects: readonly [\"geometry\", \"materials\", \"textures\"];\n readonly evaluatedAt: string;\n readonly decisionToken: string;\n}\n\n/** Canonical, immutable model-processing manifest. */\nexport interface ModelProcessingManifest {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly manifestId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly kind: ModelAssetKind;\n readonly contentHash: string;\n readonly closureHash: string;\n readonly coordinateSystem: typeof CANONICAL_MODEL_COORDINATE_SYSTEM;\n readonly technicalProfile: ModelTechnicalProfile;\n readonly lods: readonly ModelLodRecord[];\n readonly collision: ModelCollisionRecord;\n readonly collisionPolicy: ModelCollisionPolicyEvidence;\n readonly children: readonly ModelAssemblyChild[];\n readonly converter: ModelConverterEvidence;\n readonly fidelityEvidence: readonly ModelFidelityEvidence[];\n readonly fidelityGate: ModelFidelityGateEvidence;\n readonly processedAt: string;\n}\n\n/** Immutable evidence that one requester confirmed one exact candidate render pack. */\nexport interface ModelCandidateConfirmation {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly confirmationId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly confirmationToken: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly confirmedBy: string;\n readonly confirmedAt: string;\n readonly semanticRiskAccepted: boolean;\n}\n\n/** Backend-issued receipt binding one staged proposal closure to its final catalog identity. */\nexport interface ModelPromotionReceipt {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly promotionId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly proposalId: string;\n readonly confirmationId: string;\n readonly processingManifestId: string;\n readonly processingContentHash: string;\n readonly closureHash: string;\n readonly finalAssetRef: ModelAssetRef;\n readonly promotedAt: string;\n readonly publicationToken: string;\n}\n\n/** Immutable record for one asynchronous model-resolution request. */\nexport interface ModelResolution {\n readonly contractVersion: typeof MODEL_RESOLUTION_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly request: ModelRequestSpec;\n readonly attempts: number;\n readonly state: ModelResolutionState;\n readonly candidates: readonly ModelCandidate[];\n readonly bestCandidate?: ModelCandidate;\n readonly confirmation?: ModelCandidateConfirmation;\n readonly promotionReceipt?: ModelPromotionReceipt;\n readonly refinementQuestions: readonly string[];\n readonly finalAssetRef?: ModelAssetRef;\n readonly stateReasonCode?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/** Bounded compute and output budgets accepted by a generator port. */\nexport interface ModelGeneratorBudgets {\n readonly maxDurationMs: number;\n readonly maxTriangles: number;\n readonly maxBytes: number;\n readonly maxTextureBytes: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Normalized request passed to a model generator implementation. */\nexport interface ModelGeneratorRequest {\n readonly generationId: string;\n readonly request: ModelRequestSpec;\n readonly budgets: ModelGeneratorBudgets;\n readonly seed: string;\n readonly deadline: string;\n}\n\n/** Disabled Phase 1 generator result. */\nexport interface DisabledModelGeneratorResult {\n readonly status: \"disabled\";\n readonly generationId: string;\n readonly reasonCode: typeof MODEL_GENERATOR_DISABLED_REASON_CODE;\n}\n\n/** Versioned generator identity retained with source-bundle evidence. */\nexport interface ModelGeneratorIdentity {\n readonly id: string;\n readonly version: string;\n}\n\n/** Bounded internal artifacts emitted for normal ingestion by an enabled generator. */\nexport type ModelGeneratorArtifactRole =\n | \"model-entrypoint\"\n | \"model-dependency\"\n | \"binary\"\n | \"texture\"\n | \"metadata\";\n\n/** One generated artifact and its closed ingestion role. */\nexport interface ModelGeneratorArtifact extends ModelResourceRef {\n readonly role: ModelGeneratorArtifactRole;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Measured generator use checked against the invocation budgets. */\nexport interface ModelGeneratorUsage {\n readonly durationMs: number;\n readonly triangleCount: number;\n readonly byteLength: number;\n readonly textureByteLength: number;\n readonly maxTextureDimensionPx: number;\n}\n\n/** Request-bound source bundle submitted to the normal quarantine and ingestion path. */\nexport interface ModelGeneratorSourceBundle {\n readonly bundleId: string;\n readonly generationId: string;\n readonly entrypointUri: string;\n readonly artifacts: readonly ModelGeneratorArtifact[];\n readonly generator: ModelGeneratorIdentity;\n readonly generatedAt: string;\n readonly seed: string;\n readonly context: ModelGeneratorRequest;\n readonly usage: ModelGeneratorUsage;\n}\n\n/** Successful generator result consumed by the normal processing pipeline. */\nexport interface GeneratedModelGeneratorResult {\n readonly status: \"generated\";\n readonly generationId: string;\n readonly sourceBundle: ModelGeneratorSourceBundle;\n}\n\n/** Stable reasons an enabled generator may be temporarily or permanently unavailable. */\nexport type ModelGeneratorUnavailableReason =\n | \"capacity-unavailable\"\n | \"provider-unavailable\"\n | \"authentication-required\"\n | \"rate-limited\"\n | \"unsupported-request\";\n\n/** Stable generator execution or output-validation failure reasons. */\nexport type ModelGeneratorFailureReason =\n | \"provider-failed\"\n | \"invalid-generator-output\"\n | \"internal-failure\";\n\n/** Stable reasons a generator invocation ended without producing an output. */\nexport type ModelGeneratorCancellationReason =\n | \"caller-aborted\"\n | \"deadline-exceeded\"\n | \"superseded\"\n | \"service-shutdown\";\n\ninterface ModelGeneratorTerminalEvidence {\n readonly generationId: string;\n readonly retryable: boolean;\n readonly occurredAt: string;\n readonly diagnosticId?: string;\n}\n\n/** Request-bound unavailable outcome with stable retryability. */\nexport interface UnavailableModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"unavailable\";\n readonly reasonCode: ModelGeneratorUnavailableReason;\n}\n\n/** Request-bound failed outcome without raw provider error disclosure. */\nexport interface FailedModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"failed\";\n readonly reasonCode: ModelGeneratorFailureReason;\n}\n\n/** Request-bound cancellation outcome. */\nexport interface CancelledModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"cancelled\";\n readonly reasonCode: ModelGeneratorCancellationReason;\n}\n\n/** Name of one bounded generator resource dimension. */\nexport type ModelGeneratorBudgetName = keyof ModelGeneratorBudgets;\n\n/** Exact observed value that exceeded one invocation budget. */\nexport interface ModelGeneratorBudgetViolation {\n readonly budget: ModelGeneratorBudgetName;\n readonly limit: number;\n readonly observed: number;\n}\n\n/** Fail-closed outcome carrying no partial source bundle. */\nexport interface BudgetExceededModelGeneratorResult extends ModelGeneratorTerminalEvidence {\n readonly status: \"budget-exceeded\";\n readonly reasonCode: \"generator-budget-exceeded\";\n readonly retryable: false;\n readonly violations: readonly ModelGeneratorBudgetViolation[];\n}\n\n/** Stable result union shared by disabled Phase 1 and future enabled generators. */\nexport type ModelGeneratorResult =\n | DisabledModelGeneratorResult\n | GeneratedModelGeneratorResult\n | UnavailableModelGeneratorResult\n | FailedModelGeneratorResult\n | CancelledModelGeneratorResult\n | BudgetExceededModelGeneratorResult;\n\n/** Optional cancellation context for generator calls. */\nexport interface ModelGeneratorCallOptions {\n readonly signal?: AbortSignal;\n}\n\n/** Generator boundary; Phase 1 supplies only a disabled implementation. */\nexport interface ModelGeneratorPort {\n readonly enabled: boolean;\n generate(\n input: ModelGeneratorRequest,\n options?: ModelGeneratorCallOptions,\n ): Promise<ModelGeneratorResult>;\n}\n\nconst ASSET_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/u;\nconst TOKEN_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._:-]{0,127}$/u;\nconst CONFIRMATION_TOKEN_PATTERN = /^[0-9A-Za-z_-]{32,256}$/u;\nconst OPAQUE_SOURCE_ASSET_ID_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,255}$/u;\nconst MODEL_PATH_SEGMENT_PATTERN = /^[0-9A-Za-z._~-]+$/u;\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst CONTENT_TYPE_PATTERN = /^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/iu;\nconst URL_LIKE_PATTERN = /(?:https?:\\/\\/|\\bwww\\.)/iu;\nconst ENCODED_PATH_PATTERN = /%(?:2e|2f|5c|25)/iu;\nconst MAX_QUERY_LENGTH = 512;\nconst MAX_TEXT_LENGTH = 512;\nconst MAX_LIST_LENGTH = 32;\nconst MAX_CANDIDATES = 50;\nconst MAX_ATTEMPTS = 100;\nconst MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES = 1e-6;\nconst MODEL_MATCH_ASSURANCE_ORDER: Readonly<Record<ModelMatchAssurance, number>> = Object.freeze({\n none: 0,\n low: 1,\n high: 2,\n});\n\nfunction deepFreeze<T>(value: T): T {\n if (value !== null && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child);\n }\n Object.freeze(value);\n }\n return value;\n}\n\nfunction assertRecord(value: unknown, fieldName: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${fieldName} must be an object.`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${fieldName} must be a plain object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction assertAllowedKeys(\n record: Record<string, unknown>,\n allowedKeys: readonly string[],\n fieldName: string,\n): void {\n const unexpected = Object.keys(record).find((key) => !allowedKeys.includes(key));\n if (unexpected !== undefined) {\n throw new Error(`${fieldName} contains unexpected field ${unexpected}.`);\n }\n}\n\nfunction assertContractVersion(record: Record<string, unknown>, fieldName: string): void {\n if (\n record.contractVersion !== undefined\n && record.contractVersion !== MODEL_RESOLUTION_CONTRACT_VERSION\n ) {\n throw new Error(`${fieldName} contractVersion is not supported.`);\n }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n return [...value].some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 31 || codePoint === 127;\n });\n}\n\nfunction requiredString(\n value: unknown,\n fieldName: string,\n maxLength = MAX_TEXT_LENGTH,\n): string {\n if (typeof value !== \"string\") {\n throw new Error(`${fieldName} must be a string.`);\n }\n const normalized = value.trim().replace(/\\s+/gu, \" \");\n if (normalized.length === 0 || normalized.length > maxLength || hasControlCharacters(normalized)) {\n throw new Error(`${fieldName} must be a non-empty bounded string.`);\n }\n return normalized;\n}\n\nfunction optionalString(\n value: unknown,\n fieldName: string,\n maxLength = MAX_TEXT_LENGTH,\n): string | undefined {\n return value === undefined ? undefined : requiredString(value, fieldName, maxLength);\n}\n\nfunction assertNoDirectUrl(value: string, fieldName: string): void {\n if (URL_LIKE_PATTERN.test(value)) {\n throw new Error(`${fieldName} must not contain a direct URL.`);\n }\n}\n\nfunction requiredToken(value: unknown, fieldName: string): string {\n const token = requiredString(value, fieldName, 128);\n if (!TOKEN_PATTERN.test(token)) {\n throw new Error(`${fieldName} must be a token up to 128 characters.`);\n }\n return token;\n}\n\nfunction requiredModelPathSegment(value: unknown, fieldName: string): string {\n const segment = requiredString(value, fieldName, 128);\n if (\n !MODEL_PATH_SEGMENT_PATTERN.test(segment)\n || segment === \".\"\n || segment === \"..\"\n ) {\n throw new Error(`${fieldName} must be a canonical model URI path segment.`);\n }\n return segment;\n}\n\nfunction requiredAttestationToken(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !CONFIRMATION_TOKEN_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a bounded opaque signed token.`);\n }\n return value;\n}\n\nfunction requiredSha256(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a lowercase 64-character sha256 digest.`);\n }\n return value;\n}\n\nfunction requiredInteger(\n value: unknown,\n fieldName: string,\n minimum: number,\n maximum: number,\n): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new Error(`${fieldName} must be an integer between ${minimum} and ${maximum}.`);\n }\n return value as number;\n}\n\nfunction requiredFiniteNumber(\n value: unknown,\n fieldName: string,\n minimum: number,\n maximum = Number.MAX_VALUE,\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < minimum || value > maximum) {\n throw new Error(`${fieldName} must be a finite number between ${minimum} and ${maximum}.`);\n }\n return value;\n}\n\nfunction requiredBoolean(value: unknown, fieldName: string): boolean {\n if (typeof value !== \"boolean\") {\n throw new Error(`${fieldName} must be a boolean.`);\n }\n return value;\n}\n\nfunction requiredTimestamp(value: unknown, fieldName: string): string {\n const timestamp = requiredString(value, fieldName, 64);\n const parsed = new Date(timestamp);\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/u.test(timestamp) || Number.isNaN(parsed.getTime())) {\n throw new Error(`${fieldName} must be a valid UTC RFC3339 timestamp.`);\n }\n const withoutSuffix = timestamp.slice(0, -1);\n const [wholeSeconds, fractionalSeconds = \"\"] = withoutSuffix.split(\".\");\n const canonicalInput = `${wholeSeconds}.${fractionalSeconds.padEnd(3, \"0\")}Z`;\n const canonicalTimestamp = parsed.toISOString();\n if (canonicalTimestamp !== canonicalInput) {\n throw new Error(`${fieldName} must be a valid UTC RFC3339 timestamp.`);\n }\n return canonicalTimestamp;\n}\n\nfunction requiredEnum<T extends string>(\n value: unknown,\n values: readonly T[],\n fieldName: string,\n): T {\n if (typeof value !== \"string\" || !values.includes(value as T)) {\n throw new Error(`${fieldName} is not supported.`);\n }\n return value as T;\n}\n\nfunction stringList(\n value: unknown,\n fieldName: string,\n options: { readonly tokens?: boolean; readonly maxItems?: number } = {},\n): readonly string[] {\n if (!Array.isArray(value)) {\n throw new Error(`${fieldName} must be an array.`);\n }\n const maxItems = options.maxItems ?? MAX_LIST_LENGTH;\n if (value.length > maxItems) {\n throw new Error(`${fieldName} must contain at most ${maxItems} items.`);\n }\n const items = value.map((item, index) => {\n const normalized = options.tokens\n ? requiredToken(item, `${fieldName}[${index}]`)\n : requiredString(item, `${fieldName}[${index}]`, 128);\n assertNoDirectUrl(normalized, `${fieldName}[${index}]`);\n return normalized;\n });\n const normalizedKeys = new Set(items.map((item) => item.toLocaleLowerCase(\"en-GB\")));\n if (normalizedKeys.size !== items.length) {\n throw new Error(`${fieldName} must not contain duplicate values.`);\n }\n return items;\n}\n\nfunction requiredVector3(value: unknown, fieldName: string, positive = false): ModelVector3 {\n if (!Array.isArray(value) || value.length !== 3) {\n throw new Error(`${fieldName} must contain exactly three numbers.`);\n }\n return [\n requiredFiniteNumber(value[0], `${fieldName}[0]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n requiredFiniteNumber(value[1], `${fieldName}[1]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n requiredFiniteNumber(value[2], `${fieldName}[2]`, positive ? Number.EPSILON : -Number.MAX_VALUE),\n ];\n}\n\nfunction createBounds(value: unknown, fieldName: string): ModelBoundsMetres {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"min\", \"max\"], fieldName);\n const min = requiredVector3(record.min, `${fieldName}.min`);\n const max = requiredVector3(record.max, `${fieldName}.max`);\n if (min.some((axis, index) => axis >= max[index]!)) {\n throw new Error(`${fieldName} min axes must be lower than max axes.`);\n }\n return { min, max };\n}\n\nfunction createDimensions(value: unknown, fieldName: string): ModelDimensionsMetres {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"width\", \"height\", \"depth\"], fieldName);\n return {\n width: requiredFiniteNumber(record.width, `${fieldName}.width`, Number.EPSILON),\n height: requiredFiniteNumber(record.height, `${fieldName}.height`, Number.EPSILON),\n depth: requiredFiniteNumber(record.depth, `${fieldName}.depth`, Number.EPSILON),\n };\n}\n\nfunction assertModelUri(value: unknown, fieldName: string): string {\n const uri = requiredString(value, fieldName, 2048);\n const canonicalPrefix = \"mcp://models/\";\n if (\n !uri.startsWith(canonicalPrefix)\n || uri.includes(\"\\\\\")\n || uri.includes(\"?\")\n || uri.includes(\"#\")\n || ENCODED_PATH_PATTERN.test(uri)\n ) {\n throw new Error(\n `${fieldName} must be a canonical traversal-free mcp://models URI without query or fragment.`,\n );\n }\n const rawSegments = uri.slice(canonicalPrefix.length).split(\"/\");\n if (\n rawSegments.length === 0\n || rawSegments.some((segment) =>\n segment.length === 0\n || segment === \".\"\n || segment === \"..\"\n || !MODEL_PATH_SEGMENT_PATTERN.test(segment))\n ) {\n throw new Error(`${fieldName} must be a canonical traversal-free mcp://models URI.`);\n }\n let parsed: URL;\n try {\n parsed = new URL(uri);\n } catch {\n throw new Error(`${fieldName} must be a valid mcp://models URI.`);\n }\n if (\n parsed.protocol !== \"mcp:\"\n || parsed.hostname !== \"models\"\n || parsed.port.length > 0\n || parsed.username.length > 0\n || parsed.password.length > 0\n || parsed.search.length > 0\n || parsed.hash.length > 0\n ) {\n throw new Error(`${fieldName} must be a credential-free mcp://models URI.`);\n }\n if (parsed.href !== uri) {\n throw new Error(`${fieldName} must use canonical mcp://models serialization.`);\n }\n return uri;\n}\n\nfunction isPrivateHostname(hostname: string): boolean {\n const lowerHostname = hostname.toLowerCase();\n if (lowerHostname.endsWith(\".\")) {\n return true;\n }\n const normalized = lowerHostname.replace(/^\\[|\\]$/gu, \"\");\n if (\n normalized === \"localhost\"\n || normalized.endsWith(\".localhost\")\n || normalized.endsWith(\".local\")\n || normalized.endsWith(\".internal\")\n || normalized.endsWith(\".lan\")\n || normalized.endsWith(\".home\")\n || normalized.endsWith(\".arpa\")\n || normalized.endsWith(\".nip.io\")\n || normalized.endsWith(\".sslip.io\")\n || normalized === \"localtest.me\"\n || normalized.endsWith(\".localtest.me\")\n ) {\n return true;\n }\n if (normalized.includes(\":\")) {\n if (\n normalized === \"::\"\n || normalized === \"::1\"\n || normalized.startsWith(\"::ffff:\")\n || normalized.startsWith(\"fc\")\n || normalized.startsWith(\"fd\")\n || /^(?:fe8|fe9|fea|feb)/u.test(normalized)\n || normalized.startsWith(\"ff\")\n || normalized.startsWith(\"2001:db8:\")\n ) {\n return true;\n }\n const firstHextet = Number.parseInt(normalized.split(\":\", 1)[0] ?? \"\", 16);\n return !Number.isInteger(firstHextet) || firstHextet < 0x2000 || firstHextet > 0x3fff;\n }\n const match = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/u.exec(normalized);\n if (!match) {\n return !normalized.includes(\".\");\n }\n const octets = match.slice(1).map(Number);\n return octets.some((octet) => octet > 255)\n || octets[0] === 0\n || octets[0] === 10\n || (octets[0] === 100 && (octets[1] ?? 0) >= 64 && (octets[1] ?? 0) <= 127)\n || octets[0] === 127\n || (octets[0] === 169 && octets[1] === 254)\n || (octets[0] === 172 && (octets[1] ?? 0) >= 16 && (octets[1] ?? 0) <= 31)\n || (octets[0] === 192 && octets[1] === 0 && octets[2] === 0)\n || (octets[0] === 192 && octets[1] === 0 && octets[2] === 2)\n || (octets[0] === 192 && octets[1] === 168)\n || (octets[0] === 198 && (octets[1] === 18 || octets[1] === 19))\n || (octets[0] === 198 && octets[1] === 51 && octets[2] === 100)\n || (octets[0] === 203 && octets[1] === 0 && octets[2] === 113)\n || (octets[0] ?? 0) >= 224;\n}\n\nfunction assertPublicPageUri(value: unknown, fieldName: string): string {\n const uri = requiredString(value, fieldName, 2048);\n let parsed: URL;\n try {\n parsed = new URL(uri);\n } catch {\n throw new Error(`${fieldName} must be a valid public HTTPS page URI.`);\n }\n if (\n parsed.protocol !== \"https:\"\n || parsed.username.length > 0\n || parsed.password.length > 0\n || parsed.hostname.length === 0\n || uri.includes(\"?\")\n || uri.includes(\"#\")\n || isPrivateHostname(parsed.hostname)\n ) {\n throw new Error(`${fieldName} must be a credential-free public HTTPS page URI.`);\n }\n return uri;\n}\n\nfunction assetId(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !ASSET_ID_PATTERN.test(value)) {\n throw new Error(`${fieldName} must use lowercase kebab-case letters and numbers.`);\n }\n return value;\n}\n\nfunction assetVersion(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !VERSION_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be a non-empty version token up to 128 characters.`);\n }\n return value;\n}\n\nfunction opaqueSourceAssetId(value: unknown, fieldName = \"ModelProvenance.sourceAssetId\"): string {\n if (typeof value !== \"string\" || !OPAQUE_SOURCE_ASSET_ID_PATTERN.test(value)) {\n throw new Error(`${fieldName} must be an opaque bounded token.`);\n }\n return value;\n}\n\nfunction createHardConstraints(value: unknown): ModelHardConstraints {\n const record = value === undefined\n ? {}\n : assertRecord(value, \"ModelRequestSpec.hardConstraints\");\n assertAllowedKeys(record, [\n \"boundsMetres\",\n \"dimensionsMetres\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n \"maxPartitionCellMetres\",\n \"lod\",\n \"collision\",\n \"partition\",\n ], \"ModelRequestSpec.hardConstraints\");\n const result: {\n boundsMetres?: ModelBoundsMetres;\n dimensionsMetres?: ModelDimensionsMetres;\n maxTriangles?: number;\n maxBytes?: number;\n maxTextureBytes?: number;\n maxTextureDimensionPx?: number;\n maxPartitionCellMetres?: number;\n lod?: ModelRequirementPolicy;\n collision?: ModelRequirementPolicy;\n partition?: ModelPartitionPolicy;\n } = {\n maxTriangles: STATIC_WORLD_V1_MODEL_POLICY.maxTriangles,\n maxBytes: STATIC_WORLD_V1_MODEL_POLICY.maxBytes,\n maxTextureBytes: STATIC_WORLD_V1_MODEL_POLICY.maxTextureBytes,\n maxTextureDimensionPx: STATIC_WORLD_V1_MODEL_POLICY.maxTextureDimensionPx,\n maxPartitionCellMetres: STATIC_WORLD_V1_MODEL_POLICY.maxPartitionCellMetres,\n lod: \"optional\",\n collision: \"optional\",\n partition: \"allowed\",\n };\n if (record.boundsMetres !== undefined) {\n result.boundsMetres = createBounds(record.boundsMetres, \"ModelRequestSpec.hardConstraints.boundsMetres\");\n }\n if (record.dimensionsMetres !== undefined) {\n result.dimensionsMetres = createDimensions(record.dimensionsMetres, \"ModelRequestSpec.hardConstraints.dimensionsMetres\");\n }\n if (record.maxTriangles !== undefined) {\n result.maxTriangles = requiredInteger(\n record.maxTriangles,\n \"ModelRequestSpec.hardConstraints.maxTriangles\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTriangles,\n );\n }\n if (record.maxBytes !== undefined) {\n result.maxBytes = requiredInteger(\n record.maxBytes,\n \"ModelRequestSpec.hardConstraints.maxBytes\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxBytes,\n );\n }\n if (record.maxTextureBytes !== undefined) {\n result.maxTextureBytes = requiredInteger(\n record.maxTextureBytes,\n \"ModelRequestSpec.hardConstraints.maxTextureBytes\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTextureBytes,\n );\n }\n if (record.maxTextureDimensionPx !== undefined) {\n result.maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelRequestSpec.hardConstraints.maxTextureDimensionPx\",\n 1,\n STATIC_WORLD_V1_MODEL_POLICY.maxTextureDimensionPx,\n );\n }\n if (record.maxPartitionCellMetres !== undefined) {\n result.maxPartitionCellMetres = requiredFiniteNumber(\n record.maxPartitionCellMetres,\n \"ModelRequestSpec.hardConstraints.maxPartitionCellMetres\",\n Number.EPSILON,\n STATIC_WORLD_V1_MODEL_POLICY.maxPartitionCellMetres,\n );\n }\n if (record.lod !== undefined) {\n result.lod = requiredEnum(record.lod, [\"required\", \"optional\", \"forbidden\"] as const, \"ModelRequestSpec.hardConstraints.lod\");\n }\n if (record.collision !== undefined) {\n result.collision = requiredEnum(record.collision, [\"required\", \"optional\", \"forbidden\"] as const, \"ModelRequestSpec.hardConstraints.collision\");\n }\n if (record.partition !== undefined) {\n result.partition = requiredEnum(record.partition, [\"single\", \"allowed\", \"required\"] as const, \"ModelRequestSpec.hardConstraints.partition\");\n }\n if (record.maxTextureBytes === undefined && result.maxBytes !== undefined) {\n result.maxTextureBytes = Math.min(result.maxTextureBytes ?? result.maxBytes, result.maxBytes);\n }\n if (\n result.maxBytes !== undefined\n && result.maxTextureBytes !== undefined\n && result.maxTextureBytes > result.maxBytes\n ) {\n throw new Error(\"ModelRequestSpec hardConstraints maxTextureBytes must not exceed maxBytes.\");\n }\n if (result.boundsMetres !== undefined && result.dimensionsMetres !== undefined) {\n const boundsDimensions = result.boundsMetres.max.map(\n (axis, index) => axis - result.boundsMetres!.min[index]!,\n );\n const suppliedDimensions = [\n result.dimensionsMetres.width,\n result.dimensionsMetres.height,\n result.dimensionsMetres.depth,\n ];\n if (boundsDimensions.some((axis, index) =>\n Math.abs(axis - suppliedDimensions[index]!) > Math.max(1e-6, Math.abs(axis) * 1e-6))) {\n throw new Error(\"ModelRequestSpec hardConstraints dimensionsMetres must match boundsMetres.\");\n }\n }\n return result;\n}\n\nfunction createSoftPreferences(value: unknown): ModelSoftPreferences {\n if (value === undefined) {\n return {};\n }\n const record = assertRecord(value, \"ModelRequestSpec.softPreferences\");\n assertAllowedKeys(record, [\n \"category\",\n \"style\",\n \"materials\",\n \"colors\",\n \"era\",\n \"condition\",\n \"tags\",\n ], \"ModelRequestSpec.softPreferences\");\n const result: {\n category?: string;\n style?: string;\n materials?: readonly string[];\n colors?: readonly string[];\n era?: string;\n condition?: string;\n tags?: readonly string[];\n } = {};\n for (const field of [\"category\", \"style\", \"era\", \"condition\"] as const) {\n const normalized = optionalString(record[field], `ModelRequestSpec.softPreferences.${field}`, 80);\n if (normalized !== undefined) {\n assertNoDirectUrl(normalized, `ModelRequestSpec.softPreferences.${field}`);\n result[field] = normalized;\n }\n }\n for (const field of [\"materials\", \"colors\", \"tags\"] as const) {\n if (record[field] !== undefined) {\n result[field] = stringList(record[field], `ModelRequestSpec.softPreferences.${field}`);\n }\n }\n return result;\n}\n\n/** Validate and normalize an unknown model request payload. */\nexport function createModelRequestSpec(input: unknown): ModelRequestSpec {\n const record = assertRecord(input, \"ModelRequestSpec\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"policyProfileId\",\n \"query\",\n \"revision\",\n \"locale\",\n \"rankerId\",\n \"hardConstraints\",\n \"softPreferences\",\n \"exclusions\",\n ], \"ModelRequestSpec\");\n assertContractVersion(record, \"ModelRequestSpec\");\n if (\n record.policyProfileId !== undefined\n && record.policyProfileId !== STATIC_WORLD_V1_MODEL_POLICY.id\n ) {\n throw new Error(\"ModelRequestSpec.policyProfileId must be static-world-v1.\");\n }\n const query = requiredString(record.query, \"ModelRequestSpec.query\", MAX_QUERY_LENGTH);\n assertNoDirectUrl(query, \"ModelRequestSpec.query\");\n const revision = requiredInteger(\n record.revision,\n `ModelRequestSpec revision (maximum ${MODEL_REQUEST_MAX_REVISION})`,\n 0,\n MODEL_REQUEST_MAX_REVISION,\n );\n let locale: string | undefined;\n if (record.locale !== undefined) {\n const requestedLocale = requiredString(record.locale, \"ModelRequestSpec.locale\", 64);\n try {\n [locale] = Intl.getCanonicalLocales(requestedLocale);\n } catch {\n throw new Error(\"ModelRequestSpec.locale must be a valid BCP 47 locale.\");\n }\n if (locale === undefined) {\n throw new Error(\"ModelRequestSpec.locale must be a valid BCP 47 locale.\");\n }\n }\n const rankerId = record.rankerId === undefined\n ? undefined\n : requiredToken(record.rankerId, \"ModelRequestSpec.rankerId\");\n const result: ModelRequestSpec = {\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n policyProfileId: STATIC_WORLD_V1_MODEL_POLICY.id,\n query,\n revision,\n ...(locale === undefined ? {} : { locale }),\n ...(rankerId === undefined ? {} : { rankerId }),\n hardConstraints: createHardConstraints(record.hardConstraints),\n softPreferences: createSoftPreferences(record.softPreferences),\n exclusions: record.exclusions === undefined\n ? []\n : stringList(record.exclusions, \"ModelRequestSpec.exclusions\"),\n };\n return deepFreeze(result);\n}\n\nfunction deriveRawModelMatchAssurance(score: number, exactMatch: boolean): ModelMatchAssurance {\n if (exactMatch || score >= MODEL_MATCH_ASSURANCE_THRESHOLDS.high) {\n return \"high\";\n }\n if (score >= MODEL_MATCH_ASSURANCE_THRESHOLDS.low) {\n return \"low\";\n }\n return \"none\";\n}\n\n/** Derive an assurance band while independently failing closed on hard constraints. */\nexport function classifyModelMatchAssurance(\n score: number,\n hardConstraintPass: boolean,\n evidenceMode: ModelRankerEvidenceMode,\n exactMatch: boolean,\n assuranceCeiling: ModelMatchAssurance,\n): ModelMatchAssurance {\n requiredFiniteNumber(score, \"Model match score\", 0, 1);\n requiredBoolean(hardConstraintPass, \"Model match hardConstraintPass\");\n requiredEnum(evidenceMode, MODEL_RANKER_EVIDENCE_MODES, \"Model match evidenceMode\");\n requiredBoolean(exactMatch, \"Model match exactMatch\");\n requiredEnum(assuranceCeiling, MODEL_MATCH_ASSURANCE_BANDS, \"Model match assuranceCeiling\");\n if (evidenceMode === \"text-only\" && exactMatch) {\n throw new Error(\"Model match exactMatch must be false for text-only evidence.\");\n }\n if (evidenceMode === \"text-only\" && assuranceCeiling === \"high\") {\n throw new Error(\"Model match text-only assuranceCeiling must be low or none.\");\n }\n if (evidenceMode === \"exact-identifier\" && !exactMatch) {\n throw new Error(\"Model match exact-identifier evidence requires exactMatch true.\");\n }\n if (evidenceMode !== \"exact-identifier\" && evidenceMode !== \"text-only\" && exactMatch) {\n throw new Error(\"Model match exactMatch requires exact-identifier evidence.\");\n }\n if (!hardConstraintPass) {\n return \"none\";\n }\n const rawAssurance = deriveRawModelMatchAssurance(score, exactMatch);\n return MODEL_MATCH_ASSURANCE_ORDER[rawAssurance] <= MODEL_MATCH_ASSURANCE_ORDER[assuranceCeiling]\n ? rawAssurance\n : assuranceCeiling;\n}\n\nfunction createRankerRef(value: unknown): ModelRankerRef {\n const record = assertRecord(value, \"ModelMatchAssessment.ranker\");\n assertAllowedKeys(record, [\n \"id\",\n \"version\",\n \"calibrationId\",\n \"calibrationVersion\",\n \"evidenceMode\",\n \"assuranceCeiling\",\n ], \"ModelMatchAssessment.ranker\");\n return {\n id: requiredToken(record.id, \"ModelMatchAssessment.ranker.id\"),\n version: assetVersion(record.version, \"ModelMatchAssessment.ranker.version\"),\n calibrationId: requiredToken(record.calibrationId, \"ModelMatchAssessment.ranker.calibrationId\"),\n calibrationVersion: assetVersion(record.calibrationVersion, \"ModelMatchAssessment.ranker.calibrationVersion\"),\n evidenceMode: requiredEnum(\n record.evidenceMode,\n MODEL_RANKER_EVIDENCE_MODES,\n \"ModelMatchAssessment.ranker.evidenceMode\",\n ),\n assuranceCeiling: requiredEnum(\n record.assuranceCeiling,\n MODEL_MATCH_ASSURANCE_BANDS,\n \"ModelMatchAssessment.ranker.assuranceCeiling\",\n ),\n };\n}\n\n/** Validate and freeze an unknown match assessment payload. */\nexport function createModelMatchAssessment(input: unknown): ModelMatchAssessment {\n const record = assertRecord(input, \"ModelMatchAssessment\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"score\",\n \"assurance\",\n \"hardConstraintPass\",\n \"exactMatch\",\n \"reasonCodes\",\n \"ranker\",\n \"fidelityWarnings\",\n \"request\",\n \"candidateId\",\n \"candidateContentHash\",\n ], \"ModelMatchAssessment\");\n assertContractVersion(record, \"ModelMatchAssessment\");\n const score = requiredFiniteNumber(record.score, \"ModelMatchAssessment.score\", 0, 1);\n const hardConstraintPass = requiredBoolean(record.hardConstraintPass, \"ModelMatchAssessment.hardConstraintPass\");\n const exactMatch = requiredBoolean(record.exactMatch, \"ModelMatchAssessment.exactMatch\");\n const ranker = createRankerRef(record.ranker);\n const request = createModelRequestSpec(record.request);\n if (request.rankerId !== undefined && request.rankerId !== ranker.id) {\n throw new Error(\"ModelMatchAssessment ranker.id must match the caller-selected request rankerId.\");\n }\n if (record.assurance !== undefined) {\n requiredEnum(record.assurance, MODEL_MATCH_ASSURANCE_BANDS, \"ModelMatchAssessment.assurance\");\n }\n let reasonCodes = stringList(record.reasonCodes, \"ModelMatchAssessment.reasonCodes\", {\n tokens: true,\n });\n if (!hardConstraintPass && reasonCodes.length === 0) {\n throw new Error(\"ModelMatchAssessment.reasonCodes must explain a failed hard constraint.\");\n }\n const assurance = classifyModelMatchAssurance(\n score,\n hardConstraintPass,\n ranker.evidenceMode,\n exactMatch,\n ranker.assuranceCeiling,\n );\n const rawAssurance = deriveRawModelMatchAssurance(score, exactMatch);\n if (\n hardConstraintPass\n && MODEL_MATCH_ASSURANCE_ORDER[assurance] < MODEL_MATCH_ASSURANCE_ORDER[rawAssurance]\n ) {\n const ceilingReason = ranker.evidenceMode === \"text-only\"\n ? MODEL_TEXT_ONLY_ASSURANCE_CEILING_REASON_CODE\n : MODEL_RANKER_ASSURANCE_CEILING_REASON_CODE;\n if (!reasonCodes.includes(ceilingReason)) {\n if (reasonCodes.length >= MAX_LIST_LENGTH) {\n throw new Error(\n `ModelMatchAssessment.reasonCodes must contain at most ${MAX_LIST_LENGTH} items including the assurance ceiling reason.`,\n );\n }\n reasonCodes = [...reasonCodes, ceilingReason];\n }\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n score,\n assurance,\n hardConstraintPass,\n exactMatch,\n reasonCodes,\n ranker,\n fidelityWarnings: stringList(record.fidelityWarnings ?? [], \"ModelMatchAssessment.fidelityWarnings\"),\n request,\n candidateId: requiredToken(record.candidateId, \"ModelMatchAssessment.candidateId\"),\n candidateContentHash: requiredSha256(\n record.candidateContentHash,\n \"ModelMatchAssessment.candidateContentHash\",\n ),\n });\n}\n\n/** Validate and freeze technical facts about a processed candidate. */\nexport function createModelTechnicalProfile(input: unknown): ModelTechnicalProfile {\n const record = assertRecord(input, \"ModelTechnicalProfile\");\n assertAllowedKeys(record, [\n \"boundsMetres\",\n \"dimensionsMetres\",\n \"triangleCount\",\n \"byteLength\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n \"lodCount\",\n \"hasCollision\",\n \"partitionCount\",\n \"partitionCellMetres\",\n ], \"ModelTechnicalProfile\");\n const boundsMetres = createBounds(record.boundsMetres, \"ModelTechnicalProfile.boundsMetres\");\n const dimensionsMetres = createDimensions(record.dimensionsMetres, \"ModelTechnicalProfile.dimensionsMetres\");\n const derivedDimensions = boundsMetres.max.map((axis, index) => axis - boundsMetres.min[index]!) as [number, number, number];\n const suppliedDimensions = [dimensionsMetres.width, dimensionsMetres.height, dimensionsMetres.depth];\n if (derivedDimensions.some((axis, index) => Math.abs(axis - suppliedDimensions[index]!) > Math.max(1e-6, Math.abs(axis) * 1e-6))) {\n throw new Error(\"ModelTechnicalProfile dimensionsMetres must match boundsMetres.\");\n }\n const byteLength = requiredInteger(record.byteLength, \"ModelTechnicalProfile.byteLength\", 1, Number.MAX_SAFE_INTEGER);\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n \"ModelTechnicalProfile.textureByteLength\",\n 0,\n Number.MAX_SAFE_INTEGER,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelTechnicalProfile.maxTextureDimensionPx\",\n 0,\n 32_768,\n );\n if (textureByteLength > byteLength) {\n throw new Error(\"ModelTechnicalProfile.textureByteLength must not exceed model byteLength.\");\n }\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(\n \"ModelTechnicalProfile textureless models require textureByteLength and maxTextureDimensionPx to both be zero.\",\n );\n }\n return deepFreeze({\n boundsMetres,\n dimensionsMetres,\n triangleCount: requiredInteger(record.triangleCount, \"ModelTechnicalProfile.triangleCount\", 1, 1_000_000_000),\n byteLength,\n textureByteLength,\n maxTextureDimensionPx,\n lodCount: requiredInteger(record.lodCount, \"ModelTechnicalProfile.lodCount\", 1, 4),\n hasCollision: requiredBoolean(record.hasCollision, \"ModelTechnicalProfile.hasCollision\"),\n partitionCount: requiredInteger(record.partitionCount, \"ModelTechnicalProfile.partitionCount\", 1, 10_000),\n partitionCellMetres: requiredFiniteNumber(\n record.partitionCellMetres,\n \"ModelTechnicalProfile.partitionCellMetres\",\n Number.EPSILON,\n 1_000_000,\n ),\n });\n}\n\nfunction createAttribution(value: unknown): ModelAttribution {\n const record = assertRecord(value, \"ModelRightsAssessment.attribution\");\n assertAllowedKeys(record, [\"title\", \"creator\", \"notice\", \"sourcePageUri\"], \"ModelRightsAssessment.attribution\");\n const sourcePageUri = record.sourcePageUri === undefined\n ? undefined\n : assertPublicPageUri(record.sourcePageUri, \"ModelRightsAssessment.attribution.sourcePageUri\");\n return {\n title: requiredString(record.title, \"ModelRightsAssessment.attribution.title\", 256),\n creator: requiredString(record.creator, \"ModelRightsAssessment.attribution.creator\", 256),\n notice: requiredString(record.notice, \"ModelRightsAssessment.attribution.notice\", 512),\n ...(sourcePageUri === undefined ? {} : { sourcePageUri }),\n };\n}\n\n/** Validate and freeze rights and attribution evidence. */\nexport function createModelRightsAssessment(input: unknown): ModelRightsAssessment {\n const record = assertRecord(input, \"ModelRightsAssessment\");\n assertAllowedKeys(record, [\n \"decisionId\",\n \"decisionToken\",\n \"policyId\",\n \"policyVersion\",\n \"sourceId\",\n \"sourceAssetId\",\n \"sourceContentHash\",\n \"status\",\n \"licenseId\",\n \"evidencePageUri\",\n \"attribution\",\n \"reviewedAt\",\n ], \"ModelRightsAssessment\");\n const status = requiredEnum(record.status, MODEL_RIGHTS_STATUSES, \"ModelRightsAssessment.status\");\n const attribution = record.attribution === undefined ? undefined : createAttribution(record.attribution);\n if (status === \"attribution-required\" && attribution === undefined) {\n throw new Error(\"ModelRightsAssessment attribution is required for attribution-required rights.\");\n }\n if (status === \"attribution-required\" && attribution?.sourcePageUri === undefined) {\n throw new Error(\"ModelRightsAssessment attribution-required rights require a public attribution sourcePageUri.\");\n }\n return deepFreeze({\n decisionId: requiredToken(record.decisionId, \"ModelRightsAssessment.decisionId\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelRightsAssessment.decisionToken\",\n ),\n policyId: requiredToken(record.policyId, \"ModelRightsAssessment.policyId\"),\n policyVersion: assetVersion(record.policyVersion, \"ModelRightsAssessment.policyVersion\"),\n sourceId: requiredToken(record.sourceId, \"ModelRightsAssessment.sourceId\"),\n sourceAssetId: opaqueSourceAssetId(record.sourceAssetId, \"ModelRightsAssessment.sourceAssetId\"),\n sourceContentHash: requiredSha256(\n record.sourceContentHash,\n \"ModelRightsAssessment.sourceContentHash\",\n ),\n status,\n licenseId: requiredToken(record.licenseId, \"ModelRightsAssessment.licenseId\"),\n evidencePageUri: assertPublicPageUri(record.evidencePageUri, \"ModelRightsAssessment.evidencePageUri\"),\n ...(attribution === undefined ? {} : { attribution }),\n reviewedAt: requiredTimestamp(record.reviewedAt, \"ModelRightsAssessment.reviewedAt\"),\n });\n}\n\n/** Validate public-safe catalog, provider, or generated provenance. */\nexport function createModelProvenance(input: unknown): ModelProvenance {\n const record = assertRecord(input, \"ModelProvenance\");\n assertAllowedKeys(record, [\n \"kind\",\n \"sourceId\",\n \"sourceAssetId\",\n \"sourcePageUri\",\n \"contentHash\",\n \"capturedAt\",\n ], \"ModelProvenance\");\n const kind = requiredEnum(record.kind, MODEL_PROVENANCE_KINDS, \"ModelProvenance kind\");\n const sourceAssetId = opaqueSourceAssetId(record.sourceAssetId);\n const sourcePageUri = record.sourcePageUri === undefined\n ? undefined\n : assertPublicPageUri(record.sourcePageUri, \"ModelProvenance.sourcePageUri\");\n if (kind === \"provider\" && sourcePageUri === undefined) {\n throw new Error(\"ModelProvenance provider provenance requires sourcePageUri.\");\n }\n if (kind === \"generated\" && sourcePageUri !== undefined) {\n throw new Error(\"ModelProvenance generated provenance must not include sourcePageUri.\");\n }\n return deepFreeze({\n kind,\n sourceId: requiredToken(record.sourceId, \"ModelProvenance.sourceId\"),\n sourceAssetId,\n ...(sourcePageUri === undefined ? {} : { sourcePageUri }),\n contentHash: requiredSha256(record.contentHash, \"ModelProvenance.contentHash\"),\n capturedAt: requiredTimestamp(record.capturedAt, \"ModelProvenance.capturedAt\"),\n });\n}\n\n/** Validate and freeze an immutable player-safe model asset reference. */\nexport function createModelAssetRef(input: unknown): ModelAssetRef {\n const record = assertRecord(input, \"ModelAssetRef\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"assetId\",\n \"version\",\n \"kind\",\n \"contentHash\",\n \"runtimeManifestUri\",\n ], \"ModelAssetRef\");\n assertContractVersion(record, \"ModelAssetRef\");\n const validatedAssetId = assetId(record.assetId, \"ModelAssetRef.assetId\");\n const validatedVersion = assertImmutableAssetVersion(record.version);\n const runtimeManifestUri = assertModelUri(record.runtimeManifestUri, \"ModelAssetRef.runtimeManifestUri\");\n const expectedManifestUri = `mcp://models/catalog/${validatedAssetId}/versions/${validatedVersion}/manifest`;\n if (runtimeManifestUri !== expectedManifestUri) {\n throw new Error(\n \"ModelAssetRef.runtimeManifestUri must exactly match the assetId/version catalog identity.\",\n );\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n assetId: validatedAssetId,\n version: validatedVersion,\n kind: requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelAssetRef.kind\"),\n contentHash: requiredSha256(record.contentHash, \"ModelAssetRef.contentHash\"),\n runtimeManifestUri,\n });\n}\n\nfunction createCandidateAssetRef(value: unknown): ModelCandidateAssetRef {\n const record = assertRecord(value, \"ModelCandidate.assetRef\");\n const disposition = requiredEnum(record.disposition, [\"existing\", \"proposed\"], \"ModelCandidate.assetRef.disposition\");\n if (disposition === \"existing\") {\n assertAllowedKeys(record, [\"disposition\", \"asset\", \"kind\", \"contentHash\"], \"ModelCandidate.assetRef\");\n const asset = createModelAssetRef(record.asset);\n if (record.kind !== undefined && record.kind !== asset.kind) {\n throw new Error(\"ModelCandidate existing assetRef kind must match asset.\");\n }\n if (record.contentHash !== undefined && record.contentHash !== asset.contentHash) {\n throw new Error(\"ModelCandidate existing assetRef contentHash must match asset.\");\n }\n return {\n disposition,\n kind: asset.kind,\n contentHash: asset.contentHash,\n asset,\n };\n }\n assertAllowedKeys(record, [\"disposition\", \"proposalId\", \"kind\", \"contentHash\"], \"ModelCandidate.assetRef\");\n return {\n disposition,\n proposalId: requiredToken(record.proposalId, \"ModelCandidate.assetRef.proposalId\"),\n kind: requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelCandidate.assetRef.kind\"),\n contentHash: requiredSha256(record.contentHash, \"ModelCandidate.assetRef.contentHash\"),\n };\n}\n\nfunction createConfirmationView(value: unknown, index: number): ModelConfirmationView {\n const fieldName = `ModelCandidate.views[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"kind\", \"imageUri\", \"sha256\", \"contentType\", \"width\", \"height\"], fieldName);\n const width = requiredInteger(record.width, `${fieldName}.width`, MODEL_CONFIRMATION_VIEW_SIZE_PX, MODEL_CONFIRMATION_VIEW_SIZE_PX);\n const height = requiredInteger(record.height, `${fieldName}.height`, MODEL_CONFIRMATION_VIEW_SIZE_PX, MODEL_CONFIRMATION_VIEW_SIZE_PX);\n if (record.contentType !== \"image/png\") {\n throw new Error(`${fieldName}.contentType must be image/png.`);\n }\n return {\n kind: requiredEnum(record.kind, MODEL_CONFIRMATION_VIEW_KINDS, `${fieldName}.kind`),\n imageUri: assertModelUri(record.imageUri, `${fieldName}.imageUri`),\n sha256: requiredSha256(record.sha256, `${fieldName}.sha256`),\n contentType: \"image/png\",\n width: width as typeof MODEL_CONFIRMATION_VIEW_SIZE_PX,\n height: height as typeof MODEL_CONFIRMATION_VIEW_SIZE_PX,\n };\n}\n\nfunction createConfirmationViews(\n value: unknown,\n resolutionId: string,\n candidateId: string,\n): ModelConfirmationViews {\n if (!Array.isArray(value) || value.length !== MODEL_CONFIRMATION_VIEW_KINDS.length) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const views = value.map(createConfirmationView);\n const byKind = new Map(views.map((view) => [view.kind, view]));\n if (byKind.size !== MODEL_CONFIRMATION_VIEW_KINDS.length) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const ordered = MODEL_CONFIRMATION_VIEW_KINDS.map((kind) => byKind.get(kind));\n if (ordered.some((view) => view === undefined)) {\n throw new Error(\"Model candidate views must include exactly front, left, top, isometric.\");\n }\n const confirmedViews = ordered as ModelConfirmationView[];\n if (new Set(confirmedViews.map((view) => view.imageUri)).size !== confirmedViews.length) {\n throw new Error(\"Model candidate confirmation views must use unique resources.\");\n }\n for (const view of confirmedViews) {\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/${view.kind}.png`;\n if (view.imageUri !== expectedUri) {\n throw new Error(\n \"Model candidate confirmation view resources must be scoped to the resolution, candidate, and view kind.\",\n );\n }\n }\n return [ordered[0]!, ordered[1]!, ordered[2]!, ordered[3]!];\n}\n\nfunction createRenderEvidence(\n value: unknown,\n manifest: ModelProcessingManifest,\n views: ModelConfirmationViews,\n): ModelRenderEvidence {\n const record = assertRecord(value, \"ModelCandidate.renderEvidence\");\n assertAllowedKeys(record, [\n \"renderId\",\n \"rendererId\",\n \"rendererVersion\",\n \"settingsId\",\n \"settingsVersion\",\n \"processingManifestId\",\n \"sourceContentHash\",\n \"viewSha256s\",\n \"renderedAt\",\n \"attestationToken\",\n ], \"ModelCandidate.renderEvidence\");\n if (record.processingManifestId !== manifest.manifestId) {\n throw new Error(\"ModelCandidate.renderEvidence.processingManifestId must match processingManifest.\");\n }\n if (record.sourceContentHash !== manifest.lods[0]?.resource.sha256) {\n throw new Error(\"ModelCandidate.renderEvidence.sourceContentHash must match canonical LOD0.\");\n }\n if (!Array.isArray(record.viewSha256s) || record.viewSha256s.length !== 4) {\n throw new Error(\"ModelCandidate.renderEvidence.viewSha256s must contain four ordered hashes.\");\n }\n const viewSha256s = record.viewSha256s.map((digest, index) =>\n requiredSha256(digest, `ModelCandidate.renderEvidence.viewSha256s[${index}]`));\n if (viewSha256s.some((digest, index) => digest !== views[index]?.sha256)) {\n throw new Error(\"ModelCandidate.renderEvidence view hashes must match the candidate view pack.\");\n }\n const renderedAt = requiredTimestamp(record.renderedAt, \"ModelCandidate.renderEvidence.renderedAt\");\n if (Date.parse(renderedAt) < Date.parse(manifest.processedAt)) {\n throw new Error(\"ModelCandidate.renderEvidence.renderedAt must not precede processing.\");\n }\n return {\n renderId: requiredToken(record.renderId, \"ModelCandidate.renderEvidence.renderId\"),\n rendererId: requiredToken(record.rendererId, \"ModelCandidate.renderEvidence.rendererId\"),\n rendererVersion: assetVersion(record.rendererVersion, \"ModelCandidate.renderEvidence.rendererVersion\"),\n settingsId: requiredToken(record.settingsId, \"ModelCandidate.renderEvidence.settingsId\"),\n settingsVersion: assetVersion(record.settingsVersion, \"ModelCandidate.renderEvidence.settingsVersion\"),\n processingManifestId: manifest.manifestId,\n sourceContentHash: manifest.contentHash,\n viewSha256s: [viewSha256s[0]!, viewSha256s[1]!, viewSha256s[2]!, viewSha256s[3]!],\n renderedAt,\n attestationToken: requiredAttestationToken(\n record.attestationToken,\n \"ModelCandidate.renderEvidence.attestationToken\",\n ),\n };\n}\n\nfunction createCandidateHardGates(\n value: unknown,\n provenance: ModelProvenance,\n manifest: ModelProcessingManifest,\n): readonly ModelCandidateHardGateEvidence[] {\n if (!Array.isArray(value) || value.length !== MODEL_CANDIDATE_HARD_GATE_KINDS.length) {\n throw new Error(\"ModelCandidate.hardGates must contain every required independent hard gate.\");\n }\n const gates = value.map((item, index): ModelCandidateHardGateEvidence => {\n const fieldName = `ModelCandidate.hardGates[${index}]`;\n const record = assertRecord(item, fieldName);\n assertAllowedKeys(record, [\n \"kind\",\n \"outcome\",\n \"validatorId\",\n \"validatorVersion\",\n \"subjectContentHash\",\n \"reasonCodes\",\n \"evaluatedAt\",\n \"attestationToken\",\n ], fieldName);\n const kind = requiredEnum(record.kind, MODEL_CANDIDATE_HARD_GATE_KINDS, `${fieldName}.kind`);\n const subjectContentHash = requiredSha256(record.subjectContentHash, `${fieldName}.subjectContentHash`);\n const expectedHash = kind === \"malware-scan\"\n ? provenance.contentHash\n : manifest.closureHash;\n if (subjectContentHash !== expectedHash) {\n throw new Error(`${fieldName}.subjectContentHash must match the gate subject.`);\n }\n const outcome = requiredEnum(record.outcome, [\"passed\", \"blocked\"] as const, `${fieldName}.outcome`);\n const reasonCodes = stringList(record.reasonCodes ?? [], `${fieldName}.reasonCodes`, { tokens: true });\n if (outcome === \"blocked\" && reasonCodes.length === 0) {\n throw new Error(`${fieldName}.reasonCodes must explain a blocked hard gate.`);\n }\n return {\n kind,\n outcome,\n validatorId: requiredToken(record.validatorId, `${fieldName}.validatorId`),\n validatorVersion: assetVersion(record.validatorVersion, `${fieldName}.validatorVersion`),\n subjectContentHash,\n reasonCodes,\n evaluatedAt: requiredTimestamp(record.evaluatedAt, `${fieldName}.evaluatedAt`),\n attestationToken: requiredAttestationToken(record.attestationToken, `${fieldName}.attestationToken`),\n };\n });\n if (new Set(gates.map((gate) => gate.kind)).size !== MODEL_CANDIDATE_HARD_GATE_KINDS.length) {\n throw new Error(\"ModelCandidate.hardGates must contain each required gate exactly once.\");\n }\n if (new Set(gates.map((gate) => gate.attestationToken)).size !== gates.length) {\n throw new Error(\"ModelCandidate hard gate attestation tokens must be unique.\");\n }\n const byKind = new Map(gates.map((gate) => [gate.kind, gate]));\n return MODEL_CANDIDATE_HARD_GATE_KINDS.map((kind) => byKind.get(kind)!);\n}\n\n/** Validate and deeply freeze a model candidate from unknown JavaScript input. */\nexport function createModelCandidate(input: unknown): ModelCandidate {\n const record = assertRecord(input, \"ModelCandidate\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"resolutionId\",\n \"candidateId\",\n \"assetRef\",\n \"match\",\n \"provenance\",\n \"rights\",\n \"technicalProfile\",\n \"processingManifest\",\n \"views\",\n \"renderEvidence\",\n \"hardGates\",\n \"confirmationToken\",\n \"confirmationRequired\",\n ], \"ModelCandidate\");\n assertContractVersion(record, \"ModelCandidate\");\n if (record.confirmationRequired !== undefined && record.confirmationRequired !== true) {\n throw new Error(\"ModelCandidate confirmationRequired must always be true.\");\n }\n if (typeof record.confirmationToken !== \"string\" || !CONFIRMATION_TOKEN_PATTERN.test(record.confirmationToken)) {\n throw new Error(\"ModelCandidate confirmationToken must be a bounded opaque token.\");\n }\n const resolutionId = requiredModelPathSegment(record.resolutionId, \"ModelCandidate.resolutionId\");\n const candidateId = requiredModelPathSegment(record.candidateId, \"ModelCandidate.candidateId\");\n const assetRef = createCandidateAssetRef(record.assetRef);\n const technicalProfile = createModelTechnicalProfile(record.technicalProfile);\n const processingManifest = createModelProcessingManifest(record.processingManifest);\n if (\n processingManifest.resolutionId !== resolutionId\n ||\n processingManifest.candidateId !== candidateId\n || processingManifest.kind !== assetRef.kind\n || processingManifest.contentHash !== assetRef.contentHash\n || JSON.stringify(processingManifest.technicalProfile) !== JSON.stringify(technicalProfile)\n ) {\n throw new Error(\n \"ModelCandidate processingManifest must match candidateId, asset kind/contentHash, and technicalProfile.\",\n );\n }\n const match = createModelMatchAssessment(record.match);\n if (match.candidateId !== candidateId || match.candidateContentHash !== assetRef.contentHash) {\n throw new Error(\"ModelCandidate match assessment must bind candidateId and candidate contentHash.\");\n }\n const hardConstraintEvaluation = evaluateNormalizedModelHardConstraints(\n match.request,\n technicalProfile,\n );\n if (match.hardConstraintPass !== hardConstraintEvaluation.pass) {\n throw new Error(\n \"ModelCandidate match hardConstraintPass must match deterministic evaluation.\",\n );\n }\n if (\n hardConstraintEvaluation.reasonCodes.some(\n (reasonCode) => !match.reasonCodes.includes(reasonCode),\n )\n ) {\n throw new Error(\n \"ModelCandidate match reasonCodes must include every failed hard constraint.\",\n );\n }\n const provenance = createModelProvenance(record.provenance);\n if (provenance.contentHash !== processingManifest.converter.sourceContentHash) {\n throw new Error(\"ModelCandidate provenance contentHash must match converter sourceContentHash.\");\n }\n const rights = createModelRightsAssessment(record.rights);\n if (\n rights.sourceId !== provenance.sourceId\n || rights.sourceAssetId !== provenance.sourceAssetId\n || rights.sourceContentHash !== provenance.contentHash\n ) {\n throw new Error(\"ModelCandidate rights decision must bind the exact provenance source and content hash.\");\n }\n if (processingManifest.fidelityGate.outcome === \"low-only\") {\n if (\n match.assurance === \"high\"\n || !match.reasonCodes.includes(\"fidelity-low-only\")\n || match.fidelityWarnings.length === 0\n ) {\n throw new Error(\"ModelCandidate low-only fidelity must cap assurance at low and include fidelity evidence.\");\n }\n }\n if (\n processingManifest.fidelityGate.outcome === \"blocked\"\n && !match.reasonCodes.includes(\"fidelity-blocked\")\n ) {\n throw new Error(\"ModelCandidate blocked fidelity must be recorded in match reasonCodes.\");\n }\n const views = createConfirmationViews(record.views, resolutionId, candidateId);\n const renderEvidence = createRenderEvidence(record.renderEvidence, processingManifest, views);\n const hardGates = createCandidateHardGates(record.hardGates, provenance, processingManifest);\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n resolutionId,\n candidateId,\n assetRef,\n match,\n provenance,\n rights,\n technicalProfile,\n processingManifest,\n views,\n renderEvidence,\n hardGates,\n confirmationToken: record.confirmationToken,\n confirmationRequired: true,\n });\n}\n\n/** Return whether a candidate may enter mandatory human confirmation. */\nexport function isModelCandidateConfirmable(candidate: ModelCandidate): boolean {\n const blockingEvidence = [\n ...candidate.processingManifest.converter.diagnostics,\n ...candidate.processingManifest.converter.losses,\n ].some((evidence) => evidence.severity === \"blocking\");\n return candidate.confirmationRequired\n && candidate.match.hardConstraintPass\n && candidate.match.assurance !== \"none\"\n && (candidate.rights.status === \"allowed\" || candidate.rights.status === \"attribution-required\")\n && !blockingEvidence\n && candidate.processingManifest.fidelityGate.outcome !== \"blocked\"\n && candidate.hardGates.length === MODEL_CANDIDATE_HARD_GATE_KINDS.length\n && candidate.hardGates.every((gate) => gate.outcome === \"passed\")\n && candidate.views.length === MODEL_CONFIRMATION_VIEW_KINDS.length;\n}\n\n/** Validate a requester confirmation against one exact candidate and resolution. */\nexport function createModelCandidateConfirmation(\n input: unknown,\n expectedCandidate: ModelCandidate,\n expectedResolutionId: string,\n): ModelCandidateConfirmation {\n const record = assertRecord(input, \"ModelCandidateConfirmation\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"confirmationId\",\n \"resolutionId\",\n \"candidateId\",\n \"confirmationToken\",\n \"viewSha256s\",\n \"confirmedBy\",\n \"confirmedAt\",\n \"semanticRiskAccepted\",\n ], \"ModelCandidateConfirmation\");\n assertContractVersion(record, \"ModelCandidateConfirmation\");\n const candidate = createModelCandidate(expectedCandidate);\n const resolutionId = requiredModelPathSegment(\n expectedResolutionId,\n \"ModelCandidateConfirmation expected resolutionId\",\n );\n if (candidate.resolutionId !== resolutionId) {\n throw new Error(\n \"ModelCandidateConfirmation expected candidate must belong to the expected resolutionId.\",\n );\n }\n if (record.resolutionId !== resolutionId) {\n throw new Error(\"ModelCandidateConfirmation.resolutionId must match the expected resolutionId.\");\n }\n if (record.candidateId !== candidate.candidateId) {\n throw new Error(\"ModelCandidateConfirmation.candidateId must match the confirmed candidate.\");\n }\n if (\n typeof record.confirmationToken !== \"string\"\n || !CONFIRMATION_TOKEN_PATTERN.test(record.confirmationToken)\n || record.confirmationToken !== candidate.confirmationToken\n ) {\n throw new Error(\"ModelCandidateConfirmation.confirmationToken must match the signed candidate token.\");\n }\n if (!Array.isArray(record.viewSha256s) || record.viewSha256s.length !== 4) {\n throw new Error(\"ModelCandidateConfirmation.viewSha256s must contain the ordered four candidate view hashes.\");\n }\n const viewSha256s = record.viewSha256s.map((value, index) =>\n requiredSha256(value, `ModelCandidateConfirmation.viewSha256s[${index}]`));\n const expectedHashes = candidate.views.map((view) => view.sha256);\n if (viewSha256s.some((digest, index) => digest !== expectedHashes[index])) {\n throw new Error(\"ModelCandidateConfirmation view hashes must match the ordered candidate views.\");\n }\n if (!isModelCandidateConfirmable(candidate)) {\n throw new Error(\"ModelCandidateConfirmation candidate is not confirmable because a hard review gate is blocking.\");\n }\n const semanticRiskAccepted = requiredBoolean(\n record.semanticRiskAccepted,\n \"ModelCandidateConfirmation.semanticRiskAccepted\",\n );\n if (candidate.match.assurance === \"low\" && !semanticRiskAccepted) {\n throw new Error(\"ModelCandidateConfirmation low assurance requires explicit semantic risk acceptance.\");\n }\n if (candidate.match.assurance === \"high\" && semanticRiskAccepted) {\n throw new Error(\"ModelCandidateConfirmation high assurance must not record a semantic risk override.\");\n }\n const confirmedBy = requiredString(record.confirmedBy, \"ModelCandidateConfirmation.confirmedBy\", 256);\n assertNoDirectUrl(confirmedBy, \"ModelCandidateConfirmation.confirmedBy\");\n const confirmedAt = requiredTimestamp(\n record.confirmedAt,\n \"ModelCandidateConfirmation.confirmedAt\",\n );\n const latestEvidenceTime = Math.max(\n Date.parse(candidate.provenance.capturedAt),\n Date.parse(candidate.rights.reviewedAt),\n Date.parse(candidate.processingManifest.processedAt),\n Date.parse(candidate.processingManifest.fidelityGate.evaluatedAt),\n Date.parse(candidate.renderEvidence.renderedAt),\n ...candidate.hardGates.map((gate) => Date.parse(gate.evaluatedAt)),\n );\n if (Date.parse(confirmedAt) < latestEvidenceTime) {\n throw new Error(\n \"ModelCandidateConfirmation.confirmedAt must not precede the candidate evidence required for confirmation.\",\n );\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n confirmationId: requiredToken(record.confirmationId, \"ModelCandidateConfirmation.confirmationId\"),\n resolutionId,\n candidateId: candidate.candidateId,\n confirmationToken: candidate.confirmationToken,\n viewSha256s: [viewSha256s[0]!, viewSha256s[1]!, viewSha256s[2]!, viewSha256s[3]!],\n confirmedBy,\n confirmedAt,\n semanticRiskAccepted,\n });\n}\n\n/** Validate and freeze a public-safe processing resource reference. */\nexport function createModelResourceRef(input: unknown): ModelResourceRef {\n const record = assertRecord(input, \"ModelResourceRef\");\n assertAllowedKeys(record, [\"uri\", \"byteLength\", \"sha256\", \"contentType\"], \"ModelResourceRef\");\n const contentType = requiredString(record.contentType, \"ModelResourceRef.contentType\", 128);\n if (!CONTENT_TYPE_PATTERN.test(contentType)) {\n throw new Error(\"ModelResourceRef.contentType must be a valid media type.\");\n }\n return deepFreeze({\n uri: assertModelUri(record.uri, \"ModelResourceRef.uri\"),\n byteLength: requiredInteger(record.byteLength, \"ModelResourceRef.byteLength\", 1, Number.MAX_SAFE_INTEGER),\n sha256: requiredSha256(record.sha256, \"ModelResourceRef.sha256\"),\n contentType,\n });\n}\n\nfunction createLodRecord(value: unknown, index: number): ModelLodRecord {\n const fieldName = `ModelProcessingManifest.lods[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"level\", \"resource\", \"triangleCount\", \"geometricErrorMetres\"], fieldName);\n const resource = createModelResourceRef(record.resource);\n if (resource.contentType !== \"model/gltf-binary\") {\n throw new Error(`${fieldName}.resource.contentType must be model/gltf-binary for canonical GLB output.`);\n }\n return {\n level: requiredInteger(record.level, `${fieldName}.level`, 0, 3) as ModelLodLevel,\n resource,\n triangleCount: requiredInteger(record.triangleCount, `${fieldName}.triangleCount`, 1, 1_000_000_000),\n geometricErrorMetres: requiredFiniteNumber(\n record.geometricErrorMetres,\n `${fieldName}.geometricErrorMetres`,\n 0,\n 1_000_000,\n ),\n };\n}\n\nfunction createCollisionRecord(value: unknown): ModelCollisionRecord {\n const record = assertRecord(value, \"ModelProcessingManifest.collision\");\n assertAllowedKeys(record, [\"kind\", \"resource\"], \"ModelProcessingManifest.collision\");\n const kind = requiredEnum(\n record.kind,\n [\"none\", \"box\", \"convex-hull\", \"triangle-mesh\", \"compound\"],\n \"ModelProcessingManifest.collision.kind\",\n );\n if (kind === \"none\") {\n if (record.resource !== undefined) {\n throw new Error(\"ModelProcessingManifest collision kind none must not include a resource.\");\n }\n return { kind };\n }\n if (record.resource === undefined) {\n throw new Error(\"ModelProcessingManifest non-empty collision kinds require a resource.\");\n }\n const resource = createModelResourceRef(record.resource);\n if (resource.contentType !== \"model/gltf-binary\") {\n throw new Error(\"ModelProcessingManifest collision resources must be model/gltf-binary GLBs.\");\n }\n return { kind, resource };\n}\n\nfunction createTransform(value: unknown, fieldName: string): ModelTransform {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"translationMetres\", \"rotationQuaternion\", \"scale\"], fieldName);\n const translationMetres = requiredVector3(record.translationMetres, `${fieldName}.translationMetres`);\n if (!Array.isArray(record.rotationQuaternion) || record.rotationQuaternion.length !== 4) {\n throw new Error(`${fieldName}.rotationQuaternion must contain exactly four numbers.`);\n }\n const rotationQuaternion: ModelQuaternion = [\n requiredFiniteNumber(record.rotationQuaternion[0], `${fieldName}.rotationQuaternion[0]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[1], `${fieldName}.rotationQuaternion[1]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[2], `${fieldName}.rotationQuaternion[2]`, -1, 1),\n requiredFiniteNumber(record.rotationQuaternion[3], `${fieldName}.rotationQuaternion[3]`, -1, 1),\n ];\n const magnitude = Math.hypot(...rotationQuaternion);\n if (Math.abs(magnitude - 1) > 1e-4) {\n throw new Error(`${fieldName}.rotationQuaternion must be normalized.`);\n }\n return {\n translationMetres,\n rotationQuaternion,\n scale: requiredVector3(record.scale, `${fieldName}.scale`, true),\n };\n}\n\nfunction createAssemblyChildAssetRef(\n value: unknown,\n resolutionId: string,\n candidateId: string,\n fieldName: string,\n): ModelAssemblyChildAssetRef {\n const record = assertRecord(value, fieldName);\n if (record.disposition !== \"staged-derived\") {\n const catalogRef = createModelAssetRef(value);\n if (catalogRef.kind !== \"leaf\") {\n throw new Error(\"ModelProcessingManifest v1 assembly child assetRef values must be leaf assets.\");\n }\n return catalogRef;\n }\n assertAllowedKeys(record, [\n \"disposition\",\n \"derivedId\",\n \"kind\",\n \"contentHash\",\n \"processingManifestUri\",\n ], fieldName);\n if (record.kind !== \"leaf\") {\n throw new Error(\"ModelProcessingManifest staged-derived child assetRef kind must be leaf.\");\n }\n const derivedId = requiredModelPathSegment(record.derivedId, `${fieldName}.derivedId`);\n const processingManifestUri = assertModelUri(\n record.processingManifestUri,\n `${fieldName}.processingManifestUri`,\n );\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/children/${derivedId}/manifest`;\n if (processingManifestUri !== expectedUri) {\n throw new Error(`${fieldName}.processingManifestUri must match the staged child identity.`);\n }\n return {\n disposition: \"staged-derived\",\n derivedId,\n kind: \"leaf\",\n contentHash: requiredSha256(record.contentHash, `${fieldName}.contentHash`),\n processingManifestUri,\n };\n}\n\nfunction createAssemblyChild(\n value: unknown,\n index: number,\n resolutionId: string,\n candidateId: string,\n): ModelAssemblyChild {\n const fieldName = `ModelProcessingManifest.children[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"instanceId\", \"parentInstanceId\", \"assetRef\", \"transform\"], fieldName);\n const instanceId = requiredToken(record.instanceId, `${fieldName}.instanceId`);\n const parentInstanceId = record.parentInstanceId === undefined\n ? undefined\n : requiredToken(record.parentInstanceId, `${fieldName}.parentInstanceId`);\n const childAssetRef = createAssemblyChildAssetRef(\n record.assetRef,\n resolutionId,\n candidateId,\n `${fieldName}.assetRef`,\n );\n return {\n instanceId,\n ...(parentInstanceId === undefined ? {} : { parentInstanceId }),\n assetRef: childAssetRef,\n transform: createTransform(record.transform, `${fieldName}.transform`),\n };\n}\n\nfunction createDiagnostic(\n value: unknown,\n fieldName: string,\n): ModelConverterDiagnostic {\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"severity\", \"code\", \"message\"], fieldName);\n return {\n severity: requiredEnum(record.severity, [\"info\", \"warning\", \"blocking\"], `${fieldName}.severity`),\n code: requiredToken(record.code, `${fieldName}.code`),\n message: requiredString(record.message, `${fieldName}.message`, 1024),\n };\n}\n\nfunction createConverterEvidence(value: unknown): ModelConverterEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.converter\");\n assertAllowedKeys(record, [\n \"id\",\n \"version\",\n \"sourceFormat\",\n \"targetFormat\",\n \"sourceContentHash\",\n \"outputContentHash\",\n \"diagnostics\",\n \"losses\",\n ], \"ModelProcessingManifest.converter\");\n if (!Array.isArray(record.diagnostics) || record.diagnostics.length > 100) {\n throw new Error(\"ModelProcessingManifest.converter.diagnostics must be a bounded array.\");\n }\n if (!Array.isArray(record.losses) || record.losses.length > 100) {\n throw new Error(\"ModelProcessingManifest.converter.losses must be a bounded array.\");\n }\n return {\n id: requiredToken(record.id, \"ModelProcessingManifest.converter.id\"),\n version: assetVersion(record.version, \"ModelProcessingManifest.converter.version\"),\n sourceFormat: requiredToken(record.sourceFormat, \"ModelProcessingManifest.converter.sourceFormat\"),\n targetFormat: requiredToken(record.targetFormat, \"ModelProcessingManifest.converter.targetFormat\"),\n sourceContentHash: requiredSha256(record.sourceContentHash, \"ModelProcessingManifest.converter.sourceContentHash\"),\n outputContentHash: requiredSha256(record.outputContentHash, \"ModelProcessingManifest.converter.outputContentHash\"),\n diagnostics: record.diagnostics.map((item, index) =>\n createDiagnostic(item, `ModelProcessingManifest.converter.diagnostics[${index}]`)),\n losses: record.losses.map((item, index) =>\n createDiagnostic(item, `ModelProcessingManifest.converter.losses[${index}]`)),\n };\n}\n\nfunction createFidelityEvidence(value: unknown, index: number): ModelFidelityEvidence {\n const fieldName = `ModelProcessingManifest.fidelityEvidence[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\"aspect\", \"outcome\", \"message\", \"evidenceResource\"], fieldName);\n const evidenceResource = record.evidenceResource === undefined\n ? undefined\n : createModelResourceRef(record.evidenceResource);\n return {\n aspect: requiredEnum(\n record.aspect,\n [\"geometry\", \"materials\", \"textures\", \"rigging\", \"animation\", \"metadata\"],\n `${fieldName}.aspect`,\n ),\n outcome: requiredEnum(record.outcome, [\"preserved\", \"approximated\", \"lost\"], `${fieldName}.outcome`),\n message: requiredString(record.message, `${fieldName}.message`, 1024),\n ...(evidenceResource === undefined ? {} : { evidenceResource }),\n };\n}\n\nfunction createCollisionPolicyEvidence(\n value: unknown,\n collision: ModelCollisionRecord,\n): ModelCollisionPolicyEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.collisionPolicy\");\n assertAllowedKeys(record, [\n \"profileId\",\n \"profileVersion\",\n \"disposition\",\n \"category\",\n \"decisionToken\",\n ], \"ModelProcessingManifest.collisionPolicy\");\n const disposition = requiredEnum(\n record.disposition,\n [\"proxy-required\", \"none-allowed\"] as const,\n \"ModelProcessingManifest.collisionPolicy.disposition\",\n );\n if (\n (collision.kind === \"none\" && disposition !== \"none-allowed\")\n || (collision.kind !== \"none\" && disposition !== \"proxy-required\")\n ) {\n throw new Error(\"ModelProcessingManifest collisionPolicy must explicitly authorize collision none or require a proxy.\");\n }\n return {\n profileId: requiredToken(record.profileId, \"ModelProcessingManifest.collisionPolicy.profileId\"),\n profileVersion: assetVersion(\n record.profileVersion,\n \"ModelProcessingManifest.collisionPolicy.profileVersion\",\n ),\n disposition,\n category: requiredToken(record.category, \"ModelProcessingManifest.collisionPolicy.category\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelProcessingManifest.collisionPolicy.decisionToken\",\n ),\n };\n}\n\nfunction createFidelityGateEvidence(\n value: unknown,\n fidelityEvidence: readonly ModelFidelityEvidence[],\n converter: ModelConverterEvidence,\n): ModelFidelityGateEvidence {\n const record = assertRecord(value, \"ModelProcessingManifest.fidelityGate\");\n assertAllowedKeys(record, [\n \"profileId\",\n \"profileVersion\",\n \"outcome\",\n \"requiredAspects\",\n \"evaluatedAt\",\n \"decisionToken\",\n ], \"ModelProcessingManifest.fidelityGate\");\n const expectedAspects = [\"geometry\", \"materials\", \"textures\"] as const;\n if (\n !Array.isArray(record.requiredAspects)\n || record.requiredAspects.length !== expectedAspects.length\n || record.requiredAspects.some((aspect, index) => aspect !== expectedAspects[index])\n ) {\n throw new Error(\"ModelProcessingManifest.fidelityGate.requiredAspects must be geometry, materials, textures.\");\n }\n const byAspect = new Map(fidelityEvidence.map((evidence) => [evidence.aspect, evidence]));\n if (expectedAspects.some((aspect) => !byAspect.has(aspect))) {\n throw new Error(\"ModelProcessingManifest fidelityEvidence must cover geometry, materials, and textures.\");\n }\n const hasBlockingConverterEvidence = [\n ...converter.diagnostics,\n ...converter.losses,\n ].some((evidence) => evidence.severity === \"blocking\");\n const geometryLost = byAspect.get(\"geometry\")?.outcome === \"lost\";\n const hasWarningLoss = converter.losses.some((loss) => loss.severity === \"warning\");\n const hasUnresolvedFidelity = expectedAspects.some(\n (aspect) => byAspect.get(aspect)?.outcome !== \"preserved\",\n ) || hasWarningLoss;\n const derivedOutcome: ModelFidelityGateEvidence[\"outcome\"] =\n hasBlockingConverterEvidence || geometryLost\n ? \"blocked\"\n : hasUnresolvedFidelity\n ? \"low-only\"\n : \"passed\";\n const outcome = requiredEnum(\n record.outcome,\n [\"passed\", \"low-only\", \"blocked\"] as const,\n \"ModelProcessingManifest.fidelityGate.outcome\",\n );\n if (outcome !== derivedOutcome) {\n throw new Error(\"ModelProcessingManifest fidelityGate outcome must match converter and fidelity evidence.\");\n }\n return {\n profileId: requiredToken(record.profileId, \"ModelProcessingManifest.fidelityGate.profileId\"),\n profileVersion: assetVersion(record.profileVersion, \"ModelProcessingManifest.fidelityGate.profileVersion\"),\n outcome,\n requiredAspects: expectedAspects,\n evaluatedAt: requiredTimestamp(record.evaluatedAt, \"ModelProcessingManifest.fidelityGate.evaluatedAt\"),\n decisionToken: requiredAttestationToken(\n record.decisionToken,\n \"ModelProcessingManifest.fidelityGate.decisionToken\",\n ),\n };\n}\n\nfunction assertCoordinateSystem(value: unknown): void {\n if (value === undefined) {\n return;\n }\n const record = assertRecord(value, \"ModelProcessingManifest.coordinateSystem\");\n assertAllowedKeys(record, [\n \"unit\",\n \"upAxis\",\n \"forwardAxis\",\n \"origin\",\n \"outwardFaceWinding\",\n ], \"ModelProcessingManifest.coordinateSystem\");\n if (\n record.unit !== CANONICAL_MODEL_COORDINATE_SYSTEM.unit\n || record.upAxis !== CANONICAL_MODEL_COORDINATE_SYSTEM.upAxis\n || record.forwardAxis !== CANONICAL_MODEL_COORDINATE_SYSTEM.forwardAxis\n || record.origin !== CANONICAL_MODEL_COORDINATE_SYSTEM.origin\n || record.outwardFaceWinding !== CANONICAL_MODEL_COORDINATE_SYSTEM.outwardFaceWinding\n ) {\n throw new Error(\n \"ModelProcessingManifest.coordinateSystem must be metres, Y-up, -Z forward, floor-centred, and counter-clockwise outward.\",\n );\n }\n}\n\nfunction assertCandidateResourceScope(\n uri: string,\n resolutionId: string,\n candidateId: string,\n fieldName: string,\n): void {\n const expectedPrefix = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/`;\n if (!uri.startsWith(expectedPrefix)) {\n throw new Error(`${fieldName} must be scoped to resolution ${resolutionId} and candidate ${candidateId}.`);\n }\n}\n\nfunction assertAssemblyHierarchy(children: readonly ModelAssemblyChild[]): void {\n const byId = new Map(children.map((child) => [child.instanceId, child]));\n for (const child of children) {\n if (child.parentInstanceId === undefined) {\n continue;\n }\n if (child.parentInstanceId === child.instanceId) {\n throw new Error(\"ModelProcessingManifest assembly children must not parent themselves.\");\n }\n if (!byId.has(child.parentInstanceId)) {\n throw new Error(\"ModelProcessingManifest assembly parentInstanceId values must reference existing children.\");\n }\n }\n const maximumDepth = 16;\n for (const child of children) {\n const visited = new Set<string>();\n let current: ModelAssemblyChild | undefined = child;\n let depth = 0;\n while (current?.parentInstanceId !== undefined) {\n if (visited.has(current.instanceId)) {\n throw new Error(\"ModelProcessingManifest assembly hierarchy must not contain cycles.\");\n }\n visited.add(current.instanceId);\n depth += 1;\n if (depth > maximumDepth) {\n throw new Error(`ModelProcessingManifest assembly hierarchy depth must not exceed ${maximumDepth}.`);\n }\n current = byId.get(current.parentInstanceId);\n }\n }\n}\n\n/** Validate and deeply freeze a canonical processing manifest. */\nexport function createModelProcessingManifest(input: unknown): ModelProcessingManifest {\n const record = assertRecord(input, \"ModelProcessingManifest\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"manifestId\",\n \"resolutionId\",\n \"candidateId\",\n \"kind\",\n \"contentHash\",\n \"closureHash\",\n \"coordinateSystem\",\n \"technicalProfile\",\n \"lods\",\n \"collision\",\n \"collisionPolicy\",\n \"children\",\n \"converter\",\n \"fidelityEvidence\",\n \"fidelityGate\",\n \"processedAt\",\n ], \"ModelProcessingManifest\");\n assertContractVersion(record, \"ModelProcessingManifest\");\n const resolutionId = requiredModelPathSegment(\n record.resolutionId,\n \"ModelProcessingManifest.resolutionId\",\n );\n const candidateId = requiredModelPathSegment(\n record.candidateId,\n \"ModelProcessingManifest.candidateId\",\n );\n assertCoordinateSystem(record.coordinateSystem);\n const kind = requiredEnum(record.kind, MODEL_ASSET_KINDS, \"ModelProcessingManifest.kind\");\n const contentHash = requiredSha256(record.contentHash, \"ModelProcessingManifest.contentHash\");\n const closureHash = requiredSha256(record.closureHash, \"ModelProcessingManifest.closureHash\");\n if (kind === \"leaf\" && closureHash !== contentHash) {\n throw new Error(\"ModelProcessingManifest leaf closureHash must match contentHash.\");\n }\n const technicalProfile = createModelTechnicalProfile(record.technicalProfile);\n const [minimumX, minimumY, minimumZ] = technicalProfile.boundsMetres.min;\n const [maximumX, , maximumZ] = technicalProfile.boundsMetres.max;\n if (\n Math.abs(minimumY) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n || Math.abs((minimumX + maximumX) / 2) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n || Math.abs((minimumZ + maximumZ) / 2) > MODEL_CANONICAL_ORIGIN_TOLERANCE_METRES\n ) {\n throw new Error(\n \"ModelProcessingManifest floor-centred origin requires minY and the X/Z bounds centre to be zero.\",\n );\n }\n if (!Array.isArray(record.lods) || record.lods.length < 1 || record.lods.length > 4) {\n throw new Error(\"ModelProcessingManifest.lods must contain one to four adaptive levels beginning with LOD0.\");\n }\n const lods = record.lods.map(createLodRecord);\n for (const [index, lod] of lods.entries()) {\n if (lod.level !== index) {\n throw new Error(\"ModelProcessingManifest LOD levels must be contiguous and begin with LOD0.\");\n }\n if (index > 0 && lod.triangleCount > lods[index - 1]!.triangleCount) {\n throw new Error(\"ModelProcessingManifest LOD triangle counts must be monotonic non-increasing.\");\n }\n if (index > 0 && lod.geometricErrorMetres < lods[index - 1]!.geometricErrorMetres) {\n throw new Error(\"ModelProcessingManifest LOD geometric error must be monotonic non-decreasing.\");\n }\n if (index === 0 && lod.geometricErrorMetres !== 0) {\n throw new Error(\"ModelProcessingManifest LOD0 geometric error must be zero.\");\n }\n if (index > 0 && lod.triangleCount > Math.floor(lods[index - 1]!.triangleCount * 0.7)) {\n throw new Error(\"ModelProcessingManifest retained LODs must reduce the preceding level by at least 30%.\");\n }\n if (index > 0 && lod.triangleCount < 512) {\n throw new Error(\"ModelProcessingManifest retained LODs must contain at least 512 triangles.\");\n }\n }\n if (new Set(lods.map((lod) => lod.resource.uri)).size !== lods.length) {\n throw new Error(\"ModelProcessingManifest LOD resources must be unique.\");\n }\n if (new Set(lods.map((lod) => lod.resource.sha256)).size !== lods.length) {\n throw new Error(\"ModelProcessingManifest LOD resource sha256 hashes must be unique.\");\n }\n if (technicalProfile.lodCount !== lods.length) {\n throw new Error(\"ModelProcessingManifest technicalProfile.lodCount must match lods.\");\n }\n if (technicalProfile.triangleCount !== lods[0]!.triangleCount) {\n throw new Error(\"ModelProcessingManifest technicalProfile.triangleCount must match LOD0.\");\n }\n if (\n lods[0]!.resource.sha256 !== contentHash\n || lods[0]!.resource.byteLength !== technicalProfile.byteLength\n ) {\n throw new Error(\n \"ModelProcessingManifest LOD0 sha256/byteLength must match contentHash and technicalProfile.byteLength.\",\n );\n }\n for (const [index, lod] of lods.entries()) {\n assertCandidateResourceScope(\n lod.resource.uri,\n resolutionId,\n candidateId,\n `ModelProcessingManifest.lods[${index}].resource`,\n );\n }\n const collision = createCollisionRecord(record.collision);\n const collisionPolicy = createCollisionPolicyEvidence(record.collisionPolicy, collision);\n if (technicalProfile.hasCollision !== (collision.kind !== \"none\")) {\n throw new Error(\"ModelProcessingManifest technicalProfile.hasCollision must match collision evidence.\");\n }\n if (\n collision.resource !== undefined\n && lods.some((lod) =>\n lod.resource.uri === collision.resource?.uri\n || lod.resource.sha256 === collision.resource?.sha256)\n ) {\n throw new Error(\"ModelProcessingManifest collision evidence must be separate and distinct from LOD resources.\");\n }\n if (collision.resource !== undefined) {\n assertCandidateResourceScope(\n collision.resource.uri,\n resolutionId,\n candidateId,\n \"ModelProcessingManifest.collision.resource\",\n );\n }\n if (!Array.isArray(record.children) || record.children.length > 256) {\n throw new Error(\"ModelProcessingManifest.children must be a bounded array.\");\n }\n const children = record.children.map((child, index) =>\n createAssemblyChild(child, index, resolutionId, candidateId));\n if (kind === \"leaf\" && children.length !== 0) {\n throw new Error(\"ModelProcessingManifest leaf models must not contain assembly children.\");\n }\n if (kind === \"leaf\" && technicalProfile.partitionCount !== 1) {\n throw new Error(\"ModelProcessingManifest leaf models must have exactly one partition.\");\n }\n if (kind === \"assembly\" && children.length === 0) {\n throw new Error(\"ModelProcessingManifest assembly models require at least one child.\");\n }\n if (new Set(children.map((child) => child.instanceId)).size !== children.length) {\n throw new Error(\"ModelProcessingManifest assembly instanceId values must be unique.\");\n }\n assertAssemblyHierarchy(children);\n const converter = createConverterEvidence(record.converter);\n if (converter.targetFormat !== \"glb\") {\n throw new Error(\"ModelProcessingManifest converter.targetFormat must be glb.\");\n }\n if (converter.outputContentHash !== contentHash) {\n throw new Error(\"ModelProcessingManifest converter outputContentHash must match contentHash.\");\n }\n if (!Array.isArray(record.fidelityEvidence) || record.fidelityEvidence.length > 100) {\n throw new Error(\"ModelProcessingManifest.fidelityEvidence must be a bounded array.\");\n }\n const fidelityEvidence = record.fidelityEvidence.map(createFidelityEvidence);\n if (new Set(fidelityEvidence.map((evidence) => evidence.aspect)).size !== fidelityEvidence.length) {\n throw new Error(\"ModelProcessingManifest fidelity evidence aspects must be unique.\");\n }\n for (const [index, evidence] of fidelityEvidence.entries()) {\n if (evidence.evidenceResource !== undefined) {\n assertCandidateResourceScope(\n evidence.evidenceResource.uri,\n resolutionId,\n candidateId,\n `ModelProcessingManifest.fidelityEvidence[${index}].evidenceResource`,\n );\n }\n }\n const fidelityGate = createFidelityGateEvidence(record.fidelityGate, fidelityEvidence, converter);\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n manifestId: requiredToken(record.manifestId, \"ModelProcessingManifest.manifestId\"),\n resolutionId,\n candidateId,\n kind,\n contentHash,\n closureHash,\n coordinateSystem: CANONICAL_MODEL_COORDINATE_SYSTEM,\n technicalProfile,\n lods,\n collision,\n collisionPolicy,\n children,\n converter,\n fidelityEvidence,\n fidelityGate,\n processedAt: requiredTimestamp(record.processedAt, \"ModelProcessingManifest.processedAt\"),\n });\n}\n\nfunction modelCandidateEquivalent(left: ModelCandidate, right: ModelCandidate): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction finalAssetMatchesCandidate(\n finalAssetRef: ModelAssetRef,\n candidate: ModelCandidate,\n): boolean {\n if (\n finalAssetRef.kind !== candidate.assetRef.kind\n || finalAssetRef.contentHash !== candidate.assetRef.contentHash\n ) {\n return false;\n }\n if (candidate.assetRef.disposition === \"proposed\") {\n return true;\n }\n return finalAssetRef.assetId === candidate.assetRef.asset.assetId\n && finalAssetRef.version === candidate.assetRef.asset.version\n && finalAssetRef.runtimeManifestUri === candidate.assetRef.asset.runtimeManifestUri;\n}\n\nfunction createModelPromotionReceipt(\n input: unknown,\n resolutionId: string,\n candidate: ModelCandidate,\n confirmation: ModelCandidateConfirmation,\n finalAssetRef: ModelAssetRef,\n): ModelPromotionReceipt {\n if (candidate.assetRef.disposition !== \"proposed\") {\n throw new Error(\"ModelPromotionReceipt is only valid for a staged proposed candidate.\");\n }\n const record = assertRecord(input, \"ModelPromotionReceipt\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"promotionId\",\n \"resolutionId\",\n \"candidateId\",\n \"proposalId\",\n \"confirmationId\",\n \"processingManifestId\",\n \"processingContentHash\",\n \"closureHash\",\n \"finalAssetRef\",\n \"promotedAt\",\n \"publicationToken\",\n ], \"ModelPromotionReceipt\");\n assertContractVersion(record, \"ModelPromotionReceipt\");\n if (\n record.resolutionId !== resolutionId\n || record.candidateId !== candidate.candidateId\n || record.proposalId !== candidate.assetRef.proposalId\n || record.confirmationId !== confirmation.confirmationId\n || record.processingManifestId !== candidate.processingManifest.manifestId\n || record.processingContentHash !== candidate.processingManifest.contentHash\n || record.closureHash !== candidate.processingManifest.closureHash\n ) {\n throw new Error(\"ModelPromotionReceipt must bind the exact proposal, confirmation, manifest, and closure.\");\n }\n const receiptAssetRef = createModelAssetRef(record.finalAssetRef);\n if (JSON.stringify(receiptAssetRef) !== JSON.stringify(finalAssetRef)) {\n throw new Error(\"ModelPromotionReceipt.finalAssetRef must match the completed finalAssetRef.\");\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n promotionId: requiredToken(record.promotionId, \"ModelPromotionReceipt.promotionId\"),\n resolutionId,\n candidateId: candidate.candidateId,\n proposalId: candidate.assetRef.proposalId,\n confirmationId: confirmation.confirmationId,\n processingManifestId: candidate.processingManifest.manifestId,\n processingContentHash: candidate.processingManifest.contentHash,\n closureHash: candidate.processingManifest.closureHash,\n finalAssetRef: receiptAssetRef,\n promotedAt: requiredTimestamp(record.promotedAt, \"ModelPromotionReceipt.promotedAt\"),\n publicationToken: requiredAttestationToken(\n record.publicationToken,\n \"ModelPromotionReceipt.publicationToken\",\n ),\n });\n}\n\nfunction numbersApproximatelyEqual(left: number, right: number): boolean {\n return Math.abs(left - right) <= Math.max(1e-6, Math.abs(left) * 1e-6);\n}\n\nfunction evaluateNormalizedModelHardConstraints(\n request: ModelRequestSpec,\n profile: ModelTechnicalProfile,\n): ModelHardConstraintEvaluation {\n const constraints = request.hardConstraints;\n const reasonCodes: string[] = [];\n if (\n constraints.boundsMetres !== undefined\n && (\n constraints.boundsMetres.min.some((axis, index) =>\n !numbersApproximatelyEqual(axis, profile.boundsMetres.min[index]!))\n || constraints.boundsMetres.max.some((axis, index) =>\n !numbersApproximatelyEqual(axis, profile.boundsMetres.max[index]!))\n )\n ) {\n reasonCodes.push(\"bounds-mismatch\");\n }\n if (\n constraints.dimensionsMetres !== undefined\n && ![\n [constraints.dimensionsMetres.width, profile.dimensionsMetres.width],\n [constraints.dimensionsMetres.height, profile.dimensionsMetres.height],\n [constraints.dimensionsMetres.depth, profile.dimensionsMetres.depth],\n ].every(([expected, actual]) => numbersApproximatelyEqual(expected!, actual!))\n ) {\n reasonCodes.push(\"dimensions-mismatch\");\n }\n if (constraints.maxTriangles !== undefined && profile.triangleCount > constraints.maxTriangles) {\n reasonCodes.push(\"triangle-budget-exceeded\");\n }\n if (constraints.maxBytes !== undefined && profile.byteLength > constraints.maxBytes) {\n reasonCodes.push(\"model-byte-budget-exceeded\");\n }\n if (\n constraints.maxTextureBytes !== undefined\n && profile.textureByteLength > constraints.maxTextureBytes\n ) {\n reasonCodes.push(\"texture-byte-budget-exceeded\");\n }\n if (\n constraints.maxTextureDimensionPx !== undefined\n && profile.maxTextureDimensionPx > constraints.maxTextureDimensionPx\n ) {\n reasonCodes.push(\"texture-dimension-budget-exceeded\");\n }\n if (\n constraints.maxPartitionCellMetres !== undefined\n && profile.partitionCellMetres > constraints.maxPartitionCellMetres\n ) {\n reasonCodes.push(\"partition-cell-budget-exceeded\");\n }\n if (\n (constraints.lod === \"required\" && profile.lodCount < 2)\n || (constraints.lod === \"forbidden\" && profile.lodCount !== 1)\n ) {\n reasonCodes.push(\"lod-policy-failed\");\n }\n if (\n (constraints.collision === \"required\" && !profile.hasCollision)\n || (constraints.collision === \"forbidden\" && profile.hasCollision)\n ) {\n reasonCodes.push(\"collision-policy-failed\");\n }\n if (\n (constraints.partition === \"single\" && profile.partitionCount !== 1)\n || (constraints.partition === \"required\" && profile.partitionCount < 2)\n ) {\n reasonCodes.push(\"partition-policy-failed\");\n }\n return deepFreeze({ pass: reasonCodes.length === 0, reasonCodes });\n}\n\n/**\n * Deterministically evaluate a normalized request against technical facts before\n * constructing a full candidate.\n */\nexport function evaluateModelHardConstraintsForProfile(\n requestInput: ModelRequestSpec,\n profileInput: ModelTechnicalProfile,\n): ModelHardConstraintEvaluation {\n const request = createModelRequestSpec(requestInput);\n const profile = createModelTechnicalProfile(profileInput);\n return evaluateNormalizedModelHardConstraints(request, profile);\n}\n\n/** Deterministically evaluate every normalized request hard constraint against a candidate. */\nexport function evaluateModelHardConstraints(\n requestInput: ModelRequestSpec,\n candidateInput: ModelCandidate,\n): ModelHardConstraintEvaluation {\n const request = createModelRequestSpec(requestInput);\n const candidate = createModelCandidate(candidateInput);\n return evaluateModelHardConstraintsForProfile(request, candidate.technicalProfile);\n}\n\n/** Return whether an unknown value is an exact resolution state. */\nexport function isModelResolutionState(value: unknown): value is ModelResolutionState {\n return typeof value === \"string\" && MODEL_RESOLUTION_STATES.includes(value as ModelResolutionState);\n}\n\n/** Validate and deeply freeze an asynchronous model-resolution record. */\nexport function createModelResolution(input: unknown): ModelResolution {\n const record = assertRecord(input, \"ModelResolution\");\n assertAllowedKeys(record, [\n \"contractVersion\",\n \"resolutionId\",\n \"request\",\n \"attempts\",\n \"state\",\n \"candidates\",\n \"bestCandidate\",\n \"confirmation\",\n \"promotionReceipt\",\n \"refinementQuestions\",\n \"finalAssetRef\",\n \"stateReasonCode\",\n \"createdAt\",\n \"updatedAt\",\n ], \"ModelResolution\");\n assertContractVersion(record, \"ModelResolution\");\n const resolutionId = requiredModelPathSegment(record.resolutionId, \"ModelResolution.resolutionId\");\n const request = createModelRequestSpec(record.request);\n const createdAt = requiredTimestamp(record.createdAt, \"ModelResolution.createdAt\");\n const updatedAt = requiredTimestamp(record.updatedAt, \"ModelResolution.updatedAt\");\n if (Date.parse(updatedAt) < Date.parse(createdAt)) {\n throw new Error(\"ModelResolution.updatedAt must not precede createdAt.\");\n }\n const state = requiredEnum(record.state, MODEL_RESOLUTION_STATES, \"ModelResolution.state\");\n if (!Array.isArray(record.candidates) || record.candidates.length > MAX_CANDIDATES) {\n throw new Error(`ModelResolution.candidates must contain at most ${MAX_CANDIDATES} items.`);\n }\n const candidates = record.candidates.map(createModelCandidate);\n if (new Set(candidates.map((candidate) => candidate.candidateId)).size !== candidates.length) {\n throw new Error(\"ModelResolution candidateId values must be unique.\");\n }\n if (new Set(candidates.map((candidate) => candidate.confirmationToken)).size !== candidates.length) {\n throw new Error(\"ModelResolution candidate confirmationToken values must be unique.\");\n }\n for (const candidate of candidates) {\n if (candidate.resolutionId !== resolutionId) {\n throw new Error(\"ModelResolution candidates must be scoped to the resolutionId.\");\n }\n if (JSON.stringify(candidate.match.request) !== JSON.stringify(request)) {\n throw new Error(\"ModelResolution candidate match assessments must bind the immutable request revision.\");\n }\n const evaluation = evaluateModelHardConstraints(request, candidate);\n if (candidate.match.hardConstraintPass !== evaluation.pass) {\n throw new Error(\"ModelResolution candidate hardConstraintPass must match deterministic evaluation.\");\n }\n if (evaluation.reasonCodes.some((reasonCode) => !candidate.match.reasonCodes.includes(reasonCode))) {\n throw new Error(\"ModelResolution candidate match reasonCodes must include every failed hard constraint.\");\n }\n const evidenceTimes = [\n candidate.provenance.capturedAt,\n candidate.rights.reviewedAt,\n candidate.processingManifest.processedAt,\n candidate.processingManifest.fidelityGate.evaluatedAt,\n candidate.renderEvidence.renderedAt,\n ...candidate.hardGates.map((gate) => gate.evaluatedAt),\n ];\n if (evidenceTimes.some((timestamp) => Date.parse(timestamp) > Date.parse(updatedAt))) {\n throw new Error(\"ModelResolution candidate evidence timestamps must not exceed updatedAt.\");\n }\n }\n let bestCandidate: ModelCandidate | undefined;\n if (record.bestCandidate !== undefined) {\n const requestedBest = createModelCandidate(record.bestCandidate);\n bestCandidate = candidates.find((candidate) => candidate.candidateId === requestedBest.candidateId);\n if (bestCandidate === undefined || !modelCandidateEquivalent(bestCandidate, requestedBest)) {\n throw new Error(\"ModelResolution.bestCandidate must exactly match a candidate.\");\n }\n }\n if ([\"awaiting-confirmation\", \"promoting\", \"completed\"].includes(state) && bestCandidate === undefined) {\n throw new Error(`ModelResolution ${state} state requires bestCandidate.`);\n }\n if (\n [\"awaiting-confirmation\", \"promoting\", \"completed\"].includes(state)\n && bestCandidate !== undefined\n && !isModelCandidateConfirmable(bestCandidate)\n ) {\n throw new Error(\n `ModelResolution ${state} bestCandidate must pass hard, assurance, rights, and view gates.`,\n );\n }\n let confirmation: ModelCandidateConfirmation | undefined;\n if (record.confirmation !== undefined) {\n if (bestCandidate === undefined) {\n throw new Error(\"ModelResolution confirmation requires bestCandidate.\");\n }\n confirmation = createModelCandidateConfirmation(record.confirmation, bestCandidate, resolutionId);\n if (\n Date.parse(confirmation.confirmedAt) < Date.parse(createdAt)\n || Date.parse(confirmation.confirmedAt) > Date.parse(updatedAt)\n ) {\n throw new Error(\"ModelResolution confirmation.confirmedAt must fall between createdAt and updatedAt.\");\n }\n }\n if ([\"promoting\", \"completed\"].includes(state) && confirmation === undefined) {\n throw new Error(`ModelResolution ${state} state requires confirmation evidence.`);\n }\n if (state === \"awaiting-confirmation\" && confirmation !== undefined) {\n throw new Error(\"ModelResolution awaiting-confirmation state must not already contain confirmation evidence.\");\n }\n if (\n confirmation !== undefined\n && ![\"promoting\", \"completed\", \"failed\", \"cancelled\"].includes(state)\n ) {\n throw new Error(`ModelResolution confirmation evidence is not allowed in ${state} state.`);\n }\n const refinementQuestions = record.refinementQuestions === undefined\n ? []\n : stringList(record.refinementQuestions, \"ModelResolution.refinementQuestions\", { maxItems: 3 });\n const stateReasonCode = record.stateReasonCode === undefined\n ? undefined\n : requiredToken(record.stateReasonCode, \"ModelResolution.stateReasonCode\");\n if (\n [\"failed\", \"cancelled\", \"unresolved\"].includes(state)\n && stateReasonCode === undefined\n ) {\n throw new Error(`ModelResolution ${state} state requires stateReasonCode.`);\n }\n if (\n state === \"awaiting-confirmation\"\n && bestCandidate?.match.assurance === \"low\"\n && refinementQuestions.length === 0\n ) {\n throw new Error(\"ModelResolution low-assurance bestCandidate requires refinementQuestions.\");\n }\n const finalAssetRef = record.finalAssetRef === undefined\n ? undefined\n : createModelAssetRef(record.finalAssetRef);\n if (state === \"completed\" && finalAssetRef === undefined) {\n throw new Error(\"ModelResolution completed state requires finalAssetRef.\");\n }\n if (state !== \"completed\" && finalAssetRef !== undefined) {\n throw new Error(\"ModelResolution finalAssetRef is only allowed for completed state.\");\n }\n if (\n finalAssetRef !== undefined\n && bestCandidate !== undefined\n && !finalAssetMatchesCandidate(finalAssetRef, bestCandidate)\n ) {\n throw new Error(\"ModelResolution finalAssetRef must match bestCandidate kind, hash, and immutable identity.\");\n }\n let promotionReceipt: ModelPromotionReceipt | undefined;\n if (record.promotionReceipt !== undefined) {\n if (\n state !== \"completed\"\n || bestCandidate === undefined\n || confirmation === undefined\n || finalAssetRef === undefined\n ) {\n throw new Error(\"ModelResolution promotionReceipt is only allowed for a completed staged promotion.\");\n }\n promotionReceipt = createModelPromotionReceipt(\n record.promotionReceipt,\n resolutionId,\n bestCandidate,\n confirmation,\n finalAssetRef,\n );\n if (\n Date.parse(promotionReceipt.promotedAt) < Date.parse(confirmation.confirmedAt)\n || Date.parse(promotionReceipt.promotedAt) > Date.parse(updatedAt)\n ) {\n throw new Error(\"ModelResolution promotionReceipt.promotedAt must follow confirmation and not exceed updatedAt.\");\n }\n }\n if (\n state === \"completed\"\n && bestCandidate?.assetRef.disposition === \"proposed\"\n && promotionReceipt === undefined\n ) {\n throw new Error(\"ModelResolution completed proposed candidates require a promotionReceipt.\");\n }\n if (bestCandidate?.assetRef.disposition === \"existing\" && promotionReceipt !== undefined) {\n throw new Error(\"ModelResolution existing catalog selections must not include a promotionReceipt.\");\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_CONTRACT_VERSION,\n resolutionId,\n request,\n attempts: requiredInteger(record.attempts, \"ModelResolution.attempts\", 1, MAX_ATTEMPTS),\n state,\n candidates,\n ...(bestCandidate === undefined ? {} : { bestCandidate }),\n ...(confirmation === undefined ? {} : { confirmation }),\n ...(promotionReceipt === undefined ? {} : { promotionReceipt }),\n refinementQuestions,\n ...(finalAssetRef === undefined ? {} : { finalAssetRef }),\n ...(stateReasonCode === undefined ? {} : { stateReasonCode }),\n createdAt,\n updatedAt,\n });\n}\n\nfunction createGeneratorSeed(value: unknown, fieldName: string): string {\n const seed = requiredString(value, fieldName, 128);\n if (seed.length < 8) {\n throw new Error(`${fieldName} must contain at least eight characters.`);\n }\n assertNoDirectUrl(seed, fieldName);\n return seed;\n}\n\n/** Validate and normalize an unknown generator request. */\nexport function createModelGeneratorRequest(input: unknown): ModelGeneratorRequest {\n const record = assertRecord(input, \"ModelGeneratorRequest\");\n assertAllowedKeys(record, [\n \"generationId\",\n \"request\",\n \"budgets\",\n \"seed\",\n \"deadline\",\n ], \"ModelGeneratorRequest\");\n const budgets = assertRecord(record.budgets, \"ModelGeneratorRequest.budgets\");\n assertAllowedKeys(budgets, [\n \"maxDurationMs\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n ], \"ModelGeneratorRequest.budgets\");\n const seed = createGeneratorSeed(record.seed, \"ModelGeneratorRequest.seed\");\n const maxBytes = requiredInteger(\n budgets.maxBytes,\n \"ModelGeneratorRequest budget maxBytes\",\n 1,\n 10_000_000_000,\n );\n const maxTextureBytes = requiredInteger(\n budgets.maxTextureBytes,\n \"ModelGeneratorRequest budget maxTextureBytes\",\n 1,\n 10_000_000_000,\n );\n if (maxTextureBytes > maxBytes) {\n throw new Error(\"ModelGeneratorRequest maxTextureBytes must not exceed maxBytes.\");\n }\n return deepFreeze({\n generationId: requiredModelPathSegment(record.generationId, \"ModelGeneratorRequest.generationId\"),\n request: createModelRequestSpec(record.request),\n budgets: {\n maxDurationMs: requiredInteger(budgets.maxDurationMs, \"ModelGeneratorRequest budget maxDurationMs\", 1, 300_000),\n maxTriangles: requiredInteger(budgets.maxTriangles, \"ModelGeneratorRequest budget maxTriangles\", 1, 10_000_000),\n maxBytes,\n maxTextureBytes,\n maxTextureDimensionPx: requiredInteger(budgets.maxTextureDimensionPx, \"ModelGeneratorRequest budget maxTextureDimensionPx\", 1, 32_768),\n },\n seed,\n deadline: requiredTimestamp(record.deadline, \"ModelGeneratorRequest.deadline\"),\n });\n}\n\nconst MODEL_GENERATOR_ARTIFACT_ROLES = [\n \"model-entrypoint\",\n \"model-dependency\",\n \"binary\",\n \"texture\",\n \"metadata\",\n] as const;\n\nconst MODEL_GENERATOR_BUDGET_NAMES = [\n \"maxDurationMs\",\n \"maxTriangles\",\n \"maxBytes\",\n \"maxTextureBytes\",\n \"maxTextureDimensionPx\",\n] as const;\n\nconst MODEL_GENERATOR_REASON_RETRYABILITY: Readonly<Record<string, boolean>> = Object.freeze({\n \"capacity-unavailable\": true,\n \"provider-unavailable\": true,\n \"authentication-required\": true,\n \"rate-limited\": true,\n \"unsupported-request\": false,\n \"provider-failed\": true,\n \"invalid-generator-output\": false,\n \"internal-failure\": true,\n \"caller-aborted\": false,\n \"deadline-exceeded\": true,\n superseded: false,\n \"service-shutdown\": true,\n});\n\nfunction assertGeneratorRetryability(reasonCode: string, retryable: boolean): void {\n if (MODEL_GENERATOR_REASON_RETRYABILITY[reasonCode] !== retryable) {\n throw new Error(`ModelGeneratorResult retryable must match stable reason ${reasonCode}.`);\n }\n}\n\nfunction createModelGeneratorArtifact(value: unknown, index: number): ModelGeneratorArtifact {\n const fieldName = `ModelGeneratorResult.sourceBundle.artifacts[${index}]`;\n const record = assertRecord(value, fieldName);\n assertAllowedKeys(record, [\n \"uri\",\n \"byteLength\",\n \"sha256\",\n \"contentType\",\n \"role\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n ], fieldName);\n const resource = createModelResourceRef({\n uri: record.uri,\n byteLength: record.byteLength,\n sha256: record.sha256,\n contentType: record.contentType,\n });\n const role = requiredEnum(record.role, MODEL_GENERATOR_ARTIFACT_ROLES, `${fieldName}.role`);\n const compatibleContentTypes: Readonly<Record<ModelGeneratorArtifactRole, readonly string[]>> = {\n \"model-entrypoint\": [\"model/gltf-binary\", \"model/gltf+json\"],\n \"model-dependency\": [\"model/gltf-binary\", \"model/gltf+json\"],\n binary: [\"application/octet-stream\"],\n texture: [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/ktx2\"],\n metadata: [\"application/json\"],\n };\n if (!compatibleContentTypes[role].includes(resource.contentType.toLowerCase())) {\n throw new Error(`${fieldName}.contentType is not compatible with artifact role ${role}.`);\n }\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n `${fieldName}.textureByteLength`,\n 0,\n resource.byteLength,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n `${fieldName}.maxTextureDimensionPx`,\n 0,\n 32_768,\n );\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(`${fieldName} texture bytes and dimensions must both be zero or both positive.`);\n }\n if (role === \"texture\" && textureByteLength !== resource.byteLength) {\n throw new Error(`${fieldName} standalone texture bytes must equal artifact byteLength.`);\n }\n if ([\"binary\", \"metadata\"].includes(role) && textureByteLength !== 0) {\n throw new Error(`${fieldName} non-model metadata/binary artifacts must not claim embedded textures.`);\n }\n return { ...resource, role, textureByteLength, maxTextureDimensionPx };\n}\n\nfunction createModelGeneratorUsage(value: unknown): ModelGeneratorUsage {\n const record = assertRecord(value, \"ModelGeneratorResult.sourceBundle.usage\");\n assertAllowedKeys(record, [\n \"durationMs\",\n \"triangleCount\",\n \"byteLength\",\n \"textureByteLength\",\n \"maxTextureDimensionPx\",\n ], \"ModelGeneratorResult.sourceBundle.usage\");\n const textureByteLength = requiredInteger(\n record.textureByteLength,\n \"ModelGeneratorResult.sourceBundle.usage.textureByteLength\",\n 0,\n Number.MAX_SAFE_INTEGER,\n );\n const maxTextureDimensionPx = requiredInteger(\n record.maxTextureDimensionPx,\n \"ModelGeneratorResult.sourceBundle.usage.maxTextureDimensionPx\",\n 0,\n 32_768,\n );\n if ((textureByteLength === 0) !== (maxTextureDimensionPx === 0)) {\n throw new Error(\"ModelGeneratorResult texture usage bytes and dimensions must both be zero or both positive.\");\n }\n return {\n durationMs: requiredInteger(record.durationMs, \"ModelGeneratorResult.sourceBundle.usage.durationMs\", 0, 300_000),\n triangleCount: requiredInteger(record.triangleCount, \"ModelGeneratorResult.sourceBundle.usage.triangleCount\", 1, 10_000_000),\n byteLength: requiredInteger(record.byteLength, \"ModelGeneratorResult.sourceBundle.usage.byteLength\", 1, Number.MAX_SAFE_INTEGER),\n textureByteLength,\n maxTextureDimensionPx,\n };\n}\n\nfunction createGeneratorTerminalEvidence(\n record: Record<string, unknown>,\n expected: ModelGeneratorRequest,\n): ModelGeneratorTerminalEvidence {\n const generationId = requiredModelPathSegment(record.generationId, \"ModelGeneratorResult.generationId\");\n if (generationId !== expected.generationId) {\n throw new Error(\"ModelGeneratorResult.generationId must match the generator request.\");\n }\n const diagnosticId = record.diagnosticId === undefined\n ? undefined\n : requiredToken(record.diagnosticId, \"ModelGeneratorResult.diagnosticId\");\n return {\n generationId,\n retryable: requiredBoolean(record.retryable, \"ModelGeneratorResult.retryable\"),\n occurredAt: requiredTimestamp(record.occurredAt, \"ModelGeneratorResult.occurredAt\"),\n ...(diagnosticId === undefined ? {} : { diagnosticId }),\n };\n}\n\n/** Validate and deeply freeze a request-bound generator outcome. */\nexport function createModelGeneratorResult(\n input: unknown,\n expectedRequest: ModelGeneratorRequest,\n): ModelGeneratorResult {\n const expected = createModelGeneratorRequest(expectedRequest);\n const record = assertRecord(input, \"ModelGeneratorResult\");\n const status = requiredEnum(record.status, [\n \"disabled\",\n \"generated\",\n \"unavailable\",\n \"failed\",\n \"cancelled\",\n \"budget-exceeded\",\n ] as const, \"ModelGeneratorResult.status\");\n const generationId = requiredModelPathSegment(record.generationId, \"ModelGeneratorResult.generationId\");\n if (generationId !== expected.generationId) {\n throw new Error(\"ModelGeneratorResult.generationId must match the generator request.\");\n }\n if (status === \"disabled\") {\n assertAllowedKeys(record, [\"status\", \"generationId\", \"reasonCode\"], \"ModelGeneratorResult\");\n if (record.reasonCode !== MODEL_GENERATOR_DISABLED_REASON_CODE) {\n throw new Error(\n `ModelGeneratorResult.reasonCode must be ${MODEL_GENERATOR_DISABLED_REASON_CODE}.`,\n );\n }\n return deepFreeze({\n status,\n generationId,\n reasonCode: MODEL_GENERATOR_DISABLED_REASON_CODE,\n });\n }\n\n if (status === \"generated\") {\n assertAllowedKeys(record, [\"status\", \"generationId\", \"sourceBundle\"], \"ModelGeneratorResult\");\n const sourceBundle = assertRecord(record.sourceBundle, \"ModelGeneratorResult.sourceBundle\");\n assertAllowedKeys(sourceBundle, [\n \"bundleId\",\n \"generationId\",\n \"entrypointUri\",\n \"artifacts\",\n \"generator\",\n \"generatedAt\",\n \"seed\",\n \"context\",\n \"usage\",\n ], \"ModelGeneratorResult.sourceBundle\");\n const bundleId = requiredModelPathSegment(sourceBundle.bundleId, \"ModelGeneratorResult.sourceBundle.bundleId\");\n const bundleGenerationId = requiredModelPathSegment(\n sourceBundle.generationId,\n \"ModelGeneratorResult.sourceBundle.generationId\",\n );\n if (bundleId !== generationId || bundleGenerationId !== generationId) {\n throw new Error(\"ModelGeneratorResult source bundle identifiers must match generationId.\");\n }\n if (!Array.isArray(sourceBundle.artifacts) || sourceBundle.artifacts.length < 1 || sourceBundle.artifacts.length > 32) {\n throw new Error(\"ModelGeneratorResult.sourceBundle.artifacts must contain one to 32 internal resources.\");\n }\n const artifacts = sourceBundle.artifacts.map(createModelGeneratorArtifact);\n if (new Set(artifacts.map((artifact) => artifact.uri)).size !== artifacts.length) {\n throw new Error(\"ModelGeneratorResult.sourceBundle.artifacts must have unique URIs.\");\n }\n const namespace = `mcp://models/generations/${generationId}/source/`;\n if (artifacts.some((artifact) => !artifact.uri.startsWith(namespace))) {\n throw new Error(\"ModelGeneratorResult artifacts must remain inside the generation source namespace.\");\n }\n const entrypointUri = assertModelUri(sourceBundle.entrypointUri, \"ModelGeneratorResult.sourceBundle.entrypointUri\");\n const entrypointArtifacts = artifacts.filter((artifact) => artifact.role === \"model-entrypoint\");\n if (\n entrypointArtifacts.length !== 1\n || entrypointArtifacts[0]?.uri !== entrypointUri\n || !artifacts.some((artifact) => artifact.uri === entrypointUri)\n ) {\n throw new Error(\"ModelGeneratorResult source bundle requires exactly one model-entrypoint matching entrypointUri.\");\n }\n const generator = assertRecord(sourceBundle.generator, \"ModelGeneratorResult.sourceBundle.generator\");\n assertAllowedKeys(generator, [\"id\", \"version\"], \"ModelGeneratorResult.sourceBundle.generator\");\n const generatedAt = requiredTimestamp(sourceBundle.generatedAt, \"ModelGeneratorResult.sourceBundle.generatedAt\");\n if (Date.parse(generatedAt) > Date.parse(expected.deadline)) {\n throw new Error(\"ModelGeneratorResult generatedAt must not exceed the request deadline.\");\n }\n const seed = createGeneratorSeed(sourceBundle.seed, \"ModelGeneratorResult.sourceBundle.seed\");\n if (seed !== expected.seed) {\n throw new Error(\"ModelGeneratorResult source bundle seed must match the generator request.\");\n }\n const context = createModelGeneratorRequest(sourceBundle.context);\n if (JSON.stringify(context) !== JSON.stringify(expected)) {\n throw new Error(\"ModelGeneratorResult source bundle context must exactly match the generator request.\");\n }\n const usage = createModelGeneratorUsage(sourceBundle.usage);\n const aggregateBytes = artifacts.reduce((total, artifact) => total + artifact.byteLength, 0);\n const textureBytes = artifacts.reduce(\n (total, artifact) => total + artifact.textureByteLength,\n 0,\n );\n const maxTextureDimensionPx = Math.max(\n 0,\n ...artifacts.map((artifact) => artifact.maxTextureDimensionPx),\n );\n if (!Number.isSafeInteger(aggregateBytes) || usage.byteLength !== aggregateBytes) {\n throw new Error(\"ModelGeneratorResult usage.byteLength must equal aggregate artifact bytes.\");\n }\n if (usage.textureByteLength !== textureBytes) {\n throw new Error(\"ModelGeneratorResult usage.textureByteLength must equal texture artifact bytes.\");\n }\n if (usage.maxTextureDimensionPx !== maxTextureDimensionPx) {\n throw new Error(\"ModelGeneratorResult usage.maxTextureDimensionPx must equal measured artifact texture dimensions.\");\n }\n if (\n usage.durationMs > expected.budgets.maxDurationMs\n || usage.triangleCount > expected.budgets.maxTriangles\n || usage.byteLength > expected.budgets.maxBytes\n || usage.textureByteLength > expected.budgets.maxTextureBytes\n || usage.maxTextureDimensionPx > expected.budgets.maxTextureDimensionPx\n ) {\n throw new Error(\"ModelGeneratorResult generated usage exceeds the request budget.\");\n }\n return deepFreeze({\n status,\n generationId,\n sourceBundle: {\n bundleId,\n generationId,\n entrypointUri,\n artifacts,\n generator: {\n id: requiredToken(generator.id, \"ModelGeneratorResult.sourceBundle.generator.id\"),\n version: assetVersion(generator.version, \"ModelGeneratorResult.sourceBundle.generator.version\"),\n },\n generatedAt,\n seed,\n context,\n usage,\n },\n });\n }\n\n const terminalAllowedKeys = [\n \"status\",\n \"generationId\",\n \"reasonCode\",\n \"retryable\",\n \"occurredAt\",\n \"diagnosticId\",\n ] as const;\n if (status === \"budget-exceeded\") {\n assertAllowedKeys(record, [...terminalAllowedKeys, \"violations\"], \"ModelGeneratorResult\");\n if (record.reasonCode !== \"generator-budget-exceeded\" || record.retryable !== false) {\n throw new Error(\"ModelGeneratorResult budget-exceeded must use its fixed reasonCode and retryable false.\");\n }\n if (!Array.isArray(record.violations) || record.violations.length < 1 || record.violations.length > 5) {\n throw new Error(\"ModelGeneratorResult budget violations must contain one to five entries.\");\n }\n const violations = record.violations.map((value, index): ModelGeneratorBudgetViolation => {\n const fieldName = `ModelGeneratorResult.violations[${index}]`;\n const violation = assertRecord(value, fieldName);\n assertAllowedKeys(violation, [\"budget\", \"limit\", \"observed\"], fieldName);\n const budget = requiredEnum(violation.budget, MODEL_GENERATOR_BUDGET_NAMES, `${fieldName}.budget`);\n const limit = requiredInteger(violation.limit, `${fieldName}.limit`, 0, Number.MAX_SAFE_INTEGER);\n const observed = requiredInteger(violation.observed, `${fieldName}.observed`, 0, Number.MAX_SAFE_INTEGER);\n if (limit !== expected.budgets[budget] || observed <= limit) {\n throw new Error(`${fieldName} limit must match the request budget and observed must exceed it.`);\n }\n return { budget, limit, observed };\n });\n if (new Set(violations.map((violation) => violation.budget)).size !== violations.length) {\n throw new Error(\"ModelGeneratorResult budget violation names must be unique.\");\n }\n const terminal = createGeneratorTerminalEvidence(record, expected);\n return deepFreeze({\n status,\n ...terminal,\n reasonCode: \"generator-budget-exceeded\",\n retryable: false,\n violations,\n });\n }\n\n assertAllowedKeys(record, terminalAllowedKeys, \"ModelGeneratorResult\");\n const terminal = createGeneratorTerminalEvidence(record, expected);\n if (status === \"unavailable\") {\n const reasonCode = requiredEnum(record.reasonCode, [\n \"capacity-unavailable\",\n \"provider-unavailable\",\n \"authentication-required\",\n \"rate-limited\",\n \"unsupported-request\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n }\n if (status === \"failed\") {\n const reasonCode = requiredEnum(record.reasonCode, [\n \"provider-failed\",\n \"invalid-generator-output\",\n \"internal-failure\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n }\n const reasonCode = requiredEnum(record.reasonCode, [\n \"caller-aborted\",\n \"deadline-exceeded\",\n \"superseded\",\n \"service-shutdown\",\n ] as const, \"ModelGeneratorResult.reasonCode\");\n assertGeneratorRetryability(reasonCode, terminal.retryable);\n return deepFreeze({ status, ...terminal, reasonCode });\n}\n\n/** Create the fail-closed Phase 1 generator port; it never performs generation. */\nexport function createDisabledModelGeneratorPort(): ModelGeneratorPort {\n return Object.freeze({\n enabled: false,\n async generate(\n input: ModelGeneratorRequest,\n options: ModelGeneratorCallOptions = {},\n ): Promise<DisabledModelGeneratorResult> {\n if (options.signal !== undefined) {\n if (typeof options.signal.throwIfAborted !== \"function\") {\n throw new Error(\"ModelGeneratorPort signal must be an AbortSignal.\");\n }\n options.signal.throwIfAborted();\n }\n const request = createModelGeneratorRequest(input);\n return deepFreeze({\n status: \"disabled\",\n generationId: request.generationId,\n reasonCode: MODEL_GENERATOR_DISABLED_REASON_CODE,\n });\n },\n });\n}\n","import { canonicalizeGpuContract } from \"@plasius/gpu-shader\";\nimport {\n PVOX_ASSEMBLY_CLOSURE_HASH_DOMAIN,\n PVOX_BINARY_CLOSURE_HASH_DOMAIN,\n PVOX_BRICK_EDGE_VOXELS,\n PVOX_CAPABILITIES,\n PVOX_CAPABILITY_SET_HASH_DOMAIN,\n PVOX_CONFIRMATION_BINDING_HASH_DOMAIN,\n PVOX_DIRECTORY_ENTRY_BYTE_LENGTH,\n PVOX_DIRECTORY_HASH_DOMAIN,\n PVOX_DEFAULT_LIMITS,\n PVOX_EDIT_JOURNAL_GENESIS_HASH,\n PVOX_EDIT_JOURNAL_HASH_DOMAIN,\n PVOX_MAX_ABSOLUTE_COORDINATE_METRES,\n PVOX_MAX_EDIT_PATCHES,\n PVOX_EDIT_OVERLAY_ROOT_HASH_DOMAIN,\n PVOX_EVALUATION_CLOSURE_HASH_DOMAIN,\n PVOX_FORMAT_VERSION,\n PVOX_HEADER_BYTE_LENGTH,\n PVOX_MAGIC,\n PVOX_MAX_SECTIONS,\n PVOX_PAGE_SET_HASH_DOMAIN,\n PVOX_PAGE_SIZE_BYTES,\n PVOX_PHYSICAL_EVIDENCE_HASH_DOMAIN,\n PVOX_PHYSICAL_INVENTORY_HASH_DOMAIN,\n PVOX_PHYSICAL_PROPERTIES,\n PVOX_PROCESSING_CLOSURE_HASH_DOMAIN,\n PVOX_PUBLICATION_HASH_DOMAIN,\n PVOX_RENDER_EVIDENCE_HASH_DOMAIN,\n PVOX_REQUEST_SEMANTIC_PROFILE_HASH_DOMAIN,\n PVOX_ROOT_HASH_DOMAIN,\n PVOX_RUNTIME_REQUEST_PROFILE_HASH_DOMAIN,\n PVOX_SECTION_ALIGNMENT_BYTES,\n PVOX_SECTION_HASH_DOMAIN,\n} from \"./pvox-model-resolution.js\";\n\nexport const PVOX_SHA256_BYTE_LENGTH = 32 as const;\nexport const PVOX_SHA256_HEX_LENGTH = PVOX_SHA256_BYTE_LENGTH * 2;\nexport const PVOX_CANONICAL_UTF8_LENGTH_PREFIX_BYTES = 4 as const;\nexport const PVOX_ROOT_HEADER_DIRECTORY_HASH_OFFSET = 176 as const;\nexport const PVOX_ROOT_HEADER_COMPILATION_INPUT_HASH_OFFSET = 112 as const;\nexport const PVOX_ROOT_HEADER_RUNTIME_REQUEST_PROFILE_HASH_OFFSET = 144 as const;\nexport const PVOX_ROOT_HEADER_TRAILING_RESERVED_OFFSET = 208 as const;\nexport const PVOX_ROOT_HEADER_TRAILING_RESERVED_BYTE_LENGTH = 48 as const;\nexport const PVOX_ROOT_HEADER_INLINE_RESERVED_OFFSET = 58 as const;\nexport const PVOX_ROOT_HEADER_INLINE_RESERVED_BYTE_LENGTH = 2 as const;\nexport const PVOX_ROOT_HEADER_COORDINATE_BASIS_METRES_Y_UP_NEGATIVE_Z_FORWARD_CCW = 1 as const;\nexport const PVOX_ROOT_HEADER_FLAGS_V1 = 0 as const;\nexport const PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_V1 = 8 as const;\nexport const PVOX_ROOT_HEADER_MINIMUM_FIXED_POINT_FRACTION_BITS_V1 = 0 as const;\nexport const PVOX_ROOT_HEADER_MAXIMUM_FIXED_POINT_FRACTION_BITS_V1 = 32 as const;\n/** Upper bound for one canonical JSON/text component in a governed PVOX hash preimage. */\nexport const PVOX_MAX_CANONICAL_HASH_UTF8_BYTES_V1 = PVOX_DEFAULT_LIMITS.maximumArtifactBytes;\n/** Upper bound for a complete encoded hash preimage, including its domain and framing. */\nexport const PVOX_MAX_HASH_PREIMAGE_BYTES_V1 = PVOX_DEFAULT_LIMITS.maximumArtifactBytes + PVOX_PAGE_SIZE_BYTES;\n\nconst U16_MAXIMUM = 0xffff;\nconst U32_MAXIMUM = 0xffff_ffff;\nconst U64_MAXIMUM = 0xffff_ffff_ffff_ffffn;\nconst I64_MINIMUM = -0x8000_0000_0000_0000n;\nconst I64_MAXIMUM = 0x7fff_ffff_ffff_ffffn;\nconst PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT = 6 as const;\nconst PVOX_ROOT_HEADER_MAGIC_OFFSET = 0 as const;\nconst PVOX_ROOT_HEADER_FORMAT_MAJOR_OFFSET = 4 as const;\nconst PVOX_ROOT_HEADER_FORMAT_MINOR_OFFSET = 6 as const;\nconst PVOX_ROOT_HEADER_BYTE_LENGTH_OFFSET = 8 as const;\nconst PVOX_ROOT_HEADER_DIRECTORY_ENTRY_BYTE_LENGTH_OFFSET = 10 as const;\nconst PVOX_ROOT_HEADER_SECTION_COUNT_OFFSET = 12 as const;\nconst PVOX_ROOT_HEADER_FLAGS_OFFSET = 14 as const;\nconst PVOX_ROOT_HEADER_ARTIFACT_BYTE_LENGTH_OFFSET = 16 as const;\nconst PVOX_ROOT_HEADER_DIRECTORY_BYTE_OFFSET_OFFSET = 24 as const;\nconst PVOX_ROOT_HEADER_DIRECTORY_BYTE_LENGTH_OFFSET = 32 as const;\nconst PVOX_ROOT_HEADER_PAGE_SIZE_OFFSET = 40 as const;\nconst PVOX_ROOT_HEADER_PAGE_COUNT_OFFSET = 44 as const;\nconst PVOX_ROOT_HEADER_BRICK_EDGE_OFFSET = 48 as const;\nconst PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_OFFSET = 50 as const;\nconst PVOX_ROOT_HEADER_GEOMETRY_MODE_OFFSET = 51 as const;\nconst PVOX_ROOT_HEADER_COORDINATE_BASIS_OFFSET = 52 as const;\nconst PVOX_ROOT_HEADER_FIXED_POINT_FRACTION_BITS_OFFSET = 56 as const;\nconst PVOX_ROOT_HEADER_BOUNDS_OFFSET = 60 as const;\nconst PVOX_ROOT_HEADER_BOUND_COMPONENT_BYTE_LENGTH = 8 as const;\nconst PVOX_ROOT_HEADER_DIRECTORY_START_PAGE_OFFSET = 108 as const;\nconst PVOX_MAX_HASH_PREIMAGE_DATA_NODES_V1 = PVOX_DEFAULT_LIMITS.maximumHierarchyNodes;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst PVOX_MAGIC_BYTES = TEXT_ENCODER.encode(PVOX_MAGIC);\n\nfunction assertPvoxPreimageDataOnly(\n value: unknown,\n fieldName: string,\n seen = new WeakSet<object>(),\n depth = 0,\n state = { nodes: 0 },\n): void {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\" || typeof value === \"bigint\") return;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new Error(`${fieldName} must contain finite data values only.`);\n return;\n }\n if (typeof value !== \"object\") throw new Error(`${fieldName} must contain JSON/fixed-width data values only.`);\n state.nodes += 1;\n if (depth > 64 || state.nodes > PVOX_MAX_HASH_PREIMAGE_DATA_NODES_V1 || seen.has(value)) throw new Error(`${fieldName} must be an acyclic bounded data tree.`);\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n state.nodes += value.length;\n if (state.nodes > PVOX_MAX_HASH_PREIMAGE_DATA_NODES_V1) throw new Error(`${fieldName} must be an acyclic bounded data tree.`);\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Reflect.ownKeys(descriptors);\n if (keys.some((key) => typeof key === \"symbol\" || (key !== \"length\" && !/^(0|[1-9][0-9]*)$/u.test(key)))) throw new Error(`${fieldName} arrays must contain indexed data properties only.`);\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = descriptors[String(index)];\n if (!descriptor || !(\"value\" in descriptor) || !descriptor.enumerable) throw new Error(`${fieldName} arrays must be dense enumerable data properties.`);\n assertPvoxPreimageDataOnly(descriptor.value, `${fieldName}[${index}]`, seen, depth + 1, state);\n }\n return;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new Error(`${fieldName} objects must have a plain or null prototype.`);\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") throw new Error(`${fieldName} objects must contain string-keyed data properties only.`);\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !(\"value\" in descriptor) || !descriptor.enumerable) throw new Error(`${fieldName} objects must contain enumerable data properties only.`);\n assertPvoxPreimageDataOnly(descriptor.value, `${fieldName}.${key}`, seen, depth + 1, state);\n }\n } finally {\n seen.delete(value);\n }\n}\n\nfunction assertExactPvoxPreimageKeys(value: object, expectedKeys: readonly string[], fieldName: string): void {\n const actualKeys = Object.keys(value);\n if (actualKeys.length !== expectedKeys.length || expectedKeys.some((key) => !Object.hasOwn(value, key))) {\n throw new Error(`${fieldName} must contain exactly: ${expectedKeys.join(\", \")}.`);\n }\n}\n\nfunction preflightPvoxFixedObject(value: unknown, expectedKeys: readonly string[], fieldName: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`${fieldName} must be an object.`);\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new Error(`${fieldName} must have a plain or null prototype.`);\n assertExactPvoxPreimageKeys(value, expectedKeys, fieldName);\n for (const key of expectedKeys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !(\"value\" in descriptor) || !descriptor.enumerable) throw new Error(`${fieldName}.${key} must be an enumerable data property.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction getPreflightPvoxDataProperty(value: Record<string, unknown>, key: string): unknown {\n return (Object.getOwnPropertyDescriptor(value, key) as PropertyDescriptor & { value: unknown }).value;\n}\n\nfunction preflightPvoxArrayCardinality(value: unknown, minimum: number, maximum: number, fieldName: string): readonly unknown[] {\n if (!Array.isArray(value)) throw new Error(`${fieldName} must be an array.`);\n const lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n if (!lengthDescriptor || !(\"value\" in lengthDescriptor) || typeof lengthDescriptor.value !== \"number\" || !Number.isSafeInteger(lengthDescriptor.value)\n || lengthDescriptor.value < minimum || lengthDescriptor.value > maximum) {\n throw new Error(`${fieldName} must contain from ${minimum} through ${maximum} entries.`);\n }\n return value;\n}\n\nfunction copyPvoxByteInput(value: unknown, fieldName: string, maximumByteLength: number): Uint8Array {\n if (!(value instanceof Uint8Array)) throw new Error(`${fieldName} must be a Uint8Array.`);\n let byteLength: number;\n try {\n const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype) as object;\n const byteLengthGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"byteLength\")?.get;\n const bufferGetter = Object.getOwnPropertyDescriptor(typedArrayPrototype, \"buffer\")?.get;\n if (byteLengthGetter === undefined || bufferGetter === undefined) throw new Error(\"Typed-array intrinsics are unavailable.\");\n byteLength = byteLengthGetter.call(value) as number;\n const buffer = bufferGetter.call(value) as ArrayBufferLike;\n if (typeof SharedArrayBuffer !== \"undefined\" && buffer instanceof SharedArrayBuffer) {\n throw new Error(`${fieldName} must not use shared mutable storage.`);\n }\n } catch (error) {\n if (error instanceof Error && /shared mutable storage/u.test(error.message)) throw error;\n throw new Error(`${fieldName} must be an intrinsic Uint8Array.`, { cause: error });\n }\n if (byteLength > maximumByteLength) throw new Error(`${fieldName} exceeds the governed PVOX byte limit.`);\n const output = new Uint8Array(byteLength);\n for (let index = 0; index < byteLength; index += 1) output[index] = value[index]!;\n return output;\n}\n\nexport const PVOX_ROOT_HEADER_GEOMETRY_MODE_CODES_V1 = Object.freeze({\n solid: 1,\n shell: 2,\n mixed: 3,\n} as const);\n\nexport type PvoxRootHeaderGeometryModeV1 = keyof typeof PVOX_ROOT_HEADER_GEOMETRY_MODE_CODES_V1;\n\n/** Closed byte layout. Root and binary-closure digests are deliberately external to this header. */\nexport const PVOX_ROOT_HEADER_LAYOUT_V1 = Object.freeze({\n magic: Object.freeze({ offset: PVOX_ROOT_HEADER_MAGIC_OFFSET, byteLength: PVOX_MAGIC_BYTES.byteLength }),\n formatMajor: Object.freeze({ offset: PVOX_ROOT_HEADER_FORMAT_MAJOR_OFFSET, byteLength: 2 }),\n formatMinor: Object.freeze({ offset: PVOX_ROOT_HEADER_FORMAT_MINOR_OFFSET, byteLength: 2 }),\n headerByteLength: Object.freeze({ offset: PVOX_ROOT_HEADER_BYTE_LENGTH_OFFSET, byteLength: 2 }),\n directoryEntryByteLength: Object.freeze({ offset: PVOX_ROOT_HEADER_DIRECTORY_ENTRY_BYTE_LENGTH_OFFSET, byteLength: 2 }),\n sectionCount: Object.freeze({ offset: PVOX_ROOT_HEADER_SECTION_COUNT_OFFSET, byteLength: 2 }),\n flags: Object.freeze({ offset: PVOX_ROOT_HEADER_FLAGS_OFFSET, byteLength: 2 }),\n artifactByteLength: Object.freeze({ offset: PVOX_ROOT_HEADER_ARTIFACT_BYTE_LENGTH_OFFSET, byteLength: 8 }),\n directoryByteOffset: Object.freeze({ offset: PVOX_ROOT_HEADER_DIRECTORY_BYTE_OFFSET_OFFSET, byteLength: 8 }),\n directoryByteLength: Object.freeze({ offset: PVOX_ROOT_HEADER_DIRECTORY_BYTE_LENGTH_OFFSET, byteLength: 8 }),\n pageSizeBytes: Object.freeze({ offset: PVOX_ROOT_HEADER_PAGE_SIZE_OFFSET, byteLength: 4 }),\n pageCount: Object.freeze({ offset: PVOX_ROOT_HEADER_PAGE_COUNT_OFFSET, byteLength: 4 }),\n brickEdgeVoxels: Object.freeze({ offset: PVOX_ROOT_HEADER_BRICK_EDGE_OFFSET, byteLength: 2 }),\n maximumHierarchyDepth: Object.freeze({ offset: PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_OFFSET, byteLength: 1 }),\n geometryMode: Object.freeze({ offset: PVOX_ROOT_HEADER_GEOMETRY_MODE_OFFSET, byteLength: 1 }),\n coordinateBasis: Object.freeze({ offset: PVOX_ROOT_HEADER_COORDINATE_BASIS_OFFSET, byteLength: 4 }),\n fixedPointFractionBits: Object.freeze({ offset: PVOX_ROOT_HEADER_FIXED_POINT_FRACTION_BITS_OFFSET, byteLength: 2 }),\n inlineReserved: Object.freeze({ offset: PVOX_ROOT_HEADER_INLINE_RESERVED_OFFSET, byteLength: PVOX_ROOT_HEADER_INLINE_RESERVED_BYTE_LENGTH }),\n quantizedBounds: Object.freeze({ offset: PVOX_ROOT_HEADER_BOUNDS_OFFSET, byteLength: PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT * PVOX_ROOT_HEADER_BOUND_COMPONENT_BYTE_LENGTH }),\n directoryStartPage: Object.freeze({ offset: PVOX_ROOT_HEADER_DIRECTORY_START_PAGE_OFFSET, byteLength: 4 }),\n compilationInputHash: Object.freeze({ offset: PVOX_ROOT_HEADER_COMPILATION_INPUT_HASH_OFFSET, byteLength: PVOX_SHA256_BYTE_LENGTH }),\n runtimeRequestProfileHash: Object.freeze({ offset: PVOX_ROOT_HEADER_RUNTIME_REQUEST_PROFILE_HASH_OFFSET, byteLength: PVOX_SHA256_BYTE_LENGTH }),\n directoryHash: Object.freeze({ offset: PVOX_ROOT_HEADER_DIRECTORY_HASH_OFFSET, byteLength: PVOX_SHA256_BYTE_LENGTH }),\n trailingReserved: Object.freeze({ offset: PVOX_ROOT_HEADER_TRAILING_RESERVED_OFFSET, byteLength: PVOX_ROOT_HEADER_TRAILING_RESERVED_BYTE_LENGTH }),\n rootHash: Object.freeze({ storage: \"external\" }),\n binaryClosureHash: Object.freeze({ storage: \"external\" }),\n} as const);\n\nexport interface PvoxRootHeaderInputV1 {\n readonly sectionCount: number;\n readonly artifactByteLength: number | bigint;\n readonly directoryByteOffset: number | bigint;\n readonly directoryByteLength: number | bigint;\n readonly pageCount: number;\n readonly maximumHierarchyDepth: number;\n readonly geometryMode: PvoxRootHeaderGeometryModeV1;\n readonly fixedPointFractionBits: number;\n /** minX, minY, minZ, maxX, maxY, maxZ in the declared fixed-point scale. */\n readonly quantizedBounds: readonly [bigint, bigint, bigint, bigint, bigint, bigint];\n readonly directoryStartPage: number;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly directoryHash: string;\n}\n\nexport interface PvoxRootSectionHashRecordV1 {\n readonly sectionType: number;\n readonly sectionVersion: number;\n readonly sectionHash: string;\n}\n\nexport interface PvoxPageHashRecordV1 {\n readonly pageIndex: number;\n readonly byteOffset: number | bigint;\n readonly byteLength: number;\n readonly pageSha256: string;\n}\n\nexport interface PvoxBinaryClosureHashInputV1 {\n readonly sourceContentHash: string;\n readonly canonicalDocumentHash: string;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly artifactSha256: string;\n readonly rootHash: string;\n readonly directoryHash: string;\n readonly pageSetHash: string;\n}\n\nexport interface PvoxPhysicalInventoryHashRecordV1 {\n readonly regionIndex: number;\n readonly physicalPaletteIndex: number;\n readonly regionId: string;\n readonly materialId: string;\n}\n\nexport interface PvoxPhysicalInventoryHashInputV1 {\n readonly inventoryVersion: string;\n readonly subjectBinaryClosureHash: string;\n readonly validationEvidenceHash: string;\n readonly entries: readonly PvoxPhysicalInventoryHashRecordV1[];\n}\n\nexport interface PvoxEvaluationClosureHashInputV1 {\n readonly fidelityEvidenceHash: string;\n readonly physicalEvidenceHash: string;\n readonly capabilitySetHash: string;\n readonly renderEvidenceHash: string;\n}\n\nexport interface PvoxPhysicalEvidenceRegionMaterialV1 {\n readonly regionId: string;\n readonly materialId: string;\n}\n\n/** `orderedRegionMaterials` is validation context derived from the attested inventory and is not encoded twice. */\nexport interface PvoxPhysicalEvidenceHashInputV1 {\n readonly physicalInventoryHash: string;\n readonly orderedRegionMaterials: readonly PvoxPhysicalEvidenceRegionMaterialV1[];\n readonly orderedCanonicalEvidence: readonly unknown[];\n}\n\nexport interface PvoxProcessingClosureHashInputV1 {\n readonly binaryClosureHash: string;\n readonly requestSemanticProfileHash: string;\n readonly technicalProfile: unknown;\n readonly pvoxValidationEvidenceHash: string;\n readonly physicalInventoryValidationEvidenceHash: string;\n readonly capabilitySetHash: string;\n readonly physicalInventoryHash: string;\n readonly physicalEvidenceHash: string;\n readonly massPropertiesEvidenceHash: string;\n readonly bondGraphEvidenceHash: string;\n readonly interiorLayerEvidenceHash: string;\n readonly compilerEvidenceHash: string;\n readonly fidelityEvidenceHash: string;\n}\n\nexport interface PvoxAssemblyClosureHashInputV1 {\n readonly ownBinaryClosureHash: string;\n readonly orderedChildren: readonly unknown[];\n}\n\nexport interface PvoxEditOverlayRootHashInputV1 {\n readonly baseContentHash: string;\n readonly basePageSetHash: string;\n readonly placementId: string;\n readonly gridVersion: string;\n readonly expectedRevision: number | bigint;\n readonly resultingRevision: number | bigint;\n readonly previousJournalHash: string;\n readonly expectedRootHash: string;\n readonly orderedPatches: readonly PvoxEditOverlayPatchHashInputV1[];\n}\n\nexport interface PvoxEditOverlayPatchHashInputV1 {\n readonly fieldKind: \"render-field\" | \"collision-field\";\n readonly lodLevel: number;\n readonly partitionIndex: number;\n readonly hierarchyDepth: number;\n readonly mortonCode: string;\n readonly expectedPageIndex: number;\n readonly expectedPageHash: string;\n readonly operation: \"insert\" | \"replace\" | \"remove\";\n readonly expectedBrickHash: string;\n readonly resultingBrickHash: string;\n readonly resultingPageHash: string;\n}\n\nexport const PVOX_NAMED_JSON_CLOSURE_SPECS_V1 = Object.freeze({\n \"request-semantic-profile\": Object.freeze({\n domain: PVOX_REQUEST_SEMANTIC_PROFILE_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/requestSemanticProfileHash\"] as const),\n }),\n \"runtime-request-profile\": Object.freeze({\n domain: PVOX_RUNTIME_REQUEST_PROFILE_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/runtimeRequestProfileHash\"] as const),\n }),\n \"render-evidence\": Object.freeze({\n domain: PVOX_RENDER_EVIDENCE_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/evidenceHash\", \"/evidenceHashAttestation\"] as const),\n }),\n \"confirmation-binding\": Object.freeze({\n domain: PVOX_CONFIRMATION_BINDING_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/bindingHash\", \"/bindingHashAttestation\"] as const),\n }),\n \"edit-journal\": Object.freeze({\n domain: PVOX_EDIT_JOURNAL_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/journalHash\", \"/journalHashAttestation\", \"/resultingRootHashAttestation\"] as const),\n }),\n \"publication-receipt\": Object.freeze({\n domain: PVOX_PUBLICATION_HASH_DOMAIN,\n omittedJsonPointers: Object.freeze([\"/publicationHash\", \"/publicationHashAttestation\", \"/publicationToken\"] as const),\n }),\n} as const);\n\nexport type PvoxNamedJsonClosureV1 = keyof typeof PVOX_NAMED_JSON_CLOSURE_SPECS_V1;\n\nfunction assertSafeIntegerInRange(value: number, minimum: number, maximum: number, fieldName: string): number {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new Error(`${fieldName} must be a safe integer from ${minimum} through ${maximum}.`);\n }\n return value;\n}\n\nfunction asUnsignedBigInt(value: number | bigint, fieldName: string): bigint {\n const result = typeof value === \"bigint\"\n ? value\n : BigInt(assertSafeIntegerInRange(value, 0, Number.MAX_SAFE_INTEGER, fieldName));\n if (result < 0n || result > U64_MAXIMUM) throw new Error(`${fieldName} must fit an unsigned 64-bit integer.`);\n return result;\n}\n\nfunction assertSignedBigInt(value: bigint, fieldName: string): bigint {\n if (value < I64_MINIMUM || value > I64_MAXIMUM) throw new Error(`${fieldName} must fit a signed 64-bit integer.`);\n return value;\n}\n\nfunction maximumQuantizedCoordinate(fractionBits: number): bigint {\n return BigInt(PVOX_MAX_ABSOLUTE_COORDINATE_METRES) * (1n << BigInt(fractionBits));\n}\n\nfunction assertQuantizedCoordinate(value: bigint, fractionBits: number, fieldName: string): bigint {\n const coordinate = assertSignedBigInt(value, fieldName);\n const absolute = coordinate < 0n ? -coordinate : coordinate;\n if (absolute > maximumQuantizedCoordinate(fractionBits)) throw new Error(`${fieldName} exceeds the governed absolute PVOX coordinate limit.`);\n return coordinate;\n}\n\nfunction concatenateBytes(parts: readonly Uint8Array[]): Uint8Array {\n const byteLength = parts.reduce((total, part) => total + part.byteLength, 0);\n if (!Number.isSafeInteger(byteLength) || byteLength > PVOX_MAX_HASH_PREIMAGE_BYTES_V1) {\n throw new Error(\"PVOX hash preimage exceeds the governed byte limit.\");\n }\n const output = new Uint8Array(byteLength);\n let offset = 0;\n for (const part of parts) {\n output.set(part, offset);\n offset += part.byteLength;\n }\n return output;\n}\n\nfunction writeBytes(target: Uint8Array, offset: number, value: Uint8Array): void {\n target.set(value, offset);\n}\n\nfunction isZeroRange(value: Uint8Array, offset: number, byteLength: number): boolean {\n for (let index = offset; index < offset + byteLength; index += 1) {\n if (value[index] !== 0) return false;\n }\n return true;\n}\n\nfunction readAscii(value: Uint8Array, offset: number, byteLength: number): string {\n return String.fromCharCode(...value.slice(offset, offset + byteLength));\n}\n\nexport function encodePvoxU16LeV1(value: number): Uint8Array {\n const output = new Uint8Array(2);\n new DataView(output.buffer).setUint16(0, assertSafeIntegerInRange(value, 0, U16_MAXIMUM, \"u16\"), true);\n return output;\n}\n\nexport function encodePvoxU32LeV1(value: number): Uint8Array {\n const output = new Uint8Array(4);\n new DataView(output.buffer).setUint32(0, assertSafeIntegerInRange(value, 0, U32_MAXIMUM, \"u32\"), true);\n return output;\n}\n\nexport function encodePvoxU64LeV1(value: number | bigint): Uint8Array {\n const output = new Uint8Array(8);\n new DataView(output.buffer).setBigUint64(0, asUnsignedBigInt(value, \"u64\"), true);\n return output;\n}\n\nexport function encodePvoxI64LeV1(value: bigint): Uint8Array {\n const output = new Uint8Array(8);\n new DataView(output.buffer).setBigInt64(0, assertSignedBigInt(value, \"i64\"), true);\n return output;\n}\n\nexport function decodePvoxSha256HexV1(value: string, fieldName = \"sha256\"): Uint8Array {\n if (!new RegExp(`^[0-9a-f]{${PVOX_SHA256_HEX_LENGTH}}$`, \"u\").test(value)) {\n throw new Error(`${fieldName} must be a canonical lowercase SHA-256 digest.`);\n }\n const output = new Uint8Array(PVOX_SHA256_BYTE_LENGTH);\n for (let index = 0; index < output.byteLength; index += 1) {\n output[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);\n }\n return output;\n}\n\nfunction encodeCanonicalRawUtf8(value: string): Uint8Array {\n if (!value.isWellFormed()) throw new Error(\"Canonical UTF-8 values cannot contain unpaired UTF-16 surrogates.\");\n let byteLength = 0;\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n if (codeUnit <= 0x7f) byteLength += 1;\n else if (codeUnit <= 0x7ff) byteLength += 2;\n else if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n byteLength += 4;\n index += 1;\n } else byteLength += 3;\n if (byteLength > PVOX_MAX_CANONICAL_HASH_UTF8_BYTES_V1) {\n throw new Error(\"Canonical UTF-8 value exceeds the governed PVOX hash-input byte limit.\");\n }\n }\n const encoded = TEXT_ENCODER.encode(value);\n if (encoded.byteLength !== byteLength) throw new Error(\"Canonical UTF-8 byte-length calculation failed.\");\n return encoded;\n}\n\nexport function encodePvoxCanonicalUtf8V1(value: string): Uint8Array {\n const utf8 = encodeCanonicalRawUtf8(value);\n if (utf8.byteLength > U32_MAXIMUM) throw new Error(\"Canonical UTF-8 value exceeds the unsigned 32-bit length prefix.\");\n return concatenateBytes([encodePvoxU32LeV1(utf8.byteLength), utf8]);\n}\n\nexport function encodePvoxSectionHashPreimageV1(\n sectionType: number,\n sectionVersion: number,\n exactSectionBytes: Uint8Array,\n): Uint8Array {\n const sectionBytes = copyPvoxByteInput(exactSectionBytes, \"exactSectionBytes\", PVOX_DEFAULT_LIMITS.maximumArtifactBytes);\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_SECTION_HASH_DOMAIN),\n encodePvoxU32LeV1(sectionType),\n encodePvoxU16LeV1(sectionVersion),\n encodePvoxU64LeV1(sectionBytes.byteLength),\n sectionBytes,\n ]);\n}\n\nexport function encodePvoxDirectoryHashPreimageV1(\n entryCount: number,\n exactOrderedDirectoryBytes: Uint8Array,\n): Uint8Array {\n const count = assertSafeIntegerInRange(entryCount, 1, PVOX_MAX_SECTIONS, \"entryCount\");\n const directoryBytes = copyPvoxByteInput(\n exactOrderedDirectoryBytes,\n \"exactOrderedDirectoryBytes\",\n PVOX_MAX_SECTIONS * PVOX_DIRECTORY_ENTRY_BYTE_LENGTH,\n );\n if (directoryBytes.byteLength !== count * PVOX_DIRECTORY_ENTRY_BYTE_LENGTH) {\n throw new Error(\"Directory bytes must contain exactly entryCount fixed-width entries.\");\n }\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_DIRECTORY_HASH_DOMAIN),\n encodePvoxU16LeV1(count),\n encodePvoxU16LeV1(PVOX_DIRECTORY_ENTRY_BYTE_LENGTH),\n directoryBytes,\n ]);\n}\n\nexport function encodePvoxPageSetHashPreimageV1(records: readonly PvoxPageHashRecordV1[]): Uint8Array {\n preflightPvoxArrayCardinality(records, 1, PVOX_DEFAULT_LIMITS.maximumPages, \"PVOX page-set hash input\");\n assertPvoxPreimageDataOnly(records, \"PVOX page-set hash input\");\n let previousEnd = 0n;\n const encoded = records.map((record, position) => {\n assertExactPvoxPreimageKeys(record, [\"pageIndex\", \"byteOffset\", \"byteLength\", \"pageSha256\"], `records[${position}]`);\n if (record.pageIndex !== position) throw new Error(\"Page-set records must have contiguous page indexes starting at zero.\");\n const offset = asUnsignedBigInt(record.byteOffset, `records[${position}].byteOffset`);\n const byteLength = assertSafeIntegerInRange(record.byteLength, PVOX_PAGE_SIZE_BYTES, PVOX_PAGE_SIZE_BYTES, `records[${position}].byteLength`);\n if (offset !== previousEnd || offset !== BigInt(position) * BigInt(PVOX_PAGE_SIZE_BYTES)) throw new Error(\"Page-set records must exactly cover contiguous 64-KiB PVOX pages.\");\n previousEnd = offset + BigInt(byteLength);\n return concatenateBytes([\n encodePvoxU32LeV1(record.pageIndex),\n encodePvoxU64LeV1(offset),\n encodePvoxU32LeV1(byteLength),\n decodePvoxSha256HexV1(record.pageSha256, `records[${position}].pageSha256`),\n ]);\n });\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_PAGE_SET_HASH_DOMAIN),\n encodePvoxU32LeV1(records.length),\n ...encoded,\n ]);\n}\n\nfunction normalizeJsonData(value: unknown): unknown {\n return cloneProjectedData(value, \"\", new Set<string>(), new WeakSet<object>());\n}\n\nfunction encodeCanonicalJsonRecord(value: unknown): Uint8Array {\n return encodePvoxCanonicalUtf8V1(canonicalizeGpuContract(normalizeJsonData(value)));\n}\n\nfunction encodeCanonicalJsonRecords(values: readonly unknown[]): readonly Uint8Array[] {\n const normalized = normalizeJsonData(values);\n if (!Array.isArray(normalized)) throw new Error(\"Canonical JSON record input must be an array.\");\n const encoded: Uint8Array[] = [];\n let aggregateByteLength = 0;\n for (const value of normalized) {\n const record = encodeCanonicalJsonRecord(value);\n aggregateByteLength += record.byteLength;\n if (aggregateByteLength > PVOX_MAX_CANONICAL_HASH_UTF8_BYTES_V1) {\n throw new Error(\"Canonical JSON records exceed the governed PVOX hash-input byte limit.\");\n }\n encoded.push(record);\n }\n return encoded;\n}\n\nexport function encodePvoxBinaryClosureHashPreimageV1(input: PvoxBinaryClosureHashInputV1): Uint8Array {\n assertPvoxPreimageDataOnly(input, \"PVOX binary-closure hash input\");\n assertExactPvoxPreimageKeys(input, [\n \"sourceContentHash\", \"canonicalDocumentHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\",\n \"artifactSha256\", \"rootHash\", \"directoryHash\", \"pageSetHash\",\n ], \"PVOX binary-closure hash input\");\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_BINARY_CLOSURE_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.sourceContentHash, \"sourceContentHash\"),\n decodePvoxSha256HexV1(input.canonicalDocumentHash, \"canonicalDocumentHash\"),\n decodePvoxSha256HexV1(input.compilationInputHash, \"compilationInputHash\"),\n decodePvoxSha256HexV1(input.runtimeRequestProfileHash, \"runtimeRequestProfileHash\"),\n decodePvoxSha256HexV1(input.artifactSha256, \"artifactSha256\"),\n decodePvoxSha256HexV1(input.rootHash, \"rootHash\"),\n decodePvoxSha256HexV1(input.directoryHash, \"directoryHash\"),\n decodePvoxSha256HexV1(input.pageSetHash, \"pageSetHash\"),\n ]);\n}\n\nexport function encodePvoxCapabilitySetHashPreimageV1(\n subjectBinaryClosureHash: string,\n orderedCanonicalAssessments: readonly unknown[],\n): Uint8Array {\n preflightPvoxArrayCardinality(\n orderedCanonicalAssessments,\n PVOX_CAPABILITIES.length,\n PVOX_CAPABILITIES.length,\n \"Capability hash input\",\n );\n const assessments = normalizeJsonData(orderedCanonicalAssessments);\n if (!Array.isArray(assessments) || assessments.length !== PVOX_CAPABILITIES.length) {\n throw new Error(\"Capability hash input must contain every governed capability in canonical order.\");\n }\n assessments.forEach((assessment, index) => {\n if (assessment === null || typeof assessment !== \"object\" || Array.isArray(assessment)\n || (assessment as Record<string, unknown>).capability !== PVOX_CAPABILITIES[index]) {\n throw new Error(\"Capability hash input must contain every governed capability in canonical order.\");\n }\n });\n const encoded = encodeCanonicalJsonRecords(assessments);\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_CAPABILITY_SET_HASH_DOMAIN),\n decodePvoxSha256HexV1(subjectBinaryClosureHash, \"subjectBinaryClosureHash\"),\n encodePvoxU32LeV1(encoded.length),\n ...encoded,\n ]);\n}\n\nexport function encodePvoxPhysicalInventoryHashPreimageV1(input: PvoxPhysicalInventoryHashInputV1): Uint8Array {\n const shallowInput = preflightPvoxFixedObject(\n input,\n [\"inventoryVersion\", \"subjectBinaryClosureHash\", \"validationEvidenceHash\", \"entries\"],\n \"PVOX physical-inventory hash input\",\n );\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"entries\"),\n 1,\n PVOX_DEFAULT_LIMITS.maximumMaterialRegions,\n \"PVOX physical-inventory hash input.entries\",\n );\n assertPvoxPreimageDataOnly(input, \"PVOX physical-inventory hash input\");\n assertExactPvoxPreimageKeys(input, [\"inventoryVersion\", \"subjectBinaryClosureHash\", \"validationEvidenceHash\", \"entries\"], \"PVOX physical-inventory hash input\");\n if (input.entries.length < 1 || input.entries.length > PVOX_DEFAULT_LIMITS.maximumMaterialRegions) throw new Error(\"Physical inventory must fit the governed material-region limit.\");\n const encoded = input.entries.map((record, index) => {\n assertExactPvoxPreimageKeys(record, [\"regionIndex\", \"physicalPaletteIndex\", \"regionId\", \"materialId\"], `entries[${index}]`);\n const regionIndex = assertSafeIntegerInRange(record.regionIndex, 0, U32_MAXIMUM, `entries[${index}].regionIndex`);\n if (regionIndex !== index) throw new Error(\"Physical inventory records must have contiguous canonical region indexes starting at zero.\");\n return concatenateBytes([\n encodePvoxU32LeV1(regionIndex),\n encodePvoxU32LeV1(record.physicalPaletteIndex),\n encodePvoxCanonicalUtf8V1(record.regionId),\n encodePvoxCanonicalUtf8V1(record.materialId),\n ]);\n });\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_PHYSICAL_INVENTORY_HASH_DOMAIN),\n encodePvoxCanonicalUtf8V1(input.inventoryVersion),\n decodePvoxSha256HexV1(input.subjectBinaryClosureHash, \"subjectBinaryClosureHash\"),\n decodePvoxSha256HexV1(input.validationEvidenceHash, \"validationEvidenceHash\"),\n encodePvoxU32LeV1(input.entries.length),\n ...encoded,\n ]);\n}\n\nexport function encodePvoxPhysicalEvidenceHashPreimageV1(input: PvoxPhysicalEvidenceHashInputV1): Uint8Array {\n const shallowInput = preflightPvoxFixedObject(\n input,\n [\"physicalInventoryHash\", \"orderedRegionMaterials\", \"orderedCanonicalEvidence\"],\n \"PVOX physical-evidence hash input\",\n );\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"orderedRegionMaterials\"),\n 1,\n PVOX_DEFAULT_LIMITS.maximumMaterialRegions,\n \"PVOX physical-evidence hash input.orderedRegionMaterials\",\n );\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"orderedCanonicalEvidence\"),\n 0,\n PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries,\n \"PVOX physical-evidence hash input.orderedCanonicalEvidence\",\n );\n assertPvoxPreimageDataOnly(input, \"PVOX physical-evidence hash input\");\n assertExactPvoxPreimageKeys(input, [\"physicalInventoryHash\", \"orderedRegionMaterials\", \"orderedCanonicalEvidence\"], \"PVOX physical-evidence hash input\");\n if (input.orderedRegionMaterials.length < 1 || input.orderedRegionMaterials.length > PVOX_DEFAULT_LIMITS.maximumMaterialRegions) {\n throw new Error(\"Physical evidence region/material validation context must fit the governed material-region limit.\");\n }\n const regionOrder = new Map<string, number>();\n input.orderedRegionMaterials.forEach((regionMaterial, index) => {\n assertExactPvoxPreimageKeys(regionMaterial, [\"regionId\", \"materialId\"], `orderedRegionMaterials[${index}]`);\n const { regionId, materialId } = regionMaterial;\n const key = `${regionId}\\u0000${materialId}`;\n if (regionOrder.has(key)) throw new Error(\"Physical evidence region/material validation context must be unique and canonical.\");\n regionOrder.set(key, index);\n });\n const normalizedEvidence = normalizeJsonData(input.orderedCanonicalEvidence);\n if (!Array.isArray(normalizedEvidence) || normalizedEvidence.length > PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries) throw new Error(\"Physical evidence must be a bounded canonical array.\");\n let previousOrder = -1;\n for (const [index, evidence] of normalizedEvidence.entries()) {\n if (evidence === null || typeof evidence !== \"object\" || Array.isArray(evidence)) throw new Error(`Physical evidence[${index}] must be an object.`);\n const record = evidence as Record<string, unknown>;\n if (typeof record.regionId !== \"string\" || typeof record.materialId !== \"string\" || typeof record.property !== \"string\") {\n throw new Error(`Physical evidence[${index}] must declare regionId, materialId, and property.`);\n }\n const regionIndex = regionOrder.get(`${record.regionId}\\u0000${record.materialId}`);\n const propertyIndex = (PVOX_PHYSICAL_PROPERTIES as readonly string[]).indexOf(record.property);\n if (regionIndex === undefined || propertyIndex < 0) throw new Error(`Physical evidence[${index}] is absent from the governed inventory/property registry.`);\n const order = regionIndex * PVOX_PHYSICAL_PROPERTIES.length + propertyIndex;\n if (order <= previousOrder) throw new Error(\"Physical evidence must use canonical inventory-region and governed-property order.\");\n previousOrder = order;\n }\n const encoded = encodeCanonicalJsonRecords(normalizedEvidence);\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_PHYSICAL_EVIDENCE_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.physicalInventoryHash, \"physicalInventoryHash\"),\n encodePvoxU32LeV1(encoded.length),\n ...encoded,\n ]);\n}\n\nexport function encodePvoxEvaluationClosureHashPreimageV1(input: PvoxEvaluationClosureHashInputV1): Uint8Array {\n assertPvoxPreimageDataOnly(input, \"PVOX evaluation-closure hash input\");\n assertExactPvoxPreimageKeys(input, [\"fidelityEvidenceHash\", \"physicalEvidenceHash\", \"capabilitySetHash\", \"renderEvidenceHash\"], \"PVOX evaluation-closure hash input\");\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_EVALUATION_CLOSURE_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.fidelityEvidenceHash, \"fidelityEvidenceHash\"),\n decodePvoxSha256HexV1(input.physicalEvidenceHash, \"physicalEvidenceHash\"),\n decodePvoxSha256HexV1(input.capabilitySetHash, \"capabilitySetHash\"),\n decodePvoxSha256HexV1(input.renderEvidenceHash, \"renderEvidenceHash\"),\n ]);\n}\n\nexport function encodePvoxProcessingClosureHashPreimageV1(input: PvoxProcessingClosureHashInputV1): Uint8Array {\n assertPvoxPreimageDataOnly(input, \"PVOX processing-closure hash input\");\n assertExactPvoxPreimageKeys(input, [\n \"binaryClosureHash\", \"requestSemanticProfileHash\", \"technicalProfile\", \"pvoxValidationEvidenceHash\",\n \"physicalInventoryValidationEvidenceHash\", \"capabilitySetHash\", \"physicalInventoryHash\",\n \"physicalEvidenceHash\", \"massPropertiesEvidenceHash\", \"bondGraphEvidenceHash\",\n \"interiorLayerEvidenceHash\", \"compilerEvidenceHash\", \"fidelityEvidenceHash\",\n ], \"PVOX processing-closure hash input\");\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_PROCESSING_CLOSURE_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.binaryClosureHash, \"binaryClosureHash\"),\n decodePvoxSha256HexV1(input.requestSemanticProfileHash, \"requestSemanticProfileHash\"),\n encodeCanonicalJsonRecord(input.technicalProfile),\n decodePvoxSha256HexV1(input.pvoxValidationEvidenceHash, \"pvoxValidationEvidenceHash\"),\n decodePvoxSha256HexV1(input.physicalInventoryValidationEvidenceHash, \"physicalInventoryValidationEvidenceHash\"),\n decodePvoxSha256HexV1(input.capabilitySetHash, \"capabilitySetHash\"),\n decodePvoxSha256HexV1(input.physicalInventoryHash, \"physicalInventoryHash\"),\n decodePvoxSha256HexV1(input.physicalEvidenceHash, \"physicalEvidenceHash\"),\n decodePvoxSha256HexV1(input.massPropertiesEvidenceHash, \"massPropertiesEvidenceHash\"),\n decodePvoxSha256HexV1(input.bondGraphEvidenceHash, \"bondGraphEvidenceHash\"),\n decodePvoxSha256HexV1(input.interiorLayerEvidenceHash, \"interiorLayerEvidenceHash\"),\n decodePvoxSha256HexV1(input.compilerEvidenceHash, \"compilerEvidenceHash\"),\n decodePvoxSha256HexV1(input.fidelityEvidenceHash, \"fidelityEvidenceHash\"),\n ]);\n}\n\nexport function encodePvoxAssemblyClosureHashPreimageV1(input: PvoxAssemblyClosureHashInputV1): Uint8Array {\n const shallowInput = preflightPvoxFixedObject(input, [\"ownBinaryClosureHash\", \"orderedChildren\"], \"PVOX assembly-closure hash input\");\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"orderedChildren\"),\n 0,\n PVOX_DEFAULT_LIMITS.maximumAssemblyChildren,\n \"PVOX assembly-closure hash input.orderedChildren\",\n );\n assertPvoxPreimageDataOnly(input, \"PVOX assembly-closure hash input\");\n assertExactPvoxPreimageKeys(input, [\"ownBinaryClosureHash\", \"orderedChildren\"], \"PVOX assembly-closure hash input\");\n const children = normalizeJsonData(input.orderedChildren);\n if (!Array.isArray(children) || children.length > PVOX_DEFAULT_LIMITS.maximumAssemblyChildren) throw new Error(\"orderedChildren must be a canonical JSON array within the governed assembly-child limit.\");\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_ASSEMBLY_CLOSURE_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.ownBinaryClosureHash, \"ownBinaryClosureHash\"),\n encodePvoxU32LeV1(children.length),\n encodePvoxCanonicalUtf8V1(canonicalizeGpuContract(children)),\n ]);\n}\n\nexport function encodePvoxEditOverlayRootHashPreimageV1(input: PvoxEditOverlayRootHashInputV1): Uint8Array {\n const shallowInput = preflightPvoxFixedObject(input, [\n \"baseContentHash\", \"basePageSetHash\", \"placementId\", \"gridVersion\", \"expectedRevision\",\n \"resultingRevision\", \"previousJournalHash\", \"expectedRootHash\", \"orderedPatches\",\n ], \"PVOX edit-overlay hash input\");\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"orderedPatches\"),\n 1,\n PVOX_MAX_EDIT_PATCHES,\n \"PVOX edit-overlay hash input.orderedPatches\",\n );\n assertPvoxPreimageDataOnly(input, \"PVOX edit-overlay hash input\");\n assertExactPvoxPreimageKeys(input, [\n \"baseContentHash\", \"basePageSetHash\", \"placementId\", \"gridVersion\", \"expectedRevision\",\n \"resultingRevision\", \"previousJournalHash\", \"expectedRootHash\", \"orderedPatches\",\n ], \"PVOX edit-overlay hash input\");\n const expectedRevision = asUnsignedBigInt(input.expectedRevision, \"expectedRevision\");\n const resultingRevision = asUnsignedBigInt(input.resultingRevision, \"resultingRevision\");\n if (resultingRevision !== expectedRevision + 1n) throw new Error(\"Edit-overlay revisions must be sequential.\");\n const normalizedPatches = normalizeJsonData(input.orderedPatches);\n if (!Array.isArray(normalizedPatches) || normalizedPatches.length < 1 || normalizedPatches.length > PVOX_MAX_EDIT_PATCHES) {\n throw new Error(\"Edit-overlay patches must be a bounded non-empty canonical array.\");\n }\n const requiredKeys = [\n \"fieldKind\", \"lodLevel\", \"partitionIndex\", \"hierarchyDepth\", \"mortonCode\", \"expectedPageIndex\",\n \"expectedPageHash\", \"operation\", \"expectedBrickHash\", \"resultingBrickHash\", \"resultingPageHash\",\n ] as const;\n let previousAddress = \"\";\n const pageIndexes = new Set<number>();\n normalizedPatches.forEach((patch, index) => {\n if (patch === null || typeof patch !== \"object\" || Array.isArray(patch)) throw new Error(`Edit-overlay patch[${index}] must be an object.`);\n const record = patch as Record<string, unknown>;\n if (Object.keys(record).length !== requiredKeys.length || requiredKeys.some((key) => !(key in record))) throw new Error(`Edit-overlay patch[${index}] must contain the complete fixed patch address and transition.`);\n if (record.fieldKind !== \"render-field\" && record.fieldKind !== \"collision-field\") throw new Error(`Edit-overlay patch[${index}].fieldKind is invalid.`);\n const lodLevel = assertSafeIntegerInRange(record.lodLevel as number, 0, PVOX_DEFAULT_LIMITS.maximumLodCount - 1, `orderedPatches[${index}].lodLevel`);\n const partitionIndex = assertSafeIntegerInRange(record.partitionIndex as number, 0, PVOX_DEFAULT_LIMITS.maximumPartitions - 1, `orderedPatches[${index}].partitionIndex`);\n const hierarchyDepth = assertSafeIntegerInRange(record.hierarchyDepth as number, 0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth, `orderedPatches[${index}].hierarchyDepth`);\n if (typeof record.mortonCode !== \"string\" || !/^[0-9a-f]{16}$/u.test(record.mortonCode)) throw new Error(`Edit-overlay patch[${index}].mortonCode is invalid.`);\n const expectedPageIndex = assertSafeIntegerInRange(record.expectedPageIndex as number, 0, PVOX_DEFAULT_LIMITS.maximumPages - 1, `orderedPatches[${index}].expectedPageIndex`);\n if (pageIndexes.has(expectedPageIndex)) throw new Error(\"Edit-overlay permits only one transition per page.\");\n pageIndexes.add(expectedPageIndex);\n const expectedPageHash = decodePvoxSha256HexV1(record.expectedPageHash as string, `orderedPatches[${index}].expectedPageHash`);\n const resultingPageHash = decodePvoxSha256HexV1(record.resultingPageHash as string, `orderedPatches[${index}].resultingPageHash`);\n if (expectedPageHash.every((value, offset) => value === resultingPageHash[offset])) throw new Error(\"Edit-overlay page transitions must change the page hash.\");\n const expectedBrickHash = record.expectedBrickHash as string;\n const resultingBrickHash = record.resultingBrickHash as string;\n decodePvoxSha256HexV1(expectedBrickHash, `orderedPatches[${index}].expectedBrickHash`);\n decodePvoxSha256HexV1(resultingBrickHash, `orderedPatches[${index}].resultingBrickHash`);\n if (record.operation === \"insert\") {\n if (expectedBrickHash !== PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH) throw new Error(\"Edit-overlay insert must change an empty brick to a non-empty result.\");\n } else if (record.operation === \"remove\") {\n if (expectedBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash !== PVOX_EDIT_JOURNAL_GENESIS_HASH) throw new Error(\"Edit-overlay remove must change a non-empty brick to the empty result.\");\n } else if (record.operation === \"replace\") {\n if (expectedBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || expectedBrickHash === resultingBrickHash) throw new Error(\"Edit-overlay replace must change one non-empty brick to another.\");\n } else {\n throw new Error(`Edit-overlay patch[${index}].operation is invalid.`);\n }\n const address = [record.fieldKind, String(lodLevel).padStart(2, \"0\"), String(partitionIndex).padStart(6, \"0\"), String(hierarchyDepth).padStart(2, \"0\"), record.mortonCode].join(\"\\u0000\");\n if (index > 0 && address <= previousAddress) throw new Error(\"Edit-overlay patches must be unique and canonically ordered by their complete spatial address.\");\n previousAddress = address;\n });\n const patches = encodeCanonicalJsonRecords(normalizedPatches);\n return concatenateBytes([\n TEXT_ENCODER.encode(PVOX_EDIT_OVERLAY_ROOT_HASH_DOMAIN),\n decodePvoxSha256HexV1(input.baseContentHash, \"baseContentHash\"),\n decodePvoxSha256HexV1(input.basePageSetHash, \"basePageSetHash\"),\n encodePvoxCanonicalUtf8V1(input.placementId),\n encodePvoxCanonicalUtf8V1(input.gridVersion),\n encodePvoxU64LeV1(expectedRevision),\n encodePvoxU64LeV1(resultingRevision),\n decodePvoxSha256HexV1(input.previousJournalHash, \"previousJournalHash\"),\n decodePvoxSha256HexV1(input.expectedRootHash, \"expectedRootHash\"),\n encodePvoxU32LeV1(patches.length),\n ...patches,\n ]);\n}\n\nexport function encodePvoxRootHeaderV1(input: PvoxRootHeaderInputV1): Uint8Array {\n const rootHeaderKeys = [\n \"sectionCount\", \"artifactByteLength\", \"directoryByteOffset\", \"directoryByteLength\", \"pageCount\",\n \"maximumHierarchyDepth\", \"geometryMode\", \"fixedPointFractionBits\", \"quantizedBounds\",\n \"directoryStartPage\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"directoryHash\",\n ] as const;\n const shallowInput = preflightPvoxFixedObject(input, rootHeaderKeys, \"PVOX root-header input\");\n preflightPvoxArrayCardinality(\n getPreflightPvoxDataProperty(shallowInput, \"quantizedBounds\"),\n PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT,\n PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT,\n \"quantizedBounds\",\n );\n assertPvoxPreimageDataOnly(input, \"PVOX root-header input\");\n assertExactPvoxPreimageKeys(input, rootHeaderKeys, \"PVOX root-header input\");\n if (!Array.isArray(input.quantizedBounds)\n || input.quantizedBounds.length !== PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT\n || input.quantizedBounds.some((component) => typeof component !== \"bigint\")) {\n throw new Error(\"quantizedBounds must contain exactly six bigint components.\");\n }\n const sectionCount = assertSafeIntegerInRange(input.sectionCount, 1, PVOX_MAX_SECTIONS, \"sectionCount\");\n const artifactByteLength = asUnsignedBigInt(input.artifactByteLength, \"artifactByteLength\");\n const directoryByteOffset = asUnsignedBigInt(input.directoryByteOffset, \"directoryByteOffset\");\n const directoryByteLength = asUnsignedBigInt(input.directoryByteLength, \"directoryByteLength\");\n const expectedDirectoryByteLength = BigInt(sectionCount * PVOX_DIRECTORY_ENTRY_BYTE_LENGTH);\n if (directoryByteLength !== expectedDirectoryByteLength) throw new Error(\"directoryByteLength must match sectionCount fixed-width entries.\");\n if (directoryByteOffset < BigInt(PVOX_HEADER_BYTE_LENGTH)\n || directoryByteOffset % BigInt(PVOX_SECTION_ALIGNMENT_BYTES) !== 0n) {\n throw new Error(\"directoryByteOffset must follow the header and satisfy PVOX section alignment.\");\n }\n if (artifactByteLength < directoryByteOffset + directoryByteLength) {\n throw new Error(\"artifactByteLength cannot end before the directory.\");\n }\n const pageCount = assertSafeIntegerInRange(input.pageCount, 1, PVOX_DEFAULT_LIMITS.maximumPages, \"pageCount\");\n if (artifactByteLength > BigInt(PVOX_DEFAULT_LIMITS.maximumArtifactBytes)\n || artifactByteLength !== BigInt(pageCount) * BigInt(PVOX_PAGE_SIZE_BYTES)) {\n throw new Error(\"artifactByteLength must equal pageCount multiplied by the fixed PVOX page size and fit the governed ceiling.\");\n }\n const maximumHierarchyDepth = assertSafeIntegerInRange(input.maximumHierarchyDepth, 0, PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_V1, \"maximumHierarchyDepth\");\n const fixedPointFractionBits = assertSafeIntegerInRange(input.fixedPointFractionBits, PVOX_ROOT_HEADER_MINIMUM_FIXED_POINT_FRACTION_BITS_V1, PVOX_ROOT_HEADER_MAXIMUM_FIXED_POINT_FRACTION_BITS_V1, \"fixedPointFractionBits\");\n const directoryStartPage = assertSafeIntegerInRange(input.directoryStartPage, 0, U32_MAXIMUM, \"directoryStartPage\");\n const expectedDirectoryStartPage = Number(directoryByteOffset / BigInt(PVOX_PAGE_SIZE_BYTES));\n if (directoryStartPage !== expectedDirectoryStartPage || directoryStartPage >= pageCount) throw new Error(\"directoryStartPage must identify a page containing directoryByteOffset.\");\n for (let axis = 0; axis < PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT / 2; axis += 1) {\n if (input.quantizedBounds[axis]! >= input.quantizedBounds[axis + 3]!) {\n throw new Error(\"quantizedBounds minima must be below their corresponding maxima.\");\n }\n }\n\n const output = new Uint8Array(PVOX_HEADER_BYTE_LENGTH);\n const view = new DataView(output.buffer);\n writeBytes(output, PVOX_ROOT_HEADER_MAGIC_OFFSET, PVOX_MAGIC_BYTES);\n view.setUint16(PVOX_ROOT_HEADER_FORMAT_MAJOR_OFFSET, PVOX_FORMAT_VERSION.major, true);\n view.setUint16(PVOX_ROOT_HEADER_FORMAT_MINOR_OFFSET, PVOX_FORMAT_VERSION.minor, true);\n view.setUint16(PVOX_ROOT_HEADER_BYTE_LENGTH_OFFSET, PVOX_HEADER_BYTE_LENGTH, true);\n view.setUint16(PVOX_ROOT_HEADER_DIRECTORY_ENTRY_BYTE_LENGTH_OFFSET, PVOX_DIRECTORY_ENTRY_BYTE_LENGTH, true);\n view.setUint16(PVOX_ROOT_HEADER_SECTION_COUNT_OFFSET, sectionCount, true);\n view.setUint16(PVOX_ROOT_HEADER_FLAGS_OFFSET, PVOX_ROOT_HEADER_FLAGS_V1, true);\n view.setBigUint64(PVOX_ROOT_HEADER_ARTIFACT_BYTE_LENGTH_OFFSET, artifactByteLength, true);\n view.setBigUint64(PVOX_ROOT_HEADER_DIRECTORY_BYTE_OFFSET_OFFSET, directoryByteOffset, true);\n view.setBigUint64(PVOX_ROOT_HEADER_DIRECTORY_BYTE_LENGTH_OFFSET, directoryByteLength, true);\n view.setUint32(PVOX_ROOT_HEADER_PAGE_SIZE_OFFSET, PVOX_PAGE_SIZE_BYTES, true);\n view.setUint32(PVOX_ROOT_HEADER_PAGE_COUNT_OFFSET, pageCount, true);\n view.setUint16(PVOX_ROOT_HEADER_BRICK_EDGE_OFFSET, PVOX_BRICK_EDGE_VOXELS, true);\n view.setUint8(PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_OFFSET, maximumHierarchyDepth);\n view.setUint8(PVOX_ROOT_HEADER_GEOMETRY_MODE_OFFSET, PVOX_ROOT_HEADER_GEOMETRY_MODE_CODES_V1[input.geometryMode]);\n view.setUint32(PVOX_ROOT_HEADER_COORDINATE_BASIS_OFFSET, PVOX_ROOT_HEADER_COORDINATE_BASIS_METRES_Y_UP_NEGATIVE_Z_FORWARD_CCW, true);\n view.setUint16(PVOX_ROOT_HEADER_FIXED_POINT_FRACTION_BITS_OFFSET, fixedPointFractionBits, true);\n input.quantizedBounds.forEach((component, index) => {\n view.setBigInt64(PVOX_ROOT_HEADER_BOUNDS_OFFSET + index * PVOX_ROOT_HEADER_BOUND_COMPONENT_BYTE_LENGTH, assertQuantizedCoordinate(component, fixedPointFractionBits, `quantizedBounds[${index}]`), true);\n });\n view.setUint32(PVOX_ROOT_HEADER_DIRECTORY_START_PAGE_OFFSET, directoryStartPage, true);\n writeBytes(output, PVOX_ROOT_HEADER_COMPILATION_INPUT_HASH_OFFSET, decodePvoxSha256HexV1(input.compilationInputHash, \"compilationInputHash\"));\n writeBytes(output, PVOX_ROOT_HEADER_RUNTIME_REQUEST_PROFILE_HASH_OFFSET, decodePvoxSha256HexV1(input.runtimeRequestProfileHash, \"runtimeRequestProfileHash\"));\n writeBytes(output, PVOX_ROOT_HEADER_DIRECTORY_HASH_OFFSET, decodePvoxSha256HexV1(input.directoryHash, \"directoryHash\"));\n return output;\n}\n\n/** Validates the exact header and returns a defensive copy; reserved bytes are rejected, never silently rewritten. */\nexport function normalizePvoxRootHeaderForHashV1(exactHeader: Uint8Array): Uint8Array {\n const output = copyPvoxByteInput(exactHeader, \"PVOX root header\", PVOX_HEADER_BYTE_LENGTH);\n if (output.byteLength !== PVOX_HEADER_BYTE_LENGTH) throw new Error(`PVOX root header must be exactly ${PVOX_HEADER_BYTE_LENGTH} bytes.`);\n const view = new DataView(output.buffer, output.byteOffset, output.byteLength);\n if (readAscii(output, PVOX_ROOT_HEADER_MAGIC_OFFSET, PVOX_MAGIC_BYTES.byteLength) !== PVOX_MAGIC) throw new Error(\"PVOX root header magic is invalid.\");\n if (view.getUint16(PVOX_ROOT_HEADER_FORMAT_MAJOR_OFFSET, true) !== PVOX_FORMAT_VERSION.major\n || view.getUint16(PVOX_ROOT_HEADER_FORMAT_MINOR_OFFSET, true) !== PVOX_FORMAT_VERSION.minor) throw new Error(\"PVOX root header version is unsupported.\");\n if (view.getUint16(PVOX_ROOT_HEADER_BYTE_LENGTH_OFFSET, true) !== PVOX_HEADER_BYTE_LENGTH\n || view.getUint16(PVOX_ROOT_HEADER_DIRECTORY_ENTRY_BYTE_LENGTH_OFFSET, true) !== PVOX_DIRECTORY_ENTRY_BYTE_LENGTH) throw new Error(\"PVOX root header fixed-width declarations are invalid.\");\n const sectionCount = view.getUint16(PVOX_ROOT_HEADER_SECTION_COUNT_OFFSET, true);\n if (sectionCount < 1 || sectionCount > PVOX_MAX_SECTIONS) throw new Error(\"PVOX root header sectionCount is invalid.\");\n if (view.getUint16(PVOX_ROOT_HEADER_FLAGS_OFFSET, true) !== PVOX_ROOT_HEADER_FLAGS_V1) throw new Error(\"PVOX root header contains unknown flags.\");\n const directoryByteOffset = view.getBigUint64(PVOX_ROOT_HEADER_DIRECTORY_BYTE_OFFSET_OFFSET, true);\n const directoryByteLength = view.getBigUint64(PVOX_ROOT_HEADER_DIRECTORY_BYTE_LENGTH_OFFSET, true);\n if (directoryByteOffset < BigInt(PVOX_HEADER_BYTE_LENGTH)\n || directoryByteOffset % BigInt(PVOX_SECTION_ALIGNMENT_BYTES) !== 0n\n || directoryByteLength !== BigInt(sectionCount * PVOX_DIRECTORY_ENTRY_BYTE_LENGTH)) throw new Error(\"PVOX root header directory layout is invalid.\");\n const artifactByteLength = view.getBigUint64(PVOX_ROOT_HEADER_ARTIFACT_BYTE_LENGTH_OFFSET, true);\n const pageCount = view.getUint32(PVOX_ROOT_HEADER_PAGE_COUNT_OFFSET, true);\n if (artifactByteLength < directoryByteOffset + directoryByteLength\n || artifactByteLength > BigInt(PVOX_DEFAULT_LIMITS.maximumArtifactBytes)\n || pageCount < 1\n || pageCount > PVOX_DEFAULT_LIMITS.maximumPages\n || artifactByteLength !== BigInt(pageCount) * BigInt(PVOX_PAGE_SIZE_BYTES)) throw new Error(\"PVOX root header artifact/page accounting is invalid.\");\n if (view.getUint32(PVOX_ROOT_HEADER_PAGE_SIZE_OFFSET, true) !== PVOX_PAGE_SIZE_BYTES\n || view.getUint16(PVOX_ROOT_HEADER_BRICK_EDGE_OFFSET, true) !== PVOX_BRICK_EDGE_VOXELS) throw new Error(\"PVOX root header runtime layout is invalid.\");\n if (view.getUint8(PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_OFFSET) > PVOX_ROOT_HEADER_MAXIMUM_HIERARCHY_DEPTH_V1\n || !Object.values(PVOX_ROOT_HEADER_GEOMETRY_MODE_CODES_V1).includes(view.getUint8(PVOX_ROOT_HEADER_GEOMETRY_MODE_OFFSET) as 1 | 2 | 3)\n || view.getUint32(PVOX_ROOT_HEADER_COORDINATE_BASIS_OFFSET, true) !== PVOX_ROOT_HEADER_COORDINATE_BASIS_METRES_Y_UP_NEGATIVE_Z_FORWARD_CCW\n || view.getUint16(PVOX_ROOT_HEADER_FIXED_POINT_FRACTION_BITS_OFFSET, true) > PVOX_ROOT_HEADER_MAXIMUM_FIXED_POINT_FRACTION_BITS_V1) throw new Error(\"PVOX root header geometry layout is invalid.\");\n const expectedDirectoryStartPage = Number(directoryByteOffset / BigInt(PVOX_PAGE_SIZE_BYTES));\n if (view.getUint32(PVOX_ROOT_HEADER_DIRECTORY_START_PAGE_OFFSET, true) !== expectedDirectoryStartPage || expectedDirectoryStartPage >= pageCount) throw new Error(\"PVOX root header directory page binding is invalid.\");\n const fractionBits = view.getUint16(PVOX_ROOT_HEADER_FIXED_POINT_FRACTION_BITS_OFFSET, true);\n for (let axis = 0; axis < PVOX_ROOT_HEADER_BOUND_COMPONENT_COUNT / 2; axis += 1) {\n const minimum = assertQuantizedCoordinate(view.getBigInt64(PVOX_ROOT_HEADER_BOUNDS_OFFSET + axis * PVOX_ROOT_HEADER_BOUND_COMPONENT_BYTE_LENGTH, true), fractionBits, `quantizedBounds[${axis}]`);\n const maximum = assertQuantizedCoordinate(view.getBigInt64(PVOX_ROOT_HEADER_BOUNDS_OFFSET + (axis + 3) * PVOX_ROOT_HEADER_BOUND_COMPONENT_BYTE_LENGTH, true), fractionBits, `quantizedBounds[${axis + 3}]`);\n if (minimum >= maximum) throw new Error(\"PVOX root header quantized bounds are invalid.\");\n }\n if (!isZeroRange(output, PVOX_ROOT_HEADER_INLINE_RESERVED_OFFSET, PVOX_ROOT_HEADER_INLINE_RESERVED_BYTE_LENGTH)\n || !isZeroRange(output, PVOX_ROOT_HEADER_TRAILING_RESERVED_OFFSET, PVOX_ROOT_HEADER_TRAILING_RESERVED_BYTE_LENGTH)) throw new Error(\"PVOX root header reserved bytes must be zero.\");\n return output;\n}\n\nexport function encodePvoxRootHashPreimageV1(\n exactHeader: Uint8Array,\n orderedSectionHashes: readonly PvoxRootSectionHashRecordV1[],\n): Uint8Array {\n preflightPvoxArrayCardinality(orderedSectionHashes, 1, PVOX_MAX_SECTIONS, \"PVOX root section-hash input\");\n assertPvoxPreimageDataOnly(orderedSectionHashes, \"PVOX root section-hash input\");\n const header = normalizePvoxRootHeaderForHashV1(exactHeader);\n const sectionCount = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint16(PVOX_ROOT_HEADER_SECTION_COUNT_OFFSET, true);\n if (orderedSectionHashes.length !== sectionCount) throw new Error(\"Root section hashes must match the header sectionCount.\");\n let previousKey = -1n;\n const sections = orderedSectionHashes.map((record, index) => {\n assertExactPvoxPreimageKeys(record, [\"sectionType\", \"sectionVersion\", \"sectionHash\"], `orderedSectionHashes[${index}]`);\n const sectionType = assertSafeIntegerInRange(record.sectionType, 0, U32_MAXIMUM, `orderedSectionHashes[${index}].sectionType`);\n const sectionVersion = assertSafeIntegerInRange(record.sectionVersion, 0, U16_MAXIMUM, `orderedSectionHashes[${index}].sectionVersion`);\n const key = (BigInt(sectionType) << 16n) | BigInt(sectionVersion);\n if (key <= previousKey) throw new Error(\"Root section hashes must be unique and strictly ordered by type then version.\");\n previousKey = key;\n return concatenateBytes([\n encodePvoxU32LeV1(sectionType),\n encodePvoxU16LeV1(sectionVersion),\n decodePvoxSha256HexV1(record.sectionHash, `orderedSectionHashes[${index}].sectionHash`),\n ]);\n });\n return concatenateBytes([TEXT_ENCODER.encode(PVOX_ROOT_HASH_DOMAIN), header, ...sections]);\n}\n\nfunction escapeJsonPointerSegment(value: string): string {\n return value.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nfunction cloneProjectedData(\n value: unknown,\n pointer: string,\n omittedPointers: ReadonlySet<string>,\n seen: WeakSet<object>,\n depth = 0,\n state = { nodes: 0 },\n): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new Error(\"PVOX hash projections require finite JSON numbers.\");\n return value;\n }\n if (typeof value !== \"object\") throw new Error(\"PVOX hash projections accept JSON data only.\");\n state.nodes += 1;\n if (depth > 64 || state.nodes > PVOX_MAX_HASH_PREIMAGE_DATA_NODES_V1) throw new Error(\"PVOX hash projections must be bounded data trees.\");\n if (seen.has(value)) throw new Error(\"PVOX hash projections cannot contain cycles or shared object references.\");\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n state.nodes += value.length;\n if (state.nodes > PVOX_MAX_HASH_PREIMAGE_DATA_NODES_V1) throw new Error(\"PVOX hash projections must be bounded data trees.\");\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Reflect.ownKeys(descriptors);\n if (keys.some((key) => typeof key === \"symbol\" || (key !== \"length\" && !/^(0|[1-9][0-9]*)$/u.test(key)))) throw new Error(\"PVOX hash projection arrays cannot contain named or symbol properties.\");\n const output: unknown[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = descriptors[String(index)];\n if (!descriptor || descriptor.get || descriptor.set || !descriptor.enumerable) throw new Error(\"PVOX hash projection arrays must be dense enumerable data.\");\n const childPointer = `${pointer}/${index}`;\n if (omittedPointers.has(childPointer)) throw new Error(\"PVOX named omissions cannot remove array positions.\");\n output.push(cloneProjectedData(descriptor.value, childPointer, omittedPointers, seen, depth + 1, state));\n }\n return output;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new Error(\"PVOX hash projection objects must have a plain or null prototype.\");\n const output = Object.create(null) as Record<string, unknown>;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") throw new Error(\"PVOX hash projection objects cannot contain symbol properties.\");\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || descriptor.get || descriptor.set || !descriptor.enumerable) throw new Error(\"PVOX hash projection objects must contain enumerable data properties only.\");\n const childPointer = `${pointer}/${escapeJsonPointerSegment(key)}`;\n if (!omittedPointers.has(childPointer)) output[key] = cloneProjectedData(descriptor.value, childPointer, omittedPointers, seen, depth + 1, state);\n }\n return output;\n } finally {\n seen.delete(value);\n }\n}\n\nexport function projectPvoxNamedJsonClosureV1(name: PvoxNamedJsonClosureV1, value: unknown): unknown {\n const spec = PVOX_NAMED_JSON_CLOSURE_SPECS_V1[name];\n return cloneProjectedData(value, \"\", new Set<string>(spec.omittedJsonPointers), new WeakSet<object>());\n}\n\nexport function canonicalizePvoxNamedJsonClosureV1(name: PvoxNamedJsonClosureV1, value: unknown): string {\n return canonicalizeGpuContract(projectPvoxNamedJsonClosureV1(name, value));\n}\n\nexport function encodePvoxNamedJsonClosurePreimageV1(name: PvoxNamedJsonClosureV1, value: unknown): Uint8Array {\n const spec = PVOX_NAMED_JSON_CLOSURE_SPECS_V1[name];\n return concatenateBytes([\n TEXT_ENCODER.encode(spec.domain),\n encodePvoxCanonicalUtf8V1(canonicalizePvoxNamedJsonClosureV1(name, value)),\n ]);\n}\n","import { canonicalizeGpuContract } from \"@plasius/gpu-shader\";\nimport { assertImmutableAssetVersion } from \"./asset-version.js\";\nimport {\n CANONICAL_MODEL_COORDINATE_SYSTEM,\n MODEL_CONFIRMATION_VIEW_KINDS,\n MODEL_CONFIRMATION_VIEW_SIZE_PX,\n MODEL_REQUEST_MAX_REVISION,\n MODEL_RESOLUTION_STATES,\n createModelAssetRef,\n createModelMatchAssessment,\n createModelProvenance,\n createModelRequestSpec,\n createModelRightsAssessment,\n type ModelAssetKind,\n type ModelAssetRef,\n type ModelBoundsMetres,\n type ModelCandidateAssetRef,\n type ModelConfirmationViews,\n type ModelDimensionsMetres,\n type ModelMatchAssessment,\n type ModelProvenance,\n type ModelRequirementPolicy,\n type ModelResolutionState,\n type ModelRightsAssessment,\n type ModelSoftPreferences,\n type ModelTransform,\n} from \"./model-resolution.js\";\n\n/** Additive contract revision used by PVOX-backed resolution payloads. */\nexport const MODEL_RESOLUTION_V2_CONTRACT_VERSION = \"2026-08-20.v2\" as const;\n\n/** Version of the public PVOX asset manifest envelope. */\nexport const PVOX_ASSET_MANIFEST_VERSION = \"plasius.pvox-asset-manifest/1\" as const;\n\n/** Version of placement-scoped PVOX edit journals. */\nexport const PVOX_EDIT_JOURNAL_VERSION = \"plasius.pvox-edit-journal/1\" as const;\nexport const PVOX_EDIT_JOURNAL_GENESIS_HASH = \"0\".repeat(64);\nexport const PVOX_MAX_EDIT_PATCHES = 4_096 as const;\nexport const PVOX_FIDELITY_PROFILE_VERSION = \"1.0.0\" as const;\nexport const PVOX_PHYSICAL_PROPERTY_POLICY_ID = \"pvox-physical-properties-v1\" as const;\nexport const PVOX_PHYSICAL_PROPERTY_POLICY_VERSION = \"1.0.0\" as const;\nexport const PVOX_NATIVE_RENDERER_ID = \"gpu-renderer\" as const;\nexport const PVOX_NATIVE_REVIEW_SETTINGS_ID = \"pvox-review-v1\" as const;\n\n/** Binary PVOX format constants shared by contracts and hosted resource metadata. */\nexport const PVOX_FORMAT_VERSION = Object.freeze({ major: 1, minor: 0 } as const);\nexport const PVOX_MAGIC = \"PVOX\" as const;\nexport const PVOX_CONTENT_TYPE = \"application/vnd.plasius.pvox\" as const;\nexport const PVOX_FILE_EXTENSION = \".pvox\" as const;\nexport const PVOX_BRICK_EDGE_VOXELS = 8 as const;\nexport const PVOX_PAGE_SIZE_BYTES = 65_536 as const;\nexport const PVOX_HEADER_BYTE_LENGTH = 256 as const;\nexport const PVOX_DIRECTORY_ENTRY_BYTE_LENGTH = 128 as const;\nexport const PVOX_SECTION_ALIGNMENT_BYTES = 256 as const;\nexport const PVOX_MAX_SECTIONS = 64 as const;\nexport const PVOX_MAX_HIERARCHY_NODES = 1_048_576 as const;\nexport const PVOX_MAX_RUNS_PER_BRICK = 512 as const;\nexport const PVOX_MAX_LOCAL_SAMPLES_PER_BRICK = 512 as const;\nexport const PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES = 10_384 as const;\nexport const PVOX_MAX_ABSOLUTE_COORDINATE_METRES = 1_048_576 as const;\n/** Conservative fixed-record lower bounds used to reject impossible manifests. */\nexport const PVOX_MIN_BRICK_DESCRIPTOR_BYTES = 96 as const;\n/** Occupancy plus active-sample masks retained even by constant render-field bricks. */\nexport const PVOX_RENDER_BRICK_MASK_BYTES = 128 as const;\nexport const PVOX_MIN_ENCODED_SURFACE_SAMPLE_BYTES = 16 as const;\n/** Collision-field samples contain the governed fixed-width signed-distance value. */\nexport const PVOX_MIN_ENCODED_COLLISION_SAMPLE_BYTES = 4 as const;\n/** Collision bricks retain the same bounded 512-voxel occupancy/sample masks. */\nexport const PVOX_COLLISION_BRICK_MASK_BYTES = 128 as const;\nexport const PVOX_PARTITION_RECORD_BYTES = 128 as const;\nexport const PVOX_LOD_RECORD_BYTES = 128 as const;\nexport const PVOX_ROOT_RECORD_BYTES = 64 as const;\nexport const PVOX_LEVEL_SPAN_RECORD_BYTES = 32 as const;\nexport const PVOX_HIERARCHY_NODE_RECORD_BYTES = 32 as const;\nexport const PVOX_SURFACE_PROPERTY_RECORD_BYTES = 128 as const;\nexport const PVOX_PHYSICAL_PROPERTY_RECORD_BYTES = 256 as const;\nexport const PVOX_PHYSICAL_EVIDENCE_RECORD_BYTES = 96 as const;\nexport const PVOX_MATERIAL_REGION_RECORD_BYTES = 128 as const;\nexport const PVOX_INTERIOR_LAYER_RECORD_BYTES = 64 as const;\nexport const PVOX_MASS_PROPERTY_RECORD_BYTES = 128 as const;\nexport const PVOX_BOND_RECORD_BYTES = 32 as const;\nexport const PVOX_MIN_STATIC_SECTION_COUNT = 13 as const;\nexport const PVOX_COLLISION_SECTION_COUNT = 5 as const;\nexport const PVOX_PHYSICAL_REGION_INVENTORY_VERSION = \"plasius.pvox-physical-region-inventory/1\" as const;\n/** Closed v1 page families. Field pages require scoped spatial keys; structural pages forbid them. */\nexport const PVOX_PAGE_KINDS = Object.freeze([\"metadata\", \"lod-structure\", \"render-field\", \"collision-field\"] as const);\n/** Domain separators for the independently implemented PVOX 1.0 hash preimages. */\nexport const PVOX_SECTION_HASH_DOMAIN = \"PVOX-SECTION-V1\\0\" as const;\nexport const PVOX_DIRECTORY_HASH_DOMAIN = \"PVOX-DIRECTORY-V1\\0\" as const;\nexport const PVOX_PAGE_SET_HASH_DOMAIN = \"PVOX-PAGESET-V1\\0\" as const;\nexport const PVOX_ROOT_HASH_DOMAIN = \"PVOX-ROOT-V1\\0\" as const;\nexport const PVOX_BINARY_CLOSURE_HASH_DOMAIN = \"PVOX-BINARY-CLOSURE-V1\\0\" as const;\nexport const PVOX_REQUEST_SEMANTIC_PROFILE_HASH_DOMAIN = \"PVOX-REQUEST-SEMANTIC-PROFILE-V1\\0\" as const;\nexport const PVOX_RUNTIME_REQUEST_PROFILE_HASH_DOMAIN = \"PVOX-RUNTIME-REQUEST-PROFILE-V1\\0\" as const;\nexport const PVOX_CAPABILITY_SET_HASH_DOMAIN = \"PVOX-CAPABILITY-SET-V1\\0\" as const;\nexport const PVOX_PHYSICAL_INVENTORY_HASH_DOMAIN = \"PVOX-PHYSICAL-INVENTORY-V1\\0\" as const;\nexport const PVOX_PHYSICAL_EVIDENCE_HASH_DOMAIN = \"PVOX-PHYSICAL-EVIDENCE-V1\\0\" as const;\nexport const PVOX_RENDER_EVIDENCE_HASH_DOMAIN = \"PVOX-RENDER-EVIDENCE-V1\\0\" as const;\nexport const PVOX_EVALUATION_CLOSURE_HASH_DOMAIN = \"PVOX-EVALUATION-CLOSURE-V1\\0\" as const;\nexport const PVOX_PROCESSING_CLOSURE_HASH_DOMAIN = \"PVOX-PROCESSING-CLOSURE-V1\\0\" as const;\nexport const PVOX_ASSEMBLY_CLOSURE_HASH_DOMAIN = \"PVOX-ASSEMBLY-CLOSURE-V1\\0\" as const;\nexport const PVOX_CONFIRMATION_BINDING_HASH_DOMAIN = \"PVOX-CONFIRMATION-BINDING-V1\\0\" as const;\nexport const PVOX_EDIT_OVERLAY_ROOT_HASH_DOMAIN = \"PVOX-EDIT-OVERLAY-ROOT-V1\\0\" as const;\nexport const PVOX_EDIT_JOURNAL_HASH_DOMAIN = \"PVOX-EDIT-JOURNAL-V1\\0\" as const;\nexport const PVOX_PUBLICATION_HASH_DOMAIN = \"PVOX-PUBLICATION-V1\\0\" as const;\nexport const PVOX_HASH_DOMAINS = Object.freeze({\n section: PVOX_SECTION_HASH_DOMAIN,\n directory: PVOX_DIRECTORY_HASH_DOMAIN,\n pageSet: PVOX_PAGE_SET_HASH_DOMAIN,\n root: PVOX_ROOT_HASH_DOMAIN,\n binaryClosure: PVOX_BINARY_CLOSURE_HASH_DOMAIN,\n requestSemanticProfile: PVOX_REQUEST_SEMANTIC_PROFILE_HASH_DOMAIN,\n runtimeRequestProfile: PVOX_RUNTIME_REQUEST_PROFILE_HASH_DOMAIN,\n capabilitySet: PVOX_CAPABILITY_SET_HASH_DOMAIN,\n physicalInventory: PVOX_PHYSICAL_INVENTORY_HASH_DOMAIN,\n physicalEvidence: PVOX_PHYSICAL_EVIDENCE_HASH_DOMAIN,\n renderEvidence: PVOX_RENDER_EVIDENCE_HASH_DOMAIN,\n evaluationClosure: PVOX_EVALUATION_CLOSURE_HASH_DOMAIN,\n processingClosure: PVOX_PROCESSING_CLOSURE_HASH_DOMAIN,\n assemblyClosure: PVOX_ASSEMBLY_CLOSURE_HASH_DOMAIN,\n confirmationBinding: PVOX_CONFIRMATION_BINDING_HASH_DOMAIN,\n editOverlayRoot: PVOX_EDIT_OVERLAY_ROOT_HASH_DOMAIN,\n editJournal: PVOX_EDIT_JOURNAL_HASH_DOMAIN,\n publication: PVOX_PUBLICATION_HASH_DOMAIN,\n} as const);\n/** Machine-readable field order; integer fields are canonical little-endian and digests are raw 32 bytes. */\nexport const PVOX_HASH_PREIMAGE_LAYOUTS = Object.freeze({\n section: Object.freeze([\"domain\", \"type:u32le\", \"version:u16le\", \"encodedLength:u64le\", \"exactSectionBytes\"] as const),\n directory: Object.freeze([\"domain\", \"entryCount:u16le\", \"entryBytes:u16le\", \"exactOrderedDirectoryBytes\"] as const),\n pageSet: Object.freeze([\"domain\", \"pageCount:u32le\", \"ordered(pageIndex:u32le,offset:u64le,length:u32le,pageSha256:raw32)\"] as const),\n root: Object.freeze([\"domain\", \"normalizedHeader:exact256bytes(sectionCount-at-12,reserved-58-59-zero,directoryHash-at-176-once,reserved-208-255-zero)\", \"ordered(sectionType:u32le,sectionVersion:u16le,sectionHash:raw32)\"] as const),\n binaryClosure: Object.freeze([\"domain\", \"sourceContentHash:raw32\", \"canonicalDocumentHash:raw32\", \"compilationInputHash:raw32\", \"runtimeRequestProfileHash:raw32\", \"artifactSha256:raw32\", \"rootHash:raw32\", \"directoryHash:raw32\", \"pageSetHash:raw32\"] as const),\n requestSemanticProfile: Object.freeze([\"domain\", \"utf8Length:u32le\", \"canonicalRequestProjection:rfc8785-utf8\"] as const),\n runtimeRequestProfile: Object.freeze([\"domain\", \"utf8Length:u32le\", \"canonicalRuntimeProfileProjection:rfc8785-utf8\"] as const),\n capabilitySet: Object.freeze([\"domain\", \"subjectBinaryClosureHash:raw32\", \"assessmentCount:u32le\", \"orderedCanonicalCapabilityAssessments:each-u32-length+rfc8785-utf8\"] as const),\n physicalInventory: Object.freeze([\"domain\", \"inventoryVersion:utf8-length-prefixed\", \"subjectBinaryClosureHash:raw32\", \"validationEvidenceHash:raw32\", \"entryCount:u32le\", \"ordered(regionIndex:u32le,physicalPaletteIndex:u32le,regionId:utf8-length-prefixed,materialId:utf8-length-prefixed)\"] as const),\n physicalEvidence: Object.freeze([\"domain\", \"physicalInventoryHash:raw32\", \"evidenceCount:u32le\", \"orderedCanonicalEvidence:each-u32-length+rfc8785-utf8\"] as const),\n renderEvidence: Object.freeze([\"domain\", \"canonicalRenderEvidenceExcludingEvidenceHashAndAttestationLength:u32le\", \"canonicalRenderEvidenceExcludingEvidenceHashAndAttestation:rfc8785-utf8\"] as const),\n evaluationClosure: Object.freeze([\"domain\", \"fidelityEvidenceHash:raw32\", \"physicalEvidenceHash:raw32\", \"capabilitySetHash:raw32\", \"renderEvidenceHash:raw32\"] as const),\n processingClosure: Object.freeze([\"domain\", \"binaryClosureHash:raw32\", \"requestSemanticProfileHash:raw32\", \"canonicalTechnicalProfileLength:u32le\", \"canonicalTechnicalProfile:rfc8785-utf8\", \"pvoxValidationEvidenceHash:raw32\", \"physicalInventoryValidationEvidenceHash:raw32\", \"capabilitySetHash:raw32\", \"physicalInventoryHash:raw32\", \"physicalEvidenceHash:raw32\", \"massPropertiesEvidenceHash:raw32\", \"bondGraphEvidenceHash:raw32\", \"interiorLayerEvidenceHash:raw32\", \"compilerEvidenceHash:raw32\", \"fidelityEvidenceHash:raw32\"] as const),\n assemblyClosure: Object.freeze([\"domain\", \"ownBinaryClosureHash:raw32\", \"childCount:u32le\", \"orderedCanonicalChildrenLength:u32le\", \"orderedCanonicalChildren:rfc8785-utf8\"] as const),\n confirmationBinding: Object.freeze([\"domain\", \"canonicalConfirmationSubjectLength:u32le\", \"canonicalConfirmationSubjectExcluding(bindingHash,bindingHashAttestation):rfc8785-utf8\"] as const),\n editOverlayRoot: Object.freeze([\"domain\", \"baseContentHash:raw32\", \"basePageSetHash:raw32\", \"placementId:utf8-length-prefixed\", \"gridVersion:utf8-length-prefixed\", \"expectedRevision:u64le\", \"resultingRevision:u64le\", \"previousJournalHash:raw32\", \"expectedRootHash:raw32\", \"patchCount:u32le\", \"orderedFullPatchAddressAndTransitions:rfc8785-each-u32-length\"] as const),\n editJournal: Object.freeze([\"domain\", \"canonicalJournalLength:u32le\", \"canonicalJournalExcluding(journalHash,journalHashAttestation,resultingRootHashAttestation):rfc8785-utf8\"] as const),\n publication: Object.freeze([\"domain\", \"canonicalPublicationLength:u32le\", \"canonicalPointerLastPublicationReceiptExcluding(publicationHash,publicationHashAttestation,publicationToken):rfc8785-utf8\"] as const),\n} as const);\n\n/** Exact root hashing rule; `PVOX_ROOT_HEADER_LAYOUT_V1` exports every byte offset. */\nexport const PVOX_ROOT_HEADER_HASH_RULE = deepFreeze({\n rootHashStorage: \"external\",\n binaryClosureHashStorage: \"external\",\n inlineReservedByteOffset: 58,\n inlineReservedByteLength: 2,\n directoryHashByteOffset: 176,\n directoryHashByteLength: 32,\n directoryHashTreatment: \"include-as-stored\",\n reservedByteOffset: 208,\n reservedByteLength: 48,\n reservedByteValue: 0,\n directoryHashOccurrencesInRootPreimage: 1,\n} as const);\n\n/** Registered PVOX 1.0 section identifiers; FourCC values are encoded little-endian. */\nexport const PVOX_SECTION_REGISTRY = deepFreeze({\n PART: { type: 0x54524150, version: 1, recordBytes: PVOX_PARTITION_RECORD_BYTES, required: true },\n LODS: { type: 0x53444f4c, version: 1, recordBytes: PVOX_LOD_RECORD_BYTES, required: true },\n ROOT: { type: 0x544f4f52, version: 1, recordBytes: PVOX_ROOT_RECORD_BYTES, required: true },\n LEVL: { type: 0x4c56454c, version: 1, recordBytes: PVOX_LEVEL_SPAN_RECORD_BYTES, required: true },\n NODE: { type: 0x45444f4e, version: 1, recordBytes: PVOX_HIERARCHY_NODE_RECORD_BYTES, required: true },\n BRIK: { type: 0x4b495242, version: 1, recordBytes: PVOX_MIN_BRICK_DESCRIPTOR_BYTES, required: true },\n DATA: { type: 0x41544144, version: 1, recordBytes: 0, required: true },\n SURF: { type: 0x46525553, version: 1, recordBytes: PVOX_SURFACE_PROPERTY_RECORD_BYTES, required: true },\n PHYS: { type: 0x53594850, version: 1, recordBytes: PVOX_PHYSICAL_PROPERTY_RECORD_BYTES, required: true },\n PEVI: { type: 0x49564550, version: 1, recordBytes: PVOX_PHYSICAL_EVIDENCE_RECORD_BYTES, required: true },\n REGN: { type: 0x4e474552, version: 1, recordBytes: PVOX_MATERIAL_REGION_RECORD_BYTES, required: true },\n LAYR: { type: 0x5259414c, version: 1, recordBytes: PVOX_INTERIOR_LAYER_RECORD_BYTES, required: true },\n MASS: { type: 0x5353414d, version: 1, recordBytes: PVOX_MASS_PROPERTY_RECORD_BYTES, required: true },\n BOND: { type: 0x444e4f42, version: 1, recordBytes: PVOX_BOND_RECORD_BYTES, required: false },\n CROT: { type: 0x544f5243, version: 1, recordBytes: PVOX_ROOT_RECORD_BYTES, required: false },\n CLEV: { type: 0x56454c43, version: 1, recordBytes: PVOX_LEVEL_SPAN_RECORD_BYTES, required: false },\n CNOD: { type: 0x444f4e43, version: 1, recordBytes: PVOX_HIERARCHY_NODE_RECORD_BYTES, required: false },\n CBRK: { type: 0x4b524243, version: 1, recordBytes: PVOX_MIN_BRICK_DESCRIPTOR_BYTES, required: false },\n CDAT: { type: 0x54414443, version: 1, recordBytes: 0, required: false },\n} as const);\n\n/** Parent Feature rollout gate for every PVOX-backed path. */\nexport const PVOX_FEATURE_FLAG_ID = \"asset.pipeline.pvox-models.enabled\" as const;\n\n/** Request policy for texture-free PVOX runtime artifacts. */\nexport const PVOX_MODEL_REQUEST_POLICY_ID = \"pvox-world-v1\" as const;\n\n/** Governed PVOX fidelity profiles exposed to requesters. */\nexport const PVOX_FIDELITY_PROFILE_IDS = Object.freeze([\n \"precision-hero-v1\",\n \"props-furniture-v1\",\n \"rocks-organic-shells-v1\",\n \"buildings-v1\",\n \"deformable-v1\",\n] as const);\n\n/** Named runtime capability profiles; providers cannot define new values. */\nexport const PVOX_RUNTIME_CAPABILITY_PROFILE_IDS = Object.freeze([\n \"static-render-v1\",\n \"world-editable-v1\",\n \"deformable-v1\",\n] as const);\n\n/** Existing OAuth capabilities reused by PVOX MCP tools and resources. */\nexport const PVOX_REQUIRED_OAUTH_CAPABILITIES = Object.freeze([\n \"asset.catalog.request\",\n \"asset.catalog.confirm\",\n \"asset.catalog.review\",\n \"asset.source.manage\",\n \"asset.pipeline.mcp.manage\",\n] as const);\n\n/** Fail-closed default ceilings for one PVOX artifact and its public evidence. */\nexport const PVOX_DEFAULT_LIMITS = Object.freeze({\n maximumArtifactBytes: 164 * 1024 * 1024,\n maximumPages: 2_624,\n maximumHierarchyDepth: 8,\n maximumBricks: 524_288,\n maximumLogicalVoxels: 268_435_456,\n maximumEncodedSurfaceSamples: 8_388_608,\n maximumHierarchyNodes: PVOX_MAX_HIERARCHY_NODES,\n maximumSurfaceProperties: 65_536,\n maximumPartitions: 256,\n maximumLodCount: 4,\n maximumCpuResidentBytes: 512 * 1024 * 1024,\n maximumGpuResidentBytes: 512 * 1024 * 1024,\n maximumPhysicalProperties: 64,\n maximumPhysicalEvidenceEntries: 64 * 19,\n maximumMaterialRegions: 64,\n maximumInteriorLayers: 1_024,\n maximumMassPropertyRecords: 256,\n maximumBondRecords: 524_288,\n maximumAssemblyChildren: 256,\n} as const);\n\n/** Source-only acquisition/decode ceilings. These never become runtime texture budgets. */\nexport const PVOX_DEFAULT_SOURCE_INGESTION_LIMITS = Object.freeze({\n maximumDownloadBytes: 512 * 1024 * 1024,\n maximumExpandedBytes: 2 * 1024 * 1024 * 1024,\n maximumArchiveEntries: 10_000,\n maximumSourceFiles: 20_000,\n maximumDecodedTextureBytes: 512 * 1024 * 1024,\n maximumTextureDimensionPx: 16_384,\n} as const);\n\n/** Exact v2 lifecycle, retaining every v1 state and adding PVOX progress. */\nexport const MODEL_RESOLUTION_V2_STATES = Object.freeze([\n \"searching-catalog\",\n \"searching-providers\",\n \"awaiting-provider-auth\",\n \"downloading\",\n \"quarantining\",\n \"importing\",\n \"processing\",\n \"voxelizing\",\n \"evaluating-fidelity\",\n \"awaiting-material-review\",\n \"rendering\",\n \"evaluating\",\n \"awaiting-rights-review\",\n \"awaiting-confirmation\",\n \"promoting\",\n \"completed\",\n \"unresolved\",\n \"failed\",\n \"cancelled\",\n] as const);\n\nexport type ModelResolutionStateV2 = typeof MODEL_RESOLUTION_V2_STATES[number];\n\n/** Deterministic projection used only by v1 compatibility wrappers. */\nexport const MODEL_RESOLUTION_V2_COMPATIBILITY_STATES: Readonly<\n Record<ModelResolutionStateV2, ModelResolutionState>\n> = Object.freeze({\n \"searching-catalog\": \"searching-catalog\",\n \"searching-providers\": \"searching-providers\",\n \"awaiting-provider-auth\": \"awaiting-provider-auth\",\n downloading: \"searching-providers\",\n quarantining: \"quarantining\",\n importing: \"processing\",\n processing: \"processing\",\n voxelizing: \"processing\",\n \"evaluating-fidelity\": \"evaluating\",\n \"awaiting-material-review\": \"evaluating\",\n rendering: \"rendering\",\n evaluating: \"evaluating\",\n \"awaiting-rights-review\": \"awaiting-rights-review\",\n \"awaiting-confirmation\": \"awaiting-confirmation\",\n promoting: \"promoting\",\n completed: \"completed\",\n unresolved: \"unresolved\",\n failed: \"failed\",\n cancelled: \"cancelled\",\n});\n\n/** Runtime capabilities independently admitted by one PVOX artifact. */\nexport const PVOX_CAPABILITIES = Object.freeze([\n \"rendering\",\n \"collision\",\n \"destruction\",\n \"thermal\",\n \"moisture\",\n \"fluid-boundary\",\n \"deformation\",\n \"animation\",\n \"volume\",\n] as const);\n\nexport type PvoxCapability = typeof PVOX_CAPABILITIES[number];\nexport type PvoxCapabilityStatus = \"supported\" | \"unsupported\" | \"not-applicable\";\nexport type PvoxGeometryMode = \"solid\" | \"shell\" | \"mixed\";\nexport type PvoxRequestedGeometryMode = PvoxGeometryMode | \"auto\";\nexport type PvoxFidelityProfileId = typeof PVOX_FIDELITY_PROFILE_IDS[number];\nexport type PvoxRuntimeCapabilityProfileId = typeof PVOX_RUNTIME_CAPABILITY_PROFILE_IDS[number];\n\n/** Mesh/archive/texture budgets used only while a provider source is quarantined. */\nexport interface ModelSourceIngestionLimitsV2 {\n readonly maximumDownloadBytes: number;\n readonly maximumExpandedBytes: number;\n readonly maximumArchiveEntries: number;\n readonly maximumSourceFiles: number;\n readonly maximumDecodedTextureBytes: number;\n readonly maximumTextureDimensionPx: number;\n}\n\n/** Runtime-only, artifact-wide PVOX ceilings. Texture and triangle fields are intentionally absent. */\nexport interface PvoxRuntimeLimitsV1 {\n readonly maximumArtifactBytes: number;\n readonly maximumPages: number;\n readonly maximumHierarchyDepth: number;\n readonly maximumHierarchyNodes: number;\n readonly maximumBricks: number;\n readonly maximumLogicalVoxels: number;\n readonly maximumEncodedSurfaceSamples: number;\n readonly maximumSurfaceProperties: number;\n readonly maximumPhysicalPaletteRecords: number;\n readonly maximumPhysicalEvidenceEntries: number;\n readonly maximumMaterialRegions: number;\n readonly maximumInteriorLayers: number;\n readonly maximumMassPropertyRecords: number;\n readonly maximumBondRecords: number;\n readonly maximumPartitions: number;\n readonly maximumLodCount: number;\n readonly maximumCpuResidentBytes: number;\n readonly maximumGpuResidentBytes: number;\n}\n\n/** Governed PVOX representation, fidelity, capability and runtime-budget request. */\nexport interface PvoxRuntimeRequestProfileV1 {\n readonly profileId: string;\n readonly fidelityProfileId: PvoxFidelityProfileId;\n readonly capabilityProfileId: PvoxRuntimeCapabilityProfileId;\n readonly geometryMode: PvoxRequestedGeometryMode;\n readonly requiredCapabilities: readonly PvoxCapability[];\n readonly limits: PvoxRuntimeLimitsV1;\n}\n\n/** Technical constraints that remain meaningful after texture-free voxel compilation. */\nexport interface ModelHardConstraintsV2 {\n readonly boundsMetres?: ModelBoundsMetres;\n readonly dimensionsMetres?: ModelDimensionsMetres;\n readonly collision?: ModelRequirementPolicy;\n readonly partition?: \"single\" | \"allowed\" | \"required\";\n}\n\n/**\n * Normalized request for the PVOX pipeline.\n *\n * Source-ingestion limits are deliberately independent from immutable PVOX runtime\n * limits so an ingestion texture budget can never be interpreted as a runtime one.\n */\nexport interface ModelRequestSpecV2 {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly policyProfileId: typeof PVOX_MODEL_REQUEST_POLICY_ID;\n readonly requestSemanticProfileHash: string;\n readonly query: string;\n readonly revision: number;\n readonly locale?: string;\n readonly rankerId?: string;\n readonly hardConstraints: ModelHardConstraintsV2;\n readonly softPreferences: ModelSoftPreferences;\n readonly exclusions: readonly string[];\n readonly sourceIngestionLimits: ModelSourceIngestionLimitsV2;\n readonly pvoxRuntimeProfile: PvoxRuntimeRequestProfileV1;\n}\n\n/** Hard gates that semantic confidence can never override. Rights remain separate. */\nexport const PVOX_NON_OVERRIDABLE_GATE_KINDS = Object.freeze([\n \"malware-scan\",\n \"source-format-validation\",\n \"pvox-validation\",\n \"fidelity-validation\",\n \"physical-property-validation\",\n \"renderer-validation\",\n \"accessibility-review\",\n] as const);\n\nexport type PvoxNonOverridableGateKind = typeof PVOX_NON_OVERRIDABLE_GATE_KINDS[number];\n\n/** Physical fields that may be retained with localized PVOX material regions. */\nexport const PVOX_PHYSICAL_PROPERTIES = Object.freeze([\n \"density\",\n \"hardness\",\n \"tensile-strength\",\n \"compressive-strength\",\n \"shear-strength\",\n \"fracture-energy\",\n \"friction\",\n \"restitution\",\n \"thermal-conductivity\",\n \"heat-capacity\",\n \"thermal-expansion\",\n \"ignition-temperature\",\n \"melting-temperature\",\n \"porosity\",\n \"permeability\",\n \"moisture-response\",\n \"flammability\",\n \"corrosion-rate\",\n \"interior-thickness\",\n] as const);\n\nexport type PhysicalPropertyKind = typeof PVOX_PHYSICAL_PROPERTIES[number];\nexport type PhysicalPropertyProvenance = \"source\" | \"authored\" | \"derived\" | \"inferred\" | \"default\";\n\nexport interface PvoxAuthenticatedResourceMetadata {\n readonly uri: string;\n readonly byteLength: number;\n readonly sha256: string;\n readonly contentType: typeof PVOX_CONTENT_TYPE;\n readonly authenticated: true;\n}\n\nexport interface PvoxPageSpatialKey {\n readonly lodLevel: PvoxLodLevel;\n readonly partitionIndex: number;\n readonly hierarchyDepth: number;\n readonly minimumMortonCode: string;\n readonly maximumMortonCode: string;\n}\n\nexport interface PvoxPageRecord {\n readonly pageIndex: number;\n readonly pageKind: typeof PVOX_PAGE_KINDS[number];\n readonly byteOffset: number;\n readonly byteLength: number;\n readonly decodedByteLength: number;\n readonly sha256: string;\n readonly spatialKey?: PvoxPageSpatialKey;\n}\n\nexport type PvoxLodLevel = 0 | 1 | 2 | 3;\n\nexport interface PvoxLodRecord {\n readonly level: PvoxLodLevel;\n readonly firstPageIndex: number;\n readonly pageCount: number;\n readonly brickCount: number;\n readonly cellSizeMetres: number;\n readonly maximumSurfaceErrorMetres: number;\n readonly p99SurfaceErrorMetres: number;\n readonly silhouetteIou: number;\n readonly maximumContourDisplacementPx: number;\n readonly renderedSsim: number;\n readonly p95DeltaE2000: number;\n readonly normalizedMaterialError: number;\n}\n\n/** Public authenticated metadata for one immutable PVOX binary closure. */\nexport interface PvoxAssetManifestV1 {\n readonly manifestVersion: typeof PVOX_ASSET_MANIFEST_VERSION;\n readonly representation: \"pvox\";\n readonly formatVersion: typeof PVOX_FORMAT_VERSION;\n readonly contentType: typeof PVOX_CONTENT_TYPE;\n readonly fileExtension: typeof PVOX_FILE_EXTENSION;\n readonly magic: typeof PVOX_MAGIC;\n readonly brickEdgeVoxels: typeof PVOX_BRICK_EDGE_VOXELS;\n readonly pageSizeBytes: typeof PVOX_PAGE_SIZE_BYTES;\n readonly geometryMode: PvoxGeometryMode;\n readonly sourceContentHash: string;\n readonly canonicalDocumentHash: string;\n readonly rootHash: string;\n readonly directoryHash: string;\n readonly pageSetHash: string;\n readonly binaryClosureHash: string;\n readonly validationEvidenceHash: string;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly headerByteLength: typeof PVOX_HEADER_BYTE_LENGTH;\n readonly directoryEntryByteLength: typeof PVOX_DIRECTORY_ENTRY_BYTE_LENGTH;\n readonly sectionCount: number;\n readonly maximumRunsPerBrick: typeof PVOX_MAX_RUNS_PER_BRICK;\n readonly maximumLocalSamplesPerBrick: typeof PVOX_MAX_LOCAL_SAMPLES_PER_BRICK;\n readonly maximumEncodedBrickPayloadBytes: typeof PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES;\n readonly coordinateSystem: typeof CANONICAL_MODEL_COORDINATE_SYSTEM;\n readonly boundsMetres: ModelBoundsMetresV2;\n readonly artifact: PvoxAuthenticatedResourceMetadata;\n readonly pages: readonly PvoxPageRecord[];\n readonly lods: readonly PvoxLodRecord[];\n}\n\nexport type PvoxAssetManifest = PvoxAssetManifestV1;\n\nexport interface ModelBoundsMetresV2 {\n readonly min: readonly [number, number, number];\n readonly max: readonly [number, number, number];\n}\n\nexport interface ModelDimensionsMetresV2 {\n readonly width: number;\n readonly height: number;\n readonly depth: number;\n}\n\n/** PVOX runtime facts that intentionally contain no triangle or texture fields. */\nexport interface VoxelTechnicalProfile {\n readonly boundsMetres: ModelBoundsMetresV2;\n readonly dimensionsMetres: ModelDimensionsMetresV2;\n readonly geometryMode: PvoxGeometryMode;\n readonly artifactByteLength: number;\n readonly pageCount: number;\n /** Sum of render bricks across every retained spatial LOD in the artifact. */\n readonly brickCount: number;\n /** Artifact-wide render capacity; exactly `brickCount * 8 * 8 * 8`. */\n readonly logicalVoxelCapacity: number;\n /** Sum of encoded render-field surface samples across every retained LOD. */\n readonly encodedSurfaceSampleCount: number;\n readonly surfacePropertyCount: number;\n readonly sectionCount: number;\n readonly levelSpanRecordCount: number;\n readonly physicalPaletteRecordCount: number;\n readonly physicalEvidenceRecordCount: number;\n readonly materialRegionCount: number;\n readonly interiorLayerRecordCount: number;\n readonly massPropertyRecordCount: number;\n readonly bondRecordCount: number;\n readonly collisionHierarchyNodeCount: number;\n readonly collisionBrickCount: number;\n readonly collisionLogicalVoxelCapacity: number;\n readonly collisionEncodedSurfaceSampleCount: number;\n readonly hierarchyDepth: number;\n readonly hierarchyNodeCount: number;\n readonly lodCount: number;\n readonly cpuResidentByteLength: number;\n readonly gpuResidentByteLength: number;\n readonly hasCollision: boolean;\n readonly partitionCount: number;\n readonly maximumPartitionExtentMetres: number;\n readonly maximumPartitionDiagonalMetres: number;\n}\n\n/** One independently evaluated runtime capability. */\nexport interface VoxelCapabilityAssessment {\n readonly capability: PvoxCapability;\n readonly status: PvoxCapabilityStatus;\n readonly evaluatorId: string;\n readonly evaluatorVersion: string;\n readonly subjectContentHash: string;\n readonly evidenceHash: string;\n readonly reasonCodes: readonly string[];\n readonly evaluatedAt: string;\n}\n\n/** One localized physical value with explicit origin and review evidence. */\nexport interface PhysicalPropertyEvidence {\n readonly property: PhysicalPropertyKind;\n readonly value: number;\n readonly unit: string;\n readonly provenance: PhysicalPropertyProvenance;\n readonly confidence: number;\n readonly subjectContentHash: string;\n readonly regionId: string;\n readonly materialId: string;\n readonly policyId: typeof PVOX_PHYSICAL_PROPERTY_POLICY_ID;\n readonly policyVersion: typeof PVOX_PHYSICAL_PROPERTY_POLICY_VERSION;\n readonly evidenceHash: string;\n readonly reviewedBy?: string;\n readonly reviewedAt?: string;\n readonly reviewToken?: string;\n}\n\nexport interface PvoxPhysicalRegionInventoryEntry {\n readonly regionIndex: number;\n readonly physicalPaletteIndex: number;\n readonly regionId: string;\n readonly materialId: string;\n}\n\n/** Validator-attested authoritative material-region inventory read from PVOX REGN/PHYS records. */\nexport interface PvoxPhysicalRegionInventoryV1 {\n readonly inventoryVersion: typeof PVOX_PHYSICAL_REGION_INVENTORY_VERSION;\n readonly subjectContentHash: string;\n readonly inventoryHash: string;\n readonly inventoryHashAttestation: PvoxHashAttestation;\n readonly validationEvidenceHash: string;\n readonly entries: readonly PvoxPhysicalRegionInventoryEntry[];\n}\n\nexport type PvoxReviewedStructuralEvidenceKind = \"mass-properties\" | \"bond-graph\" | \"interior-layers\";\n\nexport interface PvoxReviewedStructuralEvidence {\n readonly kind: PvoxReviewedStructuralEvidenceKind;\n readonly subjectContentHash: string;\n readonly physicalInventoryHash: string;\n readonly recordCount: number;\n readonly evidenceHash: string;\n readonly reviewerId: string;\n readonly reviewedAt: string;\n readonly reviewToken: string;\n}\n\n/** Structurally cross-bound digest evidence; token verification remains an authenticated host responsibility. */\nexport interface PvoxHashAttestation {\n readonly algorithm: \"sha256\";\n readonly domain: typeof PVOX_HASH_DOMAINS[keyof typeof PVOX_HASH_DOMAINS];\n readonly digest: string;\n readonly attestationToken: string;\n}\n\n/** V1 assessment plus the exact normalized V2 request subject ranked by that assessment. */\nexport type PvoxModelMatchAssessmentV2 = ModelMatchAssessment & Readonly<{\n requestSemanticProfileHash: string;\n requestSemanticProfileCanonical: string;\n evidenceHash: string;\n}>;\n\n/** Immutable comparison of PVOX output with the verified canonical document. */\nexport interface PvoxFidelityEvidence {\n readonly profileId: PvoxFidelityProfileId;\n readonly surfaceProfileId: Exclude<PvoxFidelityProfileId, \"deformable-v1\">;\n readonly profileVersion: typeof PVOX_FIDELITY_PROFILE_VERSION;\n readonly outcome: \"passed\" | \"blocked\";\n readonly canonicalDocumentHash: string;\n readonly pvoxBinaryClosureHash: string;\n readonly evaluatedDiagonalMetres: number;\n readonly lod0CellSizeMetres: number;\n readonly maximumAllowedSurfaceErrorMetres: number;\n readonly maximumSurfaceErrorMetres: number;\n readonly p99AllowedSurfaceErrorMetres: number;\n readonly p99SurfaceErrorMetres: number;\n readonly minimumSilhouetteIou: number;\n readonly silhouetteIou: number;\n readonly maximumAllowedContourDisplacementPx: number;\n readonly maximumContourDisplacementPx: number;\n readonly minimumRenderedSsim: number;\n readonly renderedSsim: number;\n readonly maximumP95DeltaE2000: number;\n readonly p95DeltaE2000: number;\n readonly maximumNormalizedMaterialError: number;\n readonly normalizedMaterialError: number;\n readonly evidenceHash: string;\n readonly evaluatedAt: string;\n readonly decisionToken: string;\n}\n\nexport type PvoxEditOperation = \"insert\" | \"replace\" | \"remove\";\n\nexport interface PvoxBrickPatchDescriptor {\n readonly fieldKind: \"render-field\" | \"collision-field\";\n readonly lodLevel: PvoxLodLevel;\n readonly partitionIndex: number;\n readonly hierarchyDepth: number;\n readonly mortonCode: string;\n readonly expectedPageIndex: number;\n readonly expectedPageHash: string;\n readonly operation: PvoxEditOperation;\n readonly expectedBrickHash: string;\n readonly resultingBrickHash: string;\n readonly resultingPageHash: string;\n}\n\n/** Placement-scoped, sequential copy-on-write mutation journal. */\nexport interface PvoxEditJournal {\n readonly journalVersion: typeof PVOX_EDIT_JOURNAL_VERSION;\n readonly baseContentHash: string;\n readonly basePageSetHash: string;\n readonly placementId: string;\n readonly gridVersion: string;\n readonly operationId: string;\n readonly expectedRevision: number;\n readonly resultingRevision: number;\n readonly previousJournalHash: string;\n readonly expectedRootHash: string;\n readonly resultingRootHash: string;\n readonly resultingRootHashAttestation: PvoxHashAttestation;\n readonly patches: readonly PvoxBrickPatchDescriptor[];\n readonly dirtyBoundsMetres: ModelBoundsMetresV2;\n readonly massDeltaKg: number;\n readonly journalHash: string;\n readonly journalHashAttestation: PvoxHashAttestation;\n readonly recordedAt: string;\n}\n\n/** Authenticated placement state required to validate a standalone non-genesis CAS edit. */\nexport interface PvoxEditJournalCurrentState {\n readonly baseContentHash: string;\n readonly basePageSetHash: string;\n readonly placementId: string;\n readonly gridVersion: string;\n readonly revision: number;\n readonly rootHash: string;\n readonly latestJournalHash: string;\n readonly pageHashes: readonly Readonly<{ pageIndex: number; sha256: string }>[];\n}\n\nexport interface PvoxCompilerEvidence {\n readonly compilerId: string;\n readonly compilerVersion: string;\n readonly sourceFormat: string;\n readonly sourceContentHash: string;\n readonly canonicalDocumentHash: string;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly outputContentHash: string;\n readonly evidenceHash: string;\n readonly compiledAt: string;\n}\n\nexport interface PvoxGateEvidence {\n readonly kind: PvoxNonOverridableGateKind;\n readonly outcome: \"passed\" | \"blocked\";\n readonly validatorId: string;\n readonly validatorVersion: string;\n readonly subjectContentHash: string;\n readonly evidenceHash: string;\n readonly reasonCodes: readonly string[];\n readonly evaluatedAt: string;\n readonly attestationToken: string;\n}\n\nexport interface PvoxCatalogAssemblyChildRef {\n readonly disposition: \"existing\";\n readonly representation: \"pvox\";\n readonly asset: ModelAssetRef;\n readonly processingManifestId: string;\n readonly processingClosureHash: string;\n readonly binaryClosureHash: string;\n readonly processingManifestUri: string;\n}\n\nexport interface PvoxStagedAssemblyChildRef {\n readonly disposition: \"staged-derived\";\n readonly representation: \"pvox\";\n readonly derivedId: string;\n readonly kind: \"leaf\";\n readonly contentHash: string;\n readonly binaryClosureHash: string;\n readonly processingClosureHash: string;\n readonly processingManifestId: string;\n readonly processingManifestUri: string;\n}\n\nexport interface PvoxAssemblyChild {\n readonly instanceId: string;\n readonly parentInstanceId?: string;\n readonly assetRef: PvoxCatalogAssemblyChildRef | PvoxStagedAssemblyChildRef;\n readonly transform: ModelTransform;\n}\n\n/** Additive PVOX-only processing manifest. The GLB v1 manifest is unchanged. */\nexport interface ModelProcessingManifestV2 {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly representation: \"pvox\";\n readonly manifestId: string;\n readonly resolutionId: string;\n readonly candidateId: string;\n readonly kind: ModelAssetKind;\n readonly requestProfileId: string;\n readonly requestSemanticProfileHash: string;\n readonly capabilityProfileId: PvoxRuntimeCapabilityProfileId;\n readonly contentHash: string;\n readonly binaryClosureHash: string;\n readonly processingClosureHash: string;\n readonly processingClosureAttestation: PvoxHashAttestation;\n readonly assemblyClosureHash: string;\n readonly assemblyClosureAttestation: PvoxHashAttestation;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly coordinateSystem: typeof CANONICAL_MODEL_COORDINATE_SYSTEM;\n readonly pvox: PvoxAssetManifestV1;\n readonly technicalProfile: VoxelTechnicalProfile;\n readonly requiredCapabilities: readonly PvoxCapability[];\n readonly capabilities: readonly VoxelCapabilityAssessment[];\n readonly capabilityEvidenceSetHash: string;\n readonly capabilityEvidenceSetAttestation: PvoxHashAttestation;\n readonly physicalRegionInventory: PvoxPhysicalRegionInventoryV1;\n readonly physicalProperties: readonly PhysicalPropertyEvidence[];\n readonly physicalEvidenceHash: string;\n readonly physicalEvidenceAttestation: PvoxHashAttestation;\n readonly massPropertiesEvidence: PvoxReviewedStructuralEvidence;\n readonly bondGraphEvidence: PvoxReviewedStructuralEvidence;\n readonly interiorLayerEvidence: PvoxReviewedStructuralEvidence;\n readonly converter: PvoxCompilerEvidence;\n readonly fidelity: PvoxFidelityEvidence;\n readonly children: readonly PvoxAssemblyChild[];\n readonly processedAt: string;\n}\n\nexport interface PvoxRenderEvidence {\n readonly renderId: string;\n readonly representation: \"pvox\";\n readonly lodLevel: 0;\n readonly traversalBackend: \"native-pvox\";\n readonly rendererId: typeof PVOX_NATIVE_RENDERER_ID;\n readonly rendererVersion: string;\n readonly rendererQualificationHash: string;\n readonly settingsId: typeof PVOX_NATIVE_REVIEW_SETTINGS_ID;\n readonly settingsVersion: string;\n readonly cameraQualificationHash: string;\n readonly processingManifestId: string;\n readonly processingClosureHash: string;\n readonly pvoxContentHash: string;\n readonly pvoxRootHash: string;\n readonly pvoxDirectoryHash: string;\n readonly pvoxPageSetHash: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly renderedAt: string;\n readonly evidenceHash: string;\n readonly evidenceHashAttestation: PvoxHashAttestation;\n}\n\n/** Exact subject covered by a backend-issued candidate confirmation token. */\nexport interface ModelCandidateConfirmationBindingV2 {\n readonly bindingHash: string;\n readonly bindingHashAttestation: PvoxHashAttestation;\n readonly resolutionId: string;\n readonly requesterId: string;\n readonly request: ModelRequestSpecV2;\n readonly requestSemanticProfileHash: string;\n readonly requestRevision: number;\n readonly candidateId: string;\n readonly candidateContentHash: string;\n readonly candidateAssetRef: ModelCandidateAssetRef;\n readonly match: PvoxModelMatchAssessmentV2;\n readonly provenance: ModelProvenance;\n readonly rights: ModelRightsAssessment;\n readonly sourceContentHash: string;\n readonly binaryClosureHash: string;\n readonly pvoxRootHash: string;\n readonly pvoxDirectoryHash: string;\n readonly pvoxPageSetHash: string;\n readonly compilationInputHash: string;\n readonly runtimeRequestProfileHash: string;\n readonly processingClosureHash: string;\n readonly assemblyClosureHash: string;\n readonly evaluationClosureHash: string;\n readonly capabilityEvidenceSetHash: string;\n readonly hardGates: readonly PvoxGateEvidence[];\n readonly viewSha256s: readonly [string, string, string, string];\n readonly rightsDecisionId: string;\n readonly fidelityEvidenceHash: string;\n readonly physicalEvidenceHash: string;\n readonly rendererId: string;\n readonly rendererVersion: string;\n readonly rendererEvidenceHash: string;\n readonly renderEvidence: PvoxRenderEvidence;\n}\n\ninterface ModelCandidateV2Base {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly requesterId: string;\n readonly candidateId: string;\n readonly request: ModelRequestSpecV2;\n readonly assetRef: ModelCandidateAssetRef;\n readonly match: PvoxModelMatchAssessmentV2;\n readonly provenance: ModelProvenance;\n readonly rights: ModelRightsAssessment;\n readonly processingManifest: ModelProcessingManifestV2;\n readonly views: ModelConfirmationViews;\n readonly renderEvidence: PvoxRenderEvidence;\n readonly evaluationClosureHash: string;\n readonly evaluationClosureAttestation: PvoxHashAttestation;\n readonly hardGates: readonly PvoxGateEvidence[];\n}\n\nexport interface ConfirmableModelCandidateV2 extends ModelCandidateV2Base {\n readonly admissionStatus: \"confirmable\";\n readonly confirmationBinding: ModelCandidateConfirmationBindingV2;\n readonly confirmationToken: string;\n readonly confirmationRequired: true;\n}\n\nexport interface DiagnosticModelCandidateV2 extends ModelCandidateV2Base {\n readonly admissionStatus: \"diagnostic\";\n readonly blockingReasonCodes: readonly string[];\n readonly confirmationRequired: false;\n}\n\nexport type ModelCandidateV2 = ConfirmableModelCandidateV2 | DiagnosticModelCandidateV2;\n\nexport interface ModelCandidateConfirmationV2 {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly confirmationId: string;\n readonly resolutionId: string;\n readonly requesterId: string;\n readonly candidateId: string;\n readonly confirmationToken: string;\n readonly confirmationBindingHash: string;\n readonly viewSha256s: readonly [string, string, string, string];\n readonly confirmedBy: string;\n readonly confirmedAt: string;\n readonly semanticRiskAccepted: boolean;\n}\n\nexport interface ModelPromotionReceiptV2 {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly promotionId: string;\n readonly resolutionId: string;\n readonly requesterId: string;\n readonly candidateId: string;\n readonly proposalId: string;\n readonly candidateAssetRef: ModelCandidateAssetRef;\n readonly confirmationId: string;\n readonly confirmationBindingHash: string;\n readonly processingManifestId: string;\n readonly processingContentHash: string;\n readonly processingClosureHash: string;\n readonly assemblyClosureHash: string;\n readonly assemblyChildClosureHashes: readonly string[];\n readonly finalAssetRef: ModelAssetRef;\n readonly creditsRecordHash: string;\n readonly catalogRowHash: string;\n readonly indexSnapshotHash: string;\n readonly catalogPointerEtag: string;\n readonly indexPointerEtag: string;\n readonly publicationState: \"pointer-last-complete\";\n readonly creditsWrittenAt: string;\n readonly catalogRowWrittenAt: string;\n readonly indexSnapshotWrittenAt: string;\n readonly pointerPublishedAt: string;\n readonly publicationHash: string;\n readonly publicationHashAttestation: PvoxHashAttestation;\n readonly promotedAt: string;\n readonly publicationToken: string;\n}\n\nexport interface ModelRefinementQuestionV2 {\n readonly questionId: string;\n readonly prompt: string;\n readonly reasonCodes: readonly string[];\n}\n\nexport interface ModelResolutionV2 {\n readonly contractVersion: typeof MODEL_RESOLUTION_V2_CONTRACT_VERSION;\n readonly resolutionId: string;\n readonly requesterId: string;\n readonly request: ModelRequestSpecV2;\n readonly attempts: number;\n readonly state: ModelResolutionStateV2;\n readonly compatibilityState: ModelResolutionState;\n readonly candidates: readonly ModelCandidateV2[];\n readonly bestCandidate?: ModelCandidateV2;\n readonly confirmation?: ModelCandidateConfirmationV2;\n readonly promotionReceipt?: ModelPromotionReceiptV2;\n readonly refinementQuestions: readonly ModelRefinementQuestionV2[];\n readonly finalAssetRef?: ModelAssetRef;\n readonly stateReasonCode?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst SHA256 = /^[a-f0-9]{64}$/u;\nconst TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;\nconst PATH_SEGMENT = /^(?!\\.{1,2}$)[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u;\nconst ATTESTATION = /^[A-Za-z0-9_-]{32,256}$/u;\nconst REASON_CODE = /^[a-z0-9][a-z0-9._:-]{0,127}$/u;\nconst MORTON_CODE = /^[a-f0-9]{16}$/u;\nconst ISO_TIMESTAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/u;\nconst PVOX_RESOLUTION_RESOURCE = /^mcp:\\/\\/models\\/resolutions\\/([A-Za-z0-9._~-]{1,128})\\/candidates\\/([A-Za-z0-9._~-]{1,128})\\/artifacts\\/sha256\\/([a-f0-9]{64})\\.pvox$/u;\nconst PVOX_CATALOG_RESOURCE = /^mcp:\\/\\/models\\/catalog\\/([a-z0-9]+(?:-[a-z0-9]+)*)\\/versions\\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\\/artifacts\\/sha256\\/([a-f0-9]{64})\\.pvox$/u;\nconst DIRECT_URL = /(?:https?:\\/\\/|\\bwww\\.)/iu;\n\nfunction hasUnsafeControlCharacters(value: string): boolean {\n return [...value].some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 0x1f\n || (codePoint >= 0x7f && codePoint <= 0x9f)\n || codePoint === 0x2028\n || codePoint === 0x2029;\n });\n}\n\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value === null || typeof value !== \"object\") return value;\n const object = value as object;\n if (seen.has(object)) return value;\n seen.add(object);\n for (const child of Object.values(value as UnknownRecord)) deepFreeze(child, seen);\n return Object.freeze(value);\n}\n\nfunction asRecord(value: unknown, fieldName: string): UnknownRecord {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${fieldName} must be a plain object.`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${fieldName} must be a plain object.`);\n }\n const keys = Reflect.ownKeys(value);\n if (keys.some((key) => typeof key !== \"string\")) {\n throw new Error(`${fieldName} must contain enumerable string-keyed data properties only.`);\n }\n for (const key of keys as string[]) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || descriptor.enumerable !== true || !(\"value\" in descriptor)) {\n throw new Error(`${fieldName} must contain enumerable string-keyed data properties only.`);\n }\n }\n return value as UnknownRecord;\n}\n\nfunction exactKeys(record: UnknownRecord, allowed: readonly string[], fieldName: string): void {\n const set = new Set(allowed);\n const unsupported = Object.keys(record).find((key) => !set.has(key));\n if (unsupported !== undefined) throw new Error(`${fieldName} contains an unsupported field.`);\n}\n\nfunction asDenseArray(value: unknown, fieldName: string, minimum: number, maximum: number): readonly unknown[] {\n if (!Array.isArray(value) || value.length < minimum || value.length > maximum) {\n throw new Error(`${fieldName} must be a bounded dense array.`);\n }\n const ownKeys = Reflect.ownKeys(value);\n if (ownKeys.some((key) => typeof key === \"symbol\" || (key !== \"length\" && !/^(?:0|[1-9]\\d*)$/u.test(key)))) {\n throw new Error(`${fieldName} must be a bounded dense array of data elements.`);\n }\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n if (descriptor === undefined || descriptor.enumerable !== true || !(\"value\" in descriptor)) {\n throw new Error(`${fieldName} must be a bounded dense array of data elements.`);\n }\n }\n return value;\n}\n\nfunction assertDataOnlyTree(value: unknown, fieldName: string, seen = new WeakSet<object>(), depth = 0): void {\n if (value === null || typeof value !== \"object\") return;\n if (depth > 32) throw new Error(`${fieldName} data nesting exceeds the contract limit.`);\n if (seen.has(value)) throw new Error(`${fieldName} must not contain cyclic data.`);\n seen.add(value);\n if (Array.isArray(value)) {\n const entries = asDenseArray(value, fieldName, 0, 10_000);\n for (let index = 0; index < entries.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(index))!;\n assertDataOnlyTree(descriptor.value, `${fieldName}[${index}]`, seen, depth + 1);\n }\n } else {\n const record = asRecord(value, fieldName);\n for (const key of Object.keys(record)) {\n const descriptor = Object.getOwnPropertyDescriptor(record, key)!;\n assertDataOnlyTree(descriptor.value, `${fieldName}.${key}`, seen, depth + 1);\n }\n }\n seen.delete(value);\n}\n\nfunction requireString(value: unknown, fieldName: string, maximum = 512): string {\n if (\n typeof value !== \"string\"\n || value.length === 0\n || value.length > maximum\n || value.trim() !== value\n || hasUnsafeControlCharacters(value)\n ) throw new Error(`${fieldName} must be a bounded safe string.`);\n return value;\n}\n\nfunction requireToken(value: unknown, fieldName: string): string {\n const output = requireString(value, fieldName, 128);\n if (!TOKEN.test(output) || DIRECT_URL.test(output)) throw new Error(`${fieldName} must be a bounded token.`);\n return output;\n}\n\nfunction requirePathSegment(value: unknown, fieldName: string): string {\n const output = requireString(value, fieldName, 128);\n if (!PATH_SEGMENT.test(output)) throw new Error(`${fieldName} must be a safe path segment.`);\n return output;\n}\n\nfunction requireReasonCode(value: unknown, fieldName: string): string {\n const output = requireString(value, fieldName, 128);\n if (!REASON_CODE.test(output)) throw new Error(`${fieldName} must be a reason code.`);\n return output;\n}\n\nfunction requireSha256(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !SHA256.test(value)) throw new Error(`${fieldName} must be a lowercase SHA-256 digest.`);\n return value;\n}\n\nfunction requireAttestation(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !ATTESTATION.test(value)) throw new Error(`${fieldName} must be a bounded attestation token.`);\n return value;\n}\n\nfunction requireInteger(value: unknown, fieldName: string, minimum: number, maximum: number): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum || (value as number) > maximum) {\n throw new Error(`${fieldName} must be an integer from ${minimum} to ${maximum}.`);\n }\n return value as number;\n}\n\nfunction requireNumber(value: unknown, fieldName: string, minimum: number, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < minimum || value > maximum) {\n throw new Error(`${fieldName} must be a finite number from ${minimum} to ${maximum}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, fieldName: string): boolean {\n if (typeof value !== \"boolean\") throw new Error(`${fieldName} must be boolean.`);\n return value;\n}\n\nfunction requireTimestamp(value: unknown, fieldName: string): string {\n if (typeof value !== \"string\" || !ISO_TIMESTAMP.test(value) || !Number.isFinite(Date.parse(value))) {\n throw new Error(`${fieldName} must be a canonical UTC timestamp.`);\n }\n return value;\n}\n\nfunction requireEnum<const T extends readonly string[]>(value: unknown, allowed: T, fieldName: string): T[number] {\n if (typeof value !== \"string\" || !(allowed as readonly string[]).includes(value)) {\n throw new Error(`${fieldName} must be one of ${allowed.join(\", \")}.`);\n }\n return value as T[number];\n}\n\nfunction requireReasonCodes(value: unknown, fieldName: string): readonly string[] {\n const entries = asDenseArray(value, fieldName, 0, 32);\n const result = entries.map((entry, index) => requireReasonCode(entry, `${fieldName}[${index}]`));\n if (new Set(result).size !== result.length) throw new Error(`${fieldName} must not contain duplicates.`);\n return result;\n}\n\nfunction requireShaTuple(value: unknown, fieldName: string): readonly [string, string, string, string] {\n const entries = asDenseArray(value, fieldName, 4, 4);\n return [\n requireSha256(entries[0], `${fieldName}[0]`),\n requireSha256(entries[1], `${fieldName}[1]`),\n requireSha256(entries[2], `${fieldName}[2]`),\n requireSha256(entries[3], `${fieldName}[3]`),\n ];\n}\n\nfunction requireVector(value: unknown, fieldName: string): readonly [number, number, number] {\n const entries = asDenseArray(value, fieldName, 3, 3);\n return [\n requireNumber(entries[0], `${fieldName}[0]`, -PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n requireNumber(entries[1], `${fieldName}[1]`, -PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n requireNumber(entries[2], `${fieldName}[2]`, -PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n ];\n}\n\nfunction createBounds(value: unknown, fieldName: string): ModelBoundsMetresV2 {\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"min\", \"max\"], fieldName);\n const min = requireVector(record.min, `${fieldName}.min`);\n const max = requireVector(record.max, `${fieldName}.max`);\n if (min.some((coordinate, index) => coordinate >= max[index]!)) throw new Error(`${fieldName} minimum values must be below maximum values.`);\n return { min, max };\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n return Math.abs(left - right) <= Math.max(1e-6, Math.abs(left) * 1e-6, Math.abs(right) * 1e-6);\n}\n\nfunction createHashAttestation(\n value: unknown,\n expectedDomain: PvoxHashAttestation[\"domain\"],\n expectedDigest: string,\n fieldName: string,\n): PvoxHashAttestation {\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"algorithm\", \"domain\", \"digest\", \"attestationToken\"], fieldName);\n if (record.algorithm !== \"sha256\" || record.domain !== expectedDomain) {\n throw new Error(`${fieldName} must use the governed SHA-256 domain.`);\n }\n const digest = requireSha256(record.digest, `${fieldName}.digest`);\n if (digest !== expectedDigest) throw new Error(`${fieldName}.digest must match its bound contract hash.`);\n return {\n algorithm: \"sha256\",\n domain: expectedDomain,\n digest,\n attestationToken: requireAttestation(record.attestationToken, `${fieldName}.attestationToken`),\n };\n}\n\n/** Canonical JSON used only as a versioned hash preimage; SHA-256 is computed by the producing service. */\nexport function canonicalizePvoxHashProjectionV1(value: unknown): string {\n assertDataOnlyTree(value, \"PVOX hash projection\");\n return canonicalizeGpuContract(value);\n}\n\n/** Exact full-v2 request projection excluding only its externally computed digest. */\nexport function canonicalizeModelRequestSemanticProfileV1(request: ModelRequestSpecV2): string {\n return canonicalizePvoxHashProjectionV1({\n contractVersion: request.contractVersion,\n policyProfileId: request.policyProfileId,\n query: request.query,\n revision: request.revision,\n ...(request.locale === undefined ? {} : { locale: request.locale }),\n ...(request.rankerId === undefined ? {} : { rankerId: request.rankerId }),\n hardConstraints: request.hardConstraints,\n softPreferences: request.softPreferences,\n exclusions: request.exclusions,\n sourceIngestionLimits: request.sourceIngestionLimits,\n pvoxRuntimeProfile: request.pvoxRuntimeProfile,\n });\n}\n\nfunction alignPvoxSectionBytes(value: number): number {\n return Math.ceil(value / PVOX_SECTION_ALIGNMENT_BYTES) * PVOX_SECTION_ALIGNMENT_BYTES;\n}\n\n/** Conservative exact fixed-record lower bound for a declared PVOX technical profile. */\nexport function calculatePvoxMinimumArtifactByteLength(profile: VoxelTechnicalProfile): number {\n const sectionPayloads = [\n profile.partitionCount * PVOX_PARTITION_RECORD_BYTES,\n profile.lodCount * PVOX_LOD_RECORD_BYTES,\n profile.partitionCount * profile.lodCount * PVOX_ROOT_RECORD_BYTES,\n profile.levelSpanRecordCount * PVOX_LEVEL_SPAN_RECORD_BYTES,\n profile.hierarchyNodeCount * PVOX_HIERARCHY_NODE_RECORD_BYTES,\n profile.brickCount * PVOX_MIN_BRICK_DESCRIPTOR_BYTES,\n profile.brickCount * PVOX_RENDER_BRICK_MASK_BYTES\n + profile.encodedSurfaceSampleCount * PVOX_MIN_ENCODED_SURFACE_SAMPLE_BYTES,\n profile.surfacePropertyCount * PVOX_SURFACE_PROPERTY_RECORD_BYTES,\n profile.physicalPaletteRecordCount * PVOX_PHYSICAL_PROPERTY_RECORD_BYTES,\n profile.physicalEvidenceRecordCount * PVOX_PHYSICAL_EVIDENCE_RECORD_BYTES,\n profile.materialRegionCount * PVOX_MATERIAL_REGION_RECORD_BYTES,\n profile.interiorLayerRecordCount * PVOX_INTERIOR_LAYER_RECORD_BYTES,\n profile.massPropertyRecordCount * PVOX_MASS_PROPERTY_RECORD_BYTES,\n profile.bondRecordCount * PVOX_BOND_RECORD_BYTES,\n ...(profile.hasCollision ? [\n profile.partitionCount * profile.lodCount * PVOX_ROOT_RECORD_BYTES,\n profile.levelSpanRecordCount * PVOX_LEVEL_SPAN_RECORD_BYTES,\n profile.collisionHierarchyNodeCount * PVOX_HIERARCHY_NODE_RECORD_BYTES,\n profile.collisionBrickCount * PVOX_MIN_BRICK_DESCRIPTOR_BYTES,\n profile.collisionBrickCount * PVOX_COLLISION_BRICK_MASK_BYTES\n + profile.collisionEncodedSurfaceSampleCount * PVOX_MIN_ENCODED_COLLISION_SAMPLE_BYTES,\n ] : []),\n ];\n return alignPvoxSectionBytes(PVOX_HEADER_BYTE_LENGTH + profile.sectionCount * PVOX_DIRECTORY_ENTRY_BYTE_LENGTH)\n + sectionPayloads.reduce((total, byteLength) => total + alignPvoxSectionBytes(byteLength), 0);\n}\n\nfunction assertFloorCentredBounds(bounds: ModelBoundsMetresV2, fieldName: string): void {\n if (!approximatelyEqual(bounds.min[1], 0)\n || !approximatelyEqual(bounds.min[0] + bounds.max[0], 0)\n || !approximatelyEqual(bounds.min[2] + bounds.max[2], 0)) {\n throw new Error(`${fieldName} must use a floor-centred origin with centred X/Z bounds.`);\n }\n}\n\nfunction createDimensions(value: unknown, fieldName: string): ModelDimensionsMetresV2 {\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"width\", \"height\", \"depth\"], fieldName);\n return {\n width: requireNumber(record.width, `${fieldName}.width`, Number.EPSILON, 1_000_000_000),\n height: requireNumber(record.height, `${fieldName}.height`, Number.EPSILON, 1_000_000_000),\n depth: requireNumber(record.depth, `${fieldName}.depth`, Number.EPSILON, 1_000_000_000),\n };\n}\n\nfunction assertCoordinateSystem(value: unknown, fieldName: string): void {\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"unit\", \"upAxis\", \"forwardAxis\", \"origin\", \"outwardFaceWinding\"], fieldName);\n for (const [key, expected] of Object.entries(CANONICAL_MODEL_COORDINATE_SYSTEM)) {\n if (record[key] !== expected) throw new Error(`${fieldName} must use the canonical model coordinate system.`);\n }\n}\n\ntype PvoxResourceScope =\n | { readonly kind: \"resolution\"; readonly resolutionId: string; readonly candidateId: string; readonly sha256: string }\n | { readonly kind: \"catalog\"; readonly assetId: string; readonly version: string; readonly sha256: string };\n\nfunction parsePvoxResourceScope(uri: string): PvoxResourceScope {\n const resolutionMatch = PVOX_RESOLUTION_RESOURCE.exec(uri);\n if (resolutionMatch !== null) {\n return {\n kind: \"resolution\",\n resolutionId: requirePathSegment(resolutionMatch[1], \"PVOX resource resolutionId\"),\n candidateId: requirePathSegment(resolutionMatch[2], \"PVOX resource candidateId\"),\n sha256: requireSha256(resolutionMatch[3], \"PVOX resource hash\"),\n };\n }\n const catalogMatch = PVOX_CATALOG_RESOURCE.exec(uri);\n if (catalogMatch !== null) {\n return {\n kind: \"catalog\",\n assetId: requirePathSegment(catalogMatch[1], \"PVOX resource assetId\"),\n version: assertImmutableAssetVersion(catalogMatch[2]),\n sha256: requireSha256(catalogMatch[3], \"PVOX resource hash\"),\n };\n }\n throw new Error(\"PVOX artifact URI must be an authenticated canonical PVOX MCP resource.\");\n}\n\nfunction createResource(value: unknown): PvoxAuthenticatedResourceMetadata {\n const record = asRecord(value, \"PvoxAssetManifestV1.artifact\");\n exactKeys(record, [\"uri\", \"byteLength\", \"sha256\", \"contentType\", \"authenticated\"], \"PvoxAssetManifestV1.artifact\");\n const uri = requireString(record.uri, \"PvoxAssetManifestV1.artifact.uri\", 512);\n if (uri.includes(\"%\") || uri.includes(\"?\") || uri.includes(\"#\") || uri.includes(\"..\") || DIRECT_URL.test(uri)) {\n throw new Error(\"PvoxAssetManifestV1.artifact.uri must be an authenticated canonical MCP resource.\");\n }\n const scope = parsePvoxResourceScope(uri);\n const sha256 = requireSha256(record.sha256, \"PvoxAssetManifestV1.artifact.sha256\");\n if (scope.sha256 !== sha256) throw new Error(\"PvoxAssetManifestV1.artifact URI hash must match sha256.\");\n if (record.contentType !== PVOX_CONTENT_TYPE) throw new Error(\"PvoxAssetManifestV1.artifact.contentType must be the PVOX content type.\");\n if (record.authenticated !== true) throw new Error(\"PvoxAssetManifestV1.artifact must be authenticated.\");\n return {\n uri,\n byteLength: requireInteger(record.byteLength, \"PvoxAssetManifestV1.artifact.byteLength\", 1, PVOX_DEFAULT_LIMITS.maximumArtifactBytes),\n sha256,\n contentType: PVOX_CONTENT_TYPE,\n authenticated: true,\n };\n}\n\nfunction createPage(value: unknown, index: number): PvoxPageRecord {\n const fieldName = `PvoxAssetManifestV1.pages[${index}]`;\n const record = asRecord(value, fieldName);\n const pageKind = requireEnum(record.pageKind, PVOX_PAGE_KINDS, `${fieldName}.pageKind`);\n exactKeys(record, [\"pageIndex\", \"pageKind\", \"byteOffset\", \"byteLength\", \"decodedByteLength\", \"sha256\", \"spatialKey\"], fieldName);\n const byteLength = requireInteger(record.byteLength, `${fieldName}.byteLength`, PVOX_PAGE_SIZE_BYTES, PVOX_PAGE_SIZE_BYTES);\n const decodedByteLength = requireInteger(record.decodedByteLength, `${fieldName}.decodedByteLength`, PVOX_PAGE_SIZE_BYTES, PVOX_PAGE_SIZE_BYTES);\n if (decodedByteLength !== byteLength) throw new Error(`${fieldName} decodedByteLength must equal byteLength because PVOX pages are never compressed.`);\n let spatialKey: PvoxPageSpatialKey | undefined;\n if (record.spatialKey !== undefined) {\n const spatialRecord = asRecord(record.spatialKey, `${fieldName}.spatialKey`);\n exactKeys(spatialRecord, [\"lodLevel\", \"partitionIndex\", \"hierarchyDepth\", \"minimumMortonCode\", \"maximumMortonCode\"], `${fieldName}.spatialKey`);\n const minimumMortonCode = requireString(spatialRecord.minimumMortonCode, `${fieldName}.spatialKey.minimumMortonCode`, 16);\n const maximumMortonCode = requireString(spatialRecord.maximumMortonCode, `${fieldName}.spatialKey.maximumMortonCode`, 16);\n if (!MORTON_CODE.test(minimumMortonCode) || !MORTON_CODE.test(maximumMortonCode) || minimumMortonCode > maximumMortonCode) {\n throw new Error(`${fieldName} spatial Morton range must be canonical and ordered.`);\n }\n spatialKey = {\n lodLevel: requireInteger(spatialRecord.lodLevel, `${fieldName}.spatialKey.lodLevel`, 0, PVOX_DEFAULT_LIMITS.maximumLodCount - 1) as PvoxLodLevel,\n partitionIndex: requireInteger(spatialRecord.partitionIndex, `${fieldName}.spatialKey.partitionIndex`, 0, PVOX_DEFAULT_LIMITS.maximumPartitions - 1),\n hierarchyDepth: requireInteger(spatialRecord.hierarchyDepth, `${fieldName}.spatialKey.hierarchyDepth`, 0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n minimumMortonCode,\n maximumMortonCode,\n };\n }\n const spatialPage = pageKind === \"render-field\" || pageKind === \"collision-field\";\n if (spatialPage !== (spatialKey !== undefined)) {\n throw new Error(`${fieldName} render/collision field pages require spatialKey; metadata/LOD-structure pages forbid it.`);\n }\n return {\n pageIndex: requireInteger(record.pageIndex, `${fieldName}.pageIndex`, 0, PVOX_DEFAULT_LIMITS.maximumPages - 1),\n pageKind,\n byteOffset: requireInteger(record.byteOffset, `${fieldName}.byteOffset`, 0, PVOX_DEFAULT_LIMITS.maximumArtifactBytes - 1),\n byteLength,\n decodedByteLength,\n sha256: requireSha256(record.sha256, `${fieldName}.sha256`),\n ...(spatialKey === undefined ? {} : { spatialKey }),\n };\n}\n\nfunction createLod(value: unknown, index: number, pageCount: number): PvoxLodRecord {\n const fieldName = `PvoxAssetManifestV1.lods[${index}]`;\n const record = asRecord(value, fieldName);\n exactKeys(record, [\n \"level\", \"firstPageIndex\", \"pageCount\", \"brickCount\", \"cellSizeMetres\",\n \"maximumSurfaceErrorMetres\", \"p99SurfaceErrorMetres\", \"silhouetteIou\",\n \"maximumContourDisplacementPx\", \"renderedSsim\", \"p95DeltaE2000\",\n \"normalizedMaterialError\",\n ], fieldName);\n const firstPageIndex = requireInteger(record.firstPageIndex, `${fieldName}.firstPageIndex`, 0, pageCount - 1);\n const lodPageCount = requireInteger(record.pageCount, `${fieldName}.pageCount`, 1, pageCount);\n if (firstPageIndex + lodPageCount > pageCount) throw new Error(`${fieldName} page range exceeds the PVOX page set.`);\n const maximumSurfaceErrorMetres = requireNumber(record.maximumSurfaceErrorMetres, `${fieldName}.maximumSurfaceErrorMetres`, 0, 1_000_000);\n const p99SurfaceErrorMetres = requireNumber(record.p99SurfaceErrorMetres, `${fieldName}.p99SurfaceErrorMetres`, 0, maximumSurfaceErrorMetres);\n return {\n level: requireInteger(record.level, `${fieldName}.level`, 0, 3) as PvoxLodLevel,\n firstPageIndex,\n pageCount: lodPageCount,\n brickCount: requireInteger(record.brickCount, `${fieldName}.brickCount`, 1, PVOX_DEFAULT_LIMITS.maximumBricks),\n cellSizeMetres: requireNumber(record.cellSizeMetres, `${fieldName}.cellSizeMetres`, Number.EPSILON, 1_000_000),\n maximumSurfaceErrorMetres,\n p99SurfaceErrorMetres,\n silhouetteIou: requireNumber(record.silhouetteIou, `${fieldName}.silhouetteIou`, 0, 1),\n maximumContourDisplacementPx: requireNumber(record.maximumContourDisplacementPx, `${fieldName}.maximumContourDisplacementPx`, 0, 1_000_000),\n renderedSsim: requireNumber(record.renderedSsim, `${fieldName}.renderedSsim`, 0, 1),\n p95DeltaE2000: requireNumber(record.p95DeltaE2000, `${fieldName}.p95DeltaE2000`, 0, 100),\n normalizedMaterialError: requireNumber(record.normalizedMaterialError, `${fieldName}.normalizedMaterialError`, 0, 1),\n };\n}\n\nfunction createSourceIngestionLimitsV2(value: unknown): ModelSourceIngestionLimitsV2 {\n const fieldName = \"ModelRequestSpecV2.sourceIngestionLimits\";\n const record = asRecord(value, fieldName);\n exactKeys(record, [\n \"maximumDownloadBytes\",\n \"maximumExpandedBytes\",\n \"maximumArchiveEntries\",\n \"maximumSourceFiles\",\n \"maximumDecodedTextureBytes\",\n \"maximumTextureDimensionPx\",\n ], fieldName);\n const limits: ModelSourceIngestionLimitsV2 = {\n maximumDownloadBytes: requireInteger(record.maximumDownloadBytes, `${fieldName}.maximumDownloadBytes`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumDownloadBytes),\n maximumExpandedBytes: requireInteger(record.maximumExpandedBytes, `${fieldName}.maximumExpandedBytes`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumExpandedBytes),\n maximumArchiveEntries: requireInteger(record.maximumArchiveEntries, `${fieldName}.maximumArchiveEntries`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumArchiveEntries),\n maximumSourceFiles: requireInteger(record.maximumSourceFiles, `${fieldName}.maximumSourceFiles`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumSourceFiles),\n maximumDecodedTextureBytes: requireInteger(record.maximumDecodedTextureBytes, `${fieldName}.maximumDecodedTextureBytes`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumDecodedTextureBytes),\n maximumTextureDimensionPx: requireInteger(record.maximumTextureDimensionPx, `${fieldName}.maximumTextureDimensionPx`, 1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumTextureDimensionPx),\n };\n if (limits.maximumExpandedBytes < limits.maximumDownloadBytes) {\n throw new Error(`${fieldName}.maximumExpandedBytes must cover maximumDownloadBytes.`);\n }\n if (limits.maximumSourceFiles < limits.maximumArchiveEntries) {\n throw new Error(`${fieldName}.maximumSourceFiles must cover maximumArchiveEntries.`);\n }\n if (limits.maximumDecodedTextureBytes > limits.maximumExpandedBytes) {\n throw new Error(`${fieldName}.maximumDecodedTextureBytes must not exceed maximumExpandedBytes.`);\n }\n return limits;\n}\n\nfunction createPvoxRuntimeLimitsV1(value: unknown): PvoxRuntimeLimitsV1 {\n const fieldName = \"ModelRequestSpecV2.pvoxRuntimeProfile.limits\";\n const record = asRecord(value, fieldName);\n exactKeys(record, [\n \"maximumArtifactBytes\",\n \"maximumPages\",\n \"maximumHierarchyDepth\",\n \"maximumHierarchyNodes\",\n \"maximumBricks\",\n \"maximumLogicalVoxels\",\n \"maximumEncodedSurfaceSamples\",\n \"maximumSurfaceProperties\",\n \"maximumPhysicalPaletteRecords\",\n \"maximumPhysicalEvidenceEntries\",\n \"maximumMaterialRegions\",\n \"maximumInteriorLayers\",\n \"maximumMassPropertyRecords\",\n \"maximumBondRecords\",\n \"maximumPartitions\",\n \"maximumLodCount\",\n \"maximumCpuResidentBytes\",\n \"maximumGpuResidentBytes\",\n ], fieldName);\n const limits: PvoxRuntimeLimitsV1 = {\n maximumArtifactBytes: requireInteger(record.maximumArtifactBytes, `${fieldName}.maximumArtifactBytes`, 1, PVOX_DEFAULT_LIMITS.maximumArtifactBytes),\n maximumPages: requireInteger(record.maximumPages, `${fieldName}.maximumPages`, 1, PVOX_DEFAULT_LIMITS.maximumPages),\n maximumHierarchyDepth: requireInteger(record.maximumHierarchyDepth, `${fieldName}.maximumHierarchyDepth`, 0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n maximumHierarchyNodes: requireInteger(record.maximumHierarchyNodes, `${fieldName}.maximumHierarchyNodes`, 1, PVOX_DEFAULT_LIMITS.maximumHierarchyNodes),\n maximumBricks: requireInteger(record.maximumBricks, `${fieldName}.maximumBricks`, 1, PVOX_DEFAULT_LIMITS.maximumBricks),\n maximumLogicalVoxels: requireInteger(record.maximumLogicalVoxels, `${fieldName}.maximumLogicalVoxels`, 1, PVOX_DEFAULT_LIMITS.maximumLogicalVoxels),\n maximumEncodedSurfaceSamples: requireInteger(record.maximumEncodedSurfaceSamples, `${fieldName}.maximumEncodedSurfaceSamples`, 1, PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples),\n maximumSurfaceProperties: requireInteger(record.maximumSurfaceProperties, `${fieldName}.maximumSurfaceProperties`, 1, PVOX_DEFAULT_LIMITS.maximumSurfaceProperties),\n maximumPhysicalPaletteRecords: requireInteger(record.maximumPhysicalPaletteRecords, `${fieldName}.maximumPhysicalPaletteRecords`, 1, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties),\n maximumPhysicalEvidenceEntries: requireInteger(record.maximumPhysicalEvidenceEntries, `${fieldName}.maximumPhysicalEvidenceEntries`, 1, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries),\n maximumMaterialRegions: requireInteger(record.maximumMaterialRegions, `${fieldName}.maximumMaterialRegions`, 1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions),\n maximumInteriorLayers: requireInteger(record.maximumInteriorLayers, `${fieldName}.maximumInteriorLayers`, 1, PVOX_DEFAULT_LIMITS.maximumInteriorLayers),\n maximumMassPropertyRecords: requireInteger(record.maximumMassPropertyRecords, `${fieldName}.maximumMassPropertyRecords`, 1, PVOX_DEFAULT_LIMITS.maximumMassPropertyRecords),\n maximumBondRecords: requireInteger(record.maximumBondRecords, `${fieldName}.maximumBondRecords`, 0, PVOX_DEFAULT_LIMITS.maximumBondRecords),\n maximumPartitions: requireInteger(record.maximumPartitions, `${fieldName}.maximumPartitions`, 1, PVOX_DEFAULT_LIMITS.maximumPartitions),\n maximumLodCount: requireInteger(record.maximumLodCount, `${fieldName}.maximumLodCount`, 1, PVOX_DEFAULT_LIMITS.maximumLodCount),\n maximumCpuResidentBytes: requireInteger(record.maximumCpuResidentBytes, `${fieldName}.maximumCpuResidentBytes`, 1, PVOX_DEFAULT_LIMITS.maximumCpuResidentBytes),\n maximumGpuResidentBytes: requireInteger(record.maximumGpuResidentBytes, `${fieldName}.maximumGpuResidentBytes`, 1, PVOX_DEFAULT_LIMITS.maximumGpuResidentBytes),\n };\n if (limits.maximumArtifactBytes > limits.maximumPages * PVOX_PAGE_SIZE_BYTES) {\n throw new Error(`${fieldName}.maximumPages cannot contain maximumArtifactBytes.`);\n }\n if (limits.maximumLogicalVoxels > limits.maximumBricks * PVOX_BRICK_EDGE_VOXELS ** 3) {\n throw new Error(`${fieldName}.maximumLogicalVoxels cannot exceed the requested brick capacity.`);\n }\n if (limits.maximumEncodedSurfaceSamples > limits.maximumLogicalVoxels) {\n throw new Error(`${fieldName}.maximumEncodedSurfaceSamples cannot exceed maximumLogicalVoxels.`);\n }\n return limits;\n}\n\nfunction createPvoxRuntimeRequestProfileV1(value: unknown): PvoxRuntimeRequestProfileV1 {\n const fieldName = \"ModelRequestSpecV2.pvoxRuntimeProfile\";\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"profileId\", \"fidelityProfileId\", \"capabilityProfileId\", \"geometryMode\", \"requiredCapabilities\", \"limits\"], fieldName);\n const requestedCapabilityEntries = asDenseArray(record.requiredCapabilities, `${fieldName}.requiredCapabilities`, 1, PVOX_CAPABILITIES.length);\n const requiredCapabilities = requestedCapabilityEntries.map((entry, index) => requireEnum(entry, PVOX_CAPABILITIES, `${fieldName}.requiredCapabilities[${index}]`));\n if (new Set(requiredCapabilities).size !== requiredCapabilities.length) {\n throw new Error(`${fieldName}.requiredCapabilities must not contain duplicates.`);\n }\n if (!requiredCapabilities.includes(\"rendering\")) {\n throw new Error(`${fieldName}.requiredCapabilities must include rendering.`);\n }\n const capabilityProfileId = requireEnum(record.capabilityProfileId, PVOX_RUNTIME_CAPABILITY_PROFILE_IDS, `${fieldName}.capabilityProfileId`);\n const profileRequirements: Readonly<Record<PvoxRuntimeCapabilityProfileId, readonly PvoxCapability[]>> = {\n \"static-render-v1\": [\"rendering\"],\n \"world-editable-v1\": [\"rendering\", \"collision\", \"destruction\", \"thermal\", \"moisture\", \"fluid-boundary\"],\n \"deformable-v1\": [\"rendering\", \"deformation\", \"animation\"],\n };\n if (profileRequirements[capabilityProfileId].some((capability) => !requiredCapabilities.includes(capability))) {\n throw new Error(`${fieldName}.requiredCapabilities do not satisfy capabilityProfileId.`);\n }\n const limits = createPvoxRuntimeLimitsV1(record.limits);\n if (capabilityProfileId === \"world-editable-v1\"\n && limits.maximumPhysicalEvidenceEntries < limits.maximumMaterialRegions * PVOX_PHYSICAL_PROPERTIES.length) {\n throw new Error(`${fieldName}.limits must budget a complete physical-property matrix for every allowed material region.`);\n }\n return {\n profileId: requireToken(record.profileId, `${fieldName}.profileId`),\n fidelityProfileId: requireEnum(record.fidelityProfileId, PVOX_FIDELITY_PROFILE_IDS, `${fieldName}.fidelityProfileId`),\n capabilityProfileId,\n geometryMode: requireEnum(record.geometryMode, [\"solid\", \"shell\", \"mixed\", \"auto\"] as const, `${fieldName}.geometryMode`),\n requiredCapabilities,\n limits,\n };\n}\n\n/** Validate and deeply freeze one normalized PVOX model request. */\nexport function createModelRequestSpecV2(input: unknown): ModelRequestSpecV2 {\n const fieldName = \"ModelRequestSpecV2\";\n const record = asRecord(input, fieldName);\n assertDataOnlyTree(record, fieldName);\n exactKeys(record, [\n \"contractVersion\",\n \"policyProfileId\",\n \"requestSemanticProfileHash\",\n \"query\",\n \"revision\",\n \"locale\",\n \"rankerId\",\n \"hardConstraints\",\n \"softPreferences\",\n \"exclusions\",\n \"sourceIngestionLimits\",\n \"pvoxRuntimeProfile\",\n ], fieldName);\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION) {\n throw new Error(`${fieldName}.contractVersion is unsupported.`);\n }\n if (record.policyProfileId !== PVOX_MODEL_REQUEST_POLICY_ID) {\n throw new Error(`${fieldName}.policyProfileId must be ${PVOX_MODEL_REQUEST_POLICY_ID}.`);\n }\n const hardConstraintsRecord = asRecord(record.hardConstraints ?? {}, `${fieldName}.hardConstraints`);\n exactKeys(hardConstraintsRecord, [\"boundsMetres\", \"dimensionsMetres\", \"collision\", \"partition\"], `${fieldName}.hardConstraints`);\n const softPreferencesRecord = asRecord(record.softPreferences ?? {}, `${fieldName}.softPreferences`);\n for (const field of [\"materials\", \"colors\", \"tags\"] as const) {\n if (softPreferencesRecord[field] !== undefined) {\n asDenseArray(softPreferencesRecord[field], `${fieldName}.softPreferences.${field}`, 0, 32);\n }\n }\n const exclusions = asDenseArray(record.exclusions ?? [], `${fieldName}.exclusions`, 0, 32);\n const normalizedV1 = createModelRequestSpec({\n query: record.query,\n revision: record.revision,\n ...(record.locale === undefined ? {} : { locale: record.locale }),\n ...(record.rankerId === undefined ? {} : { rankerId: record.rankerId }),\n hardConstraints: hardConstraintsRecord,\n softPreferences: softPreferencesRecord,\n exclusions,\n });\n const hardConstraints: ModelHardConstraintsV2 = {\n ...(normalizedV1.hardConstraints.boundsMetres === undefined ? {} : { boundsMetres: normalizedV1.hardConstraints.boundsMetres }),\n ...(normalizedV1.hardConstraints.dimensionsMetres === undefined ? {} : { dimensionsMetres: normalizedV1.hardConstraints.dimensionsMetres }),\n ...(normalizedV1.hardConstraints.collision === undefined ? {} : { collision: normalizedV1.hardConstraints.collision }),\n ...(normalizedV1.hardConstraints.partition === undefined ? {} : { partition: normalizedV1.hardConstraints.partition }),\n };\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n policyProfileId: PVOX_MODEL_REQUEST_POLICY_ID,\n requestSemanticProfileHash: requireSha256(record.requestSemanticProfileHash, `${fieldName}.requestSemanticProfileHash`),\n query: normalizedV1.query,\n revision: normalizedV1.revision,\n ...(normalizedV1.locale === undefined ? {} : { locale: normalizedV1.locale }),\n ...(normalizedV1.rankerId === undefined ? {} : { rankerId: normalizedV1.rankerId }),\n hardConstraints,\n softPreferences: normalizedV1.softPreferences,\n exclusions: normalizedV1.exclusions,\n sourceIngestionLimits: createSourceIngestionLimitsV2(record.sourceIngestionLimits),\n pvoxRuntimeProfile: createPvoxRuntimeRequestProfileV1(record.pvoxRuntimeProfile),\n });\n}\n\n/** Validate and deeply freeze authenticated PVOX artifact metadata. */\nexport function createPvoxAssetManifestV1(input: unknown): PvoxAssetManifestV1 {\n const record = asRecord(input, \"PvoxAssetManifestV1\");\n exactKeys(record, [\n \"manifestVersion\", \"representation\", \"formatVersion\", \"contentType\", \"fileExtension\",\n \"magic\", \"brickEdgeVoxels\", \"pageSizeBytes\", \"geometryMode\", \"sourceContentHash\",\n \"canonicalDocumentHash\", \"rootHash\", \"directoryHash\", \"pageSetHash\", \"binaryClosureHash\",\n \"validationEvidenceHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\",\n \"headerByteLength\", \"directoryEntryByteLength\", \"sectionCount\", \"maximumRunsPerBrick\",\n \"maximumLocalSamplesPerBrick\", \"maximumEncodedBrickPayloadBytes\",\n \"coordinateSystem\", \"boundsMetres\", \"artifact\", \"pages\", \"lods\",\n ], \"PvoxAssetManifestV1\");\n if (record.manifestVersion !== PVOX_ASSET_MANIFEST_VERSION) throw new Error(\"PvoxAssetManifestV1.manifestVersion is unsupported.\");\n if (record.representation !== \"pvox\") throw new Error(\"PvoxAssetManifestV1.representation must be pvox.\");\n const formatVersion = asRecord(record.formatVersion, \"PvoxAssetManifestV1.formatVersion\");\n exactKeys(formatVersion, [\"major\", \"minor\"], \"PvoxAssetManifestV1.formatVersion\");\n if (formatVersion.major !== PVOX_FORMAT_VERSION.major || formatVersion.minor !== PVOX_FORMAT_VERSION.minor) throw new Error(\"PvoxAssetManifestV1.formatVersion is unsupported.\");\n if (record.contentType !== PVOX_CONTENT_TYPE || record.fileExtension !== PVOX_FILE_EXTENSION || record.magic !== PVOX_MAGIC) {\n throw new Error(\"PvoxAssetManifestV1 must declare the canonical PVOX content type, extension, and magic.\");\n }\n if (record.brickEdgeVoxels !== PVOX_BRICK_EDGE_VOXELS || record.pageSizeBytes !== PVOX_PAGE_SIZE_BYTES) {\n throw new Error(\"PvoxAssetManifestV1 must use fixed 8-cubed bricks and 64-KiB pages.\");\n }\n assertCoordinateSystem(record.coordinateSystem, \"PvoxAssetManifestV1.coordinateSystem\");\n const boundsMetres = createBounds(record.boundsMetres, \"PvoxAssetManifestV1.boundsMetres\");\n assertFloorCentredBounds(boundsMetres, \"PvoxAssetManifestV1.boundsMetres\");\n const artifact = createResource(record.artifact);\n if (artifact.byteLength % PVOX_PAGE_SIZE_BYTES !== 0) throw new Error(\"PvoxAssetManifestV1 artifact byteLength must contain whole 64-KiB pages.\");\n const pageEntries = asDenseArray(record.pages, \"PvoxAssetManifestV1.pages\", 1, PVOX_DEFAULT_LIMITS.maximumPages);\n const pages = pageEntries.map(createPage);\n let expectedOffset = 0;\n const previousSpatialMaximumByScope = new Map<string, string>();\n for (const [index, current] of pages.entries()) {\n if (current.pageIndex !== index) throw new Error(\"PvoxAssetManifestV1 pageIndex values must be contiguous from zero.\");\n if (current.byteOffset !== expectedOffset || current.byteOffset % PVOX_PAGE_SIZE_BYTES !== 0) {\n throw new Error(\"PvoxAssetManifestV1 page byteOffset values must be contiguous and page aligned.\");\n }\n const spatialKey = current.spatialKey;\n if (spatialKey !== undefined) {\n const scope = `${current.pageKind}\\u0000${spatialKey.lodLevel}\\u0000${spatialKey.partitionIndex}`;\n const previousMaximum = previousSpatialMaximumByScope.get(scope);\n if (previousMaximum !== undefined && spatialKey.minimumMortonCode <= previousMaximum) {\n throw new Error(\"PvoxAssetManifestV1 page Morton ranges must be ordered and non-overlapping within each kind, LOD, and partition.\");\n }\n previousSpatialMaximumByScope.set(scope, spatialKey.maximumMortonCode);\n }\n expectedOffset += current.byteLength;\n }\n if (expectedOffset !== artifact.byteLength) throw new Error(\"PvoxAssetManifestV1 pages must exactly cover the artifact bytes.\");\n const lodEntries = asDenseArray(record.lods, \"PvoxAssetManifestV1.lods\", 1, 4);\n const lods = lodEntries.map((entry, index) => createLod(entry, index, pages.length));\n for (const [index, current] of lods.entries()) {\n if (current.level !== index) throw new Error(\"PvoxAssetManifestV1 LOD levels must be contiguous from LOD0.\");\n const previous = lods[index - 1];\n if (previous !== undefined && (\n current.brickCount > previous.brickCount\n || current.cellSizeMetres < previous.cellSizeMetres\n || current.maximumSurfaceErrorMetres < previous.maximumSurfaceErrorMetres\n || current.p99SurfaceErrorMetres < previous.p99SurfaceErrorMetres\n )) throw new Error(\"PvoxAssetManifestV1 LOD complexity and errors must be monotonic.\");\n if (pages.slice(current.firstPageIndex, current.firstPageIndex + current.pageCount).some(({ pageKind, spatialKey }) => pageKind !== \"render-field\" || spatialKey?.lodLevel !== current.level)) {\n throw new Error(\"PvoxAssetManifestV1 LOD page ranges must reference render-field pages in the matching LOD scope.\");\n }\n }\n const sourceContentHash = requireSha256(record.sourceContentHash, \"PvoxAssetManifestV1.sourceContentHash\");\n const canonicalDocumentHash = requireSha256(record.canonicalDocumentHash, \"PvoxAssetManifestV1.canonicalDocumentHash\");\n const compilationInputHash = requireSha256(record.compilationInputHash, \"PvoxAssetManifestV1.compilationInputHash\");\n const runtimeRequestProfileHash = requireSha256(record.runtimeRequestProfileHash, \"PvoxAssetManifestV1.runtimeRequestProfileHash\");\n if (new Set([sourceContentHash, canonicalDocumentHash, compilationInputHash, runtimeRequestProfileHash]).size !== 4) {\n throw new Error(\"PvoxAssetManifestV1 source, canonical document, compilation input, and runtime request profile hashes must be distinct attestations.\");\n }\n if (record.headerByteLength !== PVOX_HEADER_BYTE_LENGTH\n || record.directoryEntryByteLength !== PVOX_DIRECTORY_ENTRY_BYTE_LENGTH\n || record.maximumRunsPerBrick !== PVOX_MAX_RUNS_PER_BRICK\n || record.maximumLocalSamplesPerBrick !== PVOX_MAX_LOCAL_SAMPLES_PER_BRICK\n || record.maximumEncodedBrickPayloadBytes !== PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES) {\n throw new Error(\"PvoxAssetManifestV1 must declare the fixed PVOX 1.0 layout and brick codec limits.\");\n }\n return deepFreeze({\n manifestVersion: PVOX_ASSET_MANIFEST_VERSION,\n representation: \"pvox\",\n formatVersion: PVOX_FORMAT_VERSION,\n contentType: PVOX_CONTENT_TYPE,\n fileExtension: PVOX_FILE_EXTENSION,\n magic: PVOX_MAGIC,\n brickEdgeVoxels: PVOX_BRICK_EDGE_VOXELS,\n pageSizeBytes: PVOX_PAGE_SIZE_BYTES,\n geometryMode: requireEnum(record.geometryMode, [\"solid\", \"shell\", \"mixed\"] as const, \"PvoxAssetManifestV1.geometryMode\"),\n sourceContentHash,\n canonicalDocumentHash,\n rootHash: requireSha256(record.rootHash, \"PvoxAssetManifestV1.rootHash\"),\n directoryHash: requireSha256(record.directoryHash, \"PvoxAssetManifestV1.directoryHash\"),\n pageSetHash: requireSha256(record.pageSetHash, \"PvoxAssetManifestV1.pageSetHash\"),\n binaryClosureHash: requireSha256(record.binaryClosureHash, \"PvoxAssetManifestV1.binaryClosureHash\"),\n validationEvidenceHash: requireSha256(record.validationEvidenceHash, \"PvoxAssetManifestV1.validationEvidenceHash\"),\n compilationInputHash,\n runtimeRequestProfileHash,\n headerByteLength: PVOX_HEADER_BYTE_LENGTH,\n directoryEntryByteLength: PVOX_DIRECTORY_ENTRY_BYTE_LENGTH,\n sectionCount: requireInteger(record.sectionCount, \"PvoxAssetManifestV1.sectionCount\", PVOX_MIN_STATIC_SECTION_COUNT, PVOX_MAX_SECTIONS),\n maximumRunsPerBrick: PVOX_MAX_RUNS_PER_BRICK,\n maximumLocalSamplesPerBrick: PVOX_MAX_LOCAL_SAMPLES_PER_BRICK,\n maximumEncodedBrickPayloadBytes: PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES,\n coordinateSystem: CANONICAL_MODEL_COORDINATE_SYSTEM,\n boundsMetres,\n artifact,\n pages,\n lods,\n });\n}\n\n/** Compatibility alias retaining the explicit v1 manifest implementation. */\nexport function createPvoxAssetManifest(input: unknown): PvoxAssetManifestV1 {\n return createPvoxAssetManifestV1(input);\n}\n\n/** Validate and deeply freeze a PVOX runtime technical profile. */\nexport function createVoxelTechnicalProfile(input: unknown): VoxelTechnicalProfile {\n const record = asRecord(input, \"VoxelTechnicalProfile\");\n exactKeys(record, [\n \"boundsMetres\", \"dimensionsMetres\", \"geometryMode\", \"artifactByteLength\", \"pageCount\",\n \"brickCount\", \"logicalVoxelCapacity\", \"encodedSurfaceSampleCount\", \"surfacePropertyCount\", \"sectionCount\",\n \"levelSpanRecordCount\", \"physicalPaletteRecordCount\", \"physicalEvidenceRecordCount\", \"materialRegionCount\",\n \"interiorLayerRecordCount\", \"massPropertyRecordCount\", \"bondRecordCount\", \"hierarchyDepth\", \"hierarchyNodeCount\", \"lodCount\",\n \"collisionHierarchyNodeCount\", \"collisionBrickCount\", \"collisionLogicalVoxelCapacity\", \"collisionEncodedSurfaceSampleCount\",\n \"cpuResidentByteLength\", \"gpuResidentByteLength\", \"hasCollision\", \"partitionCount\",\n \"maximumPartitionExtentMetres\", \"maximumPartitionDiagonalMetres\",\n ], \"VoxelTechnicalProfile\");\n const boundsMetres = createBounds(record.boundsMetres, \"VoxelTechnicalProfile.boundsMetres\");\n assertFloorCentredBounds(boundsMetres, \"VoxelTechnicalProfile.boundsMetres\");\n const dimensionsMetres = createDimensions(record.dimensionsMetres, \"VoxelTechnicalProfile.dimensionsMetres\");\n const derived = boundsMetres.max.map((coordinate, index) => coordinate - boundsMetres.min[index]!) as [number, number, number];\n const supplied = [dimensionsMetres.width, dimensionsMetres.height, dimensionsMetres.depth];\n if (derived.some((coordinate, index) => Math.abs(coordinate - supplied[index]!) > Math.max(1e-6, Math.abs(coordinate) * 1e-6))) {\n throw new Error(\"VoxelTechnicalProfile dimensionsMetres must match boundsMetres.\");\n }\n const artifactByteLength = requireInteger(record.artifactByteLength, \"VoxelTechnicalProfile.artifactByteLength\", 1, PVOX_DEFAULT_LIMITS.maximumArtifactBytes);\n const pageCount = requireInteger(record.pageCount, \"VoxelTechnicalProfile.pageCount\", 1, PVOX_DEFAULT_LIMITS.maximumPages);\n if (artifactByteLength !== pageCount * PVOX_PAGE_SIZE_BYTES) {\n throw new Error(\"VoxelTechnicalProfile artifactByteLength must equal pageCount multiplied by the fixed PVOX page size.\");\n }\n const brickCount = requireInteger(record.brickCount, \"VoxelTechnicalProfile.brickCount\", 1, PVOX_DEFAULT_LIMITS.maximumBricks);\n const logicalVoxelCapacity = requireInteger(record.logicalVoxelCapacity, \"VoxelTechnicalProfile.logicalVoxelCapacity\", 1, PVOX_DEFAULT_LIMITS.maximumLogicalVoxels);\n if (logicalVoxelCapacity !== brickCount * PVOX_BRICK_EDGE_VOXELS ** 3) {\n throw new Error(\"VoxelTechnicalProfile logicalVoxelCapacity must equal brickCount multiplied by 512 voxels per brick.\");\n }\n const encodedSurfaceSampleCount = requireInteger(record.encodedSurfaceSampleCount, \"VoxelTechnicalProfile.encodedSurfaceSampleCount\", 1, PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples);\n if (encodedSurfaceSampleCount > logicalVoxelCapacity) {\n throw new Error(\"VoxelTechnicalProfile encodedSurfaceSampleCount cannot exceed logicalVoxelCapacity.\");\n }\n const surfacePropertyCount = requireInteger(record.surfacePropertyCount, \"VoxelTechnicalProfile.surfacePropertyCount\", 1, PVOX_DEFAULT_LIMITS.maximumSurfaceProperties);\n const sectionCount = requireInteger(record.sectionCount, \"VoxelTechnicalProfile.sectionCount\", PVOX_MIN_STATIC_SECTION_COUNT, PVOX_MAX_SECTIONS);\n const hierarchyDepth = requireInteger(record.hierarchyDepth, \"VoxelTechnicalProfile.hierarchyDepth\", 0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth);\n const hierarchyNodeCount = requireInteger(record.hierarchyNodeCount, \"VoxelTechnicalProfile.hierarchyNodeCount\", 1, PVOX_DEFAULT_LIMITS.maximumHierarchyNodes);\n const lodCount = requireInteger(record.lodCount, \"VoxelTechnicalProfile.lodCount\", 1, PVOX_DEFAULT_LIMITS.maximumLodCount);\n const partitionCount = requireInteger(record.partitionCount, \"VoxelTechnicalProfile.partitionCount\", 1, PVOX_DEFAULT_LIMITS.maximumPartitions);\n const levelSpanRecordCount = requireInteger(record.levelSpanRecordCount, \"VoxelTechnicalProfile.levelSpanRecordCount\", partitionCount * lodCount, partitionCount * lodCount * (hierarchyDepth + 1));\n const physicalPaletteRecordCount = requireInteger(record.physicalPaletteRecordCount, \"VoxelTechnicalProfile.physicalPaletteRecordCount\", 1, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties);\n const physicalEvidenceRecordCount = requireInteger(record.physicalEvidenceRecordCount, \"VoxelTechnicalProfile.physicalEvidenceRecordCount\", 0, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries);\n const materialRegionCount = requireInteger(record.materialRegionCount, \"VoxelTechnicalProfile.materialRegionCount\", 1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions);\n const interiorLayerRecordCount = requireInteger(record.interiorLayerRecordCount, \"VoxelTechnicalProfile.interiorLayerRecordCount\", 0, PVOX_DEFAULT_LIMITS.maximumInteriorLayers);\n const massPropertyRecordCount = requireInteger(record.massPropertyRecordCount, \"VoxelTechnicalProfile.massPropertyRecordCount\", 0, PVOX_DEFAULT_LIMITS.maximumMassPropertyRecords);\n const bondRecordCount = requireInteger(record.bondRecordCount, \"VoxelTechnicalProfile.bondRecordCount\", 0, PVOX_DEFAULT_LIMITS.maximumBondRecords);\n const hasCollision = requireBoolean(record.hasCollision, \"VoxelTechnicalProfile.hasCollision\");\n const collisionHierarchyNodeCount = requireInteger(record.collisionHierarchyNodeCount, \"VoxelTechnicalProfile.collisionHierarchyNodeCount\", hasCollision ? 1 : 0, hasCollision ? PVOX_DEFAULT_LIMITS.maximumHierarchyNodes : 0);\n const collisionBrickCount = requireInteger(record.collisionBrickCount, \"VoxelTechnicalProfile.collisionBrickCount\", hasCollision ? 1 : 0, hasCollision ? PVOX_DEFAULT_LIMITS.maximumBricks : 0);\n const collisionLogicalVoxelCapacity = requireInteger(record.collisionLogicalVoxelCapacity, \"VoxelTechnicalProfile.collisionLogicalVoxelCapacity\", hasCollision ? PVOX_BRICK_EDGE_VOXELS ** 3 : 0, hasCollision ? PVOX_DEFAULT_LIMITS.maximumLogicalVoxels : 0);\n if (collisionLogicalVoxelCapacity !== collisionBrickCount * PVOX_BRICK_EDGE_VOXELS ** 3) {\n throw new Error(\"VoxelTechnicalProfile collisionLogicalVoxelCapacity must equal collisionBrickCount multiplied by 512.\");\n }\n const collisionEncodedSurfaceSampleCount = requireInteger(record.collisionEncodedSurfaceSampleCount, \"VoxelTechnicalProfile.collisionEncodedSurfaceSampleCount\", hasCollision ? 1 : 0, hasCollision ? PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples : 0);\n if (collisionEncodedSurfaceSampleCount > collisionLogicalVoxelCapacity) {\n throw new Error(\"VoxelTechnicalProfile collision encoded sample count cannot exceed its logical voxel capacity.\");\n }\n const requiredSectionCount = PVOX_MIN_STATIC_SECTION_COUNT + (bondRecordCount > 0 ? 1 : 0) + (hasCollision ? PVOX_COLLISION_SECTION_COUNT : 0);\n if (sectionCount !== requiredSectionCount) {\n throw new Error(\"VoxelTechnicalProfile sectionCount must exactly represent the closed static, optional bond, and optional collision section registry.\");\n }\n const maximumDimensionMetres = Math.max(...supplied);\n const fullDiagonalMetres = Math.hypot(...supplied);\n const maximumPartitionExtentMetres = requireNumber(record.maximumPartitionExtentMetres, \"VoxelTechnicalProfile.maximumPartitionExtentMetres\", Number.EPSILON, maximumDimensionMetres + Math.max(1e-9, maximumDimensionMetres * 1e-9));\n const maximumPartitionDiagonalMetres = requireNumber(record.maximumPartitionDiagonalMetres, \"VoxelTechnicalProfile.maximumPartitionDiagonalMetres\", maximumPartitionExtentMetres, fullDiagonalMetres + Math.max(1e-9, fullDiagonalMetres * 1e-9));\n if (partitionCount === 1 && (!approximatelyEqual(maximumPartitionExtentMetres, maximumDimensionMetres) || !approximatelyEqual(maximumPartitionDiagonalMetres, fullDiagonalMetres))) {\n throw new Error(\"VoxelTechnicalProfile single-partition extent and diagonal must cover the complete bounds.\");\n }\n const profile: VoxelTechnicalProfile = {\n boundsMetres,\n dimensionsMetres,\n geometryMode: requireEnum(record.geometryMode, [\"solid\", \"shell\", \"mixed\"] as const, \"VoxelTechnicalProfile.geometryMode\"),\n artifactByteLength,\n pageCount,\n brickCount,\n logicalVoxelCapacity,\n encodedSurfaceSampleCount,\n surfacePropertyCount,\n sectionCount,\n levelSpanRecordCount,\n physicalPaletteRecordCount,\n physicalEvidenceRecordCount,\n materialRegionCount,\n interiorLayerRecordCount,\n massPropertyRecordCount,\n bondRecordCount,\n hierarchyDepth,\n hierarchyNodeCount,\n lodCount,\n collisionHierarchyNodeCount,\n collisionBrickCount,\n collisionLogicalVoxelCapacity,\n collisionEncodedSurfaceSampleCount,\n cpuResidentByteLength: requireInteger(record.cpuResidentByteLength, \"VoxelTechnicalProfile.cpuResidentByteLength\", 1, PVOX_DEFAULT_LIMITS.maximumCpuResidentBytes),\n gpuResidentByteLength: requireInteger(record.gpuResidentByteLength, \"VoxelTechnicalProfile.gpuResidentByteLength\", 1, PVOX_DEFAULT_LIMITS.maximumGpuResidentBytes),\n hasCollision,\n partitionCount,\n maximumPartitionExtentMetres,\n maximumPartitionDiagonalMetres,\n };\n const minimumArtifactByteLength = calculatePvoxMinimumArtifactByteLength(profile);\n if (minimumArtifactByteLength > artifactByteLength) {\n throw new Error(`VoxelTechnicalProfile fixed PVOX records require at least ${minimumArtifactByteLength} artifact bytes.`);\n }\n return deepFreeze(profile);\n}\n\n/** Validate and deeply freeze one PVOX capability decision. */\nexport function createVoxelCapabilityAssessment(input: unknown): VoxelCapabilityAssessment {\n const record = asRecord(input, \"VoxelCapabilityAssessment\");\n exactKeys(record, [\"capability\", \"status\", \"evaluatorId\", \"evaluatorVersion\", \"subjectContentHash\", \"evidenceHash\", \"reasonCodes\", \"evaluatedAt\"], \"VoxelCapabilityAssessment\");\n const status = requireEnum(record.status, [\"supported\", \"unsupported\", \"not-applicable\"] as const, \"VoxelCapabilityAssessment.status\");\n const reasonCodes = requireReasonCodes(record.reasonCodes, \"VoxelCapabilityAssessment.reasonCodes\");\n if (status === \"supported\" && reasonCodes.length !== 0) throw new Error(\"Supported capability evidence must not contain failure reason codes.\");\n if (status !== \"supported\" && reasonCodes.length === 0) throw new Error(\"Unavailable capability evidence requires a reason code.\");\n return deepFreeze({\n capability: requireEnum(record.capability, PVOX_CAPABILITIES, \"VoxelCapabilityAssessment.capability\"),\n status,\n evaluatorId: requireToken(record.evaluatorId, \"VoxelCapabilityAssessment.evaluatorId\"),\n evaluatorVersion: assertImmutableAssetVersion(record.evaluatorVersion),\n subjectContentHash: requireSha256(record.subjectContentHash, \"VoxelCapabilityAssessment.subjectContentHash\"),\n evidenceHash: requireSha256(record.evidenceHash, \"VoxelCapabilityAssessment.evidenceHash\"),\n reasonCodes,\n evaluatedAt: requireTimestamp(record.evaluatedAt, \"VoxelCapabilityAssessment.evaluatedAt\"),\n });\n}\n\nexport const PVOX_PHYSICAL_PROPERTY_POLICIES: Readonly<Record<PhysicalPropertyKind, Readonly<{ unit: string; minimum: number; maximum: number }>>> = deepFreeze({\n density: { unit: \"kg/m3\", minimum: Number.EPSILON, maximum: 50_000 },\n hardness: { unit: \"Pa\", minimum: Number.EPSILON, maximum: 1e12 },\n \"tensile-strength\": { unit: \"Pa\", minimum: Number.EPSILON, maximum: 1e12 },\n \"compressive-strength\": { unit: \"Pa\", minimum: Number.EPSILON, maximum: 1e12 },\n \"shear-strength\": { unit: \"Pa\", minimum: Number.EPSILON, maximum: 1e12 },\n \"fracture-energy\": { unit: \"J/m2\", minimum: Number.EPSILON, maximum: 1e9 },\n friction: { unit: \"1\", minimum: 0, maximum: 1 },\n restitution: { unit: \"1\", minimum: 0, maximum: 1 },\n \"thermal-conductivity\": { unit: \"W/(m*K)\", minimum: 0, maximum: 1e5 },\n \"heat-capacity\": { unit: \"J/(kg*K)\", minimum: 0, maximum: 1e7 },\n \"thermal-expansion\": { unit: \"1/K\", minimum: -1, maximum: 1 },\n \"ignition-temperature\": { unit: \"K\", minimum: Number.EPSILON, maximum: 100_000 },\n \"melting-temperature\": { unit: \"K\", minimum: Number.EPSILON, maximum: 100_000 },\n porosity: { unit: \"1\", minimum: 0, maximum: 1 },\n permeability: { unit: \"m2\", minimum: 0, maximum: 1 },\n \"moisture-response\": { unit: \"1\", minimum: 0, maximum: 1 },\n flammability: { unit: \"1\", minimum: 0, maximum: 1 },\n \"corrosion-rate\": { unit: \"m/s\", minimum: 0, maximum: 1 },\n \"interior-thickness\": { unit: \"m\", minimum: Number.EPSILON, maximum: 1_000_000 },\n});\n\n/** Validate and deeply freeze one localized physical-property value. */\nexport function createPhysicalPropertyEvidence(input: unknown): PhysicalPropertyEvidence {\n const record = asRecord(input, \"PhysicalPropertyEvidence\");\n exactKeys(record, [\"property\", \"value\", \"unit\", \"provenance\", \"confidence\", \"subjectContentHash\", \"regionId\", \"materialId\", \"policyId\", \"policyVersion\", \"evidenceHash\", \"reviewedBy\", \"reviewedAt\", \"reviewToken\"], \"PhysicalPropertyEvidence\");\n const property = requireEnum(record.property, PVOX_PHYSICAL_PROPERTIES, \"PhysicalPropertyEvidence.property\");\n const policy = PVOX_PHYSICAL_PROPERTY_POLICIES[property];\n if (record.policyId !== PVOX_PHYSICAL_PROPERTY_POLICY_ID || record.policyVersion !== PVOX_PHYSICAL_PROPERTY_POLICY_VERSION) {\n throw new Error(\"PhysicalPropertyEvidence must use the governed immutable physical-property policy.\");\n }\n assertImmutableAssetVersion(record.policyVersion);\n if (record.unit !== policy.unit) throw new Error(\"PhysicalPropertyEvidence unit must match its governed property policy.\");\n const provenance = requireEnum(record.provenance, [\"source\", \"authored\", \"derived\", \"inferred\", \"default\"] as const, \"PhysicalPropertyEvidence.provenance\");\n const reviewedBy = record.reviewedBy === undefined ? undefined : requireToken(record.reviewedBy, \"PhysicalPropertyEvidence.reviewedBy\");\n const reviewedAt = record.reviewedAt === undefined ? undefined : requireTimestamp(record.reviewedAt, \"PhysicalPropertyEvidence.reviewedAt\");\n const reviewToken = record.reviewToken === undefined ? undefined : requireAttestation(record.reviewToken, \"PhysicalPropertyEvidence.reviewToken\");\n if (new Set([reviewedBy, reviewedAt, reviewToken].map((entry) => entry === undefined)).size !== 1) throw new Error(\"PhysicalPropertyEvidence signed review identity, timestamp, and token must be supplied together.\");\n if (provenance === \"inferred\" && reviewedBy === undefined) throw new Error(\"Inferred PhysicalPropertyEvidence requires human review.\");\n return deepFreeze({\n property,\n value: requireNumber(record.value, \"PhysicalPropertyEvidence.value\", policy.minimum, policy.maximum),\n unit: policy.unit,\n provenance,\n confidence: requireNumber(record.confidence, \"PhysicalPropertyEvidence.confidence\", 0, 1),\n subjectContentHash: requireSha256(record.subjectContentHash, \"PhysicalPropertyEvidence.subjectContentHash\"),\n regionId: requireToken(record.regionId, \"PhysicalPropertyEvidence.regionId\"),\n materialId: requireToken(record.materialId, \"PhysicalPropertyEvidence.materialId\"),\n policyId: PVOX_PHYSICAL_PROPERTY_POLICY_ID,\n policyVersion: PVOX_PHYSICAL_PROPERTY_POLICY_VERSION,\n evidenceHash: requireSha256(record.evidenceHash, \"PhysicalPropertyEvidence.evidenceHash\"),\n ...(reviewedBy === undefined ? {} : { reviewedBy, reviewedAt, reviewToken }),\n });\n}\n\n/** Validate the validator-attested inventory that makes omitted PVOX material regions detectable. */\nexport function createPvoxPhysicalRegionInventoryV1(input: unknown): PvoxPhysicalRegionInventoryV1 {\n const fieldName = \"PvoxPhysicalRegionInventoryV1\";\n const record = asRecord(input, fieldName);\n exactKeys(record, [\"inventoryVersion\", \"subjectContentHash\", \"inventoryHash\", \"inventoryHashAttestation\", \"validationEvidenceHash\", \"entries\"], fieldName);\n if (record.inventoryVersion !== PVOX_PHYSICAL_REGION_INVENTORY_VERSION) throw new Error(`${fieldName}.inventoryVersion is unsupported.`);\n const entriesInput = asDenseArray(record.entries, `${fieldName}.entries`, 1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions);\n const entries = entriesInput.map((entry, index): PvoxPhysicalRegionInventoryEntry => {\n const entryName = `${fieldName}.entries[${index}]`;\n const item = asRecord(entry, entryName);\n exactKeys(item, [\"regionIndex\", \"physicalPaletteIndex\", \"regionId\", \"materialId\"], entryName);\n return {\n regionIndex: requireInteger(item.regionIndex, `${entryName}.regionIndex`, 0, PVOX_DEFAULT_LIMITS.maximumMaterialRegions - 1),\n physicalPaletteIndex: requireInteger(item.physicalPaletteIndex, `${entryName}.physicalPaletteIndex`, 0, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties - 1),\n regionId: requireToken(item.regionId, `${entryName}.regionId`),\n materialId: requireToken(item.materialId, `${entryName}.materialId`),\n };\n });\n if (entries.some((entry, index) => entry.regionIndex !== index)) throw new Error(`${fieldName} regionIndex values must be contiguous and canonically ordered.`);\n const pairs = entries.map(({ regionId, materialId }) => `${regionId}\\u0000${materialId}`);\n if (new Set(pairs).size !== pairs.length) throw new Error(`${fieldName} region/material pairs must be unique.`);\n const inventoryHash = requireSha256(record.inventoryHash, `${fieldName}.inventoryHash`);\n return deepFreeze({\n inventoryVersion: PVOX_PHYSICAL_REGION_INVENTORY_VERSION,\n subjectContentHash: requireSha256(record.subjectContentHash, `${fieldName}.subjectContentHash`),\n inventoryHash,\n inventoryHashAttestation: createHashAttestation(record.inventoryHashAttestation, PVOX_PHYSICAL_INVENTORY_HASH_DOMAIN, inventoryHash, `${fieldName}.inventoryHashAttestation`),\n validationEvidenceHash: requireSha256(record.validationEvidenceHash, `${fieldName}.validationEvidenceHash`),\n entries,\n });\n}\n\nfunction createReviewedStructuralEvidence(\n input: unknown,\n expectedKind: PvoxReviewedStructuralEvidenceKind,\n expectedSubjectHash: string,\n expectedInventoryHash: string,\n expectedRecordCount: number,\n fieldName: string,\n): PvoxReviewedStructuralEvidence {\n const record = asRecord(input, fieldName);\n exactKeys(record, [\"kind\", \"subjectContentHash\", \"physicalInventoryHash\", \"recordCount\", \"evidenceHash\", \"reviewerId\", \"reviewedAt\", \"reviewToken\"], fieldName);\n if (record.kind !== expectedKind) throw new Error(`${fieldName}.kind must be ${expectedKind}.`);\n const subjectContentHash = requireSha256(record.subjectContentHash, `${fieldName}.subjectContentHash`);\n const physicalInventoryHash = requireSha256(record.physicalInventoryHash, `${fieldName}.physicalInventoryHash`);\n const recordCount = requireInteger(record.recordCount, `${fieldName}.recordCount`, 0, PVOX_DEFAULT_LIMITS.maximumBondRecords);\n if (subjectContentHash !== expectedSubjectHash || physicalInventoryHash !== expectedInventoryHash || recordCount !== expectedRecordCount) {\n throw new Error(`${fieldName} must bind the exact PVOX closure, physical inventory, and binary record count.`);\n }\n return deepFreeze({\n kind: expectedKind,\n subjectContentHash,\n physicalInventoryHash,\n recordCount,\n evidenceHash: requireSha256(record.evidenceHash, `${fieldName}.evidenceHash`),\n reviewerId: requireToken(record.reviewerId, `${fieldName}.reviewerId`),\n reviewedAt: requireTimestamp(record.reviewedAt, `${fieldName}.reviewedAt`),\n reviewToken: requireAttestation(record.reviewToken, `${fieldName}.reviewToken`),\n });\n}\n\n/** Validate a measured fidelity decision and derive its non-overridable outcome. */\nexport function createPvoxFidelityEvidence(input: unknown): PvoxFidelityEvidence {\n const record = asRecord(input, \"PvoxFidelityEvidence\");\n exactKeys(record, [\n \"profileId\", \"surfaceProfileId\", \"profileVersion\", \"outcome\", \"canonicalDocumentHash\",\n \"pvoxBinaryClosureHash\", \"evaluatedDiagonalMetres\", \"lod0CellSizeMetres\", \"maximumAllowedSurfaceErrorMetres\",\n \"maximumSurfaceErrorMetres\", \"p99AllowedSurfaceErrorMetres\", \"p99SurfaceErrorMetres\",\n \"minimumSilhouetteIou\", \"silhouetteIou\", \"maximumAllowedContourDisplacementPx\",\n \"maximumContourDisplacementPx\", \"minimumRenderedSsim\", \"renderedSsim\",\n \"maximumP95DeltaE2000\", \"p95DeltaE2000\", \"maximumNormalizedMaterialError\",\n \"normalizedMaterialError\", \"evidenceHash\", \"evaluatedAt\", \"decisionToken\",\n ], \"PvoxFidelityEvidence\");\n const profileId = requireEnum(record.profileId, PVOX_FIDELITY_PROFILE_IDS, \"PvoxFidelityEvidence.profileId\");\n const surfaceProfileId = requireEnum(record.surfaceProfileId, [\n \"precision-hero-v1\",\n \"props-furniture-v1\",\n \"rocks-organic-shells-v1\",\n \"buildings-v1\",\n ] as const, \"PvoxFidelityEvidence.surfaceProfileId\");\n if (profileId !== \"deformable-v1\" && profileId !== surfaceProfileId) {\n throw new Error(\"PvoxFidelityEvidence surfaceProfileId must match its governed profileId.\");\n }\n if (record.profileVersion !== PVOX_FIDELITY_PROFILE_VERSION) {\n throw new Error(\"PvoxFidelityEvidence.profileVersion must use the governed profile version.\");\n }\n assertImmutableAssetVersion(record.profileVersion);\n const evaluatedDiagonalMetres = requireNumber(record.evaluatedDiagonalMetres, \"PvoxFidelityEvidence.evaluatedDiagonalMetres\", Number.EPSILON, 1_000_000_000);\n const lod0CellSizeMetres = requireNumber(record.lod0CellSizeMetres, \"PvoxFidelityEvidence.lod0CellSizeMetres\", Number.EPSILON, 1_000_000);\n const profileFormula: Readonly<Record<typeof surfaceProfileId, readonly [number, number]>> = {\n \"precision-hero-v1\": [0.00025, 0.0001],\n \"props-furniture-v1\": [0.0005, 0.00025],\n \"rocks-organic-shells-v1\": [0.001, 0.0005],\n \"buildings-v1\": [0.002, 0.0001],\n };\n const [absoluteFloor, diagonalFactor] = profileFormula[surfaceProfileId];\n const governedP99Ceiling = Math.max(absoluteFloor, evaluatedDiagonalMetres * diagonalFactor);\n const governedMaximumCeiling = Math.min(3 * governedP99Ceiling, 1.5 * lod0CellSizeMetres);\n const suppliedP99Ceiling = requireNumber(record.p99AllowedSurfaceErrorMetres, \"PvoxFidelityEvidence.p99AllowedSurfaceErrorMetres\", 0, 1_000_000);\n const suppliedMaximumCeiling = requireNumber(record.maximumAllowedSurfaceErrorMetres, \"PvoxFidelityEvidence.maximumAllowedSurfaceErrorMetres\", 0, 1_000_000);\n if (!approximatelyEqual(suppliedP99Ceiling, governedP99Ceiling) || !approximatelyEqual(suppliedMaximumCeiling, governedMaximumCeiling)) {\n throw new Error(\"PvoxFidelityEvidence surface ceilings must match the governed profile formula and LOD0 cell limit.\");\n }\n const minimumSilhouetteIou = requireNumber(record.minimumSilhouetteIou, \"PvoxFidelityEvidence.minimumSilhouetteIou\", 0, 1);\n const maximumAllowedContourDisplacementPx = requireNumber(record.maximumAllowedContourDisplacementPx, \"PvoxFidelityEvidence.maximumAllowedContourDisplacementPx\", 0, 1_000_000);\n const minimumRenderedSsim = requireNumber(record.minimumRenderedSsim, \"PvoxFidelityEvidence.minimumRenderedSsim\", 0, 1);\n const maximumP95DeltaE2000 = requireNumber(record.maximumP95DeltaE2000, \"PvoxFidelityEvidence.maximumP95DeltaE2000\", 0, 100);\n const maximumNormalizedMaterialError = requireNumber(record.maximumNormalizedMaterialError, \"PvoxFidelityEvidence.maximumNormalizedMaterialError\", 0, 1);\n if (!approximatelyEqual(minimumSilhouetteIou, 0.995)\n || !approximatelyEqual(maximumAllowedContourDisplacementPx, 0.5)\n || !approximatelyEqual(minimumRenderedSsim, 0.98)\n || !approximatelyEqual(maximumP95DeltaE2000, 3)\n || !approximatelyEqual(maximumNormalizedMaterialError, 1 / 255)) {\n throw new Error(\"PvoxFidelityEvidence must use the governed silhouette, contour, render, colour, and material thresholds.\");\n }\n const output = {\n profileId,\n surfaceProfileId,\n profileVersion: PVOX_FIDELITY_PROFILE_VERSION,\n canonicalDocumentHash: requireSha256(record.canonicalDocumentHash, \"PvoxFidelityEvidence.canonicalDocumentHash\"),\n pvoxBinaryClosureHash: requireSha256(record.pvoxBinaryClosureHash, \"PvoxFidelityEvidence.pvoxBinaryClosureHash\"),\n evaluatedDiagonalMetres,\n lod0CellSizeMetres,\n maximumAllowedSurfaceErrorMetres: governedMaximumCeiling,\n maximumSurfaceErrorMetres: requireNumber(record.maximumSurfaceErrorMetres, \"PvoxFidelityEvidence.maximumSurfaceErrorMetres\", 0, 1_000_000),\n p99AllowedSurfaceErrorMetres: governedP99Ceiling,\n p99SurfaceErrorMetres: requireNumber(record.p99SurfaceErrorMetres, \"PvoxFidelityEvidence.p99SurfaceErrorMetres\", 0, 1_000_000),\n minimumSilhouetteIou,\n silhouetteIou: requireNumber(record.silhouetteIou, \"PvoxFidelityEvidence.silhouetteIou\", 0, 1),\n maximumAllowedContourDisplacementPx,\n maximumContourDisplacementPx: requireNumber(record.maximumContourDisplacementPx, \"PvoxFidelityEvidence.maximumContourDisplacementPx\", 0, 1_000_000),\n minimumRenderedSsim,\n renderedSsim: requireNumber(record.renderedSsim, \"PvoxFidelityEvidence.renderedSsim\", 0, 1),\n maximumP95DeltaE2000,\n p95DeltaE2000: requireNumber(record.p95DeltaE2000, \"PvoxFidelityEvidence.p95DeltaE2000\", 0, 100),\n maximumNormalizedMaterialError,\n normalizedMaterialError: requireNumber(record.normalizedMaterialError, \"PvoxFidelityEvidence.normalizedMaterialError\", 0, 1),\n evidenceHash: requireSha256(record.evidenceHash, \"PvoxFidelityEvidence.evidenceHash\"),\n evaluatedAt: requireTimestamp(record.evaluatedAt, \"PvoxFidelityEvidence.evaluatedAt\"),\n decisionToken: requireAttestation(record.decisionToken, \"PvoxFidelityEvidence.decisionToken\"),\n };\n const passed = output.maximumSurfaceErrorMetres <= output.maximumAllowedSurfaceErrorMetres\n && output.p99SurfaceErrorMetres <= output.p99AllowedSurfaceErrorMetres\n && output.silhouetteIou >= output.minimumSilhouetteIou\n && output.maximumContourDisplacementPx <= output.maximumAllowedContourDisplacementPx\n && output.renderedSsim >= output.minimumRenderedSsim\n && output.p95DeltaE2000 <= output.maximumP95DeltaE2000\n && output.normalizedMaterialError <= output.maximumNormalizedMaterialError;\n const outcome = requireEnum(record.outcome, [\"passed\", \"blocked\"] as const, \"PvoxFidelityEvidence.outcome\");\n if (outcome !== (passed ? \"passed\" : \"blocked\")) throw new Error(\"PvoxFidelityEvidence outcome must match its measured fidelity thresholds.\");\n return deepFreeze({ ...output, outcome });\n}\n\nfunction createPvoxEditJournalCurrentState(\n input: unknown,\n baseManifest: PvoxAssetManifestV1,\n): PvoxEditJournalCurrentState {\n const fieldName = \"PvoxEditJournalCurrentState\";\n const record = asRecord(input, fieldName);\n exactKeys(record, [\"baseContentHash\", \"basePageSetHash\", \"placementId\", \"gridVersion\", \"revision\", \"rootHash\", \"latestJournalHash\", \"pageHashes\"], fieldName);\n const pageEntries = asDenseArray(record.pageHashes, `${fieldName}.pageHashes`, baseManifest.pages.length, baseManifest.pages.length);\n const pageHashes = pageEntries.map((entry, index) => {\n const entryName = `${fieldName}.pageHashes[${index}]`;\n const page = asRecord(entry, entryName);\n exactKeys(page, [\"pageIndex\", \"sha256\"], entryName);\n const pageIndex = requireInteger(page.pageIndex, `${entryName}.pageIndex`, 0, baseManifest.pages.length - 1);\n if (pageIndex !== index) throw new Error(`${fieldName}.pageHashes must be complete and ordered by pageIndex.`);\n return { pageIndex, sha256: requireSha256(page.sha256, `${entryName}.sha256`) };\n });\n return deepFreeze({\n baseContentHash: requireSha256(record.baseContentHash, `${fieldName}.baseContentHash`),\n basePageSetHash: requireSha256(record.basePageSetHash, `${fieldName}.basePageSetHash`),\n placementId: requireToken(record.placementId, `${fieldName}.placementId`),\n gridVersion: requireToken(record.gridVersion, `${fieldName}.gridVersion`),\n revision: requireInteger(record.revision, `${fieldName}.revision`, 1, Number.MAX_SAFE_INTEGER),\n rootHash: requireSha256(record.rootHash, `${fieldName}.rootHash`),\n latestJournalHash: requireSha256(record.latestJournalHash, `${fieldName}.latestJournalHash`),\n pageHashes,\n });\n}\n\n/** Validate and deeply freeze one placement-specific edit journal. */\nexport function createPvoxEditJournal(\n input: unknown,\n baseManifestInput: unknown,\n currentStateInput?: unknown,\n): PvoxEditJournal {\n const record = asRecord(input, \"PvoxEditJournal\");\n exactKeys(record, [\"journalVersion\", \"baseContentHash\", \"basePageSetHash\", \"placementId\", \"gridVersion\", \"operationId\", \"expectedRevision\", \"resultingRevision\", \"previousJournalHash\", \"expectedRootHash\", \"resultingRootHash\", \"resultingRootHashAttestation\", \"patches\", \"dirtyBoundsMetres\", \"massDeltaKg\", \"journalHash\", \"journalHashAttestation\", \"recordedAt\"], \"PvoxEditJournal\");\n if (record.journalVersion !== PVOX_EDIT_JOURNAL_VERSION) throw new Error(\"PvoxEditJournal.journalVersion is unsupported.\");\n const baseManifest = createPvoxAssetManifestV1(baseManifestInput);\n const baseContentHash = requireSha256(record.baseContentHash, \"PvoxEditJournal.baseContentHash\");\n const basePageSetHash = requireSha256(record.basePageSetHash, \"PvoxEditJournal.basePageSetHash\");\n if (baseContentHash !== baseManifest.artifact.sha256 || basePageSetHash !== baseManifest.pageSetHash) {\n throw new Error(\"PvoxEditJournal must bind the exact base PVOX artifact and page inventory.\");\n }\n const expectedRevision = requireInteger(record.expectedRevision, \"PvoxEditJournal.expectedRevision\", 0, Number.MAX_SAFE_INTEGER - 1);\n const resultingRevision = requireInteger(record.resultingRevision, \"PvoxEditJournal.resultingRevision\", 1, Number.MAX_SAFE_INTEGER);\n if (resultingRevision !== expectedRevision + 1) throw new Error(\"PvoxEditJournal revisions must be sequential.\");\n const previousJournalHash = requireSha256(record.previousJournalHash, \"PvoxEditJournal.previousJournalHash\");\n if ((expectedRevision === 0) !== (previousJournalHash === PVOX_EDIT_JOURNAL_GENESIS_HASH)) {\n throw new Error(\"PvoxEditJournal genesis revision must use only the canonical genesis previousJournalHash.\");\n }\n const expectedRootHash = requireSha256(record.expectedRootHash, \"PvoxEditJournal.expectedRootHash\");\n const resultingRootHash = requireSha256(record.resultingRootHash, \"PvoxEditJournal.resultingRootHash\");\n if (expectedRootHash === resultingRootHash) throw new Error(\"PvoxEditJournal copy-on-write operation must change the overlay root hash.\");\n const placementId = requireToken(record.placementId, \"PvoxEditJournal.placementId\");\n const gridVersion = requireToken(record.gridVersion, \"PvoxEditJournal.gridVersion\");\n let currentState: PvoxEditJournalCurrentState | undefined;\n if (expectedRevision === 0) {\n if (currentStateInput !== undefined) throw new Error(\"PvoxEditJournal genesis must not supply a non-genesis current state.\");\n if (expectedRootHash !== baseManifest.rootHash) throw new Error(\"PvoxEditJournal genesis expectedRootHash must equal the authenticated base PVOX rootHash.\");\n } else {\n if (currentStateInput === undefined) throw new Error(\"PvoxEditJournal non-genesis validation requires the authenticated current placement state.\");\n currentState = createPvoxEditJournalCurrentState(currentStateInput, baseManifest);\n if (currentState.baseContentHash !== baseContentHash\n || currentState.basePageSetHash !== basePageSetHash\n || currentState.placementId !== placementId\n || currentState.gridVersion !== gridVersion\n || currentState.revision !== expectedRevision\n || currentState.rootHash !== expectedRootHash\n || currentState.latestJournalHash !== previousJournalHash) {\n throw new Error(\"PvoxEditJournal non-genesis CAS subject must match the authenticated current placement state.\");\n }\n }\n const patchEntries = asDenseArray(record.patches, \"PvoxEditJournal.patches\", 1, PVOX_MAX_EDIT_PATCHES);\n const patches = patchEntries.map((entry, index): PvoxBrickPatchDescriptor => {\n const fieldName = `PvoxEditJournal.patches[${index}]`;\n const patch = asRecord(entry, fieldName);\n exactKeys(patch, [\"fieldKind\", \"lodLevel\", \"partitionIndex\", \"hierarchyDepth\", \"mortonCode\", \"expectedPageIndex\", \"expectedPageHash\", \"operation\", \"expectedBrickHash\", \"resultingBrickHash\", \"resultingPageHash\"], fieldName);\n const mortonCode = requireString(patch.mortonCode, `${fieldName}.mortonCode`, 16);\n if (!MORTON_CODE.test(mortonCode)) throw new Error(`${fieldName}.mortonCode must be a canonical Morton code.`);\n const operation = requireEnum(patch.operation, [\"insert\", \"replace\", \"remove\"] as const, `${fieldName}.operation`);\n const expectedBrickHash = requireSha256(patch.expectedBrickHash, `${fieldName}.expectedBrickHash`);\n const resultingBrickHash = requireSha256(patch.resultingBrickHash, `${fieldName}.resultingBrickHash`);\n const expectedPageHash = requireSha256(patch.expectedPageHash, `${fieldName}.expectedPageHash`);\n const resultingPageHash = requireSha256(patch.resultingPageHash, `${fieldName}.resultingPageHash`);\n if (operation === \"replace\" && (expectedBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || expectedBrickHash === resultingBrickHash)) throw new Error(`${fieldName} replacement must change one non-empty brick hash to another.`);\n if (operation === \"insert\" && (expectedBrickHash !== PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH)) throw new Error(`${fieldName} insertion must change an empty brick to a non-empty result.`);\n if (operation === \"remove\" && (expectedBrickHash === PVOX_EDIT_JOURNAL_GENESIS_HASH || resultingBrickHash !== PVOX_EDIT_JOURNAL_GENESIS_HASH)) throw new Error(`${fieldName} removal must change a non-empty expected brick to the empty result.`);\n if (expectedPageHash === resultingPageHash) throw new Error(`${fieldName} copy-on-write patch must change the page hash.`);\n const fieldKind = requireEnum(patch.fieldKind, [\"render-field\", \"collision-field\"] as const, `${fieldName}.fieldKind`);\n const lodLevel = requireInteger(patch.lodLevel, `${fieldName}.lodLevel`, 0, PVOX_DEFAULT_LIMITS.maximumLodCount - 1) as PvoxLodLevel;\n const partitionIndex = requireInteger(patch.partitionIndex, `${fieldName}.partitionIndex`, 0, PVOX_DEFAULT_LIMITS.maximumPartitions - 1);\n const hierarchyDepth = requireInteger(patch.hierarchyDepth, `${fieldName}.hierarchyDepth`, 0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth);\n const expectedPageIndex = requireInteger(patch.expectedPageIndex, `${fieldName}.expectedPageIndex`, 0, baseManifest.pages.length - 1);\n const basePage = baseManifest.pages[expectedPageIndex]!;\n if (basePage.pageKind !== fieldKind\n || basePage.spatialKey?.lodLevel !== lodLevel\n || basePage.spatialKey.partitionIndex !== partitionIndex\n || basePage.spatialKey.hierarchyDepth !== hierarchyDepth\n || mortonCode < basePage.spatialKey.minimumMortonCode\n || mortonCode > basePage.spatialKey.maximumMortonCode\n || (expectedRevision === 0 && expectedPageHash !== basePage.sha256)\n || (currentState !== undefined && currentState.pageHashes[expectedPageIndex]!.sha256 !== expectedPageHash)) {\n throw new Error(`${fieldName} must address and CAS the exact base PVOX page inventory.`);\n }\n return {\n fieldKind,\n lodLevel,\n partitionIndex,\n hierarchyDepth,\n mortonCode,\n expectedPageIndex,\n expectedPageHash,\n operation,\n expectedBrickHash,\n resultingBrickHash,\n resultingPageHash,\n };\n });\n const patchAddress = (patch: PvoxBrickPatchDescriptor): string => [\n patch.fieldKind,\n String(patch.lodLevel).padStart(2, \"0\"),\n String(patch.partitionIndex).padStart(6, \"0\"),\n String(patch.hierarchyDepth).padStart(2, \"0\"),\n patch.mortonCode,\n ].join(\"\\u0000\");\n for (let index = 1; index < patches.length; index += 1) {\n if (patchAddress(patches[index]!) <= patchAddress(patches[index - 1]!)) throw new Error(\"PvoxEditJournal patches must be unique and ordered by field, LOD, partition, depth, and Morton code.\");\n }\n if (new Set(patches.map(({ expectedPageIndex }) => expectedPageIndex)).size !== patches.length) {\n throw new Error(\"PvoxEditJournal permits only one coherent patch transition per page.\");\n }\n const journalHash = requireSha256(record.journalHash, \"PvoxEditJournal.journalHash\");\n return deepFreeze({\n journalVersion: PVOX_EDIT_JOURNAL_VERSION,\n baseContentHash,\n basePageSetHash,\n placementId,\n gridVersion,\n operationId: requireToken(record.operationId, \"PvoxEditJournal.operationId\"),\n expectedRevision,\n resultingRevision,\n previousJournalHash,\n expectedRootHash,\n resultingRootHash,\n resultingRootHashAttestation: createHashAttestation(record.resultingRootHashAttestation, PVOX_EDIT_OVERLAY_ROOT_HASH_DOMAIN, resultingRootHash, \"PvoxEditJournal.resultingRootHashAttestation\"),\n patches,\n dirtyBoundsMetres: createBounds(record.dirtyBoundsMetres, \"PvoxEditJournal.dirtyBoundsMetres\"),\n massDeltaKg: requireNumber(record.massDeltaKg, \"PvoxEditJournal.massDeltaKg\", -Number.MAX_VALUE, Number.MAX_VALUE),\n journalHash,\n journalHashAttestation: createHashAttestation(record.journalHashAttestation, PVOX_EDIT_JOURNAL_HASH_DOMAIN, journalHash, \"PvoxEditJournal.journalHashAttestation\"),\n recordedAt: requireTimestamp(record.recordedAt, \"PvoxEditJournal.recordedAt\"),\n });\n}\n\n/** Validate an ordered, gap-free CAS journal chain for one placement overlay. */\nexport function createPvoxEditJournalChain(input: unknown, baseManifestInput: unknown): readonly PvoxEditJournal[] {\n const entries = asDenseArray(input, \"PvoxEditJournalChain\", 1, 10_000);\n const baseManifest = createPvoxAssetManifestV1(baseManifestInput);\n const journals: PvoxEditJournal[] = [];\n const operationIds = new Set<string>();\n const currentPageHashes = new Map(baseManifest.pages.map(({ pageIndex, sha256 }) => [pageIndex, sha256]));\n for (const entry of entries) {\n const previous = journals.at(-1);\n const currentState: PvoxEditJournalCurrentState | undefined = previous === undefined ? undefined : {\n baseContentHash: previous.baseContentHash,\n basePageSetHash: previous.basePageSetHash,\n placementId: previous.placementId,\n gridVersion: previous.gridVersion,\n revision: previous.resultingRevision,\n rootHash: previous.resultingRootHash,\n latestJournalHash: previous.journalHash,\n pageHashes: baseManifest.pages.map(({ pageIndex }) => ({ pageIndex, sha256: currentPageHashes.get(pageIndex)! })),\n };\n const journal = createPvoxEditJournal(entry, baseManifest, currentState);\n if (previous === undefined && (journal.expectedRevision !== 0 || journal.previousJournalHash !== PVOX_EDIT_JOURNAL_GENESIS_HASH)) {\n throw new Error(\"PvoxEditJournalChain must begin at the canonical genesis revision.\");\n }\n if (previous !== undefined && Date.parse(journal.recordedAt) < Date.parse(previous.recordedAt)) {\n throw new Error(\"PvoxEditJournalChain entries must form one chronological revision/root/hash chain.\");\n }\n if (operationIds.has(journal.operationId)) throw new Error(\"PvoxEditJournalChain operation IDs must be unique to prevent replay.\");\n operationIds.add(journal.operationId);\n for (const patch of journal.patches) {\n if (currentPageHashes.get(patch.expectedPageIndex) !== patch.expectedPageHash) {\n throw new Error(\"PvoxEditJournalChain patch expectedPageHash must match the current page CAS state.\");\n }\n currentPageHashes.set(patch.expectedPageIndex, patch.resultingPageHash);\n }\n journals.push(journal);\n }\n return deepFreeze(journals);\n}\n\nfunction createCompilerEvidence(value: unknown): PvoxCompilerEvidence {\n const record = asRecord(value, \"ModelProcessingManifestV2.converter\");\n exactKeys(record, [\"compilerId\", \"compilerVersion\", \"sourceFormat\", \"sourceContentHash\", \"canonicalDocumentHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"outputContentHash\", \"evidenceHash\", \"compiledAt\"], \"ModelProcessingManifestV2.converter\");\n return {\n compilerId: requireToken(record.compilerId, \"ModelProcessingManifestV2.converter.compilerId\"),\n compilerVersion: assertImmutableAssetVersion(record.compilerVersion),\n sourceFormat: requireToken(record.sourceFormat, \"ModelProcessingManifestV2.converter.sourceFormat\"),\n sourceContentHash: requireSha256(record.sourceContentHash, \"ModelProcessingManifestV2.converter.sourceContentHash\"),\n canonicalDocumentHash: requireSha256(record.canonicalDocumentHash, \"ModelProcessingManifestV2.converter.canonicalDocumentHash\"),\n compilationInputHash: requireSha256(record.compilationInputHash, \"ModelProcessingManifestV2.converter.compilationInputHash\"),\n runtimeRequestProfileHash: requireSha256(record.runtimeRequestProfileHash, \"ModelProcessingManifestV2.converter.runtimeRequestProfileHash\"),\n outputContentHash: requireSha256(record.outputContentHash, \"ModelProcessingManifestV2.converter.outputContentHash\"),\n evidenceHash: requireSha256(record.evidenceHash, \"ModelProcessingManifestV2.converter.evidenceHash\"),\n compiledAt: requireTimestamp(record.compiledAt, \"ModelProcessingManifestV2.converter.compiledAt\"),\n };\n}\n\n/** Validate and deeply freeze one non-overridable PVOX gate. */\nexport function createPvoxGateEvidence(input: unknown): PvoxGateEvidence {\n const record = asRecord(input, \"PvoxGateEvidence\");\n exactKeys(record, [\"kind\", \"outcome\", \"validatorId\", \"validatorVersion\", \"subjectContentHash\", \"evidenceHash\", \"reasonCodes\", \"evaluatedAt\", \"attestationToken\"], \"PvoxGateEvidence\");\n const outcome = requireEnum(record.outcome, [\"passed\", \"blocked\"] as const, \"PvoxGateEvidence.outcome\");\n const reasonCodes = requireReasonCodes(record.reasonCodes, \"PvoxGateEvidence.reasonCodes\");\n if (outcome === \"blocked\" && reasonCodes.length === 0) throw new Error(\"Blocked PvoxGateEvidence requires a reason code.\");\n return deepFreeze({\n kind: requireEnum(record.kind, PVOX_NON_OVERRIDABLE_GATE_KINDS, \"PvoxGateEvidence.kind\"),\n outcome,\n validatorId: requireToken(record.validatorId, \"PvoxGateEvidence.validatorId\"),\n validatorVersion: assertImmutableAssetVersion(record.validatorVersion),\n subjectContentHash: requireSha256(record.subjectContentHash, \"PvoxGateEvidence.subjectContentHash\"),\n evidenceHash: requireSha256(record.evidenceHash, \"PvoxGateEvidence.evidenceHash\"),\n reasonCodes,\n evaluatedAt: requireTimestamp(record.evaluatedAt, \"PvoxGateEvidence.evaluatedAt\"),\n attestationToken: requireAttestation(record.attestationToken, \"PvoxGateEvidence.attestationToken\"),\n });\n}\n\nfunction createTransform(value: unknown, fieldName: string): ModelTransform {\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"translationMetres\", \"rotationQuaternion\", \"scale\"], fieldName);\n const translationMetres = requireVector(record.translationMetres, `${fieldName}.translationMetres`);\n const rotationEntries = asDenseArray(record.rotationQuaternion, `${fieldName}.rotationQuaternion`, 4, 4);\n const rotationQuaternion = rotationEntries.map((entry, index) => requireNumber(entry, `${fieldName}.rotationQuaternion[${index}]`, -1, 1)) as [number, number, number, number];\n if (Math.abs(Math.hypot(...rotationQuaternion) - 1) > 1e-4) throw new Error(`${fieldName}.rotationQuaternion must be normalized.`);\n const scale = requireVector(record.scale, `${fieldName}.scale`);\n if (scale.some((entry) => entry <= 0)) throw new Error(`${fieldName}.scale values must be positive.`);\n return { translationMetres, rotationQuaternion, scale };\n}\n\nfunction createAssemblyChild(value: unknown, index: number, resolutionId: string, candidateId: string): PvoxAssemblyChild {\n const fieldName = `ModelProcessingManifestV2.children[${index}]`;\n const record = asRecord(value, fieldName);\n exactKeys(record, [\"instanceId\", \"parentInstanceId\", \"assetRef\", \"transform\"], fieldName);\n const childRef = asRecord(record.assetRef, `${fieldName}.assetRef`);\n let assetRef: PvoxAssemblyChild[\"assetRef\"];\n if (childRef.disposition === \"staged-derived\") {\n exactKeys(childRef, [\"disposition\", \"representation\", \"derivedId\", \"kind\", \"contentHash\", \"binaryClosureHash\", \"processingClosureHash\", \"processingManifestId\", \"processingManifestUri\"], `${fieldName}.assetRef`);\n if (childRef.kind !== \"leaf\" || childRef.representation !== \"pvox\") throw new Error(`${fieldName}.assetRef must be a PVOX leaf.`);\n const derivedId = requirePathSegment(childRef.derivedId, `${fieldName}.assetRef.derivedId`);\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/derived/${derivedId}/processing-manifest`;\n if (childRef.processingManifestUri !== expectedUri) throw new Error(`${fieldName}.assetRef.processingManifestUri must match the exact staged-derived PVOX identity.`);\n assetRef = {\n disposition: \"staged-derived\",\n representation: \"pvox\",\n derivedId,\n kind: \"leaf\",\n contentHash: requireSha256(childRef.contentHash, `${fieldName}.assetRef.contentHash`),\n binaryClosureHash: requireSha256(childRef.binaryClosureHash, `${fieldName}.assetRef.binaryClosureHash`),\n processingClosureHash: requireSha256(childRef.processingClosureHash, `${fieldName}.assetRef.processingClosureHash`),\n processingManifestId: requireToken(childRef.processingManifestId, `${fieldName}.assetRef.processingManifestId`),\n processingManifestUri: expectedUri,\n };\n } else {\n exactKeys(childRef, [\"disposition\", \"representation\", \"asset\", \"processingManifestId\", \"binaryClosureHash\", \"processingClosureHash\", \"processingManifestUri\"], `${fieldName}.assetRef`);\n if (childRef.disposition !== \"existing\" || childRef.representation !== \"pvox\") throw new Error(`${fieldName}.assetRef must use an existing or staged-derived PVOX disposition.`);\n assertDataOnlyTree(childRef.asset, `${fieldName}.assetRef.asset`);\n const asset = createModelAssetRef(childRef.asset);\n if (asset.kind !== \"leaf\") throw new Error(`${fieldName}.assetRef must reference a leaf.`);\n const expectedUri = `mcp://models/catalog/${asset.assetId}/versions/${asset.version}/processing-manifest`;\n if (childRef.processingManifestUri !== expectedUri) throw new Error(`${fieldName}.assetRef.processingManifestUri must match the immutable catalog PVOX identity.`);\n assetRef = {\n disposition: \"existing\",\n representation: \"pvox\",\n asset,\n processingManifestId: requireToken(childRef.processingManifestId, `${fieldName}.assetRef.processingManifestId`),\n binaryClosureHash: requireSha256(childRef.binaryClosureHash, `${fieldName}.assetRef.binaryClosureHash`),\n processingClosureHash: requireSha256(childRef.processingClosureHash, `${fieldName}.assetRef.processingClosureHash`),\n processingManifestUri: expectedUri,\n };\n }\n const parentInstanceId = record.parentInstanceId === undefined ? undefined : requireToken(record.parentInstanceId, `${fieldName}.parentInstanceId`);\n return {\n instanceId: requireToken(record.instanceId, `${fieldName}.instanceId`),\n ...(parentInstanceId === undefined ? {} : { parentInstanceId }),\n assetRef,\n transform: createTransform(record.transform, `${fieldName}.transform`),\n };\n}\n\nfunction assertAssembly(children: readonly PvoxAssemblyChild[]): void {\n const byId = new Map(children.map((child) => [child.instanceId, child]));\n if (byId.size !== children.length) throw new Error(\"ModelProcessingManifestV2 assembly instance IDs must be unique.\");\n if (children.some((child, index) => index > 0 && child.instanceId <= children[index - 1]!.instanceId)) throw new Error(\"ModelProcessingManifestV2 assembly children must be canonically ordered by instanceId.\");\n if (children.filter(({ parentInstanceId }) => parentInstanceId === undefined).length !== 1) throw new Error(\"ModelProcessingManifestV2 assembly must contain exactly one root child.\");\n const stagedDerivedIds = children.flatMap(({ assetRef }) => assetRef.disposition === \"staged-derived\" ? [assetRef.derivedId] : []);\n if (new Set(stagedDerivedIds).size !== stagedDerivedIds.length) throw new Error(\"ModelProcessingManifestV2 staged-derived child IDs must be unique.\");\n for (const child of children) {\n const visited = new Set<string>();\n let current: PvoxAssemblyChild | undefined = child;\n let depth = 0;\n while (current?.parentInstanceId !== undefined) {\n if (current.parentInstanceId === current.instanceId || visited.has(current.instanceId)) throw new Error(\"ModelProcessingManifestV2 assembly must be acyclic.\");\n visited.add(current.instanceId);\n current = byId.get(current.parentInstanceId);\n if (current === undefined) throw new Error(\"ModelProcessingManifestV2 assembly parent must exist.\");\n depth += 1;\n if (depth > 16) throw new Error(\"ModelProcessingManifestV2 assembly depth exceeds the limit.\");\n }\n }\n}\n\nconst PVOX_CAPABILITY_PHYSICAL_PROPERTIES: Readonly<Partial<Record<PvoxCapability, readonly PhysicalPropertyKind[]>>> = Object.freeze({\n destruction: [\"density\", \"hardness\", \"tensile-strength\", \"compressive-strength\", \"shear-strength\", \"fracture-energy\", \"friction\", \"restitution\", \"interior-thickness\"],\n thermal: [\"thermal-conductivity\", \"heat-capacity\", \"thermal-expansion\", \"ignition-temperature\", \"melting-temperature\", \"flammability\"],\n moisture: [\"porosity\", \"permeability\", \"moisture-response\", \"corrosion-rate\"],\n \"fluid-boundary\": [\"porosity\", \"permeability\"],\n});\n\nconst NON_DEFAULT_CRITICAL_PROPERTIES = new Set<PhysicalPropertyKind>([\n \"density\",\n \"hardness\",\n \"tensile-strength\",\n \"compressive-strength\",\n \"shear-strength\",\n \"fracture-energy\",\n \"interior-thickness\",\n \"ignition-temperature\",\n \"melting-temperature\",\n]);\n\n/** Validate and deeply freeze a PVOX-only processing manifest. */\nexport function createModelProcessingManifestV2(input: unknown): ModelProcessingManifestV2 {\n const record = asRecord(input, \"ModelProcessingManifestV2\");\n exactKeys(record, [\n \"contractVersion\", \"representation\", \"manifestId\", \"resolutionId\", \"candidateId\", \"kind\",\n \"requestProfileId\", \"requestSemanticProfileHash\", \"capabilityProfileId\", \"contentHash\", \"binaryClosureHash\",\n \"processingClosureHash\", \"processingClosureAttestation\", \"assemblyClosureHash\", \"assemblyClosureAttestation\",\n \"compilationInputHash\", \"runtimeRequestProfileHash\", \"coordinateSystem\", \"pvox\", \"technicalProfile\",\n \"requiredCapabilities\", \"capabilities\", \"capabilityEvidenceSetHash\", \"capabilityEvidenceSetAttestation\",\n \"physicalRegionInventory\", \"physicalProperties\", \"physicalEvidenceHash\", \"physicalEvidenceAttestation\",\n \"massPropertiesEvidence\", \"bondGraphEvidence\", \"interiorLayerEvidence\", \"converter\", \"fidelity\", \"children\", \"processedAt\",\n ], \"ModelProcessingManifestV2\");\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION) throw new Error(\"ModelProcessingManifestV2.contractVersion is unsupported.\");\n if (record.representation !== \"pvox\") throw new Error(\"ModelProcessingManifestV2.representation must be pvox.\");\n const resolutionId = requirePathSegment(record.resolutionId, \"ModelProcessingManifestV2.resolutionId\");\n const candidateId = requirePathSegment(record.candidateId, \"ModelProcessingManifestV2.candidateId\");\n assertCoordinateSystem(record.coordinateSystem, \"ModelProcessingManifestV2.coordinateSystem\");\n const pvox = createPvoxAssetManifestV1(record.pvox);\n const resourceScope = parsePvoxResourceScope(pvox.artifact.uri);\n if (resourceScope.kind === \"resolution\" && (resourceScope.resolutionId !== resolutionId || resourceScope.candidateId !== candidateId)) {\n throw new Error(\"ModelProcessingManifestV2 PVOX resource namespace must match resolutionId and candidateId.\");\n }\n const technicalProfile = createVoxelTechnicalProfile(record.technicalProfile);\n const contentHash = requireSha256(record.contentHash, \"ModelProcessingManifestV2.contentHash\");\n const binaryClosureHash = requireSha256(record.binaryClosureHash, \"ModelProcessingManifestV2.binaryClosureHash\");\n const processingClosureHash = requireSha256(record.processingClosureHash, \"ModelProcessingManifestV2.processingClosureHash\");\n const assemblyClosureHash = requireSha256(record.assemblyClosureHash, \"ModelProcessingManifestV2.assemblyClosureHash\");\n const requestSemanticProfileHash = requireSha256(record.requestSemanticProfileHash, \"ModelProcessingManifestV2.requestSemanticProfileHash\");\n const compilationInputHash = requireSha256(record.compilationInputHash, \"ModelProcessingManifestV2.compilationInputHash\");\n const runtimeRequestProfileHash = requireSha256(record.runtimeRequestProfileHash, \"ModelProcessingManifestV2.runtimeRequestProfileHash\");\n if (contentHash !== pvox.artifact.sha256) throw new Error(\"ModelProcessingManifestV2 contentHash must match the PVOX artifact.\");\n if (binaryClosureHash !== pvox.binaryClosureHash) throw new Error(\"ModelProcessingManifestV2 binaryClosureHash must match the PVOX binary closure.\");\n if (compilationInputHash !== pvox.compilationInputHash || runtimeRequestProfileHash !== pvox.runtimeRequestProfileHash) {\n throw new Error(\"ModelProcessingManifestV2 compilation input and runtime request profile hashes must match the PVOX header bindings.\");\n }\n const artifactRenderBrickCount = pvox.lods.reduce((total, lodRecord) => total + lodRecord.brickCount, 0);\n if (\n technicalProfile.artifactByteLength !== pvox.artifact.byteLength\n || technicalProfile.pageCount !== pvox.pages.length\n || technicalProfile.sectionCount !== pvox.sectionCount\n || technicalProfile.brickCount !== artifactRenderBrickCount\n || technicalProfile.lodCount !== pvox.lods.length\n || technicalProfile.geometryMode !== pvox.geometryMode\n || JSON.stringify(technicalProfile.boundsMetres) !== JSON.stringify(pvox.boundsMetres)\n ) throw new Error(\"ModelProcessingManifestV2 technicalProfile must match the PVOX artifact.\");\n if (!pvox.pages.some(({ pageKind }) => pageKind === \"metadata\")) throw new Error(\"ModelProcessingManifestV2 PVOX must contain a metadata page for its header and directory.\");\n if (technicalProfile.hierarchyNodeCount > 0 && !pvox.pages.some(({ pageKind }) => pageKind === \"lod-structure\")) {\n throw new Error(\"ModelProcessingManifestV2 hierarchy nodes require a lod-structure page.\");\n }\n const collisionPages = pvox.pages.filter(({ pageKind }) => pageKind === \"collision-field\");\n if (technicalProfile.hasCollision !== (collisionPages.length > 0)) {\n throw new Error(\"ModelProcessingManifestV2 collision technical claims require matching collision-field pages and forbid unclaimed collision pages.\");\n }\n const maximumGridExtentMetres = pvox.lods[0]!.cellSizeMetres * PVOX_BRICK_EDGE_VOXELS * 2 ** technicalProfile.hierarchyDepth;\n if (technicalProfile.maximumPartitionExtentMetres > maximumGridExtentMetres && !approximatelyEqual(technicalProfile.maximumPartitionExtentMetres, maximumGridExtentMetres)) {\n throw new Error(\"ModelProcessingManifestV2 partition extent exceeds the LOD0 cell and hierarchy grid capacity; use smaller fidelity-driven partitions.\");\n }\n const capabilityEntries = asDenseArray(record.capabilities, \"ModelProcessingManifestV2.capabilities\", PVOX_CAPABILITIES.length, PVOX_CAPABILITIES.length);\n const capabilities = capabilityEntries.map(createVoxelCapabilityAssessment);\n const byCapability = new Map(capabilities.map((entry) => [entry.capability, entry]));\n if (byCapability.size !== PVOX_CAPABILITIES.length || PVOX_CAPABILITIES.some((name) => !byCapability.has(name))) throw new Error(\"ModelProcessingManifestV2 must include every PVOX capability exactly once.\");\n const orderedCapabilities = PVOX_CAPABILITIES.map((name) => byCapability.get(name)!);\n if (orderedCapabilities.some((entry) => entry.subjectContentHash !== binaryClosureHash)) throw new Error(\"ModelProcessingManifestV2 capability evidence must bind the binaryClosureHash.\");\n const capabilityEvidenceSetHash = requireSha256(record.capabilityEvidenceSetHash, \"ModelProcessingManifestV2.capabilityEvidenceSetHash\");\n const capabilityEvidenceSetAttestation = createHashAttestation(\n record.capabilityEvidenceSetAttestation,\n PVOX_CAPABILITY_SET_HASH_DOMAIN,\n capabilityEvidenceSetHash,\n \"ModelProcessingManifestV2.capabilityEvidenceSetAttestation\",\n );\n const requiredCapabilityEntries = asDenseArray(record.requiredCapabilities, \"ModelProcessingManifestV2.requiredCapabilities\", 1, PVOX_CAPABILITIES.length);\n const requiredCapabilities = requiredCapabilityEntries.map((entry, index) => requireEnum(entry, PVOX_CAPABILITIES, `ModelProcessingManifestV2.requiredCapabilities[${index}]`));\n if (new Set(requiredCapabilities).size !== requiredCapabilities.length) throw new Error(\"ModelProcessingManifestV2.requiredCapabilities must be unique.\");\n if (!requiredCapabilities.includes(\"rendering\")) throw new Error(\"ModelProcessingManifestV2 rendering capability is always required.\");\n if (technicalProfile.hasCollision !== (byCapability.get(\"collision\")?.status === \"supported\")) throw new Error(\"ModelProcessingManifestV2 collision capability must match technicalProfile.hasCollision.\");\n if (technicalProfile.hasCollision && collisionPages.every(({ spatialKey }) => spatialKey?.lodLevel !== 0)) {\n throw new Error(\"ModelProcessingManifestV2 supported collision requires LOD0 collision-field evidence.\");\n }\n const physicalRegionInventory = createPvoxPhysicalRegionInventoryV1(record.physicalRegionInventory);\n if (physicalRegionInventory.subjectContentHash !== binaryClosureHash\n || physicalRegionInventory.validationEvidenceHash !== pvox.validationEvidenceHash\n || physicalRegionInventory.entries.length !== technicalProfile.materialRegionCount\n || physicalRegionInventory.entries.some(({ physicalPaletteIndex }) => physicalPaletteIndex >= technicalProfile.physicalPaletteRecordCount)) {\n throw new Error(\"ModelProcessingManifestV2 authoritative physical region inventory must bind the PVOX validator, closure, region count, and palette records.\");\n }\n const physicalEntries = asDenseArray(record.physicalProperties, \"ModelProcessingManifestV2.physicalProperties\", 0, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries);\n const physicalProperties = physicalEntries.map(createPhysicalPropertyEvidence);\n const byRegionProperty = new Map(physicalProperties.map((entry) => [`${entry.regionId}\\u0000${entry.materialId}\\u0000${entry.property}`, entry]));\n if (byRegionProperty.size !== physicalProperties.length) throw new Error(\"ModelProcessingManifestV2 physical properties must be unique per region, material, and property.\");\n if (physicalProperties.some((entry) => entry.subjectContentHash !== binaryClosureHash)) throw new Error(\"ModelProcessingManifestV2 physical evidence must bind the PVOX binary closure subject.\");\n const authoritativePairs = physicalRegionInventory.entries.map(({ regionId, materialId }) => `${regionId}\\u0000${materialId}`);\n const authoritativePairSet = new Set(authoritativePairs);\n if (physicalProperties.some(({ regionId, materialId }) => !authoritativePairSet.has(`${regionId}\\u0000${materialId}`))) {\n throw new Error(\"ModelProcessingManifestV2 physical evidence cannot introduce a region absent from the authoritative inventory.\");\n }\n const authoritativeRegionIndex = new Map(authoritativePairs.map((pair, index) => [pair, index]));\n const physicalPropertyIndex = new Map(PVOX_PHYSICAL_PROPERTIES.map((property, index) => [property, index]));\n let previousPhysicalOrder = -1;\n for (const evidence of physicalProperties) {\n const regionIndex = authoritativeRegionIndex.get(`${evidence.regionId}\\u0000${evidence.materialId}`)!;\n const propertyIndex = physicalPropertyIndex.get(evidence.property)!;\n const order = regionIndex * PVOX_PHYSICAL_PROPERTIES.length + propertyIndex;\n if (order <= previousPhysicalOrder) {\n throw new Error(\"ModelProcessingManifestV2 physical properties must be canonically ordered by inventory regionIndex and governed property order.\");\n }\n previousPhysicalOrder = order;\n }\n for (const capability of PVOX_CAPABILITIES) {\n if (byCapability.get(capability)?.status !== \"supported\") continue;\n if ((PVOX_CAPABILITY_PHYSICAL_PROPERTIES[capability]?.length ?? 0) > 0 && authoritativePairs.length === 0) {\n throw new Error(`Supported ${capability} capability requires governed physical evidence.`);\n }\n for (const pair of authoritativePairs) {\n const [regionId, materialId] = pair.split(\"\\u0000\");\n for (const property of PVOX_CAPABILITY_PHYSICAL_PROPERTIES[capability] ?? []) {\n const evidence = byRegionProperty.get(`${regionId}\\u0000${materialId}\\u0000${property}`);\n if (evidence === undefined || evidence.confidence < 0.8 || (NON_DEFAULT_CRITICAL_PROPERTIES.has(property) && evidence.provenance === \"default\")) {\n throw new Error(`Supported ${capability} capability requires governed ${property} evidence for every material region with confidence at least 0.80 and no critical defaults.`);\n }\n }\n }\n }\n if (physicalProperties.length !== technicalProfile.physicalEvidenceRecordCount) {\n throw new Error(\"ModelProcessingManifestV2 authoritative material-region evidence count must match the PVOX PEVI record count.\");\n }\n const physicalEvidenceHash = requireSha256(record.physicalEvidenceHash, \"ModelProcessingManifestV2.physicalEvidenceHash\");\n const physicalEvidenceAttestation = createHashAttestation(\n record.physicalEvidenceAttestation,\n PVOX_PHYSICAL_EVIDENCE_HASH_DOMAIN,\n physicalEvidenceHash,\n \"ModelProcessingManifestV2.physicalEvidenceAttestation\",\n );\n const massPropertiesEvidence = createReviewedStructuralEvidence(\n record.massPropertiesEvidence,\n \"mass-properties\",\n binaryClosureHash,\n physicalRegionInventory.inventoryHash,\n technicalProfile.massPropertyRecordCount,\n \"ModelProcessingManifestV2.massPropertiesEvidence\",\n );\n const bondGraphEvidence = createReviewedStructuralEvidence(\n record.bondGraphEvidence,\n \"bond-graph\",\n binaryClosureHash,\n physicalRegionInventory.inventoryHash,\n technicalProfile.bondRecordCount,\n \"ModelProcessingManifestV2.bondGraphEvidence\",\n );\n const interiorLayerEvidence = createReviewedStructuralEvidence(\n record.interiorLayerEvidence,\n \"interior-layers\",\n binaryClosureHash,\n physicalRegionInventory.inventoryHash,\n technicalProfile.interiorLayerRecordCount,\n \"ModelProcessingManifestV2.interiorLayerEvidence\",\n );\n if (byCapability.get(\"destruction\")?.status === \"supported\"\n && (technicalProfile.massPropertyRecordCount === 0\n || technicalProfile.bondRecordCount === 0\n || technicalProfile.interiorLayerRecordCount === 0)) {\n throw new Error(\"ModelProcessingManifestV2 destruction capability requires reviewed mass, bond-graph, and interior-layer records.\");\n }\n const converter = createCompilerEvidence(record.converter);\n if (\n converter.sourceContentHash !== pvox.sourceContentHash\n || converter.canonicalDocumentHash !== pvox.canonicalDocumentHash\n || converter.compilationInputHash !== compilationInputHash\n || converter.runtimeRequestProfileHash !== runtimeRequestProfileHash\n || converter.outputContentHash !== contentHash\n ) throw new Error(\"ModelProcessingManifestV2 converter hashes must match source, canonical document, compilation input, runtime request profile, and PVOX outputContentHash.\");\n const fidelity = createPvoxFidelityEvidence(record.fidelity);\n const diagonalMetres = technicalProfile.maximumPartitionDiagonalMetres;\n if (fidelity.canonicalDocumentHash !== pvox.canonicalDocumentHash\n || fidelity.pvoxBinaryClosureHash !== binaryClosureHash\n || !approximatelyEqual(fidelity.evaluatedDiagonalMetres, diagonalMetres)\n || !approximatelyEqual(fidelity.lod0CellSizeMetres, pvox.lods[0]!.cellSizeMetres)) {\n throw new Error(\"ModelProcessingManifestV2 fidelity evidence must bind the canonical document, PVOX closure, evaluated bounds, and LOD0 cell size.\");\n }\n const lod0 = pvox.lods[0]!;\n if (!approximatelyEqual(fidelity.maximumSurfaceErrorMetres, lod0.maximumSurfaceErrorMetres)\n || !approximatelyEqual(fidelity.p99SurfaceErrorMetres, lod0.p99SurfaceErrorMetres)\n || !approximatelyEqual(fidelity.silhouetteIou, lod0.silhouetteIou)\n || !approximatelyEqual(fidelity.maximumContourDisplacementPx, lod0.maximumContourDisplacementPx)\n || !approximatelyEqual(fidelity.renderedSsim, lod0.renderedSsim)\n || !approximatelyEqual(fidelity.p95DeltaE2000, lod0.p95DeltaE2000)\n || !approximatelyEqual(fidelity.normalizedMaterialError, lod0.normalizedMaterialError)) {\n throw new Error(\"ModelProcessingManifestV2 fidelity evidence must exactly match every governed PVOX LOD0 metric.\");\n }\n const childEntries = asDenseArray(record.children, \"ModelProcessingManifestV2.children\", 0, PVOX_DEFAULT_LIMITS.maximumAssemblyChildren);\n const children = childEntries.map((entry, index) => createAssemblyChild(entry, index, resolutionId, candidateId));\n const kind = requireEnum(record.kind, [\"leaf\", \"assembly\"] as const, \"ModelProcessingManifestV2.kind\");\n if (kind === \"leaf\" && children.length !== 0) throw new Error(\"A leaf ModelProcessingManifestV2 cannot contain children.\");\n if (kind === \"leaf\" && technicalProfile.partitionCount !== 1) throw new Error(\"A leaf ModelProcessingManifestV2 must have one partition.\");\n if (kind === \"leaf\" && assemblyClosureHash === binaryClosureHash) throw new Error(\"A leaf ModelProcessingManifestV2 requires a distinct domain-separated empty-child assemblyClosureHash.\");\n if (kind === \"assembly\" && children.length === 0) throw new Error(\"An assembly ModelProcessingManifestV2 requires children.\");\n if (kind === \"assembly\") assertAssembly(children);\n const assemblyClosureAttestation = createHashAttestation(record.assemblyClosureAttestation, PVOX_ASSEMBLY_CLOSURE_HASH_DOMAIN, assemblyClosureHash, \"ModelProcessingManifestV2.assemblyClosureAttestation\");\n const processingClosureAttestation = createHashAttestation(\n record.processingClosureAttestation,\n PVOX_PROCESSING_CLOSURE_HASH_DOMAIN,\n processingClosureHash,\n \"ModelProcessingManifestV2.processingClosureAttestation\",\n );\n const processedAt = requireTimestamp(record.processedAt, \"ModelProcessingManifestV2.processedAt\");\n const latestEvidence = Math.max(\n Date.parse(converter.compiledAt),\n Date.parse(fidelity.evaluatedAt),\n ...orderedCapabilities.map(({ evaluatedAt }) => Date.parse(evaluatedAt)),\n ...physicalProperties.flatMap(({ reviewedAt }) => reviewedAt === undefined ? [] : [Date.parse(reviewedAt)]),\n Date.parse(massPropertiesEvidence.reviewedAt),\n Date.parse(bondGraphEvidence.reviewedAt),\n Date.parse(interiorLayerEvidence.reviewedAt),\n );\n if (Date.parse(processedAt) < latestEvidence) throw new Error(\"ModelProcessingManifestV2.processedAt must follow all processing evidence.\");\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n representation: \"pvox\",\n manifestId: requireToken(record.manifestId, \"ModelProcessingManifestV2.manifestId\"),\n resolutionId,\n candidateId,\n kind,\n requestProfileId: requireToken(record.requestProfileId, \"ModelProcessingManifestV2.requestProfileId\"),\n requestSemanticProfileHash,\n capabilityProfileId: requireEnum(record.capabilityProfileId, PVOX_RUNTIME_CAPABILITY_PROFILE_IDS, \"ModelProcessingManifestV2.capabilityProfileId\"),\n contentHash,\n binaryClosureHash,\n processingClosureHash,\n processingClosureAttestation,\n assemblyClosureHash,\n assemblyClosureAttestation,\n compilationInputHash,\n runtimeRequestProfileHash,\n coordinateSystem: CANONICAL_MODEL_COORDINATE_SYSTEM,\n pvox,\n technicalProfile,\n requiredCapabilities,\n capabilities: orderedCapabilities,\n capabilityEvidenceSetHash,\n capabilityEvidenceSetAttestation,\n physicalRegionInventory,\n physicalProperties,\n physicalEvidenceHash,\n physicalEvidenceAttestation,\n massPropertiesEvidence,\n bondGraphEvidence,\n interiorLayerEvidence,\n converter,\n fidelity,\n children,\n processedAt,\n });\n}\n\nfunction createCandidateAssetRef(value: unknown): ModelCandidateAssetRef {\n const record = asRecord(value, \"ModelCandidateV2.assetRef\");\n if (record.disposition === \"existing\") {\n exactKeys(record, [\"disposition\", \"kind\", \"contentHash\", \"asset\"], \"ModelCandidateV2.assetRef\");\n assertDataOnlyTree(record.asset, \"ModelCandidateV2.assetRef.asset\");\n const asset = createModelAssetRef(record.asset);\n if (record.kind !== asset.kind || record.contentHash !== asset.contentHash) throw new Error(\"ModelCandidateV2 existing assetRef must match the immutable asset.\");\n return { disposition: \"existing\", kind: asset.kind, contentHash: asset.contentHash, asset };\n }\n exactKeys(record, [\"disposition\", \"proposalId\", \"kind\", \"contentHash\"], \"ModelCandidateV2.assetRef\");\n if (record.disposition !== \"proposed\") throw new Error(\"ModelCandidateV2.assetRef disposition is unsupported.\");\n return {\n disposition: \"proposed\",\n proposalId: requireToken(record.proposalId, \"ModelCandidateV2.assetRef.proposalId\"),\n kind: requireEnum(record.kind, [\"leaf\", \"assembly\"] as const, \"ModelCandidateV2.assetRef.kind\"),\n contentHash: requireSha256(record.contentHash, \"ModelCandidateV2.assetRef.contentHash\"),\n };\n}\n\nfunction createViews(value: unknown, resolutionId: string, candidateId: string): ModelConfirmationViews {\n const entries = asDenseArray(value, \"ModelCandidateV2.views\", 4, 4);\n const parsed = entries.map((entry, index) => {\n const fieldName = `ModelCandidateV2.views[${index}]`;\n const record = asRecord(entry, fieldName);\n exactKeys(record, [\"kind\", \"imageUri\", \"sha256\", \"contentType\", \"width\", \"height\"], fieldName);\n const kind = requireEnum(record.kind, MODEL_CONFIRMATION_VIEW_KINDS, `${fieldName}.kind`);\n const expectedUri = `mcp://models/resolutions/${resolutionId}/candidates/${candidateId}/${kind}.png`;\n if (record.imageUri !== expectedUri) throw new Error(`${fieldName}.imageUri must match the candidate view identity.`);\n if (record.contentType !== \"image/png\" || record.width !== MODEL_CONFIRMATION_VIEW_SIZE_PX || record.height !== MODEL_CONFIRMATION_VIEW_SIZE_PX) throw new Error(`${fieldName} must be an authenticated 1024x1024 PNG.`);\n return { kind, imageUri: expectedUri, sha256: requireSha256(record.sha256, `${fieldName}.sha256`), contentType: \"image/png\" as const, width: MODEL_CONFIRMATION_VIEW_SIZE_PX, height: MODEL_CONFIRMATION_VIEW_SIZE_PX };\n });\n if (parsed.some((entry, index) => entry.kind !== MODEL_CONFIRMATION_VIEW_KINDS[index])) throw new Error(\"ModelCandidateV2.views must be ordered front, left, top, isometric.\");\n return parsed as unknown as ModelConfirmationViews;\n}\n\nfunction createRenderEvidence(value: unknown): PvoxRenderEvidence {\n const record = asRecord(value, \"ModelCandidateV2.renderEvidence\");\n exactKeys(record, [\"renderId\", \"representation\", \"lodLevel\", \"traversalBackend\", \"rendererId\", \"rendererVersion\", \"rendererQualificationHash\", \"settingsId\", \"settingsVersion\", \"cameraQualificationHash\", \"processingManifestId\", \"processingClosureHash\", \"pvoxContentHash\", \"pvoxRootHash\", \"pvoxDirectoryHash\", \"pvoxPageSetHash\", \"viewSha256s\", \"renderedAt\", \"evidenceHash\", \"evidenceHashAttestation\"], \"ModelCandidateV2.renderEvidence\");\n if (record.representation !== \"pvox\" || record.lodLevel !== 0 || record.traversalBackend !== \"native-pvox\") {\n throw new Error(\"ModelCandidateV2 render evidence must use native PVOX LOD0 traversal.\");\n }\n if (record.rendererId !== PVOX_NATIVE_RENDERER_ID || record.settingsId !== PVOX_NATIVE_REVIEW_SETTINGS_ID) {\n throw new Error(\"ModelCandidateV2 render evidence must use the governed native renderer and review settings.\");\n }\n const evidenceHash = requireSha256(record.evidenceHash, \"ModelCandidateV2.renderEvidence.evidenceHash\");\n return {\n renderId: requireToken(record.renderId, \"ModelCandidateV2.renderEvidence.renderId\"),\n representation: \"pvox\",\n lodLevel: 0,\n traversalBackend: \"native-pvox\",\n rendererId: PVOX_NATIVE_RENDERER_ID,\n rendererVersion: assertImmutableAssetVersion(record.rendererVersion),\n rendererQualificationHash: requireSha256(record.rendererQualificationHash, \"ModelCandidateV2.renderEvidence.rendererQualificationHash\"),\n settingsId: PVOX_NATIVE_REVIEW_SETTINGS_ID,\n settingsVersion: assertImmutableAssetVersion(record.settingsVersion),\n cameraQualificationHash: requireSha256(record.cameraQualificationHash, \"ModelCandidateV2.renderEvidence.cameraQualificationHash\"),\n processingManifestId: requireToken(record.processingManifestId, \"ModelCandidateV2.renderEvidence.processingManifestId\"),\n processingClosureHash: requireSha256(record.processingClosureHash, \"ModelCandidateV2.renderEvidence.processingClosureHash\"),\n pvoxContentHash: requireSha256(record.pvoxContentHash, \"ModelCandidateV2.renderEvidence.pvoxContentHash\"),\n pvoxRootHash: requireSha256(record.pvoxRootHash, \"ModelCandidateV2.renderEvidence.pvoxRootHash\"),\n pvoxDirectoryHash: requireSha256(record.pvoxDirectoryHash, \"ModelCandidateV2.renderEvidence.pvoxDirectoryHash\"),\n pvoxPageSetHash: requireSha256(record.pvoxPageSetHash, \"ModelCandidateV2.renderEvidence.pvoxPageSetHash\"),\n viewSha256s: requireShaTuple(record.viewSha256s, \"ModelCandidateV2.renderEvidence.viewSha256s\"),\n renderedAt: requireTimestamp(record.renderedAt, \"ModelCandidateV2.renderEvidence.renderedAt\"),\n evidenceHash,\n evidenceHashAttestation: createHashAttestation(record.evidenceHashAttestation, PVOX_RENDER_EVIDENCE_HASH_DOMAIN, evidenceHash, \"ModelCandidateV2.renderEvidence.evidenceHashAttestation\"),\n };\n}\n\n/** Extend a released-v1 assessment without changing its closed v1 factory. */\nexport function createPvoxModelMatchAssessmentV2(input: unknown): PvoxModelMatchAssessmentV2 {\n const fieldName = \"PvoxModelMatchAssessmentV2\";\n const record = asRecord(input, fieldName);\n assertDataOnlyTree(record, fieldName);\n exactKeys(record, [\n \"contractVersion\", \"score\", \"assurance\", \"hardConstraintPass\", \"exactMatch\", \"reasonCodes\", \"ranker\",\n \"fidelityWarnings\", \"request\", \"candidateId\", \"candidateContentHash\", \"requestSemanticProfileHash\",\n \"requestSemanticProfileCanonical\", \"evidenceHash\",\n ], fieldName);\n const assessment = createModelMatchAssessment({\n ...(record.contractVersion === undefined ? {} : { contractVersion: record.contractVersion }),\n score: record.score,\n ...(record.assurance === undefined ? {} : { assurance: record.assurance }),\n hardConstraintPass: record.hardConstraintPass,\n exactMatch: record.exactMatch,\n reasonCodes: record.reasonCodes,\n ranker: record.ranker,\n fidelityWarnings: record.fidelityWarnings,\n request: record.request,\n candidateId: record.candidateId,\n candidateContentHash: record.candidateContentHash,\n });\n return deepFreeze({\n ...assessment,\n requestSemanticProfileHash: requireSha256(record.requestSemanticProfileHash, `${fieldName}.requestSemanticProfileHash`),\n requestSemanticProfileCanonical: requireString(record.requestSemanticProfileCanonical, `${fieldName}.requestSemanticProfileCanonical`, 65_536),\n evidenceHash: requireSha256(record.evidenceHash, `${fieldName}.evidenceHash`),\n });\n}\n\nfunction createConfirmationBinding(value: unknown): ModelCandidateConfirmationBindingV2 {\n const record = asRecord(value, \"ModelCandidateV2.confirmationBinding\");\n assertDataOnlyTree(record, \"ModelCandidateV2.confirmationBinding\");\n exactKeys(record, [\"bindingHash\", \"bindingHashAttestation\", \"resolutionId\", \"requesterId\", \"request\", \"requestSemanticProfileHash\", \"requestRevision\", \"candidateId\", \"candidateContentHash\", \"candidateAssetRef\", \"match\", \"provenance\", \"rights\", \"sourceContentHash\", \"binaryClosureHash\", \"pvoxRootHash\", \"pvoxDirectoryHash\", \"pvoxPageSetHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"processingClosureHash\", \"assemblyClosureHash\", \"evaluationClosureHash\", \"capabilityEvidenceSetHash\", \"hardGates\", \"viewSha256s\", \"rightsDecisionId\", \"fidelityEvidenceHash\", \"physicalEvidenceHash\", \"rendererId\", \"rendererVersion\", \"rendererEvidenceHash\", \"renderEvidence\"], \"ModelCandidateV2.confirmationBinding\");\n const bindingHash = requireSha256(record.bindingHash, \"ModelCandidateV2.confirmationBinding.bindingHash\");\n const hardGateEntries = asDenseArray(record.hardGates, \"ModelCandidateV2.confirmationBinding.hardGates\", PVOX_NON_OVERRIDABLE_GATE_KINDS.length, PVOX_NON_OVERRIDABLE_GATE_KINDS.length);\n return {\n bindingHash,\n bindingHashAttestation: createHashAttestation(record.bindingHashAttestation, PVOX_CONFIRMATION_BINDING_HASH_DOMAIN, bindingHash, \"ModelCandidateV2.confirmationBinding.bindingHashAttestation\"),\n resolutionId: requirePathSegment(record.resolutionId, \"ModelCandidateV2.confirmationBinding.resolutionId\"),\n requesterId: requireToken(record.requesterId, \"ModelCandidateV2.confirmationBinding.requesterId\"),\n request: createModelRequestSpecV2(record.request),\n requestSemanticProfileHash: requireSha256(record.requestSemanticProfileHash, \"ModelCandidateV2.confirmationBinding.requestSemanticProfileHash\"),\n requestRevision: requireInteger(record.requestRevision, \"ModelCandidateV2.confirmationBinding.requestRevision\", 0, MODEL_REQUEST_MAX_REVISION),\n candidateId: requirePathSegment(record.candidateId, \"ModelCandidateV2.confirmationBinding.candidateId\"),\n candidateContentHash: requireSha256(record.candidateContentHash, \"ModelCandidateV2.confirmationBinding.candidateContentHash\"),\n candidateAssetRef: createCandidateAssetRef(record.candidateAssetRef),\n match: createPvoxModelMatchAssessmentV2(record.match),\n provenance: createModelProvenance(record.provenance),\n rights: createModelRightsAssessment(record.rights),\n sourceContentHash: requireSha256(record.sourceContentHash, \"ModelCandidateV2.confirmationBinding.sourceContentHash\"),\n binaryClosureHash: requireSha256(record.binaryClosureHash, \"ModelCandidateV2.confirmationBinding.binaryClosureHash\"),\n pvoxRootHash: requireSha256(record.pvoxRootHash, \"ModelCandidateV2.confirmationBinding.pvoxRootHash\"),\n pvoxDirectoryHash: requireSha256(record.pvoxDirectoryHash, \"ModelCandidateV2.confirmationBinding.pvoxDirectoryHash\"),\n pvoxPageSetHash: requireSha256(record.pvoxPageSetHash, \"ModelCandidateV2.confirmationBinding.pvoxPageSetHash\"),\n compilationInputHash: requireSha256(record.compilationInputHash, \"ModelCandidateV2.confirmationBinding.compilationInputHash\"),\n runtimeRequestProfileHash: requireSha256(record.runtimeRequestProfileHash, \"ModelCandidateV2.confirmationBinding.runtimeRequestProfileHash\"),\n processingClosureHash: requireSha256(record.processingClosureHash, \"ModelCandidateV2.confirmationBinding.processingClosureHash\"),\n assemblyClosureHash: requireSha256(record.assemblyClosureHash, \"ModelCandidateV2.confirmationBinding.assemblyClosureHash\"),\n evaluationClosureHash: requireSha256(record.evaluationClosureHash, \"ModelCandidateV2.confirmationBinding.evaluationClosureHash\"),\n capabilityEvidenceSetHash: requireSha256(record.capabilityEvidenceSetHash, \"ModelCandidateV2.confirmationBinding.capabilityEvidenceSetHash\"),\n hardGates: hardGateEntries.map(createPvoxGateEvidence),\n viewSha256s: requireShaTuple(record.viewSha256s, \"ModelCandidateV2.confirmationBinding.viewSha256s\"),\n rightsDecisionId: requireToken(record.rightsDecisionId, \"ModelCandidateV2.confirmationBinding.rightsDecisionId\"),\n fidelityEvidenceHash: requireSha256(record.fidelityEvidenceHash, \"ModelCandidateV2.confirmationBinding.fidelityEvidenceHash\"),\n physicalEvidenceHash: requireSha256(record.physicalEvidenceHash, \"ModelCandidateV2.confirmationBinding.physicalEvidenceHash\"),\n rendererId: requireToken(record.rendererId, \"ModelCandidateV2.confirmationBinding.rendererId\"),\n rendererVersion: assertImmutableAssetVersion(record.rendererVersion),\n rendererEvidenceHash: requireSha256(record.rendererEvidenceHash, \"ModelCandidateV2.confirmationBinding.rendererEvidenceHash\"),\n renderEvidence: createRenderEvidence(record.renderEvidence),\n };\n}\n\nfunction assertRequestMatchesProcessing(request: ModelRequestSpecV2, processing: ModelProcessingManifestV2): void {\n const profile = request.pvoxRuntimeProfile;\n const technical = processing.technicalProfile;\n if (processing.requestProfileId !== profile.profileId\n || processing.requestSemanticProfileHash !== request.requestSemanticProfileHash\n || processing.capabilityProfileId !== profile.capabilityProfileId\n || processing.fidelity.profileId !== profile.fidelityProfileId) {\n throw new Error(\"ModelCandidateV2 processing profile IDs must match the exact v2 request.\");\n }\n if (profile.geometryMode !== \"auto\" && profile.geometryMode !== technical.geometryMode) {\n throw new Error(\"ModelCandidateV2 processing geometryMode must match the exact v2 request.\");\n }\n const requestedCapabilities = new Set(profile.requiredCapabilities);\n if (requestedCapabilities.size !== processing.requiredCapabilities.length\n || processing.requiredCapabilities.some((capability) => !requestedCapabilities.has(capability))) {\n throw new Error(\"ModelCandidateV2 processing requiredCapabilities must exactly match the v2 request.\");\n }\n const limits = profile.limits;\n if (technical.artifactByteLength > limits.maximumArtifactBytes\n || technical.pageCount > limits.maximumPages\n || technical.hierarchyDepth > limits.maximumHierarchyDepth\n || technical.hierarchyNodeCount + technical.collisionHierarchyNodeCount > limits.maximumHierarchyNodes\n || technical.brickCount + technical.collisionBrickCount > limits.maximumBricks\n || technical.logicalVoxelCapacity + technical.collisionLogicalVoxelCapacity > limits.maximumLogicalVoxels\n || technical.encodedSurfaceSampleCount + technical.collisionEncodedSurfaceSampleCount > limits.maximumEncodedSurfaceSamples\n || technical.surfacePropertyCount > limits.maximumSurfaceProperties\n || technical.physicalPaletteRecordCount > limits.maximumPhysicalPaletteRecords\n || technical.physicalEvidenceRecordCount > limits.maximumPhysicalEvidenceEntries\n || technical.materialRegionCount > limits.maximumMaterialRegions\n || technical.interiorLayerRecordCount > limits.maximumInteriorLayers\n || technical.massPropertyRecordCount > limits.maximumMassPropertyRecords\n || technical.bondRecordCount > limits.maximumBondRecords\n || technical.partitionCount > limits.maximumPartitions\n || technical.lodCount > limits.maximumLodCount\n || technical.cpuResidentByteLength > limits.maximumCpuResidentBytes\n || technical.gpuResidentByteLength > limits.maximumGpuResidentBytes) {\n throw new Error(\"ModelCandidateV2 PVOX technical profile exceeds an exact request runtime limit.\");\n }\n const constraints = request.hardConstraints;\n if (constraints.boundsMetres !== undefined\n && (constraints.boundsMetres.min.some((value, index) => !approximatelyEqual(value, technical.boundsMetres.min[index]!))\n || constraints.boundsMetres.max.some((value, index) => !approximatelyEqual(value, technical.boundsMetres.max[index]!)))) {\n throw new Error(\"ModelCandidateV2 PVOX bounds do not satisfy the exact request.\");\n }\n if (constraints.dimensionsMetres !== undefined\n && (!approximatelyEqual(constraints.dimensionsMetres.width, technical.dimensionsMetres.width)\n || !approximatelyEqual(constraints.dimensionsMetres.height, technical.dimensionsMetres.height)\n || !approximatelyEqual(constraints.dimensionsMetres.depth, technical.dimensionsMetres.depth))) {\n throw new Error(\"ModelCandidateV2 PVOX dimensions do not satisfy the exact request.\");\n }\n if ((constraints.collision === \"required\" && !technical.hasCollision)\n || (constraints.collision === \"forbidden\" && technical.hasCollision)) {\n throw new Error(\"ModelCandidateV2 PVOX collision capability does not satisfy the exact request.\");\n }\n if ((constraints.partition === \"single\" && technical.partitionCount !== 1)\n || (constraints.partition === \"required\" && technical.partitionCount < 2)) {\n throw new Error(\"ModelCandidateV2 PVOX partitioning does not satisfy the exact request.\");\n }\n}\n\n/** Validate a complete PVOX candidate and every non-overridable binding. */\nexport function createModelCandidateV2(input: unknown): ModelCandidateV2 {\n const record = asRecord(input, \"ModelCandidateV2\");\n assertDataOnlyTree(record, \"ModelCandidateV2\");\n const commonKeys = [\"contractVersion\", \"resolutionId\", \"requesterId\", \"candidateId\", \"request\", \"admissionStatus\", \"assetRef\", \"match\", \"provenance\", \"rights\", \"processingManifest\", \"views\", \"renderEvidence\", \"evaluationClosureHash\", \"evaluationClosureAttestation\", \"hardGates\", \"confirmationRequired\"] as const;\n const admissionStatus = requireEnum(record.admissionStatus, [\"confirmable\", \"diagnostic\"] as const, \"ModelCandidateV2.admissionStatus\");\n exactKeys(record, admissionStatus === \"confirmable\" ? [...commonKeys, \"confirmationBinding\", \"confirmationToken\"] : [...commonKeys, \"blockingReasonCodes\"], \"ModelCandidateV2\");\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION) throw new Error(\"ModelCandidateV2.contractVersion is unsupported.\");\n const resolutionId = requirePathSegment(record.resolutionId, \"ModelCandidateV2.resolutionId\");\n const requesterId = requireToken(record.requesterId, \"ModelCandidateV2.requesterId\");\n const candidateId = requirePathSegment(record.candidateId, \"ModelCandidateV2.candidateId\");\n const request = createModelRequestSpecV2(record.request);\n const assetRef = createCandidateAssetRef(record.assetRef);\n assertDataOnlyTree(record.match, \"ModelCandidateV2.match\");\n assertDataOnlyTree(record.provenance, \"ModelCandidateV2.provenance\");\n assertDataOnlyTree(record.rights, \"ModelCandidateV2.rights\");\n const match = createPvoxModelMatchAssessmentV2(record.match);\n assertImmutableAssetVersion(match.ranker.version);\n assertImmutableAssetVersion(match.ranker.calibrationVersion);\n const provenance = createModelProvenance(record.provenance);\n const rights = createModelRightsAssessment(record.rights);\n assertImmutableAssetVersion(rights.policyVersion);\n const processingManifest = createModelProcessingManifestV2(record.processingManifest);\n if (processingManifest.resolutionId !== resolutionId || processingManifest.candidateId !== candidateId || processingManifest.kind !== assetRef.kind || processingManifest.contentHash !== assetRef.contentHash) throw new Error(\"ModelCandidateV2 processing manifest must match candidate identity and contentHash.\");\n if (match.candidateId !== candidateId || match.candidateContentHash !== assetRef.contentHash) throw new Error(\"ModelCandidateV2 match must bind the exact candidate content.\");\n if (match.requestSemanticProfileHash !== request.requestSemanticProfileHash) throw new Error(\"ModelCandidateV2 semantic assessment must bind the complete normalized v2 request profile hash.\");\n if (match.requestSemanticProfileCanonical !== canonicalizeModelRequestSemanticProfileV1(request)) throw new Error(\"ModelCandidateV2 semantic assessment must bind the exact canonical v2 request profile.\");\n if (match.request.query !== request.query || match.request.revision !== request.revision || match.request.locale !== request.locale || match.request.rankerId !== request.rankerId) throw new Error(\"ModelCandidateV2 match must bind the exact v2 request semantics and revision.\");\n assertRequestMatchesProcessing(request, processingManifest);\n if (provenance.contentHash !== processingManifest.pvox.sourceContentHash) throw new Error(\"ModelCandidateV2 provenance must bind the PVOX sourceContentHash.\");\n if (rights.sourceId !== provenance.sourceId || rights.sourceAssetId !== provenance.sourceAssetId || rights.sourceContentHash !== provenance.contentHash) throw new Error(\"ModelCandidateV2 rights evidence must bind the exact source.\");\n const resourceScope = parsePvoxResourceScope(processingManifest.pvox.artifact.uri);\n if (assetRef.disposition === \"proposed\" && (resourceScope.kind !== \"resolution\" || resourceScope.resolutionId !== resolutionId || resourceScope.candidateId !== candidateId)) {\n throw new Error(\"ModelCandidateV2 proposed PVOX resource must use its resolution/candidate namespace.\");\n }\n if (assetRef.disposition === \"existing\" && (resourceScope.kind !== \"catalog\" || resourceScope.assetId !== assetRef.asset.assetId || resourceScope.version !== assetRef.asset.version)) {\n throw new Error(\"ModelCandidateV2 existing asset must prove the same immutable catalog PVOX representation.\");\n }\n const views = createViews(record.views, resolutionId, candidateId);\n const renderEvidence = createRenderEvidence(record.renderEvidence);\n if (\n renderEvidence.processingManifestId !== processingManifest.manifestId\n || renderEvidence.processingClosureHash !== processingManifest.processingClosureHash\n || renderEvidence.pvoxContentHash !== processingManifest.contentHash\n || renderEvidence.pvoxRootHash !== processingManifest.pvox.rootHash\n || renderEvidence.pvoxDirectoryHash !== processingManifest.pvox.directoryHash\n || renderEvidence.pvoxPageSetHash !== processingManifest.pvox.pageSetHash\n || renderEvidence.viewSha256s.some((digest, index) => digest !== views[index]!.sha256)\n ) throw new Error(\"ModelCandidateV2 renderer evidence must bind the PVOX manifest and ordered views.\");\n if (Date.parse(renderEvidence.renderedAt) < Date.parse(processingManifest.processedAt)) throw new Error(\"ModelCandidateV2 render evidence must follow processing.\");\n const evaluationClosureHash = requireSha256(record.evaluationClosureHash, \"ModelCandidateV2.evaluationClosureHash\");\n const evaluationClosureAttestation = createHashAttestation(\n record.evaluationClosureAttestation,\n PVOX_EVALUATION_CLOSURE_HASH_DOMAIN,\n evaluationClosureHash,\n \"ModelCandidateV2.evaluationClosureAttestation\",\n );\n const gateEntries = asDenseArray(record.hardGates, \"ModelCandidateV2.hardGates\", PVOX_NON_OVERRIDABLE_GATE_KINDS.length, PVOX_NON_OVERRIDABLE_GATE_KINDS.length);\n const gates = gateEntries.map(createPvoxGateEvidence);\n const byGate = new Map(gates.map((entry) => [entry.kind, entry]));\n if (byGate.size !== PVOX_NON_OVERRIDABLE_GATE_KINDS.length || PVOX_NON_OVERRIDABLE_GATE_KINDS.some((kind) => !byGate.has(kind))) throw new Error(\"ModelCandidateV2 must contain every non-overridable hard gate exactly once.\");\n const orderedGates = PVOX_NON_OVERRIDABLE_GATE_KINDS.map((kind) => byGate.get(kind)!);\n const concreteGateHashes: Readonly<Partial<Record<PvoxNonOverridableGateKind, string>>> = {\n \"source-format-validation\": processingManifest.converter.evidenceHash,\n \"pvox-validation\": processingManifest.pvox.validationEvidenceHash,\n \"fidelity-validation\": processingManifest.fidelity.evidenceHash,\n \"physical-property-validation\": processingManifest.physicalEvidenceHash,\n \"renderer-validation\": renderEvidence.evidenceHash,\n };\n for (const gate of orderedGates) {\n const expectedHash = gate.kind === \"malware-scan\" || gate.kind === \"source-format-validation\" ? provenance.contentHash : processingManifest.binaryClosureHash;\n if (gate.subjectContentHash !== expectedHash) throw new Error(`ModelCandidateV2 ${gate.kind} hard gate binds the wrong subject.`);\n const concreteHash = concreteGateHashes[gate.kind];\n if (concreteHash !== undefined && gate.evidenceHash !== concreteHash) throw new Error(`ModelCandidateV2 ${gate.kind} hard gate must bind its concrete evidence hash.`);\n }\n const fidelityGate = byGate.get(\"fidelity-validation\")!;\n if (fidelityGate.outcome !== processingManifest.fidelity.outcome) throw new Error(\"ModelCandidateV2 fidelity gate outcome must match measured fidelity evidence.\");\n const blockingReasonCodes = [\n ...(match.assurance === \"none\" ? [\"semantic-assurance-none\"] : []),\n ...(!match.hardConstraintPass ? [\"semantic-hard-constraints-failed\"] : []),\n ...(![\"allowed\", \"attribution-required\"].includes(rights.status) ? [`rights:${rights.status}`] : []),\n ...processingManifest.requiredCapabilities.flatMap((capability) => {\n const evidence = processingManifest.capabilities.find((entry) => entry.capability === capability)!;\n return evidence.status === \"supported\" ? [] : [`capability:${capability}:${evidence.status}`];\n }),\n ...orderedGates.flatMap((gate) => gate.outcome === \"passed\" ? [] : gate.reasonCodes.map((reason) => `${gate.kind}:${reason}`)),\n ];\n const shouldBeConfirmable = blockingReasonCodes.length === 0;\n if ((admissionStatus === \"confirmable\") !== shouldBeConfirmable) throw new Error(\"ModelCandidateV2 admissionStatus must reflect all rights, semantic, capability, fidelity, and hard-gate blockers.\");\n const common = {\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n resolutionId,\n requesterId,\n candidateId,\n request,\n assetRef,\n match,\n provenance,\n rights,\n processingManifest,\n views,\n renderEvidence,\n evaluationClosureHash,\n evaluationClosureAttestation,\n hardGates: orderedGates,\n };\n if (admissionStatus === \"diagnostic\") {\n if (record.confirmationRequired !== false) throw new Error(\"Diagnostic ModelCandidateV2 confirmationRequired must be false.\");\n if (record.blockingReasonCodes !== undefined) {\n const suppliedEntries = asDenseArray(record.blockingReasonCodes, \"ModelCandidateV2.blockingReasonCodes\", 1, 256);\n const suppliedBlockingReasons = suppliedEntries.map((entry, index) => requireReasonCode(entry, `ModelCandidateV2.blockingReasonCodes[${index}]`));\n if (JSON.stringify(suppliedBlockingReasons) !== JSON.stringify(blockingReasonCodes)) throw new Error(\"Diagnostic ModelCandidateV2 blockingReasonCodes must be derived from its evidence.\");\n }\n return deepFreeze({ ...common, admissionStatus: \"diagnostic\", blockingReasonCodes, confirmationRequired: false });\n }\n if (record.confirmationRequired !== true) throw new Error(\"Confirmable ModelCandidateV2 confirmationRequired must be true.\");\n const confirmationBinding = createConfirmationBinding(record.confirmationBinding);\n const expectedBinding = {\n resolutionId,\n requesterId,\n requestSemanticProfileHash: request.requestSemanticProfileHash,\n requestRevision: match.request.revision,\n candidateId,\n candidateContentHash: assetRef.contentHash,\n sourceContentHash: provenance.contentHash,\n binaryClosureHash: processingManifest.binaryClosureHash,\n pvoxRootHash: processingManifest.pvox.rootHash,\n pvoxDirectoryHash: processingManifest.pvox.directoryHash,\n pvoxPageSetHash: processingManifest.pvox.pageSetHash,\n compilationInputHash: processingManifest.compilationInputHash,\n runtimeRequestProfileHash: processingManifest.runtimeRequestProfileHash,\n processingClosureHash: processingManifest.processingClosureHash,\n assemblyClosureHash: processingManifest.assemblyClosureHash,\n evaluationClosureHash,\n capabilityEvidenceSetHash: processingManifest.capabilityEvidenceSetHash,\n rightsDecisionId: rights.decisionId,\n fidelityEvidenceHash: processingManifest.fidelity.evidenceHash,\n physicalEvidenceHash: processingManifest.physicalEvidenceHash,\n rendererId: renderEvidence.rendererId,\n rendererVersion: renderEvidence.rendererVersion,\n rendererEvidenceHash: renderEvidence.evidenceHash,\n };\n for (const [key, expected] of Object.entries(expectedBinding)) {\n if (confirmationBinding[key as keyof typeof confirmationBinding] !== expected) throw new Error(`ModelCandidateV2 confirmationBinding.${key} must match candidate evidence.`);\n }\n if (JSON.stringify(confirmationBinding.request) !== JSON.stringify(request)) throw new Error(\"ModelCandidateV2 confirmationBinding.request must match the exact v2 request.\");\n if (JSON.stringify(confirmationBinding.candidateAssetRef) !== JSON.stringify(assetRef)) throw new Error(\"ModelCandidateV2 confirmationBinding candidate asset identity must match the exact proposal or catalog asset.\");\n if (JSON.stringify(confirmationBinding.match) !== JSON.stringify(match)) throw new Error(\"ModelCandidateV2 confirmationBinding must bind the complete semantic match evidence.\");\n if (JSON.stringify(confirmationBinding.provenance) !== JSON.stringify(provenance)) throw new Error(\"ModelCandidateV2 confirmationBinding must bind the complete provider provenance identity.\");\n if (JSON.stringify(confirmationBinding.rights) !== JSON.stringify(rights)) throw new Error(\"ModelCandidateV2 confirmationBinding must bind the complete normalized rights decision.\");\n if (JSON.stringify(confirmationBinding.renderEvidence) !== JSON.stringify(renderEvidence)) throw new Error(\"ModelCandidateV2 confirmationBinding must bind the complete native renderer evidence.\");\n if (JSON.stringify(confirmationBinding.hardGates) !== JSON.stringify(orderedGates)) throw new Error(\"ModelCandidateV2 confirmationBinding must contain the complete ordered hard-gate evidence set.\");\n if (confirmationBinding.viewSha256s.some((digest, index) => digest !== views[index]!.sha256)) throw new Error(\"ModelCandidateV2 confirmationBinding view hashes must match candidate views.\");\n const confirmationToken = requireAttestation(record.confirmationToken, \"ModelCandidateV2.confirmationToken\");\n if (confirmationBinding.bindingHashAttestation.attestationToken !== confirmationToken) throw new Error(\"ModelCandidateV2 confirmation token must attest the exact confirmation binding hash.\");\n return deepFreeze({\n ...common,\n admissionStatus: \"confirmable\",\n confirmationBinding,\n confirmationToken,\n confirmationRequired: true,\n });\n}\n\n/** Return whether a fully validated candidate still satisfies every hard gate. */\nexport function isModelCandidateV2Confirmable(candidate: ModelCandidateV2): boolean {\n return candidate.admissionStatus === \"confirmable\"\n && candidate.confirmationRequired\n && candidate.match.hardConstraintPass\n && candidate.match.assurance !== \"none\"\n && (candidate.rights.status === \"allowed\" || candidate.rights.status === \"attribution-required\")\n && candidate.processingManifest.fidelity.outcome === \"passed\"\n && candidate.hardGates.length === PVOX_NON_OVERRIDABLE_GATE_KINDS.length\n && candidate.hardGates.every(({ outcome }) => outcome === \"passed\")\n && candidate.processingManifest.requiredCapabilities.every((name) => candidate.processingManifest.capabilities.find((entry) => entry.capability === name)?.status === \"supported\");\n}\n\n/** Validate one requester confirmation against the exact PVOX review subject. */\nexport function createModelCandidateConfirmationV2(input: unknown, expectedCandidate: ModelCandidateV2, expectedResolutionId: string): ModelCandidateConfirmationV2 {\n const record = asRecord(input, \"ModelCandidateConfirmationV2\");\n exactKeys(record, [\"contractVersion\", \"confirmationId\", \"resolutionId\", \"requesterId\", \"candidateId\", \"confirmationToken\", \"confirmationBindingHash\", \"viewSha256s\", \"confirmedBy\", \"confirmedAt\", \"semanticRiskAccepted\"], \"ModelCandidateConfirmationV2\");\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION) throw new Error(\"ModelCandidateConfirmationV2.contractVersion is unsupported.\");\n const candidate = createModelCandidateV2(expectedCandidate);\n if (candidate.admissionStatus !== \"confirmable\") throw new Error(\"ModelCandidateConfirmationV2 cannot confirm a diagnostic candidate.\");\n const resolutionId = requirePathSegment(expectedResolutionId, \"ModelCandidateConfirmationV2 expected resolutionId\");\n if (candidate.resolutionId !== resolutionId || record.resolutionId !== resolutionId || record.requesterId !== candidate.requesterId || record.candidateId !== candidate.candidateId) throw new Error(\"ModelCandidateConfirmationV2 must match the candidate, requester, and resolution.\");\n if (record.confirmationToken !== candidate.confirmationToken) throw new Error(\"ModelCandidateConfirmationV2 confirmationToken must match the candidate.\");\n if (record.confirmationBindingHash !== candidate.confirmationBinding.bindingHash) throw new Error(\"ModelCandidateConfirmationV2 confirmation binding must match the candidate.\");\n const viewSha256s = requireShaTuple(record.viewSha256s, \"ModelCandidateConfirmationV2.viewSha256s\");\n if (viewSha256s.some((digest, index) => digest !== candidate.views[index]!.sha256)) throw new Error(\"ModelCandidateConfirmationV2 view hashes must match candidate evidence.\");\n if (!isModelCandidateV2Confirmable(candidate)) throw new Error(\"ModelCandidateConfirmationV2 candidate is not confirmable because a hard gate is blocked.\");\n const semanticRiskAccepted = requireBoolean(record.semanticRiskAccepted, \"ModelCandidateConfirmationV2.semanticRiskAccepted\");\n if ((candidate.match.assurance === \"low\") !== semanticRiskAccepted) throw new Error(\"Only low semantic assurance requires and permits semantic risk acceptance.\");\n const confirmedAt = requireTimestamp(record.confirmedAt, \"ModelCandidateConfirmationV2.confirmedAt\");\n const latestEvidence = Math.max(\n Date.parse(candidate.provenance.capturedAt), Date.parse(candidate.rights.reviewedAt),\n Date.parse(candidate.processingManifest.processedAt), Date.parse(candidate.renderEvidence.renderedAt),\n ...candidate.hardGates.map(({ evaluatedAt }) => Date.parse(evaluatedAt)),\n );\n if (Date.parse(confirmedAt) < latestEvidence) throw new Error(\"ModelCandidateConfirmationV2 confirmation must follow all required evidence.\");\n const confirmedBy = requireString(record.confirmedBy, \"ModelCandidateConfirmationV2.confirmedBy\", 256);\n if (DIRECT_URL.test(confirmedBy)) throw new Error(\"ModelCandidateConfirmationV2.confirmedBy must not expose a URL.\");\n if (confirmedBy !== candidate.requesterId) throw new Error(\"ModelCandidateConfirmationV2 confirmedBy must be the requester bound to the resolution.\");\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n confirmationId: requireToken(record.confirmationId, \"ModelCandidateConfirmationV2.confirmationId\"),\n resolutionId,\n requesterId: candidate.requesterId,\n candidateId: candidate.candidateId,\n confirmationToken: candidate.confirmationToken,\n confirmationBindingHash: candidate.confirmationBinding.bindingHash,\n viewSha256s,\n confirmedBy,\n confirmedAt,\n semanticRiskAccepted,\n });\n}\n\n/** Narrow an unknown state to the additive PVOX lifecycle. */\nexport function isModelResolutionStateV2(value: unknown): value is ModelResolutionStateV2 {\n return typeof value === \"string\" && (MODEL_RESOLUTION_V2_STATES as readonly string[]).includes(value);\n}\n\n/** Project one v2 state for legacy wrappers without changing v1 state enums. */\nexport function toLegacyModelResolutionState(state: ModelResolutionStateV2): ModelResolutionState {\n if (!isModelResolutionStateV2(state)) throw new Error(\"Unknown ModelResolutionStateV2 state.\");\n return MODEL_RESOLUTION_V2_COMPATIBILITY_STATES[state];\n}\n\nfunction candidatesEquivalent(left: ModelCandidateV2, right: ModelCandidateV2): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction createModelPromotionReceiptV2(\n input: unknown,\n resolutionId: string,\n candidate: ConfirmableModelCandidateV2,\n confirmation: ModelCandidateConfirmationV2,\n finalAssetRef: ModelAssetRef,\n): ModelPromotionReceiptV2 {\n if (candidate.assetRef.disposition !== \"proposed\") throw new Error(\"ModelPromotionReceiptV2 is only valid for a proposed candidate.\");\n const record = asRecord(input, \"ModelPromotionReceiptV2\");\n exactKeys(record, [\n \"contractVersion\", \"promotionId\", \"resolutionId\", \"requesterId\", \"candidateId\", \"proposalId\", \"candidateAssetRef\", \"confirmationId\", \"confirmationBindingHash\",\n \"processingManifestId\", \"processingContentHash\", \"processingClosureHash\", \"assemblyClosureHash\", \"assemblyChildClosureHashes\", \"finalAssetRef\", \"creditsRecordHash\",\n \"catalogRowHash\", \"indexSnapshotHash\", \"catalogPointerEtag\", \"indexPointerEtag\", \"publicationState\",\n \"creditsWrittenAt\", \"catalogRowWrittenAt\", \"indexSnapshotWrittenAt\", \"pointerPublishedAt\",\n \"publicationHash\", \"publicationHashAttestation\", \"promotedAt\", \"publicationToken\",\n ], \"ModelPromotionReceiptV2\");\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION || record.publicationState !== \"pointer-last-complete\") {\n throw new Error(\"ModelPromotionReceiptV2 must use the v2 contract and prove pointer-last completion.\");\n }\n if (record.resolutionId !== resolutionId\n || record.requesterId !== candidate.requesterId\n || record.candidateId !== candidate.candidateId\n || record.proposalId !== candidate.assetRef.proposalId\n || record.confirmationId !== confirmation.confirmationId\n || record.confirmationBindingHash !== confirmation.confirmationBindingHash\n || record.processingManifestId !== candidate.processingManifest.manifestId\n || record.processingContentHash !== candidate.processingManifest.contentHash\n || record.processingClosureHash !== candidate.processingManifest.processingClosureHash\n || record.assemblyClosureHash !== candidate.processingManifest.assemblyClosureHash) {\n throw new Error(\"ModelPromotionReceiptV2 must bind the exact proposal, confirmation, processing content, and PVOX assembly closure.\");\n }\n assertDataOnlyTree(record.candidateAssetRef, \"ModelPromotionReceiptV2.candidateAssetRef\");\n const candidateAssetRef = createCandidateAssetRef(record.candidateAssetRef);\n if (JSON.stringify(candidateAssetRef) !== JSON.stringify(candidate.assetRef)) throw new Error(\"ModelPromotionReceiptV2 must bind the exact proposed candidate identity.\");\n const childClosureEntries = asDenseArray(record.assemblyChildClosureHashes, \"ModelPromotionReceiptV2.assemblyChildClosureHashes\", 0, PVOX_DEFAULT_LIMITS.maximumAssemblyChildren);\n const assemblyChildClosureHashes = childClosureEntries.map((entry, index) => requireSha256(entry, `ModelPromotionReceiptV2.assemblyChildClosureHashes[${index}]`));\n const expectedChildClosureHashes = candidate.processingManifest.children.map(({ assetRef }) => assetRef.binaryClosureHash);\n if (JSON.stringify(assemblyChildClosureHashes) !== JSON.stringify(expectedChildClosureHashes)) throw new Error(\"ModelPromotionReceiptV2 child closure sequence must match the canonical assembly order.\");\n assertDataOnlyTree(record.finalAssetRef, \"ModelPromotionReceiptV2.finalAssetRef\");\n const receiptAssetRef = createModelAssetRef(record.finalAssetRef);\n if (JSON.stringify(receiptAssetRef) !== JSON.stringify(finalAssetRef)) throw new Error(\"ModelPromotionReceiptV2 finalAssetRef must match the completed resolution.\");\n const creditsWrittenAt = requireTimestamp(record.creditsWrittenAt, \"ModelPromotionReceiptV2.creditsWrittenAt\");\n const catalogRowWrittenAt = requireTimestamp(record.catalogRowWrittenAt, \"ModelPromotionReceiptV2.catalogRowWrittenAt\");\n const indexSnapshotWrittenAt = requireTimestamp(record.indexSnapshotWrittenAt, \"ModelPromotionReceiptV2.indexSnapshotWrittenAt\");\n const pointerPublishedAt = requireTimestamp(record.pointerPublishedAt, \"ModelPromotionReceiptV2.pointerPublishedAt\");\n const promotedAt = requireTimestamp(record.promotedAt, \"ModelPromotionReceiptV2.promotedAt\");\n const publicationSequence = [confirmation.confirmedAt, creditsWrittenAt, catalogRowWrittenAt, indexSnapshotWrittenAt, pointerPublishedAt, promotedAt].map(Date.parse);\n if (publicationSequence.some((time, index) => index > 0 && time < publicationSequence[index - 1]!)) {\n throw new Error(\"ModelPromotionReceiptV2 must prove credits, catalog row, index snapshot, and pointers were published in pointer-last order.\");\n }\n const publicationHash = requireSha256(record.publicationHash, \"ModelPromotionReceiptV2.publicationHash\");\n const publicationHashAttestation = createHashAttestation(record.publicationHashAttestation, PVOX_PUBLICATION_HASH_DOMAIN, publicationHash, \"ModelPromotionReceiptV2.publicationHashAttestation\");\n const publicationToken = requireAttestation(record.publicationToken, \"ModelPromotionReceiptV2.publicationToken\");\n if (publicationHashAttestation.attestationToken !== publicationToken) throw new Error(\"ModelPromotionReceiptV2 publication token must attest the exact publication hash.\");\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n promotionId: requireToken(record.promotionId, \"ModelPromotionReceiptV2.promotionId\"),\n resolutionId,\n requesterId: candidate.requesterId,\n candidateId: candidate.candidateId,\n proposalId: candidate.assetRef.proposalId,\n candidateAssetRef,\n confirmationId: confirmation.confirmationId,\n confirmationBindingHash: confirmation.confirmationBindingHash,\n processingManifestId: candidate.processingManifest.manifestId,\n processingContentHash: candidate.processingManifest.contentHash,\n processingClosureHash: candidate.processingManifest.processingClosureHash,\n assemblyClosureHash: candidate.processingManifest.assemblyClosureHash,\n assemblyChildClosureHashes,\n finalAssetRef: receiptAssetRef,\n creditsRecordHash: requireSha256(record.creditsRecordHash, \"ModelPromotionReceiptV2.creditsRecordHash\"),\n catalogRowHash: requireSha256(record.catalogRowHash, \"ModelPromotionReceiptV2.catalogRowHash\"),\n indexSnapshotHash: requireSha256(record.indexSnapshotHash, \"ModelPromotionReceiptV2.indexSnapshotHash\"),\n catalogPointerEtag: requireToken(record.catalogPointerEtag, \"ModelPromotionReceiptV2.catalogPointerEtag\"),\n indexPointerEtag: requireToken(record.indexPointerEtag, \"ModelPromotionReceiptV2.indexPointerEtag\"),\n publicationState: \"pointer-last-complete\",\n creditsWrittenAt,\n catalogRowWrittenAt,\n indexSnapshotWrittenAt,\n pointerPublishedAt,\n publicationHash,\n publicationHashAttestation,\n promotedAt,\n publicationToken,\n });\n}\n\nfunction createModelRefinementQuestionV2(input: unknown, index: number): ModelRefinementQuestionV2 {\n const fieldName = `ModelResolutionV2.refinementQuestions[${index}]`;\n const record = asRecord(input, fieldName);\n exactKeys(record, [\"questionId\", \"prompt\", \"reasonCodes\"], fieldName);\n return deepFreeze({\n questionId: requireToken(record.questionId, `${fieldName}.questionId`),\n prompt: requireString(record.prompt, `${fieldName}.prompt`, 500),\n reasonCodes: requireReasonCodes(record.reasonCodes, `${fieldName}.reasonCodes`),\n });\n}\n\n/** Validate one durable PVOX model-resolution snapshot. */\nexport function createModelResolutionV2(input: unknown): ModelResolutionV2 {\n const record = asRecord(input, \"ModelResolutionV2\");\n exactKeys(record, [\"contractVersion\", \"resolutionId\", \"requesterId\", \"request\", \"attempts\", \"state\", \"compatibilityState\", \"candidates\", \"bestCandidate\", \"confirmation\", \"promotionReceipt\", \"refinementQuestions\", \"finalAssetRef\", \"stateReasonCode\", \"createdAt\", \"updatedAt\"], \"ModelResolutionV2\");\n if (record.contractVersion !== MODEL_RESOLUTION_V2_CONTRACT_VERSION) throw new Error(\"ModelResolutionV2.contractVersion is unsupported.\");\n const resolutionId = requirePathSegment(record.resolutionId, \"ModelResolutionV2.resolutionId\");\n const requesterId = requireToken(record.requesterId, \"ModelResolutionV2.requesterId\");\n const request = createModelRequestSpecV2(record.request);\n const state = requireEnum(record.state, MODEL_RESOLUTION_V2_STATES, \"ModelResolutionV2.state\");\n const compatibilityState = toLegacyModelResolutionState(state);\n if (record.compatibilityState !== undefined && record.compatibilityState !== compatibilityState) throw new Error(\"ModelResolutionV2 compatibilityState must match its deterministic legacy projection.\");\n const candidateEntries = asDenseArray(record.candidates, \"ModelResolutionV2.candidates\", 0, 20);\n const candidates = candidateEntries.map(createModelCandidateV2);\n if (new Set(candidates.map(({ candidateId }) => candidateId)).size !== candidates.length) throw new Error(\"ModelResolutionV2 candidate IDs must be unique.\");\n if (candidates.some((candidate) => candidate.resolutionId !== resolutionId || candidate.requesterId !== requesterId || JSON.stringify(candidate.request) !== JSON.stringify(request))) throw new Error(\"ModelResolutionV2 candidates must bind the exact requester, v2 resolution request, and profiles.\");\n const bestCandidate = record.bestCandidate === undefined ? undefined : createModelCandidateV2(record.bestCandidate);\n if (bestCandidate !== undefined && !candidates.some((candidate) => candidatesEquivalent(candidate, bestCandidate))) throw new Error(\"ModelResolutionV2 bestCandidate must be one exact candidate in the resolution.\");\n if (state === \"awaiting-confirmation\" && (bestCandidate === undefined || !isModelCandidateV2Confirmable(bestCandidate))) throw new Error(\"ModelResolutionV2 awaiting-confirmation requires one confirmable bestCandidate.\");\n const refinementEntries = asDenseArray(record.refinementQuestions, \"ModelResolutionV2.refinementQuestions\", 0, 3);\n const refinementQuestions = refinementEntries.map(createModelRefinementQuestionV2);\n if (new Set(refinementQuestions.map(({ questionId }) => questionId)).size !== refinementQuestions.length) throw new Error(\"ModelResolutionV2 refinement question IDs must be unique.\");\n if (state === \"awaiting-confirmation\" && bestCandidate?.match.assurance === \"low\" && refinementQuestions.length === 0) throw new Error(\"Low-assurance ModelResolutionV2 requires refinement questions.\");\n if (state === \"completed\" && record.finalAssetRef === undefined) throw new Error(\"ModelResolutionV2 completed state requires finalAssetRef.\");\n const confirmation = record.confirmation === undefined\n ? undefined\n : bestCandidate === undefined\n ? (() => { throw new Error(\"ModelResolutionV2 confirmation requires bestCandidate.\"); })()\n : createModelCandidateConfirmationV2(record.confirmation, bestCandidate, resolutionId);\n if ([\"promoting\", \"completed\"].includes(state) && confirmation === undefined) throw new Error(`ModelResolutionV2 ${state} requires confirmation.`);\n if (![\"promoting\", \"completed\"].includes(state) && confirmation !== undefined) throw new Error(\"ModelResolutionV2 confirmation is only allowed while promoting or completed.\");\n if (record.finalAssetRef !== undefined) assertDataOnlyTree(record.finalAssetRef, \"ModelResolutionV2.finalAssetRef\");\n const finalAssetRef = record.finalAssetRef === undefined ? undefined : createModelAssetRef(record.finalAssetRef);\n if (state === \"completed\" && finalAssetRef === undefined) throw new Error(\"ModelResolutionV2 completed state requires finalAssetRef.\");\n if (state !== \"completed\" && finalAssetRef !== undefined) throw new Error(\"ModelResolutionV2 finalAssetRef is only allowed for completed state.\");\n if (finalAssetRef !== undefined && bestCandidate !== undefined) {\n if (finalAssetRef.kind !== bestCandidate.assetRef.kind || finalAssetRef.contentHash !== bestCandidate.assetRef.contentHash) {\n throw new Error(\"ModelResolutionV2 finalAssetRef must match bestCandidate.\");\n }\n if (bestCandidate.assetRef.disposition === \"existing\") {\n const existingAsset = bestCandidate.assetRef.asset;\n if (finalAssetRef.assetId !== existingAsset.assetId\n || finalAssetRef.version !== existingAsset.version\n || finalAssetRef.runtimeManifestUri !== existingAsset.runtimeManifestUri) {\n throw new Error(\"ModelResolutionV2 finalAssetRef must preserve the exact existing immutable asset identity.\");\n }\n }\n }\n let promotionReceipt: ModelPromotionReceiptV2 | undefined;\n if (record.promotionReceipt !== undefined) {\n if (state !== \"completed\" || finalAssetRef === undefined || confirmation === undefined || bestCandidate?.admissionStatus !== \"confirmable\" || bestCandidate.assetRef.disposition !== \"proposed\") {\n throw new Error(\"ModelResolutionV2 promotionReceipt is only allowed for a completed confirmed proposed candidate.\");\n }\n promotionReceipt = createModelPromotionReceiptV2(record.promotionReceipt, resolutionId, bestCandidate, confirmation, finalAssetRef);\n }\n if (state === \"completed\" && bestCandidate?.assetRef.disposition === \"proposed\" && promotionReceipt === undefined) {\n throw new Error(\"ModelResolutionV2 completed proposed candidates require a pointer-last promotionReceipt.\");\n }\n if (bestCandidate?.assetRef.disposition === \"existing\" && promotionReceipt !== undefined) throw new Error(\"ModelResolutionV2 existing selections must not include a promotionReceipt.\");\n const stateReasonCode = record.stateReasonCode === undefined ? undefined : requireReasonCode(record.stateReasonCode, \"ModelResolutionV2.stateReasonCode\");\n if ([\"unresolved\", \"failed\", \"cancelled\"].includes(state) && stateReasonCode === undefined) throw new Error(`ModelResolutionV2 ${state} state requires stateReasonCode.`);\n if (![\"unresolved\", \"failed\", \"cancelled\"].includes(state) && stateReasonCode !== undefined) throw new Error(\"ModelResolutionV2 stateReasonCode is reserved for terminal non-success states.\");\n const createdAt = requireTimestamp(record.createdAt, \"ModelResolutionV2.createdAt\");\n const updatedAt = requireTimestamp(record.updatedAt, \"ModelResolutionV2.updatedAt\");\n if (Date.parse(updatedAt) < Date.parse(createdAt)) throw new Error(\"ModelResolutionV2.updatedAt must not precede createdAt.\");\n if (confirmation !== undefined && Date.parse(confirmation.confirmedAt) > Date.parse(updatedAt)) {\n throw new Error(\"ModelResolutionV2 confirmation confirmedAt must not exceed updatedAt.\");\n }\n if (promotionReceipt !== undefined && confirmation !== undefined && (Date.parse(promotionReceipt.promotedAt) < Date.parse(confirmation.confirmedAt) || Date.parse(promotionReceipt.promotedAt) > Date.parse(updatedAt))) {\n throw new Error(\"ModelResolutionV2 promotionReceipt must follow confirmation and not exceed updatedAt.\");\n }\n return deepFreeze({\n contractVersion: MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n resolutionId,\n requesterId,\n request,\n attempts: requireInteger(record.attempts, \"ModelResolutionV2.attempts\", 1, 12),\n state,\n compatibilityState,\n candidates,\n ...(bestCandidate === undefined ? {} : { bestCandidate }),\n ...(confirmation === undefined ? {} : { confirmation }),\n ...(promotionReceipt === undefined ? {} : { promotionReceipt }),\n refinementQuestions,\n ...(finalAssetRef === undefined ? {} : { finalAssetRef }),\n ...(stateReasonCode === undefined ? {} : { stateReasonCode }),\n createdAt,\n updatedAt,\n });\n}\n","import {\n CANONICAL_MODEL_COORDINATE_SYSTEM,\n MODEL_ASSET_KINDS,\n MODEL_CONFIRMATION_VIEW_KINDS,\n MODEL_CONFIRMATION_VIEW_SIZE_PX,\n MODEL_MATCH_ASSURANCE_BANDS,\n MODEL_PROVENANCE_KINDS,\n MODEL_RANKER_EVIDENCE_MODES,\n MODEL_REQUEST_MAX_REVISION,\n MODEL_RESOLUTION_CONTRACT_VERSION,\n MODEL_RESOLUTION_STATES,\n MODEL_RIGHTS_STATUSES,\n STATIC_WORLD_V1_MODEL_POLICY,\n} from \"./model-resolution.js\";\nimport {\n MODEL_RESOLUTION_V2_CONTRACT_VERSION,\n MODEL_RESOLUTION_V2_STATES,\n PVOX_ASSET_MANIFEST_VERSION,\n PVOX_BRICK_EDGE_VOXELS,\n PVOX_CAPABILITIES,\n PVOX_CONTENT_TYPE,\n PVOX_DEFAULT_LIMITS,\n PVOX_DEFAULT_SOURCE_INGESTION_LIMITS,\n PVOX_EDIT_JOURNAL_VERSION,\n PVOX_FIDELITY_PROFILE_IDS,\n PVOX_FIDELITY_PROFILE_VERSION,\n PVOX_FILE_EXTENSION,\n PVOX_HASH_DOMAINS,\n PVOX_HEADER_BYTE_LENGTH,\n PVOX_DIRECTORY_ENTRY_BYTE_LENGTH,\n PVOX_MAGIC,\n PVOX_MAX_ABSOLUTE_COORDINATE_METRES,\n PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES,\n PVOX_MAX_HIERARCHY_NODES,\n PVOX_MAX_LOCAL_SAMPLES_PER_BRICK,\n PVOX_MAX_RUNS_PER_BRICK,\n PVOX_MAX_SECTIONS,\n PVOX_MIN_STATIC_SECTION_COUNT,\n PVOX_MAX_EDIT_PATCHES,\n PVOX_MODEL_REQUEST_POLICY_ID,\n PVOX_NATIVE_RENDERER_ID,\n PVOX_NATIVE_REVIEW_SETTINGS_ID,\n PVOX_NON_OVERRIDABLE_GATE_KINDS,\n PVOX_PAGE_KINDS,\n PVOX_PAGE_SIZE_BYTES,\n PVOX_PHYSICAL_PROPERTIES,\n PVOX_PHYSICAL_REGION_INVENTORY_VERSION,\n PVOX_PHYSICAL_PROPERTY_POLICIES,\n PVOX_PHYSICAL_PROPERTY_POLICY_ID,\n PVOX_PHYSICAL_PROPERTY_POLICY_VERSION,\n PVOX_RUNTIME_CAPABILITY_PROFILE_IDS,\n} from \"./pvox-model-resolution.js\";\n\nexport type PvoxModelResolutionJsonSchema = Readonly<Record<string, unknown>> & {\n readonly $id: string;\n readonly $schema: \"https://json-schema.org/draft/2020-12/schema\";\n readonly type: \"object\";\n readonly additionalProperties: false;\n readonly $defs: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n};\n\ntype Schema = Record<string, unknown>;\n\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value === null || typeof value !== \"object\") return value;\n const object = value as object;\n if (seen.has(object)) return value;\n seen.add(object);\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child, seen);\n return Object.freeze(value);\n}\n\nfunction objectSchema(properties: Record<string, Schema>, required: readonly string[] = [], extra: Schema = {}): Schema {\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n required,\n ...extra,\n };\n}\n\nfunction arraySchema(items: Schema, minimum = 0, maximum?: number): Schema {\n return {\n type: \"array\",\n items,\n minItems: minimum,\n ...(maximum === undefined ? {} : { maxItems: maximum }),\n };\n}\n\nfunction tupleSchema(items: readonly Schema[]): Schema {\n return {\n type: \"array\",\n prefixItems: items,\n items: false,\n minItems: items.length,\n maxItems: items.length,\n };\n}\n\nfunction hashAttestationSchema(domain: Schema): Schema {\n return objectSchema({\n algorithm: { const: \"sha256\" },\n domain,\n digest: sha256,\n attestationToken: attestation,\n }, [\"algorithm\", \"domain\", \"digest\", \"attestationToken\"]);\n}\n\nconst ref = (name: string): Schema => ({ $ref: `#/$defs/${name}` });\nconst stringSchema = (maximum = 512): Schema => ({ type: \"string\", minLength: 1, maxLength: maximum });\nconst numberSchema = (minimum?: number, maximum?: number): Schema => ({\n type: \"number\",\n ...(minimum === undefined ? {} : { minimum }),\n ...(maximum === undefined ? {} : { maximum }),\n});\nconst integerSchema = (minimum: number, maximum?: number): Schema => ({\n type: \"integer\",\n minimum,\n ...(maximum === undefined ? {} : { maximum }),\n});\n\nconst sha256 = { type: \"string\", pattern: \"^[a-f0-9]{64}$\" };\nconst token = { type: \"string\", pattern: \"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$\" };\nconst opaqueSourceAssetId = { type: \"string\", pattern: \"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$\" };\nconst pathSegment = { type: \"string\", pattern: \"^(?!\\\\.{1,2}$)[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$\" };\nconst reasonCode = { type: \"string\", pattern: \"^[a-z0-9][a-z0-9._:-]{0,127}$\" };\nconst attestation = { type: \"string\", pattern: \"^[A-Za-z0-9_-]{32,256}$\" };\nconst timestamp = {\n type: \"string\",\n pattern: \"^(?:[0-9]{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])T(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]\\\\.[0-9]{3}Z$\",\n};\nconst immutableVersion = {\n type: \"string\",\n minLength: 1,\n maxLength: 128,\n pattern: \"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$\",\n not: {\n anyOf: [\n { pattern: \"^[Ll][Aa][Tt][Ee][Ss][Tt]$\" },\n { pattern: \"^[Cc][Uu][Rr][Rr][Ee][Nn][Tt]$\" },\n { pattern: \"^[Ss][Tt][Aa][Bb][Ll][Ee]$\" },\n { pattern: \"^[Pp][Rr][Ee][Vv][Ii][Ee][Ww]$\" },\n { pattern: \"^[Dd][Ee][Ff][Aa][Uu][Ll][Tt]$\" },\n { pattern: \"^[Pp][Rr][Oo][Dd][Uu][Cc][Tt][Ii][Oo][Nn]$\" },\n { pattern: \"^[Cc][Aa][Nn][Aa][Rr][Yy]$\" },\n { pattern: \"^[Nn][Ee][Xx][Tt]$\" },\n { pattern: \"^[Hh][Ee][Aa][Dd]$\" },\n { pattern: \"^[Mm][Aa][Ii][Nn]$\" },\n { pattern: \"(?:^|[._-])[xX](?:$|[._-])\" },\n ],\n },\n};\nconst reasonCodes = { ...arraySchema(reasonCode, 0, 32), uniqueItems: true };\nconst releasedV1ReasonCodes = { ...arraySchema(token, 0, 32), uniqueItems: true };\nconst mutableCatalogVersionPath = {\n anyOf: [\n { pattern: \"/versions/[Ll][Aa][Tt][Ee][Ss][Tt]/\" },\n { pattern: \"/versions/[Cc][Uu][Rr][Rr][Ee][Nn][Tt]/\" },\n { pattern: \"/versions/[Ss][Tt][Aa][Bb][Ll][Ee]/\" },\n { pattern: \"/versions/[Pp][Rr][Ee][Vv][Ii][Ee][Ww]/\" },\n { pattern: \"/versions/[Dd][Ee][Ff][Aa][Uu][Ll][Tt]/\" },\n { pattern: \"/versions/[Pp][Rr][Oo][Dd][Uu][Cc][Tt][Ii][Oo][Nn]/\" },\n { pattern: \"/versions/[Cc][Aa][Nn][Aa][Rr][Yy]/\" },\n { pattern: \"/versions/[Nn][Ee][Xx][Tt]/\" },\n { pattern: \"/versions/[Hh][Ee][Aa][Dd]/\" },\n { pattern: \"/versions/[Mm][Aa][Ii][Nn]/\" },\n { pattern: \"/versions/(?:[vV])?[xX](?:[.-]|/)\" },\n { pattern: \"/versions/[^/]*\\\\.[xX](?:[.-]|/)\" },\n ],\n};\nconst shaTuple = tupleSchema([sha256, sha256, sha256, sha256]);\nconst vector3 = tupleSchema([\n numberSchema(-PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n numberSchema(-PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n numberSchema(-PVOX_MAX_ABSOLUTE_COORDINATE_METRES, PVOX_MAX_ABSOLUTE_COORDINATE_METRES),\n]);\nconst positiveVector3 = tupleSchema([numberSchema(Number.EPSILON), numberSchema(Number.EPSILON), numberSchema(Number.EPSILON)]);\nconst quaternion = tupleSchema([numberSchema(-1, 1), numberSchema(-1, 1), numberSchema(-1, 1), numberSchema(-1, 1)]);\n\nconst definitions: Record<string, Schema> = {\n coordinateSystem: objectSchema({\n unit: { const: CANONICAL_MODEL_COORDINATE_SYSTEM.unit },\n upAxis: { const: CANONICAL_MODEL_COORDINATE_SYSTEM.upAxis },\n forwardAxis: { const: CANONICAL_MODEL_COORDINATE_SYSTEM.forwardAxis },\n origin: { const: CANONICAL_MODEL_COORDINATE_SYSTEM.origin },\n outwardFaceWinding: { const: CANONICAL_MODEL_COORDINATE_SYSTEM.outwardFaceWinding },\n }, [\"unit\", \"upAxis\", \"forwardAxis\", \"origin\", \"outwardFaceWinding\"]),\n pvoxFormatVersion: objectSchema({ major: { const: 1 }, minor: { const: 0 } }, [\"major\", \"minor\"]),\n pvoxHashAttestation: hashAttestationSchema({ enum: Object.values(PVOX_HASH_DOMAINS) }),\n pvoxAssemblyClosureHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.assemblyClosure }),\n pvoxCapabilitySetHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.capabilitySet }),\n pvoxConfirmationBindingHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.confirmationBinding }),\n pvoxEditJournalHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.editJournal }),\n pvoxEditOverlayRootHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.editOverlayRoot }),\n pvoxEvaluationClosureHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.evaluationClosure }),\n pvoxPhysicalEvidenceHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.physicalEvidence }),\n pvoxPhysicalInventoryHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.physicalInventory }),\n pvoxProcessingClosureHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.processingClosure }),\n pvoxPublicationHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.publication }),\n pvoxRenderEvidenceHashAttestation: hashAttestationSchema({ const: PVOX_HASH_DOMAINS.renderEvidence }),\n bounds: objectSchema({ min: vector3, max: vector3 }, [\"min\", \"max\"]),\n dimensions: objectSchema({\n width: numberSchema(Number.EPSILON),\n height: numberSchema(Number.EPSILON),\n depth: numberSchema(Number.EPSILON),\n }, [\"width\", \"height\", \"depth\"]),\n hardConstraintsV2: objectSchema({\n boundsMetres: ref(\"bounds\"),\n dimensionsMetres: ref(\"dimensions\"),\n collision: { enum: [\"required\", \"optional\", \"forbidden\"] },\n partition: { enum: [\"single\", \"allowed\", \"required\"] },\n }),\n softPreferences: objectSchema({\n category: stringSchema(80),\n style: stringSchema(80),\n materials: arraySchema(stringSchema(256), 0, 32),\n colors: arraySchema(stringSchema(256), 0, 32),\n era: stringSchema(80),\n condition: stringSchema(80),\n tags: arraySchema(stringSchema(256), 0, 32),\n }),\n sourceIngestionLimits: objectSchema({\n maximumDownloadBytes: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumDownloadBytes),\n maximumExpandedBytes: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumExpandedBytes),\n maximumArchiveEntries: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumArchiveEntries),\n maximumSourceFiles: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumSourceFiles),\n maximumDecodedTextureBytes: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumDecodedTextureBytes),\n maximumTextureDimensionPx: integerSchema(1, PVOX_DEFAULT_SOURCE_INGESTION_LIMITS.maximumTextureDimensionPx),\n }, [\"maximumDownloadBytes\", \"maximumExpandedBytes\", \"maximumArchiveEntries\", \"maximumSourceFiles\", \"maximumDecodedTextureBytes\", \"maximumTextureDimensionPx\"]),\n pvoxRuntimeLimits: objectSchema({\n maximumArtifactBytes: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumArtifactBytes),\n maximumPages: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPages),\n maximumHierarchyDepth: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n maximumHierarchyNodes: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumHierarchyNodes),\n maximumBricks: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumBricks),\n maximumLogicalVoxels: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumLogicalVoxels),\n maximumEncodedSurfaceSamples: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples),\n maximumSurfaceProperties: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumSurfaceProperties),\n maximumPhysicalPaletteRecords: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties),\n maximumPhysicalEvidenceEntries: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries),\n maximumMaterialRegions: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions),\n maximumInteriorLayers: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumInteriorLayers),\n maximumMassPropertyRecords: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumMassPropertyRecords),\n maximumBondRecords: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumBondRecords),\n maximumPartitions: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPartitions),\n maximumLodCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumLodCount),\n maximumCpuResidentBytes: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumCpuResidentBytes),\n maximumGpuResidentBytes: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumGpuResidentBytes),\n }, [\"maximumArtifactBytes\", \"maximumPages\", \"maximumHierarchyDepth\", \"maximumHierarchyNodes\", \"maximumBricks\", \"maximumLogicalVoxels\", \"maximumEncodedSurfaceSamples\", \"maximumSurfaceProperties\", \"maximumPhysicalPaletteRecords\", \"maximumPhysicalEvidenceEntries\", \"maximumMaterialRegions\", \"maximumInteriorLayers\", \"maximumMassPropertyRecords\", \"maximumBondRecords\", \"maximumPartitions\", \"maximumLodCount\", \"maximumCpuResidentBytes\", \"maximumGpuResidentBytes\"]),\n pvoxRuntimeProfile: objectSchema({\n profileId: token,\n fidelityProfileId: { enum: PVOX_FIDELITY_PROFILE_IDS },\n capabilityProfileId: { enum: PVOX_RUNTIME_CAPABILITY_PROFILE_IDS },\n geometryMode: { enum: [\"solid\", \"shell\", \"mixed\", \"auto\"] },\n requiredCapabilities: { ...arraySchema({ enum: PVOX_CAPABILITIES }, 1, PVOX_CAPABILITIES.length), uniqueItems: true },\n limits: ref(\"pvoxRuntimeLimits\"),\n }, [\"profileId\", \"fidelityProfileId\", \"capabilityProfileId\", \"geometryMode\", \"requiredCapabilities\", \"limits\"]),\n modelRequestSpecV2: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n policyProfileId: { const: PVOX_MODEL_REQUEST_POLICY_ID },\n requestSemanticProfileHash: sha256,\n query: stringSchema(1_000),\n revision: integerSchema(0, MODEL_REQUEST_MAX_REVISION),\n locale: stringSchema(64),\n rankerId: token,\n hardConstraints: ref(\"hardConstraintsV2\"),\n softPreferences: ref(\"softPreferences\"),\n exclusions: arraySchema(stringSchema(256), 0, 32),\n sourceIngestionLimits: ref(\"sourceIngestionLimits\"),\n pvoxRuntimeProfile: ref(\"pvoxRuntimeProfile\"),\n }, [\"contractVersion\", \"policyProfileId\", \"requestSemanticProfileHash\", \"query\", \"revision\", \"hardConstraints\", \"softPreferences\", \"exclusions\", \"sourceIngestionLimits\", \"pvoxRuntimeProfile\"]),\n pvoxResource: objectSchema({\n uri: {\n type: \"string\",\n maxLength: 512,\n oneOf: [\n { pattern: \"^mcp://models/resolutions/[A-Za-z0-9._~-]+/candidates/[A-Za-z0-9._~-]+/artifacts/sha256/[a-f0-9]{64}\\\\.pvox$\" },\n {\n pattern: \"^mcp://models/catalog/[a-z0-9]+(?:-[a-z0-9]+)*/versions/[A-Za-z0-9][A-Za-z0-9._-]{0,127}/artifacts/sha256/[a-f0-9]{64}\\\\.pvox$\",\n not: mutableCatalogVersionPath,\n },\n ],\n },\n byteLength: { ...integerSchema(PVOX_PAGE_SIZE_BYTES, PVOX_DEFAULT_LIMITS.maximumArtifactBytes), multipleOf: PVOX_PAGE_SIZE_BYTES },\n sha256,\n contentType: { const: PVOX_CONTENT_TYPE },\n authenticated: { const: true },\n }, [\"uri\", \"byteLength\", \"sha256\", \"contentType\", \"authenticated\"]),\n pvoxPageSpatialKey: objectSchema({\n lodLevel: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumLodCount - 1),\n partitionIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPartitions - 1),\n hierarchyDepth: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n minimumMortonCode: { type: \"string\", pattern: \"^[a-f0-9]{16}$\" },\n maximumMortonCode: { type: \"string\", pattern: \"^[a-f0-9]{16}$\" },\n }, [\"lodLevel\", \"partitionIndex\", \"hierarchyDepth\", \"minimumMortonCode\", \"maximumMortonCode\"]),\n pvoxPage: objectSchema({\n pageIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPages - 1),\n pageKind: { enum: PVOX_PAGE_KINDS },\n byteOffset: { ...integerSchema(0, PVOX_DEFAULT_LIMITS.maximumArtifactBytes - 1), multipleOf: PVOX_PAGE_SIZE_BYTES },\n byteLength: { const: PVOX_PAGE_SIZE_BYTES },\n decodedByteLength: { const: PVOX_PAGE_SIZE_BYTES },\n sha256,\n spatialKey: ref(\"pvoxPageSpatialKey\"),\n }, [\"pageIndex\", \"pageKind\", \"byteOffset\", \"byteLength\", \"decodedByteLength\", \"sha256\"], {\n allOf: [{\n if: {\n properties: { pageKind: { enum: [\"render-field\", \"collision-field\"] } },\n required: [\"pageKind\"],\n },\n then: { properties: { spatialKey: ref(\"pvoxPageSpatialKey\") }, required: [\"spatialKey\"] },\n else: { not: { properties: { spatialKey: {} }, required: [\"spatialKey\"] } },\n }],\n }),\n pvoxLod: objectSchema({\n level: integerSchema(0, 3),\n firstPageIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPages - 1),\n pageCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPages),\n brickCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumBricks),\n cellSizeMetres: numberSchema(Number.EPSILON),\n maximumSurfaceErrorMetres: numberSchema(0),\n p99SurfaceErrorMetres: numberSchema(0),\n silhouetteIou: numberSchema(0, 1),\n maximumContourDisplacementPx: numberSchema(0),\n renderedSsim: numberSchema(0, 1),\n p95DeltaE2000: numberSchema(0, 100),\n normalizedMaterialError: numberSchema(0, 1),\n }, [\"level\", \"firstPageIndex\", \"pageCount\", \"brickCount\", \"cellSizeMetres\", \"maximumSurfaceErrorMetres\", \"p99SurfaceErrorMetres\", \"silhouetteIou\", \"maximumContourDisplacementPx\", \"renderedSsim\", \"p95DeltaE2000\", \"normalizedMaterialError\"]),\n pvoxAssetManifest: objectSchema({\n manifestVersion: { const: PVOX_ASSET_MANIFEST_VERSION },\n representation: { const: \"pvox\" },\n formatVersion: ref(\"pvoxFormatVersion\"),\n contentType: { const: PVOX_CONTENT_TYPE },\n fileExtension: { const: PVOX_FILE_EXTENSION },\n magic: { const: PVOX_MAGIC },\n brickEdgeVoxels: { const: PVOX_BRICK_EDGE_VOXELS },\n pageSizeBytes: { const: PVOX_PAGE_SIZE_BYTES },\n geometryMode: { enum: [\"solid\", \"shell\", \"mixed\"] },\n sourceContentHash: sha256,\n canonicalDocumentHash: sha256,\n rootHash: sha256,\n directoryHash: sha256,\n pageSetHash: sha256,\n binaryClosureHash: sha256,\n validationEvidenceHash: sha256,\n compilationInputHash: sha256,\n runtimeRequestProfileHash: sha256,\n headerByteLength: { const: PVOX_HEADER_BYTE_LENGTH },\n directoryEntryByteLength: { const: PVOX_DIRECTORY_ENTRY_BYTE_LENGTH },\n sectionCount: integerSchema(PVOX_MIN_STATIC_SECTION_COUNT, PVOX_MAX_SECTIONS),\n maximumRunsPerBrick: { const: PVOX_MAX_RUNS_PER_BRICK },\n maximumLocalSamplesPerBrick: { const: PVOX_MAX_LOCAL_SAMPLES_PER_BRICK },\n maximumEncodedBrickPayloadBytes: { const: PVOX_MAX_ENCODED_BRICK_PAYLOAD_BYTES },\n coordinateSystem: ref(\"coordinateSystem\"),\n boundsMetres: ref(\"bounds\"),\n artifact: ref(\"pvoxResource\"),\n pages: arraySchema(ref(\"pvoxPage\"), 1, PVOX_DEFAULT_LIMITS.maximumPages),\n lods: arraySchema(ref(\"pvoxLod\"), 1, PVOX_DEFAULT_LIMITS.maximumLodCount),\n }, [\"manifestVersion\", \"representation\", \"formatVersion\", \"contentType\", \"fileExtension\", \"magic\", \"brickEdgeVoxels\", \"pageSizeBytes\", \"geometryMode\", \"sourceContentHash\", \"canonicalDocumentHash\", \"rootHash\", \"directoryHash\", \"pageSetHash\", \"binaryClosureHash\", \"validationEvidenceHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"headerByteLength\", \"directoryEntryByteLength\", \"sectionCount\", \"maximumRunsPerBrick\", \"maximumLocalSamplesPerBrick\", \"maximumEncodedBrickPayloadBytes\", \"coordinateSystem\", \"boundsMetres\", \"artifact\", \"pages\", \"lods\"]),\n voxelTechnicalProfile: objectSchema({\n boundsMetres: ref(\"bounds\"),\n dimensionsMetres: ref(\"dimensions\"),\n geometryMode: { enum: [\"solid\", \"shell\", \"mixed\"] },\n artifactByteLength: { ...integerSchema(PVOX_PAGE_SIZE_BYTES, PVOX_DEFAULT_LIMITS.maximumArtifactBytes), multipleOf: PVOX_PAGE_SIZE_BYTES },\n pageCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPages),\n brickCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumBricks),\n logicalVoxelCapacity: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumLogicalVoxels),\n encodedSurfaceSampleCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples),\n surfacePropertyCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumSurfaceProperties),\n sectionCount: integerSchema(PVOX_MIN_STATIC_SECTION_COUNT, PVOX_MAX_SECTIONS),\n levelSpanRecordCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPartitions * PVOX_DEFAULT_LIMITS.maximumLodCount * (PVOX_DEFAULT_LIMITS.maximumHierarchyDepth + 1)),\n physicalPaletteRecordCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties),\n physicalEvidenceRecordCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries),\n materialRegionCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions),\n interiorLayerRecordCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumInteriorLayers),\n massPropertyRecordCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumMassPropertyRecords),\n bondRecordCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumBondRecords),\n hierarchyDepth: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n hierarchyNodeCount: integerSchema(1, PVOX_MAX_HIERARCHY_NODES),\n lodCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumLodCount),\n collisionHierarchyNodeCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumHierarchyNodes),\n collisionBrickCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumBricks),\n collisionLogicalVoxelCapacity: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumLogicalVoxels),\n collisionEncodedSurfaceSampleCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumEncodedSurfaceSamples),\n cpuResidentByteLength: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumCpuResidentBytes),\n gpuResidentByteLength: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumGpuResidentBytes),\n hasCollision: { type: \"boolean\" },\n partitionCount: integerSchema(1, PVOX_DEFAULT_LIMITS.maximumPartitions),\n maximumPartitionExtentMetres: numberSchema(Number.EPSILON, PVOX_MAX_ABSOLUTE_COORDINATE_METRES * 2),\n maximumPartitionDiagonalMetres: numberSchema(Number.EPSILON, PVOX_MAX_ABSOLUTE_COORDINATE_METRES * Math.sqrt(12)),\n }, [\"boundsMetres\", \"dimensionsMetres\", \"geometryMode\", \"artifactByteLength\", \"pageCount\", \"brickCount\", \"logicalVoxelCapacity\", \"encodedSurfaceSampleCount\", \"surfacePropertyCount\", \"sectionCount\", \"levelSpanRecordCount\", \"physicalPaletteRecordCount\", \"physicalEvidenceRecordCount\", \"materialRegionCount\", \"interiorLayerRecordCount\", \"massPropertyRecordCount\", \"bondRecordCount\", \"hierarchyDepth\", \"hierarchyNodeCount\", \"lodCount\", \"collisionHierarchyNodeCount\", \"collisionBrickCount\", \"collisionLogicalVoxelCapacity\", \"collisionEncodedSurfaceSampleCount\", \"cpuResidentByteLength\", \"gpuResidentByteLength\", \"hasCollision\", \"partitionCount\", \"maximumPartitionExtentMetres\", \"maximumPartitionDiagonalMetres\"]),\n voxelCapabilityAssessment: objectSchema({\n capability: { enum: PVOX_CAPABILITIES },\n status: { enum: [\"supported\", \"unsupported\", \"not-applicable\"] },\n evaluatorId: token,\n evaluatorVersion: immutableVersion,\n subjectContentHash: sha256,\n evidenceHash: sha256,\n reasonCodes,\n evaluatedAt: timestamp,\n }, [\"capability\", \"status\", \"evaluatorId\", \"evaluatorVersion\", \"subjectContentHash\", \"evidenceHash\", \"reasonCodes\", \"evaluatedAt\"], {\n allOf: [\n {\n if: { properties: { status: { const: \"supported\" } }, required: [\"status\"] },\n then: { properties: { reasonCodes: { ...reasonCodes, maxItems: 0 } } },\n else: { properties: { reasonCodes: { ...reasonCodes, minItems: 1 } } },\n },\n ],\n }),\n physicalPropertyEvidence: objectSchema({\n property: { enum: PVOX_PHYSICAL_PROPERTIES },\n value: numberSchema(),\n unit: stringSchema(32),\n provenance: { enum: [\"source\", \"authored\", \"derived\", \"inferred\", \"default\"] },\n confidence: numberSchema(0, 1),\n subjectContentHash: sha256,\n regionId: token,\n materialId: token,\n policyId: { const: PVOX_PHYSICAL_PROPERTY_POLICY_ID },\n policyVersion: { const: PVOX_PHYSICAL_PROPERTY_POLICY_VERSION },\n evidenceHash: sha256,\n reviewedBy: token,\n reviewedAt: timestamp,\n reviewToken: attestation,\n }, [\"property\", \"value\", \"unit\", \"provenance\", \"confidence\", \"subjectContentHash\", \"regionId\", \"materialId\", \"policyId\", \"policyVersion\", \"evidenceHash\"], {\n dependentRequired: {\n reviewedBy: [\"reviewedAt\", \"reviewToken\"],\n reviewedAt: [\"reviewedBy\", \"reviewToken\"],\n reviewToken: [\"reviewedBy\", \"reviewedAt\"],\n },\n allOf: [\n {\n if: { properties: { provenance: { const: \"inferred\" } }, required: [\"provenance\"] },\n then: {\n properties: { reviewedBy: token, reviewedAt: timestamp, reviewToken: attestation },\n required: [\"reviewedBy\", \"reviewedAt\", \"reviewToken\"],\n },\n },\n {\n oneOf: Object.entries(PVOX_PHYSICAL_PROPERTY_POLICIES).map(([property, policy]) => ({\n properties: {\n property: { const: property },\n unit: { const: policy.unit },\n value: numberSchema(policy.minimum, policy.maximum),\n },\n required: [\"property\", \"unit\", \"value\"],\n })),\n },\n ],\n }),\n pvoxFidelityEvidence: objectSchema({\n profileId: { enum: PVOX_FIDELITY_PROFILE_IDS },\n surfaceProfileId: { enum: [\"precision-hero-v1\", \"props-furniture-v1\", \"rocks-organic-shells-v1\", \"buildings-v1\"] },\n profileVersion: { const: PVOX_FIDELITY_PROFILE_VERSION },\n outcome: { enum: [\"passed\", \"blocked\"] },\n canonicalDocumentHash: sha256,\n pvoxBinaryClosureHash: sha256,\n evaluatedDiagonalMetres: numberSchema(Number.EPSILON),\n lod0CellSizeMetres: numberSchema(Number.EPSILON),\n maximumAllowedSurfaceErrorMetres: numberSchema(0),\n maximumSurfaceErrorMetres: numberSchema(0),\n p99AllowedSurfaceErrorMetres: numberSchema(0),\n p99SurfaceErrorMetres: numberSchema(0),\n minimumSilhouetteIou: { const: 0.995 },\n silhouetteIou: numberSchema(0, 1),\n maximumAllowedContourDisplacementPx: { const: 0.5 },\n maximumContourDisplacementPx: numberSchema(0),\n minimumRenderedSsim: { const: 0.98 },\n renderedSsim: numberSchema(0, 1),\n maximumP95DeltaE2000: { const: 3 },\n p95DeltaE2000: numberSchema(0, 100),\n maximumNormalizedMaterialError: { const: 1 / 255 },\n normalizedMaterialError: numberSchema(0, 1),\n evidenceHash: sha256,\n evaluatedAt: timestamp,\n decisionToken: attestation,\n }, [\"profileId\", \"surfaceProfileId\", \"profileVersion\", \"outcome\", \"canonicalDocumentHash\", \"pvoxBinaryClosureHash\", \"evaluatedDiagonalMetres\", \"lod0CellSizeMetres\", \"maximumAllowedSurfaceErrorMetres\", \"maximumSurfaceErrorMetres\", \"p99AllowedSurfaceErrorMetres\", \"p99SurfaceErrorMetres\", \"minimumSilhouetteIou\", \"silhouetteIou\", \"maximumAllowedContourDisplacementPx\", \"maximumContourDisplacementPx\", \"minimumRenderedSsim\", \"renderedSsim\", \"maximumP95DeltaE2000\", \"p95DeltaE2000\", \"maximumNormalizedMaterialError\", \"normalizedMaterialError\", \"evidenceHash\", \"evaluatedAt\", \"decisionToken\"]),\n pvoxBrickPatch: objectSchema({\n fieldKind: { enum: [\"render-field\", \"collision-field\"] },\n lodLevel: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumLodCount - 1),\n partitionIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPartitions - 1),\n hierarchyDepth: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumHierarchyDepth),\n mortonCode: { type: \"string\", pattern: \"^[a-f0-9]{16}$\" },\n expectedPageIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPages - 1),\n expectedPageHash: sha256,\n operation: { enum: [\"insert\", \"replace\", \"remove\"] },\n expectedBrickHash: sha256,\n resultingBrickHash: sha256,\n resultingPageHash: sha256,\n }, [\"fieldKind\", \"lodLevel\", \"partitionIndex\", \"hierarchyDepth\", \"mortonCode\", \"expectedPageIndex\", \"expectedPageHash\", \"operation\", \"expectedBrickHash\", \"resultingBrickHash\", \"resultingPageHash\"]),\n pvoxEditJournal: objectSchema({\n journalVersion: { const: PVOX_EDIT_JOURNAL_VERSION },\n baseContentHash: sha256,\n basePageSetHash: sha256,\n placementId: token,\n gridVersion: token,\n operationId: token,\n expectedRevision: integerSchema(0),\n resultingRevision: integerSchema(1),\n previousJournalHash: sha256,\n expectedRootHash: sha256,\n resultingRootHash: sha256,\n resultingRootHashAttestation: ref(\"pvoxEditOverlayRootHashAttestation\"),\n patches: arraySchema(ref(\"pvoxBrickPatch\"), 1, PVOX_MAX_EDIT_PATCHES),\n dirtyBoundsMetres: ref(\"bounds\"),\n massDeltaKg: numberSchema(),\n journalHash: sha256,\n journalHashAttestation: ref(\"pvoxEditJournalHashAttestation\"),\n recordedAt: timestamp,\n }, [\"journalVersion\", \"baseContentHash\", \"basePageSetHash\", \"placementId\", \"gridVersion\", \"operationId\", \"expectedRevision\", \"resultingRevision\", \"previousJournalHash\", \"expectedRootHash\", \"resultingRootHash\", \"resultingRootHashAttestation\", \"patches\", \"dirtyBoundsMetres\", \"massDeltaKg\", \"journalHash\", \"journalHashAttestation\", \"recordedAt\"]),\n pvoxGateEvidence: objectSchema({\n kind: { enum: PVOX_NON_OVERRIDABLE_GATE_KINDS },\n outcome: { enum: [\"passed\", \"blocked\"] },\n validatorId: token,\n validatorVersion: immutableVersion,\n subjectContentHash: sha256,\n evidenceHash: sha256,\n reasonCodes,\n evaluatedAt: timestamp,\n attestationToken: attestation,\n }, [\"kind\", \"outcome\", \"validatorId\", \"validatorVersion\", \"subjectContentHash\", \"evidenceHash\", \"reasonCodes\", \"evaluatedAt\", \"attestationToken\"]),\n compilerEvidence: objectSchema({\n compilerId: token,\n compilerVersion: immutableVersion,\n sourceFormat: token,\n sourceContentHash: sha256,\n canonicalDocumentHash: sha256,\n compilationInputHash: sha256,\n runtimeRequestProfileHash: sha256,\n outputContentHash: sha256,\n evidenceHash: sha256,\n compiledAt: timestamp,\n }, [\"compilerId\", \"compilerVersion\", \"sourceFormat\", \"sourceContentHash\", \"canonicalDocumentHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"outputContentHash\", \"evidenceHash\", \"compiledAt\"]),\n physicalRegionInventoryEntry: objectSchema({\n regionIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumMaterialRegions - 1),\n physicalPaletteIndex: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumPhysicalProperties - 1),\n regionId: token,\n materialId: token,\n }, [\"regionIndex\", \"physicalPaletteIndex\", \"regionId\", \"materialId\"]),\n physicalRegionInventory: objectSchema({\n inventoryVersion: { const: PVOX_PHYSICAL_REGION_INVENTORY_VERSION },\n subjectContentHash: sha256,\n inventoryHash: sha256,\n inventoryHashAttestation: ref(\"pvoxPhysicalInventoryHashAttestation\"),\n validationEvidenceHash: sha256,\n entries: arraySchema(ref(\"physicalRegionInventoryEntry\"), 1, PVOX_DEFAULT_LIMITS.maximumMaterialRegions),\n }, [\"inventoryVersion\", \"subjectContentHash\", \"inventoryHash\", \"inventoryHashAttestation\", \"validationEvidenceHash\", \"entries\"]),\n reviewedStructuralEvidence: objectSchema({\n kind: { enum: [\"mass-properties\", \"bond-graph\", \"interior-layers\"] },\n subjectContentHash: sha256,\n physicalInventoryHash: sha256,\n recordCount: integerSchema(0, PVOX_DEFAULT_LIMITS.maximumBondRecords),\n evidenceHash: sha256,\n reviewerId: token,\n reviewedAt: timestamp,\n reviewToken: attestation,\n }, [\"kind\", \"subjectContentHash\", \"physicalInventoryHash\", \"recordCount\", \"evidenceHash\", \"reviewerId\", \"reviewedAt\", \"reviewToken\"]),\n transform: objectSchema({ translationMetres: vector3, rotationQuaternion: quaternion, scale: positiveVector3 }, [\"translationMetres\", \"rotationQuaternion\", \"scale\"]),\n modelAssetRef: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_CONTRACT_VERSION },\n assetId: { type: \"string\", pattern: \"^[a-z0-9]+(?:-[a-z0-9]+)*$\" },\n version: immutableVersion,\n kind: { enum: MODEL_ASSET_KINDS },\n contentHash: sha256,\n runtimeManifestUri: { type: \"string\", pattern: \"^mcp://models/catalog/[a-z0-9]+(?:-[a-z0-9]+)*/versions/[A-Za-z0-9][A-Za-z0-9._-]*/manifest$\" },\n }, [\"contractVersion\", \"assetId\", \"version\", \"kind\", \"contentHash\", \"runtimeManifestUri\"]),\n existingAssemblyChildRef: objectSchema({\n disposition: { const: \"existing\" },\n representation: { const: \"pvox\" },\n asset: ref(\"modelAssetRef\"),\n processingManifestId: token,\n binaryClosureHash: sha256,\n processingClosureHash: sha256,\n processingManifestUri: { type: \"string\", pattern: \"^mcp://models/catalog/.+/processing-manifest$\" },\n }, [\"disposition\", \"representation\", \"asset\", \"processingManifestId\", \"binaryClosureHash\", \"processingClosureHash\", \"processingManifestUri\"]),\n stagedAssemblyChildRef: objectSchema({\n disposition: { const: \"staged-derived\" },\n representation: { const: \"pvox\" },\n derivedId: pathSegment,\n kind: { const: \"leaf\" },\n contentHash: sha256,\n binaryClosureHash: sha256,\n processingClosureHash: sha256,\n processingManifestId: token,\n processingManifestUri: { type: \"string\", pattern: \"^mcp://models/resolutions/.+/processing-manifest$\" },\n }, [\"disposition\", \"representation\", \"derivedId\", \"kind\", \"contentHash\", \"binaryClosureHash\", \"processingClosureHash\", \"processingManifestId\", \"processingManifestUri\"]),\n assemblyChild: objectSchema({\n instanceId: token,\n parentInstanceId: token,\n assetRef: { oneOf: [ref(\"existingAssemblyChildRef\"), ref(\"stagedAssemblyChildRef\")] },\n transform: ref(\"transform\"),\n }, [\"instanceId\", \"assetRef\", \"transform\"]),\n modelProcessingManifest: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n representation: { const: \"pvox\" },\n manifestId: token,\n resolutionId: pathSegment,\n candidateId: pathSegment,\n kind: { enum: MODEL_ASSET_KINDS },\n requestProfileId: token,\n requestSemanticProfileHash: sha256,\n capabilityProfileId: { enum: PVOX_RUNTIME_CAPABILITY_PROFILE_IDS },\n contentHash: sha256,\n binaryClosureHash: sha256,\n processingClosureHash: sha256,\n processingClosureAttestation: ref(\"pvoxProcessingClosureHashAttestation\"),\n assemblyClosureHash: sha256,\n assemblyClosureAttestation: ref(\"pvoxAssemblyClosureHashAttestation\"),\n compilationInputHash: sha256,\n runtimeRequestProfileHash: sha256,\n coordinateSystem: ref(\"coordinateSystem\"),\n pvox: ref(\"pvoxAssetManifest\"),\n technicalProfile: ref(\"voxelTechnicalProfile\"),\n requiredCapabilities: { ...arraySchema({ enum: PVOX_CAPABILITIES }, 1, PVOX_CAPABILITIES.length), uniqueItems: true },\n capabilities: { ...arraySchema(ref(\"voxelCapabilityAssessment\"), PVOX_CAPABILITIES.length, PVOX_CAPABILITIES.length), uniqueItems: true },\n capabilityEvidenceSetHash: sha256,\n capabilityEvidenceSetAttestation: ref(\"pvoxCapabilitySetHashAttestation\"),\n physicalRegionInventory: ref(\"physicalRegionInventory\"),\n physicalProperties: arraySchema(ref(\"physicalPropertyEvidence\"), 0, PVOX_DEFAULT_LIMITS.maximumPhysicalEvidenceEntries),\n physicalEvidenceHash: sha256,\n physicalEvidenceAttestation: ref(\"pvoxPhysicalEvidenceHashAttestation\"),\n massPropertiesEvidence: ref(\"reviewedStructuralEvidence\"),\n bondGraphEvidence: ref(\"reviewedStructuralEvidence\"),\n interiorLayerEvidence: ref(\"reviewedStructuralEvidence\"),\n converter: ref(\"compilerEvidence\"),\n fidelity: ref(\"pvoxFidelityEvidence\"),\n children: arraySchema(ref(\"assemblyChild\"), 0, PVOX_DEFAULT_LIMITS.maximumAssemblyChildren),\n processedAt: timestamp,\n }, [\"contractVersion\", \"representation\", \"manifestId\", \"resolutionId\", \"candidateId\", \"kind\", \"requestProfileId\", \"requestSemanticProfileHash\", \"capabilityProfileId\", \"contentHash\", \"binaryClosureHash\", \"processingClosureHash\", \"processingClosureAttestation\", \"assemblyClosureHash\", \"assemblyClosureAttestation\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"coordinateSystem\", \"pvox\", \"technicalProfile\", \"requiredCapabilities\", \"capabilities\", \"capabilityEvidenceSetHash\", \"capabilityEvidenceSetAttestation\", \"physicalRegionInventory\", \"physicalProperties\", \"physicalEvidenceHash\", \"physicalEvidenceAttestation\", \"massPropertiesEvidence\", \"bondGraphEvidence\", \"interiorLayerEvidence\", \"converter\", \"fidelity\", \"children\", \"processedAt\"]),\n hardConstraintsV1: objectSchema({\n boundsMetres: ref(\"bounds\"),\n dimensionsMetres: ref(\"dimensions\"),\n maxTriangles: integerSchema(1, STATIC_WORLD_V1_MODEL_POLICY.maxTriangles),\n maxBytes: integerSchema(1, STATIC_WORLD_V1_MODEL_POLICY.maxBytes),\n maxTextureBytes: integerSchema(1, STATIC_WORLD_V1_MODEL_POLICY.maxTextureBytes),\n maxTextureDimensionPx: integerSchema(1, STATIC_WORLD_V1_MODEL_POLICY.maxTextureDimensionPx),\n maxPartitionCellMetres: numberSchema(Number.EPSILON, STATIC_WORLD_V1_MODEL_POLICY.maxPartitionCellMetres),\n lod: { enum: [\"required\", \"optional\", \"forbidden\"] },\n collision: { enum: [\"required\", \"optional\", \"forbidden\"] },\n partition: { enum: [\"single\", \"allowed\", \"required\"] },\n }, [\"maxTriangles\", \"maxBytes\", \"maxTextureBytes\", \"maxTextureDimensionPx\", \"maxPartitionCellMetres\", \"lod\", \"collision\", \"partition\"]),\n modelRequestSpecV1: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_CONTRACT_VERSION },\n policyProfileId: { const: STATIC_WORLD_V1_MODEL_POLICY.id },\n query: stringSchema(1_000),\n revision: integerSchema(0, MODEL_REQUEST_MAX_REVISION),\n locale: stringSchema(64),\n rankerId: token,\n hardConstraints: ref(\"hardConstraintsV1\"),\n softPreferences: ref(\"softPreferences\"),\n exclusions: arraySchema(stringSchema(256), 0, 32),\n }, [\"contractVersion\", \"policyProfileId\", \"query\", \"revision\", \"hardConstraints\", \"softPreferences\", \"exclusions\"]),\n rankerRef: objectSchema({\n id: token,\n version: immutableVersion,\n calibrationId: token,\n calibrationVersion: immutableVersion,\n evidenceMode: { enum: MODEL_RANKER_EVIDENCE_MODES },\n assuranceCeiling: { enum: MODEL_MATCH_ASSURANCE_BANDS },\n }, [\"id\", \"version\", \"calibrationId\", \"calibrationVersion\", \"evidenceMode\", \"assuranceCeiling\"]),\n modelMatchAssessment: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_CONTRACT_VERSION },\n score: numberSchema(0, 1),\n assurance: { enum: MODEL_MATCH_ASSURANCE_BANDS },\n hardConstraintPass: { type: \"boolean\" },\n exactMatch: { type: \"boolean\" },\n reasonCodes: releasedV1ReasonCodes,\n ranker: ref(\"rankerRef\"),\n fidelityWarnings: arraySchema(stringSchema(256), 0, 32),\n request: ref(\"modelRequestSpecV1\"),\n candidateId: pathSegment,\n candidateContentHash: sha256,\n requestSemanticProfileHash: sha256,\n requestSemanticProfileCanonical: stringSchema(65_536),\n evidenceHash: sha256,\n }, [\"contractVersion\", \"score\", \"assurance\", \"hardConstraintPass\", \"exactMatch\", \"reasonCodes\", \"ranker\", \"fidelityWarnings\", \"request\", \"candidateId\", \"candidateContentHash\", \"requestSemanticProfileHash\", \"requestSemanticProfileCanonical\", \"evidenceHash\"]),\n provenance: objectSchema({\n kind: { enum: MODEL_PROVENANCE_KINDS },\n sourceId: token,\n sourceAssetId: opaqueSourceAssetId,\n sourcePageUri: { type: \"string\", pattern: \"^https://\", maxLength: 2_048 },\n contentHash: sha256,\n capturedAt: timestamp,\n }, [\"kind\", \"sourceId\", \"sourceAssetId\", \"contentHash\", \"capturedAt\"]),\n attribution: objectSchema({\n title: stringSchema(256),\n creator: stringSchema(256),\n notice: stringSchema(512),\n sourcePageUri: { type: \"string\", pattern: \"^https://\", maxLength: 2_048 },\n }, [\"title\", \"creator\", \"notice\"]),\n rights: objectSchema({\n decisionId: token,\n decisionToken: attestation,\n policyId: token,\n policyVersion: immutableVersion,\n sourceId: token,\n sourceAssetId: opaqueSourceAssetId,\n sourceContentHash: sha256,\n status: { enum: MODEL_RIGHTS_STATUSES },\n licenseId: token,\n evidencePageUri: { type: \"string\", pattern: \"^https://\", maxLength: 2_048 },\n attribution: ref(\"attribution\"),\n reviewedAt: timestamp,\n }, [\"decisionId\", \"decisionToken\", \"policyId\", \"policyVersion\", \"sourceId\", \"sourceAssetId\", \"sourceContentHash\", \"status\", \"licenseId\", \"evidencePageUri\", \"reviewedAt\"]),\n existingCandidateAssetRef: objectSchema({ disposition: { const: \"existing\" }, kind: { enum: MODEL_ASSET_KINDS }, contentHash: sha256, asset: ref(\"modelAssetRef\") }, [\"disposition\", \"kind\", \"contentHash\", \"asset\"]),\n proposedCandidateAssetRef: objectSchema({ disposition: { const: \"proposed\" }, proposalId: token, kind: { enum: MODEL_ASSET_KINDS }, contentHash: sha256 }, [\"disposition\", \"proposalId\", \"kind\", \"contentHash\"]),\n confirmationView: objectSchema({\n kind: { enum: MODEL_CONFIRMATION_VIEW_KINDS },\n imageUri: { type: \"string\", pattern: \"^mcp://models/resolutions/.+\\\\.png$\", maxLength: 512 },\n sha256,\n contentType: { const: \"image/png\" },\n width: { const: MODEL_CONFIRMATION_VIEW_SIZE_PX },\n height: { const: MODEL_CONFIRMATION_VIEW_SIZE_PX },\n }, [\"kind\", \"imageUri\", \"sha256\", \"contentType\", \"width\", \"height\"]),\n renderEvidence: objectSchema({\n renderId: token,\n representation: { const: \"pvox\" },\n lodLevel: { const: 0 },\n traversalBackend: { const: \"native-pvox\" },\n rendererId: { const: PVOX_NATIVE_RENDERER_ID },\n rendererVersion: immutableVersion,\n rendererQualificationHash: sha256,\n settingsId: { const: PVOX_NATIVE_REVIEW_SETTINGS_ID },\n settingsVersion: immutableVersion,\n cameraQualificationHash: sha256,\n processingManifestId: token,\n processingClosureHash: sha256,\n pvoxContentHash: sha256,\n pvoxRootHash: sha256,\n pvoxDirectoryHash: sha256,\n pvoxPageSetHash: sha256,\n viewSha256s: shaTuple,\n renderedAt: timestamp,\n evidenceHash: sha256,\n evidenceHashAttestation: ref(\"pvoxRenderEvidenceHashAttestation\"),\n }, [\"renderId\", \"representation\", \"lodLevel\", \"traversalBackend\", \"rendererId\", \"rendererVersion\", \"rendererQualificationHash\", \"settingsId\", \"settingsVersion\", \"cameraQualificationHash\", \"processingManifestId\", \"processingClosureHash\", \"pvoxContentHash\", \"pvoxRootHash\", \"pvoxDirectoryHash\", \"pvoxPageSetHash\", \"viewSha256s\", \"renderedAt\", \"evidenceHash\", \"evidenceHashAttestation\"]),\n confirmationBinding: objectSchema({\n bindingHash: sha256,\n bindingHashAttestation: ref(\"pvoxConfirmationBindingHashAttestation\"),\n resolutionId: pathSegment,\n requesterId: token,\n request: ref(\"modelRequestSpecV2\"),\n requestSemanticProfileHash: sha256,\n requestRevision: integerSchema(0, MODEL_REQUEST_MAX_REVISION),\n candidateId: pathSegment,\n candidateContentHash: sha256,\n candidateAssetRef: { oneOf: [ref(\"existingCandidateAssetRef\"), ref(\"proposedCandidateAssetRef\")] },\n match: ref(\"modelMatchAssessment\"),\n provenance: ref(\"provenance\"),\n rights: ref(\"rights\"),\n sourceContentHash: sha256,\n binaryClosureHash: sha256,\n pvoxRootHash: sha256,\n pvoxDirectoryHash: sha256,\n pvoxPageSetHash: sha256,\n compilationInputHash: sha256,\n runtimeRequestProfileHash: sha256,\n processingClosureHash: sha256,\n assemblyClosureHash: sha256,\n evaluationClosureHash: sha256,\n capabilityEvidenceSetHash: sha256,\n hardGates: { ...arraySchema(ref(\"pvoxGateEvidence\"), PVOX_NON_OVERRIDABLE_GATE_KINDS.length, PVOX_NON_OVERRIDABLE_GATE_KINDS.length), uniqueItems: true },\n viewSha256s: shaTuple,\n rightsDecisionId: token,\n fidelityEvidenceHash: sha256,\n physicalEvidenceHash: sha256,\n rendererId: { const: PVOX_NATIVE_RENDERER_ID },\n rendererVersion: immutableVersion,\n rendererEvidenceHash: sha256,\n renderEvidence: ref(\"renderEvidence\"),\n }, [\"bindingHash\", \"bindingHashAttestation\", \"resolutionId\", \"requesterId\", \"request\", \"requestSemanticProfileHash\", \"requestRevision\", \"candidateId\", \"candidateContentHash\", \"candidateAssetRef\", \"match\", \"provenance\", \"rights\", \"sourceContentHash\", \"binaryClosureHash\", \"pvoxRootHash\", \"pvoxDirectoryHash\", \"pvoxPageSetHash\", \"compilationInputHash\", \"runtimeRequestProfileHash\", \"processingClosureHash\", \"assemblyClosureHash\", \"evaluationClosureHash\", \"capabilityEvidenceSetHash\", \"hardGates\", \"viewSha256s\", \"rightsDecisionId\", \"fidelityEvidenceHash\", \"physicalEvidenceHash\", \"rendererId\", \"rendererVersion\", \"rendererEvidenceHash\", \"renderEvidence\"]),\n modelCandidate: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n resolutionId: pathSegment,\n requesterId: token,\n candidateId: pathSegment,\n request: ref(\"modelRequestSpecV2\"),\n admissionStatus: { enum: [\"confirmable\", \"diagnostic\"] },\n assetRef: { oneOf: [ref(\"existingCandidateAssetRef\"), ref(\"proposedCandidateAssetRef\")] },\n match: ref(\"modelMatchAssessment\"),\n provenance: ref(\"provenance\"),\n rights: ref(\"rights\"),\n processingManifest: ref(\"modelProcessingManifest\"),\n views: arraySchema(ref(\"confirmationView\"), 4, 4),\n renderEvidence: ref(\"renderEvidence\"),\n evaluationClosureHash: sha256,\n evaluationClosureAttestation: ref(\"pvoxEvaluationClosureHashAttestation\"),\n hardGates: { ...arraySchema(ref(\"pvoxGateEvidence\"), PVOX_NON_OVERRIDABLE_GATE_KINDS.length, PVOX_NON_OVERRIDABLE_GATE_KINDS.length), uniqueItems: true },\n confirmationBinding: ref(\"confirmationBinding\"),\n confirmationToken: attestation,\n blockingReasonCodes: arraySchema(reasonCode, 1, 256),\n confirmationRequired: { type: \"boolean\" },\n }, [\"contractVersion\", \"resolutionId\", \"requesterId\", \"candidateId\", \"request\", \"admissionStatus\", \"assetRef\", \"match\", \"provenance\", \"rights\", \"processingManifest\", \"views\", \"renderEvidence\", \"evaluationClosureHash\", \"evaluationClosureAttestation\", \"hardGates\", \"confirmationRequired\"], {\n oneOf: [\n {\n properties: {\n admissionStatus: { const: \"confirmable\" },\n confirmationRequired: { const: true },\n confirmationBinding: ref(\"confirmationBinding\"),\n confirmationToken: attestation,\n blockingReasonCodes: arraySchema(reasonCode, 1, 256),\n },\n required: [\"admissionStatus\", \"confirmationRequired\", \"confirmationBinding\", \"confirmationToken\"],\n not: { required: [\"blockingReasonCodes\"], properties: { blockingReasonCodes: {} } },\n },\n {\n properties: {\n admissionStatus: { const: \"diagnostic\" },\n confirmationRequired: { const: false },\n blockingReasonCodes: arraySchema(reasonCode, 1, 256),\n confirmationBinding: ref(\"confirmationBinding\"),\n confirmationToken: attestation,\n },\n required: [\"admissionStatus\", \"confirmationRequired\", \"blockingReasonCodes\"],\n not: {\n anyOf: [\n { required: [\"confirmationBinding\"], properties: { confirmationBinding: {} } },\n { required: [\"confirmationToken\"], properties: { confirmationToken: {} } },\n ],\n },\n },\n ],\n }),\n modelCandidateConfirmation: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n confirmationId: token,\n resolutionId: pathSegment,\n requesterId: token,\n candidateId: pathSegment,\n confirmationToken: attestation,\n confirmationBindingHash: sha256,\n viewSha256s: shaTuple,\n confirmedBy: stringSchema(256),\n confirmedAt: timestamp,\n semanticRiskAccepted: { type: \"boolean\" },\n }, [\"contractVersion\", \"confirmationId\", \"resolutionId\", \"requesterId\", \"candidateId\", \"confirmationToken\", \"confirmationBindingHash\", \"viewSha256s\", \"confirmedBy\", \"confirmedAt\", \"semanticRiskAccepted\"]),\n modelPromotionReceipt: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n promotionId: token,\n resolutionId: pathSegment,\n requesterId: token,\n candidateId: pathSegment,\n proposalId: token,\n candidateAssetRef: ref(\"proposedCandidateAssetRef\"),\n confirmationId: token,\n confirmationBindingHash: sha256,\n processingManifestId: token,\n processingContentHash: sha256,\n processingClosureHash: sha256,\n assemblyClosureHash: sha256,\n assemblyChildClosureHashes: arraySchema(sha256, 0, PVOX_DEFAULT_LIMITS.maximumAssemblyChildren),\n finalAssetRef: ref(\"modelAssetRef\"),\n creditsRecordHash: sha256,\n catalogRowHash: sha256,\n indexSnapshotHash: sha256,\n catalogPointerEtag: token,\n indexPointerEtag: token,\n publicationState: { const: \"pointer-last-complete\" },\n creditsWrittenAt: timestamp,\n catalogRowWrittenAt: timestamp,\n indexSnapshotWrittenAt: timestamp,\n pointerPublishedAt: timestamp,\n publicationHash: sha256,\n publicationHashAttestation: ref(\"pvoxPublicationHashAttestation\"),\n promotedAt: timestamp,\n publicationToken: attestation,\n }, [\"contractVersion\", \"promotionId\", \"resolutionId\", \"requesterId\", \"candidateId\", \"proposalId\", \"candidateAssetRef\", \"confirmationId\", \"confirmationBindingHash\", \"processingManifestId\", \"processingContentHash\", \"processingClosureHash\", \"assemblyClosureHash\", \"assemblyChildClosureHashes\", \"finalAssetRef\", \"creditsRecordHash\", \"catalogRowHash\", \"indexSnapshotHash\", \"catalogPointerEtag\", \"indexPointerEtag\", \"publicationState\", \"creditsWrittenAt\", \"catalogRowWrittenAt\", \"indexSnapshotWrittenAt\", \"pointerPublishedAt\", \"publicationHash\", \"publicationHashAttestation\", \"promotedAt\", \"publicationToken\"]),\n modelRefinementQuestion: objectSchema({ questionId: token, prompt: stringSchema(500), reasonCodes }, [\"questionId\", \"prompt\", \"reasonCodes\"]),\n modelResolution: objectSchema({\n contractVersion: { const: MODEL_RESOLUTION_V2_CONTRACT_VERSION },\n resolutionId: pathSegment,\n requesterId: token,\n request: ref(\"modelRequestSpecV2\"),\n attempts: integerSchema(1, 12),\n state: { enum: MODEL_RESOLUTION_V2_STATES },\n compatibilityState: { enum: MODEL_RESOLUTION_STATES },\n candidates: arraySchema(ref(\"modelCandidate\"), 0, 20),\n bestCandidate: ref(\"modelCandidate\"),\n confirmation: ref(\"modelCandidateConfirmation\"),\n promotionReceipt: ref(\"modelPromotionReceipt\"),\n refinementQuestions: arraySchema(ref(\"modelRefinementQuestion\"), 0, 3),\n finalAssetRef: ref(\"modelAssetRef\"),\n stateReasonCode: reasonCode,\n createdAt: timestamp,\n updatedAt: timestamp,\n }, [\"contractVersion\", \"resolutionId\", \"requesterId\", \"request\", \"attempts\", \"state\", \"compatibilityState\", \"candidates\", \"refinementQuestions\", \"createdAt\", \"updatedAt\"], {\n allOf: [\n {\n if: { properties: { state: { const: \"awaiting-confirmation\" } }, required: [\"state\"] },\n then: {\n properties: {\n bestCandidate: {\n type: \"object\",\n properties: { admissionStatus: { const: \"confirmable\" } },\n required: [\"admissionStatus\"],\n },\n },\n required: [\"bestCandidate\"],\n },\n },\n {\n if: {\n properties: {\n state: { const: \"awaiting-confirmation\" },\n bestCandidate: {\n type: \"object\",\n properties: {\n match: {\n type: \"object\",\n properties: { assurance: { const: \"low\" } },\n required: [\"assurance\"],\n },\n },\n required: [\"match\"],\n },\n },\n required: [\"state\", \"bestCandidate\"],\n },\n then: {\n properties: { refinementQuestions: arraySchema(ref(\"modelRefinementQuestion\"), 1, 3) },\n required: [\"refinementQuestions\"],\n },\n },\n {\n if: { properties: { state: { enum: [\"promoting\", \"completed\"] } }, required: [\"state\"] },\n then: {\n properties: {\n bestCandidate: {\n type: \"object\",\n properties: { admissionStatus: { const: \"confirmable\" } },\n required: [\"admissionStatus\"],\n },\n confirmation: ref(\"modelCandidateConfirmation\"),\n },\n required: [\"bestCandidate\", \"confirmation\"],\n },\n else: {\n not: {\n properties: { confirmation: {} },\n required: [\"confirmation\"],\n },\n },\n },\n {\n if: { properties: { state: { const: \"completed\" } }, required: [\"state\"] },\n then: {\n properties: { finalAssetRef: ref(\"modelAssetRef\") },\n required: [\"finalAssetRef\"],\n },\n else: {\n not: {\n properties: { finalAssetRef: {} },\n required: [\"finalAssetRef\"],\n },\n },\n },\n {\n if: {\n properties: {\n state: { const: \"completed\" },\n bestCandidate: {\n type: \"object\",\n properties: {\n assetRef: {\n type: \"object\",\n properties: { disposition: { const: \"proposed\" } },\n required: [\"disposition\"],\n },\n },\n required: [\"assetRef\"],\n },\n },\n required: [\"state\", \"bestCandidate\"],\n },\n then: {\n properties: { promotionReceipt: ref(\"modelPromotionReceipt\") },\n required: [\"promotionReceipt\"],\n },\n else: {\n not: {\n properties: { promotionReceipt: {} },\n required: [\"promotionReceipt\"],\n },\n },\n },\n {\n if: {\n properties: { state: { enum: [\"unresolved\", \"failed\", \"cancelled\"] } },\n required: [\"state\"],\n },\n then: {\n properties: { stateReasonCode: reasonCode },\n required: [\"stateReasonCode\"],\n },\n else: {\n not: {\n properties: { stateReasonCode: {} },\n required: [\"stateReasonCode\"],\n },\n },\n },\n ],\n }),\n};\n\nconst frozenDefinitions = deepFreeze(definitions);\n\nfunction standaloneSchema(definitionName: string, title: string): PvoxModelResolutionJsonSchema {\n const definition = frozenDefinitions[definitionName];\n if (definition === undefined || definition.type !== \"object\" || definition.additionalProperties !== false) {\n throw new Error(\"PVOX standalone schema requires a closed object definition.\");\n }\n return deepFreeze({\n $id: `https://schemas.plasius.com/asset-contracts/model-resolution/${MODEL_RESOLUTION_V2_CONTRACT_VERSION}/${definitionName}.schema.json`,\n $schema: \"https://json-schema.org/draft/2020-12/schema\" as const,\n title,\n ...definition,\n type: \"object\" as const,\n additionalProperties: false as const,\n $defs: frozenDefinitions,\n });\n}\n\n/** Complete closed JSON Schema 2020-12 descriptors for MCP/admin consumers. */\nexport const MODEL_RESOLUTION_V2_JSON_SCHEMAS = deepFreeze({\n modelRequestSpec: standaloneSchema(\"modelRequestSpecV2\", \"ModelRequestSpecV2\"),\n pvoxAssetManifest: standaloneSchema(\"pvoxAssetManifest\", \"PvoxAssetManifestV1\"),\n voxelTechnicalProfile: standaloneSchema(\"voxelTechnicalProfile\", \"VoxelTechnicalProfile\"),\n voxelCapabilityAssessment: standaloneSchema(\"voxelCapabilityAssessment\", \"VoxelCapabilityAssessment\"),\n physicalPropertyEvidence: standaloneSchema(\"physicalPropertyEvidence\", \"PhysicalPropertyEvidence\"),\n pvoxEditJournal: standaloneSchema(\"pvoxEditJournal\", \"PvoxEditJournal\"),\n pvoxFidelityEvidence: standaloneSchema(\"pvoxFidelityEvidence\", \"PvoxFidelityEvidence\"),\n pvoxGateEvidence: standaloneSchema(\"pvoxGateEvidence\", \"PvoxGateEvidence\"),\n modelProcessingManifest: standaloneSchema(\"modelProcessingManifest\", \"ModelProcessingManifestV2\"),\n modelCandidate: standaloneSchema(\"modelCandidate\", \"ModelCandidateV2\"),\n modelCandidateConfirmation: standaloneSchema(\"modelCandidateConfirmation\", \"ModelCandidateConfirmationV2\"),\n modelPromotionReceipt: standaloneSchema(\"modelPromotionReceipt\", \"ModelPromotionReceiptV2\"),\n modelRefinementQuestion: standaloneSchema(\"modelRefinementQuestion\", \"ModelRefinementQuestionV2\"),\n modelResolution: standaloneSchema(\"modelResolution\", \"ModelResolutionV2\"),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,MAAI,UAAU,KAAK,CAAC,QAAQ,UAAU,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,SAAS,EAAE,SAAS,UAAU,QAAQ;AAC/F,UAAM,IAAI,MAAM,GAAG,SAAS,kEAAkE;AAAA,EAChG;AACA,MAAI,OAAO,SAAS,OAAO;AACzB,UAAM,IAAI,MAAM,GAAG,SAAS,wCAAwC;AAAA,EACtE;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAgB,WAA2B;AAC9D,MAAI,OAAO,UAAU,YAAY,CAACC,eAAc,KAAK,KAAK,GAAG;AAC3D,UAAM,IAAI,MAAM,GAAG,SAAS,kDAAkD;AAAA,EAChF;AACA,SAAO;AACT;AAEA,SAAS,qBAAqB,OAAgB,WAA2B;AACvE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,GAAG;AAC1D,UAAM,IAAI,MAAM,GAAG,SAAS,8BAA8B;AAAA,EAC5D;AACA,SAAO;AACT;","names":["import_gpu_shader","token","timestamp","reasonCodes","reasonCode","terminal","import_gpu_shader","deepFreeze","createBounds","createDimensions","assertCoordinateSystem","sha256","reasonCodes","createTransform","createAssemblyChild","createCandidateAssetRef","createRenderEvidence","output","deepFreeze","opaqueSourceAssetId","ASSET_ID_PATTERN","SHA256_PATTERN","TOKEN_PATTERN","assertRecord","attestation","ref","module"]}
|