@ai-matrx/alchemy 0.8.59 → 0.9.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +2 -0
  3. package/dist/actions.cjs +1 -1
  4. package/dist/actions.cjs.map +1 -1
  5. package/dist/actions.d.cts +300 -3
  6. package/dist/actions.d.ts +300 -3
  7. package/dist/actions.js +1 -1
  8. package/dist/actions.js.map +1 -1
  9. package/dist/checks.cjs +1 -1
  10. package/dist/checks.cjs.map +1 -1
  11. package/dist/checks.d.cts +22 -1
  12. package/dist/checks.d.ts +22 -1
  13. package/dist/checks.js +2 -2
  14. package/dist/checks.js.map +1 -1
  15. package/dist/core.d.cts +141 -26
  16. package/dist/core.d.ts +141 -26
  17. package/dist/declare.cjs +1 -1
  18. package/dist/declare.cjs.map +1 -1
  19. package/dist/declare.d.cts +12 -4
  20. package/dist/declare.d.ts +12 -4
  21. package/dist/declare.js +1 -1
  22. package/dist/declare.js.map +1 -1
  23. package/dist/index.d.cts +141 -26
  24. package/dist/index.d.ts +141 -26
  25. package/dist/menu.cjs +1 -1
  26. package/dist/menu.cjs.map +1 -1
  27. package/dist/menu.d.cts +109 -2
  28. package/dist/menu.d.ts +109 -2
  29. package/dist/menu.js +1 -1
  30. package/dist/menu.js.map +1 -1
  31. package/dist/operate-server.d.cts +6 -0
  32. package/dist/operate-server.d.ts +6 -0
  33. package/dist/operate.d.cts +141 -26
  34. package/dist/operate.d.ts +141 -26
  35. package/dist/ports.cjs.map +1 -1
  36. package/dist/ports.d.cts +116 -1
  37. package/dist/ports.d.ts +116 -1
  38. package/dist/react-bar.cjs +2 -2
  39. package/dist/react-bar.cjs.map +1 -1
  40. package/dist/react-bar.d.cts +4 -2
  41. package/dist/react-bar.d.ts +4 -2
  42. package/dist/react-bar.js +2 -2
  43. package/dist/react-bar.js.map +1 -1
  44. package/dist/react-host.d.cts +124 -3
  45. package/dist/react-host.d.ts +124 -3
  46. package/dist/react-menu.cjs +2 -2
  47. package/dist/react-menu.cjs.map +1 -1
  48. package/dist/react-menu.d.cts +20 -4
  49. package/dist/react-menu.d.ts +20 -4
  50. package/dist/react-menu.js +2 -2
  51. package/dist/react-menu.js.map +1 -1
  52. package/dist/react-overflow.cjs +2 -2
  53. package/dist/react-overflow.cjs.map +1 -1
  54. package/dist/react-overflow.d.cts +109 -2
  55. package/dist/react-overflow.d.ts +109 -2
  56. package/dist/react-overflow.js +2 -2
  57. package/dist/react-overflow.js.map +1 -1
  58. package/dist/react-palette.cjs +1 -1
  59. package/dist/react-palette.cjs.map +1 -1
  60. package/dist/react-palette.d.cts +4 -2
  61. package/dist/react-palette.d.ts +4 -2
  62. package/dist/react-palette.js +1 -1
  63. package/dist/react-palette.js.map +1 -1
  64. package/dist/react-selection.cjs +2 -2
  65. package/dist/react-selection.cjs.map +1 -1
  66. package/dist/react-selection.d.cts +4 -2
  67. package/dist/react-selection.d.ts +4 -2
  68. package/dist/react-selection.js +2 -2
  69. package/dist/react-selection.js.map +1 -1
  70. package/dist/react-sheet.cjs +2 -2
  71. package/dist/react-sheet.cjs.map +1 -1
  72. package/dist/react-sheet.d.cts +4 -2
  73. package/dist/react-sheet.d.ts +4 -2
  74. package/dist/react-sheet.js +2 -2
  75. package/dist/react-sheet.js.map +1 -1
  76. package/package.json +3 -3
package/dist/checks.d.ts CHANGED
@@ -215,6 +215,25 @@ type Resolved<D extends SurfaceDeclaration> = Omit<D, "values" | "groups"> & {
215
215
  */
216
216
 
217
217
  declare const GOVERNANCE_COLUMNS: readonly ["organization_id", "published_to_web"];
218
+ /**
219
+ * WHO DECLARED A ROW (Applets CONTRACTS §6, PLAN ruling 7). Every `ui.ui_surface*`
220
+ * row is `declared_by` "code" or "database". This sync writes only code rows: it
221
+ * stamps "code" on insert and never rewrites the column on conflict (a database
222
+ * trigger refuses a code takeover of a database row anyway); stale and orphan
223
+ * checks never return a database row.
224
+ */
225
+ declare const DECLARED_BY: {
226
+ readonly code: "code";
227
+ readonly database: "database";
228
+ };
229
+ type DeclaredBy = (typeof DECLARED_BY)[keyof typeof DECLARED_BY];
230
+ /** Set on insert, never on conflict: governance plus `declared_by`. */
231
+ declare const INSERT_ONLY_COLUMNS: readonly ["organization_id", "published_to_web", "declared_by"];
232
+ /** The Actions mirror. Always keyed with item_type (the table was born re-keyed). */
233
+ declare const SURFACE_ACTION_TABLE = "ui.ui_surface_action";
234
+ declare const SURFACE_ACTION_KEY: readonly ["surface_name", "item_type", "name"];
235
+ /** True for a row an organization authored in the database — code sync never touches it. */
236
+ declare function isDatabaseDeclared(row: Readonly<Record<string, unknown>>): boolean;
218
237
  interface SyncSchema {
219
238
  /** `ui_surface_value/write_target.item_type` exists and the conflict key includes it (re-key step 1). */
220
239
  itemType?: boolean;
@@ -265,6 +284,8 @@ declare function mirrorRowKey(row: Readonly<Record<string, unknown>>, columns: r
265
284
  * plan no longer declares, judged by the table's full key (`plan.keys`) — so
266
285
  * a screen value and an item value that share a name are distinct rows. The
267
286
  * caller deletes each returned row filtered by every column of that key.
287
+ * A row whose `declared_by` is "database" is never returned (pass the column
288
+ * in `existing`, and delete with `declared_by = 'code'` as well).
268
289
  */
269
290
  declare function findStaleRows<R extends Readonly<Record<string, unknown>>>(plan: SurfaceSyncPlan, table: string, existing: readonly R[]): R[];
270
291
  /** Every column a table's rows carry, in first-seen order. */
@@ -305,4 +326,4 @@ declare function findDeadUrlPatterns(declarations: readonly {
305
326
  urlPattern: string;
306
327
  }[];
307
328
 
308
- export { GOVERNANCE_COLUMNS, type SurfaceRowPlan, type SurfaceSyncPlan, type SurfaceSyncPlanOptions, type SyncSchema, type SyncTablePlan, conflictUpdateColumns, findDeadUrlPatterns, findStaleRows, mirrorRowKey, planColumns, planSurfaceSync, renderSurfaceSyncSql, renderSurfaceSyncStatements, routeSegments, sqlLiteral, urlPatternMatchesRoute };
329
+ export { DECLARED_BY, type DeclaredBy, GOVERNANCE_COLUMNS, INSERT_ONLY_COLUMNS, SURFACE_ACTION_KEY, SURFACE_ACTION_TABLE, type SurfaceRowPlan, type SurfaceSyncPlan, type SurfaceSyncPlanOptions, type SyncSchema, type SyncTablePlan, conflictUpdateColumns, findDeadUrlPatterns, findStaleRows, isDatabaseDeclared, mirrorRowKey, planColumns, planSurfaceSync, renderSurfaceSyncSql, renderSurfaceSyncStatements, routeSegments, sqlLiteral, urlPatternMatchesRoute };
package/dist/checks.js CHANGED
@@ -1,4 +1,4 @@
1
- function surfaceClientOf(surfaceName){return surfaceName.split("/")[0]??""}var DEFAULT_SENSITIVITY=Object.freeze({exportable:!0,classification:"ordinary",includedByDefault:!0});function resolveSensitivity(value){return{exportable:value.sensitivity?.exportable??DEFAULT_SENSITIVITY.exportable,classification:value.sensitivity?.classification??DEFAULT_SENSITIVITY.classification,includedByDefault:value.sensitivity?.includedByDefault??DEFAULT_SENSITIVITY.includedByDefault}}var GOVERNANCE_COLUMNS=["organization_id","published_to_web"];function childKey(schema){return schema?.itemType?["surface_name","item_type","name"]:["surface_name","name"]}function planSurfaceSync(declarations,options){let{organizationId,syncedFrom,schema}=options,provenance={synced_by:options.syncedBy??null,synced_from:syncedFrom},governance={organization_id:organizationId,published_to_web:!0},surfaces=[],values=[],targets=[],itemTypes=[],extensionTables=new Map;for(let d of declarations){let urlPattern=d.urlPattern?.trim()||options.resolveUrlPattern?.(d)||null,intro=d.intro?.trim()||null,parent=d.inheritsFrom??null,owned={client_name:surfaceClientOf(d.surfaceName),execution_mode:d.executionMode,description:d.description,label:d.label,value_groups:d.groups??[],readiness:d.readiness,readiness_note:d.readinessNote?.trim()||null,...schema?.contentHash?{content_hash:d.contentHash}:{}},claimed={...d.overlayId?{overlay_id:d.overlayId}:{},...urlPattern?{url_pattern:urlPattern}:{},...intro?{intro}:{},...parent?{parent_surface_name:parent}:{}};surfaces.push({name:d.surfaceName,insert:{name:d.surfaceName,...owned,overlay_id:d.overlayId??null,url_pattern:urlPattern,intro,parent_surface_name:parent},update:{...owned,...claimed}});for(let v of d.values)values.push({...governance,surface_name:d.surfaceName,...schema?.itemType?{item_type:""}:{},name:v.name,label:v.label,description:v.description,value_type:v.valueType,always_available:v.alwaysAvailable,typical_char_count:v.typicalCharCount,sort_order:v.sortOrder??1e3,auto_context:v.autoContext??!0,group_key:v.groupKey??v.group??"general",...schema?.valueContract?{exportable:resolveSensitivity(v).exportable,classification:resolveSensitivity(v).classification,included_by_default:resolveSensitivity(v).includedByDefault,kind_key:v.valueKind??null,live_slot:v.liveSlot??null,role:v.role??"data"}:{},...provenance});for(let t of d.writeTargets??[])targets.push({...governance,surface_name:d.surfaceName,...schema?.itemType?{item_type:t.itemType??""}:{},name:t.name,label:t.label,description:t.description,value_type:t.valueType,mode:t.mode,updates_value:t.updatesValue??null,group_key:t.group??"general",sort_order:t.sortOrder??1e3,apply_policy:t.applyPolicy??"manual",kind_key:t.valueKind??null,...schema?.valueContract?{patchable:t.patchable??!1,approval_comparison:t.approvalComparison??null,stream_ops:t.streamOps?[...t.streamOps]:null,destination:t.destination??!1}:{},...provenance});if(schema?.itemType)for(let[position,item]of(d.itemTypes??[]).entries()){itemTypes.push({...governance,surface_name:d.surfaceName,name:item.name,label:item.label,description:item.description,identity:[...item.identity],levels:item.levels?[...item.levels]:null,entity_type:item.entityType??null,sort_order:position,...provenance});for(let v of item.values)values.push({...governance,surface_name:d.surfaceName,item_type:item.name,name:v.name,label:v.label,description:v.description,value_type:v.valueType,always_available:v.alwaysAvailable,typical_char_count:v.typicalCharCount,sort_order:v.sortOrder??1e3,auto_context:v.autoContext??!0,group_key:v.group??"general",...provenance})}for(let extension of options.extensions??[])for(let entry of extension.toRows?.(d)??[]){let plan=extensionTables.get(entry.table)??{table:entry.table,conflict:entry.conflict,insertOnly:GOVERNANCE_COLUMNS,rows:[]};plan.rows.push({...governance,...entry.row,...provenance}),extensionTables.set(entry.table,plan)}}let keys={"ui.ui_surface_value":childKey(schema),"ui.ui_surface_write_target":childKey(schema),...schema?.itemType?{"ui.ui_surface_item_type":["surface_name","name"]}:{}};for(let extension of options.extensions??[])extension.mirror&&(keys[extension.mirror.table]=extension.mirror.conflict);for(let plan of extensionTables.values())keys[plan.table]??=plan.conflict;let tables=[{table:"ui.ui_surface_value",conflict:childKey(schema),insertOnly:GOVERNANCE_COLUMNS,rows:values},{table:"ui.ui_surface_write_target",conflict:childKey(schema),insertOnly:GOVERNANCE_COLUMNS,rows:targets},...schema?.itemType?[{table:"ui.ui_surface_item_type",conflict:["surface_name","name"],insertOnly:GOVERNANCE_COLUMNS,rows:itemTypes}]:[],...extensionTables.values()];return{surfaces,tables:tables.filter(table=>table.rows.length>0),keys}}function mirrorRowKey(row,columns){return columns.map(column=>String(row[column]??"")).join("\0")}function findStaleRows(plan,table,existing){let key=plan.keys[table];if(!key)throw new Error(`Sync plan declares no key for "${table}"; give the extension that owns it a \`mirror\` entry.`);let managed=new Set(plan.surfaces.map(surface=>surface.name)),declared=new Set((plan.tables.find(entry=>entry.table===table)?.rows??[]).map(row=>mirrorRowKey(row,key)));return existing.filter(row=>managed.has(String(row.surface_name))&&!declared.has(mirrorRowKey(row,key)))}function planColumns(table){let columns=[];for(let row of table.rows)for(let key of Object.keys(row))columns.includes(key)||columns.push(key);return columns}function conflictUpdateColumns(table){return planColumns(table).filter(c=>!table.conflict.includes(c)&&!table.insertOnly.includes(c))}function sqlLiteral(value){return value==null?"NULL":typeof value=="boolean"||typeof value=="number"?String(value):typeof value=="string"?`'${value.replace(/'/g,"''")}'`:Array.isArray(value)&&value.every(entry=>typeof entry=="string")?`ARRAY[${value.map(entry=>sqlLiteral(entry)).join(", ")}]::text[]`:`'${JSON.stringify(value).replace(/'/g,"''")}'::jsonb`}function renderSurfaceSyncStatements(plan){let statements=[];if(plan.surfaces.length>0){let insertColumns=Object.keys(plan.surfaces[0].insert);statements.push(`INSERT INTO ui.ui_surface (${insertColumns.join(", ")}) VALUES
1
+ function surfaceClientOf(surfaceName){return surfaceName.split("/")[0]??""}var DEFAULT_SENSITIVITY=Object.freeze({exportable:!0,classification:"ordinary",includedByDefault:!0});function resolveSensitivity(value){return{exportable:value.sensitivity?.exportable??DEFAULT_SENSITIVITY.exportable,classification:value.sensitivity?.classification??DEFAULT_SENSITIVITY.classification,includedByDefault:value.sensitivity?.includedByDefault??DEFAULT_SENSITIVITY.includedByDefault}}var GOVERNANCE_COLUMNS=["organization_id","published_to_web"],DECLARED_BY={code:"code",database:"database"},INSERT_ONLY_COLUMNS=[...GOVERNANCE_COLUMNS,"declared_by"],SURFACE_ACTION_TABLE="ui.ui_surface_action",SURFACE_ACTION_KEY=["surface_name","item_type","name"];function isDatabaseDeclared(row){return row.declared_by===DECLARED_BY.database}function childKey(schema){return schema?.itemType?["surface_name","item_type","name"]:["surface_name","name"]}function planSurfaceSync(declarations,options){let{organizationId,syncedFrom,schema}=options,provenance={synced_by:options.syncedBy??null,synced_from:syncedFrom},governance={organization_id:organizationId,published_to_web:!0,declared_by:DECLARED_BY.code},surfaces=[],values=[],targets=[],itemTypes=[],extensionTables=new Map;for(let d of declarations){let urlPattern=d.urlPattern?.trim()||options.resolveUrlPattern?.(d)||null,intro=d.intro?.trim()||null,parent=d.inheritsFrom??null,owned={client_name:surfaceClientOf(d.surfaceName),execution_mode:d.executionMode,description:d.description,label:d.label,value_groups:d.groups??[],readiness:d.readiness,readiness_note:d.readinessNote?.trim()||null,...schema?.contentHash?{content_hash:d.contentHash}:{}},claimed={...d.overlayId?{overlay_id:d.overlayId}:{},...urlPattern?{url_pattern:urlPattern}:{},...intro?{intro}:{},...parent?{parent_surface_name:parent}:{}};surfaces.push({name:d.surfaceName,insert:{name:d.surfaceName,declared_by:DECLARED_BY.code,...owned,overlay_id:d.overlayId??null,url_pattern:urlPattern,intro,parent_surface_name:parent},update:{...owned,...claimed}});for(let v of d.values)values.push({...governance,surface_name:d.surfaceName,...schema?.itemType?{item_type:""}:{},name:v.name,label:v.label,description:v.description,value_type:v.valueType,always_available:v.alwaysAvailable,typical_char_count:v.typicalCharCount,sort_order:v.sortOrder??1e3,auto_context:v.autoContext??!0,group_key:v.groupKey??v.group??"general",...schema?.valueContract?{exportable:resolveSensitivity(v).exportable,classification:resolveSensitivity(v).classification,included_by_default:resolveSensitivity(v).includedByDefault,kind_key:v.valueKind??null,live_slot:v.liveSlot??null,role:v.role??"data"}:{},...provenance});for(let t of d.writeTargets??[])targets.push({...governance,surface_name:d.surfaceName,...schema?.itemType?{item_type:t.itemType??""}:{},name:t.name,label:t.label,description:t.description,value_type:t.valueType,mode:t.mode,updates_value:t.updatesValue??null,group_key:t.group??"general",sort_order:t.sortOrder??1e3,apply_policy:t.applyPolicy??"manual",kind_key:t.valueKind??null,...schema?.valueContract?{patchable:t.patchable??!1,approval_comparison:t.approvalComparison??null,stream_ops:t.streamOps?[...t.streamOps]:null,destination:t.destination??!1}:{},...provenance});if(schema?.itemType)for(let[position,item]of(d.itemTypes??[]).entries()){itemTypes.push({...governance,surface_name:d.surfaceName,name:item.name,label:item.label,description:item.description,identity:[...item.identity],levels:item.levels?[...item.levels]:null,entity_type:item.entityType??null,sort_order:position,...provenance});for(let v of item.values)values.push({...governance,surface_name:d.surfaceName,item_type:item.name,name:v.name,label:v.label,description:v.description,value_type:v.valueType,always_available:v.alwaysAvailable,typical_char_count:v.typicalCharCount,sort_order:v.sortOrder??1e3,auto_context:v.autoContext??!0,group_key:v.group??"general",...provenance})}for(let extension of options.extensions??[])for(let entry of extension.toRows?.(d)??[]){let plan=extensionTables.get(entry.table)??{table:entry.table,conflict:entry.conflict,insertOnly:INSERT_ONLY_COLUMNS,rows:[]};plan.rows.push({...governance,...entry.row,...provenance}),extensionTables.set(entry.table,plan)}}let keys={"ui.ui_surface_value":childKey(schema),"ui.ui_surface_write_target":childKey(schema),...schema?.itemType?{"ui.ui_surface_item_type":["surface_name","name"]}:{},...extensionTables.has(SURFACE_ACTION_TABLE)?{[SURFACE_ACTION_TABLE]:SURFACE_ACTION_KEY}:{}};for(let extension of options.extensions??[])extension.mirror&&(keys[extension.mirror.table]=extension.mirror.conflict);for(let plan of extensionTables.values())keys[plan.table]??=plan.conflict;let tables=[{table:"ui.ui_surface_value",conflict:childKey(schema),insertOnly:INSERT_ONLY_COLUMNS,rows:values},{table:"ui.ui_surface_write_target",conflict:childKey(schema),insertOnly:INSERT_ONLY_COLUMNS,rows:targets},...schema?.itemType?[{table:"ui.ui_surface_item_type",conflict:["surface_name","name"],insertOnly:INSERT_ONLY_COLUMNS,rows:itemTypes}]:[],...extensionTables.values()];return{surfaces,tables:tables.filter(table=>table.rows.length>0),keys}}function mirrorRowKey(row,columns){return columns.map(column=>String(row[column]??"")).join("\0")}function findStaleRows(plan,table,existing){let key=plan.keys[table];if(!key)throw new Error(`Sync plan declares no key for "${table}"; give the extension that owns it a \`mirror\` entry.`);let managed=new Set(plan.surfaces.map(surface=>surface.name)),declared=new Set((plan.tables.find(entry=>entry.table===table)?.rows??[]).map(row=>mirrorRowKey(row,key)));return existing.filter(row=>!isDatabaseDeclared(row)&&managed.has(String(row.surface_name))&&!declared.has(mirrorRowKey(row,key)))}function planColumns(table){let columns=[];for(let row of table.rows)for(let key of Object.keys(row))columns.includes(key)||columns.push(key);return columns}function conflictUpdateColumns(table){return planColumns(table).filter(c=>!table.conflict.includes(c)&&!table.insertOnly.includes(c))}function sqlLiteral(value){return value==null?"NULL":typeof value=="boolean"||typeof value=="number"?String(value):typeof value=="string"?`'${value.replace(/'/g,"''")}'`:Array.isArray(value)&&value.every(entry=>typeof entry=="string")?`ARRAY[${value.map(entry=>sqlLiteral(entry)).join(", ")}]::text[]`:`'${JSON.stringify(value).replace(/'/g,"''")}'::jsonb`}function renderSurfaceSyncStatements(plan){let statements=[];if(plan.surfaces.length>0){let insertColumns=Object.keys(plan.surfaces[0].insert);statements.push(`INSERT INTO ui.ui_surface (${insertColumns.join(", ")}) VALUES
2
2
  ${plan.surfaces.map(s=>`(${insertColumns.map(c=>sqlLiteral(s.insert[c])).join(", ")})`).join(`,
3
3
  `)}
4
4
  ON CONFLICT (name) DO NOTHING`);for(let s of plan.surfaces)statements.push(`UPDATE ui.ui_surface SET ${Object.entries(s.update).map(([c,v])=>`${c} = ${sqlLiteral(v)}`).join(", ")}, updated_at = now() WHERE name = ${sqlLiteral(s.name)}`)}for(let table of plan.tables){let columns=planColumns(table),sets=conflictUpdateColumns(table).map(c=>`${c} = EXCLUDED.${c}`);statements.push(`INSERT INTO ${table.table} (${columns.join(", ")}) VALUES
@@ -6,5 +6,5 @@ ${table.rows.map(row=>`(${columns.map(c=>sqlLiteral(row[c])).join(", ")})`).join
6
6
  `)}
7
7
  ON CONFLICT (${table.conflict.join(", ")}) DO UPDATE SET ${[...sets,"updated_at = now()"].join(", ")}`)}return statements}function renderSurfaceSyncSql(plan){return renderSurfaceSyncStatements(plan).map(statement=>`${statement};`).join(`
8
8
 
9
- `)}function routeSegments(path){return(path.split("?")[0]??"").split("#")[0].split("/").filter(Boolean).map(segment=>/^\[\[?\.\.\..+\]\]?$/.test(segment)?"**":segment.startsWith("[")||segment.startsWith(":")?"*":segment)}function urlPatternMatchesRoute(pattern,route){let isPrefix=pattern.trimEnd().endsWith("*")&&!pattern.endsWith("]*"),segments=routeSegments(pattern.replace(/\*+\s*$/,""));for(let i=0;i<segments.length;i+=1){let routeSegment=route[i];if(routeSegment==="**")return!0;if(routeSegment===void 0)return!1;let declared=segments[i];if(declared==="**")return!0;if(declared==="*"?routeSegment!=="*":routeSegment!==declared)return!1}return isPrefix||route.length===segments.length}function findDeadUrlPatterns(declarations,liveRoutes){let routes=liveRoutes.map(routeSegments),dead=[];for(let declaration of declarations){let pattern=declaration.urlPattern;pattern&&(routes.some(route=>urlPatternMatchesRoute(pattern,route))||dead.push({surfaceName:declaration.surfaceName,urlPattern:pattern}))}return dead}export{GOVERNANCE_COLUMNS,conflictUpdateColumns,findDeadUrlPatterns,findStaleRows,mirrorRowKey,planColumns,planSurfaceSync,renderSurfaceSyncSql,renderSurfaceSyncStatements,routeSegments,sqlLiteral,urlPatternMatchesRoute};
9
+ `)}function routeSegments(path){return(path.split("?")[0]??"").split("#")[0].split("/").filter(Boolean).map(segment=>/^\[\[?\.\.\..+\]\]?$/.test(segment)?"**":segment.startsWith("[")||segment.startsWith(":")?"*":segment)}function urlPatternMatchesRoute(pattern,route){let isPrefix=pattern.trimEnd().endsWith("*")&&!pattern.endsWith("]*"),segments=routeSegments(pattern.replace(/\*+\s*$/,""));for(let i=0;i<segments.length;i+=1){let routeSegment=route[i];if(routeSegment==="**")return!0;if(routeSegment===void 0)return!1;let declared=segments[i];if(declared==="**")return!0;if(declared==="*"?routeSegment!=="*":routeSegment!==declared)return!1}return isPrefix||route.length===segments.length}function findDeadUrlPatterns(declarations,liveRoutes){let routes=liveRoutes.map(routeSegments),dead=[];for(let declaration of declarations){let pattern=declaration.urlPattern;pattern&&(routes.some(route=>urlPatternMatchesRoute(pattern,route))||dead.push({surfaceName:declaration.surfaceName,urlPattern:pattern}))}return dead}export{DECLARED_BY,GOVERNANCE_COLUMNS,INSERT_ONLY_COLUMNS,SURFACE_ACTION_KEY,SURFACE_ACTION_TABLE,conflictUpdateColumns,findDeadUrlPatterns,findStaleRows,isDatabaseDeclared,mirrorRowKey,planColumns,planSurfaceSync,renderSurfaceSyncSql,renderSurfaceSyncStatements,routeSegments,sqlLiteral,urlPatternMatchesRoute};
10
10
  //# sourceMappingURL=checks.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/declare/keys.ts","../src/declare/sensitivity.ts","../src/checks/sync.ts","../src/checks/routes.ts"],"sourcesContent":["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 * Sensitivity defaults and resolution (CONTRACT §2.1). Its own module so the\n * lightweight entries (`/actions`, the T0 React host) can project without\n * pulling the declaration registry.\n */\nimport type { DeclaredValue, Sensitivity } from \"./types\";\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","/**\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 * `published_to_web`) are INSERT-ONLY (chair ruling N5): a conflict never rewrites them.\n * Mirror rows are published to the web on insert, written explicitly (access ladder\n * T-13: never left to a column default); the database stamps when and by whom.\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\", \"published_to_web\"] 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 * The key (ON CONFLICT target) of every mirror table this plan owns,\n * including tables it emits no rows for. Stale detection and deletes use\n * exactly these columns (`findStaleRows`).\n */\n keys: Record<string, readonly string[]>;\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, published_to_web: true };\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 keys: Record<string, readonly string[]> = {\n \"ui.ui_surface_value\": childKey(schema),\n \"ui.ui_surface_write_target\": childKey(schema),\n ...(schema?.itemType ? { \"ui.ui_surface_item_type\": [\"surface_name\", \"name\"] } : {}),\n };\n for (const extension of options.extensions ?? []) {\n if (extension.mirror) keys[extension.mirror.table] = extension.mirror.conflict;\n }\n for (const plan of extensionTables.values()) keys[plan.table] ??= plan.conflict;\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), keys };\n}\n\n/** One row's key under `columns` (a missing column reads as ''). */\nexport function mirrorRowKey(row: Readonly<Record<string, unknown>>, columns: readonly string[]): string {\n return columns.map((column) => String(row[column] ?? \"\")).join(\"\\u0000\");\n}\n\n/**\n * Rows of `table` that belong to a surface this plan manages but that the\n * plan no longer declares, judged by the table's full key (`plan.keys`) — so\n * a screen value and an item value that share a name are distinct rows. The\n * caller deletes each returned row filtered by every column of that key.\n */\nexport function findStaleRows<R extends Readonly<Record<string, unknown>>>(\n plan: SurfaceSyncPlan,\n table: string,\n existing: readonly R[],\n): R[] {\n const key = plan.keys[table];\n if (!key) {\n throw new Error(\n `Sync plan declares no key for \"${table}\"; give the extension that owns it a \\`mirror\\` entry.`,\n );\n }\n const managed = new Set(plan.surfaces.map((surface) => surface.name));\n const declared = new Set(\n (plan.tables.find((entry) => entry.table === table)?.rows ?? []).map((row) => mirrorRowKey(row, key)),\n );\n return existing.filter(\n (row) => managed.has(String(row.surface_name)) && !declared.has(mirrorRowKey(row, key)),\n );\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","/**\n * The declaration half of the route check (CONTRACT §2.6 `/checks`): does each\n * declared `urlPattern` address a live route? The host supplies its route list\n * (it owns the filesystem); the matching rule lives here, once. Ported from\n * matrx-frontend `scripts/check-surface-routes.ts` (ALC-14).\n */\n\n/** Route or pattern → segments; `[x]` / `:x` → \"*\", `[...x]` / `[[...x]]` → \"**\". */\nexport function routeSegments(path: string): string[] {\n return (path.split(\"?\")[0] ?? \"\")\n .split(\"#\")[0]!\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (/^\\[\\[?\\.\\.\\..+\\]\\]?$/.test(segment)) return \"**\";\n if (segment.startsWith(\"[\") || segment.startsWith(\":\")) return \"*\";\n return segment;\n });\n}\n\n/**\n * Does a declared `urlPattern` address a live route? A literal pattern segment\n * must be a literal route segment — a dynamic route segment does NOT satisfy it,\n * or `/marketing/[brandId]/…` would \"cover\" a retired `/marketing/brands/…`.\n * A trailing `*` makes the pattern a prefix.\n */\nexport function urlPatternMatchesRoute(pattern: string, route: readonly string[]): boolean {\n const isPrefix = pattern.trimEnd().endsWith(\"*\") && !pattern.endsWith(\"]*\");\n const segments = routeSegments(pattern.replace(/\\*+\\s*$/, \"\"));\n for (let i = 0; i < segments.length; i += 1) {\n const routeSegment = route[i];\n if (routeSegment === \"**\") return true;\n if (routeSegment === undefined) return false;\n const declared = segments[i];\n if (declared === \"**\") return true;\n if (declared === \"*\" ? routeSegment !== \"*\" : routeSegment !== declared) return false;\n }\n return isPrefix || route.length === segments.length;\n}\n\n/** Every declaration whose `urlPattern` no live route can produce. */\nexport function findDeadUrlPatterns(\n declarations: readonly { surfaceName: string; urlPattern?: string | undefined }[],\n liveRoutes: readonly string[],\n): { surfaceName: string; urlPattern: string }[] {\n const routes = liveRoutes.map(routeSegments);\n const dead: { surfaceName: string; urlPattern: string }[] = [];\n for (const declaration of declarations) {\n const pattern = declaration.urlPattern;\n if (!pattern) continue;\n if (!routes.some((route) => urlPatternMatchesRoute(pattern, route))) {\n dead.push({ surfaceName: declaration.surfaceName, urlPattern: pattern });\n }\n }\n return dead;\n}\n"],"mappings":"AA8BO,SAAS,gBAAgB,YAA6B,CAC3D,OAAO,YAAY,MAAM,GAAG,EAAE,CAAC,GAAK,EACtC,CCzBO,IAAM,oBAAmC,OAAO,OAAO,CAC5D,WAAY,GACZ,eAAgB,WAChB,kBAAmB,EACrB,CAAC,EAEM,SAAS,mBAAmB,MAAwD,CACzF,MAAO,CACL,WAAY,MAAM,aAAa,YAAc,oBAAoB,WACjE,eAAgB,MAAM,aAAa,gBAAkB,oBAAoB,eACzE,kBAAmB,MAAM,aAAa,mBAAqB,oBAAoB,iBACjF,CACF,CCAO,IAAM,mBAAqB,CAAC,kBAAmB,kBAAkB,EAiDxE,SAAS,SAAS,OAAmD,CACnE,OAAO,QAAQ,SAAW,CAAC,eAAgB,YAAa,MAAM,EAAI,CAAC,eAAgB,MAAM,CAC3F,CAEO,SAAS,gBACd,aACA,QACiB,CACjB,GAAM,CAAE,eAAgB,WAAY,MAAO,EAAI,QAEzC,WAAa,CAAE,UADJ,QAAQ,UAAY,KACK,YAAa,UAAW,EAC5D,WAAa,CAAE,gBAAiB,eAAgB,iBAAkB,EAAK,EACvE,SAA6B,CAAC,EAC9B,OAAiC,CAAC,EAClC,QAAkC,CAAC,EACnC,UAAoC,CAAC,EACrC,gBAAkB,IAAI,IAE5B,QAAW,KAAK,aAAc,CAC5B,IAAM,WAAa,EAAE,YAAY,KAAK,GAAK,QAAQ,oBAAoB,CAAC,GA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K,MAAM,GAAG,EAAE,CAAC,GAAK,IAC3B,MAAM,GAAG,EAAE,CAAC,EACZ,MAAM,GAAG,EACT,OAAO,OAAO,EACd,IAAK,SACA,uBAAuB,KAAK,OAAO,EAAU,KAC7C,QAAQ,WAAW,GAAG,GAAK,QAAQ,WAAW,GAAG,EAAU,IACxD,OACR,CACL,CAQO,SAAS,uBAAuB,QAAiB,MAAmC,CACzF,IAAM,SAAW,QAAQ,QAAQ,EAAE,SAAS,GAAG,GAAK,CAAC,QAAQ,SAAS,IAAI,EACpE,SAAW,cAAc,QAAQ,QAAQ,UAAW,EAAE,CAAC,EAC7D,QAAS,EAAI,EAAG,EAAI,SAAS,OAAQ,GAAK,EAAG,CAC3C,IAAM,aAAe,MAAM,CAAC,EAC5B,GAAI,eAAiB,KAAM,MAAO,GAClC,GAAI,eAAiB,OAAW,MAAO,GACvC,IAAM,SAAW,SAAS,CAAC,EAC3B,GAAI,WAAa,KAAM,MAAO,GAC9B,GAAI,WAAa,IAAM,eAAiB,IAAM,eAAiB,SAAU,MAAO,EAClF,CACA,OAAO,UAAY,MAAM,SAAW,SAAS,MAC/C,CAGO,SAAS,oBACd,aACA,WAC+C,CAC/C,IAAM,OAAS,WAAW,IAAI,aAAa,EACrC,KAAsD,CAAC,EAC7D,QAAW,eAAe,aAAc,CACtC,IAAM,QAAU,YAAY,WACvB,UACA,OAAO,KAAM,OAAU,uBAAuB,QAAS,KAAK,CAAC,GAChE,KAAK,KAAK,CAAE,YAAa,YAAY,YAAa,WAAY,OAAQ,CAAC,EAE3E,CACA,OAAO,IACT","names":[]}
1
+ {"version":3,"sources":["../src/declare/keys.ts","../src/declare/sensitivity.ts","../src/checks/sync.ts","../src/checks/routes.ts"],"sourcesContent":["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 * Sensitivity defaults and resolution (CONTRACT §2.1). Its own module so the\n * lightweight entries (`/actions`, the T0 React host) can project without\n * pulling the declaration registry.\n */\nimport type { DeclaredValue, Sensitivity } from \"./types\";\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","/**\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 * `published_to_web`) are INSERT-ONLY (chair ruling N5): a conflict never rewrites them.\n * Mirror rows are published to the web on insert, written explicitly (access ladder\n * T-13: never left to a column default); the database stamps when and by whom.\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\", \"published_to_web\"] as const;\n\n/**\n * WHO DECLARED A ROW (Applets CONTRACTS §6, PLAN ruling 7). Every `ui.ui_surface*`\n * row is `declared_by` \"code\" or \"database\". This sync writes only code rows: it\n * stamps \"code\" on insert and never rewrites the column on conflict (a database\n * trigger refuses a code takeover of a database row anyway); stale and orphan\n * checks never return a database row.\n */\nexport const DECLARED_BY = { code: \"code\", database: \"database\" } as const;\nexport type DeclaredBy = (typeof DECLARED_BY)[keyof typeof DECLARED_BY];\n\n/** Set on insert, never on conflict: governance plus `declared_by`. */\nexport const INSERT_ONLY_COLUMNS = [...GOVERNANCE_COLUMNS, \"declared_by\"] as const;\n\n/** The Actions mirror. Always keyed with item_type (the table was born re-keyed). */\nexport const SURFACE_ACTION_TABLE = \"ui.ui_surface_action\";\nexport const SURFACE_ACTION_KEY = [\"surface_name\", \"item_type\", \"name\"] as const;\n\n/** True for a row an organization authored in the database — code sync never touches it. */\nexport function isDatabaseDeclared(row: Readonly<Record<string, unknown>>): boolean {\n return row.declared_by === DECLARED_BY.database;\n}\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 * The key (ON CONFLICT target) of every mirror table this plan owns,\n * including tables it emits no rows for. Stale detection and deletes use\n * exactly these columns (`findStaleRows`).\n */\n keys: Record<string, readonly string[]>;\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, published_to_web: true, declared_by: DECLARED_BY.code };\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 declared_by: DECLARED_BY.code,\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: INSERT_ONLY_COLUMNS,\n rows: [],\n };\n plan.rows.push({ ...governance, ...entry.row, ...provenance });\n extensionTables.set(entry.table, plan);\n }\n }\n }\n\n const keys: Record<string, readonly string[]> = {\n \"ui.ui_surface_value\": childKey(schema),\n \"ui.ui_surface_write_target\": childKey(schema),\n ...(schema?.itemType ? { \"ui.ui_surface_item_type\": [\"surface_name\", \"name\"] } : {}),\n // ui.ui_surface_action is claimed ONLY when a code declaration emits Action rows: until code\n // declares Actions, every live Action row is database-owned, and claiming the table would read\n // a future code Action as stale. Unclaimed, a stale check on it throws by name instead.\n ...(extensionTables.has(SURFACE_ACTION_TABLE) ? { [SURFACE_ACTION_TABLE]: SURFACE_ACTION_KEY } : {}),\n };\n for (const extension of options.extensions ?? []) {\n if (extension.mirror) keys[extension.mirror.table] = extension.mirror.conflict;\n }\n for (const plan of extensionTables.values()) keys[plan.table] ??= plan.conflict;\n\n const tables: SyncTablePlan[] = [\n { table: \"ui.ui_surface_value\", conflict: childKey(schema), insertOnly: INSERT_ONLY_COLUMNS, rows: values },\n { table: \"ui.ui_surface_write_target\", conflict: childKey(schema), insertOnly: INSERT_ONLY_COLUMNS, rows: targets },\n ...(schema?.itemType\n ? [{ table: \"ui.ui_surface_item_type\", conflict: [\"surface_name\", \"name\"], insertOnly: INSERT_ONLY_COLUMNS, rows: itemTypes }]\n : []),\n ...extensionTables.values(),\n ];\n return { surfaces, tables: tables.filter((table) => table.rows.length > 0), keys };\n}\n\n/** One row's key under `columns` (a missing column reads as ''). */\nexport function mirrorRowKey(row: Readonly<Record<string, unknown>>, columns: readonly string[]): string {\n return columns.map((column) => String(row[column] ?? \"\")).join(\"\\u0000\");\n}\n\n/**\n * Rows of `table` that belong to a surface this plan manages but that the\n * plan no longer declares, judged by the table's full key (`plan.keys`) — so\n * a screen value and an item value that share a name are distinct rows. The\n * caller deletes each returned row filtered by every column of that key.\n * A row whose `declared_by` is \"database\" is never returned (pass the column\n * in `existing`, and delete with `declared_by = 'code'` as well).\n */\nexport function findStaleRows<R extends Readonly<Record<string, unknown>>>(\n plan: SurfaceSyncPlan,\n table: string,\n existing: readonly R[],\n): R[] {\n const key = plan.keys[table];\n if (!key) {\n throw new Error(\n `Sync plan declares no key for \"${table}\"; give the extension that owns it a \\`mirror\\` entry.`,\n );\n }\n const managed = new Set(plan.surfaces.map((surface) => surface.name));\n const declared = new Set(\n (plan.tables.find((entry) => entry.table === table)?.rows ?? []).map((row) => mirrorRowKey(row, key)),\n );\n return existing.filter(\n (row) => !isDatabaseDeclared(row) && managed.has(String(row.surface_name)) && !declared.has(mirrorRowKey(row, key)),\n );\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","/**\n * The declaration half of the route check (CONTRACT §2.6 `/checks`): does each\n * declared `urlPattern` address a live route? The host supplies its route list\n * (it owns the filesystem); the matching rule lives here, once. Ported from\n * matrx-frontend `scripts/check-surface-routes.ts` (ALC-14).\n */\n\n/** Route or pattern → segments; `[x]` / `:x` → \"*\", `[...x]` / `[[...x]]` → \"**\". */\nexport function routeSegments(path: string): string[] {\n return (path.split(\"?\")[0] ?? \"\")\n .split(\"#\")[0]!\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (/^\\[\\[?\\.\\.\\..+\\]\\]?$/.test(segment)) return \"**\";\n if (segment.startsWith(\"[\") || segment.startsWith(\":\")) return \"*\";\n return segment;\n });\n}\n\n/**\n * Does a declared `urlPattern` address a live route? A literal pattern segment\n * must be a literal route segment — a dynamic route segment does NOT satisfy it,\n * or `/marketing/[brandId]/…` would \"cover\" a retired `/marketing/brands/…`.\n * A trailing `*` makes the pattern a prefix.\n */\nexport function urlPatternMatchesRoute(pattern: string, route: readonly string[]): boolean {\n const isPrefix = pattern.trimEnd().endsWith(\"*\") && !pattern.endsWith(\"]*\");\n const segments = routeSegments(pattern.replace(/\\*+\\s*$/, \"\"));\n for (let i = 0; i < segments.length; i += 1) {\n const routeSegment = route[i];\n if (routeSegment === \"**\") return true;\n if (routeSegment === undefined) return false;\n const declared = segments[i];\n if (declared === \"**\") return true;\n if (declared === \"*\" ? routeSegment !== \"*\" : routeSegment !== declared) return false;\n }\n return isPrefix || route.length === segments.length;\n}\n\n/** Every declaration whose `urlPattern` no live route can produce. */\nexport function findDeadUrlPatterns(\n declarations: readonly { surfaceName: string; urlPattern?: string | undefined }[],\n liveRoutes: readonly string[],\n): { surfaceName: string; urlPattern: string }[] {\n const routes = liveRoutes.map(routeSegments);\n const dead: { surfaceName: string; urlPattern: string }[] = [];\n for (const declaration of declarations) {\n const pattern = declaration.urlPattern;\n if (!pattern) continue;\n if (!routes.some((route) => urlPatternMatchesRoute(pattern, route))) {\n dead.push({ surfaceName: declaration.surfaceName, urlPattern: pattern });\n }\n }\n return dead;\n}\n"],"mappings":"AA8BO,SAAS,gBAAgB,YAA6B,CAC3D,OAAO,YAAY,MAAM,GAAG,EAAE,CAAC,GAAK,EACtC,CCzBO,IAAM,oBAAmC,OAAO,OAAO,CAC5D,WAAY,GACZ,eAAgB,WAChB,kBAAmB,EACrB,CAAC,EAEM,SAAS,mBAAmB,MAAwD,CACzF,MAAO,CACL,WAAY,MAAM,aAAa,YAAc,oBAAoB,WACjE,eAAgB,MAAM,aAAa,gBAAkB,oBAAoB,eACzE,kBAAmB,MAAM,aAAa,mBAAqB,oBAAoB,iBACjF,CACF,CCAO,IAAM,mBAAqB,CAAC,kBAAmB,kBAAkB,EAS3D,YAAc,CAAE,KAAM,OAAQ,SAAU,UAAW,EAInD,oBAAsB,CAAC,GAAG,mBAAoB,aAAa,EAG3D,qBAAuB,uBACvB,mBAAqB,CAAC,eAAgB,YAAa,MAAM,EAG/D,SAAS,mBAAmB,IAAiD,CAClF,OAAO,IAAI,cAAgB,YAAY,QACzC,CAiDA,SAAS,SAAS,OAAmD,CACnE,OAAO,QAAQ,SAAW,CAAC,eAAgB,YAAa,MAAM,EAAI,CAAC,eAAgB,MAAM,CAC3F,CAEO,SAAS,gBACd,aACA,QACiB,CACjB,GAAM,CAAE,eAAgB,WAAY,MAAO,EAAI,QAEzC,WAAa,CAAE,UADJ,QAAQ,UAAY,KACK,YAAa,UAAW,EAC5D,WAAa,CAAE,gBAAiB,eAAgB,iBAAkB,GAAM,YAAa,YAAY,IAAK,EACtG,SAA6B,CAAC,EAC9B,OAAiC,CAAC,EAClC,QAAkC,CAAC,EACnC,UAAoC,CAAC,EACrC,gBAAkB,IAAI,IA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-2,8 +2,8 @@
2
2
  * Framework-neutral transfer contracts (Alchemy Operate, CONTRACT §2.3). All data crossing this boundary is JSON.
3
3
  * Moved from `@ai-matrx/kit/content-transfer` in ALC-16; the format-adapter contract lives in `./contract`.
4
4
  */
5
- type Json$1 = null | boolean | number | string | Json$1[] | {
6
- [key: string]: Json$1;
5
+ type Json$2 = null | boolean | number | string | Json$2[] | {
6
+ [key: string]: Json$2;
7
7
  };
8
8
  type Payload =
9
9
  /** A text payload may name its language (code blocks): downloads take its extension, Markdown fences it. */
@@ -16,15 +16,15 @@ type Payload =
16
16
  text: string;
17
17
  } | {
18
18
  kind: "json";
19
- value: Json$1;
19
+ value: Json$2;
20
20
  } | {
21
21
  kind: "rows";
22
- rows: Record<string, Json$1>[];
22
+ rows: Record<string, Json$2>[];
23
23
  columns: Column[];
24
24
  } | {
25
25
  kind: "registered";
26
26
  format: string;
27
- value: Json$1;
27
+ value: Json$2;
28
28
  };
29
29
  type Column = {
30
30
  id: string;
@@ -38,9 +38,9 @@ type Column = {
38
38
  dataType?: string;
39
39
  order?: number;
40
40
  required?: boolean;
41
- defaultValue?: Json$1;
42
- validation?: Json$1;
43
- metadata?: Json$1;
41
+ defaultValue?: Json$2;
42
+ validation?: Json$2;
43
+ metadata?: Json$2;
44
44
  };
45
45
  };
46
46
  type ExportProjection = {
@@ -93,21 +93,21 @@ type Snapshot = RawSnapshot & {
93
93
  type QuerySnapshot = {
94
94
  sourceId: string;
95
95
  revision: string;
96
- query: Json$1;
96
+ query: Json$2;
97
97
  order: {
98
98
  field: string;
99
99
  direction: "asc" | "desc";
100
100
  }[];
101
101
  };
102
102
  type ExportPage = {
103
- rows: Record<string, Json$1>[];
103
+ rows: Record<string, Json$2>[];
104
104
  nextCursor: string | null;
105
105
  coverage: Coverage;
106
106
  consistencyToken: string | null;
107
107
  };
108
108
  type CapturedAllMatching = {
109
109
  query: QuerySnapshot;
110
- getRowId(row: Record<string, Json$1>): string;
110
+ getRowId(row: Record<string, Json$2>): string;
111
111
  page(request: {
112
112
  query: QuerySnapshot;
113
113
  cursor: string | null;
@@ -147,7 +147,7 @@ type Draft = {
147
147
  };
148
148
  type Transform = {
149
149
  id: string;
150
- apply(draft: Draft, options: Json$1, signal: AbortSignal): Promise<Draft>;
150
+ apply(draft: Draft, options: Json$2, signal: AbortSignal): Promise<Draft>;
151
151
  };
152
152
  type Artifact = {
153
153
  snapshotId: string;
@@ -338,9 +338,9 @@ type BoundAllMatching = {
338
338
  type NormalizeTransferJsonOptions = {
339
339
  omitUndefinedObjectProperties?: boolean;
340
340
  };
341
- declare function normalizeTransferJson(value: unknown, options?: NormalizeTransferJsonOptions): Json$1;
341
+ declare function normalizeTransferJson(value: unknown, options?: NormalizeTransferJsonOptions): Json$2;
342
342
  /** Column ids are identities, never an alternative data address. */
343
- declare function readTransferCell(row: Record<string, Json$1>, column: Column): Json$1 | undefined;
343
+ declare function readTransferCell(row: Record<string, Json$2>, column: Column): Json$2 | undefined;
344
344
  declare function projectSnapshot(raw: RawSnapshot, projection: ExportProjection): Snapshot;
345
345
  declare function directSource(payload: Payload, options?: Partial<Pick<RawSnapshot, "id" | "sourceId" | "revision" | "label" | "coverage" | "unsavedChanges" | "sections" | "limits"> & {
346
346
  projection: ExportProjection;
@@ -385,7 +385,7 @@ declare function reduceJson(draft: Draft, options: {
385
385
  maxArrayItems?: number | null;
386
386
  }): Draft;
387
387
  declare function collectAllMatching(c: BoundAllMatching, signal: AbortSignal): Promise<{
388
- rows: Record<string, Json$1>[];
388
+ rows: Record<string, Json$2>[];
389
389
  coverage: RawSnapshot["coverage"];
390
390
  omissions: Omission[];
391
391
  error?: ContentTransferError;
@@ -433,6 +433,16 @@ declare function createSurfaceTransferHandle(options: {
433
433
  /** Applies explicit preparation/source limits with exact omissions; token target is advisory. */
434
434
  declare function applyTransferLimits(draft: Draft, limits: Partial<TransferLimits>): Draft;
435
435
 
436
+ /**
437
+ * Matrx Alchemy — Declare types (CONTRACT §2.1).
438
+ *
439
+ * A declaration is plain JSON data (chair ruling N2): no functions, no classes,
440
+ * no React. Runtime behaviour lives in `MountedSurface` (`/declare/host`) and in
441
+ * handler registrations, never here. Zero React, zero `@ai-matrx/agents`.
442
+ */
443
+ type Json$1 = null | boolean | number | string | Json$1[] | {
444
+ [key: string]: Json$1;
445
+ };
436
446
  /** Unchanged from `ui_surface_value_type_chk`. */
437
447
  type ValueType = "string" | "number" | "boolean" | "object" | "array" | "document";
438
448
  type Classification = "ordinary" | "secret" | "credential";
@@ -639,6 +649,75 @@ interface ClickTarget {
639
649
  host?: unknown;
640
650
  }
641
651
 
652
+ /**
653
+ * Surface Actions — the shapes (Applets CONTRACTS §6, FROZEN; exported here as a superset).
654
+ *
655
+ * An Action is one thing a surface can have done to it, by a person, an agent,
656
+ * an applet or an automation: a write target, a client tool, a Kind Action or a
657
+ * row in `ui.ui_surface_action`. All of them project onto `ActionDeclaration`
658
+ * (`./declarations.ts`) and run through ONE runner (`./surface-run.ts`). There is
659
+ * never a second registry: `name` IS the alchemy action id, and `category`
660
+ * defaults to "applet" in alchemy's closed `ActionCategory` union.
661
+ *
662
+ * Types only — no runtime code, no React, no `@ai-matrx/agents`. `/ports`
663
+ * imports from here, so this file imports nothing but local types.
664
+ */
665
+
666
+ /** Who started a run. */
667
+ type ActionCaller = "person" | "agent" | "applet" | "automation";
668
+ /** Who may run it without a click: "manual" = only a person; "ask" = proposed first; "auto" = runs. */
669
+ type ActionPolicy = "ask" | "auto" | "manual";
670
+ interface ActionContext {
671
+ runId: string;
672
+ by: ActionCaller;
673
+ viewerId: string | null;
674
+ surfaceName?: string;
675
+ policy?: ActionPolicy;
676
+ }
677
+ /** The system's own sentence, never thrown into a UI. Superset of RecordsError (CONTRACTS §0 `AppletError`). */
678
+ interface ActionError {
679
+ code: string;
680
+ message: string;
681
+ retryable: boolean;
682
+ diagnostic?: string;
683
+ }
684
+ /** CONTRACTS §0 `Result<T>`. */
685
+ type ActionResult<T = unknown> = {
686
+ ok: true;
687
+ data: T;
688
+ } | {
689
+ ok: false;
690
+ error: ActionError;
691
+ };
692
+ /** `POST /actions/run` (aidream) — the request. */
693
+ interface ServerActionRunRequest {
694
+ name: string;
695
+ input: Json$1;
696
+ by: ActionCaller;
697
+ surface_name?: string;
698
+ policy?: ActionPolicy;
699
+ }
700
+ /** `POST /actions/run` (aidream) — the response. */
701
+ interface ServerActionRunResponse {
702
+ status: "applied" | "proposed" | "refused";
703
+ message: string;
704
+ receipts: Json$1[];
705
+ proposal?: Json$1;
706
+ }
707
+ /** A mandate run request: by alias (an Action's `target`) or by key. */
708
+ type MandateRunRequest = ({
709
+ alias: string;
710
+ key?: never;
711
+ } | {
712
+ key: string;
713
+ alias?: never;
714
+ }) & {
715
+ variables: Record<string, Json$1>;
716
+ userInput?: string;
717
+ by: ActionCaller;
718
+ policy: ActionPolicy;
719
+ };
720
+
642
721
  /**
643
722
  * `@ai-matrx/alchemy/ports` — the host ports (Matrx Alchemy CONTRACT §2.2).
644
723
  *
@@ -687,6 +766,12 @@ interface ClickTarget {
687
766
  * to an overlay carrying the session as data)
688
767
  * transferKnobs absent → no organization default recipe; a person's own
689
768
  * default (persistence) or the package's Full applies
769
+ * serverActions absent → `runs: "server"` Actions refuse with "not available here"
770
+ * mandates absent → `runs: "mandate"` Actions refuse the same way
771
+ * pageActions absent → `runs: "page"` Actions refuse the same way
772
+ * approvals absent → a policy "ask" Action started by an agent, applet or automation is refused
773
+ * ("needs a person's approval"); a person's own click is the approval
774
+ * (`runs: "navigate"` goes through `overlay.navigate`; overlay absent → refused)
690
775
  *
691
776
  * Types only: this entry has no runtime code.
692
777
  */
@@ -832,6 +917,36 @@ interface AlchemyHostPorts {
832
917
  window?: WindowPort;
833
918
  /** Organization default recipes, resolved by the host's Feature Knob ladder (platform → organization). */
834
919
  transferKnobs?: TransferKnobsPort;
920
+ /** aidream `POST /actions/run`: a registered server action by name, as the caller, under the apply-policy cascade. */
921
+ serverActions?: ServerActionPort;
922
+ /** Runs a mandate by alias or key (the host binds `@ai-matrx/agents`; alchemy never imports it). */
923
+ mandates?: MandatePort;
924
+ /** The page's own handlers for `runs: "page"` Actions (in an applet frame: routed as `{ action, input, runId }`). */
925
+ pageActions?: PageActionPort;
926
+ /** Asks a person, in place, to approve an `ask` Action that an agent, applet or automation started. */
927
+ approvals?: ApprovalPort;
928
+ }
929
+ interface ServerActionPort {
930
+ run(request: ServerActionRunRequest): Promise<ServerActionRunResponse>;
931
+ }
932
+ interface MandatePort {
933
+ /** Resolves with the run's result (a kind envelope or JSON); rejects with the system's sentence. */
934
+ run(request: MandateRunRequest): Promise<unknown>;
935
+ }
936
+ interface ApprovalRequest {
937
+ action: string;
938
+ label: string;
939
+ description: string;
940
+ input: Json;
941
+ by: "agent" | "applet" | "automation";
942
+ surfaceName: string;
943
+ }
944
+ interface ApprovalPort {
945
+ /** Resolves true when the person approves; false when they decline or dismiss. */
946
+ ask(request: ApprovalRequest): Promise<boolean>;
947
+ }
948
+ interface PageActionPort {
949
+ dispatch(name: string, input: unknown, context: ActionContext): Promise<ActionResult<unknown>>;
835
950
  }
836
951
  /**
837
952
  * Why a port and not `OverlayHostPort`: an overlay's `data` is `Json`, and a live preparation
@@ -983,7 +1098,7 @@ type TransferOperation = {
983
1098
  } | {
984
1099
  kind: "transform";
985
1100
  transform: string;
986
- options?: Json$1;
1101
+ options?: Json$2;
987
1102
  } | {
988
1103
  kind: "prepare-for-ai";
989
1104
  instruction?: string;
@@ -1028,7 +1143,7 @@ interface ServerOperation {
1028
1143
  statement: string;
1029
1144
  supports(payload: Payload): boolean;
1030
1145
  /** Projected draft only; sensitivity already applied. */
1031
- toInput(draft: Draft): Json$1;
1146
+ toInput(draft: Draft): Json$2;
1032
1147
  }
1033
1148
  /** Delivery results: `copy` and `download` only ever deliver, degrade, cancel or fail (CONTRACT R16). */
1034
1149
  type DeliveryOutcome = Extract<TransferOutcome, {
@@ -1110,7 +1225,7 @@ interface PreparationSession {
1110
1225
  readonly snapshot: Snapshot;
1111
1226
  readonly draft: Draft;
1112
1227
  /** Deterministic transform, AI preparation or any registered transform — bumps draft.revision. */
1113
- transform(id: string, options: Json$1, signal: AbortSignal): Promise<Draft>;
1228
+ transform(id: string, options: Json$2, signal: AbortSignal): Promise<Draft>;
1114
1229
  /** A manual edit. */
1115
1230
  edit(payload: Payload): Draft;
1116
1231
  /** Keep only these sections (ids from the snapshot). */
@@ -1228,19 +1343,19 @@ declare function patternBelow(pattern: string, pointer: string): boolean;
1228
1343
  /** The path a person reads and copies: `/messages/*\/metadata` → `data.messages[*].metadata`. */
1229
1344
  declare function displayPath(pointer: string, root?: string): string;
1230
1345
  /** Exactly `JSON.stringify(value).length`, computed once per object (large sources stay cheap). */
1231
- declare function jsonSize(value: Json$1): number;
1346
+ declare function jsonSize(value: Json$2): number;
1232
1347
  /** The size a person expects for a node: a string's own length, else its JSON. */
1233
- declare function nodeChars(value: Json$1): number;
1348
+ declare function nodeChars(value: Json$2): number;
1234
1349
  /**
1235
1350
  * The one-line stub that stands in for a node: its header (a string's first line, an object's
1236
1351
  * short scalar members) and its original size.
1237
1352
  */
1238
- declare function stubText(value: Json$1): string;
1353
+ declare function stubText(value: Json$2): string;
1239
1354
  /** Every concrete pointer in `value` a pattern names (for counts, diffs and highlights). */
1240
- declare function concretePointers(value: Json$1, pattern: string): string[];
1355
+ declare function concretePointers(value: Json$2, pattern: string): string[];
1241
1356
  /** Apply exclusions and per-node limits to a JSON value; returns the new value and what changed. */
1242
- declare function applyStructureToJson(value: Json$1, recipe: StructureRecipe, labels?: Readonly<Record<string, string>>): {
1243
- value: Json$1;
1357
+ declare function applyStructureToJson(value: Json$2, recipe: StructureRecipe, labels?: Readonly<Record<string, string>>): {
1358
+ value: Json$2;
1244
1359
  omissions: Omission[];
1245
1360
  };
1246
1361
  /** A JSON (or registered) draft with the person's structure choices applied. */
@@ -1250,7 +1365,7 @@ declare function applyJsonStructure(draft: Draft, recipe: StructureRecipe, label
1250
1365
  * earlier sibling is excluded). Null when the node is excluded or cut; a stubbed ancestor answers
1251
1366
  * with the stub's own pointer.
1252
1367
  */
1253
- declare function outputPointer(value: Json$1, recipe: StructureRecipe, pointer: string): string | null;
1368
+ declare function outputPointer(value: Json$2, recipe: StructureRecipe, pointer: string): string | null;
1254
1369
  declare function isProseSection(section: Section): boolean;
1255
1370
  interface SectionLayout {
1256
1371
  text: string;
@@ -1321,4 +1436,4 @@ declare function setPersonDefaultRecipe(ports: Pick<AlchemyHostPorts, "persisten
1321
1436
  [key: string]: Json;
1322
1437
  } | null): Promise<void>;
1323
1438
 
1324
- export { type AgentPayloadEnvironment, type AgentPayloadInput, type AiPreparation, type Artifact, type BoundAllMatching, type BuiltInFormatId, type CapturedAllMatching, type CapturedSource, type Column, ContentTransferError, type Coverage, type Delivery, type DeliveryOutcome, type Draft, EMPTY_STRUCTURE, type ExportPage, type ExportProjection, FORMAT_ADAPTERS, type FormatAdapter, type FormatEngine, type FormatOptions, type Json$1 as Json, type NodeLimit, type NormalizeTransferJsonOptions, type Notice, type Omission, type OutputSpan, type PageAction, type Payload, type PreparationOptions, type PreparationSession, type QuerySnapshot, type RawSnapshot, type Receipt, type RecipeOrigin, type ResolvedRecipe, type SealedArtifact, type Section, type SectionLayout, type ServerOperation, type Snapshot, type Source, type SpanMap, type StructureRecipe, type SurfaceHandle, TRANSFER_DEFAULT_RECIPE_SETTING, type TransferLimits, type TransferOperation, type TransferOutcome, type TransferPreferenceOverrides, type TransferPreferences, type TransferScope, type TransferSurfaceDeclaration, type TransferTarget, type Transform, type Transport, type WriteTargetRef, agentPayloadWithSpans, applyJsonStructure, applySectionSelection, applySectionStructure, applyStructureToJson, applyTransferLimits, assembleAgentPayload, buildAgentPayload, capture, collectAllMatching, concretePointers, createBrowserTransport, createDelivery, createDraft, createSurfaceTransferHandle, deriveDraft, directSource, displayPath, editDraft, eligibleFormats, exportedColumns, extensionForLanguage, fenceJsonBlock, formatAdapter, isProseSection, isSealed, joinPointer, jsonSize, jsonTextSpans, nodeChars, normalizeTransferJson, offsetSpans, openPreparation, outputPointer, patternBelow, patternCovers, patternMatches, pointerSegments, projectSnapshot, readTransferCell, recipeKey, reduceJson, refreshDraft, resetDraft, resolveDefaultRecipe, resolveTransferPreferences, resolveTransferRegistry, sealArtifact, sealDraft, sealTransferArtifact, sectionLayout, serialize, setPersonDefaultRecipe, sourceChanged, spanMap, stubText, transformRows, undoDraft };
1439
+ export { type AgentPayloadEnvironment, type AgentPayloadInput, type AiPreparation, type Artifact, type BoundAllMatching, type BuiltInFormatId, type CapturedAllMatching, type CapturedSource, type Column, ContentTransferError, type Coverage, type Delivery, type DeliveryOutcome, type Draft, EMPTY_STRUCTURE, type ExportPage, type ExportProjection, FORMAT_ADAPTERS, type FormatAdapter, type FormatEngine, type FormatOptions, type Json$2 as Json, type NodeLimit, type NormalizeTransferJsonOptions, type Notice, type Omission, type OutputSpan, type PageAction, type Payload, type PreparationOptions, type PreparationSession, type QuerySnapshot, type RawSnapshot, type Receipt, type RecipeOrigin, type ResolvedRecipe, type SealedArtifact, type Section, type SectionLayout, type ServerOperation, type Snapshot, type Source, type SpanMap, type StructureRecipe, type SurfaceHandle, TRANSFER_DEFAULT_RECIPE_SETTING, type TransferLimits, type TransferOperation, type TransferOutcome, type TransferPreferenceOverrides, type TransferPreferences, type TransferScope, type TransferSurfaceDeclaration, type TransferTarget, type Transform, type Transport, type WriteTargetRef, agentPayloadWithSpans, applyJsonStructure, applySectionSelection, applySectionStructure, applyStructureToJson, applyTransferLimits, assembleAgentPayload, buildAgentPayload, capture, collectAllMatching, concretePointers, createBrowserTransport, createDelivery, createDraft, createSurfaceTransferHandle, deriveDraft, directSource, displayPath, editDraft, eligibleFormats, exportedColumns, extensionForLanguage, fenceJsonBlock, formatAdapter, isProseSection, isSealed, joinPointer, jsonSize, jsonTextSpans, nodeChars, normalizeTransferJson, offsetSpans, openPreparation, outputPointer, patternBelow, patternCovers, patternMatches, pointerSegments, projectSnapshot, readTransferCell, recipeKey, reduceJson, refreshDraft, resetDraft, resolveDefaultRecipe, resolveTransferPreferences, resolveTransferRegistry, sealArtifact, sealDraft, sealTransferArtifact, sectionLayout, serialize, setPersonDefaultRecipe, sourceChanged, spanMap, stubText, transformRows, undoDraft };