@ai-matrx/alchemy 0.5.1 → 0.6.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/declare.ts","../src/declare/keys.ts","../src/declare/hash.ts","../src/declare/validate.ts","../src/declare/registry.ts"],"sourcesContent":["/**\n * `@ai-matrx/alchemy/declare` — what a screen holds (Matrx Alchemy CONTRACT §2.1).\n * Framework-neutral: zero React, zero `@ai-matrx/agents`. Agent fields are\n * extension slots registered by their owner.\n */\nexport type {\n ApplyPolicy,\n Classification,\n ConfigNamespaceDeclaration,\n DeclarationExtension,\n DeclarationIssue,\n DeclaredValue,\n EvidenceSourceDeclaration,\n ExecutionMode,\n ExtensionRow,\n ItemType,\n Json,\n LiveSlot,\n LiveValues,\n OnDemandSection,\n QualifiedValueKey,\n Readiness,\n RecentRequest,\n ResolvedItem,\n ResolvedSurfaceDeclaration,\n ResolvedValue,\n Sensitivity,\n StreamOp,\n SurfaceDeclaration,\n ValidationContext,\n ValueGroup,\n ValueProvenance,\n ValueType,\n WriteMode,\n WriteTarget,\n} from \"./declare/types\";\nexport {\n DECLARATION_NAME_RE,\n QUALIFIED_VALUE_KEY_RE,\n SURFACE_NAME_RE,\n parseQualifiedValueKey,\n qualifyValueKey,\n surfaceClientOf,\n type ParsedValueKey,\n} from \"./declare/keys\";\nexport { canonicalJson, declarationHash, sha256Hex } from \"./declare/hash\";\nexport {\n BASELINE_GROUP_ORDER,\n DEFAULT_MAX_INHERITANCE_DEPTH,\n DEFAULT_SENSITIVITY,\n GENERAL_GROUP_ORDER,\n INHERITED_GROUP_ORDER_BASE,\n RESERVED_GROUP_KEYS,\n createDeclarationRegistry,\n resolveSensitivity,\n type DeclarationRegistry,\n type DeclarationRegistryOptions,\n type Resolved,\n} from \"./declare/registry\";\nexport {\n APPLY_POLICIES,\n CLASSIFICATIONS,\n EXECUTION_MODES,\n LIVE_SLOTS,\n READINESS,\n STREAM_OPS,\n VALUE_TYPES,\n WRITE_MODES,\n findOrphanRows,\n validateDeclarations,\n validateLoadedValues,\n type ValidateOptions,\n} from \"./declare/validate\";\n","import type { QualifiedValueKey } from \"./types\";\n\n/** Every value, write-target, item-type and group name (the DB CHECK rule). */\nexport const DECLARATION_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/** \"<client>/<local>\" — the surface naming convention. */\nexport const SURFACE_NAME_RE = /^[a-z][a-z0-9-]*\\/[a-z0-9-/]+$/;\n\n/** A bare screen value (`status`) or an item value (`table_row.status`). */\nexport const QUALIFIED_VALUE_KEY_RE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$/;\n\nexport interface ParsedValueKey {\n /** \"\" for a screen-level value. */\n itemType: string;\n name: string;\n}\n\n/** Split a qualified key; null when it is not a valid bare or qualified key. */\nexport function parseQualifiedValueKey(key: string): ParsedValueKey | null {\n if (!QUALIFIED_VALUE_KEY_RE.test(key)) return null;\n const dot = key.indexOf(\".\");\n if (dot === -1) return { itemType: \"\", name: key };\n return { itemType: key.slice(0, dot), name: key.slice(dot + 1) };\n}\n\nexport function qualifyValueKey(itemType: string, name: string): QualifiedValueKey {\n return itemType ? `${itemType}.${name}` : name;\n}\n\n/** The client that owns a surface: its name prefix. */\nexport function surfaceClientOf(surfaceName: string): string {\n return surfaceName.split(\"/\")[0] ?? \"\";\n}\n","import type { SurfaceDeclaration } from \"./types\";\n\n/** Canonical JSON: keys sorted, undefined dropped, arrays in order. */\nexport function canonicalJson(value: unknown): string {\n if (value === undefined) return \"null\";\n if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .filter((key) => record[key] !== undefined)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n .join(\",\")}}`;\n}\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\n/** SHA-256 hex of a UTF-8 string. Pure, synchronous, runs anywhere (no crypto API needed). */\nexport function sha256Hex(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const bitLength = bytes.length * 8;\n const padded = new Uint8Array(((bytes.length + 9 + 63) >> 6) << 6);\n padded.set(bytes);\n padded[bytes.length] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor(bitLength / 0x100000000));\n view.setUint32(padded.length - 4, bitLength >>> 0);\n const h = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n const w = new Uint32Array(64);\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4);\n for (let i = 16; i < 64; i += 1) {\n const a = w[i - 15]!;\n const b = w[i - 2]!;\n const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);\n const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;\n }\n let a = h[0]!, b = h[1]!, c = h[2]!, d = h[3]!, e = h[4]!, f = h[5]!, g = h[6]!, hh = h[7]!;\n for (let i = 0; i < 64; i += 1) {\n const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));\n const ch = (e & f) ^ (~e & g);\n const t1 = (hh + S1 + ch + K[i]! + w[i]!) >>> 0;\n const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (S0 + maj) >>> 0;\n hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;\n }\n h[0] = (h[0]! + a) >>> 0; h[1] = (h[1]! + b) >>> 0; h[2] = (h[2]! + c) >>> 0; h[3] = (h[3]! + d) >>> 0;\n h[4] = (h[4]! + e) >>> 0; h[5] = (h[5]! + f) >>> 0; h[6] = (h[6]! + g) >>> 0; h[7] = (h[7]! + hh) >>> 0;\n }\n return Array.from(h, (word) => word.toString(16).padStart(8, \"0\")).join(\"\");\n}\n\n/**\n * Drift between clients. Computed, never authored: SHA-256 of the canonical JSON\n * of the declaration as authored (keys sorted, extension fields included).\n * Persisted as `ui_surface.content_hash` once that column exists.\n */\nexport function declarationHash(declaration: SurfaceDeclaration): string {\n return sha256Hex(canonicalJson(declaration));\n}\n","/**\n * Declaration validation — the ONE set of surface checks (CONTRACT §3 D5).\n * Ported from matrx-frontend `scripts/check-surface-drift.ts`; the app's own\n * check now runs this. Agent-owned slots (roles, client tools) validate through\n * their `DeclarationExtension`, never here.\n */\nimport { DECLARATION_NAME_RE, SURFACE_NAME_RE, surfaceClientOf } from \"./keys\";\nimport type {\n DeclarationExtension,\n DeclarationIssue,\n ResolvedSurfaceDeclaration,\n SurfaceDeclaration,\n} from \"./types\";\n\nexport const VALUE_TYPES = [\"string\", \"number\", \"boolean\", \"object\", \"array\", \"document\"] as const;\nexport const WRITE_MODES = [\"draft\", \"entity\", \"ui\", \"stream\"] as const;\nexport const APPLY_POLICIES = [\"manual\", \"ask\", \"auto\", \"queued\"] as const;\nexport const STREAM_OPS = [\"replace\", \"insert_before\", \"insert_after\", \"prepend\", \"append\", \"patch\"] as const;\nexport const EXECUTION_MODES = [\"python-stream\", \"nextjs-stream\", \"browser-realtime\", \"local-runtime\"] as const;\nexport const READINESS = [\"verified\", \"partial\", \"stub\"] as const;\nexport const LIVE_SLOTS = [\"selection\", \"on-demand\", \"errors\", \"requests\"] as const;\nexport const CLASSIFICATIONS = [\"ordinary\", \"secret\", \"credential\"] as const;\n\nconst STRUCTURED = new Set([\"object\", \"array\"]);\n\nexport interface ValidateOptions {\n /** Registered config namespaces; omitted = not checked. */\n knownNamespaces?: ReadonlySet<string>;\n /** Registered content-ir kind slugs; omitted = not checked. */\n isKnownKind?: (slug: string) => boolean;\n /** Names every declaration must expose unless `skipBaselineValues`. */\n baselineNames?: readonly string[];\n extensions?: readonly DeclarationExtension[];\n}\n\nfunction has<T extends string>(list: readonly T[], value: unknown): value is T {\n return typeof value === \"string\" && (list as readonly string[]).includes(value);\n}\n\nexport function validateDeclarations(\n declarations: readonly ResolvedSurfaceDeclaration[],\n options: ValidateOptions = {},\n): DeclarationIssue[] {\n const issues: DeclarationIssue[] = [];\n const seenSurfaces = new Set<string>();\n const labelsByClient = new Map<string, Map<string, string>>();\n\n for (const d of declarations) {\n const s = d.surfaceName;\n const push = (path: string, sentence: string, remedy: string, severity?: \"advisory\") =>\n issues.push({ surfaceName: s, path, sentence, remedy, ...(severity ? { severity } : {}) });\n\n if (seenSurfaces.has(s)) {\n push(\"surfaceName\", `Duplicate manifest surfaceName: \"${s}\" appears more than once.`, \"Keep one declaration per surface.\");\n }\n seenSurfaces.add(s);\n if (!SURFACE_NAME_RE.test(s)) {\n push(\"surfaceName\", `Surface \"${s}\" doesn't match the \"<client>/<local>\" convention.`, \"Rename it to <client>/<local>.\");\n }\n\n const prefix = surfaceClientOf(s);\n if (d.client !== prefix) {\n push(\"client\", `Surface \"${s}\" declares client \"${String(d.client)}\" but its name prefix is \"${prefix}\" — they must match.`, `Set client: \"${prefix}\".`);\n }\n if (!has(EXECUTION_MODES, d.executionMode)) {\n push(\"executionMode\", `Surface \"${s}\" has invalid executionMode \"${String(d.executionMode)}\".`, `Use one of ${EXECUTION_MODES.join(\" | \")}.`);\n }\n if (typeof d.description !== \"string\") {\n push(\"description\", `Surface \"${s}\" has no description.`, \"Add one sentence on what the surface is (\\\"\\\" only where the live row is empty).\");\n }\n\n const label = d.label?.trim();\n if (!label) {\n push(\"label\", `Surface \"${s}\" has no canonical label — label is required.`, \"Add the ONE canonical human display name.\");\n } else {\n const clientLabels = labelsByClient.get(prefix) ?? new Map<string, string>();\n const clash = clientLabels.get(label.toLowerCase());\n if (clash && clash !== s) {\n push(\"label\", `Canonical label \"${label}\" is used by both \"${clash}\" and \"${s}\" — labels must be unique per client.`, \"Give one of them a distinct label.\");\n }\n clientLabels.set(label.toLowerCase(), s);\n labelsByClient.set(prefix, clientLabels);\n }\n\n if (!has(READINESS, d.readiness)) {\n push(\"readiness\", `Surface \"${s}\" has invalid readiness \"${String(d.readiness)}\" (expected verified | partial | stub).`, \"Set a valid readiness.\");\n } else if (d.readiness !== \"verified\" && !d.readinessNote?.trim()) {\n push(\"readinessNote\", `Surface \"${s}\" is readiness \"${d.readiness}\" but has no readinessNote — say what's missing.`, \"Add a one-line readinessNote.\");\n }\n\n const groupKeys = new Set<string>();\n for (const g of d.groups ?? []) {\n groupKeys.add(g.key);\n const reserved = g.key === \"general\" || g.key === \"baseline\" || g.key.startsWith(\"inherited:\");\n if (reserved) continue;\n if (!DECLARATION_NAME_RE.test(g.key)) push(`groups/${g.key}`, `Surface \"${s}\" group \"${g.key}\" doesn't match /^[a-z][a-z0-9_]*$/.`, \"Rename the group key to lower_snake_case.\");\n if (g.sortOrder < 0 || g.sortOrder > 899) push(`groups/${g.key}/sortOrder`, `Surface \"${s}\" group \"${g.key}\" sortOrder ${g.sortOrder} is outside the curated band 0–899.`, \"Use a sortOrder between 0 and 899.\");\n if (!g.label?.trim()) push(`groups/${g.key}/label`, `Surface \"${s}\" group \"${g.key}\" has no canonical label.`, \"Add a label.\");\n }\n\n const seenNamespaces = new Set<string>();\n for (const ns of d.configNamespaces ?? []) {\n if (seenNamespaces.has(ns.namespace)) push(`configNamespaces/${ns.namespace}`, `Surface \"${s}\" declares duplicate config namespace \"${ns.namespace}\".`, \"Remove the duplicate.\");\n seenNamespaces.add(ns.namespace);\n if (options.knownNamespaces && !options.knownNamespaces.has(ns.namespace)) {\n push(`configNamespaces/${ns.namespace}`, `Surface \"${s}\" references config namespace \"${ns.namespace}\" which is not registered.`, \"Register the namespace first, or remove the reference.\");\n }\n }\n\n if (d.values.length === 0) {\n push(\"values\", `Surface \"${s}\" declares no values.`, \"Declare at least one value.\");\n continue;\n }\n\n const seenValues = new Set<string>();\n for (const v of d.values) {\n const at = `values/${v.name}`;\n if (seenValues.has(v.name)) push(at, `Surface \"${s}\" declares duplicate value \"${v.name}\".`, \"Remove the duplicate.\");\n seenValues.add(v.name);\n if (!DECLARATION_NAME_RE.test(v.name)) push(at, `Surface \"${s}\" value \"${v.name}\" doesn't match /^[a-z][a-z0-9_]*$/ — the DB CHECK constraint will reject this.`, \"Rename it to lower_snake_case.\");\n if (!has(VALUE_TYPES, v.valueType)) push(`${at}/valueType`, `Surface \"${s}\" value \"${v.name}\" has invalid valueType \"${String(v.valueType)}\".`, `Use one of ${VALUE_TYPES.join(\" | \")}.`);\n if (typeof v.typicalCharCount !== \"number\" || v.typicalCharCount < 0) push(`${at}/typicalCharCount`, `Surface \"${s}\" value \"${v.name}\" has invalid typicalCharCount.`, \"Use a non-negative number.\");\n if (v.sortOrder !== undefined && (typeof v.sortOrder !== \"number\" || v.sortOrder < 0)) push(`${at}/sortOrder`, `Surface \"${s}\" value \"${v.name}\" has invalid sortOrder.`, \"Use a non-negative number.\");\n if (v.groupKey && !groupKeys.has(v.groupKey)) push(`${at}/group`, `Surface \"${s}\" value \"${v.name}\" resolved to groupKey \"${v.groupKey}\" which is missing from the resolved groups list — registry group synthesis is broken.`, \"Fix the registry resolution.\");\n if (v.liveSlot !== undefined && !has(LIVE_SLOTS, v.liveSlot)) push(`${at}/liveSlot`, `Surface \"${s}\" value \"${v.name}\" has invalid liveSlot \"${String(v.liveSlot)}\".`, `Use one of ${LIVE_SLOTS.join(\" | \")}.`);\n if (v.role !== undefined && v.role !== \"data\" && v.role !== \"request\") push(`${at}/role`, `Surface \"${s}\" value \"${v.name}\" has invalid role \"${String(v.role)}\".`, \"Use data | request.\");\n if (v.sensitivity?.classification !== undefined && !has(CLASSIFICATIONS, v.sensitivity.classification)) push(`${at}/sensitivity/classification`, `Surface \"${s}\" value \"${v.name}\" has invalid classification \"${String(v.sensitivity.classification)}\".`, `Use one of ${CLASSIFICATIONS.join(\" | \")}.`);\n }\n\n for (const slot of d.liveSlots ?? []) {\n if (!has(LIVE_SLOTS, slot)) push(\"liveSlots\", `Surface \"${s}\" declares unknown live slot \"${String(slot)}\".`, `Use one of ${LIVE_SLOTS.join(\" | \")}.`);\n }\n\n const itemTypeNames = new Set<string>();\n for (const item of d.itemTypes ?? []) {\n const at = `itemTypes/${item.name}`;\n if (itemTypeNames.has(item.name)) push(at, `Surface \"${s}\" declares duplicate item type \"${item.name}\".`, \"Remove the duplicate.\");\n itemTypeNames.add(item.name);\n if (!DECLARATION_NAME_RE.test(item.name)) push(at, `Surface \"${s}\" item type \"${item.name}\" doesn't match /^[a-z][a-z0-9_]*$/.`, \"Rename it to lower_snake_case.\");\n if (!item.label?.trim() || !item.description?.trim()) push(at, `Surface \"${s}\" item type \"${item.name}\" needs a label and a description.`, \"Add both.\");\n const itemValues = new Set(item.values.map((v) => v.name));\n if (item.identity.length === 0) push(`${at}/identity`, `Surface \"${s}\" item type \"${item.name}\" has an empty identity.`, \"Name the value(s) that identify one item.\");\n for (const key of item.identity) {\n if (!itemValues.has(key)) push(`${at}/identity`, `Surface \"${s}\" item type \"${item.name}\" identity names \"${key}\", which is not one of its values.`, \"Declare it as an item value.\");\n }\n for (const t of item.writeTargets ?? []) {\n if (t.updatesValue && !itemValues.has(t.updatesValue)) push(`${at}/writeTargets/${t.name}`, `Surface \"${s}\" item type \"${item.name}\" write target \"${t.name}\" updatesValue \"${t.updatesValue}\" which is not an item value.`, \"Point it at a declared item value.\");\n }\n }\n\n const seenTargets = new Set<string>();\n const structuredWithoutKind: string[] = [];\n for (const w of d.writeTargets ?? []) {\n const at = `writeTargets/${w.name}`;\n if (seenTargets.has(w.name)) push(at, `Surface \"${s}\" declares duplicate write target \"${w.name}\".`, \"Remove the duplicate.\");\n seenTargets.add(w.name);\n if (!DECLARATION_NAME_RE.test(w.name)) push(at, `Surface \"${s}\" write target \"${w.name}\" doesn't match /^[a-z][a-z0-9_]*$/.`, \"Rename it to lower_snake_case.\");\n if (!w.label?.trim() || !w.description?.trim()) push(at, `Surface \"${s}\" write target \"${w.name}\" needs a label and a description.`, \"Add both.\");\n if (!has(VALUE_TYPES, w.valueType)) push(`${at}/valueType`, `Surface \"${s}\" write target \"${w.name}\" has invalid valueType \"${String(w.valueType)}\".`, `Use one of ${VALUE_TYPES.join(\" | \")}.`);\n if (!has(WRITE_MODES, w.mode)) push(`${at}/mode`, `Surface \"${s}\" write target \"${w.name}\" has invalid mode \"${String(w.mode)}\".`, `Use one of ${WRITE_MODES.join(\" | \")}.`);\n if (w.applyPolicy !== undefined && !has(APPLY_POLICIES, w.applyPolicy)) push(`${at}/applyPolicy`, `Surface \"${s}\" write target \"${w.name}\" has invalid applyPolicy \"${String(w.applyPolicy)}\".`, `Use one of ${APPLY_POLICIES.join(\" | \")}.`);\n if (w.itemType !== undefined && !itemTypeNames.has(w.itemType)) push(`${at}/itemType`, `Surface \"${s}\" write target \"${w.name}\" names item type \"${w.itemType}\", which the surface does not declare.`, \"Declare the item type or drop itemType.\");\n const readTwinDeclared = w.updatesValue ? seenValues.has(w.updatesValue) : false;\n if (w.updatesValue && !w.itemType && !readTwinDeclared) push(`${at}/updatesValue`, `Surface \"${s}\" write target \"${w.name}\" updatesValue \"${w.updatesValue}\" which is not a declared value.`, \"Point updatesValue at a declared value.\");\n if (w.patchable && !w.updatesValue) push(`${at}/patchable`, `Surface \"${s}\" write target \"${w.name}\" is patchable but declares no updatesValue — an anchored edit has nothing to read.`, \"Declare the read twin in updatesValue.\");\n if (w.patchable && w.valueType !== \"string\" && w.valueType !== \"document\") push(`${at}/patchable`, `Surface \"${s}\" write target \"${w.name}\" is patchable but valueType is \"${w.valueType}\" (patching is for \"string\" | \"document\").`, \"Drop patchable or change the value type.\");\n if (w.mode === \"stream\") {\n if (!w.streamOps || w.streamOps.length === 0) push(`${at}/streamOps`, `Surface \"${s}\" write target \"${w.name}\" is a stream target with no streamOps.`, \"List the ops it services.\");\n if (!w.updatesValue) push(`${at}/updatesValue`, `Surface \"${s}\" write target \"${w.name}\" is a stream target with no read twin.`, \"Declare updatesValue.\");\n } else if (w.streamOps !== undefined) {\n push(`${at}/streamOps`, `Surface \"${s}\" write target \"${w.name}\" lists streamOps but its mode is \"${w.mode}\".`, \"streamOps belong only to mode \\\"stream\\\".\");\n }\n for (const op of w.streamOps ?? []) {\n if (!has(STREAM_OPS, op)) push(`${at}/streamOps`, `Surface \"${s}\" write target \"${w.name}\" lists unknown stream op \"${String(op)}\".`, `Use ${STREAM_OPS.join(\" | \")}.`);\n }\n if (w.group && !groupKeys.has(w.group)) push(`${at}/group`, `Surface \"${s}\" write target \"${w.name}\" references undeclared group \"${w.group}\".`, \"Declare the group or drop it.\");\n if (w.valueKind !== undefined) {\n if (typeof w.valueKind !== \"string\" || !w.valueKind.trim()) {\n push(`${at}/valueKind`, `Surface \"${s}\" write target \"${w.name}\" has an empty valueKind.`, \"Name a registered kind slug or omit the field.\");\n } else if (options.isKnownKind && !options.isKnownKind(w.valueKind)) {\n push(`${at}/valueKind`, `Surface \"${s}\" write target \"${w.name}\" declares valueKind \"${w.valueKind}\", which is not a registered active kind.`, \"Name a registered kind slug, or register the kind first; never inline a JSON schema.\");\n }\n } else if (STRUCTURED.has(w.valueType)) {\n structuredWithoutKind.push(w.name);\n }\n }\n for (const name of structuredWithoutKind) {\n push(`writeTargets/${name}/valueKind`, `Surface \"${s}\" structured write target \"${name}\" declares no valueKind.`, \"Name a registered kind slug (the value contract ratchet).\", \"advisory\");\n }\n\n if (!d.skipBaselineValues && options.baselineNames) {\n const missing = options.baselineNames.filter((name) => !seenValues.has(name));\n if (missing.length > 0) {\n push(\"values\", `Surface \"${s}\" is missing baseline value(s): ${missing.join(\", \")}.`, \"The registry injects baselines automatically; opt out only with skipBaselineValues.\");\n }\n }\n }\n\n for (const extension of options.extensions ?? []) {\n if (!extension.validate) continue;\n for (const d of declarations) issues.push(...extension.validate(d as SurfaceDeclaration & ResolvedSurfaceDeclaration, { all: declarations }));\n }\n return issues;\n}\n\n/**\n * The runtime half: a loaded scope may carry only declared values. Returns one\n * issue per undeclared key (and per `__item` value its item type does not declare).\n */\nexport function validateLoadedValues(\n declaration: Pick<ResolvedSurfaceDeclaration, \"surfaceName\" | \"values\" | \"itemTypes\">,\n loaded: Record<string, unknown>,\n options: { ignore?: readonly string[] } = {},\n): DeclarationIssue[] {\n const declared = new Set(declaration.values.map((v) => v.name));\n const ignore = new Set(options.ignore ?? []);\n const issues: DeclarationIssue[] = [];\n for (const key of Object.keys(loaded)) {\n if (key === \"__item\" || declared.has(key) || ignore.has(key)) continue;\n issues.push({\n surfaceName: declaration.surfaceName,\n path: `values/${key}`,\n sentence: `Surface \"${declaration.surfaceName}\" loaded a value \"${key}\" it never declared.`,\n remedy: `Declare \"${key}\" in the surface's values, or stop emitting it.`,\n });\n }\n const item = loaded.__item as { itemType?: unknown; values?: unknown } | undefined;\n if (item && typeof item === \"object\") {\n const type = declaration.itemTypes?.find((t) => t.name === item.itemType);\n if (!type) {\n issues.push({\n surfaceName: declaration.surfaceName,\n path: \"__item/itemType\",\n sentence: `Surface \"${declaration.surfaceName}\" loaded an item of type \"${String(item.itemType)}\" it never declared.`,\n remedy: \"Declare the item type, or stop emitting the item.\",\n });\n } else if (item.values && typeof item.values === \"object\") {\n const itemDeclared = new Set(type.values.map((v) => v.name));\n for (const key of Object.keys(item.values)) {\n if (itemDeclared.has(key)) continue;\n issues.push({\n surfaceName: declaration.surfaceName,\n path: `__item/${type.name}.${key}`,\n sentence: `Surface \"${declaration.surfaceName}\" loaded item value \"${type.name}.${key}\" it never declared.`,\n remedy: `Declare \"${key}\" on item type \"${type.name}\".`,\n });\n }\n }\n }\n return issues;\n}\n\n/**\n * Ownership: no `ui.ui_surface` row may exist without a declaring owner\n * (CONTRACT §2.1a). `retired` rows (archived, not deleted) are exempt.\n */\nexport function findOrphanRows(\n rowNames: readonly string[],\n declaredNames: Iterable<string>,\n retired: Iterable<string> = [],\n): string[] {\n const owned = new Set(declaredNames);\n const archived = new Set(retired);\n return rowNames.filter((name) => !owned.has(name) && !archived.has(name)).sort();\n}\n","/**\n * The declaration registry: inheritance, baseline injection, provenance and\n * group synthesis (CONTRACT §2.1 `DeclarationRegistry`). Ported verbatim in\n * behaviour from matrx-frontend `features/surfaces/manifests/registry.ts`\n * (ALC-14); the app now supplies its declarations and baselines.\n *\n * Guards are LOUD by design: an unknown parent, a cycle, a chain deeper than\n * the limit, a reserved or duplicate group key, a value naming an undeclared\n * group, or a reserved platform name throws on resolution — a build fails\n * instead of silently dropping values.\n */\nimport { declarationHash } from \"./hash\";\nimport type {\n DeclarationExtension,\n DeclarationIssue,\n DeclaredValue,\n ResolvedSurfaceDeclaration,\n ResolvedValue,\n Sensitivity,\n SurfaceDeclaration,\n ValueGroup,\n ValueProvenance,\n} from \"./types\";\nimport { validateDeclarations, type ValidateOptions } from \"./validate\";\n\nexport const RESERVED_GROUP_KEYS = {\n general: \"general\",\n baseline: \"baseline\",\n inheritedPrefix: \"inherited:\",\n} as const;\n\n/** Group sortOrder bands. Curated groups author 0–899; the rest is reserved. */\nexport const GENERAL_GROUP_ORDER = 850;\nexport const INHERITED_GROUP_ORDER_BASE = 9000;\nexport const BASELINE_GROUP_ORDER = 9900;\nexport const DEFAULT_MAX_INHERITANCE_DEPTH = 3;\n\nexport const DEFAULT_SENSITIVITY: Sensitivity = Object.freeze({\n exportable: true,\n classification: \"ordinary\",\n includedByDefault: true,\n});\n\nexport function resolveSensitivity(value: Pick<DeclaredValue, \"sensitivity\">): Sensitivity {\n return {\n exportable: value.sensitivity?.exportable ?? DEFAULT_SENSITIVITY.exportable,\n classification: value.sensitivity?.classification ?? DEFAULT_SENSITIVITY.classification,\n includedByDefault: value.sensitivity?.includedByDefault ?? DEFAULT_SENSITIVITY.includedByDefault,\n };\n}\n\nexport type Resolved<D extends SurfaceDeclaration> = Omit<D, \"values\" | \"groups\"> & {\n values: readonly (D[\"values\"][number] & ResolvedValue)[];\n groups: readonly ValueGroup[];\n contentHash: string;\n};\n\nexport interface DeclarationRegistryOptions {\n /** Generic values injected into every declaration unless `skipBaselineValues`. */\n baselineValues?: readonly DeclaredValue[];\n /** Value names only the platform writes; a declaration claiming one is refused. */\n reservedValueNames?: readonly string[];\n /** Write-target names only the platform writes. */\n reservedWriteTargetNames?: readonly string[];\n maxInheritanceDepth?: number;\n}\n\nexport interface DeclarationRegistry<D extends SurfaceDeclaration> {\n /** Refuses a second declaration of the same surfaceName. */\n register(declaration: D): void;\n registerExtension(extension: DeclarationExtension<D>): void;\n extensions(): readonly DeclarationExtension<D>[];\n /** Declarations exactly as authored (inheritance unresolved, no baselines). */\n raw(): readonly D[];\n getRaw(surfaceName: string): D | undefined;\n /** Parent chain, ROOT FIRST. Unknown surfaces return []. */\n ancestry(surfaceName: string): string[];\n /** Direct children (declarations naming it in `inheritsFrom`), in declaration order. */\n children(surfaceName: string): string[];\n /** Inheritance + baseline + groups resolved; provenance kept. */\n all(): readonly Resolved<D>[];\n get(surfaceName: string): Resolved<D> | undefined;\n validate(options?: ValidateOptions): readonly DeclarationIssue[];\n}\n\nexport function createDeclarationRegistry<D extends SurfaceDeclaration>(\n options: DeclarationRegistryOptions = {},\n): DeclarationRegistry<D> {\n const baselineValues = options.baselineValues ?? [];\n const baselineNames = new Set(baselineValues.map((v) => v.name));\n const reservedValues = new Set(options.reservedValueNames ?? []);\n const reservedTargets = new Set(options.reservedWriteTargetNames ?? []);\n const maxDepth = options.maxInheritanceDepth ?? DEFAULT_MAX_INHERITANCE_DEPTH;\n const declarations: D[] = [];\n const index = new Map<string, D>();\n const extensionList: DeclarationExtension<D>[] = [];\n let resolvedCache: Resolved<D>[] | null = null;\n let resolvedIndex = new Map<string, Resolved<D>>();\n\n function ancestry(surfaceName: string): string[] {\n const chain: string[] = [];\n const seen = new Set<string>([surfaceName]);\n let current = index.get(surfaceName)?.inheritsFrom;\n while (current) {\n if (seen.has(current)) {\n throw new Error(\n `[surfaces] inheritsFrom CYCLE detected at \"${current}\" (from \"${surfaceName}\"). ` +\n `Fix the manifest chain: ${[...seen].join(\" → \")} → ${current}`,\n );\n }\n const parent = index.get(current);\n if (!parent) {\n throw new Error(\n `[surfaces] \"${surfaceName}\" inheritsFrom unknown surface \"${current}\" — ` +\n `the parent must be a registered declaration`,\n );\n }\n seen.add(current);\n chain.unshift(current);\n if (chain.length > maxDepth) {\n throw new Error(\n `[surfaces] inheritance chain for \"${surfaceName}\" exceeds depth ${maxDepth}: ` + chain.join(\" → \"),\n );\n }\n current = parent.inheritsFrom;\n }\n return chain;\n }\n\n function groupKeyFor(value: DeclaredValue, provenance: ValueProvenance): string {\n if (provenance.kind === \"own\" && value.group) return value.group;\n if (baselineNames.has(value.name)) return RESERVED_GROUP_KEYS.baseline;\n if (provenance.kind === \"inherited\") return `${RESERVED_GROUP_KEYS.inheritedPrefix}${provenance.from}`;\n if (provenance.kind === \"baseline\") return RESERVED_GROUP_KEYS.baseline;\n return RESERVED_GROUP_KEYS.general;\n }\n\n function resolve(declaration: D): Resolved<D> {\n const chain = ancestry(declaration.surfaceName);\n const lineage: { layer: D; from: string | null }[] = [\n ...chain.map((name) => {\n const layer = index.get(name);\n if (!layer) throw new Error(`[surfaces] missing inherited declaration \"${name}\"`);\n return { layer, from: name };\n }),\n { layer: declaration, from: null },\n ];\n\n const curatedKeys = new Set<string>();\n for (const group of declaration.groups ?? []) {\n if (\n group.key === RESERVED_GROUP_KEYS.general ||\n group.key === RESERVED_GROUP_KEYS.baseline ||\n group.key.startsWith(RESERVED_GROUP_KEYS.inheritedPrefix)\n ) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares reserved group key \"${group.key}\" — ` +\n `general/baseline/inherited:* are synthesized by the registry`,\n );\n }\n if (curatedKeys.has(group.key)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" declares duplicate group key \"${group.key}\"`);\n }\n curatedKeys.add(group.key);\n }\n for (const value of declaration.values) {\n if (reservedValues.has(value.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares value \"${value.name}\" — that name is written by the platform; choose another name`,\n );\n }\n if (value.group && !curatedKeys.has(value.group)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" value \"${value.name}\" references undeclared ` +\n `group \"${value.group}\" — declare it in the manifest's \\`groups\\``,\n );\n }\n }\n for (const target of declaration.writeTargets ?? []) {\n if (reservedTargets.has(target.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares write target \"${target.name}\" — that name is written by the platform; choose another name`,\n );\n }\n }\n\n const valuesByName = new Map<string, D[\"values\"][number] & ResolvedValue>();\n const inheritedLists = new Map<string, Map<string, unknown>>();\n const coreLists: { field: string; identity(entry: unknown): string }[] = [\n { field: \"configNamespaces\", identity: (entry) => (entry as { namespace: string }).namespace },\n {\n field: \"evidenceSources\",\n identity: (entry) => `${(entry as { kind: string }).kind}:${(entry as { idValue: string }).idValue}`,\n },\n ];\n const lists = [...coreLists, ...extensionList.flatMap((extension) => extension.inheritedLists ?? [])];\n for (const { layer, from } of lineage) {\n for (const value of layer.values) {\n const provenance: ValueProvenance = from ? { kind: \"inherited\", from } : { kind: \"own\" };\n valuesByName.set(value.name, {\n ...value,\n provenance,\n groupKey: groupKeyFor(value, provenance),\n resolvedSensitivity: resolveSensitivity(value),\n });\n }\n for (const list of lists) {\n const entries = (layer as unknown as Record<string, unknown>)[list.field];\n if (!Array.isArray(entries)) continue;\n const byIdentity = inheritedLists.get(list.field) ?? new Map<string, unknown>();\n for (const entry of entries) byIdentity.set(list.identity(entry), entry);\n inheritedLists.set(list.field, byIdentity);\n }\n }\n\n if (!declaration.skipBaselineValues) {\n for (const baseline of baselineValues) {\n if (valuesByName.has(baseline.name)) continue;\n valuesByName.set(baseline.name, {\n ...baseline,\n provenance: { kind: \"baseline\" },\n groupKey: RESERVED_GROUP_KEYS.baseline,\n resolvedSensitivity: resolveSensitivity(baseline),\n } as D[\"values\"][number] & ResolvedValue);\n }\n }\n\n const usedGroupKeys = new Set(Array.from(valuesByName.values(), (value) => value.groupKey));\n const groups: ValueGroup[] = [...(declaration.groups ?? [])];\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.general)) {\n groups.push({ key: RESERVED_GROUP_KEYS.general, label: \"General\", sortOrder: GENERAL_GROUP_ORDER });\n }\n for (let i = chain.length - 1, distance = 0; i >= 0; i -= 1, distance += 1) {\n const parentName = chain[i]!;\n const key = `${RESERVED_GROUP_KEYS.inheritedPrefix}${parentName}`;\n if (!usedGroupKeys.has(key)) continue;\n const parentLabel = index.get(parentName)?.label ?? parentName;\n groups.push({\n key,\n label: `Inherited from ${parentLabel}`,\n sortOrder: INHERITED_GROUP_ORDER_BASE + distance * 10,\n });\n }\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.baseline)) {\n groups.push({ key: RESERVED_GROUP_KEYS.baseline, label: \"Generic baselines\", sortOrder: BASELINE_GROUP_ORDER });\n }\n groups.sort((a, b) => a.sortOrder - b.sortOrder);\n\n const groupOrder = new Map(groups.map((group) => [group.key, group.sortOrder] as const));\n const values = Array.from(valuesByName.values()).sort((a, b) => {\n const ga = groupOrder.get(a.groupKey) ?? GENERAL_GROUP_ORDER;\n const gb = groupOrder.get(b.groupKey) ?? GENERAL_GROUP_ORDER;\n if (ga !== gb) return ga - gb;\n return (a.sortOrder ?? 1000) - (b.sortOrder ?? 1000);\n });\n\n const merged: Record<string, unknown> = {};\n for (const [field, byIdentity] of inheritedLists) {\n if (byIdentity.size > 0) merged[field] = Array.from(byIdentity.values());\n }\n return {\n ...declaration,\n values,\n groups,\n ...merged,\n contentHash: declarationHash(declaration),\n } as Resolved<D>;\n }\n\n function resolvedAll(): Resolved<D>[] {\n if (!resolvedCache) {\n resolvedCache = declarations.map(resolve);\n resolvedIndex = new Map(resolvedCache.map((entry) => [entry.surfaceName, entry] as const));\n }\n return resolvedCache;\n }\n\n const registry: DeclarationRegistry<D> = {\n register(declaration) {\n if (index.has(declaration.surfaceName)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" is declared twice — one surface, one declaration`);\n }\n declarations.push(declaration);\n index.set(declaration.surfaceName, declaration);\n resolvedCache = null;\n },\n registerExtension(extension) {\n if (extensionList.some((existing) => existing.key === extension.key)) {\n throw new Error(`[surfaces] declaration extension \"${extension.key}\" is registered twice`);\n }\n extensionList.push(extension);\n resolvedCache = null;\n },\n extensions: () => extensionList,\n raw: () => declarations,\n getRaw: (surfaceName) => index.get(surfaceName),\n ancestry,\n children: (surfaceName) =>\n declarations.filter((d) => d.inheritsFrom === surfaceName).map((d) => d.surfaceName),\n all: () => resolvedAll(),\n get(surfaceName) {\n resolvedAll();\n return resolvedIndex.get(surfaceName);\n },\n validate: (validateOptions) =>\n validateDeclarations(resolvedAll() as unknown as readonly ResolvedSurfaceDeclaration[], {\n ...validateOptions,\n extensions: [...(validateOptions?.extensions ?? []), ...(extensionList as DeclarationExtension[])],\n baselineNames: validateOptions?.baselineNames ?? [...baselineNames],\n }),\n };\n return registry;\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;;;ACGO,IAAM,sBAAsB;AAG5B,IAAM,kBAAkB;AAGxB,IAAM,yBAAyB;AAS/B,SAAS,uBAAuB,KAAoC;AACzE,MAAI,CAAC,uBAAuB,KAAK,GAAG,EAAG,QAAO;AAC9C,QAAM,MAAM,IAAI,QAAQ,GAAG;AAC3B,MAAI,QAAQ,GAAI,QAAO,EAAE,UAAU,IAAI,MAAM,IAAI;AACjD,SAAO,EAAE,UAAU,IAAI,MAAM,GAAG,GAAG,GAAG,MAAM,IAAI,MAAM,MAAM,CAAC,EAAE;AACjE;AAEO,SAAS,gBAAgB,UAAkB,MAAiC;AACjF,SAAO,WAAW,GAAG,QAAQ,IAAI,IAAI,KAAK;AAC5C;AAGO,SAAS,gBAAgB,aAA6B;AAC3D,SAAO,YAAY,MAAM,GAAG,EAAE,CAAC,KAAK;AACtC;;;AC7BO,SAAS,cAAc,OAAwB;AACpD,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO,KAAK,UAAU,KAAK;AAC5E,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,IAAI,MAAM,IAAI,CAAC,UAAU,cAAc,KAAK,CAAC,EAAE,KAAK,GAAG,CAAC;AACzF,QAAM,SAAS;AACf,SAAO,IAAI,OAAO,KAAK,MAAM,EAC1B,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data (chair ruling N2): no functions, no classes,
5
+ * no React. Runtime behaviour lives in `MountedSurface` (`/declare/host`) and in
6
+ * handler registrations, never here. Zero React, zero `@ai-matrx/agents`.
7
+ */
8
+ type Json = null | boolean | number | string | Json[] | {
9
+ [key: string]: Json;
10
+ };
11
+ /** Unchanged from `ui_surface_value_type_chk`. */
12
+ type ValueType = "string" | "number" | "boolean" | "object" | "array" | "document";
13
+ type Classification = "ordinary" | "secret" | "credential";
14
+ /** Persisted (CONTRACT §2.7). Projection enforces it before any value leaves. */
15
+ interface Sensitivity {
16
+ /** false = never leaves through Operate. Default true. */
17
+ exportable: boolean;
18
+ /** secret/credential are always excluded; no caller can relax this. Default "ordinary". */
19
+ classification: Classification;
20
+ /** Pre-checked in the preparation workspace. Default true. */
21
+ includedByDefault: boolean;
22
+ }
23
+ interface ValueGroup {
24
+ key: string;
25
+ label: string;
26
+ sortOrder: number;
27
+ description?: string;
28
+ }
29
+ /** The four runtime slots a capture fills (absorbs page-capture). */
30
+ type LiveSlot = "selection" | "on-demand" | "errors" | "requests";
31
+ interface DeclaredValue {
32
+ name: string;
33
+ label: string;
34
+ description: string;
35
+ valueType: ValueType;
36
+ /** Registered content-ir kind key (DB: kind_key). */
37
+ valueKind?: string;
38
+ alwaysAvailable: boolean;
39
+ typicalCharCount: number;
40
+ autoContext?: boolean;
41
+ group?: string;
42
+ sortOrder?: number;
43
+ sensitivity?: Partial<Sensitivity>;
44
+ /** Filled at capture time from a live slot instead of the scope. */
45
+ liveSlot?: LiveSlot;
46
+ /** "request" values drop out of "Only the data". Default "data". */
47
+ role?: "data" | "request";
48
+ }
49
+ /** Where a write lands. "stream" = applied live, op by op, into an editable text. */
50
+ type WriteMode = "draft" | "entity" | "ui" | "stream";
51
+ /** Who may apply WITHOUT a click. "queued" = filed for an organization's review. */
52
+ type ApplyPolicy = "manual" | "ask" | "auto" | "queued";
53
+ /** The WidgetHandle text op set, unchanged in meaning. */
54
+ type StreamOp = "replace" | "insert_before" | "insert_after" | "prepend" | "append" | "patch";
55
+ interface WriteTarget {
56
+ name: string;
57
+ label: string;
58
+ description: string;
59
+ valueType: ValueType;
60
+ valueKind?: string;
61
+ /** Read twin (evidence loop). Required when patchable or mode === "stream". */
62
+ updatesValue?: string;
63
+ patchable?: boolean;
64
+ approvalComparison?: "text-replacement";
65
+ mode: WriteMode;
66
+ /** Required iff mode === "stream". */
67
+ streamOps?: readonly StreamOp[];
68
+ /** Default "manual". Binding overrides may only tighten. */
69
+ applyPolicy?: ApplyPolicy;
70
+ destination?: boolean;
71
+ /** Present when the target writes into an item rather than the screen. */
72
+ itemType?: string;
73
+ group?: string;
74
+ sortOrder?: number;
75
+ }
76
+ /** One kind of thing inside a screen (a row, a message, a code block, a card). */
77
+ interface ItemType {
78
+ name: string;
79
+ label: string;
80
+ description: string;
81
+ /** Value names that together identify one item. */
82
+ identity: readonly string[];
83
+ levels?: readonly string[];
84
+ entityType?: string;
85
+ values: readonly DeclaredValue[];
86
+ writeTargets?: readonly WriteTarget[];
87
+ }
88
+ type Readiness = "verified" | "partial" | "stub";
89
+ /** `ui_surface_execution_mode_check`, unchanged. */
90
+ type ExecutionMode = "python-stream" | "nextjs-stream" | "browser-realtime" | "local-runtime";
91
+ interface ConfigNamespaceDeclaration {
92
+ namespace: string;
93
+ label: string;
94
+ description: string;
95
+ }
96
+ interface EvidenceSourceDeclaration {
97
+ kind: "processed_document";
98
+ idValue: string;
99
+ fileIdValue?: string;
100
+ labelValue?: string;
101
+ representation?: "clean" | "raw";
102
+ }
103
+ /**
104
+ * One screen's declaration. Owning packages add fields (agent roles, client
105
+ * tools) as EXTENSION SLOTS — by interface extension or declaration merging —
106
+ * and register a `DeclarationExtension` so validation and the sync cover them.
107
+ */
108
+ interface SurfaceDeclaration {
109
+ surfaceName: string;
110
+ /** REQUIRED. `ui_surface.client_name`; must equal the surfaceName prefix. */
111
+ client: string;
112
+ /** REQUIRED. `ui_surface.execution_mode`. */
113
+ executionMode: ExecutionMode;
114
+ /** REQUIRED. `ui_surface.description` ("" only where the live row is empty). */
115
+ description: string;
116
+ label: string;
117
+ readiness: Readiness;
118
+ readinessNote?: string;
119
+ urlPattern?: string;
120
+ inheritsFrom?: string;
121
+ intro?: string;
122
+ overlayId?: string;
123
+ values: readonly DeclaredValue[];
124
+ groups?: readonly ValueGroup[];
125
+ writeTargets?: readonly WriteTarget[];
126
+ itemTypes?: readonly ItemType[];
127
+ liveSlots?: readonly LiveSlot[];
128
+ configNamespaces?: readonly ConfigNamespaceDeclaration[];
129
+ evidenceSources?: readonly EvidenceSourceDeclaration[];
130
+ skipBaselineValues?: boolean;
131
+ }
132
+ interface DeclarationIssue {
133
+ surfaceName: string;
134
+ /** "writeTargets/body/updatesValue" */
135
+ path: string;
136
+ sentence: string;
137
+ remedy: string;
138
+ /** Advisory issues are reported, never fatal (the ratchets). Default "error". */
139
+ severity?: "error" | "advisory";
140
+ }
141
+ /** A row the sync writes for an extension slot (e.g. agent roles, client tools). */
142
+ interface ExtensionRow {
143
+ table: string;
144
+ /** The row's key columns within its table (e.g. ["surface_name", "name"]). */
145
+ conflict: readonly string[];
146
+ row: Record<string, Json>;
147
+ }
148
+ interface DeclarationExtension<D extends SurfaceDeclaration = SurfaceDeclaration> {
149
+ key: string;
150
+ /** Package or app that owns the slot, shown in check failures. */
151
+ owner: string;
152
+ /**
153
+ * Lists this slot contributes to inheritance: a child inherits its parent's
154
+ * entries and overrides per identity (child wins).
155
+ */
156
+ inheritedLists?: readonly {
157
+ field: string;
158
+ identity(entry: unknown): string;
159
+ }[];
160
+ validate?(declaration: D, context: ValidationContext): readonly DeclarationIssue[];
161
+ toRows?(declaration: D): readonly ExtensionRow[];
162
+ }
163
+ interface ValidationContext {
164
+ /** Every registered declaration, resolved. */
165
+ all: readonly ResolvedSurfaceDeclaration[];
166
+ }
167
+ type ValueProvenance = {
168
+ kind: "own";
169
+ } | {
170
+ kind: "inherited";
171
+ from: string;
172
+ } | {
173
+ kind: "baseline";
174
+ };
175
+ type ResolvedValue = DeclaredValue & {
176
+ provenance: ValueProvenance;
177
+ groupKey: string;
178
+ /** Defaults filled. */
179
+ resolvedSensitivity: Sensitivity;
180
+ };
181
+ interface ResolvedSurfaceDeclaration extends SurfaceDeclaration {
182
+ contentHash: string;
183
+ values: readonly ResolvedValue[];
184
+ groups: readonly ValueGroup[];
185
+ }
186
+ /**
187
+ * ITEM KEYS. A value or write target is identified by (surfaceName, itemType ?? "", name).
188
+ * The qualified key "<itemType>.<name>" names an item value; a bare name is a screen value.
189
+ */
190
+ type QualifiedValueKey = string;
191
+ /** Live slot payloads (page-capture's shapes, kept). */
192
+ interface LiveValues {
193
+ selection?: {
194
+ choices: Record<string, Json>;
195
+ text: string | null;
196
+ };
197
+ "on-demand"?: readonly OnDemandSection[];
198
+ errors?: readonly string[];
199
+ requests?: readonly RecentRequest[];
200
+ }
201
+ interface OnDemandSection {
202
+ id: string;
203
+ title: string;
204
+ description?: string;
205
+ role: "data" | "request";
206
+ brief?: Json;
207
+ load(signal: AbortSignal): Promise<Json>;
208
+ }
209
+ interface RecentRequest {
210
+ method: string;
211
+ path: string;
212
+ status: string;
213
+ httpStatus?: number;
214
+ durationMs?: number;
215
+ requestId?: string;
216
+ client?: string;
217
+ requestBody?: Json;
218
+ requestBodyNote?: string;
219
+ errorSentence?: string;
220
+ timestamp: number;
221
+ }
222
+ /** RAW-FREE. What leaves the package about a clicked item. */
223
+ interface ResolvedItem {
224
+ itemType: string;
225
+ identity: Record<string, string>;
226
+ level?: string;
227
+ readOnly: boolean;
228
+ }
229
+
230
+ /** Every value, write-target, item-type and group name (the DB CHECK rule). */
231
+ declare const DECLARATION_NAME_RE: RegExp;
232
+ /** "<client>/<local>" — the surface naming convention. */
233
+ declare const SURFACE_NAME_RE: RegExp;
234
+ /** A bare screen value (`status`) or an item value (`table_row.status`). */
235
+ declare const QUALIFIED_VALUE_KEY_RE: RegExp;
236
+ interface ParsedValueKey {
237
+ /** "" for a screen-level value. */
238
+ itemType: string;
239
+ name: string;
240
+ }
241
+ /** Split a qualified key; null when it is not a valid bare or qualified key. */
242
+ declare function parseQualifiedValueKey(key: string): ParsedValueKey | null;
243
+ declare function qualifyValueKey(itemType: string, name: string): QualifiedValueKey;
244
+ /** The client that owns a surface: its name prefix. */
245
+ declare function surfaceClientOf(surfaceName: string): string;
246
+
247
+ /** Canonical JSON: keys sorted, undefined dropped, arrays in order. */
248
+ declare function canonicalJson(value: unknown): string;
249
+ /** SHA-256 hex of a UTF-8 string. Pure, synchronous, runs anywhere (no crypto API needed). */
250
+ declare function sha256Hex(input: string): string;
251
+ /**
252
+ * Drift between clients. Computed, never authored: SHA-256 of the canonical JSON
253
+ * of the declaration as authored (keys sorted, extension fields included).
254
+ * Persisted as `ui_surface.content_hash` once that column exists.
255
+ */
256
+ declare function declarationHash(declaration: SurfaceDeclaration): string;
257
+
258
+ declare const VALUE_TYPES: readonly ["string", "number", "boolean", "object", "array", "document"];
259
+ declare const WRITE_MODES: readonly ["draft", "entity", "ui", "stream"];
260
+ declare const APPLY_POLICIES: readonly ["manual", "ask", "auto", "queued"];
261
+ declare const STREAM_OPS: readonly ["replace", "insert_before", "insert_after", "prepend", "append", "patch"];
262
+ declare const EXECUTION_MODES: readonly ["python-stream", "nextjs-stream", "browser-realtime", "local-runtime"];
263
+ declare const READINESS: readonly ["verified", "partial", "stub"];
264
+ declare const LIVE_SLOTS: readonly ["selection", "on-demand", "errors", "requests"];
265
+ declare const CLASSIFICATIONS: readonly ["ordinary", "secret", "credential"];
266
+ interface ValidateOptions {
267
+ /** Registered config namespaces; omitted = not checked. */
268
+ knownNamespaces?: ReadonlySet<string>;
269
+ /** Registered content-ir kind slugs; omitted = not checked. */
270
+ isKnownKind?: (slug: string) => boolean;
271
+ /** Names every declaration must expose unless `skipBaselineValues`. */
272
+ baselineNames?: readonly string[];
273
+ extensions?: readonly DeclarationExtension[];
274
+ }
275
+ declare function validateDeclarations(declarations: readonly ResolvedSurfaceDeclaration[], options?: ValidateOptions): DeclarationIssue[];
276
+ /**
277
+ * The runtime half: a loaded scope may carry only declared values. Returns one
278
+ * issue per undeclared key (and per `__item` value its item type does not declare).
279
+ */
280
+ declare function validateLoadedValues(declaration: Pick<ResolvedSurfaceDeclaration, "surfaceName" | "values" | "itemTypes">, loaded: Record<string, unknown>, options?: {
281
+ ignore?: readonly string[];
282
+ }): DeclarationIssue[];
283
+ /**
284
+ * Ownership: no `ui.ui_surface` row may exist without a declaring owner
285
+ * (CONTRACT §2.1a). `retired` rows (archived, not deleted) are exempt.
286
+ */
287
+ declare function findOrphanRows(rowNames: readonly string[], declaredNames: Iterable<string>, retired?: Iterable<string>): string[];
288
+
289
+ declare const RESERVED_GROUP_KEYS: {
290
+ readonly general: "general";
291
+ readonly baseline: "baseline";
292
+ readonly inheritedPrefix: "inherited:";
293
+ };
294
+ /** Group sortOrder bands. Curated groups author 0–899; the rest is reserved. */
295
+ declare const GENERAL_GROUP_ORDER = 850;
296
+ declare const INHERITED_GROUP_ORDER_BASE = 9000;
297
+ declare const BASELINE_GROUP_ORDER = 9900;
298
+ declare const DEFAULT_MAX_INHERITANCE_DEPTH = 3;
299
+ declare const DEFAULT_SENSITIVITY: Sensitivity;
300
+ declare function resolveSensitivity(value: Pick<DeclaredValue, "sensitivity">): Sensitivity;
301
+ type Resolved<D extends SurfaceDeclaration> = Omit<D, "values" | "groups"> & {
302
+ values: readonly (D["values"][number] & ResolvedValue)[];
303
+ groups: readonly ValueGroup[];
304
+ contentHash: string;
305
+ };
306
+ interface DeclarationRegistryOptions {
307
+ /** Generic values injected into every declaration unless `skipBaselineValues`. */
308
+ baselineValues?: readonly DeclaredValue[];
309
+ /** Value names only the platform writes; a declaration claiming one is refused. */
310
+ reservedValueNames?: readonly string[];
311
+ /** Write-target names only the platform writes. */
312
+ reservedWriteTargetNames?: readonly string[];
313
+ maxInheritanceDepth?: number;
314
+ }
315
+ interface DeclarationRegistry<D extends SurfaceDeclaration> {
316
+ /** Refuses a second declaration of the same surfaceName. */
317
+ register(declaration: D): void;
318
+ registerExtension(extension: DeclarationExtension<D>): void;
319
+ extensions(): readonly DeclarationExtension<D>[];
320
+ /** Declarations exactly as authored (inheritance unresolved, no baselines). */
321
+ raw(): readonly D[];
322
+ getRaw(surfaceName: string): D | undefined;
323
+ /** Parent chain, ROOT FIRST. Unknown surfaces return []. */
324
+ ancestry(surfaceName: string): string[];
325
+ /** Direct children (declarations naming it in `inheritsFrom`), in declaration order. */
326
+ children(surfaceName: string): string[];
327
+ /** Inheritance + baseline + groups resolved; provenance kept. */
328
+ all(): readonly Resolved<D>[];
329
+ get(surfaceName: string): Resolved<D> | undefined;
330
+ validate(options?: ValidateOptions): readonly DeclarationIssue[];
331
+ }
332
+ declare function createDeclarationRegistry<D extends SurfaceDeclaration>(options?: DeclarationRegistryOptions): DeclarationRegistry<D>;
333
+
334
+ export { APPLY_POLICIES, type ApplyPolicy, BASELINE_GROUP_ORDER, CLASSIFICATIONS, type Classification, type ConfigNamespaceDeclaration, DECLARATION_NAME_RE, DEFAULT_MAX_INHERITANCE_DEPTH, DEFAULT_SENSITIVITY, type DeclarationExtension, type DeclarationIssue, type DeclarationRegistry, type DeclarationRegistryOptions, type DeclaredValue, EXECUTION_MODES, type EvidenceSourceDeclaration, type ExecutionMode, type ExtensionRow, GENERAL_GROUP_ORDER, INHERITED_GROUP_ORDER_BASE, type ItemType, type Json, LIVE_SLOTS, type LiveSlot, type LiveValues, type OnDemandSection, type ParsedValueKey, QUALIFIED_VALUE_KEY_RE, type QualifiedValueKey, READINESS, RESERVED_GROUP_KEYS, type Readiness, type RecentRequest, type Resolved, type ResolvedItem, type ResolvedSurfaceDeclaration, type ResolvedValue, STREAM_OPS, SURFACE_NAME_RE, type Sensitivity, type StreamOp, type SurfaceDeclaration, VALUE_TYPES, type ValidateOptions, type ValidationContext, type ValueGroup, type ValueProvenance, type ValueType, WRITE_MODES, type WriteMode, type WriteTarget, canonicalJson, createDeclarationRegistry, declarationHash, findOrphanRows, parseQualifiedValueKey, qualifyValueKey, resolveSensitivity, sha256Hex, surfaceClientOf, validateDeclarations, validateLoadedValues };