@contractspec/lib.surface-runtime 0.3.0 → 0.3.2

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 (152) hide show
  1. package/dist/adapters/ai-sdk-stub.js +1 -6
  2. package/dist/adapters/blocknote-stub.js +3 -8
  3. package/dist/adapters/dnd-kit-adapter.js +6 -11
  4. package/dist/adapters/dnd-kit-stub.js +1 -6
  5. package/dist/adapters/floating-ui-stub.js +4 -9
  6. package/dist/adapters/index.js +7 -176
  7. package/dist/adapters/interfaces.js +0 -1
  8. package/dist/adapters/motion-stub.js +2 -7
  9. package/dist/adapters/resizable-panels-stub.js +7 -12
  10. package/dist/browser/adapters/ai-sdk-stub.js +1 -5
  11. package/dist/browser/adapters/blocknote-stub.js +3 -7
  12. package/dist/browser/adapters/dnd-kit-adapter.js +6 -10
  13. package/dist/browser/adapters/dnd-kit-stub.js +1 -5
  14. package/dist/browser/adapters/floating-ui-stub.js +4 -8
  15. package/dist/browser/adapters/index.js +7 -175
  16. package/dist/browser/adapters/motion-stub.js +2 -6
  17. package/dist/browser/adapters/resizable-panels-stub.js +5 -9
  18. package/dist/browser/evals/golden-harness.js +4 -825
  19. package/dist/browser/examples/pm-workbench.bundle.js +2 -316
  20. package/dist/browser/i18n/catalogs/en.js +1 -5
  21. package/dist/browser/i18n/catalogs/es.js +1 -5
  22. package/dist/browser/i18n/catalogs/fr.js +1 -5
  23. package/dist/browser/i18n/catalogs/index.js +3 -133
  24. package/dist/browser/i18n/index.js +3 -168
  25. package/dist/browser/i18n/keys.js +1 -5
  26. package/dist/browser/i18n/messages.js +6 -137
  27. package/dist/browser/index.js +4 -2470
  28. package/dist/browser/react/BundleProvider.js +12 -19
  29. package/dist/browser/react/BundleRenderer.js +15 -662
  30. package/dist/browser/react/OverlayConflictResolver.js +12 -180
  31. package/dist/browser/react/PatchProposalCard.js +9 -177
  32. package/dist/browser/react/RegionRenderer.js +14 -60
  33. package/dist/browser/react/SlotRenderer.js +15 -58
  34. package/dist/browser/react/WidgetPalette.js +6 -10
  35. package/dist/browser/react/index.js +14 -794
  36. package/dist/browser/runtime/apply-surface-patch.js +3 -208
  37. package/dist/browser/runtime/audit-events.js +8 -19
  38. package/dist/browser/runtime/build-context.js +2 -6
  39. package/dist/browser/runtime/extension-registry.js +3 -9
  40. package/dist/browser/runtime/field-renderer-registry.js +5 -11
  41. package/dist/browser/runtime/index.js +54 -1487
  42. package/dist/browser/runtime/overlay-alignment.js +8 -19
  43. package/dist/browser/runtime/overlay-signer.js +2 -7
  44. package/dist/browser/runtime/override-store.js +3 -9
  45. package/dist/browser/runtime/planner-prompt.js +2 -6
  46. package/dist/browser/runtime/planner-tools.js +3 -9
  47. package/dist/browser/runtime/policy-eval.js +3 -135
  48. package/dist/browser/runtime/preference-adapter.js +2 -62
  49. package/dist/browser/runtime/resolve-bundle.js +10 -447
  50. package/dist/browser/runtime/resolve-preferences.js +3 -7
  51. package/dist/browser/runtime/rollback.js +2 -325
  52. package/dist/browser/runtime/widget-registry.js +1 -5
  53. package/dist/browser/spec/define-module-bundle.js +2 -67
  54. package/dist/browser/spec/index.js +9 -317
  55. package/dist/browser/spec/validate-bundle.js +3 -8
  56. package/dist/browser/spec/validate-surface-patch.js +5 -11
  57. package/dist/browser/telemetry/index.js +4 -16
  58. package/dist/browser/telemetry/surface-metrics.js +7 -16
  59. package/dist/evals/golden-context.js +0 -1
  60. package/dist/evals/golden-harness.js +4 -826
  61. package/dist/examples/pm-workbench.bundle.js +2 -317
  62. package/dist/i18n/catalogs/en.js +1 -6
  63. package/dist/i18n/catalogs/es.js +1 -6
  64. package/dist/i18n/catalogs/fr.js +1 -6
  65. package/dist/i18n/catalogs/index.js +3 -134
  66. package/dist/i18n/index.js +3 -169
  67. package/dist/i18n/keys.js +1 -6
  68. package/dist/i18n/messages.js +6 -138
  69. package/dist/index.js +4 -2471
  70. package/dist/node/adapters/ai-sdk-stub.js +1 -5
  71. package/dist/node/adapters/blocknote-stub.js +3 -7
  72. package/dist/node/adapters/dnd-kit-adapter.js +6 -10
  73. package/dist/node/adapters/dnd-kit-stub.js +1 -5
  74. package/dist/node/adapters/floating-ui-stub.js +4 -8
  75. package/dist/node/adapters/index.js +7 -175
  76. package/dist/node/adapters/motion-stub.js +2 -6
  77. package/dist/node/adapters/resizable-panels-stub.js +5 -9
  78. package/dist/node/evals/golden-harness.js +4 -825
  79. package/dist/node/examples/pm-workbench.bundle.js +2 -316
  80. package/dist/node/i18n/catalogs/en.js +1 -5
  81. package/dist/node/i18n/catalogs/es.js +1 -5
  82. package/dist/node/i18n/catalogs/fr.js +1 -5
  83. package/dist/node/i18n/catalogs/index.js +3 -133
  84. package/dist/node/i18n/index.js +3 -168
  85. package/dist/node/i18n/keys.js +1 -5
  86. package/dist/node/i18n/messages.js +6 -137
  87. package/dist/node/index.js +4 -2470
  88. package/dist/node/react/BundleProvider.js +12 -19
  89. package/dist/node/react/BundleRenderer.js +15 -662
  90. package/dist/node/react/OverlayConflictResolver.js +12 -180
  91. package/dist/node/react/PatchProposalCard.js +9 -177
  92. package/dist/node/react/RegionRenderer.js +14 -60
  93. package/dist/node/react/SlotRenderer.js +15 -58
  94. package/dist/node/react/WidgetPalette.js +6 -10
  95. package/dist/node/react/index.js +14 -794
  96. package/dist/node/runtime/apply-surface-patch.js +3 -208
  97. package/dist/node/runtime/audit-events.js +8 -19
  98. package/dist/node/runtime/build-context.js +2 -6
  99. package/dist/node/runtime/extension-registry.js +3 -9
  100. package/dist/node/runtime/field-renderer-registry.js +5 -11
  101. package/dist/node/runtime/index.js +54 -1487
  102. package/dist/node/runtime/overlay-alignment.js +8 -19
  103. package/dist/node/runtime/overlay-signer.js +2 -7
  104. package/dist/node/runtime/override-store.js +3 -9
  105. package/dist/node/runtime/planner-prompt.js +2 -6
  106. package/dist/node/runtime/planner-tools.js +3 -9
  107. package/dist/node/runtime/policy-eval.js +3 -135
  108. package/dist/node/runtime/preference-adapter.js +2 -62
  109. package/dist/node/runtime/resolve-bundle.js +10 -447
  110. package/dist/node/runtime/resolve-preferences.js +3 -7
  111. package/dist/node/runtime/rollback.js +2 -325
  112. package/dist/node/runtime/widget-registry.js +1 -5
  113. package/dist/node/spec/define-module-bundle.js +2 -67
  114. package/dist/node/spec/index.js +9 -317
  115. package/dist/node/spec/validate-bundle.js +3 -8
  116. package/dist/node/spec/validate-surface-patch.js +5 -11
  117. package/dist/node/telemetry/index.js +4 -16
  118. package/dist/node/telemetry/surface-metrics.js +7 -16
  119. package/dist/react/BundleProvider.js +12 -20
  120. package/dist/react/BundleRenderer.js +15 -663
  121. package/dist/react/OverlayConflictResolver.js +12 -181
  122. package/dist/react/PatchProposalCard.js +9 -178
  123. package/dist/react/RegionRenderer.js +14 -61
  124. package/dist/react/SlotRenderer.js +15 -59
  125. package/dist/react/WidgetPalette.js +6 -11
  126. package/dist/react/index.js +14 -795
  127. package/dist/runtime/apply-surface-patch.js +3 -209
  128. package/dist/runtime/audit-events.js +8 -20
  129. package/dist/runtime/build-context.js +2 -7
  130. package/dist/runtime/extension-registry.js +3 -10
  131. package/dist/runtime/field-renderer-registry.js +9 -16
  132. package/dist/runtime/index.js +54 -1488
  133. package/dist/runtime/overlay-alignment.js +8 -20
  134. package/dist/runtime/overlay-signer.js +2 -8
  135. package/dist/runtime/override-store.js +3 -10
  136. package/dist/runtime/planner-prompt.js +11 -9
  137. package/dist/runtime/planner-tools.js +4 -11
  138. package/dist/runtime/policy-eval.js +3 -136
  139. package/dist/runtime/preference-adapter.js +2 -63
  140. package/dist/runtime/resolve-bundle.js +10 -448
  141. package/dist/runtime/resolve-preferences.js +3 -8
  142. package/dist/runtime/rollback.js +2 -326
  143. package/dist/runtime/widget-registry.js +1 -6
  144. package/dist/spec/define-module-bundle.js +2 -68
  145. package/dist/spec/index.js +9 -318
  146. package/dist/spec/types.js +0 -1
  147. package/dist/spec/validate-bundle.js +3 -9
  148. package/dist/spec/validate-surface-patch.js +5 -12
  149. package/dist/spec/verification-snapshot-types.js +0 -1
  150. package/dist/telemetry/index.js +4 -17
  151. package/dist/telemetry/surface-metrics.js +7 -17
  152. package/package.json +7 -7
@@ -1,823 +1,6 @@
1
- // src/telemetry/surface-metrics.ts
2
- import {
3
- createCounter,
4
- createHistogram
5
- } from "@contractspec/lib.observability/metrics";
6
- var METER_NAME = "@contractspec/lib.surface-runtime";
7
- var resolutionDurationMs = createHistogram("bundle_surface_resolution_duration_ms", "Time to resolve bundle spec to surface plan in milliseconds", METER_NAME);
8
- var patchAcceptanceCounter = createCounter("bundle_surface_patch_acceptance_total", "Total AI patch proposals accepted by user", METER_NAME);
9
- var patchRejectionCounter = createCounter("bundle_surface_patch_rejection_total", "Total AI patch proposals rejected by user", METER_NAME);
10
- var policyDenialCounter = createCounter("bundle_surface_policy_denial_total", "Total policy denials (actions denied by policy)", METER_NAME);
11
- var surfaceFallbackCounter = createCounter("bundle_surface_fallback_total", "Total surface or layout fallbacks during resolution", METER_NAME);
12
- var missingRendererCounter = createCounter("bundle_surface_renderer_missing_total", "Total slots with no renderer for requested node kind", METER_NAME);
13
- // src/runtime/resolve-preferences.ts
14
- var DIMENSION_KEYS = [
15
- "guidance",
16
- "density",
17
- "dataDepth",
18
- "control",
19
- "media",
20
- "pace",
21
- "narrative"
22
- ];
23
- var SCOPE_ORDER = [
24
- "user",
25
- "workspace-user",
26
- "bundle",
27
- "surface",
28
- "entity",
29
- "session"
30
- ];
31
- function mergeByScope(layers, ctx) {
32
- const merged = { ...ctx.preferences };
33
- const sourceByDimension = {};
34
- for (const scope of SCOPE_ORDER) {
35
- const layer = layers[scope];
36
- if (!layer)
37
- continue;
38
- for (const dim of DIMENSION_KEYS) {
39
- const val = layer[dim];
40
- if (val !== undefined) {
41
- merged[dim] = val;
42
- sourceByDimension[dim] = scope;
43
- }
44
- }
45
- }
46
- for (const dim of DIMENSION_KEYS) {
47
- if (sourceByDimension[dim] === undefined) {
48
- sourceByDimension[dim] = "session";
49
- }
50
- }
51
- return { canonical: merged, sourceByDimension };
52
- }
53
- function resolveConstraints(_canonical, _ctx) {
54
- return { constrained: {}, notes: [] };
55
- }
56
- function resolvePreferenceProfile(ctx) {
57
- const layers = {
58
- session: ctx.preferences
59
- };
60
- const { canonical, sourceByDimension } = mergeByScope(layers, ctx);
61
- const { constrained, notes } = resolveConstraints(canonical, ctx);
62
- return {
63
- canonical,
64
- sourceByDimension,
65
- constrained,
66
- notes
67
- };
68
- }
69
-
70
- // src/spec/validate-surface-patch.ts
71
- var VALID_OPS = [
72
- "insert-node",
73
- "replace-node",
74
- "remove-node",
75
- "move-node",
76
- "resize-panel",
77
- "set-layout",
78
- "reveal-field",
79
- "hide-field",
80
- "promote-action",
81
- "set-focus"
82
- ];
83
- var VALID_NODE_KINDS = [
84
- "metric-strip",
85
- "data-view",
86
- "entity-card",
87
- "entity-header",
88
- "entity-summary",
89
- "entity-section",
90
- "entity-field",
91
- "entity-activity",
92
- "entity-relations",
93
- "entity-timeline",
94
- "entity-comments",
95
- "entity-attachments",
96
- "entity-view-switcher",
97
- "entity-automation-panel",
98
- "rich-doc",
99
- "chat-thread",
100
- "assistant-panel",
101
- "action-bar",
102
- "timeline",
103
- "board",
104
- "table",
105
- "calendar",
106
- "form",
107
- "chart",
108
- "relation-graph",
109
- "custom-widget"
110
- ];
111
- function validateSurfaceNode(node, path) {
112
- if (!node.nodeId || typeof node.nodeId !== "string") {
113
- throw new Error(`${path}: nodeId must be a non-empty string`);
114
- }
115
- if (!node.kind || !VALID_NODE_KINDS.includes(node.kind)) {
116
- throw new Error(`${path}: kind must be one of ${VALID_NODE_KINDS.join(", ")}`);
117
- }
118
- if (node.children) {
119
- for (let i = 0;i < node.children.length; i++) {
120
- const child = node.children[i];
121
- if (child)
122
- validateSurfaceNode(child, `${path}.children[${i}]`);
123
- }
124
- }
125
- }
126
- function validateSurfacePatchOp(op, index) {
127
- const path = `ops[${index}]`;
128
- if (!op || typeof op !== "object" || !("op" in op)) {
129
- throw new Error(`${path}: must be an object with op field`);
130
- }
131
- const opType = op.op;
132
- if (!VALID_OPS.includes(opType)) {
133
- throw new Error(`${path}: op must be one of ${VALID_OPS.join(", ")}`);
134
- }
135
- switch (op.op) {
136
- case "insert-node":
137
- if (!op.slotId || typeof op.slotId !== "string") {
138
- throw new Error(`${path}: insert-node requires slotId string`);
139
- }
140
- if (!op.node) {
141
- throw new Error(`${path}: insert-node requires node`);
142
- }
143
- validateSurfaceNode(op.node, `${path}.node`);
144
- if (op.index !== undefined && typeof op.index !== "number") {
145
- throw new Error(`${path}: insert-node index must be number if present`);
146
- }
147
- break;
148
- case "replace-node":
149
- if (!op.nodeId || typeof op.nodeId !== "string") {
150
- throw new Error(`${path}: replace-node requires nodeId string`);
151
- }
152
- if (!op.node) {
153
- throw new Error(`${path}: replace-node requires node`);
154
- }
155
- validateSurfaceNode(op.node, `${path}.node`);
156
- break;
157
- case "remove-node":
158
- if (!op.nodeId || typeof op.nodeId !== "string") {
159
- throw new Error(`${path}: remove-node requires nodeId string`);
160
- }
161
- break;
162
- case "move-node":
163
- if (!op.nodeId || typeof op.nodeId !== "string") {
164
- throw new Error(`${path}: move-node requires nodeId string`);
165
- }
166
- if (!op.toSlotId || typeof op.toSlotId !== "string") {
167
- throw new Error(`${path}: move-node requires toSlotId string`);
168
- }
169
- if (op.index !== undefined && typeof op.index !== "number") {
170
- throw new Error(`${path}: move-node index must be number if present`);
171
- }
172
- break;
173
- case "resize-panel":
174
- if (!op.persistKey || typeof op.persistKey !== "string") {
175
- throw new Error(`${path}: resize-panel requires persistKey string`);
176
- }
177
- if (!Array.isArray(op.sizes) || op.sizes.some((s) => typeof s !== "number")) {
178
- throw new Error(`${path}: resize-panel requires sizes number[]`);
179
- }
180
- break;
181
- case "set-layout":
182
- if (!op.layoutId || typeof op.layoutId !== "string") {
183
- throw new Error(`${path}: set-layout requires layoutId string`);
184
- }
185
- break;
186
- case "reveal-field":
187
- case "hide-field":
188
- if (!op.fieldId || typeof op.fieldId !== "string") {
189
- throw new Error(`${path}: ${op.op} requires fieldId string`);
190
- }
191
- break;
192
- case "promote-action": {
193
- if (!op.actionId || typeof op.actionId !== "string") {
194
- throw new Error(`${path}: promote-action requires actionId string`);
195
- }
196
- const validPlacements = ["header", "inline", "context", "assistant"];
197
- if (!op.placement || !validPlacements.includes(op.placement)) {
198
- throw new Error(`${path}: promote-action placement must be one of ${validPlacements.join(", ")}`);
199
- }
200
- break;
201
- }
202
- case "set-focus":
203
- if (!op.targetId || typeof op.targetId !== "string") {
204
- throw new Error(`${path}: set-focus requires targetId string`);
205
- }
206
- break;
207
- default:
208
- throw new Error(`${path}: unknown op "${opType}"`);
209
- }
210
- }
211
- function validateSurfacePatch(ops) {
212
- if (!Array.isArray(ops)) {
213
- throw new Error("Patch ops must be an array");
214
- }
215
- for (let i = 0;i < ops.length; i++) {
216
- const op = ops[i];
217
- if (op)
218
- validateSurfacePatchOp(op, i);
219
- }
220
- }
221
- function validateSurfaceNodeAgainstKinds(node, allowedKinds, path) {
222
- if (!allowedKinds.includes(node.kind)) {
223
- throw new Error(`${path}: kind "${node.kind}" not in allowed list [${allowedKinds.join(", ")}]`);
224
- }
225
- if (node.children) {
226
- for (let i = 0;i < node.children.length; i++) {
227
- const child = node.children[i];
228
- if (child)
229
- validateSurfaceNodeAgainstKinds(child, allowedKinds, `${path}.children[${i}]`);
230
- }
231
- }
232
- }
233
- function validatePatchProposal(ops, constraints) {
234
- if (!Array.isArray(ops)) {
235
- throw new Error("Patch ops must be an array");
236
- }
237
- const { allowedOps, allowedSlots, allowedNodeKinds } = constraints;
238
- for (let i = 0;i < ops.length; i++) {
239
- const op = ops[i];
240
- if (!op)
241
- continue;
242
- const path = `ops[${i}]`;
243
- if (!allowedOps.includes(op.op)) {
244
- throw new Error(`${path}: op "${op.op}" not in allowed list [${allowedOps.join(", ")}]`);
245
- }
246
- switch (op.op) {
247
- case "insert-node":
248
- if (!allowedSlots.includes(op.slotId)) {
249
- throw new Error(`${path}: slotId "${op.slotId}" not in allowed slots [${allowedSlots.join(", ")}]`);
250
- }
251
- if (op.node) {
252
- validateSurfaceNodeAgainstKinds(op.node, allowedNodeKinds, `${path}.node`);
253
- }
254
- break;
255
- case "move-node":
256
- if (!allowedSlots.includes(op.toSlotId)) {
257
- throw new Error(`${path}: toSlotId "${op.toSlotId}" not in allowed slots [${allowedSlots.join(", ")}]`);
258
- }
259
- break;
260
- case "replace-node":
261
- if (op.node) {
262
- validateSurfaceNodeAgainstKinds(op.node, allowedNodeKinds, `${path}.node`);
263
- }
264
- break;
265
- default:
266
- break;
267
- }
268
- }
269
- validateSurfacePatch(ops);
270
- }
271
-
272
- // src/runtime/apply-surface-patch.ts
273
- import { Logger } from "@contractspec/lib.observability";
274
- var logger = new Logger("@contractspec/lib.surface-runtime");
275
- function findNode(nodes, nodeId) {
276
- for (const n of nodes) {
277
- if (n.nodeId === nodeId)
278
- return n;
279
- if (n.children) {
280
- const found = findNode(n.children, nodeId);
281
- if (found)
282
- return found;
283
- }
284
- }
285
- return;
286
- }
287
- function collectNodeIds(nodes) {
288
- const ids = new Set;
289
- for (const n of nodes) {
290
- ids.add(n.nodeId);
291
- if (n.children)
292
- collectNodeIds(n.children).forEach((id) => ids.add(id));
293
- }
294
- return ids;
295
- }
296
- function validateOp(op, nodeIds) {
297
- if (op.op === "remove-node" || op.op === "replace-node" || op.op === "move-node") {
298
- if (!nodeIds.has(op.nodeId)) {
299
- throw new Error(`Patch op references unknown nodeId: ${op.nodeId}`);
300
- }
301
- }
302
- if (op.op === "insert-node" && !op.node?.nodeId) {
303
- throw new Error("insert-node requires node with nodeId");
304
- }
305
- }
306
- function produceInverse(op, plan) {
307
- switch (op.op) {
308
- case "insert-node":
309
- return op.node ? { op: "remove-node", nodeId: op.node.nodeId } : null;
310
- case "remove-node": {
311
- const node = findNode(plan.nodes, op.nodeId);
312
- return node ? { op: "insert-node", slotId: "primary", node } : null;
313
- }
314
- case "replace-node": {
315
- const prev = findNode(plan.nodes, op.nodeId);
316
- return prev ? { op: "replace-node", nodeId: op.nodeId, node: prev } : null;
317
- }
318
- case "set-layout":
319
- return { op: "set-layout", layoutId: plan.layoutId };
320
- case "reveal-field":
321
- return { op: "hide-field", fieldId: op.fieldId };
322
- case "hide-field":
323
- return { op: "reveal-field", fieldId: op.fieldId };
324
- case "move-node":
325
- case "resize-panel":
326
- case "set-focus":
327
- case "promote-action":
328
- return null;
329
- default:
330
- return null;
331
- }
332
- }
333
- function applySurfacePatch(plan, ops) {
334
- if (ops.length === 0)
335
- return { plan, inverseOps: [] };
336
- validateSurfacePatch(ops);
337
- const nodeIds = collectNodeIds(plan.nodes);
338
- for (const op of ops) {
339
- validateOp(op, nodeIds);
340
- }
341
- let nextNodes = [...plan.nodes];
342
- let nextLayoutId = plan.layoutId;
343
- const inverseOps = [];
344
- for (const op of ops) {
345
- const inv = produceInverse(op, {
346
- ...plan,
347
- nodes: nextNodes,
348
- layoutId: nextLayoutId
349
- });
350
- if (inv)
351
- inverseOps.unshift(inv);
352
- switch (op.op) {
353
- case "insert-node":
354
- if (op.node)
355
- nextNodes = [...nextNodes, op.node];
356
- break;
357
- case "remove-node":
358
- nextNodes = nextNodes.filter((n) => n.nodeId !== op.nodeId);
359
- break;
360
- case "replace-node": {
361
- const replace = (nodes) => nodes.map((n) => n.nodeId === op.nodeId ? op.node : { ...n, children: n.children ? replace(n.children) : undefined });
362
- nextNodes = replace(nextNodes);
363
- break;
364
- }
365
- case "set-layout":
366
- nextLayoutId = op.layoutId;
367
- break;
368
- case "move-node":
369
- case "resize-panel":
370
- case "set-focus":
371
- case "reveal-field":
372
- case "hide-field":
373
- case "promote-action":
374
- break;
375
- }
376
- }
377
- const result = {
378
- plan: { ...plan, nodes: nextNodes, layoutId: nextLayoutId },
379
- inverseOps
380
- };
381
- logger.info("bundle.surface.patch.applied", {
382
- bundleKey: plan.bundleKey,
383
- surfaceId: plan.surfaceId,
384
- opCount: ops.length,
385
- opTypes: [...new Set(ops.map((o) => o.op))]
386
- });
387
- return result;
388
- }
389
-
390
- // src/runtime/override-store.ts
391
- function buildOverrideTargetKey(bundleKey, surfaceId, routeId) {
392
- return routeId ? `${bundleKey}:${routeId}:${surfaceId}` : `${bundleKey}:${surfaceId}`;
393
- }
394
- function createOverrideStoreWithApprovalGate(store, options) {
395
- const { requireApprovalForWorkspacePatches = false, requestApproval } = options;
396
- return {
397
- list: store.list.bind(store),
398
- async save(scope, targetKey, patch, saveOptions) {
399
- if (requireApprovalForWorkspacePatches && scope === "workspace" && requestApproval) {
400
- const approved = await requestApproval({ scope, targetKey, patch });
401
- if (!approved) {
402
- throw new Error("Workspace overlay save rejected: approval required and not granted");
403
- }
404
- }
405
- return store.save(scope, targetKey, patch, saveOptions);
406
- },
407
- remove: store.remove.bind(store)
408
- };
409
- }
410
- function createInMemoryOverrideStore() {
411
- const overrides = new Map;
412
- function nextId() {
413
- return `ov_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
414
- }
415
- return {
416
- async list(scope, targetKey) {
417
- return Array.from(overrides.values()).filter((o) => o.scope === scope && o.targetKey === targetKey);
418
- },
419
- async save(scope, targetKey, patch, options) {
420
- const overrideId = options?.overrideId ?? nextId();
421
- const stored = {
422
- overrideId,
423
- scope,
424
- targetKey,
425
- patch,
426
- createdAt: new Date().toISOString(),
427
- createdBy: options?.createdBy
428
- };
429
- overrides.set(overrideId, stored);
430
- return overrideId;
431
- },
432
- async remove(overrideId) {
433
- overrides.delete(overrideId);
434
- }
435
- };
436
- }
437
-
438
- // src/runtime/resolve-bundle.ts
439
- import { traceAsync } from "@contractspec/lib.observability/tracing";
440
- import { Logger as Logger2 } from "@contractspec/lib.observability";
441
- var logger2 = new Logger2("@contractspec/lib.surface-runtime");
442
- function getOpTarget(op) {
443
- switch (op.op) {
444
- case "hide-field":
445
- case "reveal-field":
446
- return `field:${op.fieldId}`;
447
- case "remove-node":
448
- case "replace-node":
449
- case "move-node":
450
- return `node:${op.nodeId}`;
451
- case "insert-node":
452
- return op.slotId ? `slot:${op.slotId}` : null;
453
- default:
454
- return null;
455
- }
456
- }
457
- function matchRoute(pathPattern, route) {
458
- if (pathPattern === route)
459
- return true;
460
- const patternParts = pathPattern.split("/");
461
- const routeParts = route.split("/");
462
- if (patternParts.length !== routeParts.length)
463
- return false;
464
- for (let i = 0;i < patternParts.length; i++) {
465
- const p = patternParts[i];
466
- const r = routeParts[i];
467
- if (p?.startsWith(":"))
468
- continue;
469
- if (p !== r)
470
- return false;
471
- }
472
- return true;
473
- }
474
- function selectSurface(spec, ctx) {
475
- const route = spec.routes.find((r) => matchRoute(r.path, ctx.route)) ?? spec.routes[0];
476
- if (!route) {
477
- throw new Error("No routes declared in bundle spec.");
478
- }
479
- const fallbackRoute = !spec.routes.find((r) => matchRoute(r.path, ctx.route));
480
- let surface = spec.surfaces[route.defaultSurface];
481
- let fallback;
482
- if (!surface && route.candidateSurfaces?.length) {
483
- for (const sid of route.candidateSurfaces) {
484
- surface = spec.surfaces[sid];
485
- if (surface) {
486
- fallback = `surface=${sid}`;
487
- break;
488
- }
489
- }
490
- }
491
- if (!surface) {
492
- const overview = Object.values(spec.surfaces).find((s) => s.kind === "overview");
493
- if (overview) {
494
- surface = overview;
495
- fallback = "surface=overview";
496
- }
497
- }
498
- if (!surface) {
499
- throw new Error(`Default surface "${route.defaultSurface}" was not found.`);
500
- }
501
- return {
502
- surface,
503
- routeId: route.routeId,
504
- fallback: fallback ?? (fallbackRoute ? "route" : undefined)
505
- };
506
- }
507
- function selectLayout(surface, ctx, spec) {
508
- let preferredLayoutId;
509
- if (ctx.activeViewId && ctx.entity?.type && spec?.entities?.viewKinds) {
510
- const viewKind = spec.entities.viewKinds[ctx.activeViewId];
511
- const entityType = spec.entities.entityTypes[ctx.entity.type];
512
- if (viewKind?.defaultLayoutId && entityType?.supportedViews?.includes(ctx.activeViewId)) {
513
- preferredLayoutId = viewKind.defaultLayoutId;
514
- }
515
- }
516
- const matching = surface.layouts.filter((candidate) => candidate.when?.(ctx) ?? true);
517
- let layout;
518
- if (preferredLayoutId) {
519
- layout = matching.find((l) => l.layoutId === preferredLayoutId) ?? surface.layouts.find((l) => l.layoutId === preferredLayoutId) ?? matching[matching.length - 1] ?? surface.layouts[0];
520
- } else {
521
- layout = matching[matching.length - 1] ?? surface.layouts[0];
522
- }
523
- if (!layout) {
524
- throw new Error(`Surface "${surface.surfaceId}" has no layouts.`);
525
- }
526
- const layoutFallback = matching.length === 0 && surface.layouts.length > 0;
527
- return { layout, layoutFallback: layoutFallback || undefined };
528
- }
529
- function resolveDataRecipes(recipes, ctx) {
530
- const bindings = {};
531
- for (const r of recipes) {
532
- if (r.when?.(ctx) ?? true) {
533
- const key = r.hydrateInto ?? r.recipeId;
534
- bindings[key] = { recipeId: r.recipeId, source: r.source, _stub: true };
535
- }
536
- }
537
- return bindings;
538
- }
539
- function allowFromDecision(decision) {
540
- if (!decision)
541
- return true;
542
- return decision.effect === "allow" || decision.effect === "allow-session-only";
543
- }
544
- function generateResolutionId() {
545
- return `res_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
546
- }
547
- var OVERLAY_SCOPE_ORDER = [
548
- "system",
549
- "workspace",
550
- "team",
551
- "user",
552
- "session"
553
- ];
554
- function buildAdaptation(ctx) {
555
- const profile = resolvePreferenceProfile(ctx);
556
- const notes = [...profile.notes];
557
- const constrainedEntries = Object.entries(profile.constrained);
558
- if (constrainedEntries.length > 0) {
559
- notes.push(`constrained: ${constrainedEntries.map(([k, v]) => `${k}=${v}`).join(", ")}`);
560
- }
561
- return {
562
- appliedDimensions: profile.canonical,
563
- notes
564
- };
565
- }
566
- async function resolveBundle(spec, ctx, options) {
567
- return traceAsync("surface.resolveBundle", async (span) => {
568
- const start = performance.now();
569
- try {
570
- const plan = await resolveBundleInternal(spec, ctx, options);
571
- const durationMs = performance.now() - start;
572
- resolutionDurationMs.record(durationMs, {
573
- bundleKey: spec.meta.key,
574
- surfaceId: plan.surfaceId,
575
- fallback: plan.surfaceId === "_error" ? "error" : plan.audit.reasons.some((r) => r.startsWith("fallback=")) ? "yes" : "no"
576
- });
577
- span.setAttribute("bundle.key", spec.meta.key);
578
- span.setAttribute("surface.id", plan.surfaceId);
579
- span.setAttribute("resolution.duration_ms", durationMs);
580
- logger2.info("bundle.surface.resolved", {
581
- bundleKey: spec.meta.key,
582
- surfaceId: plan.surfaceId,
583
- layoutId: plan.layoutId,
584
- resolutionMs: Math.round(durationMs),
585
- fallback: plan.audit.reasons.some((r) => r.startsWith("fallback=")),
586
- nodeCount: plan.nodes.length
587
- });
588
- return plan;
589
- } catch (err) {
590
- const durationMs = performance.now() - start;
591
- resolutionDurationMs.record(durationMs, {
592
- bundleKey: spec.meta.key,
593
- surfaceId: "_error",
594
- fallback: "error"
595
- });
596
- return createErrorPlan(spec, ctx, err);
597
- }
598
- }, "@contractspec/lib.surface-runtime");
599
- }
600
- async function resolveBundleInternal(spec, ctx, options) {
601
- const {
602
- surface,
603
- routeId,
604
- fallback: surfaceFallback
605
- } = selectSurface(spec, ctx);
606
- const { layout, layoutFallback } = selectLayout(surface, ctx, spec);
607
- let bindings = resolveDataRecipes(surface.data, ctx);
608
- const redactBinding = options?.policy?.redactBinding;
609
- if (redactBinding) {
610
- const redacted = {};
611
- for (const [k, v] of Object.entries(bindings)) {
612
- redacted[k] = redactBinding(k, ctx) ?? v;
613
- }
614
- bindings = redacted;
615
- }
616
- let nodes = [];
617
- const evaluateNode = options?.policy?.evaluateNode;
618
- if (evaluateNode) {
619
- nodes = nodes.filter((n) => allowFromDecision(evaluateNode(n, ctx)));
620
- }
621
- const reasons = [
622
- `surface=${surface.surfaceId}`,
623
- `layout=${layout.layoutId}`,
624
- `density=${ctx.preferences.density}`,
625
- `narrative=${ctx.preferences.narrative}`
626
- ];
627
- if (surfaceFallback) {
628
- reasons.push(`fallback=${surfaceFallback}`);
629
- surfaceFallbackCounter.add(1, {
630
- bundleKey: spec.meta.key,
631
- type: "surface"
632
- });
633
- }
634
- if (layoutFallback) {
635
- reasons.push("fallback=layout");
636
- surfaceFallbackCounter.add(1, { bundleKey: spec.meta.key, type: "layout" });
637
- }
638
- const resolutionId = generateResolutionId();
639
- const plan = {
640
- bundleKey: spec.meta.key,
641
- surfaceId: surface.surfaceId,
642
- layoutId: layout.layoutId,
643
- layoutRoot: layout.root,
644
- nodes,
645
- actions: surface.actions ?? [],
646
- commands: surface.commands ?? [],
647
- bindings,
648
- adaptation: buildAdaptation(ctx),
649
- overlays: [],
650
- ai: {
651
- plannerId: spec.ai?.plannerId
652
- },
653
- audit: {
654
- resolutionId,
655
- createdAt: new Date().toISOString(),
656
- reasons
657
- },
658
- locale: ctx.locale
659
- };
660
- options?.audit?.emit({
661
- eventId: `evt_${resolutionId}`,
662
- at: new Date().toISOString(),
663
- actorId: ctx.actorId,
664
- source: "system",
665
- bundleKey: spec.meta.key,
666
- surfaceId: surface.surfaceId,
667
- eventType: "surface.resolved",
668
- payload: {
669
- resolutionId,
670
- layoutId: layout.layoutId,
671
- reasons,
672
- nodeCount: nodes.length
673
- }
674
- });
675
- let finalPlan = plan;
676
- if (options?.overlayMerge) {
677
- const { overrideStore, scopes = OVERLAY_SCOPE_ORDER } = options.overlayMerge;
678
- const targetKey = buildOverrideTargetKey(spec.meta.key, surface.surfaceId, routeId);
679
- const appliedOverlays = [];
680
- const conflicts = [];
681
- const seenTargets = new Map;
682
- const conflictKeys = new Set;
683
- for (const scope of scopes) {
684
- if (scope === "session")
685
- continue;
686
- const stored = await overrideStore.list(scope, targetKey);
687
- for (const ov of stored) {
688
- if (ov.patch.length === 0)
689
- continue;
690
- for (const op of ov.patch) {
691
- const opTarget = getOpTarget(op);
692
- if (opTarget) {
693
- const prev = seenTargets.get(opTarget);
694
- if (prev && prev.scope !== scope) {
695
- const ck = [opTarget, prev.scope, scope].sort().join(":");
696
- if (!conflictKeys.has(ck)) {
697
- conflictKeys.add(ck);
698
- conflicts.push({
699
- targetKey: opTarget,
700
- scopeA: prev.scope,
701
- scopeB: scope,
702
- overlayIdA: prev.overlayId,
703
- overlayIdB: ov.overrideId
704
- });
705
- }
706
- }
707
- seenTargets.set(opTarget, { scope, overlayId: ov.overrideId });
708
- }
709
- }
710
- try {
711
- const { plan: next } = applySurfacePatch(finalPlan, ov.patch);
712
- finalPlan = next;
713
- appliedOverlays.push({
714
- overlayId: ov.overrideId,
715
- scope,
716
- appliedOps: ov.patch.length
717
- });
718
- } catch (err) {
719
- logger2.warn("bundle.overlay.apply.failed", {
720
- overlayId: ov.overrideId,
721
- scope,
722
- error: err instanceof Error ? err.message : String(err)
723
- });
724
- }
725
- }
726
- }
727
- finalPlan = {
728
- ...finalPlan,
729
- overlays: appliedOverlays,
730
- overlayConflicts: conflicts.length > 0 ? conflicts : undefined
731
- };
732
- }
733
- return finalPlan;
734
- }
735
- function createErrorPlan(spec, ctx, err) {
736
- const message = err instanceof Error ? err.message : String(err);
737
- const errorLayoutRoot = {
738
- type: "stack",
739
- direction: "vertical",
740
- children: [{ type: "slot", slotId: "primary" }]
741
- };
742
- return {
743
- bundleKey: spec.meta.key,
744
- surfaceId: "_error",
745
- layoutId: "_error",
746
- layoutRoot: errorLayoutRoot,
747
- nodes: [],
748
- actions: [],
749
- commands: [],
750
- bindings: {},
751
- adaptation: {
752
- appliedDimensions: ctx.preferences,
753
- notes: [`resolution failed: ${message}`]
754
- },
755
- overlays: [],
756
- ai: {},
757
- audit: {
758
- resolutionId: generateResolutionId(),
759
- createdAt: new Date().toISOString(),
760
- reasons: ["fallback=error", `error=${message}`]
761
- },
762
- locale: ctx.locale
763
- };
764
- }
765
-
766
- // src/runtime/build-context.ts
767
- var DEFAULT_PREFERENCES = {
768
- guidance: "hints",
769
- density: "standard",
770
- dataDepth: "detailed",
771
- control: "standard",
772
- media: "text",
773
- pace: "balanced",
774
- narrative: "top-down"
775
- };
776
- function buildContext(params) {
777
- const {
778
- route,
779
- params: routeParams = {},
780
- query = {},
781
- tenantId = "default",
782
- workspaceId,
783
- actorId,
784
- device = "desktop",
785
- preferences: partialPrefs = {},
786
- capabilities = [],
787
- featureFlags = [],
788
- mode,
789
- locale,
790
- timezone,
791
- entity,
792
- conversation,
793
- activeViewId
794
- } = params;
795
- const preferences = {
796
- ...DEFAULT_PREFERENCES,
797
- ...partialPrefs
798
- };
799
- return {
800
- tenantId,
801
- workspaceId,
802
- actorId,
803
- route,
804
- params: routeParams,
805
- query,
806
- device,
807
- mode,
808
- locale,
809
- timezone,
810
- entity,
811
- conversation,
812
- activeViewId,
813
- preferences,
814
- capabilities,
815
- featureFlags
816
- };
817
- }
818
-
819
- // src/evals/golden-harness.ts
820
- function toSnapshotPlan(plan) {
1
+ import { resolveBundle } from "../runtime/resolve-bundle";
2
+ import { buildContext } from "../runtime/build-context";
3
+ export function toSnapshotPlan(plan) {
821
4
  return {
822
5
  bundleKey: plan.bundleKey,
823
6
  surfaceId: plan.surfaceId,
@@ -831,7 +14,7 @@ function toSnapshotPlan(plan) {
831
14
  fallback: plan.audit.reasons.some((r) => r.startsWith("fallback="))
832
15
  };
833
16
  }
834
- async function runGoldenResolve(spec, ctx) {
17
+ export async function runGoldenResolve(spec, ctx) {
835
18
  const fullCtx = buildContext({
836
19
  route: ctx.route,
837
20
  params: ctx.params ?? {},
@@ -842,7 +25,3 @@ async function runGoldenResolve(spec, ctx) {
842
25
  const plan = await resolveBundle(spec, fullCtx);
843
26
  return toSnapshotPlan(plan);
844
27
  }
845
- export {
846
- toSnapshotPlan,
847
- runGoldenResolve
848
- };