@ai-matrx/alchemy 0.5.1 → 0.6.1
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 +21 -0
- package/dist/checks.cjs +249 -0
- package/dist/checks.cjs.map +1 -0
- package/dist/checks.d.cts +259 -0
- package/dist/checks.d.ts +259 -0
- package/dist/checks.js +226 -0
- package/dist/checks.js.map +1 -0
- package/dist/declare/schema.json +414 -0
- package/dist/declare-host.cjs +19 -0
- package/dist/declare-host.cjs.map +1 -0
- package/dist/declare-host.d.cts +78 -0
- package/dist/declare-host.d.ts +78 -0
- package/dist/declare-host.js +1 -0
- package/dist/declare-host.js.map +1 -0
- package/dist/declare.cjs +637 -0
- package/dist/declare.cjs.map +1 -0
- package/dist/declare.d.cts +334 -0
- package/dist/declare.d.ts +334 -0
- package/dist/declare.js +614 -0
- package/dist/declare.js.map +1 -0
- package/package.json +41 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.1 — 2026-09-26
|
|
4
|
+
|
|
5
|
+
`/checks` adds `renderSurfaceSyncStatements(plan)` (one statement per surface and table, so a caller can EXPLAIN each in a read-only transaction and prove the plan against a live schema with no write); `renderSurfaceSyncSql` joins them. With `schema.valueContract`, write-target rows also carry `patchable`, `approval_comparison`, `stream_ops` and `destination`, and value sensitivity is resolved with its defaults from the declaration itself.
|
|
6
|
+
|
|
7
|
+
### Consumer action
|
|
8
|
+
|
|
9
|
+
None required.
|
|
10
|
+
|
|
11
|
+
## 0.6.0 — 2026-09-26
|
|
12
|
+
|
|
13
|
+
Adds Declare (Matrx Alchemy ALC-14): what a screen holds moves into the package.
|
|
14
|
+
|
|
15
|
+
- `/declare` — the declaration types (`SurfaceDeclaration`, `DeclaredValue`, `WriteTarget`, `ItemType`, `Sensitivity`, live slots), `createDeclarationRegistry` (inheritance, baseline injection, provenance, group synthesis — the app registry's behaviour, ported), `validateDeclarations` (the surface checks), `validateLoadedValues` (a loaded value the surface never declared is an issue), `findOrphanRows`, qualified item keys (`table_row.status`), and `declarationHash` (SHA-256 of canonical JSON). Framework-neutral: no React, no agents. Agent fields are extension slots (`DeclarationExtension`).
|
|
16
|
+
- `/declare/host` — host-binding types only (`MountedSurface`, `ItemAnchor`, `InternalResolvedItem`).
|
|
17
|
+
- `/declare/schema.json` — the JSON Schema, generated from the types (`pnpm generate:schema`; `check:package` fails when stale). Server-side clients (SMS, voice) validate their JSON declarations against it.
|
|
18
|
+
- `/checks` — the ONE surface sync: `planSurfaceSync` (rows for every mirror table) and `renderSurfaceSyncSql`. Governance columns (`organization_id`, `visibility`) are insert-only; a conflict never rewrites them. `description`, `execution_mode` and `client_name` are now owned by the declaration. Columns from the ALC-14 migration are emitted only when the caller passes `schema`.
|
|
19
|
+
|
|
20
|
+
### Consumer action
|
|
21
|
+
|
|
22
|
+
None required for existing entries. A host that declares surfaces imports the types, registry and validation from `@ai-matrx/alchemy/declare` and runs every sync through `@ai-matrx/alchemy/checks`; its declarations must carry `client`, `executionMode` and `description`, and value sensitivity nests under `sensitivity`.
|
|
23
|
+
|
|
3
24
|
## 0.5.1
|
|
4
25
|
|
|
5
26
|
Automatic changed-only republish (docs/metadata drift since the last tag — see
|
package/dist/checks.cjs
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/checks.ts
|
|
21
|
+
var checks_exports = {};
|
|
22
|
+
__export(checks_exports, {
|
|
23
|
+
GOVERNANCE_COLUMNS: () => GOVERNANCE_COLUMNS,
|
|
24
|
+
conflictUpdateColumns: () => conflictUpdateColumns,
|
|
25
|
+
planColumns: () => planColumns,
|
|
26
|
+
planSurfaceSync: () => planSurfaceSync,
|
|
27
|
+
renderSurfaceSyncSql: () => renderSurfaceSyncSql,
|
|
28
|
+
renderSurfaceSyncStatements: () => renderSurfaceSyncStatements,
|
|
29
|
+
sqlLiteral: () => sqlLiteral
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(checks_exports);
|
|
32
|
+
|
|
33
|
+
// src/declare/keys.ts
|
|
34
|
+
function surfaceClientOf(surfaceName) {
|
|
35
|
+
return surfaceName.split("/")[0] ?? "";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/declare/registry.ts
|
|
39
|
+
var DEFAULT_SENSITIVITY = Object.freeze({
|
|
40
|
+
exportable: true,
|
|
41
|
+
classification: "ordinary",
|
|
42
|
+
includedByDefault: true
|
|
43
|
+
});
|
|
44
|
+
function resolveSensitivity(value) {
|
|
45
|
+
return {
|
|
46
|
+
exportable: value.sensitivity?.exportable ?? DEFAULT_SENSITIVITY.exportable,
|
|
47
|
+
classification: value.sensitivity?.classification ?? DEFAULT_SENSITIVITY.classification,
|
|
48
|
+
includedByDefault: value.sensitivity?.includedByDefault ?? DEFAULT_SENSITIVITY.includedByDefault
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/checks/sync.ts
|
|
53
|
+
var GOVERNANCE_COLUMNS = ["organization_id", "visibility"];
|
|
54
|
+
function childKey(schema) {
|
|
55
|
+
return schema?.itemType ? ["surface_name", "item_type", "name"] : ["surface_name", "name"];
|
|
56
|
+
}
|
|
57
|
+
function planSurfaceSync(declarations, options) {
|
|
58
|
+
const { organizationId, syncedFrom, schema } = options;
|
|
59
|
+
const syncedBy = options.syncedBy ?? null;
|
|
60
|
+
const provenance = { synced_by: syncedBy, synced_from: syncedFrom };
|
|
61
|
+
const governance = { organization_id: organizationId, visibility: "public" };
|
|
62
|
+
const surfaces = [];
|
|
63
|
+
const values = [];
|
|
64
|
+
const targets = [];
|
|
65
|
+
const itemTypes = [];
|
|
66
|
+
const extensionTables = /* @__PURE__ */ new Map();
|
|
67
|
+
for (const d of declarations) {
|
|
68
|
+
const urlPattern = d.urlPattern?.trim() || options.resolveUrlPattern?.(d) || null;
|
|
69
|
+
const intro = d.intro?.trim() || null;
|
|
70
|
+
const parent = d.inheritsFrom ?? null;
|
|
71
|
+
const client = surfaceClientOf(d.surfaceName);
|
|
72
|
+
const owned = {
|
|
73
|
+
client_name: client,
|
|
74
|
+
execution_mode: d.executionMode,
|
|
75
|
+
description: d.description,
|
|
76
|
+
label: d.label,
|
|
77
|
+
value_groups: d.groups ?? [],
|
|
78
|
+
readiness: d.readiness,
|
|
79
|
+
readiness_note: d.readinessNote?.trim() || null,
|
|
80
|
+
...schema?.contentHash ? { content_hash: d.contentHash } : {}
|
|
81
|
+
};
|
|
82
|
+
const claimed = {
|
|
83
|
+
...d.overlayId ? { overlay_id: d.overlayId } : {},
|
|
84
|
+
...urlPattern ? { url_pattern: urlPattern } : {},
|
|
85
|
+
...intro ? { intro } : {},
|
|
86
|
+
...parent ? { parent_surface_name: parent } : {}
|
|
87
|
+
};
|
|
88
|
+
surfaces.push({
|
|
89
|
+
name: d.surfaceName,
|
|
90
|
+
insert: {
|
|
91
|
+
name: d.surfaceName,
|
|
92
|
+
...owned,
|
|
93
|
+
overlay_id: d.overlayId ?? null,
|
|
94
|
+
url_pattern: urlPattern,
|
|
95
|
+
intro,
|
|
96
|
+
parent_surface_name: parent
|
|
97
|
+
},
|
|
98
|
+
update: { ...owned, ...claimed }
|
|
99
|
+
});
|
|
100
|
+
for (const v of d.values) {
|
|
101
|
+
values.push({
|
|
102
|
+
...governance,
|
|
103
|
+
surface_name: d.surfaceName,
|
|
104
|
+
...schema?.itemType ? { item_type: "" } : {},
|
|
105
|
+
name: v.name,
|
|
106
|
+
label: v.label,
|
|
107
|
+
description: v.description,
|
|
108
|
+
value_type: v.valueType,
|
|
109
|
+
always_available: v.alwaysAvailable,
|
|
110
|
+
typical_char_count: v.typicalCharCount,
|
|
111
|
+
sort_order: v.sortOrder ?? 1e3,
|
|
112
|
+
auto_context: v.autoContext ?? true,
|
|
113
|
+
group_key: v.groupKey ?? v.group ?? "general",
|
|
114
|
+
...schema?.valueContract ? {
|
|
115
|
+
exportable: resolveSensitivity(v).exportable,
|
|
116
|
+
classification: resolveSensitivity(v).classification,
|
|
117
|
+
included_by_default: resolveSensitivity(v).includedByDefault,
|
|
118
|
+
kind_key: v.valueKind ?? null,
|
|
119
|
+
live_slot: v.liveSlot ?? null,
|
|
120
|
+
role: v.role ?? "data"
|
|
121
|
+
} : {},
|
|
122
|
+
...provenance
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
for (const t of d.writeTargets ?? []) {
|
|
126
|
+
targets.push({
|
|
127
|
+
...governance,
|
|
128
|
+
surface_name: d.surfaceName,
|
|
129
|
+
...schema?.itemType ? { item_type: t.itemType ?? "" } : {},
|
|
130
|
+
name: t.name,
|
|
131
|
+
label: t.label,
|
|
132
|
+
description: t.description,
|
|
133
|
+
value_type: t.valueType,
|
|
134
|
+
mode: t.mode,
|
|
135
|
+
updates_value: t.updatesValue ?? null,
|
|
136
|
+
group_key: t.group ?? "general",
|
|
137
|
+
sort_order: t.sortOrder ?? 1e3,
|
|
138
|
+
apply_policy: t.applyPolicy ?? "manual",
|
|
139
|
+
kind_key: t.valueKind ?? null,
|
|
140
|
+
...schema?.valueContract ? {
|
|
141
|
+
patchable: t.patchable ?? false,
|
|
142
|
+
approval_comparison: t.approvalComparison ?? null,
|
|
143
|
+
stream_ops: t.streamOps ? [...t.streamOps] : null,
|
|
144
|
+
destination: t.destination ?? false
|
|
145
|
+
} : {},
|
|
146
|
+
...provenance
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
if (schema?.itemType) {
|
|
150
|
+
for (const [position, item] of (d.itemTypes ?? []).entries()) {
|
|
151
|
+
itemTypes.push({
|
|
152
|
+
...governance,
|
|
153
|
+
surface_name: d.surfaceName,
|
|
154
|
+
name: item.name,
|
|
155
|
+
label: item.label,
|
|
156
|
+
description: item.description,
|
|
157
|
+
identity: [...item.identity],
|
|
158
|
+
levels: item.levels ? [...item.levels] : null,
|
|
159
|
+
entity_type: item.entityType ?? null,
|
|
160
|
+
sort_order: position,
|
|
161
|
+
...provenance
|
|
162
|
+
});
|
|
163
|
+
for (const v of item.values) {
|
|
164
|
+
values.push({
|
|
165
|
+
...governance,
|
|
166
|
+
surface_name: d.surfaceName,
|
|
167
|
+
item_type: item.name,
|
|
168
|
+
name: v.name,
|
|
169
|
+
label: v.label,
|
|
170
|
+
description: v.description,
|
|
171
|
+
value_type: v.valueType,
|
|
172
|
+
always_available: v.alwaysAvailable,
|
|
173
|
+
typical_char_count: v.typicalCharCount,
|
|
174
|
+
sort_order: v.sortOrder ?? 1e3,
|
|
175
|
+
auto_context: v.autoContext ?? true,
|
|
176
|
+
group_key: v.group ?? "general",
|
|
177
|
+
...provenance
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const extension of options.extensions ?? []) {
|
|
183
|
+
for (const entry of extension.toRows?.(d) ?? []) {
|
|
184
|
+
const plan = extensionTables.get(entry.table) ?? {
|
|
185
|
+
table: entry.table,
|
|
186
|
+
conflict: entry.conflict,
|
|
187
|
+
insertOnly: GOVERNANCE_COLUMNS,
|
|
188
|
+
rows: []
|
|
189
|
+
};
|
|
190
|
+
plan.rows.push({ ...governance, ...entry.row, ...provenance });
|
|
191
|
+
extensionTables.set(entry.table, plan);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const tables = [
|
|
196
|
+
{ table: "ui.ui_surface_value", conflict: childKey(schema), insertOnly: GOVERNANCE_COLUMNS, rows: values },
|
|
197
|
+
{ table: "ui.ui_surface_write_target", conflict: childKey(schema), insertOnly: GOVERNANCE_COLUMNS, rows: targets },
|
|
198
|
+
...schema?.itemType ? [{ table: "ui.ui_surface_item_type", conflict: ["surface_name", "name"], insertOnly: GOVERNANCE_COLUMNS, rows: itemTypes }] : [],
|
|
199
|
+
...extensionTables.values()
|
|
200
|
+
];
|
|
201
|
+
return { surfaces, tables: tables.filter((table) => table.rows.length > 0) };
|
|
202
|
+
}
|
|
203
|
+
function planColumns(table) {
|
|
204
|
+
const columns = [];
|
|
205
|
+
for (const row of table.rows) for (const key of Object.keys(row)) if (!columns.includes(key)) columns.push(key);
|
|
206
|
+
return columns;
|
|
207
|
+
}
|
|
208
|
+
function conflictUpdateColumns(table) {
|
|
209
|
+
return planColumns(table).filter((c) => !table.conflict.includes(c) && !table.insertOnly.includes(c));
|
|
210
|
+
}
|
|
211
|
+
function sqlLiteral(value) {
|
|
212
|
+
if (value === null || value === void 0) return "NULL";
|
|
213
|
+
if (typeof value === "boolean" || typeof value === "number") return String(value);
|
|
214
|
+
if (typeof value === "string") return `'${value.replace(/'/g, "''")}'`;
|
|
215
|
+
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
|
|
216
|
+
return `ARRAY[${value.map((entry) => sqlLiteral(entry)).join(", ")}]::text[]`;
|
|
217
|
+
}
|
|
218
|
+
return `'${JSON.stringify(value).replace(/'/g, "''")}'::jsonb`;
|
|
219
|
+
}
|
|
220
|
+
function renderSurfaceSyncStatements(plan) {
|
|
221
|
+
const statements = [];
|
|
222
|
+
if (plan.surfaces.length > 0) {
|
|
223
|
+
const insertColumns = Object.keys(plan.surfaces[0].insert);
|
|
224
|
+
statements.push(
|
|
225
|
+
`INSERT INTO ui.ui_surface (${insertColumns.join(", ")}) VALUES
|
|
226
|
+
${plan.surfaces.map((s) => `(${insertColumns.map((c) => sqlLiteral(s.insert[c])).join(", ")})`).join(",\n")}
|
|
227
|
+
ON CONFLICT (name) DO NOTHING`
|
|
228
|
+
);
|
|
229
|
+
for (const s of plan.surfaces) {
|
|
230
|
+
statements.push(
|
|
231
|
+
`UPDATE ui.ui_surface SET ${Object.entries(s.update).map(([c, v]) => `${c} = ${sqlLiteral(v)}`).join(", ")}, updated_at = now() WHERE name = ${sqlLiteral(s.name)}`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
for (const table of plan.tables) {
|
|
236
|
+
const columns = planColumns(table);
|
|
237
|
+
const sets = conflictUpdateColumns(table).map((c) => `${c} = EXCLUDED.${c}`);
|
|
238
|
+
statements.push(
|
|
239
|
+
`INSERT INTO ${table.table} (${columns.join(", ")}) VALUES
|
|
240
|
+
${table.rows.map((row) => `(${columns.map((c) => sqlLiteral(row[c])).join(", ")})`).join(",\n")}
|
|
241
|
+
ON CONFLICT (${table.conflict.join(", ")}) DO UPDATE SET ${[...sets, "updated_at = now()"].join(", ")}`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
return statements;
|
|
245
|
+
}
|
|
246
|
+
function renderSurfaceSyncSql(plan) {
|
|
247
|
+
return renderSurfaceSyncStatements(plan).map((statement) => `${statement};`).join("\n\n");
|
|
248
|
+
}
|
|
249
|
+
//# sourceMappingURL=checks.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/checks.ts","../src/declare/keys.ts","../src/declare/registry.ts","../src/checks/sync.ts"],"sourcesContent":["/**\n * `@ai-matrx/alchemy/checks` — the ONE surface sync (CONTRACT §2.7): the row plan\n * every sync path executes, and its SQL rendering. Pure; no database client.\n */\nexport {\n GOVERNANCE_COLUMNS,\n conflictUpdateColumns,\n planColumns,\n planSurfaceSync,\n renderSurfaceSyncSql,\n renderSurfaceSyncStatements,\n sqlLiteral,\n type SurfaceRowPlan,\n type SurfaceSyncPlan,\n type SurfaceSyncPlanOptions,\n type SyncSchema,\n type SyncTablePlan,\n} from \"./checks/sync\";\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","/**\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","/**\n * THE ONE SYNC (CONTRACT §2.7 \"One sync path\", chair ruling B1).\n *\n * `planSurfaceSync` maps resolved declarations onto the `ui` mirror rows; every\n * sync path (the SQL emitter and the admin sync service) executes this plan and\n * builds no rows of its own. Governance columns (`organization_id`,\n * `visibility`) are INSERT-ONLY (chair ruling N5): a conflict never rewrites them.\n *\n * Schema generations: the columns added by the ALC-14 migration (item_type,\n * sensitivity, live slots, content_hash) are emitted only when the caller says\n * that migration is live (`schema`), so no emitter ever writes a column — or\n * upserts against a key — the database does not have yet.\n */\nimport { resolveSensitivity, type Resolved } from \"../declare/registry\";\nimport { surfaceClientOf } from \"../declare/keys\";\nimport type { DeclarationExtension, Json, SurfaceDeclaration } from \"../declare/types\";\n\nexport const GOVERNANCE_COLUMNS = [\"organization_id\", \"visibility\"] as const;\n\nexport interface SyncSchema {\n /** `ui_surface_value/write_target.item_type` exists and the conflict key includes it (re-key step 1). */\n itemType?: boolean;\n /** Sensitivity, kind, live slot and role columns exist on `ui_surface_value`. */\n valueContract?: boolean;\n /** `ui_surface.content_hash` exists. */\n contentHash?: boolean;\n}\n\nexport interface SurfaceSyncPlanOptions<D extends SurfaceDeclaration> {\n organizationId: string;\n syncedFrom: string;\n syncedBy?: string | null;\n /** The address the host derives for a declaration without `urlPattern`. */\n resolveUrlPattern?: (declaration: Resolved<D>) => string | undefined;\n extensions?: readonly DeclarationExtension<D>[];\n schema?: SyncSchema;\n}\n\nexport interface SurfaceRowPlan {\n name: string;\n /** Written only when the row does not exist yet. */\n insert: Record<string, Json>;\n /** Written on every sync (code owns these columns). */\n update: Record<string, Json>;\n}\n\nexport interface SyncTablePlan {\n table: string;\n /** The ON CONFLICT target (a unique index or primary key on exactly these columns). */\n conflict: readonly string[];\n /** Columns set on insert and never on conflict. */\n insertOnly: readonly string[];\n rows: Record<string, Json>[];\n}\n\nexport interface SurfaceSyncPlan {\n surfaces: SurfaceRowPlan[];\n tables: SyncTablePlan[];\n}\n\nfunction childKey(schema: SyncSchema | undefined): readonly string[] {\n return schema?.itemType ? [\"surface_name\", \"item_type\", \"name\"] : [\"surface_name\", \"name\"];\n}\n\nexport function planSurfaceSync<D extends SurfaceDeclaration>(\n declarations: readonly Resolved<D>[],\n options: SurfaceSyncPlanOptions<D>,\n): SurfaceSyncPlan {\n const { organizationId, syncedFrom, schema } = options;\n const syncedBy = options.syncedBy ?? null;\n const provenance = { synced_by: syncedBy, synced_from: syncedFrom };\n const governance = { organization_id: organizationId, visibility: \"public\" };\n const surfaces: SurfaceRowPlan[] = [];\n const values: Record<string, Json>[] = [];\n const targets: Record<string, Json>[] = [];\n const itemTypes: Record<string, Json>[] = [];\n const extensionTables = new Map<string, SyncTablePlan>();\n\n for (const d of declarations) {\n const urlPattern = d.urlPattern?.trim() || options.resolveUrlPattern?.(d) || null;\n const intro = d.intro?.trim() || null;\n const parent = d.inheritsFrom ?? null;\n const client = surfaceClientOf(d.surfaceName);\n const owned: Record<string, Json> = {\n client_name: client,\n execution_mode: d.executionMode,\n description: d.description,\n label: d.label,\n value_groups: (d.groups ?? []) as unknown as Json,\n readiness: d.readiness,\n readiness_note: d.readinessNote?.trim() || null,\n ...(schema?.contentHash ? { content_hash: d.contentHash } : {}),\n };\n // A declaration that does not claim these never clears a DB-authored value.\n const claimed: Record<string, Json> = {\n ...(d.overlayId ? { overlay_id: d.overlayId } : {}),\n ...(urlPattern ? { url_pattern: urlPattern } : {}),\n ...(intro ? { intro } : {}),\n ...(parent ? { parent_surface_name: parent } : {}),\n };\n surfaces.push({\n name: d.surfaceName,\n insert: {\n name: d.surfaceName,\n ...owned,\n overlay_id: d.overlayId ?? null,\n url_pattern: urlPattern,\n intro,\n parent_surface_name: parent,\n },\n update: { ...owned, ...claimed },\n });\n\n for (const v of d.values) {\n values.push({\n ...governance,\n surface_name: d.surfaceName,\n ...(schema?.itemType ? { item_type: \"\" } : {}),\n name: v.name,\n label: v.label,\n description: v.description,\n value_type: v.valueType,\n always_available: v.alwaysAvailable,\n typical_char_count: v.typicalCharCount,\n sort_order: v.sortOrder ?? 1000,\n auto_context: v.autoContext ?? true,\n group_key: v.groupKey ?? v.group ?? \"general\",\n ...(schema?.valueContract\n ? {\n exportable: resolveSensitivity(v).exportable,\n classification: resolveSensitivity(v).classification,\n included_by_default: resolveSensitivity(v).includedByDefault,\n kind_key: v.valueKind ?? null,\n live_slot: v.liveSlot ?? null,\n role: v.role ?? \"data\",\n }\n : {}),\n ...provenance,\n });\n }\n\n for (const t of d.writeTargets ?? []) {\n targets.push({\n ...governance,\n surface_name: d.surfaceName,\n ...(schema?.itemType ? { item_type: t.itemType ?? \"\" } : {}),\n name: t.name,\n label: t.label,\n description: t.description,\n value_type: t.valueType,\n mode: t.mode,\n updates_value: t.updatesValue ?? null,\n group_key: t.group ?? \"general\",\n sort_order: t.sortOrder ?? 1000,\n apply_policy: t.applyPolicy ?? \"manual\",\n kind_key: t.valueKind ?? null,\n ...(schema?.valueContract\n ? {\n patchable: t.patchable ?? false,\n approval_comparison: t.approvalComparison ?? null,\n stream_ops: t.streamOps ? [...t.streamOps] : null,\n destination: t.destination ?? false,\n }\n : {}),\n ...provenance,\n });\n }\n\n if (schema?.itemType) {\n for (const [position, item] of (d.itemTypes ?? []).entries()) {\n itemTypes.push({\n ...governance,\n surface_name: d.surfaceName,\n name: item.name,\n label: item.label,\n description: item.description,\n identity: [...item.identity],\n levels: item.levels ? [...item.levels] : null,\n entity_type: item.entityType ?? null,\n sort_order: position,\n ...provenance,\n });\n for (const v of item.values) {\n values.push({\n ...governance,\n surface_name: d.surfaceName,\n item_type: item.name,\n name: v.name,\n label: v.label,\n description: v.description,\n value_type: v.valueType,\n always_available: v.alwaysAvailable,\n typical_char_count: v.typicalCharCount,\n sort_order: v.sortOrder ?? 1000,\n auto_context: v.autoContext ?? true,\n group_key: v.group ?? \"general\",\n ...provenance,\n });\n }\n }\n }\n\n for (const extension of options.extensions ?? []) {\n for (const entry of extension.toRows?.(d as unknown as D) ?? []) {\n const plan = extensionTables.get(entry.table) ?? {\n table: entry.table,\n conflict: entry.conflict,\n insertOnly: GOVERNANCE_COLUMNS,\n rows: [],\n };\n plan.rows.push({ ...governance, ...entry.row, ...provenance });\n extensionTables.set(entry.table, plan);\n }\n }\n }\n\n const tables: SyncTablePlan[] = [\n { table: \"ui.ui_surface_value\", conflict: childKey(schema), insertOnly: GOVERNANCE_COLUMNS, rows: values },\n { table: \"ui.ui_surface_write_target\", conflict: childKey(schema), insertOnly: GOVERNANCE_COLUMNS, rows: targets },\n ...(schema?.itemType\n ? [{ table: \"ui.ui_surface_item_type\", conflict: [\"surface_name\", \"name\"], insertOnly: GOVERNANCE_COLUMNS, rows: itemTypes }]\n : []),\n ...extensionTables.values(),\n ];\n return { surfaces, tables: tables.filter((table) => table.rows.length > 0) };\n}\n\n/** Every column a table's rows carry, in first-seen order. */\nexport function planColumns(table: SyncTablePlan): string[] {\n const columns: string[] = [];\n for (const row of table.rows) for (const key of Object.keys(row)) if (!columns.includes(key)) columns.push(key);\n return columns;\n}\n\n/** Columns a conflict rewrites: everything except the key and the insert-only set. */\nexport function conflictUpdateColumns(table: SyncTablePlan): string[] {\n return planColumns(table).filter((c) => !table.conflict.includes(c) && !table.insertOnly.includes(c));\n}\n\nexport function sqlLiteral(value: Json | undefined): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"boolean\" || typeof value === \"number\") return String(value);\n if (typeof value === \"string\") return `'${value.replace(/'/g, \"''\")}'`;\n if (Array.isArray(value) && value.every((entry) => typeof entry === \"string\")) {\n return `ARRAY[${value.map((entry) => sqlLiteral(entry)).join(\", \")}]::text[]`;\n }\n return `'${JSON.stringify(value).replace(/'/g, \"''\")}'::jsonb`;\n}\n\n/**\n * The plan as SQL statements, one per entry: surface insert, one UPDATE per\n * surface, one upsert per table. Callers may run them, or EXPLAIN each one in a\n * read-only transaction to prove the plan against a live schema with no write.\n */\nexport function renderSurfaceSyncStatements(plan: SurfaceSyncPlan): string[] {\n const statements: string[] = [];\n if (plan.surfaces.length > 0) {\n const insertColumns = Object.keys(plan.surfaces[0]!.insert);\n statements.push(\n `INSERT INTO ui.ui_surface (${insertColumns.join(\", \")}) VALUES\\n${plan.surfaces\n .map((s) => `(${insertColumns.map((c) => sqlLiteral(s.insert[c])).join(\", \")})`)\n .join(\",\\n\")}\\nON CONFLICT (name) DO NOTHING`,\n );\n for (const s of plan.surfaces) {\n statements.push(\n `UPDATE ui.ui_surface SET ${Object.entries(s.update)\n .map(([c, v]) => `${c} = ${sqlLiteral(v)}`)\n .join(\", \")}, updated_at = now() WHERE name = ${sqlLiteral(s.name)}`,\n );\n }\n }\n for (const table of plan.tables) {\n const columns = planColumns(table);\n const sets = conflictUpdateColumns(table).map((c) => `${c} = EXCLUDED.${c}`);\n statements.push(\n `INSERT INTO ${table.table} (${columns.join(\", \")}) VALUES\\n${table.rows\n .map((row) => `(${columns.map((c) => sqlLiteral(row[c])).join(\", \")})`)\n .join(\",\\n\")}\\nON CONFLICT (${table.conflict.join(\", \")}) DO UPDATE SET ${[...sets, \"updated_at = now()\"].join(\", \")}`,\n );\n }\n return statements;\n}\n\n/** The plan as one SQL script (governance columns insert-only). */\nexport function renderSurfaceSyncSql(plan: SurfaceSyncPlan): string {\n return renderSurfaceSyncStatements(plan)\n .map((statement) => `${statement};`)\n .join(\"\\n\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8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AE,KAAK,IAAI,CAAC,GAAG,EAC9E,KAAK,KAAK,CAAC;AAAA;AAAA,IAChB;AACA,eAAW,KAAK,KAAK,UAAU;AAC7B,iBAAW;AAAA,QACT,4BAA4B,OAAO,QAAQ,EAAE,MAAM,EAChD,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,WAAW,CAAC,CAAC,EAAE,EACzC,KAAK,IAAI,CAAC,qCAAqC,WAAW,EAAE,IAAI,CAAC;AAAA,MACtE;AAAA,IACF;AAAA,EACF;AACA,aAAW,SAAS,KAAK,QAAQ;AAC/B,UAAM,UAAU,YAAY,KAAK;AACjC,UAAM,OAAO,sBAAsB,KAAK,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,eAAe,CAAC,EAAE;AAC3E,eAAW;AAAA,MACT,eAAe,MAAM,KAAK,KAAK,QAAQ,KAAK,IAAI,CAAC;AAAA,EAAa,MAAM,KACjE,IAAI,CAAC,QAAQ,IAAI,QAAQ,IAAI,CAAC,MAAM,WAAW,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,GAAG,EACrE,KAAK,KAAK,CAAC;AAAA,eAAkB,MAAM,SAAS,KAAK,IAAI,CAAC,mBAAmB,CAAC,GAAG,MAAM,oBAAoB,EAAE,KAAK,IAAI,CAAC;AAAA,IACxH;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,qBAAqB,MAA+B;AAClE,SAAO,4BAA4B,IAAI,EACpC,IAAI,CAAC,cAAc,GAAG,SAAS,GAAG,EAClC,KAAK,MAAM;AAChB;","names":[]}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matrx Alchemy — Declare types (CONTRACT §2.1).
|
|
3
|
+
*
|
|
4
|
+
* A declaration is plain JSON 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
|
+
type Resolved<D extends SurfaceDeclaration> = Omit<D, "values" | "groups"> & {
|
|
188
|
+
values: readonly (D["values"][number] & ResolvedValue)[];
|
|
189
|
+
groups: readonly ValueGroup[];
|
|
190
|
+
contentHash: string;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* THE ONE SYNC (CONTRACT §2.7 "One sync path", chair ruling B1).
|
|
195
|
+
*
|
|
196
|
+
* `planSurfaceSync` maps resolved declarations onto the `ui` mirror rows; every
|
|
197
|
+
* sync path (the SQL emitter and the admin sync service) executes this plan and
|
|
198
|
+
* builds no rows of its own. Governance columns (`organization_id`,
|
|
199
|
+
* `visibility`) are INSERT-ONLY (chair ruling N5): a conflict never rewrites them.
|
|
200
|
+
*
|
|
201
|
+
* Schema generations: the columns added by the ALC-14 migration (item_type,
|
|
202
|
+
* sensitivity, live slots, content_hash) are emitted only when the caller says
|
|
203
|
+
* that migration is live (`schema`), so no emitter ever writes a column — or
|
|
204
|
+
* upserts against a key — the database does not have yet.
|
|
205
|
+
*/
|
|
206
|
+
|
|
207
|
+
declare const GOVERNANCE_COLUMNS: readonly ["organization_id", "visibility"];
|
|
208
|
+
interface SyncSchema {
|
|
209
|
+
/** `ui_surface_value/write_target.item_type` exists and the conflict key includes it (re-key step 1). */
|
|
210
|
+
itemType?: boolean;
|
|
211
|
+
/** Sensitivity, kind, live slot and role columns exist on `ui_surface_value`. */
|
|
212
|
+
valueContract?: boolean;
|
|
213
|
+
/** `ui_surface.content_hash` exists. */
|
|
214
|
+
contentHash?: boolean;
|
|
215
|
+
}
|
|
216
|
+
interface SurfaceSyncPlanOptions<D extends SurfaceDeclaration> {
|
|
217
|
+
organizationId: string;
|
|
218
|
+
syncedFrom: string;
|
|
219
|
+
syncedBy?: string | null;
|
|
220
|
+
/** The address the host derives for a declaration without `urlPattern`. */
|
|
221
|
+
resolveUrlPattern?: (declaration: Resolved<D>) => string | undefined;
|
|
222
|
+
extensions?: readonly DeclarationExtension<D>[];
|
|
223
|
+
schema?: SyncSchema;
|
|
224
|
+
}
|
|
225
|
+
interface SurfaceRowPlan {
|
|
226
|
+
name: string;
|
|
227
|
+
/** Written only when the row does not exist yet. */
|
|
228
|
+
insert: Record<string, Json>;
|
|
229
|
+
/** Written on every sync (code owns these columns). */
|
|
230
|
+
update: Record<string, Json>;
|
|
231
|
+
}
|
|
232
|
+
interface SyncTablePlan {
|
|
233
|
+
table: string;
|
|
234
|
+
/** The ON CONFLICT target (a unique index or primary key on exactly these columns). */
|
|
235
|
+
conflict: readonly string[];
|
|
236
|
+
/** Columns set on insert and never on conflict. */
|
|
237
|
+
insertOnly: readonly string[];
|
|
238
|
+
rows: Record<string, Json>[];
|
|
239
|
+
}
|
|
240
|
+
interface SurfaceSyncPlan {
|
|
241
|
+
surfaces: SurfaceRowPlan[];
|
|
242
|
+
tables: SyncTablePlan[];
|
|
243
|
+
}
|
|
244
|
+
declare function planSurfaceSync<D extends SurfaceDeclaration>(declarations: readonly Resolved<D>[], options: SurfaceSyncPlanOptions<D>): SurfaceSyncPlan;
|
|
245
|
+
/** Every column a table's rows carry, in first-seen order. */
|
|
246
|
+
declare function planColumns(table: SyncTablePlan): string[];
|
|
247
|
+
/** Columns a conflict rewrites: everything except the key and the insert-only set. */
|
|
248
|
+
declare function conflictUpdateColumns(table: SyncTablePlan): string[];
|
|
249
|
+
declare function sqlLiteral(value: Json | undefined): string;
|
|
250
|
+
/**
|
|
251
|
+
* The plan as SQL statements, one per entry: surface insert, one UPDATE per
|
|
252
|
+
* surface, one upsert per table. Callers may run them, or EXPLAIN each one in a
|
|
253
|
+
* read-only transaction to prove the plan against a live schema with no write.
|
|
254
|
+
*/
|
|
255
|
+
declare function renderSurfaceSyncStatements(plan: SurfaceSyncPlan): string[];
|
|
256
|
+
/** The plan as one SQL script (governance columns insert-only). */
|
|
257
|
+
declare function renderSurfaceSyncSql(plan: SurfaceSyncPlan): string;
|
|
258
|
+
|
|
259
|
+
export { GOVERNANCE_COLUMNS, type SurfaceRowPlan, type SurfaceSyncPlan, type SurfaceSyncPlanOptions, type SyncSchema, type SyncTablePlan, conflictUpdateColumns, planColumns, planSurfaceSync, renderSurfaceSyncSql, renderSurfaceSyncStatements, sqlLiteral };
|