@serene-pub/sdk 0.6.0-pr-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 (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
@@ -0,0 +1,131 @@
1
+ /**
2
+ * What a template can reference at one node of one document, typed (typed
3
+ * templates P3, 2026-09-27).
4
+ *
5
+ * ```ts
6
+ * const scope = templateScopeAt(doc, 'prompt', { genre: 'showcase.twenty-questions:genre/game' })
7
+ * scope.characters // { type: 'string', … } — the context builder's port schema
8
+ * scope.secretEntry // { type: 'string', … } — a band declared upstream
9
+ * scope.annex.fields['showcase.twenty-questions'].fields.secret // the annex declaration
10
+ * ```
11
+ *
12
+ * The scope is the union, checked for collisions, of:
13
+ *
14
+ * | Root | Where it comes from |
15
+ * |---|---|
16
+ * | the node's own names | the template slot's static `variables` — Assemble's are what `render()` supplies |
17
+ * | the `prompts` slot's fields | `slotToVarField`, followed through a slot reference (`slot.prompts({ node })`, an envoy's) |
18
+ * | the context builder's keys | the declared out-port schema (`Descriptor.portSchemas`) of whatever feeds a template-context in-port |
19
+ * | one per declared band | `rendersAt` over the node's `variables` slot — the laid-out string |
20
+ * | `annex` | every declared annex key of every owner in scope (`annexVarFieldOf`), as `annex.<owner>.<key>` — only where the node's `annex` in-port is wired (P6) |
21
+ * | `state` | the builder's `state`, re-typed from the genre's attribute slots |
22
+ *
23
+ * **Order is `render()`'s.** The node's own names are the last word — Assemble
24
+ * spreads the prompts and the context first and writes its own after, so a
25
+ * builder's placeholder `sessionMessages` is superseded, not a collision.
26
+ * Anything else two declarers both claim is refused naming both
27
+ * (`BandCollisionError`), because a template reading it would get one or the
28
+ * other depending on spread order.
29
+ *
30
+ * **Safe (owner ruling Q1, 2026-09-27).** Everything rendered into the context
31
+ * may be in scope, and nothing dangerous is ever declared: annex declarations
32
+ * refuse secrets at write time (R61). What this refuses on top is the
33
+ * *kinds* no template may reach by any door — a secret, connection / sampling
34
+ * / endpoint / model identity (R53), debug metadata, embeddings — by name,
35
+ * anywhere in the tree (`ForbiddenTemplateFieldError`).
36
+ *
37
+ * The runtime value of `annex` arrives on the node's `annex` in-port, from
38
+ * `core:query/session-annex@1` with `view: 'template'` (P6, law T2); the
39
+ * scope carries it only where that port is wired.
40
+ * @experimental
41
+ */
42
+ import { type AttributeSlotDecl } from './attributes.js';
43
+ import { type BandSource } from './bands.js';
44
+ import { type SlotDecl } from './descriptors.js';
45
+ import type { DocEdge, DocNode } from './document.js';
46
+ import { type TemplateScope, type VarField } from './template.js';
47
+ import { type VariableDecl } from './variables.js';
48
+ /**
49
+ * What `templateScopeAt` needs from a node's definition. A `Descriptor`
50
+ * satisfies it, and so does a registry row read as `{ slots, ports, bands:
51
+ * policy.bands, portSchemas: policy.portSchemas }` — so a host answers from
52
+ * rows without loading a plugin (F6).
53
+ * @experimental
54
+ */
55
+ export interface ScopeSource extends BandSource {
56
+ slots?: Record<string, SlotDecl>;
57
+ portSchemas?: {
58
+ out?: Record<string, VarField>;
59
+ };
60
+ }
61
+ /** @experimental */
62
+ export interface TemplateScopeEnv {
63
+ /** Which template slot. Default: the node's first `template` slot. */
64
+ slot?: string;
65
+ /** A node's definition. Default: the registry in this process. */
66
+ describe?: (node: DocNode) => ScopeSource | undefined;
67
+ /** A registered variable, for a band's description. Default: `getVariable`. */
68
+ variable?: (id: string) => VariableDecl | undefined;
69
+ /** The session genre. Default: the document's inlet genre. */
70
+ genre?: string;
71
+ /** The annex owners in scope. Default: every owner declared in this process. */
72
+ owners?: readonly string[];
73
+ /** An owner's annex as a template variable. Default: `annexVarFieldOf`. */
74
+ annexOf?: (owner: string, genre?: string) => VarField | undefined;
75
+ /** The attribute slots `state` is typed from. Default: `genreSlots(genre)`. */
76
+ slots?: readonly AttributeSlotDecl[];
77
+ }
78
+ /** @experimental */
79
+ export interface TemplateScopeReport {
80
+ scope: TemplateScope;
81
+ /** Who declared each root — `'context' (core:task/build-template-context@1).templateContext`. */
82
+ declarers: Record<string, string>;
83
+ /**
84
+ * Producers feeding a template-context in-port with no declared schema:
85
+ * their keys reach the template untyped, so a checker must not refuse an
86
+ * unknown root while this is non-empty. Not a finding — `portSchemas` is
87
+ * optional, and a port without one is `'any'`, as every port was.
88
+ */
89
+ untyped: string[];
90
+ /** What is wrong but not fatal — each names the fix. */
91
+ findings: string[];
92
+ }
93
+ /** A kind no template may reach by any door (typed templates §1 "safe" iv, R53). @experimental */
94
+ export declare class ForbiddenTemplateFieldError extends Error {
95
+ }
96
+ /**
97
+ * Names that ARE a forbidden kind, compared case-blind: a connection, sampling,
98
+ * endpoint or model identity (R53), debug metadata, embeddings, a secret value.
99
+ * Deliberately names rather than shapes — a `VarField` has no kind for any of
100
+ * these, which is exactly why one would arrive disguised as a `string`.
101
+ * @experimental
102
+ */
103
+ export declare const FORBIDDEN_TEMPLATE_NAMES: readonly string[];
104
+ /**
105
+ * The scope, who declared each root, and what is untyped or wrong.
106
+ * Throws `BandCollisionError` on a root two declarers claim, and
107
+ * `ForbiddenTemplateFieldError` on a forbidden kind.
108
+ * @experimental
109
+ */
110
+ export declare function templateScopeReport(doc: {
111
+ nodes: readonly DocNode[];
112
+ edges: readonly DocEdge[];
113
+ input?: {
114
+ genre?: string;
115
+ };
116
+ }, nodeKey: string, env?: TemplateScopeEnv): TemplateScopeReport;
117
+ /** The in-port a template node reads the annex on (P6). @experimental */
118
+ export declare const TEMPLATE_ANNEX_PORT = "annex";
119
+ /**
120
+ * The typed scope of a template slot at `nodeKey` — see the module note.
121
+ * Throws on a root collision (naming both declarers) and on a forbidden kind.
122
+ * @experimental
123
+ */
124
+ export declare function templateScopeAt(doc: {
125
+ nodes: readonly DocNode[];
126
+ edges: readonly DocEdge[];
127
+ input?: {
128
+ genre?: string;
129
+ };
130
+ }, nodeKey: string, env?: TemplateScopeEnv): TemplateScope;
131
+ //# sourceMappingURL=templateScopeAt.d.ts.map
@@ -0,0 +1,354 @@
1
+ /**
2
+ * What a template can reference at one node of one document, typed (typed
3
+ * templates P3, 2026-09-27).
4
+ *
5
+ * ```ts
6
+ * const scope = templateScopeAt(doc, 'prompt', { genre: 'showcase.twenty-questions:genre/game' })
7
+ * scope.characters // { type: 'string', … } — the context builder's port schema
8
+ * scope.secretEntry // { type: 'string', … } — a band declared upstream
9
+ * scope.annex.fields['showcase.twenty-questions'].fields.secret // the annex declaration
10
+ * ```
11
+ *
12
+ * The scope is the union, checked for collisions, of:
13
+ *
14
+ * | Root | Where it comes from |
15
+ * |---|---|
16
+ * | the node's own names | the template slot's static `variables` — Assemble's are what `render()` supplies |
17
+ * | the `prompts` slot's fields | `slotToVarField`, followed through a slot reference (`slot.prompts({ node })`, an envoy's) |
18
+ * | the context builder's keys | the declared out-port schema (`Descriptor.portSchemas`) of whatever feeds a template-context in-port |
19
+ * | one per declared band | `rendersAt` over the node's `variables` slot — the laid-out string |
20
+ * | `annex` | every declared annex key of every owner in scope (`annexVarFieldOf`), as `annex.<owner>.<key>` — only where the node's `annex` in-port is wired (P6) |
21
+ * | `state` | the builder's `state`, re-typed from the genre's attribute slots |
22
+ *
23
+ * **Order is `render()`'s.** The node's own names are the last word — Assemble
24
+ * spreads the prompts and the context first and writes its own after, so a
25
+ * builder's placeholder `sessionMessages` is superseded, not a collision.
26
+ * Anything else two declarers both claim is refused naming both
27
+ * (`BandCollisionError`), because a template reading it would get one or the
28
+ * other depending on spread order.
29
+ *
30
+ * **Safe (owner ruling Q1, 2026-09-27).** Everything rendered into the context
31
+ * may be in scope, and nothing dangerous is ever declared: annex declarations
32
+ * refuse secrets at write time (R61). What this refuses on top is the
33
+ * *kinds* no template may reach by any door — a secret, connection / sampling
34
+ * / endpoint / model identity (R53), debug metadata, embeddings — by name,
35
+ * anywhere in the tree (`ForbiddenTemplateFieldError`).
36
+ *
37
+ * The runtime value of `annex` arrives on the node's `annex` in-port, from
38
+ * `core:query/session-annex@1` with `view: 'template'` (P6, law T2); the
39
+ * scope carries it only where that port is wired.
40
+ * @experimental
41
+ */
42
+ import { annexOwners, annexVarFieldOf } from './annexFields.js';
43
+ import { slotField } from './attributes.js';
44
+ import { BandCollisionError, bandsReaching, rendersAt } from './bands.js';
45
+ import { getDefinition } from './descriptors.js';
46
+ import { genreAllowsCustomAttributes, genreEnvoy, genreSlots, getGenre, envoyPromptsSlotFor } from './genres.js';
47
+ import { fieldToVarField, slotToVarField } from './template.js';
48
+ import { getVariable } from './variables.js';
49
+ /** The shape a context builder's payload travels as. Written out, as `bands.ts` writes its own. */
50
+ const TEMPLATE_CONTEXT_SHAPE = 'core:shape/template-context@1';
51
+ /** A kind no template may reach by any door (typed templates §1 "safe" iv, R53). @experimental */
52
+ export class ForbiddenTemplateFieldError extends Error {
53
+ }
54
+ /**
55
+ * Names that ARE a forbidden kind, compared case-blind: a connection, sampling,
56
+ * endpoint or model identity (R53), debug metadata, embeddings, a secret value.
57
+ * Deliberately names rather than shapes — a `VarField` has no kind for any of
58
+ * these, which is exactly why one would arrive disguised as a `string`.
59
+ * @experimental
60
+ */
61
+ export const FORBIDDEN_TEMPLATE_NAMES = [
62
+ 'apiKey',
63
+ 'baseUrl',
64
+ 'connection',
65
+ 'connectionId',
66
+ 'connectionRef',
67
+ 'debugMeta',
68
+ 'embedding',
69
+ 'embeddings',
70
+ 'endpoint',
71
+ 'endpointUrl',
72
+ 'model',
73
+ 'modelId',
74
+ 'modelName',
75
+ 'sampling',
76
+ 'samplingConfig',
77
+ 'samplingConfigId',
78
+ 'secretValue',
79
+ 'vector',
80
+ 'vectors',
81
+ ];
82
+ const FORBIDDEN = new Set(FORBIDDEN_TEMPLATE_NAMES.map((n) => n.toLowerCase()));
83
+ const defaultDescribe = (n) => getDefinition(`${n.definitionId}@${n.definitionVersion}`);
84
+ const shapeIdOf = (s) => typeof s === 'string' ? s : (s?.id ?? undefined);
85
+ const head = (p) => p.split('.')[0];
86
+ const isField = (d) => !!d && typeof d === 'object' && !Array.isArray(d);
87
+ const label = (n) => `'${n.key}' (${n.definitionId}@${n.definitionVersion})`;
88
+ /** Refuse a forbidden name anywhere under `root`, naming the path and who declared it. */
89
+ function refuseForbidden(root, decl, declarer) {
90
+ const walk = (name, f, path) => {
91
+ if (FORBIDDEN.has(name.toLowerCase()))
92
+ throw new ForbiddenTemplateFieldError(`'${name}' (at '${path}', declared by ${declarer}) is a kind no template may reach — a ` +
93
+ `secret, a connection, sampling, endpoint or model identity (R53), debug metadata or ` +
94
+ `embeddings. Leave it out of the declaration: a template reads what the model is told, ` +
95
+ `never how it is called.`);
96
+ if (Array.isArray(f))
97
+ for (const k of f)
98
+ walk(k, 'any', `${path}.${k}`);
99
+ if (!isField(f))
100
+ return;
101
+ for (const [k, v] of Object.entries(f.fields ?? {}))
102
+ walk(k, v, `${path}.${k}`);
103
+ if (f.of)
104
+ walkOf(f.of, `${path}[]`);
105
+ };
106
+ const walkOf = (f, path) => {
107
+ for (const [k, v] of Object.entries(f.fields ?? {}))
108
+ walk(k, v, `${path}.${k}`);
109
+ if (f.of)
110
+ walkOf(f.of, `${path}[]`);
111
+ };
112
+ walk(root, decl, root);
113
+ }
114
+ /** An attribute slot's value as a template reads it; a secret is refused, never dropped. */
115
+ function slotVarField(decl) {
116
+ const f = slotField(decl);
117
+ if (f?.type === 'secret')
118
+ throw new ForbiddenTemplateFieldError(`attribute slot '${decl.id}' holds a secret, and state is rendered into the context. ` +
119
+ `A secret is never an attribute — keep it in a secret setting the model never sees.`);
120
+ // A derived slot declares no field: what it computes is a value, not a shape.
121
+ const vf = f ? fieldToVarField(f) : { type: 'string' };
122
+ return { ...(vf ?? { type: 'string' }), optional: true, description: decl.descriptor };
123
+ }
124
+ /** `hp` and `owner_hp` — the bare key a template reads, and the qualified one (host `slotKey`). */
125
+ const slotKeys = (id) => {
126
+ const bare = id.replace(/^.*:slot\//, '').replace(/@\d+$/, '');
127
+ const qualified = id
128
+ .replace(/@\d+$/, '')
129
+ .replace(/:slot\//, '_')
130
+ .replace(/[.\-]/g, '_');
131
+ return [bare, qualified];
132
+ };
133
+ /**
134
+ * `state`, typed from attribute slots: `state.world.<slot>`,
135
+ * `state.cast.<member>.<slot>` beside the member's `id`, `key` and `name`,
136
+ * and `state.locations.<place>.<slot>` likewise (P6 — what the host renders:
137
+ * slug-keyed holders only, never the `byId` index).
138
+ * A genre that lets sessions add attributes of their own (`customAttributes:
139
+ * 'allow'`) — or no known genre at all — leaves the bags open: the honest
140
+ * answer for a set nobody can list.
141
+ */
142
+ function stateVarField(slots, open, base) {
143
+ const bag = (applies) => {
144
+ const out = {};
145
+ for (const d of slots ?? []) {
146
+ if (!d.appliesTo.includes(applies))
147
+ continue;
148
+ const vf = slotVarField(d);
149
+ const [bare, qualified] = slotKeys(d.id);
150
+ out[qualified] = vf;
151
+ out[bare] ??= vf;
152
+ }
153
+ return out;
154
+ };
155
+ const world = open ? { type: 'record' } : { type: 'object', fields: bag('world') };
156
+ const holder = (applies) => open
157
+ ? { type: 'record' }
158
+ : {
159
+ type: 'object',
160
+ fields: {
161
+ id: { type: 'number' },
162
+ key: { type: 'string' },
163
+ name: { type: 'string' },
164
+ ...bag(applies),
165
+ },
166
+ };
167
+ const member = holder('cast');
168
+ return {
169
+ ...(base?.description !== undefined ? { description: base.description } : {}),
170
+ type: 'object',
171
+ optional: true,
172
+ fields: {
173
+ ...(base?.fields ?? {}),
174
+ world,
175
+ cast: { type: 'record', of: member },
176
+ locations: { type: 'record', optional: true, of: holder('location') },
177
+ },
178
+ };
179
+ }
180
+ /**
181
+ * The fields a node's `prompts` slot puts at the top of its template — its
182
+ * own declaration, or the one its slot reference points at (the builder's,
183
+ * an envoy's), because that is what the run resolves.
184
+ */
185
+ function promptsFields(doc, node, slots, describe, genre) {
186
+ const out = [];
187
+ for (const [name, decl] of Object.entries(slots)) {
188
+ if (decl.kind !== 'prompts')
189
+ continue;
190
+ const ref = node.config?.[name];
191
+ let target = decl;
192
+ let declarer = `${label(node)} slot '${name}'`;
193
+ if (ref?.__ref === 'slot' && ref.ofEnvoy) {
194
+ const envoy = genre ? genreEnvoy(genre, ref.ofEnvoy) : undefined;
195
+ target = envoy ? envoyPromptsSlotFor(envoy) : undefined;
196
+ declarer = `envoy '${ref.ofEnvoy}' prompts`;
197
+ }
198
+ else if (ref?.__ref === 'slot' && ref.ofNode && ref.ofNode !== node.key) {
199
+ const owner = doc.nodes.find((n) => n.key === ref.ofNode);
200
+ target = owner ? describe(owner)?.slots?.[ref.slot ?? name] : undefined;
201
+ if (owner)
202
+ declarer = `${label(owner)} slot '${ref.slot ?? name}'`;
203
+ }
204
+ const vf = target ? slotToVarField(target) : undefined;
205
+ for (const [k, f] of Object.entries(vf?.fields ?? {}))
206
+ out.push([k, f, declarer]);
207
+ }
208
+ return out;
209
+ }
210
+ /**
211
+ * The scope, who declared each root, and what is untyped or wrong.
212
+ * Throws `BandCollisionError` on a root two declarers claim, and
213
+ * `ForbiddenTemplateFieldError` on a forbidden kind.
214
+ * @experimental
215
+ */
216
+ export function templateScopeReport(doc, nodeKey, env = {}) {
217
+ const describe = env.describe ?? defaultDescribe;
218
+ const variable = env.variable ?? getVariable;
219
+ const genre = env.genre ?? doc.input?.genre;
220
+ const node = doc.nodes.find((n) => n.key === nodeKey);
221
+ if (!node)
222
+ throw new Error(`templateScopeAt: no node '${nodeKey}' in this document`);
223
+ const d = describe(node);
224
+ if (!d)
225
+ throw new Error(`templateScopeAt: ${label(node)} is not a definition this build knows`);
226
+ const slots = d.slots ?? {};
227
+ const slotName = env.slot ?? Object.keys(slots).find((k) => slots[k].kind === 'template');
228
+ const template = slotName ? slots[slotName] : undefined;
229
+ if (!template || template.kind !== 'template')
230
+ throw new Error(`templateScopeAt: ${label(node)} has no template slot${env.slot ? ` '${env.slot}'` : ''}`);
231
+ const scope = {};
232
+ const declarers = {};
233
+ const untyped = [];
234
+ const findings = [];
235
+ // The node's own names: the last word, so every layer below yields to them.
236
+ const own = template.variables ?? {};
237
+ const ownDeclarer = `${label(node)} slot '${slotName}'`;
238
+ for (const [k, v] of Object.entries(own)) {
239
+ scope[k] = v;
240
+ declarers[k] = ownDeclarer;
241
+ }
242
+ // A prompts field a context builder also publishes is the same value,
243
+ // resolved: `render()` spreads the prompts first and the context over them
244
+ // ("the order is the fix"), so the context's supersedes it.
245
+ const fromPrompts = new Set();
246
+ const put = (root, field, declarer, layer) => {
247
+ if (Object.prototype.hasOwnProperty.call(own, root))
248
+ return;
249
+ const existing = declarers[root];
250
+ if (layer === 'context' && fromPrompts.has(root))
251
+ fromPrompts.delete(root);
252
+ else if (existing !== undefined && existing !== declarer)
253
+ throw new BandCollisionError(`'${root}' reaches the template at '${nodeKey}' from two declarers: ${existing}, and ` +
254
+ `${declarer}. A top-level template name means one thing — rename one of the two.`);
255
+ scope[root] = field;
256
+ declarers[root] = declarer;
257
+ if (layer === 'prompts')
258
+ fromPrompts.add(root);
259
+ };
260
+ for (const [k, f, by] of promptsFields(doc, node, slots, describe, genre))
261
+ put(k, f, by, 'prompts');
262
+ // What the context builder declares it publishes.
263
+ const contextPorts = Object.entries(d.ports?.in ?? {})
264
+ .filter(([, s]) => shapeIdOf(s) === TEMPLATE_CONTEXT_SHAPE)
265
+ .map(([p]) => p);
266
+ for (const port of contextPorts)
267
+ for (const e of doc.edges.filter((x) => x.to === nodeKey && head(x.toPort) === port)) {
268
+ const producer = doc.nodes.find((n) => n.key === e.from);
269
+ if (!producer)
270
+ continue;
271
+ const outPort = head(e.fromPort);
272
+ const schema = describe(producer)?.portSchemas?.out?.[outPort];
273
+ const by = `${label(producer)}.${outPort}`;
274
+ if (!schema) {
275
+ untyped.push(by);
276
+ continue;
277
+ }
278
+ if (schema.type !== 'object') {
279
+ findings.push(`${by} feeds '${nodeKey}.${port}' with a declared ${schema.type}; a template context ` +
280
+ `is an object of named values — declare its schema as { type: 'object', fields }.`);
281
+ continue;
282
+ }
283
+ for (const [k, f] of Object.entries(schema.fields ?? {}))
284
+ put(k, f, by, 'context');
285
+ }
286
+ // `state`, re-typed from the attribute slots the session tracks.
287
+ if (isField(scope.state) && declarers.state !== ownDeclarer) {
288
+ const g = genre ? getGenre(genre) : undefined;
289
+ const slotsIn = env.slots ?? (genre ? genreSlots(genre) : undefined);
290
+ const open = env.slots ? false : !g || genreAllowsCustomAttributes(g);
291
+ scope.state = stateVarField(slotsIn, open, scope.state);
292
+ }
293
+ // Bands declared upstream, each at the top level as its laid-out value.
294
+ for (const [vName, vSlot] of Object.entries(slots)) {
295
+ if (vSlot.kind !== 'variables' || !vSlot.rendersBands?.from)
296
+ continue;
297
+ const renders = rendersAt(doc, nodeKey, vSlot, describe);
298
+ const reaching = bandsReaching(doc, nodeKey, vSlot.rendersBands.from, describe);
299
+ for (const [band, id] of Object.entries(renders)) {
300
+ if (Object.prototype.hasOwnProperty.call(vSlot.renders ?? {}, band))
301
+ continue;
302
+ const v = variable(id);
303
+ if (!v)
304
+ findings.push(`band '${band}' is laid out by '${id}', which is not registered here — declare it ` +
305
+ `with definePluginVariable() before the definition that names it.`);
306
+ const description = v?.description ?? v?.i18n?.name;
307
+ const by = reaching[band]?.declarer ?? `${label(node)} slot '${vName}'`;
308
+ if (Object.prototype.hasOwnProperty.call(own, band) || declarers[band] !== undefined)
309
+ throw new BandCollisionError(`band '${band}' declared by ${by} collides with '${band}' from ` +
310
+ `${declarers[band] ?? ownDeclarer} at '${nodeKey}'. A top-level template name ` +
311
+ `means one thing — rename the band.`);
312
+ put(band, { type: 'string', optional: true, ...(description !== undefined ? { description } : {}) }, by);
313
+ }
314
+ }
315
+ // The annex — every declared key of every owner in scope — where the
316
+ // node's `annex` in-port is WIRED (P6): the value arrives on that port
317
+ // (law T2 says from where), so an unwired node has no `annex` at all and a
318
+ // template naming it is refused instead of rendering nothing.
319
+ if (annexWired(doc, node, d)) {
320
+ const annexOf = env.annexOf ?? annexVarFieldOf;
321
+ const owners = {};
322
+ for (const owner of env.owners ?? annexOwners()) {
323
+ const f = annexOf(owner, genre);
324
+ if (f && Object.keys(f.fields ?? {}).length)
325
+ owners[owner] = { ...f, optional: true };
326
+ }
327
+ if (Object.keys(owners).length) {
328
+ if (declarers.annex !== undefined)
329
+ throw new BandCollisionError(`'annex' at '${nodeKey}' is declared by ${declarers.annex}, and is also where every ` +
330
+ `owner's declared annex keys are read (annex.<owner>.<key>). Rename the other.`);
331
+ put('annex', { type: 'object', optional: true, fields: owners }, 'the annex declarations in scope');
332
+ }
333
+ }
334
+ for (const [root, decl] of Object.entries(scope))
335
+ refuseForbidden(root, decl, declarers[root]);
336
+ return { scope, declarers, untyped, findings };
337
+ }
338
+ /** The in-port a template node reads the annex on (P6). @experimental */
339
+ export const TEMPLATE_ANNEX_PORT = 'annex';
340
+ /** Whether `node` declares the annex in-port and something feeds it. */
341
+ function annexWired(doc, node, d) {
342
+ if (!Object.prototype.hasOwnProperty.call(d.ports?.in ?? {}, TEMPLATE_ANNEX_PORT))
343
+ return false;
344
+ return doc.edges.some((e) => e.to === node.key && head(e.toPort) === TEMPLATE_ANNEX_PORT);
345
+ }
346
+ /**
347
+ * The typed scope of a template slot at `nodeKey` — see the module note.
348
+ * Throws on a root collision (naming both declarers) and on a forbidden kind.
349
+ * @experimental
350
+ */
351
+ export function templateScopeAt(doc, nodeKey, env) {
352
+ return templateScopeReport(doc, nodeKey, env).scope;
353
+ }
354
+ //# sourceMappingURL=templateScopeAt.js.map
@@ -0,0 +1,177 @@
1
+ /**
2
+ * `@serene-pub/sdk/testing` — the harness a **plugin author** runs (03 §9, U11).
3
+ *
4
+ * Distinct from `src/conformance.ts`, which is what **SP Core** runs against its own
5
+ * executor. Two different audiences and two different questions:
6
+ *
7
+ * conformance.ts — "does this host obey the laws?"
8
+ * testing.ts — "does my hook behave, and did my change alter what gets sent?"
9
+ *
10
+ * The second question is the one that keeps a plugin working across SP releases, and it
11
+ * is answered by goldens: record a receipt now, compare later, and see the diff rather
12
+ * than a pass/fail. **"It still runs" is not the assertion anyone needs** — a plugin that
13
+ * runs and quietly changes the prompt is the failure mode that reaches users.
14
+ */
15
+ import type { Receipt } from './receipt.js';
16
+ import type { SpecDocument } from './document.js';
17
+ import type { Bindings, RunOptions } from './executor.js';
18
+ import type { Descriptor } from './descriptors.js';
19
+ /**
20
+ * The plugin sandbox's context, in this harness (plans 29 §14 D-3) — the half
21
+ * the executor cannot supply, because a plugin's node handlers never run
22
+ * against the executor's context at install. Re-exported here so an author's
23
+ * one import is `@serene-pub/sdk/testing`.
24
+ */
25
+ export * from './pluginHarness.js';
26
+ /** @experimental */
27
+ export interface Golden {
28
+ name: string;
29
+ specId: string;
30
+ specVersion: string;
31
+ seed: string;
32
+ outcome: Receipt['outcome'];
33
+ haltReason?: string;
34
+ /** Per node: what went in and what came out. Timings are excluded on purpose. */
35
+ nodes: Array<{
36
+ nodeKey: string;
37
+ kind: string;
38
+ result: string;
39
+ input?: unknown;
40
+ output?: unknown;
41
+ }>;
42
+ emitted: Array<{
43
+ event: string;
44
+ cause: string;
45
+ }>;
46
+ /** The payload a preview run would have sent, when there is one. */
47
+ wire?: unknown;
48
+ }
49
+ /**
50
+ * Reduce a receipt to what a golden should hold.
51
+ *
52
+ * Timings, run ids and wall-clock are all excluded — a golden that fails because a run
53
+ * took 3ms instead of 2ms is a golden nobody keeps. What is kept is every decision and
54
+ * every payload, which is what actually changes when a plugin's behaviour changes.
55
+ * @experimental
56
+ */
57
+ export declare function toGolden(name: string, r: Receipt): Golden;
58
+ /** @experimental */
59
+ export interface GoldenDiff {
60
+ path: string;
61
+ before: unknown;
62
+ after: unknown;
63
+ }
64
+ /** A structural diff, deepest-path-first, so the first line names the actual change. @experimental */
65
+ export declare function diffGolden(before: Golden, after: Golden): GoldenDiff[];
66
+ /** @experimental */
67
+ export declare function renderDiff(d: GoldenDiff[]): string;
68
+ /** @experimental */
69
+ export declare class GoldenMismatch extends Error {
70
+ readonly name: string;
71
+ readonly diff: GoldenDiff[];
72
+ constructor(name: string, diff: GoldenDiff[]);
73
+ }
74
+ /** Record if absent, compare if present. The whole workflow in one call. @experimental */
75
+ export declare function checkGolden(name: string, r: Receipt, stored?: Golden): {
76
+ golden: Golden;
77
+ recorded: boolean;
78
+ };
79
+ /** @experimental */
80
+ export interface BindingProbe {
81
+ id: string;
82
+ title: string;
83
+ consequence: string;
84
+ check(hook: (input: any, ctx: any) => any, d: Descriptor, ctx: ProbeCtx): Promise<void> | void;
85
+ }
86
+ /** @experimental */
87
+ export interface ProbeCtx {
88
+ sampleInput: unknown;
89
+ /** A context object shaped like the one the executor injects for this kind. */
90
+ makeCtx(over?: Record<string, unknown>): any;
91
+ }
92
+ /**
93
+ * What a hook has to do to be a hook. Run these in your own tests — the executor assumes
94
+ * all of it, and a hook that breaks one of them fails in a way that is hard to attribute.
95
+ * @experimental
96
+ */
97
+ export declare const BINDING_PROBES: BindingProbe[];
98
+ /** @experimental */
99
+ export interface ProbeResult {
100
+ id: string;
101
+ title: string;
102
+ pass: boolean;
103
+ error?: string;
104
+ consequence?: string;
105
+ }
106
+ /** @experimental */
107
+ export declare function probeBinding(hook: (input: any, ctx: any) => any, descriptor: Descriptor, ctx: ProbeCtx): Promise<ProbeResult[]>;
108
+ /** A context shaped like the executor's, per kind — so a probe tests the real surface. @experimental */
109
+ export declare const probeCtxFor: (kind: Descriptor['kind'], sampleInput?: unknown) => ProbeCtx;
110
+ /**
111
+ * The seed and the clock an executed example runs on.
112
+ *
113
+ * Fixed, and fixed *here* rather than per example: two runs of the same page
114
+ * have to produce the same bytes or the golden is noise, and a seed chosen by
115
+ * each example is a seed one of them forgets to choose. Everything a receipt
116
+ * records that moves on its own — run id, timestamps, durations — is either
117
+ * excluded by `toGolden` or never rendered by `renderRunSummary`.
118
+ *
119
+ * They live in the SDK rather than in the docs generator because the generator
120
+ * is not the only thing that runs an example any more: the browser playground
121
+ * runs the same module against the same seed, and a reader who compares what
122
+ * they just ran against the page has to be comparing the same run.
123
+ * @experimental
124
+ */
125
+ export declare const EXAMPLE_SEED = "seed:example";
126
+ /** @experimental */
127
+ export declare const EXAMPLE_CLOCK = 1700000000000;
128
+ /** Everything `run` takes except the two things the harness decides. @experimental */
129
+ export type ExampleRunOptions = Omit<RunOptions, 'seed' | 'now'>;
130
+ /**
131
+ * What an example's `run()` is handed: its own compiled document, and the way
132
+ * to execute it deterministically. Deliberately small — the fixture host itself
133
+ * (bindings, scope data) is the example's own import, because a reader of the
134
+ * page has to be able to see which hooks answered.
135
+ * @experimental
136
+ */
137
+ export interface ExampleRunCtx {
138
+ /** This example's document — already compiled from `build()` and validated. */
139
+ doc: SpecDocument;
140
+ /** The run seed. Passed for the example to show; `run` applies it regardless. */
141
+ seed: string;
142
+ /** The run clock, for the same reason. */
143
+ now: () => number;
144
+ /** Execute `doc` under this seed and clock. Everything else is the example's. */
145
+ run(opts: ExampleRunOptions): Promise<Receipt>;
146
+ }
147
+ /** The context an executed example runs against. Seed and clock default to the fixed pair. @experimental */
148
+ export declare function makeExampleRunCtx(doc: SpecDocument, opts?: {
149
+ seed?: string;
150
+ now?: () => number;
151
+ }): ExampleRunCtx;
152
+ /**
153
+ * A receipt as a page shows it: what ran, in order, and how each step ended.
154
+ *
155
+ * Not `renderReceipt`, which is the run inspector's rendering and carries the
156
+ * run id, the elapsed times and the wall clock. Every one of those moves
157
+ * between two identical runs, and a page that changed on every build would
158
+ * teach a reader to ignore it. What is left is what the run DECIDED — which is
159
+ * the only part worth pinning.
160
+ * @experimental
161
+ */
162
+ export declare function renderRunSummary(r: Receipt): string;
163
+ /**
164
+ * F26 as a one-liner an author can run: parallel and forced-sequential must produce the
165
+ * same result. If your hook has a hidden ordering dependency, this is where it shows up
166
+ * — not in a user's chat at 2am under load.
167
+ * @experimental
168
+ */
169
+ export declare function assertEquivalent(doc: SpecDocument, opts: RunOptions): Promise<void>;
170
+ /** Run the same spec twice on one seed and assert nothing moved (F11). @experimental */
171
+ export declare function assertDeterministic(doc: SpecDocument, opts: RunOptions & {
172
+ seed: string;
173
+ }): Promise<void>;
174
+ /** @experimental */
175
+ export declare function renderProbes(results: ProbeResult[]): string;
176
+ export type { Bindings };
177
+ //# sourceMappingURL=testing.d.ts.map