@serene-pub/contracts 0.6.0-pr-1 → 0.6.0-pr-4

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.
package/dist/tasks.js ADDED
@@ -0,0 +1,4011 @@
1
+ /**
2
+ * Core's **task** node definitions — pure transforms.
3
+ *
4
+ * One file per node kind, with the helpers only that kind uses; `index.ts`
5
+ * re-exports them all.
6
+ */
7
+ import { S, tf, IoKinds } from '@serene-pub/sdk';
8
+ import { handlebars, liquid } from '@serene-pub/sdk';
9
+ import { describeTaskDefinition, pin } from '@serene-pub/sdk';
10
+ import { PROMPT_BLOCKS_DECL } from '@serene-pub/sdk';
11
+ // ── Tasks ───────────────────────────────────────────────────────────────────
12
+ /** @public */
13
+ export const contextBudget = pin(describeTaskDefinition({
14
+ id: 'core:task/context-budget@1',
15
+ timeoutMs: 500,
16
+ slots: {
17
+ /**
18
+ * Where the window comes from.
19
+ *
20
+ * The context window belongs to the sampling config, never to a knob
21
+ * on a node (17 §1a) — and the executor resolves a `sampling` slot to
22
+ * the config's switched-on *values*, so this stays a pure Task reading
23
+ * data it was handed rather than a Query looking one up.
24
+ *
25
+ * ⚠ Point this at the same config the generating step uses. A budget
26
+ * computed against one window and a prompt sent against another is
27
+ * wrong in the direction that truncates, silently.
28
+ */
29
+ sampling: { kind: 'sampling', quick: true },
30
+ /**
31
+ * The connection the reply is sent on — for the model's own
32
+ * context window (0114), which caps the sampling config's when
33
+ * the model states one.
34
+ *
35
+ * Shared with the generating step in every shipped spec
36
+ * (`slot.connectionOf('generate')`), on the same terms as
37
+ * `sampling` above: the budget has to be sized to the window the
38
+ * request is actually sent against, and the ONE computation of
39
+ * that window (R-8) reads both halves off the same resolved pair.
40
+ */
41
+ connection: { kind: 'connection' },
42
+ params: {
43
+ kind: 'parameters',
44
+ schema: {
45
+ /**
46
+ * ⚠ There is no `reserveForReply` here, and there was: an
47
+ * integer defaulting to 512, sitting beside the sampling
48
+ * config's own `responseTokens` that also defaults to 512. The same mistake as the ranker's `budget: 4096` —
49
+ * re-entering a number the system already knows, free to
50
+ * drift from the model actually being called and warning
51
+ * nobody when it did. Context in, response out: the reserve
52
+ * *is* the response allowance, so it is read, not typed.
53
+ */
54
+ safetyMargin: {
55
+ type: 'number',
56
+ default: 0.05,
57
+ description: 'Fraction of the window kept free as a buffer against token-count drift.',
58
+ },
59
+ },
60
+ },
61
+ },
62
+ ports: { out: { main: S.budget, available: S.budget } },
63
+ }));
64
+ /**
65
+ * Fuse two mechanisms that answered the same question into one ordering.
66
+ *
67
+ * Reciprocal-rank fusion, and it is only fusion when the inputs *overlap* —
68
+ * the keyword mechanism and the vector mechanism ranking the same pool, so an entry both
69
+ * found outranks one either found alone. Handed several **disjoint** lists it
70
+ * degrades into concatenation with a fabricated score: every item is unique, so
71
+ * its fused score collapses to its position in its own list, and the
72
+ * `presetScore` stamped on the way out then overrides every signal weight
73
+ * downstream. That is what `core:task/concat-candidates@1` is for, and the
74
+ * binding says so on the receipt when it sees it.
75
+ *
76
+ * ⚠ This declared `strategy` (auto/vector/keyword/hybrid) and `dedup`, and the
77
+ * binding read neither. `strategy` was the 0.5 engine choice, which pipelines
78
+ * replaced with wiring — the mechanisms a run uses are the nodes it has — and `dedup`
79
+ * described what rank fusion does unconditionally, since fusion is keyed by
80
+ * `source:id`. Two controls that rendered, validated and stored a value nothing
81
+ * would ever read; removed rather than wired, because there is no behaviour
82
+ * behind either one to turn on.
83
+ * @public
84
+ */
85
+ export const mergeCandidates = pin(describeTaskDefinition({
86
+ id: 'core:task/merge-candidates@1',
87
+ timeoutMs: 500,
88
+ ports: {
89
+ in: { sources: S.candidates },
90
+ out: {
91
+ // Both open with the band-intent elements the sources carried
92
+ // (lifted out before the fusion, put back after — a fused rank
93
+ // is never stamped on one); readers call `splitCandidates()`.
94
+ main: S.candidates,
95
+ candidates: S.candidates,
96
+ /** What fused with what — and a complaint when nothing did. */
97
+ diagnostics: S.json,
98
+ },
99
+ },
100
+ }));
101
+ /**
102
+ * Put several candidate lists end to end, in the order they were wired.
103
+ *
104
+ * The counterpart to `core:task/merge-candidates@1`, and the distinction is not
105
+ * cosmetic: **concatenation is not fusion**. Lore lanes are disjoint by
106
+ * construction — a world-lore entry is never also a history entry — so there is
107
+ * no agreement between them to measure and nothing to fuse. Passing them
108
+ * through the merge stamped a reciprocal-rank `presetScore` on every candidate,
109
+ * which `select` prefers over the weighted signal sum, so each entry was ranked
110
+ * by its position in its own list and every signal weight was inert.
111
+ *
112
+ * This node deliberately stamps **no score at all**. Ranking is the ranker's
113
+ * job: `core:task/rank-hybrid@1` scores each candidate from its signals against
114
+ * its source's weights, and budgets across sources with the share bands — which
115
+ * is what the bands are for. Order within a source is preserved so a producer's
116
+ * own ordering survives to the tie-break.
117
+ *
118
+ * Repeats are dropped, first occurrence winning, keyed `source:id` the way
119
+ * every other candidate set in the ranker is: the same entry arriving from two
120
+ * lanes should occupy one slot, and the earlier lane is the one the author
121
+ * wired first.
122
+ * @public
123
+ */
124
+ export const concatCandidates = pin(describeTaskDefinition({
125
+ id: 'core:task/concat-candidates@1',
126
+ i18n: { name: { en: 'Combine candidates' } },
127
+ timeoutMs: 500,
128
+ ports: {
129
+ in: { sources: S.candidates },
130
+ out: {
131
+ // Both open with band-intent elements — the first per band
132
+ // across every source, hoisted ahead of the items; readers
133
+ // call `splitCandidates()`.
134
+ main: S.candidates,
135
+ candidates: S.candidates,
136
+ /** How many arrived per list, and how many repeats were dropped. */
137
+ diagnostics: S.json,
138
+ },
139
+ },
140
+ }));
141
+ /**
142
+ * **Eligibility** — the hard gates between the mechanisms and the ranker
143
+ * (C2; owner rulings R2 and R4, 2026-09-30; built 2026-10-02).
144
+ *
145
+ * Scoring and eligibility are separate on purpose: a hard rule must not compete
146
+ * numerically with a soft one and lose. This node scores nothing. It takes the
147
+ * concatenated pool and returns **the same array**, with `ineligible: { reason }`
148
+ * set on each candidate a rule rules out; it never deletes one, so the ranker
149
+ * turns each into an `excluded_ineligible` decision carrying the sentence, and
150
+ * the receipt says why rather than "it scored badly".
151
+ *
152
+ * Its rules, and nothing else:
153
+ *
154
+ * 1. **Exclusions.** A candidate one of the wired `exclusions` lists names
155
+ * (`{ source, id, reason }` — the keyword lanes publish the entries an
156
+ * author's own selective logic ruled out). The same entry brought in again
157
+ * by meaning or by name is the entry the author said *not here*.
158
+ * 2. **Secrecy.** A `relationships` candidate that is somebody's secret
159
+ * (`payload.secretOf`, the holder's participant reference) is ineligible for
160
+ * any other `speaker`. Unwired or null, the producers' own scope decided.
161
+ * 3. **Presence** (R4). A candidate about a cast member (`payload.lorebookBindingId`)
162
+ * whose member has presences on the line and none holding at `at` — the
163
+ * member is not in the world then. A member with no presences is always
164
+ * present.
165
+ *
166
+ * Wired between the final concatenation and `rank-hybrid`. A custom source
167
+ * passes through it like a core one: any candidate with a payload saying who it
168
+ * is about is gated the same way.
169
+ * @experimental
170
+ */
171
+ export const eligibility = pin(describeTaskDefinition({
172
+ id: 'core:task/eligibility@1',
173
+ i18n: { name: { en: 'Check eligibility' } },
174
+ timeoutMs: 500,
175
+ ports: {
176
+ in: {
177
+ candidates: S.candidates,
178
+ /**
179
+ * `{ source, id, reason }` verdicts — one list, or several as a
180
+ * nested literal (`[$.a.exclusions, $.b.exclusions]`), the
181
+ * construction `concat-candidates`' `sources` uses.
182
+ */
183
+ exclusions: S.json,
184
+ /** Whose turn this pool is for. Null or unwired: no secrecy rule. */
185
+ speaker: S.participantRef,
186
+ /** `core:query/cast-presences@1`'s rows. */
187
+ presences: S.json,
188
+ /** The moment they are judged at — `cast-presences`' `at`. */
189
+ at: S.json,
190
+ },
191
+ out: {
192
+ // The same array, band intents first as they came; readers call
193
+ // `splitCandidates()`.
194
+ main: S.candidates,
195
+ candidates: S.candidates,
196
+ /** How many each rule ruled out. */
197
+ diagnostics: S.json,
198
+ },
199
+ },
200
+ }));
201
+ const rankPorts = {
202
+ in: { candidates: S.candidates, budget: S.budget },
203
+ out: {
204
+ main: S.candidates,
205
+ candidates: S.candidates,
206
+ /**
207
+ * The per-candidate trail: score, included, reason, and the signal
208
+ * breakdown behind it.
209
+ *
210
+ * A declared out-port rather than an implementation detail, because it is
211
+ * what Assemble allocates from — and because a ranker swapped in by a
212
+ * plugin has to produce it too, or the budget panel goes blank the moment
213
+ * anyone changes rankers (16 §5c).
214
+ *
215
+ * Shape `S.decisions` (R64): a node publishing it is recorded in the
216
+ * ranking store automatically — a plugin's ranker included.
217
+ */
218
+ decisions: S.decisions,
219
+ },
220
+ };
221
+ /**
222
+ * The five core bands a context is built from — the members of the ranker's
223
+ * **signal** matrix, which is cross-source and stays here.
224
+ *
225
+ * ⚠ No longer the members of `share` / `maxEntries` / `minEntries`: those are
226
+ * per-source and live on the sources (R-7 P5, `bandIntentFields`), so a plugin
227
+ * adding a sixth band declares its own intent on its own definition and never
228
+ * touches this list. Its candidates score by `presetScore` or by the ranker's
229
+ * lore signal set — a per-band signal row for a plugin band is a follow-up,
230
+ * not something this list can grant. `weights.ts` calls this `RetrievalBand`,
231
+ * and the two must agree — the binding maps straight onto it.
232
+ */
233
+ const SOURCES = [
234
+ {
235
+ key: 'messages',
236
+ label: { en: 'Conversation' },
237
+ description: { en: 'The chat itself — what was actually said.' },
238
+ tone: 0,
239
+ },
240
+ {
241
+ key: 'worldLore',
242
+ label: { en: 'World lore' },
243
+ description: { en: 'Lorebook entries about the world.' },
244
+ tone: 1,
245
+ },
246
+ {
247
+ key: 'characterLore',
248
+ label: { en: 'Character lore' },
249
+ description: { en: 'Lorebook entries bound to a character.' },
250
+ tone: 2,
251
+ },
252
+ {
253
+ key: 'history',
254
+ label: { en: 'History entries' },
255
+ description: { en: 'Dated entries recording earlier events.' },
256
+ tone: 3,
257
+ },
258
+ {
259
+ key: 'relationships',
260
+ label: { en: 'Relationships' },
261
+ description: { en: 'The narrative graph. Off by default.' },
262
+ tone: 4,
263
+ },
264
+ ];
265
+ /**
266
+ * How the shares the sources declared are turned into token budgets — the one
267
+ * thing about shares that is genuinely the ranker's (16 §5a: Assemble "keeps
268
+ * only what is genuinely global: total budget, truncation policy, and how
269
+ * weights normalize").
270
+ *
271
+ * `relative` is what ships and is arithmetically what has always run: every
272
+ * band with a share above zero gets `pool × share / Σ shares`, so only the
273
+ * ratios matter and a source added or removed re-divides the whole window.
274
+ * `fixed` reads each share as the fraction of the window it says — a source
275
+ * declaring 0.25 gets a quarter whether one other source exists or six — and
276
+ * scales them all down together only when they add up to more than one. In
277
+ * both, whatever a band cannot spend is swept to the others in score order.
278
+ *
279
+ * ⚠ **The per-source maps this file used to declare here are gone** (R-7 P5,
280
+ * 2026-09-16). `share`, `maxEntries` and `minEntries` — five-band maps keyed
281
+ * `{messages, worldLore, characterLore, history, relationships}` — were the
282
+ * per-source table 16 §5a rejected, kept on the ranker rather than on
283
+ * Assemble. Each source declares its own now (`bandIntentFields`) and the
284
+ * ranker reads them off the candidates it is handed (`BandIntent` in the SDK);
285
+ * migration 0135 moved every stored value to the node that owns it. What is
286
+ * left on this node is cross-source only: this, the mechanism and signal
287
+ * weights, and the allocation precedence.
288
+ */
289
+ const SHARE_NORMALISATION = {
290
+ type: 'enum',
291
+ of: ['relative', 'fixed'],
292
+ members: [
293
+ {
294
+ key: 'relative',
295
+ label: { en: 'Relative' },
296
+ description: {
297
+ en: "Each source's share is a ratio against the others, so together they always fill the whole window.",
298
+ },
299
+ },
300
+ {
301
+ key: 'fixed',
302
+ label: { en: 'Fixed' },
303
+ description: {
304
+ en: 'Each share is the fraction of the window it states, scaled down only when they add up to more than the whole.',
305
+ },
306
+ },
307
+ ],
308
+ default: 'relative',
309
+ label: { en: 'How shares divide the window' },
310
+ description: {
311
+ en: "Whether each source's share is a ratio against the others or the fraction of the window it states.",
312
+ },
313
+ };
314
+ /**
315
+ * The signal weights, transposed for declaration.
316
+ *
317
+ * `weights.ts` holds these as `Record<RetrievalBand, SignalWeights>` — one
318
+ * complete set per source, because scoring reads them that way. The slot
319
+ * system's unit is the *field*, rendered as one per-source control row, so the
320
+ * declaration is the transpose: one `perMember` field per signal, over the same
321
+ * five sources every other ranking control uses. The binding transposes back.
322
+ *
323
+ * ⚠ **The set is not free-standing** — `runtime/signalWiring.test.ts` holds it
324
+ * identical to `keyof SignalWeights` and to what the wired mechanisms actually
325
+ * write, in both directions. Adding a field here without a producer fails, and
326
+ * so does producing a signal without declaring it.
327
+ *
328
+ * Every default reproduces `DEFAULT_SIGNAL_WEIGHTS` exactly — which is what
329
+ * makes declaring them behaviour-preserving. A zero is "does not apply today",
330
+ * not "cannot apply": the scorer has no per-source branches, so turning
331
+ * `nameMatch` on for messages is moving a slider, not asking for a feature.
332
+ *
333
+ * On `rank-hybrid` alone, like its `scripts` hook and for the same reason
334
+ * (S3): the `rank-recall` example ranks without signals, and widening a
335
+ * sibling's declared surface is a hash change on a type nobody meant to touch.
336
+ */
337
+ const SIGNAL_WEIGHT_FIELDS = {
338
+ signalKeyword: {
339
+ type: 'perMember',
340
+ members: SOURCES,
341
+ default: {
342
+ messages: 0,
343
+ worldLore: 0.35,
344
+ characterLore: 0.35,
345
+ history: 0.35,
346
+ relationships: 0,
347
+ },
348
+ label: { en: 'Keyword match' },
349
+ description: {
350
+ en: "How much an entry's own trigger keywords appearing in recent messages counts toward its score.",
351
+ },
352
+ },
353
+ signalNameMatch: {
354
+ type: 'perMember',
355
+ members: SOURCES,
356
+ default: {
357
+ messages: 0,
358
+ worldLore: 0.25,
359
+ characterLore: 0.25,
360
+ history: 0,
361
+ relationships: 0,
362
+ },
363
+ label: { en: 'Name mentioned' },
364
+ description: {
365
+ en: "How much a cast member's name appearing in the entry counts when that character is in the scene.",
366
+ },
367
+ },
368
+ /**
369
+ * Two questions under one name, split by source — bug 16, and it stays split.
370
+ *
371
+ * World lore and history ask *how much of what the scene is naming does this
372
+ * entry name too*; character lore asks *did this entry's own character speak
373
+ * in the guaranteed window*. A character-lore entry names its own character
374
+ * by construction, so the first question scores every present character's
375
+ * private lore alike and distinguishes nothing.
376
+ *
377
+ * ⚠ **The world-lore half is graded now, and this weight moved with it**
378
+ * (design §13.10, retrieval plan phase 3). It used to be a binary substring
379
+ * test — does the entry's title or keys contain a cast name, `Al` firing on
380
+ * `Alchemy` — worth exactly `{0, 0.2}`. It is now the rarity-weighted,
381
+ * word-boundary, two-sided overlap the admission gate already used: what the
382
+ * conversation named, intersected with what this entry names, weighted so
383
+ * that a thing every entry mentions counts for nothing.
384
+ *
385
+ * That measure **saturates**: about 0.63 for one rare shared entity and 0.86
386
+ * for two, so at the old 0.2 its live range would have been ~[0.13, 0.17] —
387
+ * *narrower* than the crude signal it replaces. Grading without re-weighting
388
+ * makes a signal more correct and less influential at the same time, so the
389
+ * weight is sized for the measure that is actually running: 0.35, the same
390
+ * anchor `entity-search`'s own strength uses, which keeps one strongly
391
+ * shared name worth a little less than an entry whose every key fired.
392
+ *
393
+ * Character lore keeps **0.2**. Its measurement did not change, so its
394
+ * weight must not either.
395
+ */
396
+ signalEntityCooccurrence: {
397
+ type: 'perMember',
398
+ members: SOURCES,
399
+ default: { messages: 0, worldLore: 0.35, characterLore: 0.2, history: 0, relationships: 0 },
400
+ label: { en: 'Shared entities' },
401
+ description: {
402
+ en: 'How much an entry naming the same people and places as the recent conversation counts. For character lore it asks something else: whether that character has been speaking.',
403
+ },
404
+ },
405
+ /**
406
+ * How much *being about the same thing* counts, as an embedding measures it.
407
+ *
408
+ * The fourth mechanism and the only one that needs a model. It arrives on
409
+ * candidates the semantic mechanism found — `core:query/vector-search@1`, wired
410
+ * into the reply pipeline as a sibling of the lore lanes — and it is a
411
+ * **score component**, not a rival ordering: an entry both the keyword scan
412
+ * and the semantic mechanism found keeps its keyword signals and gains this one,
413
+ * so agreement between two independent mechanisms compounds by addition and
414
+ * there is no fusion step to reconcile two incomparable scales.
415
+ *
416
+ * ⚠ **Not zero, and that is deliberate.** The mechanism has one switch, one
417
+ * level up: `query-windows.searchByMeaning`, on the first node of its chain
418
+ * since 2026-09-29. It ships *Automatic* — on whenever an embedding model is
419
+ * set up, local or a service alike, and off when there is none — so nothing
420
+ * carries this signal on an install with no embedding model or with the
421
+ * switch Off. Making the weight zero as well would mean
422
+ * turning the switch on changed nothing, which is the trap a two-switch
423
+ * feature always sets. One switch, and it is the one named after what it
424
+ * does.
425
+ *
426
+ * Sized below a keyword hit on purpose. A cosine above the mechanism's own
427
+ * threshold is real evidence and weaker evidence than an authored key
428
+ * firing: keys still guarantee, meaning still only adds.
429
+ */
430
+ signalSemantic: {
431
+ type: 'perMember',
432
+ members: SOURCES,
433
+ default: {
434
+ messages: 0,
435
+ worldLore: 0.3,
436
+ characterLore: 0.3,
437
+ history: 0.3,
438
+ relationships: 0,
439
+ },
440
+ label: { en: 'Similar meaning' },
441
+ description: {
442
+ en: 'How much it counts that an entry is about what the conversation is about, even with no shared words. Needs an embedding model and the semantic arm switched on.',
443
+ },
444
+ },
445
+ /**
446
+ * How much *being called that* counts, as an embedding measures it.
447
+ *
448
+ * The fifth mechanism, and the one that catches the reference nothing else
449
+ * can. It arrives on candidates `core:query/entity-link@1` matched a
450
+ * **description** in the conversation to one of an entry's **names** —
451
+ * *"the captain"* → Captain Vell, *"the order"* → The Ashguard Riders.
452
+ * Neither reference shares a character with its target, so keywords,
453
+ * trigrams and the gazetteer all miss them.
454
+ *
455
+ * ⚠ **Sized to sit strictly below `signalNameMatch`, and that is a rule.**
456
+ * Invented proper nouns are where embeddings are least reliable — "Vell"
457
+ * has no learned meaning, so its vector comes from subword fragments and
458
+ * Vell, Vall and Vela cluster — so exact and trigram matching own invented
459
+ * names, entity vectors own descriptive references, and a vector link must
460
+ * never outrank an entry whose title literally occurred. A similarity
461
+ * cannot exceed 1, so 0.2 against `signalNameMatch`'s 0.25 keeps that true
462
+ * at every value the mechanism can produce.
463
+ *
464
+ * Not zero, for `signalSemantic`'s reason one field up: the mechanism's switch is
465
+ * `mention-spans.maxMentions` and it is 0, so nothing carries this signal
466
+ * until somebody raises it. One switch, not two.
467
+ */
468
+ signalEntityVector: {
469
+ type: 'perMember',
470
+ members: SOURCES,
471
+ default: {
472
+ messages: 0,
473
+ worldLore: 0.2,
474
+ characterLore: 0.2,
475
+ history: 0.2,
476
+ relationships: 0,
477
+ },
478
+ label: { en: 'Called by a description' },
479
+ description: {
480
+ en: 'How much it counts that the conversation described something — "the captain", "the order" — that matches what an entry is called. Needs an embedding model and the description arm switched on. Deliberately weaker than an entry whose name was actually said.',
481
+ },
482
+ },
483
+ signalTfidf: {
484
+ type: 'perMember',
485
+ members: SOURCES,
486
+ default: {
487
+ messages: 0.1,
488
+ worldLore: 0.1,
489
+ characterLore: 0.1,
490
+ history: 0.1,
491
+ relationships: 0,
492
+ },
493
+ label: { en: 'Distinctive words' },
494
+ description: {
495
+ en: 'How much rare, distinctive vocabulary shared with the conversation counts — common words prove little.',
496
+ },
497
+ },
498
+ signalLastRefRecency: {
499
+ type: 'perMember',
500
+ members: SOURCES,
501
+ default: {
502
+ messages: 0,
503
+ worldLore: 0.1,
504
+ characterLore: 0.1,
505
+ history: 0.1,
506
+ relationships: 0,
507
+ },
508
+ label: { en: 'Recently referenced' },
509
+ description: {
510
+ en: 'How much an entry the conversation touched a moment ago outranks one it has not mentioned in a while.',
511
+ },
512
+ },
513
+ /**
514
+ * ⚠ **`signalRecency` and `signalSceneAffinity` were declared here and are
515
+ * gone (migration 0099).** Neither had a producer — anywhere, ever. No
516
+ * mechanism wrote `signals.recency` and none wrote `signals.sceneAffinity`,
517
+ * so both weights multiplied a permanent zero: two controls that rendered,
518
+ * validated, saved, resolved through the whole scope chain, and could not
519
+ * move a single prompt at any value on any install.
520
+ *
521
+ * They are removed rather than wired because each needs a *design decision*
522
+ * this change is not entitled to make, and both are the kind that is
523
+ * cheaper to get right later than to guess at now:
524
+ *
525
+ * · **Recency** carried `history: 0.2`, on a band that really is
526
+ * populated, so building a producer for it would reorder every install's
527
+ * history entries — and the number it would rank on is genuinely
528
+ * ambiguous. A dated entry has an *in-world* date and an *authored*
529
+ * order, they disagree constantly (a flashback is old and new at once),
530
+ * and picking one silently is a worse answer than picking neither.
531
+ * · **Scene affinity** has no fact to read. `scenes` and
532
+ * `lorebook_bindings.scene_id` exist in the schema, but nothing in
533
+ * retrieval knows which scene a session is *in*, so the producer is a
534
+ * feature and not a wiring job.
535
+ *
536
+ * Both are welcome back the day something produces them — as a new field
537
+ * beside its producer, which is the order that keeps this from happening a
538
+ * third time. `runtime/signalWiring.test.ts` is what enforces that: a signal
539
+ * declared here and producible by nothing fails, and so does the reverse.
540
+ *
541
+ * `signalDensity` survives the same audit for the opposite reason — it now
542
+ * has one. `densitySignal` had existed in `ranking/signals.ts` with no
543
+ * caller for as long as this weight had existed with no producer; the scan
544
+ * writes it on every candidate now, exactly as it writes `proximity`.
545
+ */
546
+ signalDensity: {
547
+ type: 'perMember',
548
+ members: SOURCES,
549
+ /**
550
+ * ⚠ **Unmoved, and the lore bands' 0 is what makes wiring it safe.**
551
+ *
552
+ * `signalProximity`'s case exactly: the number falls out of the key walk
553
+ * that was already happening, so the only thing this weight decides is
554
+ * whether it counts — and turning it on reorders lore in an upgraded
555
+ * install that never asked. Every lore band therefore stays at 0 and the
556
+ * scan simply starts *reporting* the number, where a reader can see its
557
+ * value before deciding to weight it.
558
+ *
559
+ * `messages: 0.1` is left exactly as it was rather than tidied to 0.
560
+ * That band is not populated on the shipped path (the entity
561
+ * mechanism's `messages` out-port is deliberately unwired) and nothing
562
+ * writes `density` on a message candidate even when it is, so the number
563
+ * is inert either way — and moving a default that cannot change an
564
+ * outcome is a re-tune with no reason attached.
565
+ */
566
+ default: { messages: 0.1, worldLore: 0, characterLore: 0, history: 0, relationships: 0 },
567
+ label: { en: 'Length against the pool' },
568
+ description: {
569
+ en: 'How much a longer-than-average entry outranks a short one. Length is a proxy for how much an entry has to say; raise it when your book mixes one-line stubs with real articles.',
570
+ },
571
+ },
572
+ /**
573
+ * How tightly an entry's matched keys clustered in the window.
574
+ *
575
+ * Two keys matching adjacent is stronger evidence than the same two
576
+ * matching twenty words apart: "the Ashguard rode" is about the Ashguard
577
+ * riding, and the same two words either side of a paragraph break are two
578
+ * unrelated sentences. `signalKeyword` cannot tell those apart — it counts
579
+ * *how many* of an entry's keys matched and never *where* — so this is the
580
+ * distinction that signal is missing rather than a second reading of it.
581
+ *
582
+ * ⚠ **0 everywhere, which is the one default it can have.** The number is
583
+ * computed on every scan (it falls out of the key walk that was already
584
+ * happening), so the only thing this weight decides is whether it counts —
585
+ * and turning it on reorders lore in an upgraded install that never asked.
586
+ * Same convention as `admitThreshold` and `scoreLedAllocation`.
587
+ */
588
+ signalProximity: {
589
+ type: 'perMember',
590
+ members: SOURCES,
591
+ default: { messages: 0, worldLore: 0, characterLore: 0, history: 0, relationships: 0 },
592
+ label: { en: 'Keywords close together' },
593
+ description: {
594
+ en: "How much it counts that an entry's keywords appeared near each other rather than scattered across the window.",
595
+ },
596
+ },
597
+ signalPriorityBonus: {
598
+ type: 'perMember',
599
+ members: SOURCES,
600
+ default: {
601
+ messages: 0,
602
+ worldLore: 0.15,
603
+ characterLore: 0.15,
604
+ history: 0,
605
+ relationships: 0,
606
+ },
607
+ label: { en: 'Author priority' },
608
+ description: {
609
+ en: "Score added per step of an entry's own priority setting — the author's thumb on the scale.",
610
+ },
611
+ },
612
+ };
613
+ /**
614
+ * How much each way of *finding* an entry counts (retrieval plan §1, phase 3).
615
+ *
616
+ * The signal weights above are the right data at the wrong altitude.
617
+ * Nobody thinks in "tf-idf", and a reader who wants less guessing and more
618
+ * literal matching has to know which of them to move and in which
619
+ * direction. These three sit over them and group them by the **mechanism** that
620
+ * produced the evidence:
621
+ *
622
+ * | Bar | Scales | Asks |
623
+ * |---|---|---|
624
+ * | Keyword | `signalKeyword`, `signalTfidf`, `signalProximity` | "these words appeared" |
625
+ * | Semantic | `signalSemantic` | "this is about that" |
626
+ * | Name | `signalNameMatch`, `signalEntityCooccurrence`, `signalEntityVector` | "this is called that" |
627
+ *
628
+ * The three that are left — last-referred, density and the author's priority
629
+ * bonus — are **structural**, not mechanisms. They answer
630
+ * *"does this matter now"* rather than *"did we find it"*, and scaling them by a
631
+ * retrieval mechanism would be a category error: an entry does not stop being
632
+ * long, or stop having come up a moment ago, because a reader turned keyword
633
+ * matching down.
634
+ *
635
+ * ⚠ **This is not the source split, and the two are on screen together.** The
636
+ * `share` bar above divides the *budget* between world lore, character lore and
637
+ * conversation — turning one up takes tokens from the others. These decide how
638
+ * much each retrieval *method* contributes to one entry's score — turning one up
639
+ * takes nothing from anything, and every bar may be 1 at once. Different axes,
640
+ * different questions, which is why they are different control types rather than
641
+ * one type with a flag (`FieldType.strengths` in the SDK carries that argument).
642
+ *
643
+ * **1 is neutral, not maximum**, and all three ship at 1: multiplying by one is
644
+ * arithmetically what already happens, so an upgraded install scores exactly what
645
+ * it scored before. 0 switches a whole mechanism off, which is the readable way
646
+ * to say "keys only" or "stop guessing" — and is a thing to want.
647
+ *
648
+ * On `rank-hybrid` alone, like the signal matrix and `scoreLedAllocation` and for
649
+ * the same reason (S3): the `rank-recall` example does not score with signals,
650
+ * and widening a sibling's declared surface is a hash change on a type nobody
651
+ * meant to touch.
652
+ */
653
+ const MECHANISM_WEIGHTS = {
654
+ type: 'strengths',
655
+ min: 0,
656
+ max: 1,
657
+ quick: true,
658
+ members: [
659
+ {
660
+ key: 'keyword',
661
+ label: { en: 'Keywords' },
662
+ description: {
663
+ en: "The author's own trigger words, how distinctive the shared vocabulary is, and how closely the matches clustered.",
664
+ },
665
+ tone: 1,
666
+ },
667
+ {
668
+ key: 'semantic',
669
+ label: { en: 'Meaning' },
670
+ description: {
671
+ en: 'Similarity of meaning, with no shared words required. Needs an embedding model and the semantic arm switched on.',
672
+ },
673
+ tone: 3,
674
+ },
675
+ {
676
+ key: 'name',
677
+ label: { en: 'Names' },
678
+ description: {
679
+ en: 'An entry called by its own name, and entries naming the same people and places as the scene.',
680
+ },
681
+ tone: 2,
682
+ },
683
+ ],
684
+ default: { keyword: 1, semantic: 1, name: 1 },
685
+ label: { en: 'How entries are found' },
686
+ description: {
687
+ en: 'How much each way of finding an entry counts toward its score. Turning one up takes nothing from the others — this is not the context split.',
688
+ },
689
+ };
690
+ /**
691
+ * Which allocation precedence the selection runs under (design §7).
692
+ *
693
+ * Off is what ships, and off is the shipped engine exactly: the shares split
694
+ * the window into fixed bands and each source fills its own. A turn that needs
695
+ * no history still reserves history's band, and one relevant world-lore entry
696
+ * larger than a sixth of the window cannot be kept however it scored — which is
697
+ * the thing design §7 calls backwards.
698
+ *
699
+ * On, the precedence inverts to *score allocates, minimums guarantee, shares
700
+ * cap*: the minimums are met first exactly as before, then one pool is spent
701
+ * strictly best-first across every source with each band a ceiling on what one
702
+ * source may take out of it, and the sweep still hands out whatever no source
703
+ * could use. Everything a user can read a promise about is unchanged either
704
+ * way — pins come first and do not consume the entry cap, a band set to zero
705
+ * leaves that source out, minimums are met before any share is worked out, and
706
+ * ties break on score then authored position.
707
+ *
708
+ * **A declared parameter rather than a call option, and that is the whole
709
+ * reason this exists.** `SelectOptions.scoreLedAllocation` has been built and
710
+ * tested since the inversion was written, and `core:task/rank-hybrid@1` is the
711
+ * only runtime `select()` call there is — so with nowhere for a user to say
712
+ * so, every shipped run took the share-first branch and the option was
713
+ * reachable only from a unit test. This is the somewhere.
714
+ *
715
+ * **False is the shipped default**, the `maxRecursionDepth` / `admitThreshold`
716
+ * convention and for their reason: it changes what reaches the model, so it is
717
+ * a thing somebody turns on rather than a thing that happens to them on
718
+ * upgrade. An upgraded install selects exactly what it selected before, which
719
+ * is what leaves the parity corpus measuring the shipped path.
720
+ *
721
+ * On `rank-hybrid` alone, like the signal matrix and the `scripts` hook and for
722
+ * the same reason (S3): the `rank-recall` example does not run this selection,
723
+ * and widening a sibling's declared surface is a hash change on a type nobody
724
+ * meant to touch.
725
+ */
726
+ const SCORE_LED_ALLOCATION = {
727
+ type: 'boolean',
728
+ default: false,
729
+ label: { en: 'Let the best entries lead' },
730
+ description: {
731
+ en: 'Spend the whole context on whatever scored highest, wherever it came from, and treat each band as a ceiling rather than a reserved slice. Off divides the context into bands first and fills each one separately, which is how it has always worked.',
732
+ },
733
+ };
734
+ /** @experimental */
735
+ export const rankHybrid = pin(describeTaskDefinition({
736
+ id: 'core:task/rank-hybrid@1',
737
+ timeoutMs: 500,
738
+ slots: {
739
+ params: {
740
+ kind: 'parameters',
741
+ facet: 'weights',
742
+ schema: {
743
+ // Cross-source only (R-7 P5). Ahead of the nine, because it
744
+ // is the altitude a reader starts at: the grouped mechanisms
745
+ // first, the individual signals under them for anyone who
746
+ // wants that far in, then how the sources' shares divide
747
+ // the window and in what precedence it is filled.
748
+ mechanismWeights: MECHANISM_WEIGHTS,
749
+ ...SIGNAL_WEIGHT_FIELDS,
750
+ shareNormalisation: SHARE_NORMALISATION,
751
+ scoreLedAllocation: SCORE_LED_ALLOCATION,
752
+ },
753
+ },
754
+ /**
755
+ * The post-retrieval hook (18 §4a): user chains over the candidate
756
+ * pool before ranking sees it. Spread onto this type alone rather
757
+ * than into `rankSlots` — widening a sibling's accepted set is a
758
+ * hash change on a type nobody meant to touch (S3).
759
+ */
760
+ scripts: {
761
+ kind: 'scripts',
762
+ accepts: ['core:script:candidates/filter@1', 'core:script:candidates/rescore@1'],
763
+ port: 'candidates',
764
+ phase: 'before',
765
+ description: 'Scripts that drop or rescore retrieved entries before the ranker orders them. Dropping excludes with a reason; rescoring changes the order.',
766
+ },
767
+ },
768
+ ports: {
769
+ in: {
770
+ ...rankPorts.in,
771
+ /**
772
+ * **Entries the prompt already shows in a slot of their own**
773
+ * (lorebooks plan, the room rule, 2026-10-02) — lorebook entry
774
+ * ids, one or a list (nulls skipped). A lore candidate (world
775
+ * lore, character lore, history) with one of these ids is
776
+ * ruled out before ranking, as `excluded_ineligible` with the
777
+ * reason, so it spends no budget and the prompt never reads it
778
+ * twice. Adventure and the Lair wire the room their place slot
779
+ * (`{{locationEntry}}`) shows — the world's `location`,
780
+ * resolved by `undescribed-name@1`. Unwired, nothing changes.
781
+ *
782
+ * ⚠ Not `core:task/eligibility@1`'s `exclusions`: those are
783
+ * verdicts (a rule that fired, with its sentence); this is a
784
+ * fact about the prompt, and a bare id is all it needs. On
785
+ * `rank-hybrid` alone, like the parameters above: the
786
+ * `rank-recall` example builds no prompt with slots.
787
+ */
788
+ shownElsewhere: S.json,
789
+ },
790
+ out: {
791
+ ...rankPorts.out,
792
+ /**
793
+ * What each band was allotted, what it spent, and how many
794
+ * entries it got there (D-H).
795
+ *
796
+ * ⚠ **Published by the binding since it was written, declared
797
+ * by nobody.** `select()` returns this beside the decisions and
798
+ * the binding has always returned it on this key — but an
799
+ * undeclared out-port is invisible: nothing downstream could
800
+ * learn it existed, `validate.ts` skipped the edge, and
801
+ * `core:task/assemble@2` ran its allocation on empty defaults
802
+ * while the numbers sat one node upstream.
803
+ *
804
+ * Spread onto this type alone rather than into `rankPorts` —
805
+ * the same reason the `scripts` hook above is, one construct up
806
+ * (S3). The `rank-recall` example computes no per-band usage;
807
+ * giving it a port it cannot fill would move a hash to declare
808
+ * a promise it does not keep.
809
+ *
810
+ * `json` rather than a shape of its own. It is
811
+ * `Record<band, {allocated, used, entries}>` and the band
812
+ * vocabulary is the ranker's `SOURCES` list, which a plugin may
813
+ * extend — a shape id pinned here would freeze the very list
814
+ * that is meant to grow.
815
+ */
816
+ groups: S.json,
817
+ },
818
+ },
819
+ }));
820
+ /**
821
+ * The two retrieval query windows, as text.
822
+ *
823
+ * A Task because *how a message is written when it is a query* is a decision —
824
+ * speaker attribution in brackets, emphasis stripped — and a different
825
+ * embedding model might want a different shape. It is also where the two
826
+ * windows are cut, which is the parameter a user with long posts will reach for
827
+ * first.
828
+ *
829
+ * And it carries the **semantic mechanism's one switch**, `searchByMeaning`,
830
+ * because it is the first node of the mechanism's chain (2026-09-29, genre
831
+ * uplift C3) — `auto | on | off`, shipping `auto`, which searches whenever an
832
+ * embedding model is set up, wherever it runs (owner, 2026-09-30).
833
+ * @experimental
834
+ */
835
+ export const queryWindows = pin(describeTaskDefinition({
836
+ id: 'core:task/query-windows@1',
837
+ i18n: { name: { en: 'Retrieval queries' } },
838
+ timeoutMs: 500,
839
+ slots: {
840
+ /**
841
+ * The **embedding** connection — the one the probes would be
842
+ * embedded on, for *whether there is one*. Every shipped spec wires
843
+ * it as this step's own (`slot.connection()`), resolving to the
844
+ * install's active embedding connection: a pipeline never chooses
845
+ * its embedding connection, so there is no pick to make here.
846
+ *
847
+ * Read for one fact, and only under `searchByMeaning: 'auto'`:
848
+ * resolved to a connection, an embedding model is **set up** and
849
+ * `auto` searches; unwired, or resolved to nothing, there is none and
850
+ * `auto` does not. ⚠ Nothing else about the connection is read — not
851
+ * where it runs, not whether it bills: a local model and an embedding
852
+ * service search alike (owner, 2026-09-30). A host that embeds
853
+ * through one fixed connection must hold this slot there (Serene Pub
854
+ * offers no pick and drops a stored one), or this step decides about
855
+ * a connection the embed never uses — INTEGRATING.md, Step 3. A pure
856
+ * Task reading data it was handed, the `context-budget` shape: the
857
+ * connection is resolved before the run.
858
+ *
859
+ * Until 2026-10-05 it was wired by reference to the embed step's
860
+ * slot (`slot.connectionOf('semantic.arm.embed')`); `embed-text`
861
+ * declares no connection now (owner ruling D-c), so the slot states
862
+ * its own kind.
863
+ */
864
+ connection: {
865
+ kind: 'connection',
866
+ shape: S.embeddings,
867
+ requires: [tf({ in: [IoKinds.text], out: [IoKinds.embedding] })],
868
+ },
869
+ params: {
870
+ kind: 'parameters',
871
+ facet: 'weights',
872
+ schema: {
873
+ /**
874
+ * ⚠ **The semantic mechanism's one switch**, on the *first*
875
+ * node of its chain on purpose — the shape
876
+ * `mention-spans.maxMentions` gives the entity-vector
877
+ * mechanism. Off, this cuts no probes: `embed-text` is handed
878
+ * no texts and makes no model call, and `vector-search`
879
+ * returns before its reads.
880
+ *
881
+ * **`auto`, the default, searches whenever an embedding model
882
+ * is set up** — a local model, a runtime you run yourself or a
883
+ * service billed per request, alike — and not when none is (an
884
+ * optional mechanism that is unavailable is skipped). `on`
885
+ * searches with whatever model is set up; `off` never
886
+ * searches. "Set up" is the `connection` slot above resolving
887
+ * to a connection.
888
+ *
889
+ * ⚠ **Where the model runs is not a question it asks.** For
890
+ * one day (2026-09-29) `auto` searched only with a model on
891
+ * this machine and skipped a service, read into a ruling about
892
+ * one expensive call per turn; the owner, 2026-09-30: *"I
893
+ * never said to skip paid services for retrieval, that's what
894
+ * they are there for. Don't do that."*
895
+ *
896
+ * The vocabulary is `embed-text`'s `enabled` — `auto | on |
897
+ * off`, labelled Automatic, On, Off — and the question is
898
+ * not. ⚠ That one says what to do when no model is loaded;
899
+ * this says whether to search at all. `auto` there calls
900
+ * whatever is loaded; `auto` here asks whether one is set up.
901
+ *
902
+ * It was `vector-search.maxEntries = 0`, on the chain's
903
+ * *last* node, until 2026-09-29. By then the probes had
904
+ * been embedded, so every turn with an embedding model
905
+ * ready paid for an embed it threw away — a provider call
906
+ * per turn in API mode. `maxEntries` is a ceiling now, and
907
+ * ships non-zero so that turning this on does something.
908
+ * It was then a boolean defaulting to off for one day
909
+ * (C3), which spent nothing and searched nothing.
910
+ */
911
+ searchByMeaning: {
912
+ type: 'enum',
913
+ of: ['auto', 'on', 'off'],
914
+ members: [
915
+ {
916
+ key: 'auto',
917
+ label: { en: 'Automatic' },
918
+ description: {
919
+ en: 'Searches whenever an embedding model is set up, on this machine or a service, and skips the search when none is.',
920
+ },
921
+ },
922
+ {
923
+ key: 'on',
924
+ label: { en: 'On' },
925
+ description: {
926
+ en: 'Searches on every turn with whatever embedding model is set up.',
927
+ },
928
+ },
929
+ {
930
+ key: 'off',
931
+ label: { en: 'Off' },
932
+ description: {
933
+ en: 'Never searches by meaning, and makes no embedding request for it.',
934
+ },
935
+ },
936
+ ],
937
+ default: 'auto',
938
+ quick: true,
939
+ label: { en: 'Search by meaning' },
940
+ description: 'Find lorebook entries that are about what the conversation is about, even with no keyword in common. Needs an embedding model, and embeds the latest messages on every turn. Automatic searches whenever one is set up.',
941
+ },
942
+ currentWindow: {
943
+ type: 'integer',
944
+ default: 2,
945
+ description: "How many of the latest messages form the 'current' retrieval query.",
946
+ },
947
+ recentWindow: {
948
+ type: 'integer',
949
+ default: 3,
950
+ description: "How many messages before those form the wider 'recent' retrieval query.",
951
+ },
952
+ },
953
+ },
954
+ },
955
+ ports: {
956
+ in: { messages: S.messages, cast: S.sessionCast },
957
+ out: { main: S.json, current: S.json, recent: S.json },
958
+ },
959
+ }));
960
+ /**
961
+ * The semantic mechanism's ranking, as a Task.
962
+ *
963
+ * Nine stages the legacy engine runs inline: fuse the per-query lists, normalise
964
+ * to the top, boost recency and author priority, cut on an adaptive threshold,
965
+ * diversify with MMR, and cap each source. Every constant behind them is a
966
+ * parameter here — one of them carries a `TODO: make configurable` in the
967
+ * original.
968
+ *
969
+ * A Task rather than part of the vector Query because **it is policy**: which of
970
+ * these stages run, and how hard, is exactly what an installation should be able
971
+ * to replace. The Query retrieves and computes similarity; this decides.
972
+ *
973
+ * `similarity` is a port because MMR needs to compare candidates to each other
974
+ * and a Task cannot ask the host for anything (F11). It is a matrix of cosines,
975
+ * not the embeddings — derived, bounded, and not reversible into the vectors.
976
+ * @experimental
977
+ */
978
+ export const rankSemantic = pin(describeTaskDefinition({
979
+ id: 'core:task/rank-semantic@1',
980
+ i18n: { name: { en: 'Rank semantic results' } },
981
+ timeoutMs: 1000,
982
+ slots: {
983
+ params: {
984
+ kind: 'parameters',
985
+ facet: 'weights',
986
+ schema: {
987
+ /**
988
+ * ⚠ No `currentWindow` / `recentWindow` here, and there
989
+ * were (culled 2026-09-16, R-12). They size the two query
990
+ * windows — how many messages form the 'current' and the
991
+ * 'recent' question — which `core:task/query-windows@1`
992
+ * cuts and declares as its own params. Declared here too,
993
+ * they were rendered twice and read once: the ranker
994
+ * receives windows already cut and consults neither.
995
+ */
996
+ rrfK: {
997
+ type: 'integer',
998
+ default: 60,
999
+ description: 'Rank-fusion constant — higher values flatten the difference between ranks.',
1000
+ },
1001
+ recencyBoost: {
1002
+ type: 'number',
1003
+ default: 0.15,
1004
+ description: 'Extra score given to recent entries.',
1005
+ },
1006
+ recencyDecay: {
1007
+ type: 'number',
1008
+ default: 0.01,
1009
+ description: 'How quickly the recency boost fades per message of age.',
1010
+ },
1011
+ thresholdMin: {
1012
+ type: 'number',
1013
+ default: 0.3,
1014
+ description: 'Minimum similarity a match needs to be considered at all.',
1015
+ },
1016
+ relativeThreshold: {
1017
+ type: 'number',
1018
+ default: 0.7,
1019
+ description: 'Drop matches scoring below this fraction of the best match.',
1020
+ },
1021
+ mmrLambda: {
1022
+ type: 'number',
1023
+ default: 0.7,
1024
+ description: 'Balance between relevance and variety — 1 is pure relevance, 0 maximum variety.',
1025
+ },
1026
+ /**
1027
+ * ⚠ Not the five `SOURCES` the budget split uses. These are
1028
+ * the semantic mechanism's own record kinds — what a stored vector
1029
+ * *is* — and `historyEntry` vs `history` is a real
1030
+ * difference, not a spelling. Mapping one vocabulary onto
1031
+ * the other here would quietly rename keys the ranker
1032
+ * matches literally (`weights.ts DEFAULT_SEMANTIC`).
1033
+ */
1034
+ sourceBudget: {
1035
+ type: 'perMember',
1036
+ members: [
1037
+ {
1038
+ key: 'message',
1039
+ label: { en: 'Messages' },
1040
+ description: { en: 'Chat messages found by meaning.' },
1041
+ tone: 0,
1042
+ },
1043
+ {
1044
+ key: 'worldLore',
1045
+ label: { en: 'World lore' },
1046
+ description: { en: 'Lorebook entries about the world.' },
1047
+ tone: 1,
1048
+ },
1049
+ {
1050
+ key: 'characterLore',
1051
+ label: { en: 'Character lore' },
1052
+ description: { en: 'Lorebook entries bound to a character.' },
1053
+ tone: 2,
1054
+ },
1055
+ {
1056
+ key: 'historyEntry',
1057
+ label: { en: 'History entries' },
1058
+ description: { en: 'Dated entries recording earlier events.' },
1059
+ tone: 3,
1060
+ },
1061
+ {
1062
+ key: 'narrativeRelationship',
1063
+ label: { en: 'Relationships' },
1064
+ description: { en: 'The narrative graph. Off by default.' },
1065
+ tone: 4,
1066
+ },
1067
+ ],
1068
+ default: {
1069
+ message: 12,
1070
+ worldLore: 8,
1071
+ characterLore: 6,
1072
+ historyEntry: 6,
1073
+ narrativeRelationship: 5,
1074
+ },
1075
+ label: { en: 'Most matches per kind' },
1076
+ description: {
1077
+ en: 'A ceiling on how many semantic matches of each kind survive fusion, before the budget ranker sees them.',
1078
+ },
1079
+ },
1080
+ defaultSourceBudget: {
1081
+ type: 'integer',
1082
+ default: 20,
1083
+ description: 'The ceiling for any match kind not named above — what a plugin-added source gets until it declares its own.',
1084
+ },
1085
+ },
1086
+ },
1087
+ },
1088
+ ports: {
1089
+ in: {
1090
+ /**
1091
+ * One entry per query window, each carrying its own per-message
1092
+ * ranked lists and its own similarity matrix. The whole stack
1093
+ * runs per window; the results are concatenated, not fused.
1094
+ */
1095
+ windows: S.json,
1096
+ messages: S.messages,
1097
+ },
1098
+ out: {
1099
+ main: S.candidates,
1100
+ candidates: S.candidates,
1101
+ diagnostics: S.json,
1102
+ },
1103
+ },
1104
+ }));
1105
+ /**
1106
+ * A plugin's ranker — same kind, same shape, so the swap list offers it (16 §5c).
1107
+ *
1108
+ * Named `rankRecall`, not `rankSemantic`: binding names derive from the id's
1109
+ * name segment and ignore the namespace, so this and `core:task/rank-semantic@1`
1110
+ * would both want to be `rankSemantic` and generation would emit one export
1111
+ * twice. `checkUnique` now catches that; the id changed here because a plugin
1112
+ * naming its ranker after its own product is the better name anyway.
1113
+ * @internal
1114
+ */
1115
+ export const rankRecall = pin(describeTaskDefinition({
1116
+ id: 'chariot.recall:rank-recall@1',
1117
+ timeoutMs: 500,
1118
+ ports: rankPorts,
1119
+ }));
1120
+ /**
1121
+ * What Assemble's `render()` puts on a context template itself — see the
1122
+ * template slot below. Laid-out values are strings.
1123
+ */
1124
+ const ASSEMBLE_TEMPLATE_SCOPE = {
1125
+ worldLore: { type: 'string', optional: true, description: 'World lore that fit the budget, laid out.' },
1126
+ characterLore: {
1127
+ type: 'string',
1128
+ optional: true,
1129
+ description: 'Lore bound to a cast member that fit the budget, laid out — only what this speaker may see.',
1130
+ },
1131
+ history: { type: 'string', optional: true, description: 'History entries that fit the budget, laid out.' },
1132
+ currentDate: { type: 'string', optional: true, description: 'The story’s current date, laid out.' },
1133
+ sessionMessages: {
1134
+ type: 'list',
1135
+ description: 'The transcript, oldest first, ending with the seed line.',
1136
+ of: {
1137
+ type: 'object',
1138
+ fields: {
1139
+ id: { type: 'number' },
1140
+ role: { type: 'string' },
1141
+ name: { type: 'string' },
1142
+ message: { type: 'string', optional: true },
1143
+ /**
1144
+ * 🚧 The line's files, placed (PLAN-composer-attachments
1145
+ * §3.5): media markers, inlined text files and placeholders,
1146
+ * from `core:task/place-attachments@1`. Absent on a line
1147
+ * with no files, and on every line of a spec with no
1148
+ * placement step.
1149
+ */
1150
+ attachments: {
1151
+ type: 'string',
1152
+ optional: true,
1153
+ description: "The line's attachments, placed: files the model receives, text files inlined, and names for the rest.",
1154
+ },
1155
+ },
1156
+ },
1157
+ },
1158
+ injectionsByIndex: {
1159
+ type: 'record',
1160
+ description: 'Script injections, keyed by the message index they render at.',
1161
+ of: {
1162
+ type: 'list',
1163
+ of: { type: 'object', fields: { role: { type: 'string' }, content: { type: 'string' } } },
1164
+ },
1165
+ },
1166
+ budget: {
1167
+ type: 'object',
1168
+ description: 'The token budget this prompt was allocated against.',
1169
+ fields: { total: { type: 'number' }, used: { type: 'number' }, remaining: { type: 'number' } },
1170
+ },
1171
+ postHistory: {
1172
+ type: 'object',
1173
+ optional: true,
1174
+ description: 'The post-history block, placed: render it when the loop reaches targetIndex.',
1175
+ fields: {
1176
+ targetIndex: { type: 'number' },
1177
+ instructions: { type: 'string', optional: true },
1178
+ charInstructions: { type: 'string', optional: true },
1179
+ exampleDialogue: { type: 'string', optional: true },
1180
+ hasContent: { type: 'boolean' },
1181
+ },
1182
+ },
1183
+ /**
1184
+ * 🚧 The session's **author's note**, placed (2026-10-02, AN1) — the
1185
+ * person's own steering text for this session, at its own depth, with no
1186
+ * token trigger. Not the post-history reminder: that one is the pipeline's
1187
+ * and the card's "how to respond"; this is the person's "what is true now".
1188
+ * Absent for a genre that declares no `authorsNote` field.
1189
+ */
1190
+ authorsNote: {
1191
+ type: 'object',
1192
+ optional: true,
1193
+ description: 'The session’s author’s note, placed: render it when the loop reaches targetIndex, before the injections and the post-history block.',
1194
+ fields: {
1195
+ targetIndex: { type: 'number' },
1196
+ text: { type: 'string', optional: true },
1197
+ role: { type: 'string' },
1198
+ hasContent: { type: 'boolean' },
1199
+ },
1200
+ },
1201
+ };
1202
+ /** @public */
1203
+ export const assemble = pin(describeTaskDefinition({
1204
+ id: 'core:task/assemble@2',
1205
+ timeoutMs: 1000,
1206
+ slots: {
1207
+ // An *assembly* template: its scope really is the input ports, so this half of
1208
+ // 16 §4's claim holds.
1209
+ template: {
1210
+ kind: 'template',
1211
+ // Handlebars FIRST, then Liquid: the first entry is what a new
1212
+ // template here is written in, and every shipped row holds
1213
+ // Handlebars — so the order is what keeps the parity corpus
1214
+ // byte-identical. Both are accepted because a story string is a
1215
+ // layout, not a dialect: the same arrangement is expressible in
1216
+ // either, and a slot naming one makes the other unselectable
1217
+ // everywhere. Jinja is absent because core renders neither
1218
+ // parity nor helpers for it (12 §2a).
1219
+ acceptedEngines: [handlebars.id, liquid.id],
1220
+ facet: 'templates',
1221
+ /**
1222
+ * Assemble's own names — what `render()` writes onto the context
1223
+ * AFTER spreading the prompts and the builder's context, so these
1224
+ * are the last word (typed templates P3, edited in place — owner
1225
+ * ruling Q4).
1226
+ *
1227
+ * Corrected 2026-09-27: this declared `blocks`, `budget` as two
1228
+ * bare names and `prompts` — `blocks` is a param that reorders the
1229
+ * template and never reaches it, and `prompts` is never a name:
1230
+ * the prompts slot's fields are spread at the top level. The
1231
+ * builder's keys and the prompts fields join these in
1232
+ * `templateScopeAt`; declared bands join them too.
1233
+ */
1234
+ variables: ASSEMBLE_TEMPLATE_SCOPE,
1235
+ description: 'The story string: the overall layout of the finished prompt — where the character cards, lore, history and instructions sit. Leave empty to use the built-in layout.',
1236
+ },
1237
+ prompts: {
1238
+ kind: 'prompts',
1239
+ quick: true,
1240
+ facet: 'prompts',
1241
+ fields: {
1242
+ system: { type: 'text' },
1243
+ postHistory: { type: 'text' },
1244
+ },
1245
+ },
1246
+ /**
1247
+ * How the values Assemble itself produces are laid out.
1248
+ *
1249
+ * These exist here rather than upstream because they come out the
1250
+ * other side of the budget: what a layout receives is what actually
1251
+ * fit, which no earlier node knows. `characterLore` among them — the
1252
+ * admitted lore of cast members, which a context template places
1253
+ * with `{{{characterLore}}}` like any other lore.
1254
+ */
1255
+ variables: {
1256
+ kind: 'variables',
1257
+ facet: 'variables',
1258
+ description: 'How the retrieved lore and history are laid out — JSON, prose, or whatever you write. Duplicate one to change it.',
1259
+ renders: {
1260
+ worldLore: 'core:var/world-lore@1',
1261
+ characterLore: 'core:var/character-lore@1',
1262
+ history: 'core:var/history@1',
1263
+ currentDate: 'core:var/current-date@1',
1264
+ },
1265
+ /**
1266
+ * Open (typed templates P2, edited in place — owner ruling Q4):
1267
+ * every band declared upstream of `candidates` is rendered too,
1268
+ * under its key and through its variable's layout — a plugin's
1269
+ * source adds its band here by declaring it.
1270
+ */
1271
+ rendersBands: { from: 'candidates' },
1272
+ },
1273
+ params: {
1274
+ kind: 'parameters',
1275
+ facet: 'weights',
1276
+ schema: {
1277
+ /**
1278
+ * ⚠ No `budget` here either. It was an integer defaulting to
1279
+ * 4096 — the same re-entered number the ranker carried, with
1280
+ * the same defect: an absolute count on a node cannot know
1281
+ * which model the prompt is about to be sent to, so it was
1282
+ * free to disagree with the window and warn nobody. The
1283
+ * total now arrives on the `budget` in-port from
1284
+ * `core:task/context-budget@1`, which derives it from the
1285
+ * sampling config the reply is generated against.
1286
+ */
1287
+ /**
1288
+ * Where the post-history reminder goes, and whether it goes
1289
+ * at all.
1290
+ *
1291
+ * Numbers, so they are parameters rather than prompt text —
1292
+ * a `prompts` slot carries authored strings and typing a
1293
+ * count as one would be the wrong shape wearing a
1294
+ * convenient home. The trigger is a **suppression**: below
1295
+ * it a short chat gets no reminder, because a reinforcement
1296
+ * note two messages after the system prompt is noise.
1297
+ */
1298
+ postHistoryDepth: {
1299
+ type: 'integer',
1300
+ default: 0,
1301
+ description: 'Place the post-history reminder this many messages before the end. 0 puts it last.',
1302
+ },
1303
+ postHistoryTokenTrigger: {
1304
+ type: 'integer',
1305
+ default: 0,
1306
+ description: 'Only add the reminder once the chat is at least this many tokens long. 0 always adds it.',
1307
+ },
1308
+ /**
1309
+ * ⚠ No `truncation` here, and there was one — an enum of
1310
+ * `oldest-first | lowest-weight`, "what gets dropped first
1311
+ * when the context is over budget" — declared, rendered,
1312
+ * and read by nothing (culled 2026-09-16, R-12). What LORE
1313
+ * fits is decided upstream by the ranker's `select`, per
1314
+ * band, against `share`, `maxEntries`, `minEntries` and
1315
+ * `scoreLedAllocation` on `core:task/rank-hybrid@1`, and
1316
+ * this node renders the decisions it is handed. A second
1317
+ * drop rule for lore here would be a second owner of one
1318
+ * decision. NOMENCLATURE §25 records the cull.
1319
+ *
1320
+ * ⚠ The TRANSCRIPT is the exception, because nobody else
1321
+ * owns it (B2, 2026-10-03): no shipped spec ranks a message
1322
+ * candidate, so the conversation's rows were never fitted
1323
+ * at all and a long session went out larger than the
1324
+ * window. The host's binding measures what it rendered and,
1325
+ * over the budget, leaves out the oldest lines in a chunk
1326
+ * at a cut point it holds across turns — not a param,
1327
+ * because there is nothing to choose: a prompt that does
1328
+ * not fit is trimmed by the backend instead, from the
1329
+ * front, every turn.
1330
+ */
1331
+ /**
1332
+ * Which sections the prompt is built from, and in what order —
1333
+ * SillyTavern's *prompt list*, as a param on the node that
1334
+ * assembles the prompt (ruling 2026-09-10).
1335
+ *
1336
+ * A param and not a session setting, and not a table: it is the
1337
+ * same kind of fact as "which prompt does this step use", so it
1338
+ * belongs in the configuration a preset selects and it is an
1339
+ * administrator's. A preset carries it to every session started
1340
+ * from it for free, because a preset's configuration is already
1341
+ * what a run resolves against.
1342
+ *
1343
+ * ⚠ **The declared default means "leave the template alone".** It
1344
+ * is the shipped template's own order, so a configuration nobody
1345
+ * has touched stores nothing and renders the bytes it always did —
1346
+ * and a template somebody WROTE, whose sections sit in an order
1347
+ * they chose, is not silently reordered into this one. See
1348
+ * `isShippedPromptBlocks`.
1349
+ */
1350
+ blocks: PROMPT_BLOCKS_DECL,
1351
+ },
1352
+ },
1353
+ /**
1354
+ * Which connection this prompt is being written FOR.
1355
+ *
1356
+ * Not compute, and this node calls nothing: the only thing read out
1357
+ * of it is `metadata.promptFormat` — whether the finished prompt is
1358
+ * one instruct-wrapped string or a role-tagged array, and which
1359
+ * wrapper. A wire format is a property of the endpoint, and until
1360
+ * this slot existed there was no way for the node that renders the
1361
+ * prompt to learn it. `renderers.ts` fell back to Vicuna on every
1362
+ * run, so a ChatML or Llama-2 connection was sent Vicuna markers and
1363
+ * nothing anywhere said so.
1364
+ *
1365
+ * ## Wire it to the SENDING node, always
1366
+ *
1367
+ * `slot.connectionOf('generate')`, exactly as `contextBudget` shares
1368
+ * the sampling reference, and for the same reason stated there: a
1369
+ * prompt wrapped for one endpoint and sent to another is wrong
1370
+ * silently. Sharing the reference makes the two impossible to point
1371
+ * apart rather than documenting that they must agree and hoping.
1372
+ *
1373
+ * ## No `requires`
1374
+ *
1375
+ * The sibling connection slots declare one because they are about to
1376
+ * CALL the connection and an unmet capability should refuse at bind.
1377
+ * This one reads a label. Declaring a capability it never exercises
1378
+ * would let an untested connection grey itself out of a picker for a
1379
+ * node that was never going to send it anything.
1380
+ */
1381
+ connection: {
1382
+ kind: 'connection',
1383
+ shape: S.textGen,
1384
+ description: 'Which connection this prompt is formatted for. Point it at the step that sends the reply — a prompt wrapped for one endpoint and sent to another is wrong in a way nothing reports.',
1385
+ },
1386
+ },
1387
+ ports: {
1388
+ in: {
1389
+ candidates: S.candidates,
1390
+ budget: S.budget,
1391
+ templateContext: S.templateContext,
1392
+ /**
1393
+ * The ranker's per-candidate trail — score, verdict, reason.
1394
+ *
1395
+ * ⚠ **Supplied since the node was written, declared only now.**
1396
+ * All three shipped specs wire `decisions: $.rank.decisions`,
1397
+ * and the binding halts without them ("wire a ranker between
1398
+ * retrieval and assembly"), so this is not a new input — it is
1399
+ * the load-bearing one. What was missing was the declaration,
1400
+ * and the cost of that is exact: `validate.ts` skips its shape
1401
+ * check when either side is undeclared (`if (!outShape ||
1402
+ * !inShape) continue`), so a plugin ranker publishing the wrong
1403
+ * shape on this edge got no finding, and a plugin ASSEMBLER had
1404
+ * nothing to read to learn the port existed.
1405
+ *
1406
+ * `S.decisions`, matching `rankPorts.out.decisions` (R64) — a
1407
+ * decision is a candidate with its arithmetic attached, and the
1408
+ * panel reads the same objects the allocator does. Typed, so a
1409
+ * plugin ranker wired here publishes the shape the ranking store
1410
+ * records.
1411
+ */
1412
+ decisions: S.decisions,
1413
+ /**
1414
+ * The finished chat lines, from `core:task/process-messages@1`.
1415
+ *
1416
+ * Wired by all three specs (`messages: $.lines.messages`) and
1417
+ * undeclared for the same stretch as `decisions`. Two readers
1418
+ * depend on it and neither is optional: the transcript the
1419
+ * template renders, and the depth the post-history reminder is
1420
+ * placed at — which is computed against *these* lines because
1421
+ * the context builder ships a placeholder index, the final
1422
+ * array not existing when it runs.
1423
+ */
1424
+ messages: S.messages,
1425
+ /**
1426
+ * Per band: allocated, used, entries — the arithmetic the
1427
+ * ranker did while deciding (D-H).
1428
+ *
1429
+ * ⚠ **The one genuinely new edge in this set.** The two
1430
+ * above were supplied and undeclared; this was PUBLISHED by
1431
+ * `core:task/rank-hybrid@1` and wired by nobody, so `allocate`
1432
+ * fell to its own `{}` and the per-band numbers the ranker had
1433
+ * already computed were dropped on the floor between two
1434
+ * adjacent nodes.
1435
+ *
1436
+ * What it does NOT touch is the prompt: `allocate` puts this
1437
+ * straight onto `AllocatedContext.groups` and reads it nowhere
1438
+ * else, so `blocks`, `totalTokens` and `budget` — everything
1439
+ * the render sees — are byte-identical with it wired or not.
1440
+ * What changes is the receipt: `dispatch.ts` publishes
1441
+ * `payload.groups` as the run's `sources`, which is the budget
1442
+ * panel's whole data set and has been empty on every run.
1443
+ *
1444
+ * Undeclared on purpose for the other rankers. A ranker that
1445
+ * computes no per-band usage leaves this unwired and
1446
+ * `allocate` takes the branch it has always taken.
1447
+ */
1448
+ groups: S.json,
1449
+ /**
1450
+ * The annex a template may read, as `annex.<owner>.<key>`
1451
+ * (typed templates P6, edited in place — owner ruling Q4).
1452
+ *
1453
+ * Fed ONLY by `core:query/session-annex@1` with `view:
1454
+ * 'template'`: every DECLARED key of every owner in scope —
1455
+ * core, the enabled plugins — for the session's genre, keyed by
1456
+ * owner. A key no declaration covers never arrives, and a
1457
+ * declaration refuses secrets at write time (R61), so what
1458
+ * reaches a template is what an owner said may be kept there
1459
+ * (owner ruling Q1: "nothing dangerous should ever be stored
1460
+ * there"). Law T2 refuses anything else wired here, and a
1461
+ * template-view read wired anywhere else.
1462
+ *
1463
+ * Optional: unwired, `annex` is not in the template's scope at
1464
+ * all, so a template naming it is refused rather than rendering
1465
+ * nothing.
1466
+ */
1467
+ annex: S.json,
1468
+ },
1469
+ out: { main: S.assembled, context: S.assembled },
1470
+ },
1471
+ }));
1472
+ /**
1473
+ * The ports both context builders expose. Identical because the two nodes do
1474
+ * the same job — the difference between them is entirely what can be
1475
+ * *configured*, which is what a node type is for.
1476
+ */
1477
+ const contextPorts = {
1478
+ in: {
1479
+ cast: S.sessionCast,
1480
+ /**
1481
+ * Whose voice the reply is, when a next-speaker node decided (19 §5).
1482
+ * Optional: unwired, the speaker still rides the cast bundle (the
1483
+ * scope's value), which is how every spec worked before the node
1484
+ * existed — and how the narrator's context, which has no speaker,
1485
+ * still works. Wired, it wins, so the receipt's speaker and the
1486
+ * prompt's speaker cannot disagree.
1487
+ */
1488
+ currentCharacterId: S.rowIds,
1489
+ },
1490
+ out: {
1491
+ main: S.templateContext,
1492
+ templateContext: S.templateContext,
1493
+ /**
1494
+ * The name on the trailing assistant line.
1495
+ *
1496
+ * Its own port rather than a field inside the context, because
1497
+ * nothing renders `{{seedName}}` — it is not a template variable.
1498
+ * It is what the message processor writes on the line the model
1499
+ * continues from, and in narrator mode it is the one name that
1500
+ * must *not* be the joined cast list: seeding "Alice and Cara:"
1501
+ * teaches the model to write joint dialogue instead of narrating.
1502
+ */
1503
+ seedName: S.text,
1504
+ },
1505
+ };
1506
+ const PROMPTS_DESCRIPTION = 'The written instructions this pipeline sends the model — pick a prompt, or duplicate one and make it yours.';
1507
+ /**
1508
+ * How each value this node produces is *presented*.
1509
+ *
1510
+ * Every one of these was a `JSON.stringify` in TypeScript, indentation and all
1511
+ * — so "render my characters as prose" was a code change rather than a setting.
1512
+ * Each key here points at a swappable template row, selected the way a prompt
1513
+ * is, and keyed by the variable it renders rather than by this spec: a prose
1514
+ * rendering written here is selectable from any pipeline that renders the same
1515
+ * variable.
1516
+ *
1517
+ * The shipped rows reproduce the old TypeScript byte for byte. The JSON shape is
1518
+ * not a default anyone drifted into — it was A/B tested before 0.1.0 and
1519
+ * measurably improved how reliably models hold a character — so prose is opt-in
1520
+ * and stays that way.
1521
+ */
1522
+ const VARIABLES_DESCRIPTION = 'How each part of the prompt is laid out — JSON, prose, or whatever you write. Duplicate one to change it.';
1523
+ /**
1524
+ * What a context builder's `templateContext` carries, in the template type
1525
+ * language (typed templates P3, 2026-09-27) — so a template editor offers
1526
+ * `{{{characters}}}` with a type, and `templateScopeAt` puts these keys in
1527
+ * the scope of whatever template renders the builder's output.
1528
+ *
1529
+ * Written from what the builder RETURNS (the app's `buildTemplateContext`),
1530
+ * not from the legacy `TemplateContext` type, which also lists names only
1531
+ * Assemble supplies (`worldLore`, `history`, `currentDate`). The app holds
1532
+ * the two together at compile time: the builder's returned object
1533
+ * `satisfies VarValue<typeof TEMPLATE_CONTEXT_SCHEMA>`, so a key added on
1534
+ * one side and not the other fails `tsc`.
1535
+ *
1536
+ * Every rendered value is a **string** — each is laid out through its
1537
+ * variable's selected layout before it leaves the builder (a user's
1538
+ * `{{{characters}}}` would otherwise render `[object Object]`). `state` is
1539
+ * the one structure: `templateScopeAt` re-types it from the session genre's
1540
+ * attribute slots. `sessionMessages` and `postHistory` are placeholders
1541
+ * Assemble supersedes with its own.
1542
+ *
1543
+ * **Policy** (`portSchemas`): it describes the payload; no hash moves.
1544
+ * @experimental
1545
+ */
1546
+ export const TEMPLATE_CONTEXT_SCHEMA = {
1547
+ type: 'object',
1548
+ fields: {
1549
+ instructions: { type: 'string', description: 'The system prompt, resolved and laid out.' },
1550
+ characters: { type: 'string', description: 'The cast’s character cards, laid out (JSON by default), trimmed to the session’s character detail.' },
1551
+ personas: { type: 'string', description: 'The personas, laid out (JSON by default).' },
1552
+ scenario: { type: 'string', description: 'The scenario, resolved and laid out.' },
1553
+ characterNames: { type: 'string', description: '“A, B, and C” — every enabled character’s name (none at speaker-only detail).' },
1554
+ personaNames: { type: 'string', description: '“A, B, and C” — every persona’s name.' },
1555
+ exampleDialogue: { type: 'string', description: 'The speaker’s example dialogue.' },
1556
+ postHistoryInstructions: { type: 'string', description: 'The post-history instructions, resolved.' },
1557
+ relationshipsPerspectives: { type: 'string', description: 'How the speaker regards everyone.' },
1558
+ relationshipsKnown: { type: 'string', description: 'How everyone regards the speaker.' },
1559
+ char: { type: 'string', description: 'The speaking character’s name.' },
1560
+ character: { type: 'string', description: 'The speaking character’s name.' },
1561
+ user: { type: 'string', description: 'The persona’s name.' },
1562
+ persona: { type: 'string', description: 'The persona’s name.' },
1563
+ postHistory: {
1564
+ type: 'object',
1565
+ description: 'The post-history block, before Assemble decides where it goes.',
1566
+ fields: {
1567
+ targetIndex: { type: 'number' },
1568
+ instructions: { type: 'string', optional: true },
1569
+ charInstructions: { type: 'string', optional: true },
1570
+ exampleDialogue: { type: 'string', optional: true },
1571
+ hasContent: { type: 'boolean' },
1572
+ gatedBy: { type: 'string', optional: true },
1573
+ },
1574
+ },
1575
+ /**
1576
+ * 🚧 The author's note before Assemble places it — present only when
1577
+ * the session's genre declares `authorsNote` and the spec wires the
1578
+ * genre fields into this node. `targetIndex` is a placeholder, as
1579
+ * `postHistory`'s is.
1580
+ */
1581
+ authorsNote: {
1582
+ type: 'object',
1583
+ optional: true,
1584
+ description: 'The session’s author’s note, before Assemble decides where it goes.',
1585
+ fields: {
1586
+ targetIndex: { type: 'number' },
1587
+ text: { type: 'string', optional: true },
1588
+ role: { type: 'string' },
1589
+ depth: { type: 'number' },
1590
+ interval: { type: 'number' },
1591
+ replyCount: { type: 'number', optional: true },
1592
+ hasContent: { type: 'boolean' },
1593
+ gatedBy: { type: 'string', optional: true },
1594
+ },
1595
+ },
1596
+ sessionMessages: { type: 'list', description: 'Empty here; Assemble supplies the transcript.' },
1597
+ state: {
1598
+ type: 'object',
1599
+ optional: true,
1600
+ description: 'The session’s stats and states — state.world.<slot>, state.cast.<member>.<slot>, state.locations.<place>.<slot>.',
1601
+ fields: { world: { type: 'record' }, cast: { type: 'record' }, locations: { type: 'record', optional: true } },
1602
+ },
1603
+ },
1604
+ };
1605
+ /** Rendered by every context builder, whoever is speaking. */
1606
+ const sharedRenders = {
1607
+ instructions: 'core:var/instructions@1',
1608
+ characters: 'core:var/characters@1',
1609
+ personas: 'core:var/personas@1',
1610
+ scenario: 'core:var/scenario@1',
1611
+ postHistoryInstructions: 'core:var/post-history-instructions@1',
1612
+ characterNames: 'core:var/character-names@1',
1613
+ personaNames: 'core:var/persona-names@1',
1614
+ };
1615
+ /**
1616
+ * The reply pipeline's context builder.
1617
+ *
1618
+ * ## Why the narrator has its own type
1619
+ *
1620
+ * Through 0.6.0 both pipelines pinned this one, and the panel is generated from
1621
+ * the registry row — so each advertised the other's controls. Reply prompts all
1622
+ * carried an empty `narratorName` box, and the narrator offered layout pickers
1623
+ * for `exampleDialogue` (which comes from the speaking character it does not
1624
+ * have) and the two relationship variables (which its spec deliberately never supplies).
1625
+ * Three controls wired to nothing, in both directions.
1626
+ *
1627
+ * A type is the unit that declares a configurable surface — it is how a plugin
1628
+ * declares one, and `RegistryEntry.slots` carries the declaration precisely so
1629
+ * core can render a form without executing the plugin that owns it (12 §2, F6).
1630
+ * Narrowing per-spec instead would have meant the row said one thing and the
1631
+ * running pipeline another, which is the defect widening that column fixed.
1632
+ *
1633
+ * The two share `contextPorts` and `sharedRenders` rather than restating them,
1634
+ * so the halves that must not drift cannot.
1635
+ * @public
1636
+ */
1637
+ export const buildTemplateContext = pin(describeTaskDefinition({
1638
+ id: 'core:task/build-template-context@1',
1639
+ i18n: { name: { en: 'Build template context' } },
1640
+ timeoutMs: 2000,
1641
+ /** What `templateContext` carries — typed templates P3; policy, so no pin moves. */
1642
+ portSchemas: { out: { main: TEMPLATE_CONTEXT_SCHEMA, templateContext: TEMPLATE_CONTEXT_SCHEMA } },
1643
+ /**
1644
+ * The example-dialogue pick. Declaring it is what gets `ctx.random` — the
1645
+ * run-seeded RNG — instead of `Math.random()`, so the same run replayed
1646
+ * chooses the same example and a different turn still gets variety.
1647
+ */
1648
+ declaresRandomness: true,
1649
+ /**
1650
+ * The authored text. It arrives as config rather than on a port because it
1651
+ * *is* config — the same prompt config the assembly template renders from,
1652
+ * layered instance → user → chat like every other slot.
1653
+ */
1654
+ slots: {
1655
+ prompts: {
1656
+ kind: 'prompts',
1657
+ quick: true,
1658
+ facet: 'prompts',
1659
+ description: PROMPTS_DESCRIPTION,
1660
+ fields: {
1661
+ systemPrompt: { type: 'text' },
1662
+ postHistoryInstructions: { type: 'text' },
1663
+ },
1664
+ },
1665
+ variables: {
1666
+ kind: 'variables',
1667
+ facet: 'variables',
1668
+ description: VARIABLES_DESCRIPTION,
1669
+ renders: {
1670
+ ...sharedRenders,
1671
+ /** From the speaking character's card. */
1672
+ exampleDialogue: 'core:var/example-dialogue@1',
1673
+ /**
1674
+ * The narrative graph, as two variables rather than one.
1675
+ *
1676
+ * They were `speakerRelationships` — a single block holding
1677
+ * both what the speaker thinks of everyone and what everyone
1678
+ * thinks of the speaker. Opposite claims under one heading,
1679
+ * which a model reads as one list, and one layout, one
1680
+ * priority and one on/off switch for both.
1681
+ */
1682
+ relationshipsPerspectives: 'core:var/relationships-perspectives@1',
1683
+ relationshipsKnown: 'core:var/relationships-known@1',
1684
+ },
1685
+ },
1686
+ /**
1687
+ * The pre-assemble context hook (18 §4a): user chains over the
1688
+ * finished template context — conditional style guides, seeded
1689
+ * event tables — after this node resolves it and before anything
1690
+ * renders it.
1691
+ *
1692
+ * `messages/inject` lives here too — **not** on the message
1693
+ * processor — because of the ruling of 2026-08-23: injections are
1694
+ * template-context *data* (`context.injections`, resolved to
1695
+ * `injectionsByIndex` beside `postHistory.targetIndex`), rendered
1696
+ * by the template's own message loop. Splicing them into the list
1697
+ * behind the template's back would be the §20 defect again, one
1698
+ * layer down: a position the template cannot express, an author
1699
+ * cannot see, and a corpus cannot check.
1700
+ */
1701
+ scripts: {
1702
+ kind: 'scripts',
1703
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
1704
+ port: 'main',
1705
+ phase: 'after',
1706
+ description: 'Scripts over what the prompt template renders — edit the instructions, roll an occasional event, or inject a reminder at a depth in the conversation.',
1707
+ },
1708
+ },
1709
+ ports: {
1710
+ in: {
1711
+ ...contextPorts.in,
1712
+ /**
1713
+ * The narrative graph, as the two claims it really is — how the
1714
+ * speaker regards everyone, and how everyone regards the
1715
+ * speaker (D-I).
1716
+ *
1717
+ * ⚠ **Supplied by `respond` since the split, declared here
1718
+ * only now.** The spec wires both off
1719
+ * `core:query/relationships-perspectives@1` and
1720
+ * `core:query/relationships-known@1`, the two `renders` above
1721
+ * name the variables they feed, and the builder reads both by
1722
+ * these exact names — so every part of the round trip was
1723
+ * written down except the ports themselves.
1724
+ *
1725
+ * `json`, matching what those queries publish and for the
1726
+ * reason stated at them: the structure travels so a variable
1727
+ * layout can render it, rather than a blob nothing can
1728
+ * restyle.
1729
+ *
1730
+ * ⚠ Declared on THIS type alone rather than in `contextPorts`,
1731
+ * which the narrator builder shares. Its own docblock says the
1732
+ * narrate spec never supplies these because graph context
1733
+ * needs a speaker's perspective and a narrator has none — so
1734
+ * widening the shared map would give it two ports it must
1735
+ * leave empty forever, and move its hash to say so (S3).
1736
+ */
1737
+ relationshipsPerspectives: S.json,
1738
+ relationshipsKnown: S.json,
1739
+ /**
1740
+ * Who is speaking, when the speaker is not in the cast.
1741
+ *
1742
+ * ⚠ **Neither is wired by any spec, and both are supplied on
1743
+ * every side-character turn.** `core:task/build-side-character-
1744
+ * context@1` is not a separate implementation — the host's
1745
+ * binding for it unwraps its `sideCharacter` in-port and calls THIS
1746
+ * type's handler with the name and the card spread onto the
1747
+ * input, because `resolveContextInput` owns the card rules and
1748
+ * a side character's card and a cast member's must compile
1749
+ * through one function.
1750
+ *
1751
+ * So the supplier is the host rather than a document, and that
1752
+ * is exactly why declaring them matters: it is the only record
1753
+ * that this type's input surface is wider than its edges. An
1754
+ * undeclared key reaching a handler is indistinguishable from a
1755
+ * typo until someone reads both files at once.
1756
+ *
1757
+ * `speakerName` is `text` — it is the name on the seed line and
1758
+ * what `{{char}}` renders. `speakerCharacter` is `json`: the
1759
+ * card, or `null` for a free-form name, which is a normal turn
1760
+ * rather than a degraded one.
1761
+ */
1762
+ speakerName: S.text,
1763
+ speakerCharacter: S.json,
1764
+ /**
1765
+ * Who is speaking, as a participant reference (R-18 (3); U5g,
1766
+ * 2026-09-16) — the turn strategy's `speaker`. Read for one
1767
+ * thing: an **envoy** (`envoy:<slug>`) has no character row, so
1768
+ * its card — name and description, off the genre's declaration
1769
+ * the cast read carries — is compiled here where a cast
1770
+ * member's would be, through the same `speakerName` /
1771
+ * `speakerCharacter` seam a side character uses. A `character:`
1772
+ * reference changes nothing: `currentCharacterId` already says
1773
+ * it. Optional; unwired on the specs that seat no envoy.
1774
+ */
1775
+ speaker: S.participantRef,
1776
+ /**
1777
+ * The session's resolved stats and states, as
1778
+ * `core:query/session-state@1` publishes them:
1779
+ * `{ world, cast, locations, slots, who, version }`, already
1780
+ * resolved down the session → lorebook → card → default chain
1781
+ * (a location's: this run's → the entry's → default; 🚧 phase 4).
1782
+ *
1783
+ * A template reads `state.world.weather` and
1784
+ * `state.cast.verity.hp` — the **resolved** value and nothing
1785
+ * below it. Which layer a number came from is a question for
1786
+ * the Cast member page, not for a prompt.
1787
+ *
1788
+ * ⚠ Declared on THIS type alone rather than in `contextPorts`,
1789
+ * following `relationshipsPerspectives` above and for the same
1790
+ * reason: widening the shared map moves the narrator's hash to
1791
+ * declare a port no shipped spec fills. Unwired — which is
1792
+ * every shipped spec today — the key is absent and the context
1793
+ * has no `state`, which is what a chat session should have.
1794
+ */
1795
+ state: S.json,
1796
+ /**
1797
+ * What the person typed with the press, for an action that
1798
+ * reads its composer text as **direction** (lair pass B17,
1799
+ * 2026-09-27): the Lair's Trigger trap and Reveal, and
1800
+ * Whodunit's Search — what the detective is looking for (genre
1801
+ * uplift C2, 2026-09-29). Rendered as
1802
+ * `{{turnDirection}}` — the same name, and the same meaning,
1803
+ * `build-scene-context@1` gives the Lair's reply (B11). Absent
1804
+ * when blank, so a prompt writes `{{#if turnDirection}}…{{/if}}`
1805
+ * and a press with nothing typed leaves it to the prompt.
1806
+ * Declared here rather than in `contextPorts`, like `state`
1807
+ * above; the narrator and side-character builders declare
1808
+ * their own (C2). Unwired on every spec whose composer text is
1809
+ * a line somebody said.
1810
+ */
1811
+ turnDirection: S.text,
1812
+ /**
1813
+ * The places the lorebook holds, for an envoy that talks about
1814
+ * the world from outside it (lair re-plan R6, 2026-09-28): the
1815
+ * Lair's Castellan in the Sanctum. A
1816
+ * `core:query/lorebook-entries@1` listing, rendered exactly as
1817
+ * the planner's and the scene's port of this name is —
1818
+ * `{{knownLocations}}` (their names) and `{{locationEntry}}`
1819
+ * (the room the world's `location` names). Declared on THIS
1820
+ * type alone, like `state`; unwired on every other spec.
1821
+ */
1822
+ locationEntries: S.json,
1823
+ /**
1824
+ * The story's newest rows, for a speaker who talks ABOUT the
1825
+ * story from another channel (lair re-plan R6): the Castellan
1826
+ * in the Sanctum reads `main`'s last few rows. Transcript rows
1827
+ * (a `session-history@1` read), rendered as prose — one
1828
+ * `Name: line` per row, named as the transcript names them, no
1829
+ * JSON blocks — into `{{recentStory}}`, so they are background
1830
+ * in the instructions and never turns the model continues.
1831
+ * Absent when unwired or empty.
1832
+ */
1833
+ recentStory: S.messages,
1834
+ /**
1835
+ * The session's genre fields, by their own names (lair re-plan
1836
+ * R13, 2026-09-28): `{{sanctumSteers}}` for the Castellan in
1837
+ * the Sanctum, whose instructions say whether its talk shapes
1838
+ * the next turn. The planner's and the scene's `fields`, on the
1839
+ * same terms. Declared on THIS type alone, like `state`;
1840
+ * unwired on every other spec.
1841
+ */
1842
+ fields: S.json,
1843
+ /**
1844
+ * The speaker's own running notes (lair re-plan R13, owner
1845
+ * 2026-09-28): the Castellan's **scratchpad**, the Lair's annex
1846
+ * field `castellan-scratchpad`, read for it alone
1847
+ * (`session-annex@1`'s AI view, with its own reference as the
1848
+ * speaker). Rendered as `{{scratchpad}}`; absent when unwired
1849
+ * or blank. Declared on THIS type alone, like `state`.
1850
+ */
1851
+ scratchpad: S.text,
1852
+ },
1853
+ out: contextPorts.out,
1854
+ },
1855
+ }));
1856
+ /**
1857
+ * The narrator pipeline's context builder.
1858
+ *
1859
+ * Same implementation, same ports, different surface — see
1860
+ * `buildTemplateContext` for why that makes it a different type.
1861
+ *
1862
+ * What it drops: `exampleDialogue`, which `characterExampleDialogue` reads off
1863
+ * the speaking character and so is always empty here, and both relationship
1864
+ * variables, which the narrate spec never supplies because graph context needs
1865
+ * a speaker's perspective and a narrator has none.
1866
+ *
1867
+ * What it adds: `narratorName`. Load-bearing rather than cosmetic — it is the
1868
+ * name on the seed line the model continues from, and `{{narratorName}}` in the
1869
+ * narrator's own prompt text.
1870
+ *
1871
+ * No `declaresRandomness`: the only random choice this node ever made was which
1872
+ * example dialogue to use, and it has none to choose from.
1873
+ * @public
1874
+ */
1875
+ export const buildNarratorContext = pin(describeTaskDefinition({
1876
+ id: 'core:task/build-narrator-context@1',
1877
+ i18n: { name: { en: 'Build narrator context' } },
1878
+ timeoutMs: 2000,
1879
+ /** The same builder, the same payload (`TEMPLATE_CONTEXT_SCHEMA`). Policy. */
1880
+ portSchemas: { out: { main: TEMPLATE_CONTEXT_SCHEMA, templateContext: TEMPLATE_CONTEXT_SCHEMA } },
1881
+ slots: {
1882
+ prompts: {
1883
+ kind: 'prompts',
1884
+ quick: true,
1885
+ facet: 'prompts',
1886
+ description: PROMPTS_DESCRIPTION,
1887
+ fields: {
1888
+ systemPrompt: { type: 'text' },
1889
+ postHistoryInstructions: { type: 'text' },
1890
+ narratorName: { type: 'text' },
1891
+ },
1892
+ },
1893
+ variables: {
1894
+ kind: 'variables',
1895
+ facet: 'variables',
1896
+ description: VARIABLES_DESCRIPTION,
1897
+ renders: { ...sharedRenders },
1898
+ },
1899
+ /** The same hook as `build-template-context` — see it for the terms. */
1900
+ scripts: {
1901
+ kind: 'scripts',
1902
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
1903
+ port: 'main',
1904
+ phase: 'after',
1905
+ description: 'Scripts over what the prompt template renders — edit the instructions, roll an occasional event, or inject a reminder at a depth in the conversation.',
1906
+ },
1907
+ },
1908
+ ports: {
1909
+ in: {
1910
+ ...contextPorts.in,
1911
+ /**
1912
+ * What the person asked this narration to do (genre uplift
1913
+ * C2, 2026-09-29): the narrator modal's text or `/narrate
1914
+ * <text>` — the turn's triggering text, `$.input.text`.
1915
+ * Rendered as `{{turnDirection}}`, the name and the meaning
1916
+ * `build-template-context@1` and `build-scene-context@1` give
1917
+ * it (B11); absent when blank, so a row writes
1918
+ * `{{#if turnDirection}}…{{/if}}` and an undirected narration
1919
+ * renders exactly what it did before.
1920
+ *
1921
+ * ⚠ Declared because the placeholder's `instructions` is not
1922
+ * a prompt: it is stored beside the row and shown with it. For
1923
+ * as long as that was the direction's only reader, 0.5.3's
1924
+ * _Additional focus for this response_ reached no model.
1925
+ */
1926
+ turnDirection: S.text,
1927
+ },
1928
+ out: contextPorts.out,
1929
+ },
1930
+ }));
1931
+ /**
1932
+ * The side-character pipeline's context builder (ruling 2026-09-07).
1933
+ *
1934
+ * Same implementation and the same ports as the other two, plus one in-port —
1935
+ * `sideCharacter` — and that port is the whole reason it is a third type rather
1936
+ * than a flag.
1937
+ *
1938
+ * ## Why the name is a port and not a prompt field
1939
+ *
1940
+ * `build-narrator-context@1` takes `narratorName` in its **prompts** slot,
1941
+ * which is correct there: the narrator's name is a setting, chosen once, the
1942
+ * same on every turn. A side character's name is *data from the trigger* — it
1943
+ * differs per turn and a person may type it in the modal — so putting it in a
1944
+ * prompts slot would mean editing a prompt config to speak as somebody else,
1945
+ * and every turn would render with whichever name was stored last.
1946
+ *
1947
+ * ## What it drops, and what it keeps
1948
+ *
1949
+ * Drops `exampleDialogue`, for the narrator's reason: it is read off the
1950
+ * speaking *cast member*, and a side character is not one. Drops both
1951
+ * relationship variables, because graph context is built from a cast member's
1952
+ * node and this speaker has none. Keeps every shared render, so the cards, the
1953
+ * scenario and the two name lists are laid out exactly as they are elsewhere.
1954
+ *
1955
+ * ⚠ It declares **no** `narratorName` prompt field. A side-character prompt
1956
+ * that wrote `{{narratorName}}` would render the narrator's configured name
1957
+ * into a turn the narrator is not speaking — the same "control wired to
1958
+ * nothing, in both directions" the two context builders were split to end.
1959
+ * `{{char}}` is the speaker here, exactly as it is in a reply.
1960
+ *
1961
+ * ⚠ And it does **not** inherit `contextPorts.in.currentCharacterId`, which the
1962
+ * other two carry. Not an oversight: character-lore visibility is decided by
1963
+ * the host read, which keys on the run's SCOPE, so a speaker id arriving here
1964
+ * could change whose voice the prompt is written in without changing whose lore
1965
+ * it was given — a prompt in one person's voice over another's private
1966
+ * knowledge. The port would be a control that half-works, which is the exact
1967
+ * class this whole split exists to remove. `sideCharacter` carries the name and
1968
+ * the card; the id stays where the host can act on it.
1969
+ *
1970
+ * ⚠ **The OUT-port `speaker` is the other half of that sentence** (added
1971
+ * 2026-09-17, W1). The half-working control was a speaker id that changed the
1972
+ * prompt's voice and not the lore; the repair is not an in-port but a lane
1973
+ * inside the same clause reading the answer this node already computed —
1974
+ * `core:query/character-lore@1` takes `speaker`, so the voice and its private
1975
+ * knowledge move together or not at all.
1976
+ * @experimental
1977
+ */
1978
+ export const buildSideCharacterContext = pin(describeTaskDefinition({
1979
+ id: 'core:task/build-side-character-context@1',
1980
+ i18n: { name: { en: 'Build side character context' } },
1981
+ timeoutMs: 2000,
1982
+ slots: {
1983
+ prompts: {
1984
+ kind: 'prompts',
1985
+ quick: true,
1986
+ facet: 'prompts',
1987
+ description: PROMPTS_DESCRIPTION,
1988
+ fields: {
1989
+ systemPrompt: { type: 'text' },
1990
+ postHistoryInstructions: { type: 'text' },
1991
+ },
1992
+ },
1993
+ variables: {
1994
+ kind: 'variables',
1995
+ facet: 'variables',
1996
+ description: VARIABLES_DESCRIPTION,
1997
+ renders: { ...sharedRenders },
1998
+ },
1999
+ /** The same hook as the other two builders — see them for the terms. */
2000
+ scripts: {
2001
+ kind: 'scripts',
2002
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
2003
+ port: 'main',
2004
+ phase: 'after',
2005
+ description: 'Scripts over what the prompt template renders — edit the instructions, roll an occasional event, or inject a reminder at a depth in the conversation.',
2006
+ },
2007
+ },
2008
+ ports: {
2009
+ in: {
2010
+ cast: contextPorts.in.cast,
2011
+ /**
2012
+ * `{ name, characterId, ref, known, character }`, from the
2013
+ * trigger's first step. `name` is what the seed line carries and
2014
+ * what `{{char}}` renders; `character` is the card, absent for a
2015
+ * free-form name, which is a normal turn rather than a degraded
2016
+ * one — the builder falls back to the name it was given,
2017
+ * because a typed name is all there is.
2018
+ *
2019
+ * `characterId` (a row id) or `ref` (a participant reference,
2020
+ * `character:<id>` — what a pressed option carries, plan A28
2021
+ * review) names the speaker BY ROW, and then the row is who
2022
+ * speaks: the name is a label, never a second lookup, so two
2023
+ * people sharing a name stay two people and a row the cast does
2024
+ * not seat is still the person it names. A fact with neither
2025
+ * resolves by name against the cast.
2026
+ *
2027
+ * Was `speaker` until 2026-09-16 — see the inlet's port of
2028
+ * this name for why the fact moved off that word.
2029
+ */
2030
+ sideCharacter: S.json,
2031
+ /**
2032
+ * Where this turn is happening, as the world state says it.
2033
+ *
2034
+ * Declared late, and for a defect rather than for symmetry: a
2035
+ * voice built with no place in front of it answered from
2036
+ * whatever the transcript suggested and moved the scene to a
2037
+ * harbour the plan had never mentioned. Unwired on every
2038
+ * pipeline that had this node before it, so those keep the
2039
+ * context they already had.
2040
+ */
2041
+ state: S.json,
2042
+ /**
2043
+ * The planner's document, for the one fact the state cannot
2044
+ * supply on a first turn: where the scene is, before anything
2045
+ * has written a location down.
2046
+ */
2047
+ plan: S.json,
2048
+ /**
2049
+ * The rooms, listed (`core:query/lorebook-entries@1`), as the
2050
+ * planner and the scene get them (lair pass R8, 2026-09-28):
2051
+ * `{{knownLocations}}` and the one the party stand in as
2052
+ * `{{locationEntry}}`, so a voice can name the room it is in
2053
+ * now that nobody narrates it first. Unwired, neither renders.
2054
+ */
2055
+ locationEntries: S.json,
2056
+ /**
2057
+ * A place described only in prose, as `{{locationPassage}}`
2058
+ * (lair pass R9, 2026-09-28): the paragraph
2059
+ * `core:task/undescribed-name@1` found describing the room the
2060
+ * party are about to walk into (its `passage`), when no entry
2061
+ * describes it — that room's text for this turn. Blank or
2062
+ * unwired, it does not render.
2063
+ */
2064
+ locationPassage: S.text,
2065
+ /**
2066
+ * What the person asked this side character's turn to do
2067
+ * (genre uplift C2, 2026-09-29) — the narrator modal's text,
2068
+ * which feeds both of its halves. `{{turnDirection}}`, on the
2069
+ * terms `build-narrator-context@1` states; wired by
2070
+ * `core:spec/chat-side-character` alone, so a genre's voices
2071
+ * (whose composer text is a line somebody said) render
2072
+ * nothing new.
2073
+ */
2074
+ turnDirection: S.text,
2075
+ },
2076
+ out: {
2077
+ ...contextPorts.out,
2078
+ /**
2079
+ * Who this voice is, as a **participant reference** — the row
2080
+ * the fact named (`characterId` or `ref`), else
2081
+ * `character:<id>` for a name the cast holds, else null for a
2082
+ * free-form one. Additive, 2026-09-17 (W1). A lore read wired
2083
+ * to it takes null as unwired, so the run's scope decides for
2084
+ * a free-form voice.
2085
+ *
2086
+ * The resolution already happened: this node derives the
2087
+ * speaking character from the `sideCharacter` fact so the card,
2088
+ * `{{char}}` and the seed line agree. Publishing it is what lets
2089
+ * a lore lane INSIDE the same `each` be handed the same answer
2090
+ * — `speaker: $.voices.item.context.speaker` on
2091
+ * `core:query/character-lore@1` — rather than a second
2092
+ * name-to-row match somewhere downstream, which is how the
2093
+ * prompt's speaker and the lore's speaker come to disagree.
2094
+ *
2095
+ * ⚠ It is published, never taken: there is still no
2096
+ * `currentCharacterId` IN-port here, for the reason the header
2097
+ * gives. What changed is that the id the node computed is now
2098
+ * readable, not that a spec may set it.
2099
+ */
2100
+ speaker: S.participantRef,
2101
+ },
2102
+ },
2103
+ }));
2104
+ /* ── The adventure genre's agent contexts ───────────────────────────────────
2105
+ *
2106
+ * Three more surfaces onto the ONE context builder, declared for the reason
2107
+ * `buildNarratorContext` states beside `buildTemplateContext`: a different
2108
+ * prompt surface is a different type. The reason is mechanical rather than
2109
+ * tidy-minded. A prompt lives in a pool keyed by (node type, slot), and
2110
+ * `defaultPromptFor` resolves **one row per pool per spec** — two nodes of the
2111
+ * same type in one pipeline must land on the same shipped prompt. A multi-agent
2112
+ * turn whose planner, narrator and state-keeper were all
2113
+ * `build-template-context@1` would therefore ship all three agents the same
2114
+ * instructions, and the person who noticed would have to fix it three times in
2115
+ * a panel rather than once in a package.
2116
+ *
2117
+ * They take `state` because that is the whole premise of the genre they serve:
2118
+ * every agent reads the bars, the world strip and the inventory as facts before
2119
+ * it writes anything. `core:task/build-template-context@1` declares the same
2120
+ * port and stays the type a spec uses when it wants the standard surface.
2121
+ */
2122
+ /**
2123
+ * ⚠ Returns the literal slot keys, not `Record<string, SlotDecl>` — as
2124
+ * `loreSlots` and `relationshipSlots` do. The erased form made
2125
+ * `SlotNamesOf<typeof buildPlannerContext>` `never`, so a handler bound to the
2126
+ * three surfaces could type-check reading NO slot and declare NO slot read,
2127
+ * which is the "declares least, checked least" hole `nodeInput.ts` warns about.
2128
+ * Found when the surfaces gained `reads` declarations (R-12, 2026-09-16).
2129
+ */
2130
+ const agentContextSlots = (promptFields) => ({
2131
+ prompts: {
2132
+ kind: 'prompts',
2133
+ quick: true,
2134
+ facet: 'prompts',
2135
+ description: PROMPTS_DESCRIPTION,
2136
+ fields: promptFields,
2137
+ },
2138
+ variables: {
2139
+ kind: 'variables',
2140
+ facet: 'variables',
2141
+ description: VARIABLES_DESCRIPTION,
2142
+ renders: { ...sharedRenders },
2143
+ },
2144
+ /** The same pre-assemble hook the other three builders carry. */
2145
+ scripts: {
2146
+ kind: 'scripts',
2147
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
2148
+ port: 'main',
2149
+ phase: 'after',
2150
+ description: 'Scripts over what the prompt template renders — edit the instructions, roll an occasional event, or inject a reminder at a depth in the conversation.',
2151
+ },
2152
+ });
2153
+ /**
2154
+ * The planner's context: the cast, the state, and nothing about a speaker.
2155
+ *
2156
+ * A planner decides who speaks; it is not itself anybody, so
2157
+ * `currentCharacterId` is deliberately absent rather than declared and left
2158
+ * empty. What it publishes is what every other builder publishes, so the
2159
+ * planner's prompt is assembled by the same node as everyone else's.
2160
+ * @experimental
2161
+ */
2162
+ export const buildPlannerContext = pin(describeTaskDefinition({
2163
+ id: 'core:task/build-planner-context@1',
2164
+ i18n: { name: { en: 'Build planner context' } },
2165
+ timeoutMs: 2000,
2166
+ slots: agentContextSlots({
2167
+ systemPrompt: { type: 'text' },
2168
+ postHistoryInstructions: { type: 'text' },
2169
+ }),
2170
+ ports: {
2171
+ in: {
2172
+ cast: contextPorts.in.cast,
2173
+ state: S.json,
2174
+ /**
2175
+ * The session's own genre fields, by key — `tone`,
2176
+ * `difficulty` and whatever else the genre declared.
2177
+ *
2178
+ * On the template context under their own names, so an
2179
+ * authored prompt writes `{{tone}}` the way it writes
2180
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2181
+ * declaration promises: declared on the genre, edited in
2182
+ * session settings, stored on the row, published by the input
2183
+ * node, and read here by the agent whose wording depends on
2184
+ * them. Without this port the last step was missing and a
2185
+ * prompt naming `{{tone}}` rendered a blank.
2186
+ */
2187
+ fields: S.json,
2188
+ /**
2189
+ * What the person just sent, when the genre reads it as
2190
+ * **direction** rather than as a line somebody said (lair pass
2191
+ * B11, 2026-09-27) — the Lair's composer. On the template
2192
+ * context and in the prompt as `{{turnDirection}}`; empty or
2193
+ * absent on a turn nobody directed (a Continue), so a prompt
2194
+ * writes `{{#if turnDirection}}…{{/if}}`. A genre whose composer
2195
+ * text is a participant's line leaves it unwired: that line is
2196
+ * already in the transcript. *Turn* direction, never bare
2197
+ * `direction`: that word is the Lair's standing-note state slot
2198
+ * (`core:slot/direction@1`), a different fact (R1, renamed
2199
+ * 2026-09-27).
2200
+ */
2201
+ turnDirection: S.text,
2202
+ /**
2203
+ * The places the lorebook holds — a
2204
+ * `core:query/lorebook-entries@1` listing of location entries
2205
+ * (lair pass B13, 2026-09-27). On the template context as
2206
+ * `{{knownLocations}}` (their names, one line) and
2207
+ * `{{locationEntry}}` (the entry whose name is the world's
2208
+ * `location` slot — where the party are, its exits included),
2209
+ * whatever the retrieval ranking admitted: a planner that is
2210
+ * never shown the room it stands in cannot tell an open door
2211
+ * from an unbuilt one. Both are absent when nothing is listed.
2212
+ */
2213
+ locationEntries: S.json,
2214
+ /**
2215
+ * **Side talk** (lair re-plan R13, 2026-09-28): what was said on
2216
+ * another channel since the story's last line — the Lair's
2217
+ * Sanctum talk, read by `session-history@1` with
2218
+ * `unplayedOnly`. Transcript rows, rendered as prose into
2219
+ * `{{sideTalk}}` (one `Name: line` per row, as `recentStory`
2220
+ * is), so a prompt gives it its own labelled block and it never
2221
+ * reads as story turns. Absent when unwired or empty: the Lair
2222
+ * wires it only while the session's _Sanctum talk steers the
2223
+ * story_ is on.
2224
+ */
2225
+ sideTalk: S.messages,
2226
+ /**
2227
+ * The planner's own running notes (lair re-plan R13, owner
2228
+ * 2026-09-28): the Castellan's **scratchpad**, rendered as
2229
+ * `{{scratchpad}}`. Absent when unwired or blank; the Lair
2230
+ * wires it beside `sideTalk`.
2231
+ */
2232
+ scratchpad: S.text,
2233
+ /**
2234
+ * **How the cast stand with each other** (genre plan F6(a),
2235
+ * 2026-09-29): the ranker's allocated candidates, of which the
2236
+ * builder reads the `relationships` band's `castRelationships`
2237
+ * lane — `core:query/relationship-search@1` read with nobody
2238
+ * speaking. Rendered as `{{castRelationships}}`: JSON keyed by
2239
+ * who holds each view, then by whom it is of, in rank order.
2240
+ * Only what the budget
2241
+ * admitted arrives, so a band at share 0 renders nothing. Absent
2242
+ * when unwired or empty.
2243
+ *
2244
+ * ⚠ On the planner and the scene only — the game master's two
2245
+ * agents. A voice is a cast member speaking, and
2246
+ * `build-side-character-context@1` has no such port on purpose:
2247
+ * another member's secret must never reach it.
2248
+ */
2249
+ castRelationships: S.candidates,
2250
+ },
2251
+ out: contextPorts.out,
2252
+ },
2253
+ }));
2254
+ /**
2255
+ * The narrator's context for a planned turn — the one builder that takes a
2256
+ * **plan**.
2257
+ *
2258
+ * `plan` is the only genuinely new thing in this file's three types: the
2259
+ * structured object the planning step produced, put on the template context
2260
+ * under `plan` so the narrator's story string can render its beats and its
2261
+ * world hints. It is a port rather than a nested literal on `state` because the
2262
+ * two are different facts and a template author should be able to tell which is
2263
+ * which — `state.world.weather` is what the world IS, `plan.worldHints` is what
2264
+ * this turn was asked to make of it.
2265
+ *
2266
+ * `narratorName` rides the prompts slot, as it does on `build-narrator-context@1`
2267
+ * and for the same reason: it is the name on the seed line the model continues
2268
+ * from, which is a setting somebody stored rather than data a trigger carried.
2269
+ * @experimental
2270
+ */
2271
+ export const buildSceneContext = pin(describeTaskDefinition({
2272
+ id: 'core:task/build-scene-context@1',
2273
+ i18n: { name: { en: 'Build scene context' } },
2274
+ timeoutMs: 2000,
2275
+ slots: agentContextSlots({
2276
+ systemPrompt: { type: 'text' },
2277
+ postHistoryInstructions: { type: 'text' },
2278
+ narratorName: { type: 'text' },
2279
+ }),
2280
+ ports: {
2281
+ in: {
2282
+ cast: contextPorts.in.cast,
2283
+ state: S.json,
2284
+ /** What the planning step decided this turn is about. */
2285
+ plan: S.json,
2286
+ /**
2287
+ * The session's own genre fields, by key — `tone`,
2288
+ * `difficulty` and whatever else the genre declared.
2289
+ *
2290
+ * On the template context under their own names, so an
2291
+ * authored prompt writes `{{tone}}` the way it writes
2292
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2293
+ * declaration promises: declared on the genre, edited in
2294
+ * session settings, stored on the row, published by the input
2295
+ * node, and read here by the agent whose wording depends on
2296
+ * them. Without this port the last step was missing and a
2297
+ * prompt naming `{{tone}}` rendered a blank.
2298
+ */
2299
+ fields: S.json,
2300
+ /**
2301
+ * What the person just sent, when the genre reads it as
2302
+ * **direction** rather than as a line somebody said (lair pass
2303
+ * B11, 2026-09-27) — the Lair's composer. On the template
2304
+ * context and in the prompt as `{{turnDirection}}`; empty or
2305
+ * absent on a turn nobody directed (a Continue), so a prompt
2306
+ * writes `{{#if turnDirection}}…{{/if}}`. A genre whose composer
2307
+ * text is a participant's line leaves it unwired: that line is
2308
+ * already in the transcript. *Turn* direction, never bare
2309
+ * `direction`: that word is the Lair's standing-note state slot
2310
+ * (`core:slot/direction@1`), a different fact (R1, renamed
2311
+ * 2026-09-27).
2312
+ */
2313
+ turnDirection: S.text,
2314
+ /**
2315
+ * The places the lorebook holds — a
2316
+ * `core:query/lorebook-entries@1` listing of location entries
2317
+ * (lair pass B13, 2026-09-27). On the template context as
2318
+ * `{{knownLocations}}` (their names, one line) and
2319
+ * `{{locationEntry}}` (the room the world's `location` names,
2320
+ * else the planner's location hint — where the party are, its
2321
+ * exits included), whatever the retrieval ranking admitted: a
2322
+ * planner that is never shown the room it stands in cannot
2323
+ * tell an open door from an unbuilt one. Both are absent when
2324
+ * nothing is listed.
2325
+ */
2326
+ locationEntries: S.json,
2327
+ /**
2328
+ * **Side talk** (lair re-plan R13, 2026-09-28), on the
2329
+ * planner's terms: the Lair's Sanctum talk since the story's
2330
+ * last line, rendered as prose into `{{sideTalk}}` — for the
2331
+ * Castellan's narration, wired while the session's _Sanctum
2332
+ * talk steers the story_ is on, or when Narrate was pressed in
2333
+ * the Sanctum. Absent when unwired or empty.
2334
+ */
2335
+ sideTalk: S.messages,
2336
+ /**
2337
+ * How the cast stand with each other, on the narrator's terms
2338
+ * — the same port as the planner's (F6(a), 2026-09-29), rendered
2339
+ * as `{{castRelationships}}`. See `buildPlannerContext`.
2340
+ */
2341
+ castRelationships: S.candidates,
2342
+ /**
2343
+ * **Whose lines this call writes** (Lair party speech,
2344
+ * 2026-09-30): a list of side-character facts — the planner's
2345
+ * `{ name, intent }`, or `{ characterId }` for a picked
2346
+ * delver — rendered as `{{partySpeakers}}`, one line per
2347
+ * speaker in order: the name the cast gives them, then what
2348
+ * they mean to do when the fact says. A nested list is read
2349
+ * flat, so a spec may hand `[first, rest]` from
2350
+ * `split-first@1` as it is. A name the cast does not hold is
2351
+ * kept as written. Absent when unwired or empty.
2352
+ *
2353
+ * For a call that writes the cast's lines **as nobody's
2354
+ * voice** — the Lair's Castellan speaking for the party: this
2355
+ * surface hears no holder-only slot and reads no member's
2356
+ * private lore, so naming the speakers here gives away nothing
2357
+ * a voice of their own would keep.
2358
+ */
2359
+ partySpeakers: S.json,
2360
+ /**
2361
+ * 🚧 **Which places' stats this surface reads** (place sight,
2362
+ * owner ruling 2026-09-30), a literal: `'reach'` — the place
2363
+ * the scene is at and the places one way from it (the room's
2364
+ * listed links to other places, the "From here:" ways); every
2365
+ * other place's stats are left out, its name kept. Absent, the
2366
+ * session's sight: every place it sees. The Lair's Castellan
2367
+ * speaking for the party wires `'reach'`; its narration does
2368
+ * not.
2369
+ */
2370
+ placeSight: S.json,
2371
+ },
2372
+ out: contextPorts.out,
2373
+ },
2374
+ }));
2375
+ /**
2376
+ * The state-keeper's context: the state as it stands, so the keeper can report
2377
+ * only what the scene changed about it.
2378
+ *
2379
+ * Its own type rather than the planner's because the two read the same facts
2380
+ * for opposite purposes — one is deciding what should happen, the other is
2381
+ * writing down what did — and a shared pool would ship them one set of
2382
+ * instructions.
2383
+ * @experimental
2384
+ */
2385
+ export const buildKeeperContext = pin(describeTaskDefinition({
2386
+ id: 'core:task/build-keeper-context@1',
2387
+ i18n: { name: { en: 'Build state keeper context' } },
2388
+ timeoutMs: 2000,
2389
+ slots: agentContextSlots({
2390
+ systemPrompt: { type: 'text' },
2391
+ postHistoryInstructions: { type: 'text' },
2392
+ }),
2393
+ ports: {
2394
+ in: {
2395
+ cast: contextPorts.in.cast,
2396
+ state: S.json,
2397
+ /**
2398
+ * The reply this keeper is reading, as text — put on the
2399
+ * template context under `reply`, because the thing a keeper
2400
+ * reports on is the scene that was just written and the
2401
+ * transcript does not contain it yet.
2402
+ */
2403
+ reply: S.text,
2404
+ /**
2405
+ * ⚠ **An ORDERING edge, and nothing else reads it.**
2406
+ *
2407
+ * A state change is anchored to the newest message in the
2408
+ * session, which is how a swipe takes its changes back with it.
2409
+ * So the keeper has to run AFTER the reply is written, not
2410
+ * merely beside it — and in a graph whose order is its edges,
2411
+ * the only way to say "after that write" is to take the write's
2412
+ * result on a port. It is the write result rather than the text
2413
+ * for exactly that reason: the text exists before the write and
2414
+ * would order nothing.
2415
+ *
2416
+ * ⚠ Typed `json`, NOT `write-result@1`, and the difference is
2417
+ * the standing rule rather than a convenience.
2418
+ * `core:shape/write-result@1` is deliberately accepted nowhere:
2419
+ * under async review a write is a proposal a reviewer may still
2420
+ * reject, so a port declaring that shape is a port promising to
2421
+ * handle both arms of it. This node handles neither — it never
2422
+ * looks inside — and declaring the shape would claim otherwise.
2423
+ * `json` is the honest type for a value taken as opaque, and
2424
+ * write results are assignable to it like everything else.
2425
+ */
2426
+ afterWrite: S.json,
2427
+ /**
2428
+ * The session's own genre fields, by key — `tone`,
2429
+ * `difficulty` and whatever else the genre declared.
2430
+ *
2431
+ * On the template context under their own names, so an
2432
+ * authored prompt writes `{{tone}}` the way it writes
2433
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2434
+ * declaration promises: declared on the genre, edited in
2435
+ * session settings, stored on the row, published by the input
2436
+ * node, and read here by the agent whose wording depends on
2437
+ * them. Without this port the last step was missing and a
2438
+ * prompt naming `{{tone}}` rendered a blank.
2439
+ */
2440
+ fields: S.json,
2441
+ },
2442
+ out: contextPorts.out,
2443
+ },
2444
+ }));
2445
+ /**
2446
+ * Chat rows into the objects a template renders.
2447
+ *
2448
+ * A Task rather than part of the history Query, because naming a message —
2449
+ * which participant said it, under what name at the time — is a *decision*, and
2450
+ * decisions are the things a plugin should be able to replace. The Query returns
2451
+ * rows; this says who spoke.
2452
+ * @public
2453
+ */
2454
+ export const processMessages = pin(describeTaskDefinition({
2455
+ id: 'core:task/process-messages@1',
2456
+ i18n: { name: { en: 'Process messages' } },
2457
+ timeoutMs: 1000,
2458
+ slots: {
2459
+ /**
2460
+ * The message-rewrite hook (18 §4a), on the *processed* list —
2461
+ * names resolved, per-message interpolation done. `transform` only:
2462
+ * `messages/inject` deliberately does **not** live here. Injection
2463
+ * is a statement about *position in the rendered conversation*, and
2464
+ * position belongs to the template (§20, ruling of 2026-08-23) —
2465
+ * inject chains attach on the context builders, land as
2466
+ * `context.injections`, and the template's own loop renders them.
2467
+ * Splicing rows into this list would be a position the template
2468
+ * cannot express and an author cannot see.
2469
+ */
2470
+ scripts: {
2471
+ kind: 'scripts',
2472
+ accepts: ['core:script:messages/transform@1'],
2473
+ port: 'main',
2474
+ phase: 'after',
2475
+ description: 'Scripts over the message list the model will see — rewrite or drop lines. Reminders at a depth attach on the context step instead.',
2476
+ },
2477
+ },
2478
+ ports: {
2479
+ in: {
2480
+ messages: S.messages,
2481
+ cast: S.sessionCast,
2482
+ templateContext: S.templateContext,
2483
+ seedName: S.text,
2484
+ /**
2485
+ * Text the model is being asked to CONTINUE — the seed line's
2486
+ * body rather than a message of its own (ruling 2026-09-08,
2487
+ * D-2).
2488
+ *
2489
+ * ⚠ **Absent on an ordinary turn, and that is the normal case.**
2490
+ * There is no `optional` marker for a port: a port nothing wires
2491
+ * resolves to `undefined`, the seed line renders empty, and the
2492
+ * model starts the reply. Every spec but an extend leaves it
2493
+ * unwired on purpose.
2494
+ *
2495
+ * It is a port rather than a second synthetic message because a
2496
+ * partial reply is not a turn: appending it as one produces two
2497
+ * consecutive assistant entries on a chat endpoint and a
2498
+ * wrongly-closed block on a completion one. The seed is the one
2499
+ * place in the prompt whose block is deliberately left open
2500
+ * (`includeClose: false` for id -2), which is exactly what a
2501
+ * continuation needs.
2502
+ *
2503
+ * ⚠ It is **not** a stored message, and nothing downstream may
2504
+ * treat it as one. The row holding it is `isGenerating` and is
2505
+ * excluded from every message read, so lore scans, semantic and
2506
+ * entity queries and history windows do not see it. It counts
2507
+ * against the token budget, because it is in the prompt.
2508
+ */
2509
+ continuationPrefill: S.text,
2510
+ },
2511
+ out: { main: S.messages, messages: S.messages },
2512
+ },
2513
+ }));
2514
+ /**
2515
+ * The conversation as PROSE, for a step that reads it rather than takes a turn.
2516
+ *
2517
+ * Two differences from `process-messages@1`, and both are properties of the
2518
+ * transcript rather than of the request, which is why they live here and not on
2519
+ * the Provider: by the time a prompt is rendered for a completion wire the
2520
+ * conversation is one string with an open block at the end of it, and nothing
2521
+ * downstream can take either of them back out.
2522
+ *
2523
+ * · **No seed.** `process-messages@1` ends its list with an empty assistant
2524
+ * line carrying the next speaker's name, because that line is what tells a
2525
+ * model whose turn it is. A planner and a state keeper are not taking a
2526
+ * turn, and a prompt that ends `Verity:` asks for Verity's next paragraph
2527
+ * however plainly the instructions asked for JSON.
2528
+ * · **No JSON blocks.** A reply that carried a document at the end of it
2529
+ * teaches the next turn's planner its own schema and the keeper somebody
2530
+ * else's. The cut happens on the way into the prompt and never on the
2531
+ * stored row — see `prompt/jsonBlocks.ts`.
2532
+ *
2533
+ * Everything else is the same naming and the same interpolation, from the same
2534
+ * implementation: who spoke, under what name at the time, reaching through
2535
+ * participants who have since left.
2536
+ * @public
2537
+ */
2538
+ export const proseTranscript = pin(describeTaskDefinition({
2539
+ id: 'core:task/prose-transcript@1',
2540
+ i18n: { name: { en: 'Transcript as prose' } },
2541
+ timeoutMs: 1000,
2542
+ ports: {
2543
+ in: {
2544
+ messages: S.messages,
2545
+ cast: S.sessionCast,
2546
+ templateContext: S.templateContext,
2547
+ },
2548
+ out: { main: S.messages, messages: S.messages },
2549
+ },
2550
+ }));
2551
+ /**
2552
+ * 🚧 **Where each line's attachments go** (PLAN-composer-attachments §3.5; owner
2553
+ * D2/D3, 2026-10-02).
2554
+ *
2555
+ * Pure. Takes the processed lines and the attachments by message, and gives
2556
+ * each line an `attachments` string the template renders after the line's text
2557
+ * (`{{{attachments}}}` in the shipped template):
2558
+ *
2559
+ * - an image or PDF the call can read, within `mediaLookback` messages of the
2560
+ * end, becomes a **media marker** the prompt parser lifts onto that line's
2561
+ * own turn;
2562
+ * - a text file becomes a fenced block with its name, trimmed to
2563
+ * `textFileTokens` with a stated note — never silently;
2564
+ * - anything else — a kind the call cannot read, or media older than the
2565
+ * lookback — becomes a **placeholder**: `[image: cat.png]`, with the
2566
+ * person's description when there is one.
2567
+ *
2568
+ * What the call can read comes from its `connection` slot — wire it with
2569
+ * `slot.connectionOf('<the step that sends the prompt>')` — whose descriptor
2570
+ * carries `metadata.reads` (`ConnectionReadsV1`). Unwired, the call reads no
2571
+ * media and every image is a name: what a text-only step such as a summary
2572
+ * wants. A line with no files is passed through untouched, so a transcript
2573
+ * with no attachments renders byte for byte what it did without this step.
2574
+ *
2575
+ * `notes` are sentences for the run's receipt ("2 images older than the media
2576
+ * lookback were sent as names").
2577
+ * @experimental
2578
+ */
2579
+ export const placeAttachments = pin(describeTaskDefinition({
2580
+ id: 'core:task/place-attachments@1',
2581
+ i18n: { name: { en: 'Place attachments' } },
2582
+ timeoutMs: 1000,
2583
+ slots: {
2584
+ connection: {
2585
+ kind: 'connection',
2586
+ shape: S.textGen,
2587
+ description: 'Which step these lines are written for. Point it at the step that sends the prompt: what that step can read decides whether an image is sent or named.',
2588
+ },
2589
+ params: {
2590
+ kind: 'parameters',
2591
+ facet: 'weights',
2592
+ schema: {
2593
+ mediaLookback: {
2594
+ type: 'integer',
2595
+ min: 0,
2596
+ default: 10,
2597
+ label: { en: 'Media lookback (messages)' },
2598
+ description: {
2599
+ en: 'Images and PDFs in the last this-many messages are sent to the model; older ones are sent as their names. Set to zero to send every attachment as a name.',
2600
+ },
2601
+ },
2602
+ textFileTokens: {
2603
+ type: 'integer',
2604
+ min: 0,
2605
+ default: 4000,
2606
+ label: { en: 'Text file budget (tokens)' },
2607
+ description: {
2608
+ en: 'How much of each attached text file goes into the prompt. A longer file is cut here, and the prompt says it was cut.',
2609
+ },
2610
+ },
2611
+ },
2612
+ },
2613
+ },
2614
+ ports: {
2615
+ in: { messages: S.messages, attachments: S.mediaByMessage },
2616
+ out: { main: S.messages, messages: S.messages, notes: S.json },
2617
+ },
2618
+ }));
2619
+ /**
2620
+ * The turn-order pool, orderer and strategies (PLAN-turn-order §4.4, R3/R8;
2621
+ * re-ported in place 2026-09-22, pre-release).
2622
+ *
2623
+ * Turn order is **state**, not a decision made inside the reply run
2624
+ * (§3). One spec per genre — `core:spec/<genre>-turn-order` — answers a session event by
2625
+ * reading the cast and the history, pooling who *may* be seated, ordering
2626
+ * them, turning them into entries, and writing the result to
2627
+ * `sessions.metadata.turnOrder`. The reply run then fires an entry; it
2628
+ * decides nothing.
2629
+ *
2630
+ * Three node families, composable in that order:
2631
+ *
2632
+ * - **the pool** (`turn-pool`) decides who may be seated at all, from the
2633
+ * settings document's cast. Its params are the genre's and the session's
2634
+ * to set; its floors are not (a removed row is never a candidate, and an
2635
+ * `on-action` envoy speaks only through its action).
2636
+ * - **an orderer** (`turn-mentioned`) rewrites the candidate list's order
2637
+ * and hands on the same shape, so any number of them compose.
2638
+ * - **a strategy** turns candidates into *entries*: who speaks, where, and
2639
+ * what to fire. It is the last node before the write.
2640
+ *
2641
+ * ⚠ **No `speaker` in-port, and no halt** (§4.4, §6). An explicit pick never
2642
+ * enters a strategy — a person's pick is fired directly (`fireTurnEntry`,
2643
+ * §4.6) and the next recompute sees the row it produced — and a strategy
2644
+ * that seats nobody publishes an **empty order**, which is an answer. The
2645
+ * halt (`nobody is due`) and the `characterId` port went with the decider
2646
+ * they belonged to.
2647
+ */
2648
+ const turnStrategy = (id, label, extras = {}) => describeTaskDefinition({
2649
+ id,
2650
+ i18n: { name: { en: label } },
2651
+ timeoutMs: 1000,
2652
+ ...extras,
2653
+ ports: {
2654
+ in: {
2655
+ /** Who may be seated — the pool's output, through any orderers. */
2656
+ candidates: S.turnCandidates,
2657
+ /** The session's visible history, ascending. */
2658
+ messages: S.messages,
2659
+ },
2660
+ out: {
2661
+ /**
2662
+ * The prepared turns, in order. `main` and `order` carry the
2663
+ * same value: `main` is what the shape-based swap list keys
2664
+ * on (a strategy is a node publishing `turn-entries@1`), and
2665
+ * `order` is what `set-turn-order` is wired from, named for
2666
+ * what it is.
2667
+ */
2668
+ main: S.turnEntries,
2669
+ order: S.turnEntries,
2670
+ },
2671
+ },
2672
+ });
2673
+ /**
2674
+ * Round robin: the candidates that have not spoken since the last user row,
2675
+ * in candidate order. A character spoke when a non-hidden, non-narrator row
2676
+ * after the last user row carries its id; an envoy when `metadata.speaker`
2677
+ * carries its reference; a persona when a user row carries its `personaId`
2678
+ * — which is how a session knows it is the person's turn (R15).
2679
+ * @experimental
2680
+ */
2681
+ export const turnRoundRobin = pin(turnStrategy('core:task/turn-round-robin@1', 'Round robin'));
2682
+ /**
2683
+ * A seeded uniform pick over the not-yet-spoken candidates — one entry.
2684
+ * `declaresRandomness`, so a replayed run re-rolls identically; an
2685
+ * unrelated recompute may roll differently, which is documented rather than
2686
+ * prevented (§4.4).
2687
+ * @experimental
2688
+ */
2689
+ export const turnRandom = pin(turnStrategy('core:task/turn-random@1', 'Random', {
2690
+ declaresRandomness: true,
2691
+ }));
2692
+ /**
2693
+ * Round robin over the candidates whose `ownerUserId` is the last sender's,
2694
+ * so one person's cast completes a turn before another's; plain round robin
2695
+ * when that set is empty. The rule narrows, it never starves.
2696
+ * @experimental
2697
+ */
2698
+ export const turnUserSplit = pin(turnStrategy('core:task/turn-user-split@1', 'Round robin by user'));
2699
+ /**
2700
+ * Round robin, with the `select` point free to rewrite it: the host hands
2701
+ * `{ order, candidates, lastSpeaker, sinceUser }` to a
2702
+ * `core:script:turn/select@1` chain and keeps the entries it returns whose
2703
+ * `ref` is a candidate — a script cannot seat somebody the pool did not
2704
+ * admit, and a refusal is a receipt note. Entries the chain changed carry
2705
+ * `via: 'script'`.
2706
+ * @experimental
2707
+ */
2708
+ export const turnScripted = pin(turnStrategy('core:task/turn-scripted@1', 'Scripted', {
2709
+ scriptPoints: [
2710
+ {
2711
+ key: 'select',
2712
+ accepts: ['core:script:turn/select@1'],
2713
+ label: { en: 'Order the turns' },
2714
+ description: {
2715
+ en: 'Scripts that rewrite the prepared order, in order — each is handed the order so far and hands one back.',
2716
+ },
2717
+ },
2718
+ ],
2719
+ }));
2720
+ /** Always an empty order: nothing is prepared, and every turn is a press. @experimental */
2721
+ export const turnManual = pin(turnStrategy('core:task/turn-manual@1', 'Manual'));
2722
+ /**
2723
+ * One entry in the pipeline's own voice (`{ ref: null, via: 'voice' }`) when
2724
+ * the last row is a user row, else empty. How a planner genre — Adventure,
2725
+ * the Lair, the Whodunit showcase plugin — gets exactly one reply per send
2726
+ * with no cast in the pool at all.
2727
+ * @experimental
2728
+ */
2729
+ export const turnNarrator = pin(turnStrategy('core:task/turn-narrator@1', 'Narrator replies'));
2730
+ /**
2731
+ * The pool (§4.4): who *may* be seated this recompute, from the settings
2732
+ * document's cast and the history.
2733
+ *
2734
+ * Its four params are the whole of a genre's or a session's say over
2735
+ * eligibility. Two floors are not params, because a param that could
2736
+ * override them would be a way to seat somebody who has left: a row with
2737
+ * `removedAt` is never a candidate, and an envoy declared `speaks:
2738
+ * 'on-action'` is never a candidate — it speaks through its action's
2739
+ * outputs alone.
2740
+ *
2741
+ * Output order is characters by `position`, then personas by `position`,
2742
+ * then envoys by `position`. An orderer may rewrite it; a strategy reads it
2743
+ * as given.
2744
+ * @experimental
2745
+ */
2746
+ export const turnPool = pin(describeTaskDefinition({
2747
+ id: 'core:task/turn-pool@1',
2748
+ i18n: { name: { en: 'Turn pool' } },
2749
+ timeoutMs: 1000,
2750
+ slots: {
2751
+ params: {
2752
+ kind: 'parameters',
2753
+ facet: 'behavior',
2754
+ schema: {
2755
+ characters: {
2756
+ type: 'enum',
2757
+ of: ['active', 'all', 'none'],
2758
+ members: [
2759
+ {
2760
+ key: 'active',
2761
+ label: { en: 'Active' },
2762
+ description: { en: 'The characters switched on in the cast.' },
2763
+ },
2764
+ {
2765
+ key: 'all',
2766
+ label: { en: 'All' },
2767
+ description: { en: 'Ones switched off in the cast too.' },
2768
+ },
2769
+ { key: 'none', label: { en: 'None' } },
2770
+ ],
2771
+ default: 'active',
2772
+ label: { en: 'Characters' },
2773
+ description: {
2774
+ en: "Which of the session's characters may take a turn. 'All' admits ones switched off in the cast; a removed character never is.",
2775
+ },
2776
+ },
2777
+ personas: {
2778
+ type: 'enum',
2779
+ of: ['none', 'all', 'others'],
2780
+ members: [
2781
+ { key: 'none', label: { en: 'None' } },
2782
+ {
2783
+ key: 'all',
2784
+ label: { en: 'All' },
2785
+ description: { en: 'Everyone in the session.' },
2786
+ },
2787
+ {
2788
+ key: 'others',
2789
+ label: { en: 'Others' },
2790
+ description: { en: 'Everyone but whoever just wrote.' },
2791
+ },
2792
+ ],
2793
+ default: 'all',
2794
+ label: { en: 'Personas' },
2795
+ description: {
2796
+ en: "Whether the people in the session appear in the order. A person's entry is shown as their turn and never generated — that is how a session says it is your turn. 'Others' leaves out whoever just wrote.",
2797
+ },
2798
+ },
2799
+ envoys: {
2800
+ type: 'enum',
2801
+ of: ['in-turn', 'none', 'only', 'except'],
2802
+ members: [
2803
+ {
2804
+ key: 'in-turn',
2805
+ label: { en: 'Those that take turns' },
2806
+ description: {
2807
+ en: 'Envoys declared to speak in turn; one that speaks only on an action never does.',
2808
+ },
2809
+ },
2810
+ { key: 'none', label: { en: 'None' } },
2811
+ {
2812
+ key: 'only',
2813
+ label: { en: 'Only' },
2814
+ description: { en: 'Only the envoys in the list below.' },
2815
+ },
2816
+ {
2817
+ key: 'except',
2818
+ label: { en: 'Except' },
2819
+ description: { en: 'Every envoy but those in the list below.' },
2820
+ },
2821
+ ],
2822
+ default: 'in-turn',
2823
+ label: { en: 'Envoys' },
2824
+ description: {
2825
+ en: "Which of the genre's envoys may take a turn. 'Only' and 'Except' read the list below.",
2826
+ },
2827
+ },
2828
+ envoySlugs: {
2829
+ type: 'string',
2830
+ list: true,
2831
+ default: [],
2832
+ label: { en: 'Envoy list' },
2833
+ description: {
2834
+ en: "The envoys 'Only' admits, or 'Except' leaves out. Ignored otherwise.",
2835
+ },
2836
+ },
2837
+ },
2838
+ },
2839
+ },
2840
+ ports: {
2841
+ in: {
2842
+ /** The settings document's cast, envoys included (§4.12). */
2843
+ cast: S.sessionCast,
2844
+ /** The session's visible history, ascending. */
2845
+ messages: S.messages,
2846
+ },
2847
+ out: { main: S.turnCandidates },
2848
+ },
2849
+ }));
2850
+ /**
2851
+ * The first orderer (R8): mentioned candidates sort to the front.
2852
+ *
2853
+ * A composable node rather than a seventh strategy, because "who was named"
2854
+ * and "whose turn it is" are two questions — a session can have the
2855
+ * mentioned rule under round robin, under user-split or under a plugin's
2856
+ * strategy by placing this before any of them.
2857
+ *
2858
+ * Case-insensitive whole-word match of each candidate's `name` and
2859
+ * `nickname` against the most recent `lookback` **user** rows; mentioned
2860
+ * candidates move to the front ordered by first mention, and the rest keep
2861
+ * the order they arrived in. The receipt records `mentioned`. (A
2862
+ * gazetteer-backed match is a later improvement; this is names.)
2863
+ * @experimental
2864
+ */
2865
+ export const turnMentioned = pin(describeTaskDefinition({
2866
+ id: 'core:task/turn-mentioned@1',
2867
+ i18n: { name: { en: 'Mentioned first' } },
2868
+ timeoutMs: 1000,
2869
+ slots: {
2870
+ params: {
2871
+ kind: 'parameters',
2872
+ facet: 'behavior',
2873
+ schema: {
2874
+ lookback: {
2875
+ type: 'integer',
2876
+ default: 1,
2877
+ min: 1,
2878
+ label: { en: 'Messages scanned' },
2879
+ description: {
2880
+ en: 'How many of your most recent messages are read for names.',
2881
+ },
2882
+ },
2883
+ },
2884
+ },
2885
+ },
2886
+ ports: {
2887
+ in: { candidates: S.turnCandidates, messages: S.messages },
2888
+ out: { main: S.turnCandidates },
2889
+ },
2890
+ }));
2891
+ /**
2892
+ * Tool calling's two pure halves (20 §9). A *tool* is any same-shaped
2893
+ * provider — a sandboxed plugin hook canonically — and these tasks only
2894
+ * decide how the model learns about it and how its answer is read back.
2895
+ * Between them sits the ordinary generate step; around them sits the loop
2896
+ * block, whose iterations are the receipted agentic turn.
2897
+ * @experimental
2898
+ */
2899
+ export const advertiseTools = pin(describeTaskDefinition({
2900
+ id: 'core:task/advertise-tools@1',
2901
+ i18n: { name: { en: 'Advertise tools' } },
2902
+ timeoutMs: 500,
2903
+ slots: {
2904
+ params: {
2905
+ kind: 'parameters',
2906
+ schema: {
2907
+ style: {
2908
+ type: 'enum',
2909
+ of: ['native', 'prompt'],
2910
+ members: [
2911
+ {
2912
+ key: 'native',
2913
+ label: { en: 'Native tool calling' },
2914
+ description: { en: "Hands the declarations to the API's own tool-calling." },
2915
+ },
2916
+ {
2917
+ key: 'prompt',
2918
+ label: { en: 'In the prompt' },
2919
+ description: { en: 'Writes them into the context, for models without tool-calling.' },
2920
+ },
2921
+ ],
2922
+ default: 'prompt',
2923
+ description: "How the model learns its tools: natively through the API's own tool-calling, or written into the prompt for models without one.",
2924
+ },
2925
+ },
2926
+ },
2927
+ },
2928
+ ports: {
2929
+ // [{ name, description, parameters }] — parameters as JSON Schema.
2930
+ in: { tools: S.json },
2931
+ out: { main: S.json, native: S.json, prompt: S.text },
2932
+ },
2933
+ }));
2934
+ /** @experimental */
2935
+ export const parseToolCall = pin(describeTaskDefinition({
2936
+ id: 'core:task/parse-tool-call@1',
2937
+ i18n: { name: { en: 'Parse tool call' } },
2938
+ timeoutMs: 500,
2939
+ ports: {
2940
+ in: { text: S.text, tools: S.json },
2941
+ // `call` is { tool, args } | null — null is the loop's exit
2942
+ // predicate, not an error: a reply with no call is the model being
2943
+ // done. `text` is the reply with the call block stripped, so what
2944
+ // renders is prose and what dispatches is data.
2945
+ out: { main: S.json, call: S.json, text: S.text },
2946
+ },
2947
+ }));
2948
+ /**
2949
+ * A repeated block's outputs, as one string.
2950
+ *
2951
+ * The missing half of `map` and `loop`. Both publish a **list** — `values`, one
2952
+ * entry per iteration — and everything that writes (a message, a lore entry)
2953
+ * takes a scalar, so every spec that repeats anything has needed this and
2954
+ * every spec has had to end at the block. Reducing in a Consumer instead would
2955
+ * put the join inside the write, where no receipt can show it and no author
2956
+ * can change it.
2957
+ *
2958
+ * `path` is what makes it usable on a block: an iteration's value is that
2959
+ * chain's last node's **ports object**, so the interesting text is at
2960
+ * `.text` or `.answer` rather than at the top. Empty entries are skipped
2961
+ * rather than joined, which is what makes "every iteration's answer, and only
2962
+ * the iteration that had one" a wiring rather than a filter node.
2963
+ * @experimental
2964
+ */
2965
+ export const joinText = pin(describeTaskDefinition({
2966
+ id: 'core:task/join-text@1',
2967
+ i18n: { name: { en: 'Join text' } },
2968
+ timeoutMs: 500,
2969
+ slots: {
2970
+ params: {
2971
+ kind: 'parameters',
2972
+ schema: {
2973
+ path: {
2974
+ type: 'string',
2975
+ default: 'text',
2976
+ description: 'Which key to read off each entry. Empty reads the entry itself, for a list of plain strings.',
2977
+ },
2978
+ separator: {
2979
+ type: 'string',
2980
+ default: '\n\n',
2981
+ description: 'What goes between the entries that had something to say.',
2982
+ },
2983
+ },
2984
+ },
2985
+ },
2986
+ ports: { in: { items: S.json }, out: { main: S.text, text: S.text } },
2987
+ }));
2988
+ /**
2989
+ * A document's lists, as one **folded section** a reply carries collapsed
2990
+ * (lair pass B5, decision D5, 2026-09-27).
2991
+ *
2992
+ * The producer the message outlets' `sections` in-port was built for: a
2993
+ * planner's document is structure, and the person reading the reply wants its
2994
+ * beats and speakers as a short list under a "Plan" heading — never the JSON,
2995
+ * and never in the body. `path` names the keys read, comma-separated and in
2996
+ * order; each list entry becomes one line, and an object entry reads as its
2997
+ * own text values joined with ` — ` (`sectionItemsOf` in the SDK is the one
2998
+ * reading). A document with nothing to list publishes an empty list, which a
2999
+ * write takes as "no sections".
3000
+ *
3001
+ * `kind` and `label` are parameters, not ports: they are what the section IS,
3002
+ * chosen by whoever wires it, and a model never names them.
3003
+ * @experimental
3004
+ */
3005
+ export const listSection = pin(describeTaskDefinition({
3006
+ id: 'core:task/list-section@1',
3007
+ i18n: { name: { en: 'List section' } },
3008
+ timeoutMs: 500,
3009
+ slots: {
3010
+ params: {
3011
+ kind: 'parameters',
3012
+ schema: {
3013
+ path: {
3014
+ type: 'string',
3015
+ default: '',
3016
+ description: 'Which keys of the document to list, comma-separated and in order. Empty lists the document itself.',
3017
+ },
3018
+ kind: {
3019
+ type: 'string',
3020
+ default: 'notes',
3021
+ description: "The section's kind: a lowercase slug such as 'plan'.",
3022
+ },
3023
+ label: {
3024
+ type: 'string',
3025
+ default: 'Notes',
3026
+ description: "The heading the section's button shows.",
3027
+ },
3028
+ },
3029
+ },
3030
+ },
3031
+ ports: {
3032
+ in: { json: S.json },
3033
+ out: {
3034
+ main: S.foldedSections,
3035
+ sections: S.foldedSections,
3036
+ /**
3037
+ * The same lines as a markdown list, one `- ` item per line
3038
+ * (lair pass R8, 2026-09-28) — for a message whose BODY is the
3039
+ * list: the Lair's beats row in the Sanctum. Empty when
3040
+ * nothing was listed.
3041
+ */
3042
+ text: S.text,
3043
+ },
3044
+ },
3045
+ }));
3046
+ /**
3047
+ * A list, split into its **first** item and the **rest**, in order (lair pass
3048
+ * R8, 2026-09-28).
3049
+ *
3050
+ * A data reference is `{node, port}` with no sub-path, and `parse-json@1`'s
3051
+ * `path` selects a key or an index but never a tail — so a spec that treats
3052
+ * the first of a list differently from the others (the Lair's lead delver,
3053
+ * whose line streams into the run's live row, before the rest of the party
3054
+ * speak in an `each`) had no way to name "all but the first". Pure: no read,
3055
+ * no model, 1 ms.
3056
+ *
3057
+ * `first` is absent on an empty list, so a junction on it skips the step
3058
+ * that needs one; `rest` is always a list — empty on a list of one or none —
3059
+ * so an `each` wired to it never has to defend itself. Anything that is not
3060
+ * a list is a list of one.
3061
+ * @experimental
3062
+ */
3063
+ export const splitFirst = pin(describeTaskDefinition({
3064
+ id: 'core:task/split-first@1',
3065
+ i18n: { name: { en: 'Split first' } },
3066
+ timeoutMs: 500,
3067
+ ports: {
3068
+ in: { items: S.json },
3069
+ out: { main: S.json, first: S.json, rest: S.json },
3070
+ },
3071
+ }));
3072
+ /**
3073
+ * A model's JSON answer, read back as data.
3074
+ *
3075
+ * ## Why a Task and not a shape on the Provider
3076
+ *
3077
+ * `core:oracle/generate-text@1` is published and frozen, and it publishes
3078
+ * prose. A pipeline that wants structure out of a model therefore needs one
3079
+ * more step, and that step is the honest place for every way the reading can
3080
+ * fail: a fenced block, a preamble the model could not resist, a reply cut off
3081
+ * by the token limit. Put inside the Provider it would be a second job hidden
3082
+ * in the node that calls the model; here it is a node on the receipt, with its
3083
+ * own timing and its own halt.
3084
+ *
3085
+ * ## `path` is what makes the result WIREABLE
3086
+ *
3087
+ * A data reference is `{node, port}` — there is no sub-path — so a downstream
3088
+ * `map` cannot iterate `plan.speakers` off a port carrying the whole document.
3089
+ * `path` is the answer: the parsed document is always on `json`, and `value`
3090
+ * and `items` carry whatever `path` selects, so one node serves both the step
3091
+ * that reads the whole plan and the block that iterates one list inside it.
3092
+ * `items` is `value` as a list — an absent or single value becomes an empty or
3093
+ * one-element list, so a map wired to it never has to defend itself.
3094
+ *
3095
+ * ## It halts rather than inventing an empty answer
3096
+ *
3097
+ * A reply this node cannot read is a model that did not do what it was asked,
3098
+ * and an empty object published as though it were an answer would travel
3099
+ * downstream as "nothing changed" — indistinguishable from a turn where
3100
+ * genuinely nothing did. `optional: true` on the node is how a spec says it can
3101
+ * live without the structure; the executor then records `recoveredAsEmpty` and
3102
+ * a reader can see which one happened.
3103
+ * @experimental
3104
+ */
3105
+ export const parseJson = pin(describeTaskDefinition({
3106
+ id: 'core:task/parse-json@1',
3107
+ i18n: { name: { en: 'Read JSON' } },
3108
+ timeoutMs: 1000,
3109
+ /**
3110
+ * A reply nobody can read subtracts the structure and nothing else.
3111
+ *
3112
+ * The binding answers `err` with the reason, the executor absorbs it as
3113
+ * `recoveredAsEmpty`, and every downstream port reads absent: a `map`
3114
+ * over the missing list runs zero times, a template renders no block. So
3115
+ * a model that ignored the schema costs a turn its plan, not its reply —
3116
+ * which is the same "an unavailable mechanism subtracts a signal, it
3117
+ * never disables a path" rule retrieval already works by.
3118
+ */
3119
+ optional: true,
3120
+ slots: {
3121
+ params: {
3122
+ kind: 'parameters',
3123
+ schema: {
3124
+ path: {
3125
+ type: 'string',
3126
+ quick: true,
3127
+ description: 'Which value inside the answer to publish on `value` and `items`, as a dotted path. Empty publishes the whole answer.',
3128
+ },
3129
+ },
3130
+ },
3131
+ },
3132
+ ports: {
3133
+ in: { text: S.textStream },
3134
+ out: {
3135
+ main: S.json,
3136
+ /** The whole parsed document, whatever `path` says. */
3137
+ json: S.json,
3138
+ /** The value at `path` — the document itself when `path` is empty. */
3139
+ value: S.json,
3140
+ /** That same value as a list, for a `map` to iterate. */
3141
+ items: S.json,
3142
+ },
3143
+ },
3144
+ }));
3145
+ /** @internal */
3146
+ export const roll = pin(describeTaskDefinition({
3147
+ id: 'chariot.dice-tray:roll@1',
3148
+ i18n: { name: { en: 'Roll dice' } },
3149
+ timeoutMs: 200,
3150
+ declaresRandomness: true,
3151
+ ports: {
3152
+ in: { notation: S.text },
3153
+ out: { main: S.json, total: S.json },
3154
+ },
3155
+ }));
3156
+ /** @internal */
3157
+ export const gate = pin(describeTaskDefinition({
3158
+ id: 'test:task/gate@1',
3159
+ timeoutMs: 500,
3160
+ ports: { in: { main: S.json }, out: { main: S.json } },
3161
+ }));
3162
+ /** @internal */
3163
+ export const slow = pin(describeTaskDefinition({
3164
+ id: 'test:task/slow@1',
3165
+ timeoutMs: 30,
3166
+ ports: { in: { main: S.json }, out: { main: S.json } },
3167
+ }));
3168
+ /** @internal */
3169
+ export const passthrough = pin(describeTaskDefinition({
3170
+ id: 'test:task/passthrough@1',
3171
+ timeoutMs: 500,
3172
+ toggleable: true,
3173
+ ports: { in: { main: S.json }, out: { main: S.json } },
3174
+ }));
3175
+ /** @internal */
3176
+ export const badToggleable = pin(describeTaskDefinition({
3177
+ id: 'test:task/bad-toggleable@1',
3178
+ timeoutMs: 500,
3179
+ toggleable: true,
3180
+ ports: { in: { main: S.text }, out: { main: S.image } },
3181
+ }));
3182
+ /**
3183
+ * A stream consumer with no `earlyExit` declared — the fixture that proves
3184
+ * stream-abandoned. Its `earlyExit: true` twin lives with the SDK's own suite
3185
+ * (`sdk-tests/fixtures.ts`), where the early-exit proofs are.
3186
+ * @internal
3187
+ */
3188
+ export const sloppyStream = pin(describeTaskDefinition({
3189
+ id: 'test:task/sloppy-stream@1',
3190
+ timeoutMs: 5000,
3191
+ ports: { in: { main: S.textStream }, out: { main: S.json } },
3192
+ }));
3193
+ // ── Forms (plans/29 R-15 *Forms* · *The line*; R-21 (5); 30 §U5d, 2026-09-17) ──
3194
+ /**
3195
+ * The form as a prompt and as a schema. Takes the block and the context the
3196
+ * builder compiled for the addressee, and publishes the context with the
3197
+ * question and the options laid in (`formQuestion`, `formOptions` — what the
3198
+ * assembly template renders under the transcript), the JSON Schema the
3199
+ * oracle answers against (`formAnswerSchema`: an enum of the option keys, or
3200
+ * the field schema), and the question as text. Pure; no model, no rows.
3201
+ * @experimental
3202
+ */
3203
+ export const formContext = pin(describeTaskDefinition({
3204
+ id: 'core:task/form-context@1',
3205
+ i18n: { name: { en: 'Form as prompt and schema' } },
3206
+ timeoutMs: 1000,
3207
+ ports: {
3208
+ in: { form: S.json, templateContext: S.templateContext },
3209
+ out: {
3210
+ main: S.templateContext,
3211
+ templateContext: S.templateContext,
3212
+ schema: S.json,
3213
+ question: S.text,
3214
+ },
3215
+ },
3216
+ }));
3217
+ /**
3218
+ * An oracle's question, as blocks. Takes the document a `generate-json@1`
3219
+ * produced — `{ question, options: [{ key, label }], addressee? }` — and the
3220
+ * function the options fire, and publishes a block list holding one
3221
+ * `choices` block: the question on it, its options carrying the keys,
3222
+ * addressed to whom the document names. The document's `addressee` is a
3223
+ * **name** the model read off the transcript or a participant reference; a
3224
+ * name is resolved against `cast` into `character:<id>` (or `envoy:<slug>`),
3225
+ * and the `addressee` in-port, when wired, wins over both. A name nobody in
3226
+ * the cast bears leaves the block unaddressed — buttons, not a form. The
3227
+ * host stamps the action identity and the block id at the write; this task
3228
+ * only shapes. `text` is the question as prose, for the row's own content,
3229
+ * so a transcript that reads content alone still carries what was asked. A
3230
+ * document with no options publishes an empty list and an empty text.
3231
+ * @experimental
3232
+ */
3233
+ export const makeChoices = pin(describeTaskDefinition({
3234
+ id: 'core:task/make-choices@1',
3235
+ i18n: { name: { en: 'Question as choices' } },
3236
+ timeoutMs: 1000,
3237
+ ports: {
3238
+ in: {
3239
+ /** The oracle's document: `{ question, options, addressee? }`. */
3240
+ json: S.json,
3241
+ /** The function every option fires — the block's `fn`. */
3242
+ fn: S.text,
3243
+ /**
3244
+ * The identity of the declaration the options fire, when it is
3245
+ * another spec's (`core:spec/adventure-answer#answer`). Absent,
3246
+ * the host stamps this spec's own declaration for `fn` at the
3247
+ * write.
3248
+ */
3249
+ action: S.text,
3250
+ /** Who the question is put to. Wired, it wins over the document's. */
3251
+ addressee: S.participantRef,
3252
+ /** The cast, to resolve a name the document used into a reference. */
3253
+ cast: S.sessionCast,
3254
+ /**
3255
+ * What the question is about, by name — stamped on the block
3256
+ * as its `referent` and handed back by `read-answer@1` to the
3257
+ * run the press fires (lair pass B12, 2026-09-27: the room the
3258
+ * party knocked at). Blank or absent writes none.
3259
+ */
3260
+ referent: S.text,
3261
+ /**
3262
+ * Where the question was asked **from**, by name — stamped on
3263
+ * the block as its `vantage` and handed back by
3264
+ * `read-answer@1`, beside `referent` (plan A27, 2026-09-30:
3265
+ * the room the Lair's planner said the party stood in as
3266
+ * they knocked). JSON because it is usually read off a
3267
+ * model's document (`parse-json@1`'s `value`); anything but
3268
+ * a non-blank string writes none.
3269
+ */
3270
+ vantage: S.json,
3271
+ },
3272
+ out: {
3273
+ main: S.json,
3274
+ blocks: S.json,
3275
+ /** The question as prose — the row's content. */
3276
+ text: S.text,
3277
+ /** Who the block was addressed to, resolved; null when nobody. */
3278
+ addressee: S.participantRef,
3279
+ },
3280
+ },
3281
+ }));
3282
+ /**
3283
+ * A form's answer, port by port — for the action a form fires. Takes the
3284
+ * inlet's `payload` (what the press sent) and `form` (the block facts the
3285
+ * host read off the row) and publishes the parts a spec wires: the chosen
3286
+ * option's key and label, the addressee and their character row, the
3287
+ * question, and the answered values. Pure.
3288
+ * @experimental
3289
+ */
3290
+ export const readAnswer = pin(describeTaskDefinition({
3291
+ id: 'core:task/read-answer@1',
3292
+ i18n: { name: { en: 'Read the answer' } },
3293
+ timeoutMs: 1000,
3294
+ ports: {
3295
+ in: { payload: S.json, form: S.json },
3296
+ out: {
3297
+ main: S.json,
3298
+ /** The chosen option's key (`choices`), else null. */
3299
+ choice: S.text,
3300
+ /** The chosen option's label, else null. */
3301
+ label: S.text,
3302
+ /** Who answered, as a participant reference — the form's addressee. */
3303
+ addressee: S.participantRef,
3304
+ /** The addressee's character row, null for an envoy or a person. */
3305
+ characterId: S.rowIds,
3306
+ question: S.text,
3307
+ /**
3308
+ * What the question was about, by name — the block's
3309
+ * `referent`, as the asking run stamped it (lair pass B12);
3310
+ * empty when it named nothing, never null, so a write wired
3311
+ * to it still offers the field at its review gate (a review
3312
+ * form shows only the fields a payload carries).
3313
+ */
3314
+ referent: S.text,
3315
+ /**
3316
+ * Where the question was asked from, by name — the block's
3317
+ * `vantage`, as the asking run stamped it (plan A27); null
3318
+ * when it named nowhere.
3319
+ */
3320
+ vantage: S.json,
3321
+ /** The whole answer: `{ choice }` or the entered values. */
3322
+ values: S.json,
3323
+ },
3324
+ },
3325
+ }));
3326
+ // ── Summarization ───────────────────────────────────────────────────────────
3327
+ /**
3328
+ * Cut the messages into batches a model can hold.
3329
+ *
3330
+ * A Task, not a Query: the cut is a *decision* — how many tokens per batch, and
3331
+ * therefore how much context each draft is written against — and it is the
3332
+ * first parameter a user with long posts reaches for.
3333
+ * @internal
3334
+ */
3335
+ export const batchMessages = pin(describeTaskDefinition({
3336
+ id: 'core:task/batch-messages@1',
3337
+ i18n: { name: { en: 'Batch messages' } },
3338
+ timeoutMs: 2000,
3339
+ slots: {
3340
+ /**
3341
+ * The window the cut is clamped to — the same slot, by reference,
3342
+ * that the drafting step generates against.
3343
+ *
3344
+ * The context window belongs to the sampling config, never to a knob
3345
+ * on a node (17 §1a), and the executor resolves a `sampling` slot to
3346
+ * the config's switched-on *values* — so this stays a pure Task
3347
+ * reading data it was handed rather than a Query looking one up. Same
3348
+ * shape and same reason as `core:task/context-budget@1`.
3349
+ *
3350
+ * ⚠ Wire it as a REFERENCE to the drafting oracle's sampling slot
3351
+ * (`slot.samplingOf(...)`), not as a picker of its own. A batch cut
3352
+ * against one window and drafted against another is wrong in the
3353
+ * direction that overflows, silently — and unlike the assembled
3354
+ * context there is no truncation on this path to catch it, because
3355
+ * the batch prompt is injected whole.
3356
+ */
3357
+ sampling: { kind: 'sampling', quick: true },
3358
+ params: {
3359
+ kind: 'parameters',
3360
+ facet: 'weights',
3361
+ schema: {
3362
+ /**
3363
+ * The chat half of a batch prompt, and only that half — the
3364
+ * template around it and the room the draft is written back
3365
+ * into are a reserve the binding adds on top, which is why
3366
+ * this can be raised right up to the window minus that
3367
+ * reserve and no further.
3368
+ *
3369
+ * ⚠ Bigger is not better. Long-context models degrade in the
3370
+ * middle, so this is a QUALITY point rather than a fraction
3371
+ * of whatever window happens to be available: nothing scales
3372
+ * it up to fill a large one, and the window is only ever a
3373
+ * ceiling on what an admin asks for.
3374
+ *
3375
+ * 2560 is 0.5's effective batch (`4096 - 1500`) at a round
3376
+ * 2.5 Ki, so arriving here re-tunes nobody.
3377
+ */
3378
+ batchTokens: {
3379
+ type: 'integer',
3380
+ default: 2560,
3381
+ label: { en: 'How much chat each batch holds' },
3382
+ description: {
3383
+ en: 'Tokens of chat one summary draft is written from. Capped by the drafting step\u2019s Context Tokens, less room for the prompt and the draft itself.',
3384
+ },
3385
+ },
3386
+ minBatchMessages: {
3387
+ type: 'integer',
3388
+ default: 1,
3389
+ description: 'Never cut a batch smaller than this many messages.',
3390
+ },
3391
+ },
3392
+ },
3393
+ },
3394
+ ports: {
3395
+ /**
3396
+ * `attachments` (2026-10-03, owner ruling on the attachments
3397
+ * follow-ups): the files by message, from
3398
+ * `core:query/history-attachments@1`. Each message that shows
3399
+ * files is batched with a placeholder per file after its text —
3400
+ * `[image: cat.png — a grey cat]`, `[file: notes.txt]` — and the
3401
+ * cut counts them, so a message that is only a picture still
3402
+ * reaches the draft as something. Unwired, or a message with no
3403
+ * files, and the message is batched exactly as it was.
3404
+ */
3405
+ in: { messages: S.messages, attachments: S.mediaByMessage },
3406
+ out: { main: S.drafts, batches: S.drafts },
3407
+ },
3408
+ }));
3409
+ // ── Stats and states ────────────────────────────────────────────────────────
3410
+ /** @experimental */
3411
+ export const setState = pin(describeTaskDefinition({
3412
+ id: 'core:task/set-state@1',
3413
+ i18n: { name: { en: 'Set state' } },
3414
+ timeoutMs: 5000,
3415
+ slots: {
3416
+ params: {
3417
+ kind: 'parameters',
3418
+ schema: {
3419
+ mode: {
3420
+ type: 'enum',
3421
+ of: ['propose', 'apply'],
3422
+ members: [
3423
+ {
3424
+ key: 'propose',
3425
+ label: { en: 'Propose' },
3426
+ description: { en: 'Holds the changes for the player to accept or reject.' },
3427
+ },
3428
+ {
3429
+ key: 'apply',
3430
+ label: { en: 'Apply' },
3431
+ description: {
3432
+ en: 'Writes them immediately, stamped with this run. Only where the pipeline itself decided the number.',
3433
+ },
3434
+ },
3435
+ ],
3436
+ default: 'propose',
3437
+ quick: true,
3438
+ description: "Whether the changes wait for the player or are written at once. Use Apply only where the pipeline itself decided the number.",
3439
+ },
3440
+ },
3441
+ },
3442
+ },
3443
+ ports: {
3444
+ // [{ owner: { kind, id }, slotId, value, base? } | { owner, entryId, delta, base? }]
3445
+ // `scope` is what says which session, and therefore which message a
3446
+ // change is anchored to — a change with no anchor is one a swipe
3447
+ // could not take back.
3448
+ in: {
3449
+ changes: S.json,
3450
+ scope: S.sessionScope,
3451
+ /**
3452
+ * The **state version** the changes are deltas against (plans/29
3453
+ * R-15 *Staleness and order*; U5f) — the session-state query's
3454
+ * `version`, for every change that does not carry its own
3455
+ * `base`. In `apply` mode a base behind the current version is
3456
+ * **rebased**: a change whose slot is untouched since the base
3457
+ * still holds and is applied; one whose slot moved is put on
3458
+ * `refused` with the versions named, and the next turn's
3459
+ * `resolve-state-changes` re-resolves it — a run never re-enters
3460
+ * an earlier node. In `propose` mode the base is stamped on the
3461
+ * proposal for the accept to judge the same way. Optional: with
3462
+ * none, the write is against whatever is current.
3463
+ */
3464
+ base: S.json,
3465
+ /**
3466
+ * **The row the WORLD's changes are filed at** (lair pass R8,
3467
+ * 2026-09-28): a message this run wrote earlier, as that
3468
+ * write's result. Optional, and only for world-owned changes
3469
+ * (the session and its places); a cast member's change still
3470
+ * files at that member's own latest line (the turn lock).
3471
+ * Declared, never inferred: the Lair wires its Sanctum beats
3472
+ * row, so the turn's world changes show in the Sanctum beside
3473
+ * the plan that made them rather than on whichever delver
3474
+ * spoke last. A write-result only — a run may name its OWN
3475
+ * row, which is open to it for the rest of its turn; any
3476
+ * other value is refused.
3477
+ */
3478
+ worldRow: S.writeResult,
3479
+ },
3480
+ /**
3481
+ * What happened, as three lists: `applied` for rows written,
3482
+ * `proposed` for rows held, `refused` for the sentences — a value
3483
+ * the slot does not accept, or a slot that moved since `base`.
3484
+ * The first two are always present and one of them is always
3485
+ * empty, so nothing downstream decides which mode ran by looking
3486
+ * for a missing key.
3487
+ */
3488
+ out: { main: S.json, applied: S.json, proposed: S.json, refused: S.json },
3489
+ },
3490
+ }));
3491
+ /**
3492
+ * A room name, unless something already describes it (lair pass R7,
3493
+ * 2026-09-28; replaced `core:task/unlisted-name@1`).
3494
+ *
3495
+ * The Lair's planner names the room the party are about to walk into when it
3496
+ * thinks nobody has built it, and the turn stops to ask the dungeon's master
3497
+ * to describe it (owner ruling 2, 2026-09-28: *ask, unless it is already
3498
+ * described in prose or the lorebook*). This is the deterministic check after
3499
+ * the planner's judgement. Lookups, in order; the first hit wins:
3500
+ *
3501
+ * 1. **Entry.** An entry whose `name`, or any of whose `keys` (a list, or a
3502
+ * comma-separated string, split on commas), is the same name. Entries on
3503
+ * `locationEntries` are checked before `entries`. Any entry type counts.
3504
+ * → `describedBy` `entry`, `entryId`.
3505
+ * 2. **Prose.** Among the newest `window` rows of `messages` on the
3506
+ * `channels` named, the newest row whose author is **a person, an envoy or
3507
+ * a speakerless reply** — never a character: a delver's line naming a door
3508
+ * is not a description — with a paragraph (split on blank lines) that
3509
+ * names the name and holds at least `minWords` words besides it.
3510
+ * → `describedBy` `prose`, `passage` (that paragraph).
3511
+ * 3. Otherwise `undescribed` is the name, trimmed.
3512
+ *
3513
+ * "The same name" and "names the name" are the SDK's name rule
3514
+ * (`normalizeName`, `sameName`, `passageNaming` in `names.ts`): NFKC, case,
3515
+ * a possessive `'s`, apostrophes and punctuation, and one leading article —
3516
+ * then whole equality, never a substring ("the vault" is not "the sunken
3517
+ * vault").
3518
+ *
3519
+ * Pure: the rows come in on ports (a `core:query/lorebook-entries@1` listing,
3520
+ * a `core:query/session-history@1` read), so a genre decides what is read
3521
+ * and the task decides only what counts. `channels` filters the rows by their
3522
+ * own `channel` (a bare slug is every lane of it), so a core task never
3523
+ * hard-codes a genre's slug: a spec that wants a side channel's prose to count
3524
+ * reads it and names it here.
3525
+ *
3526
+ * ## Which room is this one (places plan B6, 2026-09-29)
3527
+ *
3528
+ * The same lookup answers the Lair's other question: *which room do the party
3529
+ * stand in?* — the world's `location` stat, resolved against the rooms, so
3530
+ * *Answer the door* can link the room it writes to it. Two things make that
3531
+ * wireable:
3532
+ *
3533
+ * - **`path`**: a data reference has no sub-path, and the location sits
3534
+ * inside a `core:query/session-state@1` document, so `path` says where the
3535
+ * name is inside `name` (`world.location`) — the dotted spelling
3536
+ * `parse-json@1` and `generate-json@1` read. Empty reads `name` itself.
3537
+ * - **A lore reference is its entry.** A location stat set to a place entry
3538
+ * holds `{ entryId }`, not words, and naming it again by its title would
3539
+ * find a namesake. So a value with an `entryId` is answered by the listed
3540
+ * entry with that id (`describedBy` `entry`), and by nothing when no
3541
+ * listing holds it — archived, or hidden from this read.
3542
+ * - **`fallbackName`** (plan A27, 2026-09-30): what to look for when `name`
3543
+ * (at `path`) names nothing — for the Lair, the room its planner said the
3544
+ * party stood in as they knocked (the knock's `vantage`). The world's
3545
+ * value wins and the hint stands in only while it names nothing: the
3546
+ * order a play turn's prompts read the location in (the world's value,
3547
+ * else that turn's plan). No prompt in the knock turn shows the hinted
3548
+ * room; it is the planner's own answer for that turn. Read whole, by the
3549
+ * same rules as `name`.
3550
+ * @experimental
3551
+ */
3552
+ export const undescribedName = pin(describeTaskDefinition({
3553
+ id: 'core:task/undescribed-name@1',
3554
+ i18n: { name: { en: 'Undescribed name' } },
3555
+ timeoutMs: 500,
3556
+ slots: {
3557
+ params: {
3558
+ kind: 'parameters',
3559
+ facet: 'behavior',
3560
+ schema: {
3561
+ /**
3562
+ * Whose prose counts, by channel slug. `main` by default;
3563
+ * the Lair adds its side channel so a room its master
3564
+ * described there counts too.
3565
+ */
3566
+ channels: {
3567
+ type: 'string',
3568
+ list: true,
3569
+ default: ['main'],
3570
+ label: { en: 'Channels read' },
3571
+ description: {
3572
+ en: 'Which channels’ messages can describe a room. A slug covers every lane of that channel.',
3573
+ },
3574
+ },
3575
+ /** How far back prose counts, in rows across those channels. */
3576
+ window: {
3577
+ type: 'integer',
3578
+ default: 40,
3579
+ min: 1,
3580
+ max: 500,
3581
+ label: { en: 'Messages read' },
3582
+ description: {
3583
+ en: 'How many of the newest messages on those channels are searched for a description.',
3584
+ },
3585
+ },
3586
+ /**
3587
+ * How long a paragraph must be to be a description rather
3588
+ * than a mention: words besides the name itself.
3589
+ */
3590
+ minWords: {
3591
+ type: 'integer',
3592
+ default: 12,
3593
+ min: 0,
3594
+ max: 500,
3595
+ label: { en: 'Words to describe' },
3596
+ description: {
3597
+ en: 'How many words, besides the name, a paragraph needs before it counts as describing the room rather than mentioning it.',
3598
+ },
3599
+ },
3600
+ /**
3601
+ * Where the name is inside `name`, as a dotted path (places
3602
+ * plan B6) — the Lair reads `world.location` off a
3603
+ * session-state document. Empty reads `name` itself.
3604
+ */
3605
+ path: {
3606
+ type: 'string',
3607
+ default: '',
3608
+ label: { en: 'Where the name is' },
3609
+ description: {
3610
+ en: 'Where the name sits inside what is wired in, as a dotted path such as world.location. Leave it empty when the name itself is wired in.',
3611
+ },
3612
+ },
3613
+ },
3614
+ },
3615
+ },
3616
+ ports: {
3617
+ in: {
3618
+ /**
3619
+ * The name to look for — JSON rather than text because it is
3620
+ * usually read off a model's document (`parse-json@1`'s
3621
+ * `value`), or a document holding it at `path`; anything but a
3622
+ * string is no name, and nothing is undescribed — save a lore
3623
+ * reference (`{ entryId }`), which is the listed entry it
3624
+ * references (B6).
3625
+ */
3626
+ name: S.json,
3627
+ /**
3628
+ * What to look for when `name` at `path` names nothing — a
3629
+ * name or a lore reference, read whole (no `path`). Unwired,
3630
+ * nothing is looked for in its place.
3631
+ */
3632
+ fallbackName: S.json,
3633
+ /** Location entries (rows with `id`, `name`, `keys`), checked first. */
3634
+ locationEntries: S.json,
3635
+ /** The rest of the book, any entry type, checked second. */
3636
+ entries: S.json,
3637
+ /** Recent rows, ascending, each carrying its `channel`. */
3638
+ messages: S.messages,
3639
+ },
3640
+ out: {
3641
+ main: S.text,
3642
+ /** `name`, trimmed, when nothing describes it; else empty. */
3643
+ undescribed: S.text,
3644
+ /** `entry`, `prose`, or empty when nothing describes it. */
3645
+ describedBy: S.text,
3646
+ /** The describing entry's id, or null. */
3647
+ entryId: S.json,
3648
+ /** The describing paragraph, or empty. */
3649
+ passage: S.text,
3650
+ },
3651
+ },
3652
+ }));
3653
+ // ── D-4a: pure pick and cast options ──────────────────────────── start ──────
3654
+ /**
3655
+ * The item this session picks — a pure function of a key and a list.
3656
+ *
3657
+ * ## The gap it closes
3658
+ *
3659
+ * Nothing in the bound catalogue evaluated a pure function over run data. The
3660
+ * closest was `core:task/turn-random@1`, which draws on `ctx.random` — seeded
3661
+ * per RUN, so it answers differently every turn — and that is right for whose
3662
+ * turn it is and useless for a fact that has to stay the same all game. So a
3663
+ * genre wanting its hidden fact **chosen** (which suspect did it, which lore
3664
+ * entry the answer is) had two options and neither was honest: ask a model,
3665
+ * which can change its mind between two answers, or write it into the one
3666
+ * per-session store a spec can reach — the attribute-slot ledger, which the
3667
+ * player's own state panel renders. Whodunit shipped adjudicating from an
3668
+ * authored case file for exactly this reason, with its rendezvous rule
3669
+ * published, tested and called by nobody.
3670
+ *
3671
+ * Derived instead: the create run and every later turn hand the same
3672
+ * `scopeKey` and the same list to this node and reach the same item, with
3673
+ * nothing written down anywhere and nothing on screen.
3674
+ *
3675
+ * ## Rendezvous hashing, and why not `list[hash % length]`
3676
+ *
3677
+ * Each candidate is scored on its own — `hash(key + '#' + itemKey)` — and the
3678
+ * highest wins (`rendezvousPick`, SDK `pick.ts`, the one implementation the
3679
+ * app's binding and a plugin's own picker share). A modulo into the list
3680
+ * moves *every* session's answer when the list length changes; rendezvous
3681
+ * moves it exactly when the newcomer's own score wins, so seating a fifth
3682
+ * suspect mid-case displaces the culprit in about a fifth of sessions and
3683
+ * leaves the rest alone. The hash carries murmur3's `fmix32` finalizer
3684
+ * because the comparison is over whole hashes and plain FNV-1a leaves the
3685
+ * high bits systematic for ids differing in their last digit — measured at
3686
+ * 49% of sessions for the first of three, instead of 33%.
3687
+ *
3688
+ * ## `scopeKey` is the session's address, never the run's seed
3689
+ *
3690
+ * A spec wires `$.input.sessionScope` (or a literal) — something durable. The
3691
+ * run's seed is a different string every turn and a pick keyed on it would
3692
+ * move between two questions. It is `scopeKey` and not `key` (R3, named
3693
+ * 2026-09-17, before anything shipped): *key* alone is the option key on a
3694
+ * choice, the identity a candidate is scored under, and a settings field's
3695
+ * name, and this port is none of them — it is the scope the pick is made
3696
+ * within.
3697
+ *
3698
+ * ## No `optional`
3699
+ *
3700
+ * Absent, so an empty list is the run's failure. A genre that derived its
3701
+ * secret from this node cannot be handed "nobody" and carry on, and
3702
+ * `optional: true` would turn that into an `ok` with every downstream port
3703
+ * reading absent — indistinguishable from a turn where the pick genuinely
3704
+ * chose nothing.
3705
+ * @experimental
3706
+ */
3707
+ export const pickByHash = pin(describeTaskDefinition({
3708
+ id: 'core:task/pick-by-hash@1',
3709
+ i18n: {
3710
+ name: { en: 'Pick by hash' },
3711
+ description: {
3712
+ en: 'Picks one entry of a list for this session, the same one every time, without writing anything down. Adding an entry almost never moves the pick.',
3713
+ },
3714
+ },
3715
+ /** Pure arithmetic over a list that is already in memory. */
3716
+ timeoutMs: 500,
3717
+ slots: {
3718
+ params: {
3719
+ kind: 'parameters',
3720
+ schema: {
3721
+ /**
3722
+ * Which field on each entry identifies it.
3723
+ *
3724
+ * The identity is what the hash is taken over, so it
3725
+ * decides the answer: two runs that disagree about it
3726
+ * disagree about the pick. Absent, an entry that IS a
3727
+ * string is its own identity and anything else is
3728
+ * identified by `id` — the two shapes a core list
3729
+ * actually arrives in (`cast-choices` publishes `key`,
3730
+ * a lore listing publishes rows with `id`).
3731
+ *
3732
+ * ⚠ It must be **stable**: a name the author may edit
3733
+ * moves the pick the day they edit it. A row id does not.
3734
+ */
3735
+ by: {
3736
+ type: 'string',
3737
+ quick: true,
3738
+ label: { en: 'Identified by' },
3739
+ description: 'Which field on each entry identifies it — a row id, or the option key. Leave it empty for plain strings, or for rows with an `id`.',
3740
+ },
3741
+ },
3742
+ },
3743
+ },
3744
+ ports: {
3745
+ in: {
3746
+ /** The list to pick from. */
3747
+ items: S.json,
3748
+ /**
3749
+ * The stable key this session picks under.
3750
+ *
3751
+ * Either the session's **scope** — `$.input.sessionScope`,
3752
+ * which the binding spells `session:<id>` — or a literal
3753
+ * string for a pick that is not per-session.
3754
+ *
3755
+ * ⚠ `S.json` rather than `S.text`, and not for want of a
3756
+ * type. `session-scope@1` is not assignable to `text@1`, and
3757
+ * there is no text-shaped port anywhere that carries a
3758
+ * session's identity — so a `text` port here could be wired
3759
+ * to a literal and to nothing else, which would give every
3760
+ * session of a genre the same answer. `json` is the
3761
+ * permissive sink, so the scope wires, a literal wires, and
3762
+ * anything a spec wires that the binding cannot read as a key
3763
+ * halts with a sentence naming what to wire instead.
3764
+ */
3765
+ scopeKey: S.json,
3766
+ },
3767
+ out: {
3768
+ /** The chosen entry, whole and exactly as it arrived. */
3769
+ main: S.json,
3770
+ /**
3771
+ * Where it sat in the list **as handed in**, not among the
3772
+ * identifiable entries. `pickIndex` rather than `index`
3773
+ * (R3): a bare *index* is a database index, a message's
3774
+ * position and a list offset all at once.
3775
+ */
3776
+ pickIndex: S.json,
3777
+ /**
3778
+ * The identity it won under — the string the hash was taken
3779
+ * over. This is the side a later junction compares an answer
3780
+ * against with `equalsPath`, which is why it is published at
3781
+ * all: the chosen item is a document, and a predicate
3782
+ * compares keys.
3783
+ */
3784
+ chosenKey: S.text,
3785
+ },
3786
+ },
3787
+ }));
3788
+ /**
3789
+ * The room, as options a question can be put with.
3790
+ *
3791
+ * `core:task/make-choices@1` needs `{ key, label }` options and nothing in
3792
+ * core turned a cast into that list, so both Whodunit pickers spend a model
3793
+ * call whose entire job is to read the cast back out as JSON — a request, a
3794
+ * schema and a wait, for a fact the run already held. Worse than slow: a
3795
+ * model enumerating the room can misspell a suspect, invent one, or leave one
3796
+ * out, and the options it writes are what the player may press.
3797
+ *
3798
+ * Pure. The cast read is the fact; this shapes it.
3799
+ *
3800
+ * ## The key is a participant reference
3801
+ *
3802
+ * `character:<id>`, the reference vocabulary (R-18 (3)) — not a name, which
3803
+ * two cast members can share and an author can edit, and not a bare id, which
3804
+ * says nothing about what it identifies. It survives the round trip: the key
3805
+ * lands on the pressed option, `core:task/read-answer@1` publishes it as
3806
+ * `choice`, and a junction can compare that against a
3807
+ * `core:task/pick-by-hash@1` `chosenKey` derived over these same options.
3808
+ *
3809
+ * ## Who is in the list
3810
+ *
3811
+ * Live seats only — a departed or inactive cast member is not somebody a
3812
+ * question may be put about — and **never an envoy**: `exclude` offers no way
3813
+ * to turn one off, and a narrator among the suspects with no way to remove it
3814
+ * is worse than a narrator a spec has to add for itself.
3815
+ *
3816
+ * ## It publishes the whole document, not only the list (ruled (b), 2026-09-17)
3817
+ *
3818
+ * `make-choices@1` reads `{ question, options, addressee? }` off ONE `json`
3819
+ * port, so a spec handed only `options` still has nowhere to put the question
3820
+ * — and the obvious repair, a second in-port on `make-choices`, would move
3821
+ * the hash of a node that is published and wired into shipped specs. So the
3822
+ * shaping happens on this side: `question` comes in, `json` goes out in
3823
+ * exactly the shape that port reads, and the two nodes wire straight to each
3824
+ * other with no model call in between. `options` stays beside it for a spec
3825
+ * that wants the bare list (a pick over the same options, a `each` over the
3826
+ * room), which is the same value the document carries.
3827
+ *
3828
+ * No `addressee`: the document's is a **name** `make-choices` resolves
3829
+ * against the cast, and this node has no more idea who the question is for
3830
+ * than the cast document does. A spec that knows wires `make-choices`'s own
3831
+ * `addressee` port, which wins over the document's anyway.
3832
+ * @experimental
3833
+ */
3834
+ export const castChoices = pin(describeTaskDefinition({
3835
+ id: 'core:task/cast-choices@1',
3836
+ i18n: {
3837
+ name: { en: 'The cast as choices' },
3838
+ description: {
3839
+ en: 'Turns the session’s cast into the option list a question is asked with — one option per live character, keyed by who they are.',
3840
+ },
3841
+ },
3842
+ timeoutMs: 500,
3843
+ slots: {
3844
+ params: {
3845
+ kind: 'parameters',
3846
+ schema: {
3847
+ /**
3848
+ * Which half of the room to leave out.
3849
+ *
3850
+ * A persona is a character the player voices (0132), so
3851
+ * both halves are cast members and which one a question
3852
+ * is about depends entirely on the question: *who do you
3853
+ * accuse* is asked about the suspects and must not offer
3854
+ * the detective, while *who do you play* is the other way
3855
+ * round.
3856
+ */
3857
+ exclude: {
3858
+ type: 'enum',
3859
+ of: ['none', 'personas', 'characters'],
3860
+ members: [
3861
+ { key: 'none', label: { en: 'Nobody' } },
3862
+ {
3863
+ key: 'personas',
3864
+ label: { en: 'Personas' },
3865
+ description: { en: 'The characters the players voice.' },
3866
+ },
3867
+ {
3868
+ key: 'characters',
3869
+ label: { en: 'Characters' },
3870
+ description: { en: 'The rest of the cast.' },
3871
+ },
3872
+ ],
3873
+ default: 'none',
3874
+ quick: true,
3875
+ label: { en: 'Left out' },
3876
+ description: 'Leave out the characters the players voice (personas), the rest of the cast (characters), or nobody.',
3877
+ },
3878
+ },
3879
+ },
3880
+ },
3881
+ ports: {
3882
+ in: {
3883
+ cast: S.sessionCast,
3884
+ /**
3885
+ * The question the options answer — the prose that sits
3886
+ * above them on the block, and the row's own content.
3887
+ *
3888
+ * Unwired it is the empty string, and `make-choices@1`
3889
+ * publishes no block for a document with no question — the
3890
+ * same silence it answers an empty option list with, rather
3891
+ * than a block asking nothing.
3892
+ */
3893
+ question: S.text,
3894
+ },
3895
+ out: {
3896
+ /** `{ key, label }[]`, in seating order: characters, then personas. */
3897
+ main: S.json,
3898
+ options: S.json,
3899
+ /**
3900
+ * `{ question, options }` — the document
3901
+ * `core:task/make-choices@1` reads off its own `json` port,
3902
+ * in exactly that shape, so the two wire straight to each
3903
+ * other and no oracle stands between a cast read and the
3904
+ * question it is asked with.
3905
+ */
3906
+ json: S.json,
3907
+ },
3908
+ },
3909
+ }));
3910
+ // ── D-4a: pure pick and cast options ────────────────────────────── end ──────
3911
+ // ── Contracts batch 2: the two-document pair ──────────────────── start ──────
3912
+ /**
3913
+ * Two values, side by side in one document, under names a path can read.
3914
+ *
3915
+ * ## The gap it closes
3916
+ *
3917
+ * A junction branches on **one** port, and `equalsPath` compares two paths of
3918
+ * **one** document (D-4a). So the grammar can ask *is the accused the culprit?*
3919
+ * only once something has put the accused and the culprit in the same
3920
+ * document, and nothing in core did: no task merged two json ports, and the
3921
+ * obvious repair — a second in-port on the junction — is not a repair, it is a
3922
+ * different clause. Whodunit shipped with its verdict's `accused` node wired to
3923
+ * nothing for exactly this reason.
3924
+ *
3925
+ * Pure, and deliberately the dullest node in the catalogue. It computes
3926
+ * nothing, decides nothing and reads nothing: it is the shape change that lets
3927
+ * a predicate see both sides.
3928
+ *
3929
+ * ## ⚠ An absent side is **omitted**, never null
3930
+ *
3931
+ * This is the whole of the node's behaviour worth stating. `predicateHolds`
3932
+ * answers `false` when either side of an `equalsPath` is `undefined` — two
3933
+ * absences are not a match — and that rule is what makes a junction over this
3934
+ * document **safe on a turn where nothing was decided**: a run in which the
3935
+ * accuse never happened has no `accused`, so
3936
+ * `{ path: 'accused', equalsPath: 'culprit' }` fires nothing, and the spec
3937
+ * falls through to its default branch.
3938
+ *
3939
+ * Writing `null` for an unwired side would destroy that. `null` is a *value*:
3940
+ * `readPath` returns it, it is not `undefined`, and `null === null` — so a
3941
+ * document with both sides missing would compare **equal** and the verdict
3942
+ * branch would fire on a turn where nobody accused anybody. The omission is
3943
+ * therefore load-bearing and pinned by a test, not an implementation detail of
3944
+ * the handler.
3945
+ *
3946
+ * The same rule covers the side that is wired but produced nothing: a port
3947
+ * resolving absent is absent here too. What arrives is written; what does not
3948
+ * is not mentioned.
3949
+ *
3950
+ * ## The names are the spec's
3951
+ *
3952
+ * `firstKey` and `secondKey` decide what the document's keys are called, so
3953
+ * the same node reads as `{ accused, culprit }` in one spec and
3954
+ * `{ guess, secret }` in another and the predicate paths are the spec's own
3955
+ * words. Defaults `first` and `second`, which are honest and nobody would
3956
+ * write a predicate against on purpose.
3957
+ *
3958
+ * Two keys that are the same string are refused rather than collapsed: one key
3959
+ * holding whichever side was written last is a document that compares equal to
3960
+ * itself, which is the one answer this node must never produce by accident.
3961
+ * @experimental
3962
+ */
3963
+ export const pair = pin(describeTaskDefinition({
3964
+ id: 'core:task/pair@1',
3965
+ i18n: {
3966
+ name: { en: 'Pair' },
3967
+ description: {
3968
+ en: 'Puts two values side by side in one document, under names you choose, so a branch can compare them. Whichever side is missing is left out.',
3969
+ },
3970
+ },
3971
+ /** Two reads and an object literal. */
3972
+ timeoutMs: 500,
3973
+ slots: {
3974
+ params: {
3975
+ kind: 'parameters',
3976
+ schema: {
3977
+ firstKey: {
3978
+ type: 'string',
3979
+ default: 'first',
3980
+ quick: true,
3981
+ label: { en: 'Name for the first value' },
3982
+ description: 'What the first value is called in the document — the word a branch reads it by.',
3983
+ },
3984
+ secondKey: {
3985
+ type: 'string',
3986
+ default: 'second',
3987
+ quick: true,
3988
+ label: { en: 'Name for the second value' },
3989
+ description: 'What the second value is called in the document. It must differ from the first.',
3990
+ },
3991
+ },
3992
+ },
3993
+ },
3994
+ ports: {
3995
+ in: {
3996
+ /** Whatever the spec wants compared. Absent is a legal input. */
3997
+ first: S.json,
3998
+ second: S.json,
3999
+ },
4000
+ out: {
4001
+ /**
4002
+ * `{ [firstKey]: first, [secondKey]: second }`, with an absent
4003
+ * side **omitted** — see the note above; it is the property a
4004
+ * junction over this document depends on.
4005
+ */
4006
+ main: S.json,
4007
+ },
4008
+ },
4009
+ }));
4010
+ // ── Contracts batch 2: the two-document pair ────────────────────── end ──────
4011
+ //# sourceMappingURL=tasks.js.map