@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,1329 @@
1
+ /**
2
+ * Descriptors — the shared-scope declaration of a **node definition** (01 §1, 04 §3;
3
+ * NOMENCLATURE §5 — *node type* is retired, ruled 2026-09-14).
4
+ *
5
+ * A descriptor is data: it can be listed, rendered and validated without loading
6
+ * the handler that implements it. That is what lets the plugin manager and the
7
+ * editor work from rows (10 §10.2).
8
+ */
9
+ import { pluginRuleRef } from './pluginRuleRef.js';
10
+ import { checkBandDeclarations } from './bands.js';
11
+ import { settingsSchemaFindings } from './settings.js';
12
+ import { i18nFindings, isI18n, localeMapOf } from './i18n.js';
13
+ import { eventById, notADeclaredEvent } from './events.js';
14
+ import { enabledWhenFindings, evaluateEnabledWhen, normalizeEnabledWhen, } from './predicates.js';
15
+ import { widgetReadsFindings } from './widgetDecls.js';
16
+ import { contentHash, declarationData, refuseUnlessSameHash } from './hash.js';
17
+ // The substrate's `settings` slot is projected onto a registry row beside the
18
+ // author's; the contract material leaves it out by name (`authoredSlots`).
19
+ // `settingsSlot.ts` imports nothing from here at runtime, so no cycle.
20
+ import { authoredSlots } from './settingsSlot.js';
21
+ import { DEFAULT_CHANNEL, parseChannel } from './channels.js';
22
+ // F39's registry door: `register()` hears `core:verdict/settings-travel` for
23
+ // every declared out-port (01 §13). `verdicts.ts` reads only leaf
24
+ // vocabulary, so this import starts no cycle.
25
+ import { refusalText, settingsTravelVerdict } from './verdicts.js';
26
+ export { fieldLabel, fieldAccepts } from './settings.js';
27
+ /**
28
+ * A definition's interior points, as copies — the one reader of
29
+ * `scriptPoints` (the executor's broker and the registry projection both go
30
+ * through it), so a caller may not edit the declaration through it.
31
+ * @experimental
32
+ */
33
+ export function scriptPointsOf(d) {
34
+ return (d.scriptPoints ?? []).map((p) => ({
35
+ ...p,
36
+ key: String(p.key),
37
+ accepts: Array.isArray(p.accepts) ? [...p.accepts] : [],
38
+ }));
39
+ }
40
+ /**
41
+ * The message verbs no genre may remove (R-15, ruled 2026-09-15): a person
42
+ * can always stop a reply, branch a session and rewrite a line. Not keys of
43
+ * `SessionShape.messageVerbs`; a declaration naming one `false` is refused
44
+ * at registration (`assertMessageVerbFloors`).
45
+ * @experimental
46
+ */
47
+ export const MESSAGE_VERB_FLOORS = ['stop', 'branch', 'edit'];
48
+ /**
49
+ * The opt-in built-ins: core's writes a genre may switch off and never
50
+ * re-implement. Default on.
51
+ * @experimental
52
+ */
53
+ export const MESSAGE_VERB_BUILT_INS = ['delete', 'hide', 'swipe'];
54
+ /** The genre-declared content actions — built-in write + declared content. @experimental */
55
+ export const MESSAGE_VERB_CONTENT = ['retry', 'extend', 'stepBack'];
56
+ /** Every forbiddable verb, in the order the availability map reads them. @experimental */
57
+ export const MESSAGE_VERBS = [...MESSAGE_VERB_CONTENT, ...MESSAGE_VERB_BUILT_INS];
58
+ /**
59
+ * The turn controls (lair pass B7 + B8, 2026-09-27) — the composer's presses
60
+ * that move the story on, as opposed to the message verbs, which act on one
61
+ * row. Keys of `SessionShape.turnControls`, in the order the extra venue
62
+ * draws them.
63
+ *
64
+ * - `advance` is **Continue**: it fires the turn order's head
65
+ * (`sessions:fireTurn` with no entry). ⚠ Not `extend` — that is the
66
+ * message verb that extends one reply by prefill (`messageVerbs.extend`).
67
+ * - `pick` is **Pick who speaks**: it fires a character the person names
68
+ * (`sessions:fireTurn` with a `character:<id>` entry the order does not
69
+ * hold).
70
+ * - `narrate` fires a **narrator turn** (`sessions:fireTurn` with a `null`
71
+ * ref the order does not hold) — only a `voice: 'narrator'` genre has a
72
+ * narrator to fire (`turnControlDefault`).
73
+ * - `retake` is **Regenerate the last turn, as a whole** (lair pass R2,
74
+ * owner 2026-09-28; label _Regenerate_, `sessions:retakeTurn`): it
75
+ * deletes the newest turn's **turn yield** — every row that turn's run
76
+ * created, on every channel, never a person's own line — and takes the
77
+ * same turn again. ⚠ Not `retry`, the message verb that rewrites ONE
78
+ * reply in place and keeps its swipes. Offered only where a genre
79
+ * declares it (`turnControlDefault`): a genre whose turn writes one row
80
+ * keeps `retry`.
81
+ * @experimental
82
+ */
83
+ export const TURN_CONTROLS = ['advance', 'pick', 'narrate', 'retake'];
84
+ /**
85
+ * What an undeclared turn control resolves to — read off the shape's own
86
+ * declarations, so a genre that says nothing keeps what its shape already
87
+ * means (R42: turn controls only where there is somebody to take a turn):
88
+ *
89
+ * - `advance` and `pick` are on where the shape has a **character system**
90
+ * (`characters` declared with a `max` other than 0; an unreadable shape
91
+ * counts as having one) — the composer's historical rule.
92
+ * - `narrate` is on where the shape has a **narrator** (`voice:
93
+ * 'narrator'`), the one genre family with a narrator to fire.
94
+ * - `retake` is never on by default: nothing in a shape says a turn writes
95
+ * more than one row, so a genre opts in (`turnControls.retake: true`).
96
+ * @experimental
97
+ */
98
+ export function turnControlDefault(shape, control) {
99
+ const s = shape && typeof shape === 'object' ? shape : null;
100
+ if (control === 'retake')
101
+ return false;
102
+ if (control === 'narrate')
103
+ return s?.voice === 'narrator';
104
+ if (!s)
105
+ return true;
106
+ const characters = s.characters;
107
+ return !!characters && typeof characters === 'object' && (characters.max ?? 1) !== 0;
108
+ }
109
+ /**
110
+ * What turn controls this shape offers, resolved — the `resolveWrites`
111
+ * posture: an undeclared or unreadable control is the shape's default
112
+ * (`turnControlDefault`), `false` takes it away, `true` or an object offers it. Pure, and
113
+ * takes `unknown` for a stored shape.
114
+ *
115
+ * With a `channel` (a slug or `slug:lane`; lair re-plan R6), that channel's
116
+ * declared `ChannelDecl.turnControls` win over the genre's, key by key — the
117
+ * `messageVerbs` merge. A channel the shape does not declare in the long
118
+ * form answers the genre's policy.
119
+ * @experimental
120
+ */
121
+ export function resolveTurnControls(shape, channel) {
122
+ const declared = shape && typeof shape === 'object'
123
+ ? (shape.turnControls ?? null)
124
+ : null;
125
+ const genre = plainObject(declared) ?? {};
126
+ const own = channel === undefined ? undefined : channelTurnControlsOf(shape, channel);
127
+ const d = own ? { ...genre, ...own } : genre;
128
+ return Object.fromEntries(TURN_CONTROLS.map((t) => {
129
+ const v = d[t];
130
+ if (v === true || v === false)
131
+ return [t, { offered: v, presentWhen: [] }];
132
+ if (v && typeof v === 'object' && !Array.isArray(v))
133
+ return [
134
+ t,
135
+ {
136
+ offered: true,
137
+ presentWhen: normalizeEnabledWhen(v.presentWhen),
138
+ },
139
+ ];
140
+ return [t, { offered: turnControlDefault(shape, t), presentWhen: [] }];
141
+ }));
142
+ }
143
+ /** A plain object, else undefined — how a stored declaration's map is read. */
144
+ function plainObject(v) {
145
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
146
+ }
147
+ /** One declared channel's own `turnControls`, by slug (the lane is multiplicity). */
148
+ function channelTurnControlsOf(shape, channel) {
149
+ const channels = plainObject(shape)?.channels;
150
+ if (!Array.isArray(channels))
151
+ return undefined;
152
+ const slug = parseChannel(channel).slug;
153
+ for (const raw of channels) {
154
+ const decl = plainObject(raw);
155
+ if (decl && typeof decl.slug === 'string' && parseChannel(decl.slug).slug === slug)
156
+ return plainObject(decl.turnControls);
157
+ }
158
+ return undefined;
159
+ }
160
+ /**
161
+ * Is this turn control present over these published values — offered, and
162
+ * every present-when holds? The failing predicate's reason when not; `null`
163
+ * reason for a control the genre does not offer at all.
164
+ * @experimental
165
+ */
166
+ export function turnControlPresent(policy, control, values) {
167
+ const p = policy[control];
168
+ if (!p.offered)
169
+ return { present: false, reason: null };
170
+ const verdict = evaluateEnabledWhen(p.presentWhen, values);
171
+ return verdict.enabled ? { present: true } : { present: false, reason: verdict.reason };
172
+ }
173
+ /**
174
+ * A `turnControls` declaration's faults, refused at the declaration: an
175
+ * unknown control, a value that is neither a boolean nor `{ presentWhen }`,
176
+ * a present-when the enabled-when grammar refuses, or a present-when over
177
+ * `item.*` (a turn control acts on no row).
178
+ * @experimental
179
+ */
180
+ export function assertTurnControls(shape, who) {
181
+ const raw = shape?.turnControls;
182
+ if (raw === undefined)
183
+ return;
184
+ const problems = [];
185
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
186
+ problems.push(`turnControls is { ${TURN_CONTROLS.map((t) => `${t}?`).join(', ')} }`);
187
+ }
188
+ else {
189
+ for (const [k, v] of Object.entries(raw)) {
190
+ if (!TURN_CONTROLS.includes(k)) {
191
+ problems.push(`turnControls.${k}: not a turn control — one of ${TURN_CONTROLS.join(', ')}`);
192
+ continue;
193
+ }
194
+ if (typeof v === 'boolean')
195
+ continue;
196
+ if (!v || typeof v !== 'object' || Array.isArray(v) || !('presentWhen' in v)) {
197
+ problems.push(`turnControls.${k}: true, false, or { presentWhen } — enabled-when predicates ` +
198
+ `over the published values, such as { on: 'session.fields.<field>', ` +
199
+ `equals: '<value>', reason: { en: '<why it is absent>' } }`);
200
+ continue;
201
+ }
202
+ const pw = v.presentWhen;
203
+ problems.push(...enabledWhenFindings(pw, `turnControls.${k}.presentWhen`));
204
+ normalizeEnabledWhen(pw).forEach((p, i) => {
205
+ if (p.on === 'item' || p.on.startsWith('item.'))
206
+ problems.push(`turnControls.${k}.presentWhen[${i}]: reads '${p.on}' — a turn control acts ` +
207
+ `on no row, so it cannot read one`);
208
+ });
209
+ }
210
+ }
211
+ if (problems.length)
212
+ throw new Error(`${who}: ${problems.join('\n')}`);
213
+ }
214
+ /**
215
+ * The writes a genre may switch off (R-B, 2026-09-17) — what a session does
216
+ * *beyond messages*. Keys of `SessionShape.writes`, in the order a policy
217
+ * reads them.
218
+ * @experimental
219
+ */
220
+ export const SESSION_WRITES = ['lore', 'scenes'];
221
+ /**
222
+ * What this shape lets a session write, resolved. Absent, unknown or
223
+ * unreadable is **both on** — the standard chat's posture, and the same
224
+ * "a policy that cannot be read refuses nothing" rule `messageVerbs` keeps.
225
+ * Only an explicit `false` takes a write away.
226
+ *
227
+ * Pure, and takes `unknown` on purpose: the app reads a shape that arrived
228
+ * from a stored registry row, not a typed declaration.
229
+ * @experimental
230
+ */
231
+ export function resolveWrites(shape) {
232
+ const declared = shape && typeof shape === 'object'
233
+ ? (shape.writes ?? null)
234
+ : null;
235
+ if (!declared || typeof declared !== 'object')
236
+ return Object.fromEntries(SESSION_WRITES.map((w) => [w, true]));
237
+ const d = declared;
238
+ return Object.fromEntries(SESSION_WRITES.map((w) => [w, d[w] !== false]));
239
+ }
240
+ /**
241
+ * A `writes` declaration whose values are not booleans is refused — with a
242
+ * sentence, at the declaration, where the author is. Shared by `register`
243
+ * (an inlet's `sessionShape`) and `genre()` (a genre's `shape`), on the same
244
+ * terms as `assertMessageVerbFloors`. Unknown keys are ignored, as the
245
+ * resolver ignores them: a key this release does not know is not a write.
246
+ * @experimental
247
+ */
248
+ export function assertSessionWrites(shape, who) {
249
+ const writes = shape?.writes;
250
+ if (writes === undefined)
251
+ return;
252
+ if (!writes || typeof writes !== 'object' || Array.isArray(writes))
253
+ throw new Error(`${who} declares a 'writes' that is not an object. A genre's writes are ` +
254
+ `{ lore?: boolean; scenes?: boolean } — absent means both on, and only an ` +
255
+ `explicit false takes one away (R-B).`);
256
+ const bad = SESSION_WRITES.filter((w) => writes[w] !== undefined && typeof writes[w] !== 'boolean');
257
+ if (!bad.length)
258
+ return;
259
+ throw new Error(`${who} declares writes { ${bad.map((w) => `${w}: ${JSON.stringify(writes[w])}`).join(', ')} }. ` +
260
+ `Each write is a boolean or absent — absent means on, and only an explicit ` +
261
+ `false takes the write away (R-B).`);
262
+ }
263
+ /**
264
+ * The five built-in writes (R-15), by the verb a person knows them as: the
265
+ * one-node spec core runs for each, and the outlet that spec ends in.
266
+ *
267
+ * Here rather than only in the core catalog because the **validator** needs
268
+ * them (U5b review W8): a built-in outlet performs the item rule's write —
269
+ * the handler judged who may act on which row before the run began — so a
270
+ * spec that is not the built-in's own placing one would perform that write
271
+ * with nobody having judged anything. `validate()` refuses the placement
272
+ * unless the document's id is one of `BUILTIN_SPEC_IDS`, and the host
273
+ * refuses the commit on the same test (defence in depth). A manifest
274
+ * permission letting a plugin spec place one is the future this leaves room
275
+ * for; it is not granted today.
276
+ * @internal
277
+ */
278
+ export const BUILTIN_SPEC_IDS = Object.freeze({
279
+ delete: 'core:spec/builtin-delete',
280
+ hide: 'core:spec/builtin-hide',
281
+ edit: 'core:spec/builtin-edit',
282
+ swipe: 'core:spec/builtin-swipe',
283
+ branch: 'core:spec/builtin-branch',
284
+ });
285
+ /** The outlet each built-in's spec ends in — `effects: 'write'`, every one. @experimental */
286
+ export const BUILTIN_OUTLET_IDS = Object.freeze({
287
+ delete: 'core:outlet/delete-message@1',
288
+ hide: 'core:outlet/hide-message@1',
289
+ edit: 'core:outlet/edit-message@1',
290
+ swipe: 'core:outlet/swipe-message@1',
291
+ branch: 'core:outlet/branch-session@1',
292
+ });
293
+ /** Is this definition id one of the five built-in write outlets? @experimental */
294
+ export const isBuiltInOutlet = (definitionId) => Object.values(BUILTIN_OUTLET_IDS).includes(definitionId);
295
+ /** Is this spec id one of the five built-in specs — the only documents that may place a built-in outlet? @internal */
296
+ export const isBuiltInSpec = (specId) => Object.values(BUILTIN_SPEC_IDS).includes(specId);
297
+ /**
298
+ * The form-answer pair (plans/29 R-15 *Forms*; 30 §U5d, built 2026-09-17):
299
+ * the inlet `core:event/form-addressed@1` lands on, and the outlet that
300
+ * commits an oracle's answer exactly as a click would. The outlet may be
301
+ * placed only in a document whose inlet is the form-addressed one
302
+ * (`validate()`; the host checks the same at the commit): it answers THE
303
+ * form the event carried, and a document reached by any other event has no
304
+ * form to answer — a spec placing it elsewhere would fire an action as
305
+ * somebody nobody asked.
306
+ * @internal
307
+ */
308
+ export const FORM_ADDRESSED_INLET_ID = 'core:inlet/form-addressed@1';
309
+ /** @experimental */
310
+ export const ANSWER_FORM_OUTLET_ID = 'core:outlet/answer-form@1';
311
+ /**
312
+ * The review-fields rule (R-15 *The review gate*; 30 §U5d): a definition
313
+ * with `effects: 'write' | 'external'` declares `review: { fields }` — what a
314
+ * reviewer may edit at the gate, `[]` when nothing (approve or refuse). A
315
+ * definition that declares none still registers and still gates — the form
316
+ * is then **inferred** from the whole payload, every field editable, which is
317
+ * the documented fallback a plugin definition gets — but `register()` records
318
+ * the omission as a finding and `validate()` reports it on every node bound
319
+ * to such a definition, so a shipped effectful definition without one is
320
+ * visible rather than silent. Every core definition declares one.
321
+ * @experimental
322
+ */
323
+ export function reviewFieldsFinding(d) {
324
+ if (d.effects !== 'write' && d.effects !== 'external')
325
+ return null;
326
+ if (d.review && Array.isArray(d.review.fields))
327
+ return null;
328
+ return (`${d.id} declares effects: '${d.effects}' and no review.fields. An effectful definition ` +
329
+ `says which of its in-ports a reviewer may edit at the gate — review: { fields: ['text'] }, ` +
330
+ `or review: { fields: [] } when the gate is approve-or-refuse. Until it does, the form is ` +
331
+ `inferred from the whole payload and every field is editable, including any row id.`);
332
+ }
333
+ const registrationFindings = new Map();
334
+ /**
335
+ * What `register()` noted about a definition without refusing it — today
336
+ * the review-fields rule alone. Keyed by definition id; empty for a clean
337
+ * one. Read by a host at boot to say so once, and by tests asserting that
338
+ * every shipped effectful definition declares its fields.
339
+ * @experimental
340
+ */
341
+ export function definitionFindings(id) {
342
+ if (id !== undefined)
343
+ return [...(registrationFindings.get(id) ?? [])];
344
+ return [...registrationFindings.values()].flat();
345
+ }
346
+ /**
347
+ * A `messageVerbs` declaration that names a floor `false` is refused — with a
348
+ * sentence, at the declaration, where the author is. Shared by `register`
349
+ * (an inlet's `sessionShape`) and `genre()` (a genre's `shape`), so the two
350
+ * places a shape can be declared cannot disagree about what a floor is.
351
+ * Unknown keys are ignored, as the app's reader ignores them: a key this
352
+ * release does not know is not a floor.
353
+ * @experimental
354
+ */
355
+ export function assertMessageVerbFloors(shape, who) {
356
+ const verbs = shape?.messageVerbs;
357
+ if (!verbs || typeof verbs !== 'object')
358
+ return;
359
+ const forbidden = MESSAGE_VERB_FLOORS.filter((floor) => verbs[floor] === false);
360
+ if (!forbidden.length)
361
+ return;
362
+ throw new Error(`${who} declares messageVerbs { ${forbidden.map((f) => `${f}: false`).join(', ')} }. ` +
363
+ `Stop, branch and edit are floors — present in every genre, never switched off ` +
364
+ `(R-15). A genre may switch off delete, hide or swipe, and may forbid retry, ` +
365
+ `extend or stepBack; drop the floor from the declaration.`);
366
+ }
367
+ /** The roles a channel's messages may play in a prompt. @experimental */
368
+ export const CHANNEL_ROLES = ['conversation', 'folio'];
369
+ /** The voices a channel's turn may seed under. `none` seeds no row at all. @experimental */
370
+ export const CHANNEL_VOICES = ['character', 'narrator', 'none'];
371
+ /**
372
+ * This shape's channels as full declarations, defaults resolved — the one
373
+ * reader every consumer of `SessionShape.channels` should use, so the short
374
+ * and long forms cannot be read differently anywhere.
375
+ *
376
+ * `main` comes first and always exists, declared or not: it is the session's
377
+ * default channel, so a genre that lists only `manuscript` still has it. A
378
+ * genre that *does* declare `main` gets its own declaration in that first
379
+ * position rather than a second row.
380
+ *
381
+ * What "resolved" means, per entry: `role` is always present; `voice` is the
382
+ * channel's, else the genre's, else absent; `messageVerbs` is the genre's
383
+ * with the channel's declared keys over the top, absent when neither declares
384
+ * any; `turnControls` the same, over the genre's `turnControls`; `label` a
385
+ * locale map, absent when undeclared. So the answer read off an entry is the
386
+ * effective one, and no caller has to remember the inheritance.
387
+ *
388
+ * Takes `unknown` for the same reason `resolveWrites` does, and never throws:
389
+ * a shape from a stored registry row is data. An unreadable entry is skipped
390
+ * rather than guessed at — the refusal belongs at the declaration
391
+ * (`assertChannelDecls`), not at a read on the turn's path.
392
+ * @experimental
393
+ */
394
+ export function channelDecls(shape) {
395
+ const s = (shape && typeof shape === 'object' ? shape : {});
396
+ const genreVoice = typeof s.voice === 'string' ? s.voice : undefined;
397
+ const genreVerbs = s.messageVerbs;
398
+ const genreControls = plainObject(s.turnControls);
399
+ const resolve = (raw) => {
400
+ const decl = typeof raw === 'string'
401
+ ? { slug: raw.trim() }
402
+ : raw && typeof raw === 'object' && !Array.isArray(raw)
403
+ ? raw
404
+ : {};
405
+ const slug = typeof decl.slug === 'string' ? decl.slug.trim() : '';
406
+ if (!slug)
407
+ return undefined;
408
+ const verbs = decl.messageVerbs || genreVerbs ? { ...genreVerbs, ...decl.messageVerbs } : undefined;
409
+ const ownControls = plainObject(decl.turnControls);
410
+ const controls = ownControls || genreControls ? { ...genreControls, ...ownControls } : undefined;
411
+ return {
412
+ slug,
413
+ role: decl.role ?? 'conversation',
414
+ ...(decl.voice ?? genreVoice ? { voice: decl.voice ?? genreVoice } : {}),
415
+ ...(verbs ? { messageVerbs: verbs } : {}),
416
+ ...(isI18n(decl.label) ? { label: localeMapOf(decl.label) } : {}),
417
+ ...(controls ? { turnControls: controls } : {}),
418
+ };
419
+ };
420
+ const declared = (Array.isArray(s.channels) ? s.channels : [])
421
+ .map(resolve)
422
+ .filter((d) => d !== undefined);
423
+ const main = declared.find((d) => d.slug === DEFAULT_CHANNEL);
424
+ return [main ?? resolve(DEFAULT_CHANNEL), ...declared.filter((d) => d !== main)];
425
+ }
426
+ /**
427
+ * A channel declaration that cannot mean what it says is refused — with a
428
+ * sentence, at the declaration, on the same terms as `assertMessageVerbFloors`.
429
+ *
430
+ * `main` may only be a conversation: it is the channel every session has and
431
+ * the one a turn lands on by default, so a genre that made it a document
432
+ * would leave the session with nowhere to talk.
433
+ * @experimental
434
+ */
435
+ export function assertChannelDecls(shape, who) {
436
+ const channels = shape?.channels;
437
+ if (channels === undefined)
438
+ return;
439
+ if (!Array.isArray(channels))
440
+ throw new Error(`${who} declares a 'channels' that is not an array. A genre's channels are a list ` +
441
+ `of slugs, each a bare string or a { slug, role?, voice?, messageVerbs?, label?, turnControls? } (R-C).`);
442
+ for (const raw of channels) {
443
+ const isString = typeof raw === 'string';
444
+ if (!isString && (!raw || typeof raw !== 'object' || Array.isArray(raw)))
445
+ throw new Error(`${who} declares a channel that is neither a slug nor a declaration: ` +
446
+ `${JSON.stringify(raw)}. Each channel is a bare string or a ` +
447
+ `{ slug, role?, voice?, messageVerbs?, label?, turnControls? } (R-C).`);
448
+ const decl = (isString ? { slug: raw } : raw);
449
+ const slug = typeof decl.slug === 'string' ? decl.slug.trim() : '';
450
+ if (!slug)
451
+ throw new Error(`${who} declares a channel with no slug. A channel is named by the slug it is ` +
452
+ `referenced and stored under (R-C).`);
453
+ if (slug.includes(':'))
454
+ throw new Error(`${who} declares the channel '${slug}'. A channel is declared by its slug alone — ` +
455
+ `lanes under it are runtime and open-ended, allocated by this genre's ` +
456
+ `pipelines, and no lane count is declared anywhere (ruling 2026-09-09).`);
457
+ const at = `${who} channel '${slug}'`;
458
+ if (decl.role !== undefined && !CHANNEL_ROLES.includes(decl.role))
459
+ throw new Error(`${at} declares role '${decl.role}'. A channel's role is ` +
460
+ `${CHANNEL_ROLES.map((r) => `'${r}'`).join(' or ')} — how its messages enter a ` +
461
+ `prompt, turns with speakers or one block of text (R-C).`);
462
+ if (decl.voice !== undefined && !CHANNEL_VOICES.includes(decl.voice))
463
+ throw new Error(`${at} declares voice '${decl.voice}'. A channel's voice is ` +
464
+ `${CHANNEL_VOICES.map((v) => `'${v}'`).join(', ')} — whose name a turn ` +
465
+ `triggered here seeds under, or none for no seed row at all (R-C).`);
466
+ assertMessageVerbFloors({ messageVerbs: decl.messageVerbs }, at);
467
+ // R6: the display name is display text, and the per-channel turn
468
+ // controls are judged on exactly the terms the genre's are.
469
+ const label = i18nFindings(decl.label, `${at} label`);
470
+ if (label.length)
471
+ throw new Error(label.join('\n'));
472
+ assertTurnControls({ turnControls: decl.turnControls }, at);
473
+ if (slug === DEFAULT_CHANNEL && (decl.role ?? 'conversation') !== 'conversation')
474
+ throw new Error(`${at} is declared role '${decl.role}'. '${DEFAULT_CHANNEL}' is the channel every ` +
475
+ `session has and the one a turn lands on by default, so it is always a ` +
476
+ `conversation; declare another channel for the folio (R-C).`);
477
+ }
478
+ }
479
+ const types = new Map();
480
+ /**
481
+ * A descriptor's display text, beyond the `i18n`/`description` pair every
482
+ * declaration carries.
483
+ *
484
+ * `label` is what settings.ts calls the canonical key for a field or a member
485
+ * band — `i18n` there is its deprecated alias — and those sit two levels down
486
+ * inside `slots[].schema` and `entryShape.fields`. Renaming "Top K" was
487
+ * therefore a hash change, which is exactly the edit src/hash.ts promises will
488
+ * not put the reload loop back.
489
+ *
490
+ * ⚠ `title` is deliberately absent. `WidgetDecl.title` is a heading, but
491
+ * `EntryRoles.title` is which field the engine reads as a row's title —
492
+ * contract, and moving one is an `@N+1` on purpose. One word, two answers, both
493
+ * reachable from here, so a key-name rule cannot have it both ways; the panel
494
+ * heading stays hashed until one of them is renamed.
495
+ *
496
+ * ## Where it is read
497
+ *
498
+ * Inside `definitionContract`, on every contract field that can carry a
499
+ * label — `slots`, `scriptPoints`, `sessionShape`, `entryShape`. The
500
+ * re-declaration guard below and core's `pipeline_definition_registry`
501
+ * projection both hash through that one function, so there is no second list
502
+ * to keep in step; the value is exported for the tests that prove the strip
503
+ * holds at every depth. Adding a word here re-hashes every definition that
504
+ * carries it — a pointer move on every install, exactly as adding one to
505
+ * `UNIVERSAL_DISPLAY` would be.
506
+ * @internal
507
+ */
508
+ export const DESCRIPTOR_DISPLAY_KEYS = { display: ['label'] };
509
+ /**
510
+ * The two halves of a `Descriptor` (plans/31 V6, ruled 2026-09-17).
511
+ *
512
+ * **Contract** is what a pinned spec runs against: the ports and shapes a
513
+ * document was compiled against, the slots it configures and their schema,
514
+ * the effects the gate keys on, the fields a reviewer's decision may carry,
515
+ * whether the node may fail empty, return early, draw on the seed, hold the
516
+ * live row, cause an event, take media. It is what `definitionContractHash`
517
+ * digests, and that hash is what a registry row's pointer and a run's receipt
518
+ * name — so moving any of it republishes the slug on every install.
519
+ *
520
+ * **Policy** is what is *offered* or *shown*: whether the definition is
521
+ * listed (`provisional`, `public`), where its gate starts, whether the panel
522
+ * offers a switch, how long the host waits, what the receipt reads, what the
523
+ * node is called. It lives on the registry row (`RegistryEntry.policy`,
524
+ * `i18n`, `public`) and is never hashed: flipping any of it leaves every pin
525
+ * where it is and takes effect on the next sync — and on the next hot reload,
526
+ * since the registry replaces a re-declaration whose contract is unchanged.
527
+ *
528
+ * Every `Descriptor` key is in exactly one list. `DescriptorFieldsClassified`
529
+ * below makes a key in neither — or in both — a compile error, so a new field
530
+ * is classified before it exists; `sdk-tests/contract.test.ts` gives the
531
+ * one-line reason per field.
532
+ * @experimental
533
+ */
534
+ export const DESCRIPTOR_CONTRACT_KEYS = [
535
+ 'id',
536
+ 'kind',
537
+ 'ports',
538
+ 'slots',
539
+ 'effects',
540
+ 'review',
541
+ 'shape',
542
+ 'optional',
543
+ 'declaresRandomness',
544
+ 'scriptPoints',
545
+ 'sessionShape',
546
+ 'earlyExit',
547
+ 'causesEvent',
548
+ 'causesEventFrom',
549
+ 'payloads',
550
+ 'liveRow',
551
+ 'media',
552
+ 'entryShape',
553
+ 'bands',
554
+ 'bandPorts',
555
+ 'portSchemas',
556
+ ];
557
+ /** @experimental */
558
+ export const DESCRIPTOR_POLICY_KEYS = [
559
+ 'i18n',
560
+ 'reviewDefault',
561
+ 'toggleable',
562
+ 'provisional',
563
+ 'public',
564
+ 'timeoutMs',
565
+ 'timeoutKind',
566
+ 'usage',
567
+ ];
568
+ /** @experimental */
569
+ export const DESCRIPTOR_FIELDS_CLASSIFIED = true;
570
+ /** A definition's policy, projected — `undefined` keys dropped so a row and a re-read agree. @experimental */
571
+ export function definitionPolicy(d) {
572
+ const policy = {};
573
+ if (d.provisional === true)
574
+ policy.provisional = true;
575
+ if (d.reviewDefault !== undefined)
576
+ policy.reviewDefault = d.reviewDefault;
577
+ if (d.timeoutMs !== undefined)
578
+ policy.timeoutMs = d.timeoutMs;
579
+ if (d.timeoutKind !== undefined)
580
+ policy.timeoutKind = d.timeoutKind;
581
+ if (d.toggleable !== undefined)
582
+ policy.toggleable = d.toggleable;
583
+ // By id: the row carries which variable, and the registry says the rest.
584
+ // Sorted, so a row and a re-read agree whatever order the author wrote.
585
+ if (d.bands && Object.keys(d.bands).length)
586
+ policy.bands = Object.fromEntries(Object.entries(d.bands)
587
+ .map(([k, v]) => [k, typeof v === 'string' ? v : v.id])
588
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
589
+ const bandPorts = bandPortsMaterial(d.bandPorts);
590
+ if (bandPorts)
591
+ policy.bandPorts = bandPorts;
592
+ if (d.portSchemas !== undefined)
593
+ policy.portSchemas = d.portSchemas;
594
+ return policy;
595
+ }
596
+ /** `{ key: variableId }`, sorted by key; none and `{}` are one contract (absent). */
597
+ function bandsMaterial(bands) {
598
+ if (!bands || !Object.keys(bands).length)
599
+ return undefined;
600
+ return Object.fromEntries(Object.entries(bands)
601
+ .map(([k, v]) => [k, typeof v === 'string' ? v : v.id])
602
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
603
+ }
604
+ /** `{ key: ports }`, keys and ports sorted; none and `{}` are one contract (absent). */
605
+ function bandPortsMaterial(bandPorts) {
606
+ if (!bandPorts || !Object.keys(bandPorts).length)
607
+ return undefined;
608
+ return Object.fromEntries(Object.entries(bandPorts)
609
+ .map(([k, ports]) => [k, [...ports].sort()])
610
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
611
+ }
612
+ /** Out-port schemas, display text out; no declared port is the field absent. */
613
+ function portSchemasMaterial(p) {
614
+ if (!p?.out || !Object.keys(p.out).length)
615
+ return undefined;
616
+ return contractData({ out: p.out });
617
+ }
618
+ const contractData = (v) => declarationData(v, DESCRIPTOR_DISPLAY_KEYS);
619
+ const flag = (v) => (v === true ? true : undefined);
620
+ const portShapes = (ports) => Object.fromEntries(Object.entries(ports ?? {}).map(([k, v]) => [
621
+ k,
622
+ typeof v === 'string' ? v : (v?.id ?? undefined),
623
+ ]));
624
+ /** The contract of a definition — every `DESCRIPTOR_CONTRACT_KEYS` field, as data, and nothing else. @internal */
625
+ export function definitionContract(source) {
626
+ const at = source.id.lastIndexOf('@');
627
+ const pinned = at > 0 && /^\d+$/.test(source.id.slice(at + 1));
628
+ const entryShape = source.entryShape && typeof source.entryShape === 'object'
629
+ ? {
630
+ ...source.entryShape,
631
+ ...(source.configSchema !== undefined ? { fields: source.configSchema } : {}),
632
+ }
633
+ : undefined;
634
+ return {
635
+ id: pinned ? source.id.slice(0, at) : source.id,
636
+ version: source.version ?? (pinned ? Number(source.id.slice(at + 1)) : 1),
637
+ kind: source.kind,
638
+ ports: { in: portShapes(source.ports?.in), out: portShapes(source.ports?.out) },
639
+ slots: contractData(authoredSlots(source.slots)),
640
+ effects: source.effects,
641
+ review: source.review ? { fields: [...source.review.fields] } : undefined,
642
+ shape: source.shape,
643
+ optional: flag(source.optional),
644
+ declaresRandomness: flag(source.declaresRandomness),
645
+ scriptPoints: source.scriptPoints ? contractData(scriptPointsOf(source)) : undefined,
646
+ sessionShape: contractData(source.sessionShape),
647
+ earlyExit: flag(source.earlyExit),
648
+ causesEvent: source.causesEvent,
649
+ causesEventFrom: source.causesEventFrom,
650
+ // Sorted: which payloads an inlet reads is a set, not a sequence.
651
+ payloads: source.payloads?.length ? [...source.payloads].sort() : undefined,
652
+ liveRow: flag(source.liveRow),
653
+ media: contractData(source.media),
654
+ entryShape: contractData(entryShape),
655
+ // Contract that rides the row's policy (owner ruling 2026-09-27): a
656
+ // descriptor's own field, else the row's policy spelling — one hash.
657
+ bands: bandsMaterial(source.bands ?? source.policy?.bands ?? undefined),
658
+ bandPorts: bandPortsMaterial(source.bandPorts ?? source.policy?.bandPorts ?? undefined),
659
+ portSchemas: portSchemasMaterial(source.portSchemas ?? source.policy?.portSchemas ?? undefined),
660
+ semantics: source.semantics,
661
+ };
662
+ }
663
+ /**
664
+ * The content hash of a definition — a digest of `definitionContract`, and
665
+ * the one answer to *is this the same definition?* The registry guard below,
666
+ * core's `pipeline_definition_registry` pointer and a run's receipt all name
667
+ * this string.
668
+ * @internal
669
+ */
670
+ export function definitionContractHash(source) {
671
+ return contentHash(definitionContract(source));
672
+ }
673
+ function register(d) {
674
+ // Contract, not arrival (src/hash.ts): a re-declaration whose contract is
675
+ // unchanged replaces the entry — policy and display text are the fresher
676
+ // author's — and one whose contract moved is refused with both hashes.
677
+ // Only computed when there is something to compare against, so the
678
+ // ordinary path costs nothing.
679
+ const existing = types.get(d.id);
680
+ if (existing)
681
+ refuseUnlessSameHash(definitionContractHash(existing), definitionContractHash(d), `duplicate type id: ${d.id}`);
682
+ checkWritePublishes(d);
683
+ checkNoAuthoredSettings(d);
684
+ checkNoSettingsPort(d);
685
+ checkScriptPointsAccept(d);
686
+ checkCausesEvent(d);
687
+ checkNoAmbientExtras(d);
688
+ // Before the id is claimed, so a refused declaration can be fixed and retried.
689
+ checkModeTitled(d);
690
+ checkDisplayText(d);
691
+ // Bands (typed templates P2): identifier keys, a registered variable whose
692
+ // scope names the key, and one meaning per key across every definition.
693
+ checkBandDeclarations(d, types.values());
694
+ assertMessageVerbFloors(d.sessionShape, d.id);
695
+ assertSessionWrites(d.sessionShape, d.id);
696
+ assertTurnControls(d.sessionShape, d.id);
697
+ assertChannelDecls(d.sessionShape, d.id);
698
+ // A finding, not a refusal: the fallback is documented (inference), the
699
+ // omission is recorded, and `validate()` says it on every placement.
700
+ const reviewFinding = reviewFieldsFinding(d);
701
+ if (reviewFinding)
702
+ registrationFindings.set(d.id, [reviewFinding]);
703
+ else
704
+ registrationFindings.delete(d.id);
705
+ types.set(d.id, d);
706
+ return d;
707
+ }
708
+ /**
709
+ * The extras every script site is offered, whatever its slot lists (R32,
710
+ * PLAN-turn-order §4.14): `session`, the run's settings document. The
711
+ * executor supplies them at every site — a slot's port hook and an interior
712
+ * point alike — so a slot's `extras` names only what is particular to it,
713
+ * and listing an ambient one is refused (one way to say it, R26).
714
+ * @internal
715
+ */
716
+ export const AMBIENT_SCRIPT_EXTRAS = ['session'];
717
+ function checkNoAmbientExtras(d) {
718
+ for (const [name, slot] of Object.entries(d.slots ?? {})) {
719
+ const listed = slot.extras ?? [];
720
+ const ambient = listed.filter((e) => AMBIENT_SCRIPT_EXTRAS.includes(e));
721
+ if (ambient.length)
722
+ throw new Error(`${d.id}: slot '${name}' lists ${ambient.map((e) => `'${e}'`).join(', ')} in its extras — ` +
723
+ `every script site is handed ${AMBIENT_SCRIPT_EXTRAS.map((e) => `'${e}'`).join(', ')} already (R32); drop it from the list`);
724
+ }
725
+ }
726
+ /** `{ a: shape, … }` as one comparable line, so a misfit names the ports. */
727
+ const portLine = (ports) => Object.entries(ports ?? {})
728
+ .sort(([a], [b]) => a.localeCompare(b))
729
+ .map(([k, v]) => `${k}: ${String(v)}`)
730
+ .join(', ');
731
+ // Authored slots only: the registry adds the substrate `settings` slot to
732
+ // every definition (R-9), which a raw declaration does not carry (M4).
733
+ const slotLine = (slots) => Object.keys(authoredSlots(slots) ?? {}).sort().join(', ');
734
+ /**
735
+ * Can `swap` stand in for `pinned` at node `key` (R28)? A swap is seated with
736
+ * the pin's node config, so it must be the same kind with the same in- and
737
+ * out-ports (by name and shape) and the same slots — a slot the pin's node
738
+ * does not wire would never reach the swap, and a person would pick an
739
+ * option that silently ignores its own settings. Script points are free: a
740
+ * chain is configured on the node key, whatever sits there. One sentence
741
+ * for the builder and the package pass alike.
742
+ * @experimental
743
+ */
744
+ export function swapFitFinding(key, pinned, swap) {
745
+ // A provisional definition has no handler (plans/29 R-2): offering it
746
+ // would put an option in front of a person that cannot run.
747
+ if (swap.provisional)
748
+ return `'${swap.id}' cannot stand in for '${key}': it is provisional — declared, with no handler to run`;
749
+ // Plugins are blind to connections (R53): a node that uses one is one only
750
+ // core's code can stand in for, whatever the fit.
751
+ const usesConnection = Object.values(pinned.slots ?? {}).some((slot) => slot?.kind === 'connection');
752
+ if (usesConnection && !swap.id.startsWith('core:'))
753
+ return (`'${swap.id}' cannot stand in for '${key}': that node uses a connection, and a plugin's code never ` +
754
+ `touches connection data or calls a model (R53) — shape the core node with prompts or a config instead` +
755
+ pluginRuleRef('connections'));
756
+ const want = `a ${pinned.kind} with in { ${portLine(pinned.ports?.in)} } → out { ${portLine(pinned.ports?.out)} } and slots [${slotLine(pinned.slots)}]`;
757
+ const got = `a ${swap.kind} with in { ${portLine(swap.ports?.in)} } → out { ${portLine(swap.ports?.out)} } and slots [${slotLine(swap.slots)}]`;
758
+ return want === got
759
+ ? undefined
760
+ : `'${swap.id}' cannot stand in for '${key}': a swap must match the pin's kind, ports and slots — ${want}; it is ${got}`;
761
+ }
762
+ /**
763
+ * Can one inlet answer every event of an `events` lock (R33)? Each listed
764
+ * event must carry a payload the inlet declares it reads; an inlet that
765
+ * declares none answers one event only. One sentence for the builder and
766
+ * the package pass alike.
767
+ * @experimental
768
+ */
769
+ export function eventsLockFindings(inlet, events) {
770
+ const reads = inlet.payloads ?? [];
771
+ if (!reads.length)
772
+ return [
773
+ `'${inlet.id}' declares no payloads, so it answers one event: { genre, event }. ` +
774
+ `A spec answering several events uses an inlet that reads them all — ` +
775
+ `core:inlet/session-event@1 (PLAN-turn-order §4.14)`,
776
+ ];
777
+ const out = [];
778
+ for (const e of events) {
779
+ const shape = eventById(e)?.payload;
780
+ if (!eventById(e))
781
+ continue; // refused by the lock's own event check, in its own words
782
+ if (!shape)
783
+ out.push(`'${e}' carries no payload, so it cannot share an inlet with other events — lock it alone: { genre, event }`);
784
+ else if (!reads.includes(shape))
785
+ out.push(`'${inlet.id}' does not read '${shape}', the payload of '${e}' — it reads ${reads.map((r) => `'${r}'`).join(', ')}`);
786
+ }
787
+ return out;
788
+ }
789
+ /**
790
+ * `causesEvent` agrees with the event's own `causedBy` (R33). The event side
791
+ * is the complete statement — `message-completed` is caused by three writes
792
+ * whose own `causesEvent` names their primary event — so this field may only
793
+ * name an event that already lists the definition. And only core defines
794
+ * events (R30, F8): a package's outlet cannot cause one.
795
+ */
796
+ function checkCausesEvent(d) {
797
+ if (d.causesEventFrom !== undefined) {
798
+ if (d.kind !== 'outlet' || d.effects !== 'write')
799
+ throw new Error(`'${d.id}' declares causesEventFrom — only a write outlet causes an event`);
800
+ if (d.causesEvent)
801
+ throw new Error(`'${d.id}' declares both causesEvent and causesEventFrom — one says which event, not both`);
802
+ if (!d.ports.in?.[d.causesEventFrom])
803
+ throw new Error(`'${d.id}' names causesEventFrom '${d.causesEventFrom}', which is not one of its in-ports`);
804
+ return;
805
+ }
806
+ if (!d.causesEvent)
807
+ return;
808
+ const event = eventById(d.causesEvent);
809
+ if (!event)
810
+ throw new Error(`${d.id}: ${notADeclaredEvent(d.causesEvent)}`);
811
+ const base = d.id.replace(/@\d+$/, '');
812
+ if (!event.causedBy?.includes(base))
813
+ throw new Error(`'${d.id}' causes '${d.causesEvent}', but that event's causedBy does not name '${base}'. ` +
814
+ `causedBy is the one statement of what causes what — add '${base}' there, or drop causesEvent (R33)`);
815
+ }
816
+ /**
817
+ * A gate-eligible write publishes `write-result@1`, never raw ids (13 §7j-b).
818
+ *
819
+ * Checked at registration rather than reviewed by hand, because the hand-written version
820
+ * was already wrong: three core Consumers declared `row-ids@1` out ports while declaring
821
+ * `effects: 'write'`. Each one was a spec that could wire a downstream foreign key to a
822
+ * row a reviewer had not approved yet — and under `async` review that row may never exist.
823
+ * The failure lands long after the run that caused it, which is the worst kind to find by
824
+ * reading.
825
+ */
826
+ function checkWritePublishes(d) {
827
+ if (d.effects !== 'write')
828
+ return;
829
+ const bad = Object.entries(d.ports?.out ?? {}).filter(([, s]) => shapeIdOf(s) === 'core:shape/row-ids@1');
830
+ if (!bad.length)
831
+ return;
832
+ throw new Error(`${d.id} declares effects: 'write' but publishes core:shape/row-ids@1 on ` +
833
+ `${bad.map(([k]) => `'${k}'`).join(', ')}. A gate-eligible write publishes ` +
834
+ `core:shape/write-result@1 — pending under async review, committed otherwise — so a ` +
835
+ `downstream port wanting raw ids fails at publish instead of writing a foreign key ` +
836
+ `that dangles when the reviewer rejects (13 §7j-b).`);
837
+ }
838
+ /**
839
+ * `settings` is the substrate's slot, never an author's (R-9).
840
+ *
841
+ * Refused at registration rather than merged, because the two would collide
842
+ * at one address: the executor reads `config[key].settings.enabled` to skip
843
+ * an optional node and `.review` to gate a write, and an authored field of
844
+ * the same name would be read as that switch. It is also what lets the
845
+ * registry hash leave the projected slot out — a slot that is never authored
846
+ * is never a change to what an author declared.
847
+ */
848
+ function checkNoAuthoredSettings(d) {
849
+ if (!d.slots)
850
+ return;
851
+ if ('settings' in d.slots)
852
+ throw new Error(`${d.id} declares a slot named 'settings'. That name is reserved for the substrate's ` +
853
+ `own slot — \`enabled\` on an optional node, \`review\` on a gated one — which the ` +
854
+ `registry projection declares and the executor reads. Name the slot for what it ` +
855
+ `holds ('parameters' for tunables).`);
856
+ // By kind as well as by name (U4 residual, 2026-09-16): a slot called
857
+ // anything else but declared `kind: 'settings'` would render through the
858
+ // substrate's branch of the panel and hash as authored material, which is
859
+ // the same collision one address over.
860
+ const byKind = Object.entries(d.slots).find(([, decl]) => decl?.kind === 'settings');
861
+ if (byKind)
862
+ throw new Error(`${d.id} declares slot '${byKind[0]}' with kind 'settings'. That kind is the ` +
863
+ `substrate's — derived from \`optional\` and \`effects\`, never authored. Declare ` +
864
+ `'parameters' for tunables.`);
865
+ }
866
+ /**
867
+ * Nor an out-port of the name (F39; U7 review, S2).
868
+ *
869
+ * `<nodeKey>.settings` and `<nodeKey>.settings.*` are the address the
870
+ * validator and the executor read as the substrate's switches: a data edge
871
+ * drawn from it is refused as a setting travelling (F39), and a reference to
872
+ * it resolves to nothing. A definition publishing an out-port of that name
873
+ * would have every edge from the port refused under a law about something
874
+ * else — a port nobody could wire — so the name is refused where the author
875
+ * is, and the F39 edge rule can never mistake a declared port for a switch.
876
+ * `register()` is F39's registry door: `core:verdict/settings-travel` judges
877
+ * each declared out-port and this quotes it (01 §13).
878
+ */
879
+ function checkNoSettingsPort(d) {
880
+ for (const port of Object.keys(d.ports?.out ?? {})) {
881
+ const heard = settingsTravelVerdict.judge({ kind: 'port', definitionId: d.id, port });
882
+ if (!heard.ok)
883
+ throw new Error(refusalText(heard));
884
+ }
885
+ }
886
+ /**
887
+ * A script point names the kinds it accepts (R-11; U4 residual 2026-09-16).
888
+ * A point nothing can attach to is a control with no effect wearing a
889
+ * contract: the panel would offer the hook and every kind would be refused
890
+ * at it.
891
+ */
892
+ function checkScriptPointsAccept(d) {
893
+ for (const p of d.scriptPoints ?? []) {
894
+ const point = p;
895
+ const key = typeof point === 'string' ? point : String(point?.key);
896
+ const accepts = typeof point === 'string' ? undefined : point?.accepts;
897
+ if (!Array.isArray(accepts) || accepts.length === 0)
898
+ throw new Error(`${d.id} declares script point '${key}' accepting no script kind. A point is ` +
899
+ `{ key, accepts, label } — list the kinds it takes (e.g. ['core:script:text/transform@1']); ` +
900
+ `a point that accepts nothing is a hook nothing can attach to.`);
901
+ }
902
+ }
903
+ const shapeIdOf = (s) => typeof s === 'string' ? s : (s?.id ?? undefined);
904
+ /**
905
+ * Is there text a person reads — a non-blank string, or a map with a non-blank
906
+ * `en`? A map carrying only `fr` is not titled: `en` is the locale every other
907
+ * falls back to (R-20), so a card with no `en` has no face on an English install.
908
+ */
909
+ const hasDisplayText = (v) => isI18n(v);
910
+ /**
911
+ * A chat mode ships titled (19 §2).
912
+ *
913
+ * A shape-bearing input type *is* a chat mode, and the New Chat picker renders one card
914
+ * per mode from rows — `i18n.name` is that card's face. An untitled mode could only
915
+ * render as its type id, which is an address, not a name; refused here at declaration,
916
+ * where the author is, rather than at install, where the admin is. A missing
917
+ * `description` is a poorer card rather than a broken one, so the packager warns about
918
+ * that instead of this throwing (cli/src/compiler.ts, W_MODE_NO_DESCRIPTION).
919
+ */
920
+ function checkModeTitled(d) {
921
+ if (d.kind !== 'inlet' || !d.sessionShape)
922
+ return;
923
+ if (hasDisplayText(d.i18n?.name))
924
+ return;
925
+ throw new Error(`${d.id} declares a sessionShape but no i18n.name. A shape-bearing input type is a ` +
926
+ `session mode, and the New Session picker renders every mode as a card — give it a ` +
927
+ `title: i18n: { name: { en: '…' } }. Add a description there too; the packager ` +
928
+ `warns when a mode ships without one.`);
929
+ }
930
+ /**
931
+ * Every display string a definition declares is `I18n` (R-20; U5i, ruled
932
+ * 2026-09-17): `i18n.name` and `i18n.description`; each slot's `description`,
933
+ * its prompt `fields[].i18n` and its `schema` (through `settingsSchemaFindings`);
934
+ * each script point's `label`, `description` and deprecated `i18n`; a session
935
+ * shape's `fields` and its `panels[].title`; an entry shape's `fields`. All
936
+ * kinds, not only a mode-bearing inlet — `checkModeTitled` keeps the one
937
+ * strictness of its own (a mode must have a name); this refuses a blank or a
938
+ * mis-shaped value anywhere, with the field named and the fix stated.
939
+ */
940
+ function checkDisplayText(d) {
941
+ const findings = [];
942
+ findings.push(...i18nFindings(d.i18n?.name, `${d.id} i18n.name`));
943
+ findings.push(...i18nFindings(d.i18n?.description, `${d.id} i18n.description`));
944
+ for (const [slotName, slot] of Object.entries(d.slots ?? {})) {
945
+ if (!slot)
946
+ continue;
947
+ const at = `${d.id} slots.${slotName}`;
948
+ findings.push(...i18nFindings(slot.description, `${at}.description`));
949
+ for (const [field, decl] of Object.entries(slot.fields ?? {}))
950
+ findings.push(...i18nFindings(decl?.i18n, `${at}.fields.${field}.i18n`));
951
+ findings.push(...settingsSchemaFindings(slot.schema, `${at}.schema`));
952
+ }
953
+ for (const p of d.scriptPoints ?? []) {
954
+ const at = `${d.id} scriptPoints[${String(p.key)}]`;
955
+ findings.push(...i18nFindings(p.label, `${at}.label`));
956
+ findings.push(...i18nFindings(p.description, `${at}.description`));
957
+ }
958
+ if (d.sessionShape) {
959
+ findings.push(...settingsSchemaFindings(d.sessionShape.fields, `${d.id} sessionShape.fields`));
960
+ findings.push(...widgetDeclsFindings(d.sessionShape.panels, `${d.id} sessionShape.panels`));
961
+ }
962
+ if (d.entryShape)
963
+ findings.push(...settingsSchemaFindings(d.entryShape.fields, `${d.id} entryShape.fields`));
964
+ if (findings.length)
965
+ throw new Error(`${d.id} declares display text a publish refuses (R-20):\n · ${findings.join('\n · ')}`);
966
+ }
967
+ /**
968
+ * The display text of a list of widget declarations (R-20): each `title`
969
+ * (required — the chrome and the tray show it) and each `settings` schema.
970
+ * Shared by a session shape's `panels` and a genre's shape, which carry the
971
+ * same declarations.
972
+ * @experimental
973
+ */
974
+ export function widgetDeclsFindings(raw, where) {
975
+ if (raw === undefined)
976
+ return [];
977
+ if (!Array.isArray(raw))
978
+ return [`${where}: the widgets are an array of declarations`];
979
+ const out = [];
980
+ raw.forEach((w, i) => {
981
+ const decl = w;
982
+ const at = `${where}[${typeof decl?.id === 'string' ? decl.id : i}]`;
983
+ if (!decl || typeof decl !== 'object') {
984
+ out.push(`${at}: a widget declaration is an object — { id, title, component }`);
985
+ return;
986
+ }
987
+ out.push(...i18nFindings(decl.title, `${at}.title`, { required: true }));
988
+ out.push(...settingsSchemaFindings(decl.settings, `${at}.settings`));
989
+ // The base sections it reads (R75): a name outside them is refused here.
990
+ out.push(...widgetReadsFindings(decl.reads, `${at}.reads`));
991
+ // What renders inside: `component` (R25), a component's slug — the
992
+ // one way. The `surface` shortcut is gone (2026-10-02).
993
+ if (decl.surface !== undefined)
994
+ out.push(`${at}.surface: gone — give \`component\`, and place an \`sp-frame\` inside it for a document`);
995
+ else if (decl.component === undefined)
996
+ out.push(`${at}: names nothing to render — give \`component\`, a component's slug`);
997
+ else if (typeof decl.component !== 'string' || !decl.component)
998
+ out.push(`${at}.component: a component's slug`);
999
+ });
1000
+ return out;
1001
+ }
1002
+ /** @experimental */
1003
+ export function getDefinition(id) {
1004
+ return types.get(id);
1005
+ }
1006
+ /** @experimental */
1007
+ export function allDefinitions() {
1008
+ return [...types.values()];
1009
+ }
1010
+ /** @experimental */
1011
+ export function _clearDefinitions() {
1012
+ types.clear();
1013
+ registrationFindings.clear();
1014
+ }
1015
+ // ── describe*Definition — one per kind, same shape, no modality anywhere ─────
1016
+ //
1017
+ // `describeInletDefinition · describeQueryDefinition · describeTaskDefinition ·
1018
+ // describeOracleDefinition · describeOutletDefinition`. `describeEntryType`
1019
+ // keeps *type*: the entry-type word is not yet ruled (NOMENCLATURE §5).
1020
+ /**
1021
+ * ## Why every `describe*` is generic over its slots
1022
+ *
1023
+ * `Descriptor.slots` is the open `Record<string, SlotDecl>`, so a declaration
1024
+ * passed straight into it arrives with its **keys erased** — and with them the
1025
+ * `params` slot's `schema` keys, which is the entire declared parameter
1026
+ * vocabulary of the node. That erasure is what let `input.params.foo` be an
1027
+ * `any` lookup on a node whose schema has no `foo`: `topK` and `limit` were
1028
+ * both read that way for releases, off nodes that did declare them, at a
1029
+ * spelling nothing supplied.
1030
+ *
1031
+ * Capturing the argument in `S` keeps the literal keys, which is what
1032
+ * `InputOf` (src/nodeInput.ts) derives a handler's `input` type from.
1033
+ *
1034
+ * ⚠ **Type-level only.** `register()` still receives the same object and the
1035
+ * content hash is computed over the same runtime value, so nothing here moves a
1036
+ * declaration or re-hashes a type.
1037
+ *
1038
+ * ⚠ **`S` is constrained rather than `const`, and the difference is
1039
+ * deliberate.** `describeOracleDefinition` below needs the literal *values* — the
1040
+ * `optional: ['json_schema']` tuple `ctx.can()` narrows against — so it pays
1041
+ * for `const` with a validation done by intersection in the parameter. Names
1042
+ * are all `InputOf` needs, and an object literal keeps its own keys with or
1043
+ * without `const`; a `const` here would additionally freeze `accepts: [...]`
1044
+ * and `extras: [...]` into readonly tuples, which `SlotDecl` declares as
1045
+ * mutable `string[]` and which several core input and task types use.
1046
+ * @experimental
1047
+ */
1048
+ export const describeInletDefinition = (d) => register({ ...d, kind: 'inlet' });
1049
+ /** @experimental */
1050
+ export const describeQueryDefinition = (d) => register({ ...d, kind: 'query' });
1051
+ /** @public */
1052
+ export const describeTaskDefinition = (d) => register({ ...d, kind: 'task' });
1053
+ /**
1054
+ * An oracle definition.
1055
+ *
1056
+ * `const S` on the slots is what makes `ctx.can()` safe: without it,
1057
+ * `optional: ['json_schema']` widens to `CapabilityId[]` at the declaration and
1058
+ * the binding can only be told "some capability", which is no narrowing at all.
1059
+ * With it the literal tuple survives into `Pinned<D>` and out the other side, so
1060
+ * a binding asking about a capability its node never declared does not compile.
1061
+ * @experimental
1062
+ */
1063
+ export const describeOracleDefinition = (
1064
+ // The slot validation lives in the PARAMETER, not in `S`'s constraint. A
1065
+ // constraint of `Record<string, SlotDecl>` widens each slot to SlotDecl's own
1066
+ // declared types, so `optional: ['json_schema']` arrives as
1067
+ // `readonly CapabilityId[]` and `ctx.can()` narrows to nothing. Intersecting
1068
+ // here validates just as strictly while leaving `S` the literal it was written
1069
+ // as — which is the whole basis of the typed probe.
1070
+ d) => register({ ...d, kind: 'oracle' });
1071
+ /** @experimental */
1072
+ export const describeOutletDefinition = (d) => register({ ...d, kind: 'outlet' });
1073
+ // ── Entry types (Part 1) ────────────────────────────────────────────────────
1074
+ //
1075
+ // A lorebook row's *kind* is a declared, versioned type rather than the table
1076
+ // it happens to sit in. Three near-identical tables collapse into one, and what
1077
+ // used to be a schema fact — "world lore has a category, history has a year" —
1078
+ // becomes a declaration the engine reads.
1079
+ //
1080
+ // What keeps that from turning into a swamp is the **field role**: the ranker asks
1081
+ // the type which field is priority instead of reading `.priority`, so a fourth
1082
+ // shape is a declaration and not a branch. Three constraints hold the line, and
1083
+ // each is enforced here rather than reviewed by hand:
1084
+ //
1085
+ // 1. **No mini-DSLs.** `order` is an array of `{field, dir}`, never
1086
+ // `'date:year,month,day'`. A string the engine parses is code the type
1087
+ // ships with extra steps.
1088
+ // 2. **A new behaviour may add a field role; a new type may not.** The vocabulary is
1089
+ // the frozen list below, and a conformance canary (`checkEntryTypes`)
1090
+ // watches both directions of it.
1091
+ // 3. **Types never ship code.** Anything branchy is a *named, versioned,
1092
+ // core-owned policy* the type selects from a closed registry — mirroring
1093
+ // the deliberate absence of T3 validator code in values.ts.
1094
+ /**
1095
+ * The field roles the engine reads. Frozen, and the reason it is frozen is rule 2
1096
+ * above: the list grows when a *behaviour* needs a new question answered, never
1097
+ * because a type has a field it would like consulted.
1098
+ * @experimental
1099
+ */
1100
+ export const ENTRY_ROLES = [
1101
+ /** Which field is this row's display title. */
1102
+ 'title',
1103
+ /** How siblings sort among themselves — structured keys, never a string. */
1104
+ 'order',
1105
+ /** Which field carries the manual 1..3 boost. Absent means **no bonus**. */
1106
+ 'priority',
1107
+ /** Which reference column decides who may see this row, under which policy. */
1108
+ 'anchor',
1109
+ /** Which fields make the text an embedding is computed over. */
1110
+ 'embedText',
1111
+ /** Which field holds the trigger keys the keyword scan matches. */
1112
+ 'key',
1113
+ /** Which reference column points at the row this one hangs under. */
1114
+ 'parent',
1115
+ ];
1116
+ /**
1117
+ * The budget bands a candidate can compete in — the engine's `RetrievalBand`,
1118
+ * closed on purpose.
1119
+ *
1120
+ * ⚠ Closed because the failure of an open one is **silent**: the signal-weight
1121
+ * and share maps are total over this union, so an entry type declaring a band
1122
+ * nobody budgets has its candidates scored against `undefined` and dropped with
1123
+ * a green test suite. That is not hypothetical — history was absent from every
1124
+ * prompt for two spec versions exactly this way. A new shape picks the band it
1125
+ * competes in; it does not mint one.
1126
+ * @experimental
1127
+ */
1128
+ export const ENTRY_SOURCE_KINDS = [
1129
+ 'messages',
1130
+ 'worldLore',
1131
+ 'characterLore',
1132
+ 'history',
1133
+ 'relationships',
1134
+ ];
1135
+ /**
1136
+ * The short name this type's rows carry on the wire — `extensions.serenepub`
1137
+ * in a character-card book.
1138
+ *
1139
+ * Closed to the names the importer reads: the three every file has carried,
1140
+ * plus `location` and `item`, which the app's importer restores as a place and
1141
+ * an item (lorebooks plan A26 — written as world lore, a place reads back
1142
+ * without its links' meaning or its stats). A type outside them declares
1143
+ * nothing here: no marker is honest, where a marker no importer reads is a
1144
+ * file that round-trips into the wrong shape. Widening the list is a
1145
+ * deliberate act with an importer change beside it.
1146
+ * @experimental
1147
+ */
1148
+ export const ENTRY_EXPORT_KEYS = ['world', 'character', 'history', 'location', 'item'];
1149
+ /**
1150
+ * Visibility policies a type may select for its anchor.
1151
+ *
1152
+ * `core:policy/binding-visibility@1` is the four branches character lore
1153
+ * already has — character equality, persona membership, narrator-only when the
1154
+ * binding is unbound, invisible when the row is unanchored. That is *policy*,
1155
+ * so it is named, versioned and implemented by core; the type picks from this
1156
+ * list and never authors one (rule 3).
1157
+ * @experimental
1158
+ */
1159
+ export const ENTRY_ANCHOR_POLICIES = ['core:policy/binding-visibility@1'];
1160
+ const ENTRY_TYPE_ID = /^([a-z0-9][a-z0-9.-]*):entry\/([a-z0-9][a-z0-9-]*)@(\d+)$/;
1161
+ /**
1162
+ * Declare an entry type.
1163
+ *
1164
+ * The version lives in the id and therefore at every call site that names one,
1165
+ * which is the same convention `pin()` keeps for node definitions. What is
1166
+ * deliberately *not* here is a pinned constructor: `pin()` mints `v1()`, and
1167
+ * `v1()` builds a node a spec wires. An entry type is a row shape — there is
1168
+ * nothing to construct — so minting one would offer a call that can only ever
1169
+ * be a mistake.
1170
+ * @experimental
1171
+ */
1172
+ export const describeEntryType = (d) => {
1173
+ const { id, i18n, ...shape } = d;
1174
+ // Before the id is claimed, so a refused declaration can be fixed and
1175
+ // retried — the same order `checkModeTitled` runs in.
1176
+ assertEntryShape(id, shape);
1177
+ return register({
1178
+ id,
1179
+ i18n,
1180
+ kind: 'entry',
1181
+ // An entry type publishes nothing: it is not in the graph. Empty rather
1182
+ // than optional so `Descriptor` keeps meaning one thing for the five
1183
+ // kinds that are.
1184
+ ports: {},
1185
+ entryShape: shape,
1186
+ });
1187
+ };
1188
+ /** Every entry type this build declares. @internal */
1189
+ export const allEntryTypes = () => allDefinitions().filter((t) => t.kind === 'entry');
1190
+ /**
1191
+ * Refusals at the author's line — an id, a namespace, and four closed
1192
+ * vocabularies.
1193
+ *
1194
+ * Throwing rather than collecting findings, because every one of these is a
1195
+ * typo or a decision somebody has to make, and none of them has a partial
1196
+ * answer worth keeping.
1197
+ */
1198
+ function assertEntryShape(id, shape) {
1199
+ if (!ENTRY_TYPE_ID.test(id))
1200
+ throw new Error(`'${id}' is not a valid entry type id. The grammar is ` +
1201
+ `'<namespace>:entry/<name>@<major>' — 'core:entry/world-lore@1'. The version ` +
1202
+ `is the pin, exactly as for node definitions.`);
1203
+ /**
1204
+ * Core is the sole author of entry types, and this line is the switch.
1205
+ *
1206
+ * Not a permanent property of the design — an entry type is data, and
1207
+ * nothing about the projection cares who wrote it. What is missing is the
1208
+ * rest of the story: a plugin-authored type needs its constraint projection
1209
+ * gated, its `fields` reviewed and its rows owned. Until that exists the
1210
+ * honest state is off, said out loud, in one place.
1211
+ */
1212
+ if (!id.startsWith('core:'))
1213
+ throw new Error(`'${id}' cannot be declared: entry types are core-authored in this release. ` +
1214
+ `The row shape is data and nothing in the projection cares who wrote it, so ` +
1215
+ `this is a switch rather than a wall — but a plugin-owned type also owns a ` +
1216
+ `database constraint and the rows under it, and that half is not built.`);
1217
+ const unknown = unknownRoles(shape);
1218
+ if (unknown.length)
1219
+ throw new Error(`${id} declares ${unknown.map((r) => `'${r}'`).join(', ')}, which no engine ` +
1220
+ `behaviour reads. The field roles are ${ENTRY_ROLES.join(', ')} — a new *behaviour* ` +
1221
+ `may add one, a new *type* may not, or the vocabulary is just a second name ` +
1222
+ `for the field.`);
1223
+ for (const [field, decl] of Object.entries(shape.fields ?? {})) {
1224
+ const narrowed = decl?.narrows;
1225
+ if (narrowed === undefined)
1226
+ continue;
1227
+ if (narrowed === field)
1228
+ throw new Error(`${id} declares that '${field}' narrows itself. A field narrows another ` +
1229
+ `field of its own type, as a day narrows a month.`);
1230
+ if (!Object.prototype.hasOwnProperty.call(shape.fields, narrowed))
1231
+ throw new Error(`'${field}' narrows '${narrowed}', which ${id} does not declare. A field ` +
1232
+ `narrows another field of its own type, as a day narrows a month.`);
1233
+ }
1234
+ if (!ENTRY_SOURCE_KINDS.includes(shape.sourceKind))
1235
+ throw new Error(`${id} declares sourceKind '${shape.sourceKind}', which is not a budget band. ` +
1236
+ `Pick one of ${ENTRY_SOURCE_KINDS.join(', ')} — the weight and share maps are ` +
1237
+ `total over those five, so a sixth name is not a new band, it is candidates ` +
1238
+ `scored against undefined and dropped with nothing reporting it.`);
1239
+ if (shape.exportKey && !ENTRY_EXPORT_KEYS.includes(shape.exportKey))
1240
+ throw new Error(`${id} declares exportKey '${shape.exportKey}', which no importer reads. The ` +
1241
+ `wire names are ${ENTRY_EXPORT_KEYS.join(', ')}; declare nothing to export ` +
1242
+ `without a marker.`);
1243
+ const policy = shape.roles?.anchor?.policy;
1244
+ if (policy && !ENTRY_ANCHOR_POLICIES.includes(policy))
1245
+ throw new Error(`${id} anchors under policy '${policy}', which core does not implement. Pick ` +
1246
+ `one of ${ENTRY_ANCHOR_POLICIES.join(', ')}. Types select policies; they ` +
1247
+ `never author them, which is what keeps a declaration from being code.`);
1248
+ const render = shape.render;
1249
+ if (render !== undefined && !/^[a-z0-9][a-z0-9.-]*:var\/[a-z0-9-]+@\d+$/.test(render))
1250
+ throw new Error(`${id} renders as '${render}', which is not a variable id. Name the variable ` +
1251
+ `whose layout renders these rows — 'core:var/world-lore@1'.`);
1252
+ }
1253
+ const unknownRoles = (shape) => Object.keys(shape.roles ?? {}).filter((r) => !ENTRY_ROLES.includes(r));
1254
+ /**
1255
+ * The conformance canary — the field role vocabulary checked in **both** directions
1256
+ * (the shape values.ts's four-way registry canary already has).
1257
+ *
1258
+ * Forward: nothing declares a field role the engine does not read.
1259
+ * `describeEntryType`
1260
+ * refuses that at the author's line, so this is the backstop for declarations
1261
+ * that did not come through the door — a row written by another build, a type
1262
+ * read back from the registry.
1263
+ *
1264
+ * Backward, and this is the direction that earns the canary: **every field role
1265
+ * the engine reads is declared by somebody.** A field role no type answers is a
1266
+ * question
1267
+ * the engine asks nothing, and the vocabulary is frozen precisely so that one
1268
+ * gets deleted rather than sitting there looking supported.
1269
+ * @experimental
1270
+ */
1271
+ export function checkEntryTypes(types) {
1272
+ const findings = [];
1273
+ const declared = new Set();
1274
+ for (const t of types) {
1275
+ const shape = t.entryShape;
1276
+ if (!shape)
1277
+ continue;
1278
+ for (const role of Object.keys(shape.roles ?? {}))
1279
+ declared.add(role);
1280
+ for (const role of unknownRoles(shape))
1281
+ findings.push({
1282
+ severity: 'error',
1283
+ code: 'E_UNKNOWN_ROLE',
1284
+ where: t.id,
1285
+ message: `declares field role '${role}', which no engine behaviour reads`,
1286
+ fix: `use one of ${ENTRY_ROLES.join(', ')}, or add the field role here and the ` +
1287
+ `behaviour that reads it in the same change. A field role only a declaration ` +
1288
+ `knows about is a field with a longer name.`,
1289
+ });
1290
+ }
1291
+ for (const role of ENTRY_ROLES)
1292
+ if (!declared.has(role))
1293
+ findings.push({
1294
+ severity: 'error',
1295
+ code: 'E_DEAD_ROLE',
1296
+ where: role,
1297
+ message: `no entry type declares '${role}', so nothing answers it`,
1298
+ fix: `declare it on the type it describes, or delete the field role. The vocabulary ` +
1299
+ `is frozen so that it stays small — an unanswered field role is one the engine ` +
1300
+ `asks and nobody hears.`,
1301
+ });
1302
+ return findings;
1303
+ }
1304
+ /** @public */
1305
+ export function pin(descriptor) {
1306
+ const version = /@(\d+)$/.exec(descriptor.id)?.[1] ?? '1';
1307
+ const ctor = (config = {}) => ({
1308
+ __node: true,
1309
+ descriptor,
1310
+ config,
1311
+ });
1312
+ return { [`v${version}`]: ctor, id: descriptor.id, descriptor };
1313
+ }
1314
+ /**
1315
+ * The in-ports that make a `liveRow` outlet's write the run's live row (F7,
1316
+ * W1): a placeholder (`generating`) or a claimed row (`row`). Anything else
1317
+ * the outlet writes is a complete row — an ordinary write, as many as the
1318
+ * pipeline likes.
1319
+ * @experimental
1320
+ */
1321
+ export const LIVE_ROW_PORTS = ['generating', 'row'];
1322
+ /** Whether a `liveRow` outlet's resolved payload opens the live row (see `LIVE_ROW_PORTS`). @experimental */
1323
+ export function opensLiveRow(payload) {
1324
+ if (!payload || typeof payload !== 'object')
1325
+ return false;
1326
+ const p = payload;
1327
+ return Boolean(p.generating) || (p.row !== undefined && p.row !== null);
1328
+ }
1329
+ //# sourceMappingURL=descriptors.js.map