@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,677 @@
1
+ /**
2
+ * The builder (04 §4). Kind-named methods — `.inlet() .query() .task() .oracle()
3
+ * .outlet()` — so reading a spec top to bottom shows the effect taxonomy, and so
4
+ * the type system can enforce laws that a generic .step() could only find at
5
+ * validation time (04 §4a). Clauses are `.gather() .each() .loop() .junction()`
6
+ * (R-14, ruled 2026-09-15).
7
+ *
8
+ * The chain is a *value*. It compiles to a document; SP imports the document and
9
+ * never this code (F6).
10
+ *
11
+ * Every node method takes either a pinned constructor or a **callback that receives the
12
+ * scope** — `$ => C.assemble({ messages: $.history.messages })`. The callback form is
13
+ * preferred: it types the node key and the port, and it makes a forward reference
14
+ * impossible to write rather than a finding to read (src/scope.ts). Both forms compile
15
+ * to the same rows.
16
+ */
17
+ import { eventsLockFindings, swapFitFinding, } from './descriptors.js';
18
+ import { makeScope, ITEM } from './scope.js';
19
+ import { isDataRef, isSlotRef } from './refs.js';
20
+ import { assertSpecId, parseSpecId } from './identity.js';
21
+ import { TURN_ORDER_CHANGED_IS_INTERNAL, genreIdOf, sessionEvents } from './genres.js';
22
+ import { eventById, isSessionEventDecl, notADeclaredEvent, packageEventById } from './events.js';
23
+ import { i18nFindings } from './i18n.js';
24
+ import { actionFindings, normalizeContributes, slashCollisions, } from './actions.js';
25
+ /**
26
+ * The stored mark (R28): swaps as ids, present only when non-empty and
27
+ * implying `session: true`, plus the streaming step and step status
28
+ * (B3/B18) when stated; `undefined` when the mark says nothing, so a
29
+ * node that declares nothing hashes as it always did.
30
+ */
31
+ function exposeOf(key, pinned, expose) {
32
+ if (expose.session === false && expose.swaps?.length)
33
+ throw new Error(`node '${key}': expose.swaps offers a choice in session settings, so it cannot be combined with session: false`);
34
+ const swaps = swapIds(key, pinned, expose.swaps);
35
+ for (const field of ['status', 'label', 'purpose']) {
36
+ if (expose[field] === undefined)
37
+ continue;
38
+ const bad = i18nFindings(expose[field], `node '${key}': expose.${field}`);
39
+ if (bad.length)
40
+ throw new Error(bad[0]);
41
+ }
42
+ if (expose.purpose !== undefined && !isModelCall(pinned))
43
+ throw new Error(stepPurposeRefusal(key, pinned.id));
44
+ // What the node shows while it runs (B3/B18), and what the settings call
45
+ // it, ride beside the session mark; the streaming step's laws are
46
+ // `validate()`'s, which sees the whole document (one per execution path,
47
+ // never JSON, never in a repeat).
48
+ const shown = {
49
+ ...(expose.stream === true ? { stream: true } : {}),
50
+ ...(expose.status !== undefined ? { status: expose.status } : {}),
51
+ ...(expose.label !== undefined ? { label: expose.label } : {}),
52
+ ...(expose.purpose !== undefined ? { purpose: expose.purpose } : {}),
53
+ };
54
+ if (swaps.length)
55
+ return { session: true, swaps, ...shown };
56
+ if (expose.session === true)
57
+ return { session: true, ...shown };
58
+ return Object.keys(shown).length ? shown : undefined;
59
+ }
60
+ /**
61
+ * Whether a definition is a **model call**: an oracle that declares a
62
+ * `connection` slot — the only step a step purpose may sit on (see
63
+ * `BuiltNode.expose`). An assemble's `connection` slot says which model the
64
+ * prompt is formatted for; it calls none, so it does not count.
65
+ * @internal
66
+ */
67
+ export function isModelCall(def) {
68
+ return def.kind === 'oracle' && Object.values(def.slots ?? {}).some((s) => s.kind === 'connection');
69
+ }
70
+ /** The one sentence a misplaced step purpose is refused with, at construction and at `validate()`. @internal */
71
+ export const stepPurposeRefusal = (key, definitionId) => `node '${key}': expose.purpose says what a model call is for, but ${definitionId} calls no model — ` +
72
+ `put the purpose on the oracle that does, or give this step a label instead`;
73
+ /**
74
+ * The swap list a node declares, refused where it cannot work (R28, R26):
75
+ * a swap that does not fit would seat a node the spec's edges and config
76
+ * cannot feed, and a person would pick it and get a broken run with no
77
+ * sentence. Returns the stored form — definition ids.
78
+ */
79
+ function swapIds(key, pinned, swaps) {
80
+ const out = [];
81
+ for (const s of swaps ?? []) {
82
+ if (!s?.descriptor)
83
+ throw new Error(`node '${key}': expose.swaps takes pins (C.turnRandom), not ids — got ${JSON.stringify(s)}`);
84
+ const id = s.descriptor.id;
85
+ if (id === pinned.id)
86
+ throw new Error(`node '${key}': '${id}' is the pin — it is always offered first, so it is never listed in expose.swaps`);
87
+ if (out.includes(id))
88
+ throw new Error(`node '${key}': expose.swaps lists '${id}' twice`);
89
+ const misfit = swapFitFinding(key, pinned, s.descriptor);
90
+ if (misfit)
91
+ throw new Error(misfit);
92
+ out.push(id);
93
+ }
94
+ return out;
95
+ }
96
+ /** Lowercase kebab. A slug is a database reference, not display text. */
97
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
98
+ const parseId = (definitionId) => {
99
+ const m = /^(.*)@(\d+)$/.exec(definitionId);
100
+ return m ? { base: m[1], version: Number(m[2]) } : { base: definitionId, version: 1 };
101
+ };
102
+ // ── Chain builders ──────────────────────────────────────────────────────────
103
+ /** @experimental */
104
+ class ChainBuilder {
105
+ spec;
106
+ clauseCtx;
107
+ constructor(spec, clauseCtx) {
108
+ this.spec = spec;
109
+ this.clauseCtx = clauseCtx;
110
+ }
111
+ /** Resolve the callback form against the nodes declared so far. */
112
+ resolve(arg) {
113
+ if (typeof arg !== 'function')
114
+ return arg;
115
+ const known = new Set(this.spec.nodes.map((n) => n.key));
116
+ // Clauses publish under their own id, so they are addressable exactly like nodes —
117
+ // and for an each or a loop that is the *only* well-defined thing to address.
118
+ for (const b of this.spec.clauses)
119
+ known.add(b.id);
120
+ // Inside an each, the current item is addressable without naming the clause.
121
+ if (this.clauseCtx)
122
+ known.add(`${this.clauseCtx.clauseId}.${ITEM}`);
123
+ const localPrefix = this.clauseCtx
124
+ ? `${this.clauseCtx.clauseId}.${this.clauseCtx.chain}`
125
+ : undefined;
126
+ const scope = makeScope(known, localPrefix, this.clauseCtx?.clauseId);
127
+ return arg(scope);
128
+ }
129
+ add(kind, key, arg, opts) {
130
+ const node = this.resolve(arg);
131
+ if (node?.descriptor?.kind !== kind) {
132
+ throw new Error(`.${kind}('${key}', …) was given a ${node?.descriptor?.kind ?? 'non-node'} ` +
133
+ `('${node?.descriptor?.id ?? '?'}'). The method names the kind; use .${node?.descriptor?.kind}() instead.`);
134
+ }
135
+ // A colon marks a synthetic config address, not a node: an envoy's
136
+ // config lives at `envoy:<key>` beside the node keys in the resolved
137
+ // config (`envoyConfigKey`), and a node spelled with one could shadow
138
+ // it — or be read as one. Refused at the key, before it can (U5g
139
+ // review, S2).
140
+ if (key.includes(':')) {
141
+ throw new Error(`node key '${key}' contains ':' — a colon marks a synthetic config address ` +
142
+ `(\`envoy:<key>\`), which a node key must never be mistaken for`);
143
+ }
144
+ if (this.spec.nodes.some((n) => n.key === this.qualify(key))) {
145
+ throw new Error(`duplicate node key '${this.qualify(key)}' — keys are explicit and unique (F21)`);
146
+ }
147
+ // Nodes and clauses share one address space: `$.tools` must name exactly
148
+ // one thing, and the executor publishes a clause's union under its id
149
+ // beside the node values. Found when the tool loop took the key `tools`
150
+ // (2026-09-16) beside a query of the same name.
151
+ if (this.spec.clauses.some((c) => c.id === this.qualify(key))) {
152
+ throw new Error(`node key '${this.qualify(key)}' is already a clause id — nodes and clauses share one address space`);
153
+ }
154
+ const { base, version } = parseId(node.descriptor.id);
155
+ this.spec.nodes.push({
156
+ key: this.qualify(key),
157
+ kind,
158
+ definitionId: base,
159
+ definitionVersion: version,
160
+ // A declaration value given as a literal (an event you declared)
161
+ // is written as its id: the document is JSON, the source is typed.
162
+ config: Object.fromEntries(Object.entries(node.config ?? {}).map(([k, v]) => [
163
+ k,
164
+ // A ref is a proxy that refuses any other property: test it first.
165
+ !isDataRef(v) && !isSlotRef(v) && isSessionEventDecl(v) ? v.id : v,
166
+ ])),
167
+ clauseId: this.clauseCtx?.clauseId,
168
+ clauseKind: this.clauseCtx
169
+ ? (this.spec.clauses.find((b) => b.id === this.clauseCtx.clauseId)?.kind ?? 'gather')
170
+ : undefined,
171
+ clauseChain: this.clauseCtx?.chain,
172
+ position: this.spec.nodes.length,
173
+ // Only when stated: a document written before the mark existed
174
+ // hashes exactly as it did, and a node nobody marked carries no key.
175
+ ...(() => {
176
+ const expose = opts?.expose ? exposeOf(key, node.descriptor, opts.expose) : undefined;
177
+ return expose ? { expose } : {};
178
+ })(),
179
+ });
180
+ return this;
181
+ }
182
+ qualify(key) {
183
+ return this.clauseCtx ? `${this.clauseCtx.clauseId}.${this.clauseCtx.chain}.${key}` : key;
184
+ }
185
+ /** Where a clause declared here sits, so clauses nest exactly as nodes do. */
186
+ declareClause(b) {
187
+ if (this.spec.nodes.some((n) => n.key === b.id) || this.spec.clauses.some((c) => c.id === b.id))
188
+ throw new Error(`clause id '${b.id}' is already a node key or clause id — nodes and clauses share one address space`);
189
+ const clause = {
190
+ ...b,
191
+ clauseId: this.clauseCtx?.clauseId,
192
+ clauseChain: this.clauseCtx?.chain,
193
+ position: this.spec.nodes.length,
194
+ };
195
+ this.spec.clauses.push(clause);
196
+ return clause;
197
+ }
198
+ /**
199
+ * A **gather** clause: several chains collected and awaited together (01 §4).
200
+ * `mode` is a setting — by the equivalence law (C8) parallel and sequential
201
+ * are unobservable, which is why the construct is named for what it does
202
+ * (gather) and not for how (was `.async()`).
203
+ */
204
+ gather(id, opts, fn) {
205
+ const qualified = this.qualify(id);
206
+ this.declareClause({
207
+ id: qualified,
208
+ kind: 'gather',
209
+ mode: opts.mode ?? 'parallel',
210
+ chains: [],
211
+ });
212
+ fn(new GatherBuilder(this.spec, qualified));
213
+ return this;
214
+ }
215
+ /** An **each** clause: one contained chain, once per item of a list (01 §4). Was `.map()`. */
216
+ each(id, opts, fn) {
217
+ const qualified = this.qualify(id);
218
+ this.declareClause({
219
+ id: qualified,
220
+ kind: 'each',
221
+ mode: opts.mode ?? 'parallel',
222
+ over: typeof opts.over === 'function' ? this.resolve(opts.over) : opts.over,
223
+ max: opts.max,
224
+ chains: ['item'],
225
+ });
226
+ fn(new ChainBuilder(this.spec, { clauseId: qualified, chain: 'item' }));
227
+ return this;
228
+ }
229
+ /**
230
+ * One contained chain, repeated while a declared port stays truthy — bounded by a
231
+ * mandatory `max` (01 §4a).
232
+ *
233
+ * This is the construct that makes tool-calling expressible on the spine. It is **not
234
+ * a back-edge**: like `each`, the repetition lives in the clause's declaration rather
235
+ * than in an edge that points backwards, and the executor already knew how to run a
236
+ * chain more than once. A loop is an each whose iteration count comes from a predicate
237
+ * instead of a list length.
238
+ *
239
+ * Always sequential — each iteration depends on the last, so `mode` would be a lie.
240
+ */
241
+ loop(id, opts, fn) {
242
+ const qualified = this.qualify(id);
243
+ const clause = this.declareClause({
244
+ id: qualified,
245
+ kind: 'loop',
246
+ mode: 'sequential',
247
+ max: opts.max,
248
+ chains: ['item'],
249
+ });
250
+ fn(new ChainBuilder(this.spec, { clauseId: qualified, chain: 'item' }));
251
+ // Resolved *after* the body, so the predicate may name a node inside it — which
252
+ // is the only place a predicate that ever changes can come from.
253
+ clause.repeatWhile =
254
+ typeof opts.repeatWhile === 'function'
255
+ ? new ChainBuilder(this.spec, {
256
+ clauseId: qualified,
257
+ chain: 'item',
258
+ }).resolvePublic(opts.repeatWhile)
259
+ : opts.repeatWhile;
260
+ return this;
261
+ }
262
+ /** Internal: the callback resolver, reachable from `loop` after the body is built. */
263
+ resolvePublic(arg) {
264
+ return this.resolve(arg);
265
+ }
266
+ /**
267
+ * A **junction** clause (was `.route()`): branches selected by declared
268
+ * predicates over a value on the spine (20 §10). Any subset fires — one,
269
+ * several, or none — plus an optional `otherwise` that fires exactly when
270
+ * nothing else did. The decision is *data a task computed* (the value the
271
+ * junction is `on`); the branching is declaration; the receipt records
272
+ * every predicate's evaluation, fired and skipped alike. Not a back-edge
273
+ * and not code in the executor — the loop clause's whole argument, applied
274
+ * to fan-out. 01 §4 amended: branching exists as a declared junction; no
275
+ * back-edges.
276
+ *
277
+ * Skipped branches publish `halt('not selected')` results marked
278
+ * `fired: false`; the union's `ok`/`values` read the *fired* branches, so
279
+ * downstream folds see what ran, in declaration order (13 §1).
280
+ */
281
+ junction(id, opts, fn) {
282
+ const qualified = this.qualify(id);
283
+ const clause = this.declareClause({
284
+ id: qualified,
285
+ kind: 'junction',
286
+ mode: opts.mode ?? 'parallel',
287
+ on: typeof opts.on === 'function' ? this.resolve(opts.on) : opts.on,
288
+ branches: {},
289
+ chains: [],
290
+ });
291
+ fn(new JunctionBuilder(this.spec, qualified, clause));
292
+ return this;
293
+ }
294
+ query(key, node, opts) {
295
+ return this.add('query', key, node, opts);
296
+ }
297
+ task(key, node, opts) {
298
+ return this.add('task', key, node, opts);
299
+ }
300
+ oracle(key, node, opts) {
301
+ return this.add('oracle', key, node, opts);
302
+ }
303
+ outlet(key, node, opts) {
304
+ return this.add('outlet', key, node, opts);
305
+ }
306
+ }
307
+ class GatherBuilder {
308
+ spec;
309
+ clauseId;
310
+ constructor(spec, clauseId) {
311
+ this.spec = spec;
312
+ this.clauseId = clauseId;
313
+ }
314
+ /**
315
+ * Each chain's nodes accumulate into the clause's type, so by the time `.gather()`
316
+ * returns, the spine's scope contains every node the clause declared — under the
317
+ * qualified key it actually has.
318
+ */
319
+ chain(name, fn) {
320
+ const clause = this.spec.clauses.find((b) => b.id === this.clauseId);
321
+ clause.chains.push(name);
322
+ fn(new ChainBuilder(this.spec, {
323
+ clauseId: this.clauseId,
324
+ chain: name,
325
+ }));
326
+ return this;
327
+ }
328
+ }
329
+ /**
330
+ * The junction clause's own builder: every branch is a named chain *with a
331
+ * declared predicate*, and the two are stated together so a branch without a
332
+ * condition cannot be written at all.
333
+ * @experimental
334
+ */
335
+ export class JunctionBuilder {
336
+ spec;
337
+ clauseId;
338
+ clause;
339
+ constructor(spec, clauseId, clause) {
340
+ this.spec = spec;
341
+ this.clauseId = clauseId;
342
+ this.clause = clause;
343
+ }
344
+ /** A branch that fires when its predicate matches the junction's value. */
345
+ when(name, predicate, fn) {
346
+ this.clause.chains.push(name);
347
+ this.clause.branches[name] = { ...predicate };
348
+ fn(new ChainBuilder(this.spec, {
349
+ clauseId: this.clauseId,
350
+ chain: name,
351
+ }));
352
+ return this;
353
+ }
354
+ /** The branch that fires exactly when nothing else did. At most one. */
355
+ otherwise(name, fn) {
356
+ this.clause.chains.push(name);
357
+ this.clause.branches[name] = { default: true };
358
+ fn(new ChainBuilder(this.spec, {
359
+ clauseId: this.clauseId,
360
+ chain: name,
361
+ }));
362
+ return this;
363
+ }
364
+ }
365
+ /**
366
+ * Slot-named methods, for the same reason the chain has kind-named ones (04 §4a): the
367
+ * method names the slot, so setting a slot a node never declared is caught by name rather
368
+ * than becoming an override row that silently matches nothing.
369
+ * @experimental
370
+ */
371
+ export class PresetBuilder {
372
+ preset;
373
+ constructor(preset) {
374
+ this.preset = preset;
375
+ }
376
+ set(nodeKey, slot, value) {
377
+ this.preset.values.push({ nodeKey, slot, value });
378
+ return this;
379
+ }
380
+ /** Node behaviour knobs — retrieval `weight`, `minInclude`, `topK` (12 §2). */
381
+ params(nodeKey, value) {
382
+ return this.set(nodeKey, 'params', value);
383
+ }
384
+ /** Authored text fields the node declares. */
385
+ prompts(nodeKey, value) {
386
+ return this.set(nodeKey, 'prompts', value);
387
+ }
388
+ /** A template **and its engine** — the engine travels on the value (src/engines.ts). */
389
+ template(nodeKey, value) {
390
+ return this.set(nodeKey, 'template', value);
391
+ }
392
+ /** Generation parameters: a reference to a named config, or field overrides on top. */
393
+ sampling(nodeKey, value) {
394
+ return this.set(nodeKey, 'sampling', value);
395
+ }
396
+ /** Node toggles and the review position. */
397
+ settings(nodeKey, value) {
398
+ return this.set(nodeKey, 'settings', value);
399
+ }
400
+ }
401
+ /** @experimental */
402
+ export class SpecBuilder extends ChainBuilder {
403
+ inletDone = false;
404
+ constructor(rawId, meta) {
405
+ assertSpecId(rawId);
406
+ const parsed = parseSpecId(rawId);
407
+ /**
408
+ * The stored id is the **slug**, versionless (`identity.ts`): a trailing
409
+ * `@N` is type-pin syntax `parseSpecId` tolerates, and until 2026-09-16
410
+ * it was kept verbatim here — so `demo:roll@1` contributed actions whose
411
+ * identity read `demo:roll@1#roll`, which the host's identity grammar
412
+ * (`<spec slug>#<key>`, no `@`) refuses. One spelling leaves the builder.
413
+ */
414
+ const id = rawId.replace(/@\d+$/, '');
415
+ const normalized = { ...meta };
416
+ // The genre is stated once, on the inlet lock (R48): the catalogue's
417
+ // `taxonomy.genre` and every contributed action's `genre` are copied
418
+ // from it by `.inlet()`, so they can never disagree with the lock.
419
+ if (normalized.taxonomy) {
420
+ const t = { ...normalized.taxonomy };
421
+ if (t.genre !== undefined)
422
+ throw new Error(`spec '${id}' states taxonomy.genre — drop it: the genre comes from the inlet lock ` +
423
+ `(.inlet(key, node, { genre, event })), and taxonomy is filled from there`);
424
+ normalized.taxonomy = t;
425
+ }
426
+ // The action model (U5c): every action takes its document form, and
427
+ // a malformed declaration — an
428
+ // unknown venue kind, a slash name outside the spec's namespace, a
429
+ // bare-string-less label — is refused here, where the author is.
430
+ if (normalized.contributes) {
431
+ const stated = (normalized.contributes.actions ?? []).find((a) => a.genre !== undefined);
432
+ if (stated)
433
+ throw new Error(`spec '${id}' action '${stated.key ?? '?'}' states a genre — drop it: ` +
434
+ `an action is offered to the genre of the spec's inlet lock`);
435
+ // Normalised actions carry no genre yet; the cast is the authoring type.
436
+ normalized.contributes = normalizeContributes(normalized.contributes);
437
+ const actions = normalized.contributes?.actions ?? [];
438
+ // Validated with the genre still pending — `.inlet()` supplies it,
439
+ // and `build()` refuses an action that never got one.
440
+ // Slash names collide per genre, so that check waits for the lock too.
441
+ const faults = actions.flatMap((a) => actionFindings({ ...a, genre: PENDING_GENRE }, id));
442
+ if (faults.length)
443
+ throw new Error(`spec '${id}' declares an action core cannot offer:\n · ${faults.join('\n · ')}`);
444
+ }
445
+ super({
446
+ id,
447
+ meta: { ...normalized, owner: normalized.owner ?? parsed.owner },
448
+ nodes: [],
449
+ clauses: [],
450
+ includes: [],
451
+ presets: [],
452
+ });
453
+ }
454
+ // The four node methods are re-declared here purely so the spine keeps offering
455
+ // .gather(), .each(), .include() and .build(). Same implementation, narrower return.
456
+ query(key, node, opts) {
457
+ return this.add('query', key, node, opts);
458
+ }
459
+ task(key, node, opts) {
460
+ return this.add('task', key, node, opts);
461
+ }
462
+ oracle(key, node, opts) {
463
+ return this.add('oracle', key, node, opts);
464
+ }
465
+ outlet(key, node, opts) {
466
+ return this.add('outlet', key, node, opts);
467
+ }
468
+ /**
469
+ * A named configuration the spec ships with (12 §3a). Declared **after** the nodes,
470
+ * so the node keys it addresses are the ones that exist — same accumulation the
471
+ * scope uses, so a typo is a compile error rather than a dead override row.
472
+ *
473
+ * ```ts
474
+ * .preset('lore-heavy', { label: 'Lore-heavy' }, p => p
475
+ * .params ('lore', { weight: 0.5, minInclude: 3 })
476
+ * .prompts ('generate', { system: LORE_SYSTEM })
477
+ * .template('prompt', jinja(LORE_ASSEMBLY)))
478
+ * ```
479
+ */
480
+ preset(slug, meta, fn) {
481
+ if (!SLUG.test(slug)) {
482
+ throw new Error(`'${slug}' is not a valid preset slug. Use lowercase letters, digits and hyphens ` +
483
+ `(e.g. 'lore-heavy'). The slug is a stable database reference an update matches on, ` +
484
+ `not display text — put the pretty name in \`label\` (12 §3a).`);
485
+ }
486
+ // The display text (R-20): the label a picker lists the preset by, and
487
+ // the line under it — refused here, where the author is; `validate()`
488
+ // gives a stored document the same sentence.
489
+ const display = [
490
+ ...i18nFindings(meta.label, `presets[${slug}].label`, { required: true }),
491
+ ...i18nFindings(meta.description, `presets[${slug}].description`),
492
+ ];
493
+ if (display.length)
494
+ throw new Error(`preset '${slug}' declares display text a publish refuses (R-20):\n · ${display.join('\n · ')}`);
495
+ if (this.spec.presets.some((p) => p.slug === slug)) {
496
+ throw new Error(`duplicate preset slug '${slug}' — slugs are unique per spec, because they are the sync key (12 §3a)`);
497
+ }
498
+ if (meta.default && this.spec.presets.some((p) => p.default)) {
499
+ throw new Error(`'${slug}' is a second default preset. A spec ships at most one default; ` +
500
+ `an admin chooses among the rest (12 §3a)`);
501
+ }
502
+ const built = {
503
+ slug,
504
+ ...meta,
505
+ owner: meta.owner ?? this.spec.meta.owner,
506
+ values: [],
507
+ };
508
+ fn(new PresetBuilder(built));
509
+ this.spec.presets.push(built);
510
+ return this;
511
+ }
512
+ /**
513
+ * Exactly one **inlet**, positionally first (01 §2). Enforced here rather than
514
+ * by the validator, so it is a throw at authoring time.
515
+ *
516
+ * The optional third argument is the **usage lock** (24 §4): the session
517
+ * event this inlet answers and the genre it serves. A session-event spec
518
+ * without it does not compile — required for now, and relaxing later
519
+ * (`genre: string[]`, `"*"`) is additive, never breaking. **The lock is the
520
+ * only subscription** (R-4, 09-B B5): `.on()` and `subscribes` were deleted
521
+ * 2026-09-16 — nothing read them at dispatch.
522
+ */
523
+ inlet(key, node, binding) {
524
+ // An event is named by value where a package declared it: its id.
525
+ if (binding) {
526
+ const idOf = (e) => (isSessionEventDecl(e) ? e.id : e);
527
+ binding =
528
+ 'events' in binding
529
+ ? { ...binding, events: binding.events?.map(idOf) }
530
+ : { ...binding, event: idOf(binding.event) };
531
+ }
532
+ if (this.inletDone)
533
+ throw new Error('a spec has exactly one inlet (01 §2) — .inlet() may be called once');
534
+ if (this.spec.nodes.length > 0)
535
+ throw new Error('the inlet must be the first node (01 §2)');
536
+ if (binding) {
537
+ // The lock over several events (PLAN-turn-order §4.1): `events`
538
+ // is the alternative to one `event`, never a second copy of it —
539
+ // a spec says which of the two it is, and a list that is empty or
540
+ // repeats itself is an authoring mistake, refused here.
541
+ // Normalised to ids above.
542
+ const many = 'events' in binding ? binding.events : undefined;
543
+ const one = 'event' in binding ? binding.event : undefined;
544
+ if (many !== undefined) {
545
+ if (!Array.isArray(many) || many.length === 0)
546
+ throw new Error('an inlet binding over several events lists them — { genre, events: [ … ] } (PLAN-turn-order §4.1)');
547
+ if (many.some((e) => typeof e !== 'string' || !e))
548
+ throw new Error('an inlet binding lists event ids — every entry of `events` is a string');
549
+ if (new Set(many).size !== many.length)
550
+ throw new Error(`an inlet binding lists each event once — { genre, events: [${many.map((e) => `'${e}'`).join(', ')}] } repeats one`);
551
+ }
552
+ else if (!one)
553
+ throw new Error('an inlet binding names its event — { genre, event } (24 §4)');
554
+ // An undeclared event would compile, publish and never fire.
555
+ // Refused here, where the author is.
556
+ for (const e of many ?? [one]) {
557
+ if (!eventById(e))
558
+ throw new Error(notADeclaredEvent(e));
559
+ if (e === sessionEvents.turnOrderChanged)
560
+ throw new Error(TURN_ORDER_CHANGED_IS_INTERNAL);
561
+ }
562
+ // A package's event arrives in the recorded-event envelope, so a
563
+ // lock on one — even alone — needs an inlet that reads it.
564
+ if (many === undefined && one && packageEventById(one)) {
565
+ const d = node?.descriptor;
566
+ const [first] = eventsLockFindings(d, [one]);
567
+ if (first)
568
+ throw new Error(first);
569
+ }
570
+ // An `events` lock is read through one inlet (R33): every listed
571
+ // event's payload must be one the inlet declares it reads, or the
572
+ // spec would run on a payload its ports were never shaped for.
573
+ if (many !== undefined) {
574
+ const d = node?.descriptor;
575
+ const [first] = eventsLockFindings(d, many);
576
+ if (first)
577
+ throw new Error(first);
578
+ }
579
+ if (typeof binding.genre === 'string')
580
+ throw new Error(`the inlet lock names its genre as the string '${binding.genre}' — pass the genre value ` +
581
+ `(import it), or use('${binding.genre}') for one you cannot import`);
582
+ if (!binding.genre)
583
+ throw new Error(`a spec answering '${one ?? many.join(', ')}' must declare the genre it serves — ` +
584
+ `{ genre, event } (24 §4). Required for now; multi-genre opens later ` +
585
+ `without breaking this declaration.`);
586
+ const genre = genreIdOf(binding.genre);
587
+ this.spec.input =
588
+ many !== undefined ? { genre, events: [...many] } : { genre, event: one };
589
+ // The genre's other two homes, filled from the lock (R48).
590
+ const actions = this.spec.meta.contributes?.actions;
591
+ if (actions?.length) {
592
+ const collisions = slashCollisions(actions.map((a) => ({ ...a, genre, specId: this.spec.id })));
593
+ if (collisions.length)
594
+ throw new Error(`spec '${this.spec.id}' declares an action core cannot offer:\n · ${collisions.join('\n · ')}`);
595
+ }
596
+ // Taxonomy only where the author declared one: a spec that never
597
+ // claimed a catalogue place does not grow one (its hash is its own).
598
+ this.spec.meta = {
599
+ ...this.spec.meta,
600
+ ...(this.spec.meta.taxonomy ? { taxonomy: { ...this.spec.meta.taxonomy, genre: genre } } : {}),
601
+ ...(this.spec.meta.contributes?.actions
602
+ ? {
603
+ contributes: {
604
+ ...this.spec.meta.contributes,
605
+ actions: this.spec.meta.contributes.actions.map((a) => ({ ...a, genre: genre })),
606
+ },
607
+ }
608
+ : {}),
609
+ };
610
+ }
611
+ this.inletDone = true;
612
+ return this.add('inlet', key, node);
613
+ }
614
+ // Clauses are inherited from ChainBuilder so they nest; re-declared here only so the
615
+ // spine keeps offering .include() and .build() afterwards.
616
+ gather(id, opts, fn) {
617
+ return super.gather(id, opts, fn);
618
+ }
619
+ each(id, opts, fn) {
620
+ return super.each(id, opts, fn);
621
+ }
622
+ loop(id, opts, fn) {
623
+ return super.loop(id, opts, fn);
624
+ }
625
+ junction(id, opts, fn) {
626
+ return super.junction(id, opts, fn);
627
+ }
628
+ /** Compile-time include — expanded here, so rows hold the flat chain (16 §3a). */
629
+ include(key, fragment) {
630
+ this.spec.includes.push({ key, fragmentId: fragment.id });
631
+ for (const n of fragment.nodes) {
632
+ this.spec.nodes.push({
633
+ ...n,
634
+ key: `${key}.${n.key}`,
635
+ clauseId: n.clauseId ? `${key}.${n.clauseId}` : undefined,
636
+ position: this.spec.nodes.length,
637
+ });
638
+ }
639
+ for (const b of fragment.clauses) {
640
+ this.spec.clauses.push({
641
+ ...b,
642
+ id: `${key}.${b.id}`,
643
+ clauseId: b.clauseId ? `${key}.${b.clauseId}` : undefined,
644
+ position: this.spec.nodes.length,
645
+ });
646
+ }
647
+ return this;
648
+ }
649
+ build() {
650
+ const orphan = this.spec.meta.contributes?.actions?.find((a) => !a.genre);
651
+ if (orphan)
652
+ throw new Error(`spec '${this.spec.id}' contributes action '${orphan.key}' but has no inlet lock — ` +
653
+ `an action is offered to the genre of the lock: .inlet(key, node, { genre, event })`);
654
+ return this.spec;
655
+ }
656
+ }
657
+ /** Stands in for an action's genre until `.inlet()` supplies the lock's. */
658
+ const PENDING_GENRE = 'pending:genre/lock';
659
+ /** @public */
660
+ export function spec(id, meta) {
661
+ return new SpecBuilder(id, meta);
662
+ }
663
+ /** @experimental */
664
+ export function fragment(id, fn) {
665
+ const inner = {
666
+ id,
667
+ meta: { version: '0.0.0' },
668
+ nodes: [],
669
+ clauses: [],
670
+ includes: [],
671
+ presets: [],
672
+ };
673
+ fn(new ChainBuilder(inner));
674
+ return { id, nodes: inner.nodes, clauses: inner.clauses };
675
+ }
676
+ export { ChainBuilder };
677
+ //# sourceMappingURL=builder.js.map