@serene-pub/contracts 0.6.0-pr-2 → 0.6.0-pr-5

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,4654 @@
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 — 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, 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 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
+ * (owner rulings of 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.** 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.
214
+ *
215
+ * Shape `S.decisions`: 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 (`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 (Assemble keeps only what
268
+ * is genuinely global: total budget, truncation policy, and how weights
269
+ * 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**
280
+ * (2026-09-16). `share`, `maxEntries` and `minEntries` — five-band maps keyed
281
+ * `{messages, worldLore, characterLore, history, relationships}` — were a
282
+ * per-source table the design rejects, 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
+ * 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
+ * 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.
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: 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.
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 precedence the design 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: 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. 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: 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.
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
+ * 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) —
831
+ * `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
+ * (2026-09-29), 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. 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). 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.
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: media markers, inlined text files and placeholders,
1145
+ * from `core:task/place-attachments@1`. Absent on a line
1146
+ * with no files, and on every line of a spec with no
1147
+ * placement step.
1148
+ */
1149
+ attachments: {
1150
+ type: 'string',
1151
+ optional: true,
1152
+ description: "The line's attachments, placed: files the model receives, text files inlined, and names for the rest.",
1153
+ },
1154
+ },
1155
+ },
1156
+ },
1157
+ injectionsByIndex: {
1158
+ type: 'record',
1159
+ description: 'Script injections, keyed by the message index they render at.',
1160
+ of: {
1161
+ type: 'list',
1162
+ of: { type: 'object', fields: { role: { type: 'string' }, content: { type: 'string' } } },
1163
+ },
1164
+ },
1165
+ budget: {
1166
+ type: 'object',
1167
+ description: 'The token budget this prompt was allocated against.',
1168
+ fields: { total: { type: 'number' }, used: { type: 'number' }, remaining: { type: 'number' } },
1169
+ },
1170
+ postHistory: {
1171
+ type: 'object',
1172
+ optional: true,
1173
+ description: 'The post-history block, placed: render it when the loop reaches targetIndex.',
1174
+ fields: {
1175
+ targetIndex: { type: 'number' },
1176
+ instructions: { type: 'string', optional: true },
1177
+ charInstructions: { type: 'string', optional: true },
1178
+ exampleDialogue: { type: 'string', optional: true },
1179
+ hasContent: { type: 'boolean' },
1180
+ },
1181
+ },
1182
+ /**
1183
+ * 🚧 The session's **author's note**, placed (2026-10-02) — the
1184
+ * person's own steering text for this session, at its own depth, with no
1185
+ * token trigger. Not the post-history reminder: that one is the pipeline's
1186
+ * and the card's "how to respond"; this is the person's "what is true now".
1187
+ * Absent for a genre that declares no `authorsNote` field.
1188
+ */
1189
+ authorsNote: {
1190
+ type: 'object',
1191
+ optional: true,
1192
+ description: 'The session’s author’s note, placed: render it when the loop reaches targetIndex, before the injections and the post-history block.',
1193
+ fields: {
1194
+ targetIndex: { type: 'number' },
1195
+ text: { type: 'string', optional: true },
1196
+ role: { type: 'string' },
1197
+ hasContent: { type: 'boolean' },
1198
+ },
1199
+ },
1200
+ };
1201
+ /** @public */
1202
+ export const assemble = pin(describeTaskDefinition({
1203
+ id: 'core:task/assemble@2',
1204
+ timeoutMs: 1000,
1205
+ slots: {
1206
+ // An *assembly* template: its scope really is the input ports, so this half of
1207
+ // the claim holds.
1208
+ template: {
1209
+ kind: 'template',
1210
+ // Handlebars FIRST, then Liquid: the first entry is what a new
1211
+ // template here is written in, and every shipped row holds
1212
+ // Handlebars — so the order is what keeps the parity corpus
1213
+ // byte-identical. Both are accepted because a story string is a
1214
+ // layout, not a dialect: the same arrangement is expressible in
1215
+ // either, and a slot naming one makes the other unselectable
1216
+ // everywhere. Jinja is absent because core renders neither
1217
+ // parity nor helpers for it.
1218
+ acceptedEngines: [handlebars.id, liquid.id],
1219
+ facet: 'templates',
1220
+ /**
1221
+ * Assemble's own names — what `render()` writes onto the context
1222
+ * AFTER spreading the prompts and the builder's context, so these
1223
+ * are the last word (typed templates, edited in place by owner
1224
+ * ruling).
1225
+ *
1226
+ * Corrected 2026-09-27: this declared `blocks`, `budget` as two
1227
+ * bare names and `prompts` — `blocks` is a param that reorders the
1228
+ * template and never reaches it, and `prompts` is never a name:
1229
+ * the prompts slot's fields are spread at the top level. The
1230
+ * builder's keys and the prompts fields join these in
1231
+ * `templateScopeAt`; declared bands join them too.
1232
+ */
1233
+ variables: ASSEMBLE_TEMPLATE_SCOPE,
1234
+ 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.',
1235
+ },
1236
+ prompts: {
1237
+ kind: 'prompts',
1238
+ quick: true,
1239
+ facet: 'prompts',
1240
+ fields: {
1241
+ system: { type: 'text' },
1242
+ postHistory: { type: 'text' },
1243
+ },
1244
+ },
1245
+ /**
1246
+ * How the values Assemble itself produces are laid out.
1247
+ *
1248
+ * These exist here rather than upstream because they come out the
1249
+ * other side of the budget: what a layout receives is what actually
1250
+ * fit, which no earlier node knows. `characterLore` among them — the
1251
+ * admitted lore of cast members, which a context template places
1252
+ * with `{{{characterLore}}}` like any other lore.
1253
+ */
1254
+ variables: {
1255
+ kind: 'variables',
1256
+ facet: 'variables',
1257
+ description: 'How the retrieved lore and history are laid out — JSON, prose, or whatever you write. Duplicate one to change it.',
1258
+ renders: {
1259
+ worldLore: 'core:var/world-lore@1',
1260
+ characterLore: 'core:var/character-lore@1',
1261
+ history: 'core:var/history@1',
1262
+ currentDate: 'core:var/current-date@1',
1263
+ },
1264
+ /**
1265
+ * Open (typed templates, edited in place by owner ruling):
1266
+ * every band declared upstream of `candidates` is rendered too,
1267
+ * under its key and through its variable's layout — a plugin's
1268
+ * source adds its band here by declaring it.
1269
+ */
1270
+ rendersBands: { from: 'candidates' },
1271
+ },
1272
+ params: {
1273
+ kind: 'parameters',
1274
+ facet: 'weights',
1275
+ schema: {
1276
+ /**
1277
+ * ⚠ No `budget` here either. It was an integer defaulting to
1278
+ * 4096 — the same re-entered number the ranker carried, with
1279
+ * the same defect: an absolute count on a node cannot know
1280
+ * which model the prompt is about to be sent to, so it was
1281
+ * free to disagree with the window and warn nobody. The
1282
+ * total now arrives on the `budget` in-port from
1283
+ * `core:task/context-budget@1`, which derives it from the
1284
+ * sampling config the reply is generated against.
1285
+ */
1286
+ /**
1287
+ * Where the post-history reminder goes, and whether it goes
1288
+ * at all.
1289
+ *
1290
+ * Numbers, so they are parameters rather than prompt text —
1291
+ * a `prompts` slot carries authored strings and typing a
1292
+ * count as one would be the wrong shape wearing a
1293
+ * convenient home. The trigger is a **suppression**: below
1294
+ * it a short chat gets no reminder, because a reinforcement
1295
+ * note two messages after the system prompt is noise.
1296
+ */
1297
+ postHistoryDepth: {
1298
+ type: 'integer',
1299
+ default: 0,
1300
+ description: 'Place the post-history reminder this many messages before the end. 0 puts it last.',
1301
+ },
1302
+ postHistoryTokenTrigger: {
1303
+ type: 'integer',
1304
+ default: 0,
1305
+ description: 'Only add the reminder once the chat is at least this many tokens long. 0 always adds it.',
1306
+ },
1307
+ /**
1308
+ * ⚠ No `truncation` here, and there was one — an enum of
1309
+ * `oldest-first | lowest-weight`, "what gets dropped first
1310
+ * when the context is over budget" — declared, rendered,
1311
+ * and read by nothing (culled 2026-09-16). What LORE
1312
+ * fits is decided upstream by the ranker's `select`, per
1313
+ * band, against `share`, `maxEntries`, `minEntries` and
1314
+ * `scoreLedAllocation` on `core:task/rank-hybrid@1`, and
1315
+ * this node renders the decisions it is handed. A second
1316
+ * drop rule for lore here would be a second owner of one
1317
+ * decision.
1318
+ *
1319
+ * ⚠ The TRANSCRIPT is the exception, because nobody else
1320
+ * owns it (2026-10-03): no shipped spec ranks a message
1321
+ * candidate, so the conversation's rows were never fitted
1322
+ * at all and a long session went out larger than the
1323
+ * window. The host's binding measures what it rendered and,
1324
+ * over the budget, leaves out the oldest lines in a chunk
1325
+ * at a cut point it holds across turns — not a param,
1326
+ * because there is nothing to choose: a prompt that does
1327
+ * not fit is trimmed by the backend instead, from the
1328
+ * front, every turn.
1329
+ */
1330
+ /**
1331
+ * Which sections the prompt is built from, and in what order —
1332
+ * SillyTavern's *prompt list*, as a param on the node that
1333
+ * assembles the prompt (ruling 2026-09-10).
1334
+ *
1335
+ * A param and not a session setting, and not a table: it is the
1336
+ * same kind of fact as "which prompt does this step use", so it
1337
+ * belongs in the configuration a preset selects and it is an
1338
+ * administrator's. A preset carries it to every session started
1339
+ * from it for free, because a preset's configuration is already
1340
+ * what a run resolves against.
1341
+ *
1342
+ * ⚠ **The declared default means "leave the template alone".** It
1343
+ * is the shipped template's own order, so a configuration nobody
1344
+ * has touched stores nothing and renders the bytes it always did —
1345
+ * and a template somebody WROTE, whose sections sit in an order
1346
+ * they chose, is not silently reordered into this one. See
1347
+ * `isShippedPromptBlocks`.
1348
+ */
1349
+ blocks: PROMPT_BLOCKS_DECL,
1350
+ },
1351
+ },
1352
+ /**
1353
+ * Which connection this prompt is being written FOR.
1354
+ *
1355
+ * Not compute, and this node calls nothing: the only thing read out
1356
+ * of it is `metadata.promptFormat` — whether the finished prompt is
1357
+ * one instruct-wrapped string or a role-tagged array, and which
1358
+ * wrapper. A wire format is a property of the endpoint, and until
1359
+ * this slot existed there was no way for the node that renders the
1360
+ * prompt to learn it. `renderers.ts` fell back to Vicuna on every
1361
+ * run, so a ChatML or Llama-2 connection was sent Vicuna markers and
1362
+ * nothing anywhere said so.
1363
+ *
1364
+ * ## Wire it to the SENDING node, always
1365
+ *
1366
+ * `slot.connectionOf('generate')`, exactly as `contextBudget` shares
1367
+ * the sampling reference, and for the same reason stated there: a
1368
+ * prompt wrapped for one endpoint and sent to another is wrong
1369
+ * silently. Sharing the reference makes the two impossible to point
1370
+ * apart rather than documenting that they must agree and hoping.
1371
+ *
1372
+ * ## No `requires`
1373
+ *
1374
+ * The sibling connection slots declare one because they are about to
1375
+ * CALL the connection and an unmet capability should refuse at bind.
1376
+ * This one reads a label. Declaring a capability it never exercises
1377
+ * would let an untested connection grey itself out of a picker for a
1378
+ * node that was never going to send it anything.
1379
+ */
1380
+ connection: {
1381
+ kind: 'connection',
1382
+ shape: S.textGen,
1383
+ 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.',
1384
+ },
1385
+ },
1386
+ ports: {
1387
+ in: {
1388
+ candidates: S.candidates,
1389
+ budget: S.budget,
1390
+ templateContext: S.templateContext,
1391
+ /**
1392
+ * The ranker's per-candidate trail — score, verdict, reason.
1393
+ *
1394
+ * ⚠ **Supplied since the node was written, declared only now.**
1395
+ * All three shipped specs wire `decisions: $.rank.decisions`,
1396
+ * and the binding halts without them ("wire a ranker between
1397
+ * retrieval and assembly"), so this is not a new input — it is
1398
+ * the load-bearing one. What was missing was the declaration,
1399
+ * and the cost of that is exact: `validate.ts` skips its shape
1400
+ * check when either side is undeclared (`if (!outShape ||
1401
+ * !inShape) continue`), so a plugin ranker publishing the wrong
1402
+ * shape on this edge got no finding, and a plugin ASSEMBLER had
1403
+ * nothing to read to learn the port existed.
1404
+ *
1405
+ * `S.decisions`, matching `rankPorts.out.decisions` — a
1406
+ * decision is a candidate with its arithmetic attached, and the
1407
+ * panel reads the same objects the allocator does. Typed, so a
1408
+ * plugin ranker wired here publishes the shape the ranking store
1409
+ * records.
1410
+ */
1411
+ decisions: S.decisions,
1412
+ /**
1413
+ * The finished chat lines, from `core:task/process-messages@1`.
1414
+ *
1415
+ * Wired by all three specs (`messages: $.lines.messages`) and
1416
+ * undeclared for the same stretch as `decisions`. Two readers
1417
+ * depend on it and neither is optional: the transcript the
1418
+ * template renders, and the depth the post-history reminder is
1419
+ * placed at — which is computed against *these* lines because
1420
+ * the context builder ships a placeholder index, the final
1421
+ * array not existing when it runs.
1422
+ */
1423
+ messages: S.messages,
1424
+ /**
1425
+ * Per band: allocated, used, entries — the arithmetic the
1426
+ * ranker did while deciding (D-H).
1427
+ *
1428
+ * ⚠ **The one genuinely new edge in this set.** The two
1429
+ * above were supplied and undeclared; this was PUBLISHED by
1430
+ * `core:task/rank-hybrid@1` and wired by nobody, so `allocate`
1431
+ * fell to its own `{}` and the per-band numbers the ranker had
1432
+ * already computed were dropped on the floor between two
1433
+ * adjacent nodes.
1434
+ *
1435
+ * What it does NOT touch is the prompt: `allocate` puts this
1436
+ * straight onto `AllocatedContext.groups` and reads it nowhere
1437
+ * else, so `blocks`, `totalTokens` and `budget` — everything
1438
+ * the render sees — are byte-identical with it wired or not.
1439
+ * What changes is the receipt: `dispatch.ts` publishes
1440
+ * `payload.groups` as the run's `sources`, which is the budget
1441
+ * panel's whole data set and has been empty on every run.
1442
+ *
1443
+ * Undeclared on purpose for the other rankers. A ranker that
1444
+ * computes no per-band usage leaves this unwired and
1445
+ * `allocate` takes the branch it has always taken.
1446
+ */
1447
+ groups: S.json,
1448
+ /**
1449
+ * The annex a template may read, as `annex.<owner>.<key>`
1450
+ * (typed templates, edited in place by owner ruling).
1451
+ *
1452
+ * Fed ONLY by `core:query/session-annex@1` with `view:
1453
+ * 'template'`: every DECLARED key of every owner in scope —
1454
+ * core, the enabled plugins — for the session's genre, keyed by
1455
+ * owner. A key no declaration covers never arrives, and a
1456
+ * declaration refuses secrets at write time, so what
1457
+ * reaches a template is what an owner said may be kept there
1458
+ * (owner ruling: "nothing dangerous should ever be stored
1459
+ * there"). Law T2 refuses anything else wired here, and a
1460
+ * template-view read wired anywhere else.
1461
+ *
1462
+ * Optional: unwired, `annex` is not in the template's scope at
1463
+ * all, so a template naming it is refused rather than rendering
1464
+ * nothing.
1465
+ */
1466
+ annex: S.json,
1467
+ },
1468
+ out: { main: S.assembled, context: S.assembled },
1469
+ },
1470
+ }));
1471
+ /**
1472
+ * The ports both context builders expose. Identical because the two nodes do
1473
+ * the same job — the difference between them is entirely what can be
1474
+ * *configured*, which is what a node type is for.
1475
+ */
1476
+ const contextPorts = {
1477
+ in: {
1478
+ cast: S.sessionCast,
1479
+ /**
1480
+ * Whose voice the reply is, when a next-speaker node decided.
1481
+ * Optional: unwired, the speaker still rides the cast bundle (the
1482
+ * scope's value), which is how every spec worked before the node
1483
+ * existed — and how the narrator's context, which has no speaker,
1484
+ * still works. Wired, it wins, so the receipt's speaker and the
1485
+ * prompt's speaker cannot disagree.
1486
+ */
1487
+ currentCharacterId: S.rowIds,
1488
+ },
1489
+ out: {
1490
+ main: S.templateContext,
1491
+ templateContext: S.templateContext,
1492
+ /**
1493
+ * The name on the trailing assistant line.
1494
+ *
1495
+ * Its own port rather than a field inside the context, because
1496
+ * nothing renders `{{seedName}}` — it is not a template variable.
1497
+ * It is what the message processor writes on the line the model
1498
+ * continues from, and in narrator mode it is the one name that
1499
+ * must *not* be the joined cast list: seeding "Alice and Cara:"
1500
+ * teaches the model to write joint dialogue instead of narrating.
1501
+ */
1502
+ seedName: S.text,
1503
+ },
1504
+ };
1505
+ const PROMPTS_DESCRIPTION = 'The written instructions this pipeline sends the model — pick a prompt, or duplicate one and make it yours.';
1506
+ /**
1507
+ * How each value this node produces is *presented*.
1508
+ *
1509
+ * Every one of these was a `JSON.stringify` in TypeScript, indentation and all
1510
+ * — so "render my characters as prose" was a code change rather than a setting.
1511
+ * Each key here points at a swappable template row, selected the way a prompt
1512
+ * is, and keyed by the variable it renders rather than by this spec: a prose
1513
+ * rendering written here is selectable from any pipeline that renders the same
1514
+ * variable.
1515
+ *
1516
+ * The shipped rows reproduce the old TypeScript byte for byte. The JSON shape is
1517
+ * not a default anyone drifted into — it was A/B tested before 0.1.0 and
1518
+ * measurably improved how reliably models hold a character — so prose is opt-in
1519
+ * and stays that way.
1520
+ */
1521
+ const VARIABLES_DESCRIPTION = 'How each part of the prompt is laid out — JSON, prose, or whatever you write. Duplicate one to change it.';
1522
+ /**
1523
+ * What a context builder's `templateContext` carries, in the template type
1524
+ * language (typed templates, 2026-09-27) — so a template editor offers
1525
+ * `{{{characters}}}` with a type, and `templateScopeAt` puts these keys in
1526
+ * the scope of whatever template renders the builder's output.
1527
+ *
1528
+ * Written from what the builder RETURNS (the app's `buildTemplateContext`),
1529
+ * not from the legacy `TemplateContext` type, which also lists names only
1530
+ * Assemble supplies (`worldLore`, `history`, `currentDate`). The app holds
1531
+ * the two together at compile time: the builder's returned object
1532
+ * `satisfies VarValue<typeof TEMPLATE_CONTEXT_SCHEMA>`, so a key added on
1533
+ * one side and not the other fails `tsc`.
1534
+ *
1535
+ * Every rendered value is a **string** — each is laid out through its
1536
+ * variable's selected layout before it leaves the builder (a user's
1537
+ * `{{{characters}}}` would otherwise render `[object Object]`). `state` is
1538
+ * the one structure: `templateScopeAt` re-types it from the session genre's
1539
+ * attribute slots. `sessionMessages` and `postHistory` are placeholders
1540
+ * Assemble supersedes with its own.
1541
+ *
1542
+ * **Policy** (`portSchemas`): it describes the payload; no hash moves.
1543
+ * @experimental
1544
+ */
1545
+ export const TEMPLATE_CONTEXT_SCHEMA = {
1546
+ type: 'object',
1547
+ fields: {
1548
+ instructions: { type: 'string', description: 'The system prompt, resolved and laid out.' },
1549
+ characters: { type: 'string', description: 'The cast’s character cards, laid out (JSON by default), trimmed to the session’s character detail.' },
1550
+ personas: { type: 'string', description: 'The personas, laid out (JSON by default).' },
1551
+ scenario: { type: 'string', description: 'The scenario, resolved and laid out.' },
1552
+ characterNames: { type: 'string', description: '“A, B, and C” — every enabled character’s name (none at speaker-only detail).' },
1553
+ personaNames: { type: 'string', description: '“A, B, and C” — every persona’s name.' },
1554
+ /** 🚧 `core:var/likenesses@1` — everyone on stage's likeness prompt, laid out. */
1555
+ likenesses: { type: 'string', description: 'Everyone on stage’s likeness prompt, by name, laid out (JSON by default).' },
1556
+ exampleDialogue: { type: 'string', description: 'The speaker’s example dialogue.' },
1557
+ postHistoryInstructions: { type: 'string', description: 'The post-history instructions, resolved.' },
1558
+ relationshipsPerspectives: { type: 'string', description: 'How the speaker regards everyone.' },
1559
+ relationshipsKnown: { type: 'string', description: 'How everyone regards the speaker.' },
1560
+ char: { type: 'string', description: 'The speaking character’s name.' },
1561
+ character: { type: 'string', description: 'The speaking character’s name.' },
1562
+ user: { type: 'string', description: 'The persona’s name.' },
1563
+ persona: { type: 'string', description: 'The persona’s name.' },
1564
+ postHistory: {
1565
+ type: 'object',
1566
+ description: 'The post-history block, before Assemble decides where it goes.',
1567
+ fields: {
1568
+ targetIndex: { type: 'number' },
1569
+ instructions: { type: 'string', optional: true },
1570
+ charInstructions: { type: 'string', optional: true },
1571
+ exampleDialogue: { type: 'string', optional: true },
1572
+ hasContent: { type: 'boolean' },
1573
+ gatedBy: { type: 'string', optional: true },
1574
+ },
1575
+ },
1576
+ /**
1577
+ * 🚧 The author's note before Assemble places it — present only when
1578
+ * the session's genre declares `authorsNote` and the spec wires the
1579
+ * genre fields into this node. `targetIndex` is a placeholder, as
1580
+ * `postHistory`'s is.
1581
+ */
1582
+ authorsNote: {
1583
+ type: 'object',
1584
+ optional: true,
1585
+ description: 'The session’s author’s note, before Assemble decides where it goes.',
1586
+ fields: {
1587
+ targetIndex: { type: 'number' },
1588
+ text: { type: 'string', optional: true },
1589
+ role: { type: 'string' },
1590
+ depth: { type: 'number' },
1591
+ interval: { type: 'number' },
1592
+ replyCount: { type: 'number', optional: true },
1593
+ hasContent: { type: 'boolean' },
1594
+ gatedBy: { type: 'string', optional: true },
1595
+ },
1596
+ },
1597
+ sessionMessages: { type: 'list', description: 'Empty here; Assemble supplies the transcript.' },
1598
+ state: {
1599
+ type: 'object',
1600
+ optional: true,
1601
+ description: 'The session’s stats and states — state.world.<slot>, state.cast.<member>.<slot>, state.locations.<place>.<slot>.',
1602
+ fields: { world: { type: 'record' }, cast: { type: 'record' }, locations: { type: 'record', optional: true } },
1603
+ },
1604
+ },
1605
+ };
1606
+ /** Rendered by every context builder, whoever is speaking. */
1607
+ const sharedRenders = {
1608
+ instructions: 'core:var/instructions@1',
1609
+ characters: 'core:var/characters@1',
1610
+ personas: 'core:var/personas@1',
1611
+ scenario: 'core:var/scenario@1',
1612
+ postHistoryInstructions: 'core:var/post-history-instructions@1',
1613
+ characterNames: 'core:var/character-names@1',
1614
+ personaNames: 'core:var/persona-names@1',
1615
+ /** 🚧 Everyone on stage's likeness prompt. */
1616
+ likenesses: 'core:var/likenesses@1',
1617
+ };
1618
+ /**
1619
+ * The reply pipeline's context builder.
1620
+ *
1621
+ * ## Why the narrator has its own type
1622
+ *
1623
+ * Through 0.6.0 both pipelines pinned this one, and the panel is generated from
1624
+ * the registry row — so each advertised the other's controls. Reply prompts all
1625
+ * carried an empty `narratorName` box, and the narrator offered layout pickers
1626
+ * for `exampleDialogue` (which comes from the speaking character it does not
1627
+ * have) and the two relationship variables (which its spec deliberately never supplies).
1628
+ * Three controls wired to nothing, in both directions.
1629
+ *
1630
+ * A type is the unit that declares a configurable surface — it is how a plugin
1631
+ * declares one, and `RegistryEntry.slots` carries the declaration precisely so
1632
+ * core can render a form without executing the plugin that owns it.
1633
+ * Narrowing per-spec instead would have meant the row said one thing and the
1634
+ * running pipeline another, which is the defect widening that column fixed.
1635
+ *
1636
+ * The two share `contextPorts` and `sharedRenders` rather than restating them,
1637
+ * so the halves that must not drift cannot.
1638
+ * @public
1639
+ */
1640
+ export const buildTemplateContext = pin(describeTaskDefinition({
1641
+ id: 'core:task/build-template-context@1',
1642
+ i18n: { name: { en: 'Build template context' } },
1643
+ timeoutMs: 2000,
1644
+ /** What `templateContext` carries — typed templates; policy, so no pin moves. */
1645
+ portSchemas: { out: { main: TEMPLATE_CONTEXT_SCHEMA, templateContext: TEMPLATE_CONTEXT_SCHEMA } },
1646
+ /**
1647
+ * The example-dialogue pick. Declaring it is what gets `ctx.random` — the
1648
+ * run-seeded RNG — instead of `Math.random()`, so the same run replayed
1649
+ * chooses the same example and a different turn still gets variety.
1650
+ */
1651
+ declaresRandomness: true,
1652
+ /**
1653
+ * The authored text. It arrives as config rather than on a port because it
1654
+ * *is* config — the same prompt config the assembly template renders from,
1655
+ * layered instance → user → chat like every other slot.
1656
+ */
1657
+ slots: {
1658
+ prompts: {
1659
+ kind: 'prompts',
1660
+ quick: true,
1661
+ facet: 'prompts',
1662
+ description: PROMPTS_DESCRIPTION,
1663
+ fields: {
1664
+ systemPrompt: { type: 'text' },
1665
+ postHistoryInstructions: { type: 'text' },
1666
+ },
1667
+ },
1668
+ variables: {
1669
+ kind: 'variables',
1670
+ facet: 'variables',
1671
+ description: VARIABLES_DESCRIPTION,
1672
+ renders: {
1673
+ ...sharedRenders,
1674
+ /** From the speaking character's card. */
1675
+ exampleDialogue: 'core:var/example-dialogue@1',
1676
+ /**
1677
+ * The narrative graph, as two variables rather than one.
1678
+ *
1679
+ * They were `speakerRelationships` — a single block holding
1680
+ * both what the speaker thinks of everyone and what everyone
1681
+ * thinks of the speaker. Opposite claims under one heading,
1682
+ * which a model reads as one list, and one layout, one
1683
+ * priority and one on/off switch for both.
1684
+ */
1685
+ relationshipsPerspectives: 'core:var/relationships-perspectives@1',
1686
+ relationshipsKnown: 'core:var/relationships-known@1',
1687
+ },
1688
+ },
1689
+ /**
1690
+ * The pre-assemble context hook: user chains over the
1691
+ * finished template context — conditional style guides, seeded
1692
+ * event tables — after this node resolves it and before anything
1693
+ * renders it.
1694
+ *
1695
+ * `messages/inject` lives here too — **not** on the message
1696
+ * processor — because of the ruling of 2026-08-23: injections are
1697
+ * template-context *data* (`context.injections`, resolved to
1698
+ * `injectionsByIndex` beside `postHistory.targetIndex`), rendered
1699
+ * by the template's own message loop. Splicing them into the list
1700
+ * behind the template's back would repeat an old defect one
1701
+ * layer down: a position the template cannot express, an author
1702
+ * cannot see, and a corpus cannot check.
1703
+ */
1704
+ scripts: {
1705
+ kind: 'scripts',
1706
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
1707
+ port: 'main',
1708
+ phase: 'after',
1709
+ 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.',
1710
+ },
1711
+ },
1712
+ ports: {
1713
+ in: {
1714
+ ...contextPorts.in,
1715
+ /**
1716
+ * The narrative graph, as the two claims it really is — how the
1717
+ * speaker regards everyone, and how everyone regards the
1718
+ * speaker (D-I).
1719
+ *
1720
+ * ⚠ **Supplied by `respond` since the split, declared here
1721
+ * only now.** The spec wires both off
1722
+ * `core:query/relationships-perspectives@1` and
1723
+ * `core:query/relationships-known@1`, the two `renders` above
1724
+ * name the variables they feed, and the builder reads both by
1725
+ * these exact names — so every part of the round trip was
1726
+ * written down except the ports themselves.
1727
+ *
1728
+ * `json`, matching what those queries publish and for the
1729
+ * reason stated at them: the structure travels so a variable
1730
+ * layout can render it, rather than a blob nothing can
1731
+ * restyle.
1732
+ *
1733
+ * ⚠ Declared on THIS type alone rather than in `contextPorts`,
1734
+ * which the narrator builder shares. Its own docblock says the
1735
+ * narrate spec never supplies these because graph context
1736
+ * needs a speaker's perspective and a narrator has none — so
1737
+ * widening the shared map would give it two ports it must
1738
+ * leave empty forever, and move its hash to say so.
1739
+ */
1740
+ relationshipsPerspectives: S.json,
1741
+ relationshipsKnown: S.json,
1742
+ /**
1743
+ * Who is speaking, when the speaker is not in the cast.
1744
+ *
1745
+ * ⚠ **Neither is wired by any spec, and both are supplied on
1746
+ * every side-character turn.** `core:task/build-side-character-
1747
+ * context@1` is not a separate implementation — the host's
1748
+ * binding for it unwraps its `sideCharacter` in-port and calls THIS
1749
+ * type's handler with the name and the card spread onto the
1750
+ * input, because `resolveContextInput` owns the card rules and
1751
+ * a side character's card and a cast member's must compile
1752
+ * through one function.
1753
+ *
1754
+ * So the supplier is the host rather than a document, and that
1755
+ * is exactly why declaring them matters: it is the only record
1756
+ * that this type's input surface is wider than its edges. An
1757
+ * undeclared key reaching a handler is indistinguishable from a
1758
+ * typo until someone reads both files at once.
1759
+ *
1760
+ * `speakerName` is `text` — it is the name on the seed line and
1761
+ * what `{{char}}` renders. `speakerCharacter` is `json`: the
1762
+ * card, or `null` for a free-form name, which is a normal turn
1763
+ * rather than a degraded one.
1764
+ */
1765
+ speakerName: S.text,
1766
+ speakerCharacter: S.json,
1767
+ /**
1768
+ * Who is speaking, as a participant reference (2026-09-16)
1769
+ * — the turn strategy's `speaker`. Read for one
1770
+ * thing: an **envoy** (`envoy:<slug>`) has no character row, so
1771
+ * its card — name and description, off the genre's declaration
1772
+ * the cast read carries — is compiled here where a cast
1773
+ * member's would be, through the same `speakerName` /
1774
+ * `speakerCharacter` seam a side character uses. A `character:`
1775
+ * reference changes nothing: `currentCharacterId` already says
1776
+ * it. Optional; unwired on the specs that seat no envoy.
1777
+ */
1778
+ speaker: S.participantRef,
1779
+ /**
1780
+ * The session's resolved stats and states, as
1781
+ * `core:query/session-state@1` publishes them:
1782
+ * `{ world, cast, locations, slots, who, version }`, already
1783
+ * resolved down the session → lorebook → card → default chain
1784
+ * (a location's: this run's → the entry's → default; 🚧 phase 4).
1785
+ *
1786
+ * A template reads `state.world.weather` and
1787
+ * `state.cast.verity.hp` — the **resolved** value and nothing
1788
+ * below it. Which layer a number came from is a question for
1789
+ * the Cast member page, not for a prompt.
1790
+ *
1791
+ * ⚠ Declared on THIS type alone rather than in `contextPorts`,
1792
+ * following `relationshipsPerspectives` above and for the same
1793
+ * reason: widening the shared map moves the narrator's hash to
1794
+ * declare a port no shipped spec fills. Unwired — which is
1795
+ * every shipped spec today — the key is absent and the context
1796
+ * has no `state`, which is what a chat session should have.
1797
+ */
1798
+ state: S.json,
1799
+ /**
1800
+ * What the person typed with the press, for an action that
1801
+ * reads its composer text as **direction** (2026-09-27): the
1802
+ * Lair's Trigger trap and Reveal, and Whodunit's Search — what
1803
+ * the detective is looking for (2026-09-29). Rendered as
1804
+ * `{{turnDirection}}` — the same name, and the same meaning,
1805
+ * `build-scene-context@1` gives the Lair's reply. Absent
1806
+ * when blank, so a prompt writes `{{#if turnDirection}}…{{/if}}`
1807
+ * and a press with nothing typed leaves it to the prompt.
1808
+ * Declared here rather than in `contextPorts`, like `state`
1809
+ * above; the narrator and side-character builders declare
1810
+ * their own. Unwired on every spec whose composer text is
1811
+ * a line somebody said.
1812
+ */
1813
+ turnDirection: S.text,
1814
+ /**
1815
+ * The places the lorebook holds, for an envoy that talks about
1816
+ * the world from outside it (2026-09-28): the
1817
+ * Lair's Castellan in the Sanctum. A
1818
+ * `core:query/lorebook-entries@1` listing, rendered exactly as
1819
+ * the planner's and the scene's port of this name is —
1820
+ * `{{knownLocations}}` (their names) and `{{locationEntry}}`
1821
+ * (the room the world's `location` names). Declared on THIS
1822
+ * type alone, like `state`; unwired on every other spec.
1823
+ */
1824
+ locationEntries: S.json,
1825
+ /**
1826
+ * The story's newest rows, for a speaker who talks ABOUT the
1827
+ * story from another channel: the Castellan
1828
+ * in the Sanctum reads `main`'s last few rows. Transcript rows
1829
+ * (a `session-history@1` read), rendered as prose — one
1830
+ * `Name: line` per row, named as the transcript names them, no
1831
+ * JSON blocks — into `{{recentStory}}`, so they are background
1832
+ * in the instructions and never turns the model continues.
1833
+ * Absent when unwired or empty.
1834
+ */
1835
+ recentStory: S.messages,
1836
+ /**
1837
+ * The session's genre fields, by their own names (2026-09-28):
1838
+ * `{{sanctumSteers}}` for the Castellan in
1839
+ * the Sanctum, whose instructions say whether its talk shapes
1840
+ * the next turn. The planner's and the scene's `fields`, on the
1841
+ * same terms. Declared on THIS type alone, like `state`;
1842
+ * unwired on every other spec.
1843
+ */
1844
+ fields: S.json,
1845
+ /**
1846
+ * The speaker's own running notes (owner ruling of
1847
+ * 2026-09-28): the Castellan's **scratchpad**, the Lair's annex
1848
+ * field `castellan-scratchpad`, read for it alone
1849
+ * (`session-annex@1`'s AI view, with its own reference as the
1850
+ * speaker). Rendered as `{{scratchpad}}`; absent when unwired
1851
+ * or blank. Declared on THIS type alone, like `state`.
1852
+ */
1853
+ scratchpad: S.text,
1854
+ },
1855
+ out: contextPorts.out,
1856
+ },
1857
+ }));
1858
+ /**
1859
+ * The narrator pipeline's context builder.
1860
+ *
1861
+ * Same implementation, same ports, different surface — see
1862
+ * `buildTemplateContext` for why that makes it a different type.
1863
+ *
1864
+ * What it drops: `exampleDialogue`, which `characterExampleDialogue` reads off
1865
+ * the speaking character and so is always empty here, and both relationship
1866
+ * variables, which the narrate spec never supplies because graph context needs
1867
+ * a speaker's perspective and a narrator has none.
1868
+ *
1869
+ * What it adds: `narratorName`. Load-bearing rather than cosmetic — it is the
1870
+ * name on the seed line the model continues from, and `{{narratorName}}` in the
1871
+ * narrator's own prompt text.
1872
+ *
1873
+ * No `declaresRandomness`: the only random choice this node ever made was which
1874
+ * example dialogue to use, and it has none to choose from.
1875
+ * @public
1876
+ */
1877
+ export const buildNarratorContext = pin(describeTaskDefinition({
1878
+ id: 'core:task/build-narrator-context@1',
1879
+ i18n: { name: { en: 'Build narrator context' } },
1880
+ timeoutMs: 2000,
1881
+ /** The same builder, the same payload (`TEMPLATE_CONTEXT_SCHEMA`). Policy. */
1882
+ portSchemas: { out: { main: TEMPLATE_CONTEXT_SCHEMA, templateContext: TEMPLATE_CONTEXT_SCHEMA } },
1883
+ slots: {
1884
+ prompts: {
1885
+ kind: 'prompts',
1886
+ quick: true,
1887
+ facet: 'prompts',
1888
+ description: PROMPTS_DESCRIPTION,
1889
+ fields: {
1890
+ systemPrompt: { type: 'text' },
1891
+ postHistoryInstructions: { type: 'text' },
1892
+ narratorName: { type: 'text' },
1893
+ },
1894
+ },
1895
+ variables: {
1896
+ kind: 'variables',
1897
+ facet: 'variables',
1898
+ description: VARIABLES_DESCRIPTION,
1899
+ renders: { ...sharedRenders },
1900
+ },
1901
+ /** The same hook as `build-template-context` — see it for the terms. */
1902
+ scripts: {
1903
+ kind: 'scripts',
1904
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
1905
+ port: 'main',
1906
+ phase: 'after',
1907
+ 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.',
1908
+ },
1909
+ },
1910
+ ports: {
1911
+ in: {
1912
+ ...contextPorts.in,
1913
+ /**
1914
+ * What the person asked this narration to do (2026-09-29):
1915
+ * the narrator modal's text or `/narrate
1916
+ * <text>` — the turn's triggering text, `$.input.text`.
1917
+ * Rendered as `{{turnDirection}}`, the name and the meaning
1918
+ * `build-template-context@1` and `build-scene-context@1` give
1919
+ * it; absent when blank, so a row writes
1920
+ * `{{#if turnDirection}}…{{/if}}` and an undirected narration
1921
+ * renders exactly what it did before.
1922
+ *
1923
+ * ⚠ Declared because the placeholder's `instructions` is not
1924
+ * a prompt: it is stored beside the row and shown with it. For
1925
+ * as long as that was the direction's only reader, 0.5.3's
1926
+ * _Additional focus for this response_ reached no model.
1927
+ */
1928
+ turnDirection: S.text,
1929
+ },
1930
+ out: contextPorts.out,
1931
+ },
1932
+ }));
1933
+ /**
1934
+ * The side-character pipeline's context builder (ruling 2026-09-07).
1935
+ *
1936
+ * Same implementation and the same ports as the other two, plus one in-port —
1937
+ * `sideCharacter` — and that port is the whole reason it is a third type rather
1938
+ * than a flag.
1939
+ *
1940
+ * ## Why the name is a port and not a prompt field
1941
+ *
1942
+ * `build-narrator-context@1` takes `narratorName` in its **prompts** slot,
1943
+ * which is correct there: the narrator's name is a setting, chosen once, the
1944
+ * same on every turn. A side character's name is *data from the trigger* — it
1945
+ * differs per turn and a person may type it in the modal — so putting it in a
1946
+ * prompts slot would mean editing a prompt config to speak as somebody else,
1947
+ * and every turn would render with whichever name was stored last.
1948
+ *
1949
+ * ## What it drops, and what it keeps
1950
+ *
1951
+ * Drops `exampleDialogue`, for the narrator's reason: it is read off the
1952
+ * speaking *cast member*, and a side character is not one. Drops both
1953
+ * relationship variables, because graph context is built from a cast member's
1954
+ * node and this speaker has none. Keeps every shared render, so the cards, the
1955
+ * scenario and the two name lists are laid out exactly as they are elsewhere.
1956
+ *
1957
+ * ⚠ It declares **no** `narratorName` prompt field. A side-character prompt
1958
+ * that wrote `{{narratorName}}` would render the narrator's configured name
1959
+ * into a turn the narrator is not speaking — the same "control wired to
1960
+ * nothing, in both directions" the two context builders were split to end.
1961
+ * `{{char}}` is the speaker here, exactly as it is in a reply.
1962
+ *
1963
+ * ⚠ And it does **not** inherit `contextPorts.in.currentCharacterId`, which the
1964
+ * other two carry. Not an oversight: character-lore visibility is decided by
1965
+ * the host read, which keys on the run's SCOPE, so a speaker id arriving here
1966
+ * could change whose voice the prompt is written in without changing whose lore
1967
+ * it was given — a prompt in one person's voice over another's private
1968
+ * knowledge. The port would be a control that half-works, which is the exact
1969
+ * class this whole split exists to remove. `sideCharacter` carries the name and
1970
+ * the card; the id stays where the host can act on it.
1971
+ *
1972
+ * ⚠ **The OUT-port `speaker` is the other half of that sentence** (added
1973
+ * 2026-09-17). The half-working control was a speaker id that changed the
1974
+ * prompt's voice and not the lore; the repair is not an in-port but a lane
1975
+ * inside the same clause reading the answer this node already computed —
1976
+ * `core:query/character-lore@1` takes `speaker`, so the voice and its private
1977
+ * knowledge move together or not at all.
1978
+ * @experimental
1979
+ */
1980
+ export const buildSideCharacterContext = pin(describeTaskDefinition({
1981
+ id: 'core:task/build-side-character-context@1',
1982
+ i18n: { name: { en: 'Build side character context' } },
1983
+ timeoutMs: 2000,
1984
+ slots: {
1985
+ prompts: {
1986
+ kind: 'prompts',
1987
+ quick: true,
1988
+ facet: 'prompts',
1989
+ description: PROMPTS_DESCRIPTION,
1990
+ fields: {
1991
+ systemPrompt: { type: 'text' },
1992
+ postHistoryInstructions: { type: 'text' },
1993
+ },
1994
+ },
1995
+ variables: {
1996
+ kind: 'variables',
1997
+ facet: 'variables',
1998
+ description: VARIABLES_DESCRIPTION,
1999
+ renders: { ...sharedRenders },
2000
+ },
2001
+ /** The same hook as the other two builders — see them for the terms. */
2002
+ scripts: {
2003
+ kind: 'scripts',
2004
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
2005
+ port: 'main',
2006
+ phase: 'after',
2007
+ 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.',
2008
+ },
2009
+ },
2010
+ ports: {
2011
+ in: {
2012
+ cast: contextPorts.in.cast,
2013
+ /**
2014
+ * `{ name, characterId, ref, known, character }`, from the
2015
+ * trigger's first step. `name` is what the seed line carries and
2016
+ * what `{{char}}` renders; `character` is the card, absent for a
2017
+ * free-form name, which is a normal turn rather than a degraded
2018
+ * one — the builder falls back to the name it was given,
2019
+ * because a typed name is all there is.
2020
+ *
2021
+ * `characterId` (a row id) or `ref` (a participant reference,
2022
+ * `character:<id>` — what a pressed option carries) names the
2023
+ * speaker BY ROW, and then the row is who
2024
+ * speaks: the name is a label, never a second lookup, so two
2025
+ * people sharing a name stay two people and a row the cast does
2026
+ * not seat is still the person it names. A fact with neither
2027
+ * resolves by name against the cast.
2028
+ *
2029
+ * Was `speaker` until 2026-09-16 — see the inlet's port of
2030
+ * this name for why the fact moved off that word.
2031
+ */
2032
+ sideCharacter: S.json,
2033
+ /**
2034
+ * Where this turn is happening, as the world state says it.
2035
+ *
2036
+ * Declared late, and for a defect rather than for symmetry: a
2037
+ * voice built with no place in front of it answered from
2038
+ * whatever the transcript suggested and moved the scene to a
2039
+ * harbour the plan had never mentioned. Unwired on every
2040
+ * pipeline that had this node before it, so those keep the
2041
+ * context they already had.
2042
+ */
2043
+ state: S.json,
2044
+ /**
2045
+ * The planner's document, for the one fact the state cannot
2046
+ * supply on a first turn: where the scene is, before anything
2047
+ * has written a location down.
2048
+ */
2049
+ plan: S.json,
2050
+ /**
2051
+ * The rooms, listed (`core:query/lorebook-entries@1`), as the
2052
+ * planner and the scene get them (2026-09-28):
2053
+ * `{{knownLocations}}` and the one the party stand in as
2054
+ * `{{locationEntry}}`, so a voice can name the room it is in
2055
+ * now that nobody narrates it first. Unwired, neither renders.
2056
+ */
2057
+ locationEntries: S.json,
2058
+ /**
2059
+ * A place described only in prose, as `{{locationPassage}}`
2060
+ * (2026-09-28): the paragraph
2061
+ * `core:task/undescribed-name@1` found describing the room the
2062
+ * party are about to walk into (its `passage`), when no entry
2063
+ * describes it — that room's text for this turn. Blank or
2064
+ * unwired, it does not render.
2065
+ */
2066
+ locationPassage: S.text,
2067
+ /**
2068
+ * What the person asked this side character's turn to do
2069
+ * (2026-09-29) — the narrator modal's text,
2070
+ * which feeds both of its halves. `{{turnDirection}}`, on the
2071
+ * terms `build-narrator-context@1` states; wired by
2072
+ * `core:spec/chat-side-character` alone, so a genre's voices
2073
+ * (whose composer text is a line somebody said) render
2074
+ * nothing new.
2075
+ */
2076
+ turnDirection: S.text,
2077
+ },
2078
+ out: {
2079
+ ...contextPorts.out,
2080
+ /**
2081
+ * Who this voice is, as a **participant reference** — the row
2082
+ * the fact named (`characterId` or `ref`), else
2083
+ * `character:<id>` for a name the cast holds, else null for a
2084
+ * free-form one. Additive, 2026-09-17. A lore read wired
2085
+ * to it takes null as unwired, so the run's scope decides for
2086
+ * a free-form voice.
2087
+ *
2088
+ * The resolution already happened: this node derives the
2089
+ * speaking character from the `sideCharacter` fact so the card,
2090
+ * `{{char}}` and the seed line agree. Publishing it is what lets
2091
+ * a lore lane INSIDE the same `each` be handed the same answer
2092
+ * — `speaker: $.voices.item.context.speaker` on
2093
+ * `core:query/character-lore@1` — rather than a second
2094
+ * name-to-row match somewhere downstream, which is how the
2095
+ * prompt's speaker and the lore's speaker come to disagree.
2096
+ *
2097
+ * ⚠ It is published, never taken: there is still no
2098
+ * `currentCharacterId` IN-port here, for the reason the header
2099
+ * gives. What changed is that the id the node computed is now
2100
+ * readable, not that a spec may set it.
2101
+ */
2102
+ speaker: S.participantRef,
2103
+ },
2104
+ },
2105
+ }));
2106
+ /* ── The adventure genre's agent contexts ───────────────────────────────────
2107
+ *
2108
+ * Three more surfaces onto the ONE context builder, declared for the reason
2109
+ * `buildNarratorContext` states beside `buildTemplateContext`: a different
2110
+ * prompt surface is a different type. The reason is mechanical rather than
2111
+ * tidy-minded. A prompt lives in a pool keyed by (node type, slot), and
2112
+ * `defaultPromptFor` resolves **one row per pool per spec** — two nodes of the
2113
+ * same type in one pipeline must land on the same shipped prompt. A multi-agent
2114
+ * turn whose planner, narrator and state-keeper were all
2115
+ * `build-template-context@1` would therefore ship all three agents the same
2116
+ * instructions, and the person who noticed would have to fix it three times in
2117
+ * a panel rather than once in a package.
2118
+ *
2119
+ * They take `state` because that is the whole premise of the genre they serve:
2120
+ * every agent reads the bars, the world strip and the inventory as facts before
2121
+ * it writes anything. `core:task/build-template-context@1` declares the same
2122
+ * port and stays the type a spec uses when it wants the standard surface.
2123
+ */
2124
+ /**
2125
+ * ⚠ Returns the literal slot keys, not `Record<string, SlotDecl>` — as
2126
+ * `loreSlots` and `relationshipSlots` do. The erased form made
2127
+ * `SlotNamesOf<typeof buildPlannerContext>` `never`, so a handler bound to the
2128
+ * three surfaces could type-check reading NO slot and declare NO slot read,
2129
+ * which is the "declares least, checked least" hole `nodeInput.ts` warns about.
2130
+ * Found when the surfaces gained `reads` declarations (2026-09-16).
2131
+ */
2132
+ const agentContextSlots = (promptFields) => ({
2133
+ prompts: {
2134
+ kind: 'prompts',
2135
+ quick: true,
2136
+ facet: 'prompts',
2137
+ description: PROMPTS_DESCRIPTION,
2138
+ fields: promptFields,
2139
+ },
2140
+ variables: {
2141
+ kind: 'variables',
2142
+ facet: 'variables',
2143
+ description: VARIABLES_DESCRIPTION,
2144
+ renders: { ...sharedRenders },
2145
+ },
2146
+ /** The same pre-assemble hook the other three builders carry. */
2147
+ scripts: {
2148
+ kind: 'scripts',
2149
+ accepts: ['core:script:context/transform@1', 'core:script:messages/inject@1'],
2150
+ port: 'main',
2151
+ phase: 'after',
2152
+ 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.',
2153
+ },
2154
+ });
2155
+ /**
2156
+ * The planner's context: the cast, the state, and nothing about a speaker.
2157
+ *
2158
+ * A planner decides who speaks; it is not itself anybody, so
2159
+ * `currentCharacterId` is deliberately absent rather than declared and left
2160
+ * empty. What it publishes is what every other builder publishes, so the
2161
+ * planner's prompt is assembled by the same node as everyone else's.
2162
+ * @experimental
2163
+ */
2164
+ export const buildPlannerContext = pin(describeTaskDefinition({
2165
+ id: 'core:task/build-planner-context@1',
2166
+ i18n: { name: { en: 'Build planner context' } },
2167
+ timeoutMs: 2000,
2168
+ slots: agentContextSlots({
2169
+ systemPrompt: { type: 'text' },
2170
+ postHistoryInstructions: { type: 'text' },
2171
+ }),
2172
+ ports: {
2173
+ in: {
2174
+ cast: contextPorts.in.cast,
2175
+ state: S.json,
2176
+ /**
2177
+ * The session's own genre fields, by key — `tone`,
2178
+ * `difficulty` and whatever else the genre declared.
2179
+ *
2180
+ * On the template context under their own names, so an
2181
+ * authored prompt writes `{{tone}}` the way it writes
2182
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2183
+ * declaration promises: declared on the genre, edited in
2184
+ * session settings, stored on the row, published by the input
2185
+ * node, and read here by the agent whose wording depends on
2186
+ * them. Without this port the last step was missing and a
2187
+ * prompt naming `{{tone}}` rendered a blank.
2188
+ */
2189
+ fields: S.json,
2190
+ /**
2191
+ * What the person just sent, when the genre reads it as
2192
+ * **direction** rather than as a line somebody said
2193
+ * (2026-09-27) — the Lair's composer. On the template
2194
+ * context and in the prompt as `{{turnDirection}}`; empty or
2195
+ * absent on a turn nobody directed (a Continue), so a prompt
2196
+ * writes `{{#if turnDirection}}…{{/if}}`. A genre whose composer
2197
+ * text is a participant's line leaves it unwired: that line is
2198
+ * already in the transcript. *Turn* direction, never bare
2199
+ * `direction`: that word is the Lair's standing-note state slot
2200
+ * (`core:slot/direction@1`), a different fact (one word, one
2201
+ * meaning; renamed 2026-09-27).
2202
+ */
2203
+ turnDirection: S.text,
2204
+ /**
2205
+ * The places the lorebook holds — a
2206
+ * `core:query/lorebook-entries@1` listing of location entries
2207
+ * (2026-09-27). On the template context as
2208
+ * `{{knownLocations}}` (their names, one line) and
2209
+ * `{{locationEntry}}` (the entry whose name is the world's
2210
+ * `location` slot — where the party are, its exits included),
2211
+ * whatever the retrieval ranking admitted: a planner that is
2212
+ * never shown the room it stands in cannot tell an open door
2213
+ * from an unbuilt one. Both are absent when nothing is listed.
2214
+ */
2215
+ locationEntries: S.json,
2216
+ /**
2217
+ * **Side talk** (2026-09-28): what was said on
2218
+ * another channel since the story's last line — the Lair's
2219
+ * Sanctum talk, read by `session-history@1` with
2220
+ * `unplayedOnly`. Transcript rows, rendered as prose into
2221
+ * `{{sideTalk}}` (one `Name: line` per row, as `recentStory`
2222
+ * is), so a prompt gives it its own labelled block and it never
2223
+ * reads as story turns. Absent when unwired or empty: the Lair
2224
+ * wires it only while the session's _Sanctum talk steers the
2225
+ * story_ is on.
2226
+ */
2227
+ sideTalk: S.messages,
2228
+ /**
2229
+ * The planner's own running notes (owner ruling of
2230
+ * 2026-09-28): the Castellan's **scratchpad**, rendered as
2231
+ * `{{scratchpad}}`. Absent when unwired or blank; the Lair
2232
+ * wires it beside `sideTalk`.
2233
+ */
2234
+ scratchpad: S.text,
2235
+ /**
2236
+ * **How the cast stand with each other** (2026-09-29): the
2237
+ * ranker's allocated candidates, of which the
2238
+ * builder reads the `relationships` band's `castRelationships`
2239
+ * lane — `core:query/relationship-search@1` read with nobody
2240
+ * speaking. Rendered as `{{castRelationships}}`: JSON keyed by
2241
+ * who holds each view, then by whom it is of, in rank order.
2242
+ * Only what the budget
2243
+ * admitted arrives, so a band at share 0 renders nothing. Absent
2244
+ * when unwired or empty.
2245
+ *
2246
+ * ⚠ On the planner and the scene only — the game master's two
2247
+ * agents. A voice is a cast member speaking, and
2248
+ * `build-side-character-context@1` has no such port on purpose:
2249
+ * another member's secret must never reach it.
2250
+ */
2251
+ castRelationships: S.candidates,
2252
+ },
2253
+ out: contextPorts.out,
2254
+ },
2255
+ }));
2256
+ /**
2257
+ * The narrator's context for a planned turn — the one builder that takes a
2258
+ * **plan**.
2259
+ *
2260
+ * `plan` is the only genuinely new thing in this file's three types: the
2261
+ * structured object the planning step produced, put on the template context
2262
+ * under `plan` so the narrator's story string can render its beats and its
2263
+ * world hints. It is a port rather than a nested literal on `state` because the
2264
+ * two are different facts and a template author should be able to tell which is
2265
+ * which — `state.world.weather` is what the world IS, `plan.worldHints` is what
2266
+ * this turn was asked to make of it.
2267
+ *
2268
+ * `narratorName` rides the prompts slot, as it does on `build-narrator-context@1`
2269
+ * and for the same reason: it is the name on the seed line the model continues
2270
+ * from, which is a setting somebody stored rather than data a trigger carried.
2271
+ * @experimental
2272
+ */
2273
+ export const buildSceneContext = pin(describeTaskDefinition({
2274
+ id: 'core:task/build-scene-context@1',
2275
+ i18n: { name: { en: 'Build scene context' } },
2276
+ timeoutMs: 2000,
2277
+ slots: agentContextSlots({
2278
+ systemPrompt: { type: 'text' },
2279
+ postHistoryInstructions: { type: 'text' },
2280
+ narratorName: { type: 'text' },
2281
+ }),
2282
+ ports: {
2283
+ in: {
2284
+ cast: contextPorts.in.cast,
2285
+ state: S.json,
2286
+ /** What the planning step decided this turn is about. */
2287
+ plan: S.json,
2288
+ /**
2289
+ * The session's own genre fields, by key — `tone`,
2290
+ * `difficulty` and whatever else the genre declared.
2291
+ *
2292
+ * On the template context under their own names, so an
2293
+ * authored prompt writes `{{tone}}` the way it writes
2294
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2295
+ * declaration promises: declared on the genre, edited in
2296
+ * session settings, stored on the row, published by the input
2297
+ * node, and read here by the agent whose wording depends on
2298
+ * them. Without this port the last step was missing and a
2299
+ * prompt naming `{{tone}}` rendered a blank.
2300
+ */
2301
+ fields: S.json,
2302
+ /**
2303
+ * What the person just sent, when the genre reads it as
2304
+ * **direction** rather than as a line somebody said
2305
+ * (2026-09-27) — the Lair's composer. On the template
2306
+ * context and in the prompt as `{{turnDirection}}`; empty or
2307
+ * absent on a turn nobody directed (a Continue), so a prompt
2308
+ * writes `{{#if turnDirection}}…{{/if}}`. A genre whose composer
2309
+ * text is a participant's line leaves it unwired: that line is
2310
+ * already in the transcript. *Turn* direction, never bare
2311
+ * `direction`: that word is the Lair's standing-note state slot
2312
+ * (`core:slot/direction@1`), a different fact (one word, one
2313
+ * meaning; renamed 2026-09-27).
2314
+ */
2315
+ turnDirection: S.text,
2316
+ /**
2317
+ * The places the lorebook holds — a
2318
+ * `core:query/lorebook-entries@1` listing of location entries
2319
+ * (2026-09-27). On the template context as
2320
+ * `{{knownLocations}}` (their names, one line) and
2321
+ * `{{locationEntry}}` (the room the world's `location` names,
2322
+ * else the planner's location hint — where the party are, its
2323
+ * exits included), whatever the retrieval ranking admitted: a
2324
+ * planner that is never shown the room it stands in cannot
2325
+ * tell an open door from an unbuilt one. Both are absent when
2326
+ * nothing is listed.
2327
+ */
2328
+ locationEntries: S.json,
2329
+ /**
2330
+ * **Side talk** (2026-09-28), on the
2331
+ * planner's terms: the Lair's Sanctum talk since the story's
2332
+ * last line, rendered as prose into `{{sideTalk}}` — for the
2333
+ * Castellan's narration, wired while the session's _Sanctum
2334
+ * talk steers the story_ is on, or when Narrate was pressed in
2335
+ * the Sanctum. Absent when unwired or empty.
2336
+ */
2337
+ sideTalk: S.messages,
2338
+ /**
2339
+ * How the cast stand with each other, on the narrator's terms
2340
+ * — the same port as the planner's (2026-09-29), rendered
2341
+ * as `{{castRelationships}}`. See `buildPlannerContext`.
2342
+ */
2343
+ castRelationships: S.candidates,
2344
+ /**
2345
+ * **Whose lines this call writes** (Lair party speech,
2346
+ * 2026-09-30): a list of side-character facts — the planner's
2347
+ * `{ name, intent }`, or `{ characterId }` for a picked
2348
+ * delver — rendered as `{{partySpeakers}}`, one line per
2349
+ * speaker in order: the name the cast gives them, then what
2350
+ * they mean to do when the fact says. A nested list is read
2351
+ * flat, so a spec may hand `[first, rest]` from
2352
+ * `split-first@1` as it is. A name the cast does not hold is
2353
+ * kept as written. Absent when unwired or empty.
2354
+ *
2355
+ * For a call that writes the cast's lines **as nobody's
2356
+ * voice** — the Lair's Castellan speaking for the party: this
2357
+ * surface hears no holder-only slot and reads no member's
2358
+ * private lore, so naming the speakers here gives away nothing
2359
+ * a voice of their own would keep.
2360
+ */
2361
+ partySpeakers: S.json,
2362
+ /**
2363
+ * 🚧 **Which places' stats this surface reads** (place sight,
2364
+ * owner ruling 2026-09-30), a literal: `'reach'` — the place
2365
+ * the scene is at and the places one way from it (the room's
2366
+ * listed links to other places, the "From here:" ways); every
2367
+ * other place's stats are left out, its name kept. Absent, the
2368
+ * session's sight: every place it sees. The Lair's Castellan
2369
+ * speaking for the party wires `'reach'`; its narration does
2370
+ * not.
2371
+ */
2372
+ placeSight: S.json,
2373
+ },
2374
+ out: contextPorts.out,
2375
+ },
2376
+ }));
2377
+ /**
2378
+ * The state-keeper's context: the state as it stands, so the keeper can report
2379
+ * only what the scene changed about it.
2380
+ *
2381
+ * Its own type rather than the planner's because the two read the same facts
2382
+ * for opposite purposes — one is deciding what should happen, the other is
2383
+ * writing down what did — and a shared pool would ship them one set of
2384
+ * instructions.
2385
+ * @experimental
2386
+ */
2387
+ export const buildKeeperContext = pin(describeTaskDefinition({
2388
+ id: 'core:task/build-keeper-context@1',
2389
+ i18n: { name: { en: 'Build state keeper context' } },
2390
+ timeoutMs: 2000,
2391
+ slots: agentContextSlots({
2392
+ systemPrompt: { type: 'text' },
2393
+ postHistoryInstructions: { type: 'text' },
2394
+ }),
2395
+ ports: {
2396
+ in: {
2397
+ cast: contextPorts.in.cast,
2398
+ state: S.json,
2399
+ /**
2400
+ * The reply this keeper is reading, as text — put on the
2401
+ * template context under `reply`, because the thing a keeper
2402
+ * reports on is the scene that was just written and the
2403
+ * transcript does not contain it yet.
2404
+ */
2405
+ reply: S.text,
2406
+ /**
2407
+ * ⚠ **An ORDERING edge, and nothing else reads it.**
2408
+ *
2409
+ * A state change is anchored to the newest message in the
2410
+ * session, which is how a swipe takes its changes back with it.
2411
+ * So the keeper has to run AFTER the reply is written, not
2412
+ * merely beside it — and in a graph whose order is its edges,
2413
+ * the only way to say "after that write" is to take the write's
2414
+ * result on a port. It is the write result rather than the text
2415
+ * for exactly that reason: the text exists before the write and
2416
+ * would order nothing.
2417
+ *
2418
+ * ⚠ Typed `json`, NOT `write-result@1`, and the difference is
2419
+ * the standing rule rather than a convenience.
2420
+ * `core:shape/write-result@1` is deliberately accepted nowhere:
2421
+ * under async review a write is a proposal a reviewer may still
2422
+ * reject, so a port declaring that shape is a port promising to
2423
+ * handle both arms of it. This node handles neither — it never
2424
+ * looks inside — and declaring the shape would claim otherwise.
2425
+ * `json` is the honest type for a value taken as opaque, and
2426
+ * write results are assignable to it like everything else.
2427
+ */
2428
+ afterWrite: S.json,
2429
+ /**
2430
+ * The session's own genre fields, by key — `tone`,
2431
+ * `difficulty` and whatever else the genre declared.
2432
+ *
2433
+ * On the template context under their own names, so an
2434
+ * authored prompt writes `{{tone}}` the way it writes
2435
+ * `{{char}}`. That is the whole round trip the genre's `fields`
2436
+ * declaration promises: declared on the genre, edited in
2437
+ * session settings, stored on the row, published by the input
2438
+ * node, and read here by the agent whose wording depends on
2439
+ * them. Without this port the last step was missing and a
2440
+ * prompt naming `{{tone}}` rendered a blank.
2441
+ */
2442
+ fields: S.json,
2443
+ /**
2444
+ * 🚧 **How much time the player chose** (live scenes §15 G6,
2445
+ * 2026-10-13): a collected clock step, `{ by, unit }` — the
2446
+ * inlet's `clockStep` on a *Time passes…* press. Spelled on the
2447
+ * template context as `{{clockStep}}` (`3 hours`, `1 day`,
2448
+ * `2 hours back`), so the keeper describes what the world does
2449
+ * over the span the player picked rather than one notch of
2450
+ * the time of day. Absent when unwired or not a step.
2451
+ */
2452
+ clockStep: S.json,
2453
+ },
2454
+ out: contextPorts.out,
2455
+ },
2456
+ }));
2457
+ /**
2458
+ * Chat rows into the objects a template renders.
2459
+ *
2460
+ * A Task rather than part of the history Query, because naming a message —
2461
+ * which participant said it, under what name at the time — is a *decision*, and
2462
+ * decisions are the things a plugin should be able to replace. The Query returns
2463
+ * rows; this says who spoke.
2464
+ * @public
2465
+ */
2466
+ export const processMessages = pin(describeTaskDefinition({
2467
+ id: 'core:task/process-messages@1',
2468
+ i18n: { name: { en: 'Process messages' } },
2469
+ timeoutMs: 1000,
2470
+ slots: {
2471
+ /**
2472
+ * The message-rewrite hook, on the *processed* list —
2473
+ * names resolved, per-message interpolation done. `transform` only:
2474
+ * `messages/inject` deliberately does **not** live here. Injection
2475
+ * is a statement about *position in the rendered conversation*, and
2476
+ * position belongs to the template (ruling of 2026-08-23) —
2477
+ * inject chains attach on the context builders, land as
2478
+ * `context.injections`, and the template's own loop renders them.
2479
+ * Splicing rows into this list would be a position the template
2480
+ * cannot express and an author cannot see.
2481
+ */
2482
+ scripts: {
2483
+ kind: 'scripts',
2484
+ accepts: ['core:script:messages/transform@1'],
2485
+ port: 'main',
2486
+ phase: 'after',
2487
+ description: 'Scripts over the message list the model will see — rewrite or drop lines. Reminders at a depth attach on the context step instead.',
2488
+ },
2489
+ },
2490
+ ports: {
2491
+ in: {
2492
+ messages: S.messages,
2493
+ cast: S.sessionCast,
2494
+ templateContext: S.templateContext,
2495
+ seedName: S.text,
2496
+ /**
2497
+ * Text the model is being asked to CONTINUE — the seed line's
2498
+ * body rather than a message of its own (ruling 2026-09-08).
2499
+ *
2500
+ * ⚠ **Absent on an ordinary turn, and that is the normal case.**
2501
+ * There is no `optional` marker for a port: a port nothing wires
2502
+ * resolves to `undefined`, the seed line renders empty, and the
2503
+ * model starts the reply. Every spec but an extend leaves it
2504
+ * unwired on purpose.
2505
+ *
2506
+ * It is a port rather than a second synthetic message because a
2507
+ * partial reply is not a turn: appending it as one produces two
2508
+ * consecutive assistant entries on a chat endpoint and a
2509
+ * wrongly-closed block on a completion one. The seed is the one
2510
+ * place in the prompt whose block is deliberately left open
2511
+ * (`includeClose: false` for id -2), which is exactly what a
2512
+ * continuation needs.
2513
+ *
2514
+ * ⚠ It is **not** a stored message, and nothing downstream may
2515
+ * treat it as one. The row holding it is `isGenerating` and is
2516
+ * excluded from every message read, so lore scans, semantic and
2517
+ * entity queries and history windows do not see it. It counts
2518
+ * against the token budget, because it is in the prompt.
2519
+ */
2520
+ continuationPrefill: S.text,
2521
+ },
2522
+ out: { main: S.messages, messages: S.messages },
2523
+ },
2524
+ }));
2525
+ /**
2526
+ * The conversation as PROSE, for a step that reads it rather than takes a turn.
2527
+ *
2528
+ * Two differences from `process-messages@1`, and both are properties of the
2529
+ * transcript rather than of the request, which is why they live here and not on
2530
+ * the Provider: by the time a prompt is rendered for a completion wire the
2531
+ * conversation is one string with an open block at the end of it, and nothing
2532
+ * downstream can take either of them back out.
2533
+ *
2534
+ * · **No seed.** `process-messages@1` ends its list with an empty assistant
2535
+ * line carrying the next speaker's name, because that line is what tells a
2536
+ * model whose turn it is. A planner and a state keeper are not taking a
2537
+ * turn, and a prompt that ends `Verity:` asks for Verity's next paragraph
2538
+ * however plainly the instructions asked for JSON.
2539
+ * · **No JSON blocks.** A reply that carried a document at the end of it
2540
+ * teaches the next turn's planner its own schema and the keeper somebody
2541
+ * else's. The cut happens on the way into the prompt and never on the
2542
+ * stored row — see `prompt/jsonBlocks.ts`.
2543
+ *
2544
+ * Everything else is the same naming and the same interpolation, from the same
2545
+ * implementation: who spoke, under what name at the time, reaching through
2546
+ * participants who have since left.
2547
+ * @public
2548
+ */
2549
+ export const proseTranscript = pin(describeTaskDefinition({
2550
+ id: 'core:task/prose-transcript@1',
2551
+ i18n: { name: { en: 'Transcript as prose' } },
2552
+ timeoutMs: 1000,
2553
+ ports: {
2554
+ in: {
2555
+ messages: S.messages,
2556
+ cast: S.sessionCast,
2557
+ templateContext: S.templateContext,
2558
+ },
2559
+ out: { main: S.messages, messages: S.messages },
2560
+ },
2561
+ }));
2562
+ /**
2563
+ * 🚧 **Where each line's attachments go** (owner rulings of 2026-10-02).
2564
+ *
2565
+ * Pure. Takes the processed lines and the attachments by message, and gives
2566
+ * each line an `attachments` string the template renders after the line's text
2567
+ * (`{{{attachments}}}` in the shipped template):
2568
+ *
2569
+ * - an image or PDF the call can read, within `mediaLookback` messages of the
2570
+ * end, becomes a **media marker** the prompt parser lifts onto that line's
2571
+ * own turn;
2572
+ * - a text file becomes a fenced block with its name, trimmed to
2573
+ * `textFileTokens` with a stated note — never silently;
2574
+ * - anything else — a kind the call cannot read, or media older than the
2575
+ * lookback — becomes a **placeholder**: `[image: cat.png]`, with the
2576
+ * person's description when there is one.
2577
+ *
2578
+ * What the call can read comes from its `connection` slot — wire it with
2579
+ * `slot.connectionOf('<the step that sends the prompt>')` — whose descriptor
2580
+ * carries `metadata.reads` (`ConnectionReadsV1`). Unwired, the call reads no
2581
+ * media and every image is a name: what a text-only step such as a summary
2582
+ * wants. A line with no files is passed through untouched, so a transcript
2583
+ * with no attachments renders byte for byte what it did without this step.
2584
+ *
2585
+ * `notes` are sentences for the run's receipt ("2 images older than the media
2586
+ * lookback were sent as names").
2587
+ * @experimental
2588
+ */
2589
+ export const placeAttachments = pin(describeTaskDefinition({
2590
+ id: 'core:task/place-attachments@1',
2591
+ i18n: { name: { en: 'Place attachments' } },
2592
+ timeoutMs: 1000,
2593
+ slots: {
2594
+ connection: {
2595
+ kind: 'connection',
2596
+ shape: S.textGen,
2597
+ 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.',
2598
+ },
2599
+ params: {
2600
+ kind: 'parameters',
2601
+ facet: 'weights',
2602
+ schema: {
2603
+ mediaLookback: {
2604
+ type: 'integer',
2605
+ min: 0,
2606
+ default: 10,
2607
+ label: { en: 'Media lookback (messages)' },
2608
+ description: {
2609
+ 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.',
2610
+ },
2611
+ },
2612
+ textFileTokens: {
2613
+ type: 'integer',
2614
+ min: 0,
2615
+ default: 4000,
2616
+ label: { en: 'Text file budget (tokens)' },
2617
+ description: {
2618
+ 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.',
2619
+ },
2620
+ },
2621
+ },
2622
+ },
2623
+ },
2624
+ ports: {
2625
+ in: { messages: S.messages, attachments: S.mediaByMessage },
2626
+ out: { main: S.messages, messages: S.messages, notes: S.json },
2627
+ },
2628
+ }));
2629
+ /**
2630
+ * The turn-order pool, orderer and strategies (re-ported in place
2631
+ * 2026-09-22, pre-release).
2632
+ *
2633
+ * Turn order is **state**, not a decision made inside the reply run.
2634
+ * One spec per genre — `core:spec/<genre>-turn-order` — answers a session event by
2635
+ * reading the cast and the history, pooling who *may* be seated, ordering
2636
+ * them, turning them into entries, and writing the result to
2637
+ * `sessions.metadata.turnOrder`. The reply run then fires an entry; it
2638
+ * decides nothing.
2639
+ *
2640
+ * Three node families, composable in that order:
2641
+ *
2642
+ * - **the pool** (`turn-pool`) decides who may be seated at all, from the
2643
+ * settings document's cast. Its params are the genre's and the session's
2644
+ * to set; its floors are not (a removed row is never a candidate, and an
2645
+ * `on-action` envoy speaks only through its action).
2646
+ * - **an orderer** (`turn-mentioned`) rewrites the candidate list's order
2647
+ * and hands on the same shape, so any number of them compose.
2648
+ * - **a strategy** turns candidates into *entries*: who speaks, where, and
2649
+ * what to fire. It is the last node before the write.
2650
+ *
2651
+ * ⚠ **No `speaker` in-port, and no halt**. An explicit pick never
2652
+ * enters a strategy — a person's pick is fired directly (`fireTurnEntry`)
2653
+ * and the next recompute sees the row it produced — and a strategy
2654
+ * that seats nobody publishes an **empty order**, which is an answer. The
2655
+ * halt (`nobody is due`) and the `characterId` port went with the decider
2656
+ * they belonged to.
2657
+ */
2658
+ const turnStrategy = (id, label, extras = {}) => describeTaskDefinition({
2659
+ id,
2660
+ i18n: { name: { en: label } },
2661
+ timeoutMs: 1000,
2662
+ ...extras,
2663
+ ports: {
2664
+ in: {
2665
+ /** Who may be seated — the pool's output, through any orderers. */
2666
+ candidates: S.turnCandidates,
2667
+ /** The session's visible history, ascending. */
2668
+ messages: S.messages,
2669
+ },
2670
+ out: {
2671
+ /**
2672
+ * The prepared turns, in order. `main` and `order` carry the
2673
+ * same value: `main` is what the shape-based swap list keys
2674
+ * on (a strategy is a node publishing `turn-entries@1`), and
2675
+ * `order` is what `set-turn-order` is wired from, named for
2676
+ * what it is.
2677
+ */
2678
+ main: S.turnEntries,
2679
+ order: S.turnEntries,
2680
+ },
2681
+ },
2682
+ });
2683
+ /**
2684
+ * Round robin: the candidates that have not spoken since the last user row,
2685
+ * in candidate order. A character spoke when a non-hidden, non-narrator row
2686
+ * after the last user row carries its id; an envoy when `metadata.speaker`
2687
+ * carries its reference; a persona when a user row carries its `personaId`
2688
+ * — which is how a session knows it is the person's turn.
2689
+ * @experimental
2690
+ */
2691
+ export const turnRoundRobin = pin(turnStrategy('core:task/turn-round-robin@1', 'Round robin'));
2692
+ /**
2693
+ * A seeded uniform pick over the not-yet-spoken candidates — one entry.
2694
+ * `declaresRandomness`, so a replayed run re-rolls identically; an
2695
+ * unrelated recompute may roll differently, which is documented rather than
2696
+ * prevented.
2697
+ * @experimental
2698
+ */
2699
+ export const turnRandom = pin(turnStrategy('core:task/turn-random@1', 'Random', {
2700
+ declaresRandomness: true,
2701
+ }));
2702
+ /**
2703
+ * Round robin over the candidates whose `ownerUserId` is the last sender's,
2704
+ * so one person's cast completes a turn before another's; plain round robin
2705
+ * when that set is empty. The rule narrows, it never starves.
2706
+ * @experimental
2707
+ */
2708
+ export const turnUserSplit = pin(turnStrategy('core:task/turn-user-split@1', 'Round robin by user'));
2709
+ /**
2710
+ * Round robin, with the `select` point free to rewrite it: the host hands
2711
+ * `{ order, candidates, lastSpeaker, sinceUser }` to a
2712
+ * `core:script:turn/select@1` chain and keeps the entries it returns whose
2713
+ * `ref` is a candidate — a script cannot seat somebody the pool did not
2714
+ * admit, and a refusal is a receipt note. Entries the chain changed carry
2715
+ * `via: 'script'`.
2716
+ * @experimental
2717
+ */
2718
+ export const turnScripted = pin(turnStrategy('core:task/turn-scripted@1', 'Scripted', {
2719
+ scriptPoints: [
2720
+ {
2721
+ key: 'select',
2722
+ accepts: ['core:script:turn/select@1'],
2723
+ label: { en: 'Order the turns' },
2724
+ description: {
2725
+ en: 'Scripts that rewrite the prepared order, in order — each is handed the order so far and hands one back.',
2726
+ },
2727
+ },
2728
+ ],
2729
+ }));
2730
+ /** Always an empty order: nothing is prepared, and every turn is a press. @experimental */
2731
+ export const turnManual = pin(turnStrategy('core:task/turn-manual@1', 'Manual'));
2732
+ /**
2733
+ * One entry in the pipeline's own voice (`{ ref: null, via: 'voice' }`) when
2734
+ * the last row is a user row, else empty. How a planner genre — Adventure,
2735
+ * the Lair, the Whodunit showcase plugin — gets exactly one reply per send
2736
+ * with no cast in the pool at all.
2737
+ * @experimental
2738
+ */
2739
+ export const turnNarrator = pin(turnStrategy('core:task/turn-narrator@1', 'Narrator replies'));
2740
+ /**
2741
+ * The pool: who *may* be seated this recompute, from the settings
2742
+ * document's cast and the history.
2743
+ *
2744
+ * Its four params are the whole of a genre's or a session's say over
2745
+ * eligibility. Two floors are not params, because a param that could
2746
+ * override them would be a way to seat somebody who has left: a row with
2747
+ * `removedAt` is never a candidate, and an envoy declared `speaks:
2748
+ * 'on-action'` is never a candidate — it speaks through its action's
2749
+ * outputs alone.
2750
+ *
2751
+ * Output order is characters by `position`, then personas by `position`,
2752
+ * then envoys by `position`. An orderer may rewrite it; a strategy reads it
2753
+ * as given.
2754
+ * @experimental
2755
+ */
2756
+ export const turnPool = pin(describeTaskDefinition({
2757
+ id: 'core:task/turn-pool@1',
2758
+ i18n: { name: { en: 'Turn pool' } },
2759
+ timeoutMs: 1000,
2760
+ slots: {
2761
+ params: {
2762
+ kind: 'parameters',
2763
+ facet: 'behavior',
2764
+ schema: {
2765
+ characters: {
2766
+ type: 'enum',
2767
+ of: ['active', 'all', 'none'],
2768
+ members: [
2769
+ {
2770
+ key: 'active',
2771
+ label: { en: 'Active' },
2772
+ description: { en: 'The characters switched on in the cast.' },
2773
+ },
2774
+ {
2775
+ key: 'all',
2776
+ label: { en: 'All' },
2777
+ description: { en: 'Ones switched off in the cast too.' },
2778
+ },
2779
+ { key: 'none', label: { en: 'None' } },
2780
+ ],
2781
+ default: 'active',
2782
+ label: { en: 'Characters' },
2783
+ description: {
2784
+ en: "Which of the session's characters may take a turn. 'All' admits ones switched off in the cast; a removed character never is.",
2785
+ },
2786
+ },
2787
+ personas: {
2788
+ type: 'enum',
2789
+ of: ['none', 'all', 'others'],
2790
+ members: [
2791
+ { key: 'none', label: { en: 'None' } },
2792
+ {
2793
+ key: 'all',
2794
+ label: { en: 'All' },
2795
+ description: { en: 'Everyone in the session.' },
2796
+ },
2797
+ {
2798
+ key: 'others',
2799
+ label: { en: 'Others' },
2800
+ description: { en: 'Everyone but whoever just wrote.' },
2801
+ },
2802
+ ],
2803
+ default: 'all',
2804
+ label: { en: 'Personas' },
2805
+ description: {
2806
+ 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.",
2807
+ },
2808
+ },
2809
+ envoys: {
2810
+ type: 'enum',
2811
+ of: ['in-turn', 'none', 'only', 'except'],
2812
+ members: [
2813
+ {
2814
+ key: 'in-turn',
2815
+ label: { en: 'Those that take turns' },
2816
+ description: {
2817
+ en: 'Envoys declared to speak in turn; one that speaks only on an action never does.',
2818
+ },
2819
+ },
2820
+ { key: 'none', label: { en: 'None' } },
2821
+ {
2822
+ key: 'only',
2823
+ label: { en: 'Only' },
2824
+ description: { en: 'Only the envoys in the list below.' },
2825
+ },
2826
+ {
2827
+ key: 'except',
2828
+ label: { en: 'Except' },
2829
+ description: { en: 'Every envoy but those in the list below.' },
2830
+ },
2831
+ ],
2832
+ default: 'in-turn',
2833
+ label: { en: 'Envoys' },
2834
+ description: {
2835
+ en: "Which of the genre's envoys may take a turn. 'Only' and 'Except' read the list below.",
2836
+ },
2837
+ },
2838
+ envoySlugs: {
2839
+ type: 'string',
2840
+ list: true,
2841
+ default: [],
2842
+ label: { en: 'Envoy list' },
2843
+ description: {
2844
+ en: "The envoys 'Only' admits, or 'Except' leaves out. Ignored otherwise.",
2845
+ },
2846
+ },
2847
+ },
2848
+ },
2849
+ },
2850
+ ports: {
2851
+ in: {
2852
+ /** The settings document's cast, envoys included. */
2853
+ cast: S.sessionCast,
2854
+ /** The session's visible history, ascending. */
2855
+ messages: S.messages,
2856
+ },
2857
+ out: { main: S.turnCandidates },
2858
+ },
2859
+ }));
2860
+ /**
2861
+ * The first orderer: mentioned candidates sort to the front.
2862
+ *
2863
+ * A composable node rather than a seventh strategy, because "who was named"
2864
+ * and "whose turn it is" are two questions — a session can have the
2865
+ * mentioned rule under round robin, under user-split or under a plugin's
2866
+ * strategy by placing this before any of them.
2867
+ *
2868
+ * Case-insensitive whole-word match of each candidate's `name` and
2869
+ * `nickname` against the most recent `lookback` **user** rows; mentioned
2870
+ * candidates move to the front ordered by first mention, and the rest keep
2871
+ * the order they arrived in. The receipt records `mentioned`. (A
2872
+ * gazetteer-backed match is a later improvement; this is names.)
2873
+ * @experimental
2874
+ */
2875
+ export const turnMentioned = pin(describeTaskDefinition({
2876
+ id: 'core:task/turn-mentioned@1',
2877
+ i18n: { name: { en: 'Mentioned first' } },
2878
+ timeoutMs: 1000,
2879
+ slots: {
2880
+ params: {
2881
+ kind: 'parameters',
2882
+ facet: 'behavior',
2883
+ schema: {
2884
+ lookback: {
2885
+ type: 'integer',
2886
+ default: 1,
2887
+ min: 1,
2888
+ label: { en: 'Messages scanned' },
2889
+ description: {
2890
+ en: 'How many of your most recent messages are read for names.',
2891
+ },
2892
+ },
2893
+ },
2894
+ },
2895
+ },
2896
+ ports: {
2897
+ in: { candidates: S.turnCandidates, messages: S.messages },
2898
+ out: { main: S.turnCandidates },
2899
+ },
2900
+ }));
2901
+ /**
2902
+ * Card strokes — marks each keyword stroke fired or not against the recent
2903
+ * transcript; never ranks, never budgets.
2904
+ *
2905
+ * A card painted in strokes (`strokes.ts`) carries keyword strokes: prose that
2906
+ * belongs in the prompt only when one of its keys was said. Unrun, every
2907
+ * enabled stroke is in — the card's cached `description`/`personality` — and
2908
+ * nothing is lost but room. Placed before the context builder, this stamps
2909
+ * `fired` on every stroke of every cast member (`resolveStrokes`), and the
2910
+ * builder then compiles `always` + fired ones only and puts the resolved list
2911
+ * on the card (`core:var/characters@1`'s optional `strokes`).
2912
+ *
2913
+ * The host answers each keyword condition with the lore keyword **matcher**
2914
+ * — the same match modes and regex time limit, one matcher at the seam — but
2915
+ * a stroke is not a lorebook entry: it never reaches the ranker, the lore
2916
+ * budget or `select`, and never competes with lore for room.
2917
+ *
2918
+ * `cast` in, `cast` out, so it slots between the cast read and the builder
2919
+ * without either changing; a card with no strokes passes through as it came.
2920
+ * The window is the last `scanDepth` rows of `messages`, defaulting to the
2921
+ * lore scan's 10 for the reason given there: a round grows with the cast.
2922
+ * Pure — the explicit step "no magic in core" asks for, placed in a spec.
2923
+ *
2924
+ * ⏸ Paused 2026-10-11 (owner): no core spec places this step and the app hides strokes behind `STROKES_ENABLED`; kept so stored documents and the registry hash stay stable.
2925
+ * @experimental
2926
+ */
2927
+ export const cardStrokes = pin(describeTaskDefinition({
2928
+ id: 'core:task/card-strokes@1',
2929
+ i18n: {
2930
+ name: { en: 'Card strokes' },
2931
+ description: {
2932
+ en: 'Marks each keyword stroke fired or not against the recent transcript; never ranks, never budgets.',
2933
+ },
2934
+ },
2935
+ timeoutMs: 1000,
2936
+ slots: {
2937
+ params: {
2938
+ kind: 'parameters',
2939
+ facet: 'behavior',
2940
+ schema: {
2941
+ scanDepth: {
2942
+ type: 'integer',
2943
+ default: 10,
2944
+ min: 1,
2945
+ label: { en: 'Messages scanned for stroke keywords' },
2946
+ description: {
2947
+ en: "How many recent messages are read for a keyword stroke's keys.",
2948
+ },
2949
+ },
2950
+ },
2951
+ },
2952
+ },
2953
+ ports: {
2954
+ in: { cast: S.sessionCast, messages: S.messages },
2955
+ out: { main: S.sessionCast, cast: S.sessionCast },
2956
+ },
2957
+ }));
2958
+ /**
2959
+ * Tool calling's two pure halves. A *tool* is any same-shaped
2960
+ * provider — a sandboxed plugin hook canonically — and these tasks only
2961
+ * decide how the model learns about it and how its answer is read back.
2962
+ * Between them sits the ordinary generate step; around them sits the loop
2963
+ * block, whose iterations are the receipted agentic turn.
2964
+ * @experimental
2965
+ */
2966
+ export const advertiseTools = pin(describeTaskDefinition({
2967
+ id: 'core:task/advertise-tools@1',
2968
+ i18n: { name: { en: 'Advertise tools' } },
2969
+ timeoutMs: 500,
2970
+ slots: {
2971
+ params: {
2972
+ kind: 'parameters',
2973
+ schema: {
2974
+ style: {
2975
+ type: 'enum',
2976
+ of: ['native', 'prompt'],
2977
+ members: [
2978
+ {
2979
+ key: 'native',
2980
+ label: { en: 'Native tool calling' },
2981
+ description: { en: "Hands the declarations to the API's own tool-calling." },
2982
+ },
2983
+ {
2984
+ key: 'prompt',
2985
+ label: { en: 'In the prompt' },
2986
+ description: { en: 'Writes them into the context, for models without tool-calling.' },
2987
+ },
2988
+ ],
2989
+ default: 'prompt',
2990
+ description: "How the model learns its tools: natively through the API's own tool-calling, or written into the prompt for models without one.",
2991
+ },
2992
+ },
2993
+ },
2994
+ },
2995
+ ports: {
2996
+ // [{ name, description, parameters }] — parameters as JSON Schema.
2997
+ in: { tools: S.json },
2998
+ out: { main: S.json, native: S.json, prompt: S.text },
2999
+ },
3000
+ }));
3001
+ /** @experimental */
3002
+ export const parseToolCall = pin(describeTaskDefinition({
3003
+ id: 'core:task/parse-tool-call@1',
3004
+ i18n: { name: { en: 'Parse tool call' } },
3005
+ timeoutMs: 500,
3006
+ ports: {
3007
+ in: { text: S.text, tools: S.json },
3008
+ // `call` is { tool, args } | null — null is the loop's exit
3009
+ // predicate, not an error: a reply with no call is the model being
3010
+ // done. `text` is the reply with the call block stripped, so what
3011
+ // renders is prose and what dispatches is data.
3012
+ out: { main: S.json, call: S.json, text: S.text },
3013
+ },
3014
+ }));
3015
+ /**
3016
+ * A repeated block's outputs, as one string.
3017
+ *
3018
+ * The missing half of `map` and `loop`. Both publish a **list** — `values`, one
3019
+ * entry per iteration — and everything that writes (a message, a lore entry)
3020
+ * takes a scalar, so every spec that repeats anything has needed this and
3021
+ * every spec has had to end at the block. Reducing in a Consumer instead would
3022
+ * put the join inside the write, where no receipt can show it and no author
3023
+ * can change it.
3024
+ *
3025
+ * `path` is what makes it usable on a block: an iteration's value is that
3026
+ * chain's last node's **ports object**, so the interesting text is at
3027
+ * `.text` or `.answer` rather than at the top. Empty entries are skipped
3028
+ * rather than joined, which is what makes "every iteration's answer, and only
3029
+ * the iteration that had one" a wiring rather than a filter node.
3030
+ * @experimental
3031
+ */
3032
+ export const joinText = pin(describeTaskDefinition({
3033
+ id: 'core:task/join-text@1',
3034
+ i18n: { name: { en: 'Join text' } },
3035
+ timeoutMs: 500,
3036
+ slots: {
3037
+ params: {
3038
+ kind: 'parameters',
3039
+ schema: {
3040
+ path: {
3041
+ type: 'string',
3042
+ default: 'text',
3043
+ description: 'Which key to read off each entry. Empty reads the entry itself, for a list of plain strings.',
3044
+ },
3045
+ separator: {
3046
+ type: 'string',
3047
+ default: '\n\n',
3048
+ description: 'What goes between the entries that had something to say.',
3049
+ },
3050
+ },
3051
+ },
3052
+ },
3053
+ ports: { in: { items: S.json }, out: { main: S.text, text: S.text } },
3054
+ }));
3055
+ /**
3056
+ * A document's lists, as one **folded section** a reply carries collapsed
3057
+ * (2026-09-27).
3058
+ *
3059
+ * The producer the message outlets' `sections` in-port was built for: a
3060
+ * planner's document is structure, and the person reading the reply wants its
3061
+ * beats and speakers as a short list under a "Plan" heading — never the JSON,
3062
+ * and never in the body. `path` names the keys read, comma-separated and in
3063
+ * order; each list entry becomes one line, and an object entry reads as its
3064
+ * own text values joined with ` — ` (`sectionItemsOf` in the SDK is the one
3065
+ * reading). A document with nothing to list publishes an empty list, which a
3066
+ * write takes as "no sections".
3067
+ *
3068
+ * `kind` and `label` are parameters, not ports: they are what the section IS,
3069
+ * chosen by whoever wires it, and a model never names them.
3070
+ * @experimental
3071
+ */
3072
+ export const listSection = pin(describeTaskDefinition({
3073
+ id: 'core:task/list-section@1',
3074
+ i18n: { name: { en: 'List section' } },
3075
+ timeoutMs: 500,
3076
+ slots: {
3077
+ params: {
3078
+ kind: 'parameters',
3079
+ schema: {
3080
+ path: {
3081
+ type: 'string',
3082
+ default: '',
3083
+ description: 'Which keys of the document to list, comma-separated and in order. Empty lists the document itself.',
3084
+ },
3085
+ kind: {
3086
+ type: 'string',
3087
+ default: 'notes',
3088
+ description: "The section's kind: a lowercase slug such as 'plan'.",
3089
+ },
3090
+ label: {
3091
+ type: 'string',
3092
+ default: 'Notes',
3093
+ description: "The heading the section's button shows.",
3094
+ },
3095
+ },
3096
+ },
3097
+ },
3098
+ ports: {
3099
+ in: { json: S.json },
3100
+ out: {
3101
+ main: S.foldedSections,
3102
+ sections: S.foldedSections,
3103
+ /**
3104
+ * The same lines as a markdown list, one `- ` item per line
3105
+ * (2026-09-28) — for a message whose BODY is the
3106
+ * list: the Lair's beats row in the Sanctum. Empty when
3107
+ * nothing was listed.
3108
+ */
3109
+ text: S.text,
3110
+ },
3111
+ },
3112
+ }));
3113
+ /**
3114
+ * A list, split into its **first** item and the **rest**, in order
3115
+ * (2026-09-28).
3116
+ *
3117
+ * A data reference is `{node, port}` with no sub-path, and `parse-json@1`'s
3118
+ * `path` selects a key or an index but never a tail — so a spec that treats
3119
+ * the first of a list differently from the others (the Lair's lead delver,
3120
+ * whose line streams into the run's live row, before the rest of the party
3121
+ * speak in an `each`) had no way to name "all but the first". Pure: no read,
3122
+ * no model, 1 ms.
3123
+ *
3124
+ * `first` is absent on an empty list, so a junction on it skips the step
3125
+ * that needs one; `rest` is always a list — empty on a list of one or none —
3126
+ * so an `each` wired to it never has to defend itself. Anything that is not
3127
+ * a list is a list of one.
3128
+ * @experimental
3129
+ */
3130
+ export const splitFirst = pin(describeTaskDefinition({
3131
+ id: 'core:task/split-first@1',
3132
+ i18n: { name: { en: 'Split first' } },
3133
+ timeoutMs: 500,
3134
+ ports: {
3135
+ in: { items: S.json },
3136
+ out: { main: S.json, first: S.json, rest: S.json },
3137
+ },
3138
+ }));
3139
+ /**
3140
+ * A model's JSON answer, read back as data.
3141
+ *
3142
+ * ## Why a Task and not a shape on the Provider
3143
+ *
3144
+ * `core:oracle/generate-text@1` is published and frozen, and it publishes
3145
+ * prose. A pipeline that wants structure out of a model therefore needs one
3146
+ * more step, and that step is the honest place for every way the reading can
3147
+ * fail: a fenced block, a preamble the model could not resist, a reply cut off
3148
+ * by the token limit. Put inside the Provider it would be a second job hidden
3149
+ * in the node that calls the model; here it is a node on the receipt, with its
3150
+ * own timing and its own halt.
3151
+ *
3152
+ * ## `path` is what makes the result WIREABLE
3153
+ *
3154
+ * A data reference is `{node, port}` — there is no sub-path — so a downstream
3155
+ * `map` cannot iterate `plan.speakers` off a port carrying the whole document.
3156
+ * `path` is the answer: the parsed document is always on `json`, and `value`
3157
+ * and `items` carry whatever `path` selects, so one node serves both the step
3158
+ * that reads the whole plan and the block that iterates one list inside it.
3159
+ * `items` is `value` as a list — an absent or single value becomes an empty or
3160
+ * one-element list, so a map wired to it never has to defend itself.
3161
+ *
3162
+ * ## It halts rather than inventing an empty answer
3163
+ *
3164
+ * A reply this node cannot read is a model that did not do what it was asked,
3165
+ * and an empty object published as though it were an answer would travel
3166
+ * downstream as "nothing changed" — indistinguishable from a turn where
3167
+ * genuinely nothing did. `optional: true` on the node is how a spec says it can
3168
+ * live without the structure; the executor then records `recoveredAsEmpty` and
3169
+ * a reader can see which one happened.
3170
+ * @experimental
3171
+ */
3172
+ export const parseJson = pin(describeTaskDefinition({
3173
+ id: 'core:task/parse-json@1',
3174
+ i18n: { name: { en: 'Read JSON' } },
3175
+ timeoutMs: 1000,
3176
+ /**
3177
+ * A reply nobody can read subtracts the structure and nothing else.
3178
+ *
3179
+ * The binding answers `err` with the reason, the executor absorbs it as
3180
+ * `recoveredAsEmpty`, and every downstream port reads absent: a `map`
3181
+ * over the missing list runs zero times, a template renders no block. So
3182
+ * a model that ignored the schema costs a turn its plan, not its reply —
3183
+ * which is the same "an unavailable mechanism subtracts a signal, it
3184
+ * never disables a path" rule retrieval already works by.
3185
+ */
3186
+ optional: true,
3187
+ slots: {
3188
+ params: {
3189
+ kind: 'parameters',
3190
+ schema: {
3191
+ path: {
3192
+ type: 'string',
3193
+ quick: true,
3194
+ description: 'Which value inside the answer to publish on `value` and `items`, as a dotted path. Empty publishes the whole answer.',
3195
+ },
3196
+ },
3197
+ },
3198
+ },
3199
+ ports: {
3200
+ in: { text: S.textStream },
3201
+ out: {
3202
+ main: S.json,
3203
+ /** The whole parsed document, whatever `path` says. */
3204
+ json: S.json,
3205
+ /** The value at `path` — the document itself when `path` is empty. */
3206
+ value: S.json,
3207
+ /** That same value as a list, for a `map` to iterate. */
3208
+ items: S.json,
3209
+ },
3210
+ },
3211
+ }));
3212
+ /** @internal */
3213
+ export const roll = pin(describeTaskDefinition({
3214
+ id: 'chariot.dice-tray:roll@1',
3215
+ i18n: { name: { en: 'Roll dice' } },
3216
+ timeoutMs: 200,
3217
+ declaresRandomness: true,
3218
+ ports: {
3219
+ in: { notation: S.text },
3220
+ out: { main: S.json, total: S.json },
3221
+ },
3222
+ }));
3223
+ /** @internal */
3224
+ export const gate = pin(describeTaskDefinition({
3225
+ id: 'test:task/gate@1',
3226
+ timeoutMs: 500,
3227
+ ports: { in: { main: S.json }, out: { main: S.json } },
3228
+ }));
3229
+ /** @internal */
3230
+ export const slow = pin(describeTaskDefinition({
3231
+ id: 'test:task/slow@1',
3232
+ timeoutMs: 30,
3233
+ ports: { in: { main: S.json }, out: { main: S.json } },
3234
+ }));
3235
+ /** @internal */
3236
+ export const passthrough = pin(describeTaskDefinition({
3237
+ id: 'test:task/passthrough@1',
3238
+ timeoutMs: 500,
3239
+ toggleable: true,
3240
+ ports: { in: { main: S.json }, out: { main: S.json } },
3241
+ }));
3242
+ /** @internal */
3243
+ export const badToggleable = pin(describeTaskDefinition({
3244
+ id: 'test:task/bad-toggleable@1',
3245
+ timeoutMs: 500,
3246
+ toggleable: true,
3247
+ ports: { in: { main: S.text }, out: { main: S.image } },
3248
+ }));
3249
+ /**
3250
+ * A stream consumer with no `earlyExit` declared — the fixture that proves
3251
+ * stream-abandoned. Its `earlyExit: true` twin lives with the SDK's own suite
3252
+ * (`sdk-tests/fixtures.ts`), where the early-exit proofs are.
3253
+ * @internal
3254
+ */
3255
+ export const sloppyStream = pin(describeTaskDefinition({
3256
+ id: 'test:task/sloppy-stream@1',
3257
+ timeoutMs: 5000,
3258
+ ports: { in: { main: S.textStream }, out: { main: S.json } },
3259
+ }));
3260
+ // ── Forms (plans/29 R-15 *Forms* · *The line*; R-21 (5); 30 §U5d, 2026-09-17) ──
3261
+ /**
3262
+ * The form as a prompt and as a schema. Takes the block and the context the
3263
+ * builder compiled for the addressee, and publishes the context with the
3264
+ * question and the options laid in (`formQuestion`, `formOptions` — what the
3265
+ * assembly template renders under the transcript), the JSON Schema the
3266
+ * oracle answers against (`formAnswerSchema`: an enum of the option keys, or
3267
+ * the field schema), and the question as text. Pure; no model, no rows.
3268
+ * @experimental
3269
+ */
3270
+ export const formContext = pin(describeTaskDefinition({
3271
+ id: 'core:task/form-context@1',
3272
+ i18n: { name: { en: 'Form as prompt and schema' } },
3273
+ timeoutMs: 1000,
3274
+ ports: {
3275
+ in: { form: S.json, templateContext: S.templateContext },
3276
+ out: {
3277
+ main: S.templateContext,
3278
+ templateContext: S.templateContext,
3279
+ schema: S.json,
3280
+ question: S.text,
3281
+ },
3282
+ },
3283
+ }));
3284
+ /**
3285
+ * An oracle's question, as blocks. Takes the document a `generate-json@1`
3286
+ * produced — `{ question, options: [{ key, label }], addressee? }` — and the
3287
+ * function the options fire, and publishes a block list holding one
3288
+ * `choices` block: the question on it, its options carrying the keys,
3289
+ * addressed to whom the document names. The document's `addressee` is a
3290
+ * **name** the model read off the transcript or a participant reference; a
3291
+ * name is resolved against `cast` into `character:<id>` (or `envoy:<slug>`),
3292
+ * and the `addressee` in-port, when wired, wins over both. A name nobody in
3293
+ * the cast bears leaves the block unaddressed — buttons, not a form. The
3294
+ * host stamps the action identity and the block id at the write; this task
3295
+ * only shapes. `text` is the question as prose, for the row's own content,
3296
+ * so a transcript that reads content alone still carries what was asked. A
3297
+ * document with no options publishes an empty list and an empty text.
3298
+ * @experimental
3299
+ */
3300
+ export const makeChoices = pin(describeTaskDefinition({
3301
+ id: 'core:task/make-choices@1',
3302
+ i18n: { name: { en: 'Question as choices' } },
3303
+ timeoutMs: 1000,
3304
+ ports: {
3305
+ in: {
3306
+ /** The oracle's document: `{ question, options, addressee? }`. */
3307
+ json: S.json,
3308
+ /** The function every option fires — the block's `fn`. */
3309
+ fn: S.text,
3310
+ /**
3311
+ * The identity of the declaration the options fire, when it is
3312
+ * another spec's (`core:spec/adventure-answer#answer`). Absent,
3313
+ * the host stamps this spec's own declaration for `fn` at the
3314
+ * write.
3315
+ */
3316
+ action: S.text,
3317
+ /** Who the question is put to. Wired, it wins over the document's. */
3318
+ addressee: S.participantRef,
3319
+ /** The cast, to resolve a name the document used into a reference. */
3320
+ cast: S.sessionCast,
3321
+ /**
3322
+ * What the question is about, by name — stamped on the block
3323
+ * as its `referent` and handed back by `read-answer@1` to the
3324
+ * run the press fires (2026-09-27: the room the
3325
+ * party knocked at). Blank or absent writes none.
3326
+ */
3327
+ referent: S.text,
3328
+ /**
3329
+ * Where the question was asked **from**, by name — stamped on
3330
+ * the block as its `vantage` and handed back by
3331
+ * `read-answer@1`, beside `referent` (2026-09-30:
3332
+ * the room the Lair's planner said the party stood in as
3333
+ * they knocked). JSON because it is usually read off a
3334
+ * model's document (`parse-json@1`'s `value`); anything but
3335
+ * a non-blank string writes none.
3336
+ */
3337
+ vantage: S.json,
3338
+ },
3339
+ out: {
3340
+ main: S.json,
3341
+ blocks: S.json,
3342
+ /** The question as prose — the row's content. */
3343
+ text: S.text,
3344
+ /** Who the block was addressed to, resolved; null when nobody. */
3345
+ addressee: S.participantRef,
3346
+ },
3347
+ },
3348
+ }));
3349
+ /**
3350
+ * A form's answer, port by port — for the action a form fires. Takes the
3351
+ * inlet's `payload` (what the press sent) and `form` (the block facts the
3352
+ * host read off the row) and publishes the parts a spec wires: the chosen
3353
+ * option's key and label, the addressee and their character row, the
3354
+ * question, and the answered values. Pure.
3355
+ * @experimental
3356
+ */
3357
+ export const readAnswer = pin(describeTaskDefinition({
3358
+ id: 'core:task/read-answer@1',
3359
+ i18n: { name: { en: 'Read the answer' } },
3360
+ timeoutMs: 1000,
3361
+ ports: {
3362
+ in: { payload: S.json, form: S.json },
3363
+ out: {
3364
+ main: S.json,
3365
+ /** The chosen option's key (`choices`), else null. */
3366
+ choice: S.text,
3367
+ /** The chosen option's label, else null. */
3368
+ label: S.text,
3369
+ /** Who answered, as a participant reference — the form's addressee. */
3370
+ addressee: S.participantRef,
3371
+ /** The addressee's character row, null for an envoy or a person. */
3372
+ characterId: S.rowIds,
3373
+ question: S.text,
3374
+ /**
3375
+ * What the question was about, by name — the block's
3376
+ * `referent`, as the asking run stamped it;
3377
+ * empty when it named nothing, never null, so a write wired
3378
+ * to it still offers the field at its review gate (a review
3379
+ * form shows only the fields a payload carries).
3380
+ */
3381
+ referent: S.text,
3382
+ /**
3383
+ * Where the question was asked from, by name — the block's
3384
+ * `vantage`, as the asking run stamped it; null
3385
+ * when it named nowhere.
3386
+ */
3387
+ vantage: S.json,
3388
+ /** The whole answer: `{ choice }` or the entered values. */
3389
+ values: S.json,
3390
+ },
3391
+ },
3392
+ }));
3393
+ // ── Summarization ───────────────────────────────────────────────────────────
3394
+ /**
3395
+ * Cut the messages into batches a model can hold.
3396
+ *
3397
+ * A Task, not a Query: the cut is a *decision* — how many tokens per batch, and
3398
+ * therefore how much context each draft is written against — and it is the
3399
+ * first parameter a user with long posts reaches for.
3400
+ * @internal
3401
+ */
3402
+ const batchMessagesAt1 = pin(describeTaskDefinition({
3403
+ id: 'core:task/batch-messages@1',
3404
+ i18n: { name: { en: 'Batch messages' } },
3405
+ timeoutMs: 2000,
3406
+ slots: {
3407
+ /**
3408
+ * The window the cut is clamped to — the same slot, by reference,
3409
+ * that the drafting step generates against.
3410
+ *
3411
+ * The context window belongs to the sampling config, never to a knob
3412
+ * on a node, and the executor resolves a `sampling` slot to
3413
+ * the config's switched-on *values* — so this stays a pure Task
3414
+ * reading data it was handed rather than a Query looking one up. Same
3415
+ * shape and same reason as `core:task/context-budget@1`.
3416
+ *
3417
+ * ⚠ Wire it as a REFERENCE to the drafting oracle's sampling slot
3418
+ * (`slot.samplingOf(...)`), not as a picker of its own. A batch cut
3419
+ * against one window and drafted against another is wrong in the
3420
+ * direction that overflows, silently — and unlike the assembled
3421
+ * context there is no truncation on this path to catch it, because
3422
+ * the batch prompt is injected whole.
3423
+ */
3424
+ sampling: { kind: 'sampling', quick: true },
3425
+ params: {
3426
+ kind: 'parameters',
3427
+ facet: 'weights',
3428
+ schema: {
3429
+ /**
3430
+ * The chat half of a batch prompt, and only that half — the
3431
+ * template around it and the room the draft is written back
3432
+ * into are a reserve the binding adds on top, which is why
3433
+ * this can be raised right up to the window minus that
3434
+ * reserve and no further.
3435
+ *
3436
+ * ⚠ Bigger is not better. Long-context models degrade in the
3437
+ * middle, so this is a QUALITY point rather than a fraction
3438
+ * of whatever window happens to be available: nothing scales
3439
+ * it up to fill a large one, and the window is only ever a
3440
+ * ceiling on what an admin asks for.
3441
+ *
3442
+ * 2560 is 0.5's effective batch (`4096 - 1500`) at a round
3443
+ * 2.5 Ki, so arriving here re-tunes nobody.
3444
+ */
3445
+ batchTokens: {
3446
+ type: 'integer',
3447
+ default: 2560,
3448
+ label: { en: 'How much chat each batch holds' },
3449
+ description: {
3450
+ 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.',
3451
+ },
3452
+ },
3453
+ minBatchMessages: {
3454
+ type: 'integer',
3455
+ default: 1,
3456
+ description: 'Never cut a batch smaller than this many messages.',
3457
+ },
3458
+ },
3459
+ },
3460
+ },
3461
+ ports: {
3462
+ /**
3463
+ * `attachments` (2026-10-03, owner ruling on the attachments
3464
+ * follow-ups): the files by message, from
3465
+ * `core:query/history-attachments@1`. Each message that shows
3466
+ * files is batched with a placeholder per file after its text —
3467
+ * `[image: cat.png — a grey cat]`, `[file: notes.txt]` — and the
3468
+ * cut counts them, so a message that is only a picture still
3469
+ * reaches the draft as something. Unwired, or a message with no
3470
+ * files, and the message is batched exactly as it was.
3471
+ */
3472
+ in: { messages: S.messages, attachments: S.mediaByMessage },
3473
+ out: { main: S.drafts, batches: S.drafts },
3474
+ },
3475
+ }));
3476
+ /**
3477
+ * 🚧 What a genre's **transcript template** may read, section by section
3478
+ * (live scenes §12.1/§14). The template is one Handlebars source holding
3479
+ * three inline partials — `{{#*inline "preamble"}}`, `{{#*inline "line"}}`
3480
+ * and `{{#*inline "aside"}}` — and the binding renders each on its own:
3481
+ * `preamble` once, `line` per story message, `aside` per aside row. Text
3482
+ * outside the three partials is never rendered. A section the template does
3483
+ * not define falls back to the shipped Default's.
3484
+ */
3485
+ const TRANSCRIPT_TEMPLATE_SCOPE = {
3486
+ scene: {
3487
+ type: 'object',
3488
+ optional: true,
3489
+ description: 'The scene, in `preamble`: its name, place and date when the host knows them.',
3490
+ fields: {
3491
+ name: { type: 'string', optional: true },
3492
+ place: { type: 'string', optional: true },
3493
+ date: { type: 'string', optional: true },
3494
+ },
3495
+ },
3496
+ cast: {
3497
+ type: 'list',
3498
+ description: 'Who was present, in `preamble`, by name.',
3499
+ of: { type: 'object', fields: { name: { type: 'string' } } },
3500
+ },
3501
+ messageId: { type: 'number', description: 'In `line` and `aside`: the message this unit renders.' },
3502
+ name: { type: 'string', description: 'In `line` and `aside`: who wrote the line, as the session names them.' },
3503
+ role: { type: 'string', description: "In `line` and `aside`: 'user', 'assistant' or 'system'." },
3504
+ text: { type: 'string', description: "In `line` and `aside`: the message's text." },
3505
+ attachments: {
3506
+ type: 'string',
3507
+ description: "In `line` and `aside`: the files the message shows, each named on a line of its own — `[image: cat.png — a grey cat]`, `[file: notes.txt]` — carrying its own leading line break when the message has text, so it renders straight after `{{{text}}}`, as `place-attachments@1`'s does. Empty when the message shows none. A summary is drafted from text, so a file reaches it as its name.",
3508
+ },
3509
+ channel: { type: 'string', description: 'In `aside`: the channel the row was written on — `sanctum`, `sanctum:2`.' },
3510
+ };
3511
+ /**
3512
+ * 🚧 Lay a scene's messages out as text, one **transcript unit** per message
3513
+ * — the genre's own words for what a line and an aside look like (live
3514
+ * scenes §12.1, §14, 2026-10-13).
3515
+ *
3516
+ * ## Why a template, and why it is the spec's
3517
+ *
3518
+ * A summary of the Lair has to say the Sanctum is talk the party never hear;
3519
+ * a summary of Chat has nothing to say about it. That difference is
3520
+ * presentation, so it is a template on this node's `template` slot, and the
3521
+ * shipped template is the summarize-scene spec's Default — a genre ships its
3522
+ * own by building its spec with `summarizeScene(…, { transcript })`, and an
3523
+ * admin edits it in the Pipelines view like any other template.
3524
+ *
3525
+ * ## The outlet
3526
+ *
3527
+ * `preamble` — the rendered `preamble` section, once. `units` — every
3528
+ * story line and aside in reading order (each aside after the story line it
3529
+ * is attached to), `{ messageId, text, tokens }`: the batch cut needs the
3530
+ * count, and the message id is what makes a draft traceable to its rows.
3531
+ * Pure: no model, no write. An empty span renders an empty `units`.
3532
+ * @experimental
3533
+ */
3534
+ export const renderTranscript = pin(describeTaskDefinition({
3535
+ id: 'core:task/render-transcript@1',
3536
+ i18n: { name: { en: 'Lay out the transcript' } },
3537
+ timeoutMs: 2000,
3538
+ slots: {
3539
+ template: {
3540
+ kind: 'template',
3541
+ acceptedEngines: [handlebars.id],
3542
+ facet: 'templates',
3543
+ variables: TRANSCRIPT_TEMPLATE_SCOPE,
3544
+ description: 'How the transcript a summary is drafted from reads: three sections — the preamble, a story line, and an aside. Leave empty to use the built-in layout.',
3545
+ },
3546
+ },
3547
+ ports: {
3548
+ in: {
3549
+ /** The story's rows (`summarize-source@2`'s `messages`). */
3550
+ messages: S.messages,
3551
+ /** The aside rows (`summarize-source@2`'s `asides`). */
3552
+ asides: S.messages,
3553
+ /**
3554
+ * The files by message, from `core:query/history-attachments@1`
3555
+ * over the story rows — `batch-messages@1`'s port, for its
3556
+ * reason: a message that is only a picture still reaches the
3557
+ * draft as something. Each story line's files are named into
3558
+ * the `line` section's `attachments`. Unwired, or a message
3559
+ * with no files, and the line renders as it would without.
3560
+ */
3561
+ attachments: S.mediaByMessage,
3562
+ /**
3563
+ * 🚧 The aside rows' files by message, from a second
3564
+ * `core:query/history-attachments@1` over the asides (lane
3565
+ * E): each aside's files are named into the `aside`
3566
+ * section's `attachments`. Unwired, an aside renders as it
3567
+ * would without.
3568
+ */
3569
+ asideAttachments: S.mediaByMessage,
3570
+ /** Who was present — the session's cast read. */
3571
+ cast: S.sessionCast,
3572
+ /**
3573
+ * The scene being summarized: its name, place and date where the
3574
+ * host knows them. Wired to the summarize request in the shipped
3575
+ * specs; the binding reads the request's `scene` field.
3576
+ */
3577
+ scene: S.json,
3578
+ },
3579
+ out: {
3580
+ main: S.transcriptUnits,
3581
+ preamble: S.text,
3582
+ units: S.transcriptUnits,
3583
+ },
3584
+ },
3585
+ }));
3586
+ /**
3587
+ * 🚧 Cut a rendered transcript into batches a model can hold — `@1`'s cut,
3588
+ * over **text** (live scenes §14, 2026-10-13).
3589
+ *
3590
+ * `@1` cuts message rows and formats them itself; this one is handed units the
3591
+ * transcript template already laid out, counts each unit's `tokens`, and opens
3592
+ * every batch with the `preamble` so each draft knows the scene it is in. A
3593
+ * unit is never split. Out: `batches`, one string per batch, in order. An
3594
+ * empty `units` cuts to no batches. `@1` stays for the shared summarize specs.
3595
+ * @experimental
3596
+ */
3597
+ const batchMessagesAt2 = pin(describeTaskDefinition({
3598
+ id: 'core:task/batch-messages@2',
3599
+ i18n: { name: { en: 'Batch the transcript' } },
3600
+ timeoutMs: 2000,
3601
+ slots: {
3602
+ /**
3603
+ * The window the cut is clamped to — wired by REFERENCE to the
3604
+ * drafting step's sampling, for `@1`'s reason: a batch cut against
3605
+ * one window and drafted against another overflows silently.
3606
+ */
3607
+ sampling: { kind: 'sampling', quick: true },
3608
+ params: {
3609
+ kind: 'parameters',
3610
+ facet: 'weights',
3611
+ schema: {
3612
+ batchTokens: {
3613
+ type: 'integer',
3614
+ default: 2560,
3615
+ label: { en: 'How much chat each batch holds' },
3616
+ description: {
3617
+ en: 'Tokens of transcript one summary draft is written from. Capped by the drafting step\u2019s Context Tokens, less room for the prompt and the draft itself.',
3618
+ },
3619
+ },
3620
+ minBatchMessages: {
3621
+ type: 'integer',
3622
+ default: 1,
3623
+ description: 'Never cut a batch smaller than this many messages.',
3624
+ },
3625
+ },
3626
+ },
3627
+ },
3628
+ ports: {
3629
+ in: { preamble: S.text, units: S.transcriptUnits },
3630
+ out: { main: S.drafts, batches: S.drafts },
3631
+ },
3632
+ }));
3633
+ /**
3634
+ * Cut a summary's material into batches — both pins on one export (04 §4b):
3635
+ * `C.batchMessages.v1(…)` cuts message rows, `C.batchMessages.v2(…)` cuts a
3636
+ * rendered transcript. `id` and `descriptor` stay `@1`'s; `@2`'s descriptor
3637
+ * rides its constructor (`typeof C.batchMessages.v2` types a binding).
3638
+ * @internal
3639
+ */
3640
+ export const batchMessages = {
3641
+ ...batchMessagesAt1,
3642
+ v2: Object.assign(batchMessagesAt2.v2, { descriptor: batchMessagesAt2.descriptor }),
3643
+ };
3644
+ // ── Stats and states ────────────────────────────────────────────────────────
3645
+ /** @experimental */
3646
+ export const setState = pin(describeTaskDefinition({
3647
+ id: 'core:task/set-state@1',
3648
+ i18n: { name: { en: 'Set state' } },
3649
+ timeoutMs: 5000,
3650
+ slots: {
3651
+ params: {
3652
+ kind: 'parameters',
3653
+ schema: {
3654
+ mode: {
3655
+ type: 'enum',
3656
+ of: ['propose', 'apply'],
3657
+ members: [
3658
+ {
3659
+ key: 'propose',
3660
+ label: { en: 'Propose' },
3661
+ description: { en: 'Holds the changes for the player to accept or reject.' },
3662
+ },
3663
+ {
3664
+ key: 'apply',
3665
+ label: { en: 'Apply' },
3666
+ description: {
3667
+ en: 'Writes them immediately, stamped with this run. Only where the pipeline itself decided the number.',
3668
+ },
3669
+ },
3670
+ ],
3671
+ default: 'propose',
3672
+ quick: true,
3673
+ description: "Whether the changes wait for the player or are written at once. Use Apply only where the pipeline itself decided the number.",
3674
+ },
3675
+ },
3676
+ },
3677
+ },
3678
+ ports: {
3679
+ // [{ owner: { kind, id }, slotId, value, base? } | { owner, entryId, delta, base? }]
3680
+ // `scope` is what says which session, and therefore which message a
3681
+ // change is anchored to — a change with no anchor is one a swipe
3682
+ // could not take back. 🚧 A clock line `{ kind: 'clock', by, unit }`
3683
+ // (★3) is held by `propose` as a clock proposal and passed over by
3684
+ // `apply` — see `resolve-state-changes@1`'s `clock` out-port. One
3685
+ // marked `skipped` (a sentence: the story has no clock to take it,
3686
+ // live scenes §15 G16) is written to the session's ledger as a
3687
+ // skipped clock move in either mode — never proposed, never moved
3688
+ // — and its row id rides `main.skipped`.
3689
+ in: {
3690
+ changes: S.json,
3691
+ scope: S.sessionScope,
3692
+ /**
3693
+ * The **state version** the changes are deltas against — the
3694
+ * session-state query's
3695
+ * `version`, for every change that does not carry its own
3696
+ * `base`. In `apply` mode a base behind the current version is
3697
+ * **rebased**: a change whose slot is untouched since the base
3698
+ * still holds and is applied; one whose slot moved is put on
3699
+ * `refused` with the versions named, and the next turn's
3700
+ * `resolve-state-changes` re-resolves it — a run never re-enters
3701
+ * an earlier node. In `propose` mode the base is stamped on the
3702
+ * proposal for the accept to judge the same way. Optional: with
3703
+ * none, the write is against whatever is current.
3704
+ */
3705
+ base: S.json,
3706
+ /**
3707
+ * **The row the WORLD's changes are filed at** (2026-09-28): a
3708
+ * message this run wrote earlier, as that
3709
+ * write's result. Optional, and only for world-owned changes
3710
+ * (the session and its places); a cast member's change still
3711
+ * files at that member's own latest line (the turn lock).
3712
+ * Declared, never inferred: the Lair wires its Sanctum beats
3713
+ * row, so the turn's world changes show in the Sanctum beside
3714
+ * the plan that made them rather than on whichever delver
3715
+ * spoke last. A write-result only — a run may name its OWN
3716
+ * row, which is open to it for the rest of its turn; any
3717
+ * other value is refused.
3718
+ */
3719
+ worldRow: S.writeResult,
3720
+ },
3721
+ /**
3722
+ * What happened, as three lists: `applied` for rows written,
3723
+ * `proposed` for rows held, `refused` for the sentences — a value
3724
+ * the slot does not accept, or a slot that moved since `base`.
3725
+ * The first two are always present and one of them is always
3726
+ * empty, so nothing downstream decides which mode ran by looking
3727
+ * for a missing key.
3728
+ */
3729
+ out: { main: S.json, applied: S.json, proposed: S.json, refused: S.json },
3730
+ },
3731
+ }));
3732
+ /**
3733
+ * A room name, unless something already describes it (2026-09-28; replaced
3734
+ * `core:task/unlisted-name@1`).
3735
+ *
3736
+ * The Lair's planner names the room the party are about to walk into when it
3737
+ * thinks nobody has built it, and the turn stops to ask the dungeon's master
3738
+ * to describe it (owner ruling, 2026-09-28: *ask, unless it is already
3739
+ * described in prose or the lorebook*). This is the deterministic check after
3740
+ * the planner's judgement. Lookups, in order; the first hit wins:
3741
+ *
3742
+ * 1. **Entry.** An entry whose `name`, or any of whose `keys` (a list, or a
3743
+ * comma-separated string, split on commas), is the same name. Entries on
3744
+ * `locationEntries` are checked before `entries`. Any entry type counts.
3745
+ * → `describedBy` `entry`, `entryId`.
3746
+ * 2. **Prose.** Among the newest `window` rows of `messages` on the
3747
+ * `channels` named, the newest row whose author is **a person, an envoy or
3748
+ * a speakerless reply** — never a character: a delver's line naming a door
3749
+ * is not a description — with a paragraph (split on blank lines) that
3750
+ * names the name and holds at least `minWords` words besides it.
3751
+ * → `describedBy` `prose`, `passage` (that paragraph).
3752
+ * 3. Otherwise `undescribed` is the name, trimmed.
3753
+ *
3754
+ * "The same name" and "names the name" are the SDK's name rule
3755
+ * (`normalizeName`, `sameName`, `passageNaming` in `names.ts`): NFKC, case,
3756
+ * a possessive `'s`, apostrophes and punctuation, and one leading article —
3757
+ * then whole equality, never a substring ("the vault" is not "the sunken
3758
+ * vault").
3759
+ *
3760
+ * Pure: the rows come in on ports (a `core:query/lorebook-entries@1` listing,
3761
+ * a `core:query/session-history@1` read), so a genre decides what is read
3762
+ * and the task decides only what counts. `channels` filters the rows by their
3763
+ * own `channel` (a bare slug is every lane of it), so a core task never
3764
+ * hard-codes a genre's slug: a spec that wants a side channel's prose to count
3765
+ * reads it and names it here.
3766
+ *
3767
+ * ## Which room is this one (2026-09-29)
3768
+ *
3769
+ * The same lookup answers the Lair's other question: *which room do the party
3770
+ * stand in?* — the world's `location` stat, resolved against the rooms, so
3771
+ * *Answer the door* can link the room it writes to it. Two things make that
3772
+ * wireable:
3773
+ *
3774
+ * - **`path`**: a data reference has no sub-path, and the location sits
3775
+ * inside a `core:query/session-state@1` document, so `path` says where the
3776
+ * name is inside `name` (`world.location`) — the dotted spelling
3777
+ * `parse-json@1` and `generate-json@1` read. Empty reads `name` itself.
3778
+ * - **A lore reference is its entry.** A location stat set to a place entry
3779
+ * holds `{ entryId }`, not words, and naming it again by its title would
3780
+ * find a namesake. So a value with an `entryId` is answered by the listed
3781
+ * entry with that id (`describedBy` `entry`), and by nothing when no
3782
+ * listing holds it — archived, or hidden from this read.
3783
+ * - **`fallbackName`** (2026-09-30): what to look for when `name`
3784
+ * (at `path`) names nothing — for the Lair, the room its planner said the
3785
+ * party stood in as they knocked (the knock's `vantage`). The world's
3786
+ * value wins and the hint stands in only while it names nothing: the
3787
+ * order a play turn's prompts read the location in (the world's value,
3788
+ * else that turn's plan). No prompt in the knock turn shows the hinted
3789
+ * room; it is the planner's own answer for that turn. Read whole, by the
3790
+ * same rules as `name`.
3791
+ * @experimental
3792
+ */
3793
+ export const undescribedName = pin(describeTaskDefinition({
3794
+ id: 'core:task/undescribed-name@1',
3795
+ i18n: { name: { en: 'Undescribed name' } },
3796
+ timeoutMs: 500,
3797
+ slots: {
3798
+ params: {
3799
+ kind: 'parameters',
3800
+ facet: 'behavior',
3801
+ schema: {
3802
+ /**
3803
+ * Whose prose counts, by channel slug. `main` by default;
3804
+ * the Lair adds its side channel so a room its master
3805
+ * described there counts too.
3806
+ */
3807
+ channels: {
3808
+ type: 'string',
3809
+ list: true,
3810
+ default: ['main'],
3811
+ label: { en: 'Channels read' },
3812
+ description: {
3813
+ en: 'Which channels’ messages can describe a room. A slug covers every lane of that channel.',
3814
+ },
3815
+ },
3816
+ /** How far back prose counts, in rows across those channels. */
3817
+ window: {
3818
+ type: 'integer',
3819
+ default: 40,
3820
+ min: 1,
3821
+ max: 500,
3822
+ label: { en: 'Messages read' },
3823
+ description: {
3824
+ en: 'How many of the newest messages on those channels are searched for a description.',
3825
+ },
3826
+ },
3827
+ /**
3828
+ * How long a paragraph must be to be a description rather
3829
+ * than a mention: words besides the name itself.
3830
+ */
3831
+ minWords: {
3832
+ type: 'integer',
3833
+ default: 12,
3834
+ min: 0,
3835
+ max: 500,
3836
+ label: { en: 'Words to describe' },
3837
+ description: {
3838
+ en: 'How many words, besides the name, a paragraph needs before it counts as describing the room rather than mentioning it.',
3839
+ },
3840
+ },
3841
+ /**
3842
+ * Where the name is inside `name`, as a dotted path — the
3843
+ * Lair reads `world.location` off a
3844
+ * session-state document. Empty reads `name` itself.
3845
+ */
3846
+ path: {
3847
+ type: 'string',
3848
+ default: '',
3849
+ label: { en: 'Where the name is' },
3850
+ description: {
3851
+ 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.',
3852
+ },
3853
+ },
3854
+ },
3855
+ },
3856
+ },
3857
+ ports: {
3858
+ in: {
3859
+ /**
3860
+ * The name to look for — JSON rather than text because it is
3861
+ * usually read off a model's document (`parse-json@1`'s
3862
+ * `value`), or a document holding it at `path`; anything but a
3863
+ * string is no name, and nothing is undescribed — save a lore
3864
+ * reference (`{ entryId }`), which is the listed entry it
3865
+ * references.
3866
+ */
3867
+ name: S.json,
3868
+ /**
3869
+ * What to look for when `name` at `path` names nothing — a
3870
+ * name or a lore reference, read whole (no `path`). Unwired,
3871
+ * nothing is looked for in its place.
3872
+ */
3873
+ fallbackName: S.json,
3874
+ /** Location entries (rows with `id`, `name`, `keys`), checked first. */
3875
+ locationEntries: S.json,
3876
+ /** The rest of the book, any entry type, checked second. */
3877
+ entries: S.json,
3878
+ /** Recent rows, ascending, each carrying its `channel`. */
3879
+ messages: S.messages,
3880
+ },
3881
+ out: {
3882
+ main: S.text,
3883
+ /** `name`, trimmed, when nothing describes it; else empty. */
3884
+ undescribed: S.text,
3885
+ /** `entry`, `prose`, or empty when nothing describes it. */
3886
+ describedBy: S.text,
3887
+ /** The describing entry's id, or null. */
3888
+ entryId: S.json,
3889
+ /** The describing paragraph, or empty. */
3890
+ passage: S.text,
3891
+ },
3892
+ },
3893
+ }));
3894
+ // ── D-4a: pure pick and cast options ──────────────────────────── start ──────
3895
+ /**
3896
+ * The item this session picks — a pure function of a key and a list.
3897
+ *
3898
+ * ## The gap it closes
3899
+ *
3900
+ * Nothing in the bound catalogue evaluated a pure function over run data. The
3901
+ * closest was `core:task/turn-random@1`, which draws on `ctx.random` — seeded
3902
+ * per RUN, so it answers differently every turn — and that is right for whose
3903
+ * turn it is and useless for a fact that has to stay the same all game. So a
3904
+ * genre wanting its hidden fact **chosen** (which suspect did it, which lore
3905
+ * entry the answer is) had two options and neither was honest: ask a model,
3906
+ * which can change its mind between two answers, or write it into the one
3907
+ * per-session store a spec can reach — the attribute-slot ledger, which the
3908
+ * player's own state panel renders. Whodunit shipped adjudicating from an
3909
+ * authored case file for exactly this reason, with its rendezvous rule
3910
+ * published, tested and called by nobody.
3911
+ *
3912
+ * Derived instead: the create run and every later turn hand the same
3913
+ * `scopeKey` and the same list to this node and reach the same item, with
3914
+ * nothing written down anywhere and nothing on screen.
3915
+ *
3916
+ * ## Rendezvous hashing, and why not `list[hash % length]`
3917
+ *
3918
+ * Each candidate is scored on its own — `hash(key + '#' + itemKey)` — and the
3919
+ * highest wins (`rendezvousPick`, SDK `pick.ts`, the one implementation the
3920
+ * app's binding and a plugin's own picker share). A modulo into the list
3921
+ * moves *every* session's answer when the list length changes; rendezvous
3922
+ * moves it exactly when the newcomer's own score wins, so seating a fifth
3923
+ * suspect mid-case displaces the culprit in about a fifth of sessions and
3924
+ * leaves the rest alone. The hash carries murmur3's `fmix32` finalizer
3925
+ * because the comparison is over whole hashes and plain FNV-1a leaves the
3926
+ * high bits systematic for ids differing in their last digit — measured at
3927
+ * 49% of sessions for the first of three, instead of 33%.
3928
+ *
3929
+ * ## `scopeKey` is the session's address, never the run's seed
3930
+ *
3931
+ * A spec wires `$.input.sessionScope` (or a literal) — something durable. The
3932
+ * run's seed is a different string every turn and a pick keyed on it would
3933
+ * move between two questions. It is `scopeKey` and not `key` (a qualified
3934
+ * name, never the bare noun; named 2026-09-17, before anything shipped):
3935
+ * *key* alone is the option key on a
3936
+ * choice, the identity a candidate is scored under, and a settings field's
3937
+ * name, and this port is none of them — it is the scope the pick is made
3938
+ * within.
3939
+ *
3940
+ * ## No `optional`
3941
+ *
3942
+ * Absent, so an empty list is the run's failure. A genre that derived its
3943
+ * secret from this node cannot be handed "nobody" and carry on, and
3944
+ * `optional: true` would turn that into an `ok` with every downstream port
3945
+ * reading absent — indistinguishable from a turn where the pick genuinely
3946
+ * chose nothing.
3947
+ * @experimental
3948
+ */
3949
+ export const pickByHash = pin(describeTaskDefinition({
3950
+ id: 'core:task/pick-by-hash@1',
3951
+ i18n: {
3952
+ name: { en: 'Pick by hash' },
3953
+ description: {
3954
+ 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.',
3955
+ },
3956
+ },
3957
+ /** Pure arithmetic over a list that is already in memory. */
3958
+ timeoutMs: 500,
3959
+ slots: {
3960
+ params: {
3961
+ kind: 'parameters',
3962
+ schema: {
3963
+ /**
3964
+ * Which field on each entry identifies it.
3965
+ *
3966
+ * The identity is what the hash is taken over, so it
3967
+ * decides the answer: two runs that disagree about it
3968
+ * disagree about the pick. Absent, an entry that IS a
3969
+ * string is its own identity and anything else is
3970
+ * identified by `id` — the two shapes a core list
3971
+ * actually arrives in (`cast-choices` publishes `key`,
3972
+ * a lore listing publishes rows with `id`).
3973
+ *
3974
+ * ⚠ It must be **stable**: a name the author may edit
3975
+ * moves the pick the day they edit it. A row id does not.
3976
+ */
3977
+ by: {
3978
+ type: 'string',
3979
+ quick: true,
3980
+ label: { en: 'Identified by' },
3981
+ 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`.',
3982
+ },
3983
+ },
3984
+ },
3985
+ },
3986
+ ports: {
3987
+ in: {
3988
+ /** The list to pick from. */
3989
+ items: S.json,
3990
+ /**
3991
+ * The stable key this session picks under.
3992
+ *
3993
+ * Either the session's **scope** — `$.input.sessionScope`,
3994
+ * which the binding spells `session:<id>` — or a literal
3995
+ * string for a pick that is not per-session.
3996
+ *
3997
+ * ⚠ `S.json` rather than `S.text`, and not for want of a
3998
+ * type. `session-scope@1` is not assignable to `text@1`, and
3999
+ * there is no text-shaped port anywhere that carries a
4000
+ * session's identity — so a `text` port here could be wired
4001
+ * to a literal and to nothing else, which would give every
4002
+ * session of a genre the same answer. `json` is the
4003
+ * permissive sink, so the scope wires, a literal wires, and
4004
+ * anything a spec wires that the binding cannot read as a key
4005
+ * halts with a sentence naming what to wire instead.
4006
+ */
4007
+ scopeKey: S.json,
4008
+ },
4009
+ out: {
4010
+ /** The chosen entry, whole and exactly as it arrived. */
4011
+ main: S.json,
4012
+ /**
4013
+ * Where it sat in the list **as handed in**, not among the
4014
+ * identifiable entries. `pickIndex` rather than `index`
4015
+ * (qualified, never the bare noun): a bare *index* is a database index, a message's
4016
+ * position and a list offset all at once.
4017
+ */
4018
+ pickIndex: S.json,
4019
+ /**
4020
+ * The identity it won under — the string the hash was taken
4021
+ * over. This is the side a later junction compares an answer
4022
+ * against with `equalsPath`, which is why it is published at
4023
+ * all: the chosen item is a document, and a predicate
4024
+ * compares keys.
4025
+ */
4026
+ chosenKey: S.text,
4027
+ },
4028
+ },
4029
+ }));
4030
+ /**
4031
+ * The room, as options a question can be put with.
4032
+ *
4033
+ * `core:task/make-choices@1` needs `{ key, label }` options and nothing in
4034
+ * core turned a cast into that list, so both Whodunit pickers spend a model
4035
+ * call whose entire job is to read the cast back out as JSON — a request, a
4036
+ * schema and a wait, for a fact the run already held. Worse than slow: a
4037
+ * model enumerating the room can misspell a suspect, invent one, or leave one
4038
+ * out, and the options it writes are what the player may press.
4039
+ *
4040
+ * Pure. The cast read is the fact; this shapes it.
4041
+ *
4042
+ * ## The key is a participant reference
4043
+ *
4044
+ * `character:<id>`, the reference vocabulary — not a name, which
4045
+ * two cast members can share and an author can edit, and not a bare id, which
4046
+ * says nothing about what it identifies. It survives the round trip: the key
4047
+ * lands on the pressed option, `core:task/read-answer@1` publishes it as
4048
+ * `choice`, and a junction can compare that against a
4049
+ * `core:task/pick-by-hash@1` `chosenKey` derived over these same options.
4050
+ *
4051
+ * ## Who is in the list
4052
+ *
4053
+ * Live seats only — a departed or inactive cast member is not somebody a
4054
+ * question may be put about — and **never an envoy**: `exclude` offers no way
4055
+ * to turn one off, and a narrator among the suspects with no way to remove it
4056
+ * is worse than a narrator a spec has to add for itself.
4057
+ *
4058
+ * ## It publishes the whole document, not only the list (ruled (b), 2026-09-17)
4059
+ *
4060
+ * `make-choices@1` reads `{ question, options, addressee? }` off ONE `json`
4061
+ * port, so a spec handed only `options` still has nowhere to put the question
4062
+ * — and the obvious repair, a second in-port on `make-choices`, would move
4063
+ * the hash of a node that is published and wired into shipped specs. So the
4064
+ * shaping happens on this side: `question` comes in, `json` goes out in
4065
+ * exactly the shape that port reads, and the two nodes wire straight to each
4066
+ * other with no model call in between. `options` stays beside it for a spec
4067
+ * that wants the bare list (a pick over the same options, a `each` over the
4068
+ * room), which is the same value the document carries.
4069
+ *
4070
+ * No `addressee`: the document's is a **name** `make-choices` resolves
4071
+ * against the cast, and this node has no more idea who the question is for
4072
+ * than the cast document does. A spec that knows wires `make-choices`'s own
4073
+ * `addressee` port, which wins over the document's anyway.
4074
+ * @experimental
4075
+ */
4076
+ export const castChoices = pin(describeTaskDefinition({
4077
+ id: 'core:task/cast-choices@1',
4078
+ i18n: {
4079
+ name: { en: 'The cast as choices' },
4080
+ description: {
4081
+ 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.',
4082
+ },
4083
+ },
4084
+ timeoutMs: 500,
4085
+ slots: {
4086
+ params: {
4087
+ kind: 'parameters',
4088
+ schema: {
4089
+ /**
4090
+ * Which half of the room to leave out.
4091
+ *
4092
+ * A persona is a character the player voices, so
4093
+ * both halves are cast members and which one a question
4094
+ * is about depends entirely on the question: *who do you
4095
+ * accuse* is asked about the suspects and must not offer
4096
+ * the detective, while *who do you play* is the other way
4097
+ * round.
4098
+ */
4099
+ exclude: {
4100
+ type: 'enum',
4101
+ of: ['none', 'personas', 'characters'],
4102
+ members: [
4103
+ { key: 'none', label: { en: 'Nobody' } },
4104
+ {
4105
+ key: 'personas',
4106
+ label: { en: 'Personas' },
4107
+ description: { en: 'The characters the players voice.' },
4108
+ },
4109
+ {
4110
+ key: 'characters',
4111
+ label: { en: 'Characters' },
4112
+ description: { en: 'The rest of the cast.' },
4113
+ },
4114
+ ],
4115
+ default: 'none',
4116
+ quick: true,
4117
+ label: { en: 'Left out' },
4118
+ description: 'Leave out the characters the players voice (personas), the rest of the cast (characters), or nobody.',
4119
+ },
4120
+ },
4121
+ },
4122
+ },
4123
+ ports: {
4124
+ in: {
4125
+ cast: S.sessionCast,
4126
+ /**
4127
+ * The question the options answer — the prose that sits
4128
+ * above them on the block, and the row's own content.
4129
+ *
4130
+ * Unwired it is the empty string, and `make-choices@1`
4131
+ * publishes no block for a document with no question — the
4132
+ * same silence it answers an empty option list with, rather
4133
+ * than a block asking nothing.
4134
+ */
4135
+ question: S.text,
4136
+ },
4137
+ out: {
4138
+ /** `{ key, label }[]`, in seating order: characters, then personas. */
4139
+ main: S.json,
4140
+ options: S.json,
4141
+ /**
4142
+ * `{ question, options }` — the document
4143
+ * `core:task/make-choices@1` reads off its own `json` port,
4144
+ * in exactly that shape, so the two wire straight to each
4145
+ * other and no oracle stands between a cast read and the
4146
+ * question it is asked with.
4147
+ */
4148
+ json: S.json,
4149
+ },
4150
+ },
4151
+ }));
4152
+ // ── D-4a: pure pick and cast options ────────────────────────────── end ──────
4153
+ // ── Contracts batch 2: the two-document pair ──────────────────── start ──────
4154
+ /**
4155
+ * Two values, side by side in one document, under names a path can read.
4156
+ *
4157
+ * ## The gap it closes
4158
+ *
4159
+ * A junction branches on **one** port, and `equalsPath` compares two paths of
4160
+ * **one** document. So the grammar can ask *is the accused the culprit?*
4161
+ * only once something has put the accused and the culprit in the same
4162
+ * document, and nothing in core did: no task merged two json ports, and the
4163
+ * obvious repair — a second in-port on the junction — is not a repair, it is a
4164
+ * different clause. Whodunit shipped with its verdict's `accused` node wired to
4165
+ * nothing for exactly this reason.
4166
+ *
4167
+ * Pure, and deliberately the dullest node in the catalogue. It computes
4168
+ * nothing, decides nothing and reads nothing: it is the shape change that lets
4169
+ * a predicate see both sides.
4170
+ *
4171
+ * ## ⚠ An absent side is **omitted**, never null
4172
+ *
4173
+ * This is the whole of the node's behaviour worth stating. `predicateHolds`
4174
+ * answers `false` when either side of an `equalsPath` is `undefined` — two
4175
+ * absences are not a match — and that rule is what makes a junction over this
4176
+ * document **safe on a turn where nothing was decided**: a run in which the
4177
+ * accuse never happened has no `accused`, so
4178
+ * `{ path: 'accused', equalsPath: 'culprit' }` fires nothing, and the spec
4179
+ * falls through to its default branch.
4180
+ *
4181
+ * Writing `null` for an unwired side would destroy that. `null` is a *value*:
4182
+ * `readPath` returns it, it is not `undefined`, and `null === null` — so a
4183
+ * document with both sides missing would compare **equal** and the verdict
4184
+ * branch would fire on a turn where nobody accused anybody. The omission is
4185
+ * therefore load-bearing and pinned by a test, not an implementation detail of
4186
+ * the handler.
4187
+ *
4188
+ * The same rule covers the side that is wired but produced nothing: a port
4189
+ * resolving absent is absent here too. What arrives is written; what does not
4190
+ * is not mentioned.
4191
+ *
4192
+ * ## The names are the spec's
4193
+ *
4194
+ * `firstKey` and `secondKey` decide what the document's keys are called, so
4195
+ * the same node reads as `{ accused, culprit }` in one spec and
4196
+ * `{ guess, secret }` in another and the predicate paths are the spec's own
4197
+ * words. Defaults `first` and `second`, which are honest and nobody would
4198
+ * write a predicate against on purpose.
4199
+ *
4200
+ * Two keys that are the same string are refused rather than collapsed: one key
4201
+ * holding whichever side was written last is a document that compares equal to
4202
+ * itself, which is the one answer this node must never produce by accident.
4203
+ * @experimental
4204
+ */
4205
+ export const pair = pin(describeTaskDefinition({
4206
+ id: 'core:task/pair@1',
4207
+ i18n: {
4208
+ name: { en: 'Pair' },
4209
+ description: {
4210
+ 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.',
4211
+ },
4212
+ },
4213
+ /** Two reads and an object literal. */
4214
+ timeoutMs: 500,
4215
+ slots: {
4216
+ params: {
4217
+ kind: 'parameters',
4218
+ schema: {
4219
+ firstKey: {
4220
+ type: 'string',
4221
+ default: 'first',
4222
+ quick: true,
4223
+ label: { en: 'Name for the first value' },
4224
+ description: 'What the first value is called in the document — the word a branch reads it by.',
4225
+ },
4226
+ secondKey: {
4227
+ type: 'string',
4228
+ default: 'second',
4229
+ quick: true,
4230
+ label: { en: 'Name for the second value' },
4231
+ description: 'What the second value is called in the document. It must differ from the first.',
4232
+ },
4233
+ },
4234
+ },
4235
+ },
4236
+ ports: {
4237
+ in: {
4238
+ /** Whatever the spec wants compared. Absent is a legal input. */
4239
+ first: S.json,
4240
+ second: S.json,
4241
+ },
4242
+ out: {
4243
+ /**
4244
+ * `{ [firstKey]: first, [secondKey]: second }`, with an absent
4245
+ * side **omitted** — see the note above; it is the property a
4246
+ * junction over this document depends on.
4247
+ */
4248
+ main: S.json,
4249
+ },
4250
+ },
4251
+ }));
4252
+ // ── Contracts batch 2: the two-document pair ────────────────────── end ──────
4253
+ // ── Pictures: the cut-out (image generation I4, 2026-10-12) ────────────────
4254
+ /**
4255
+ * 🚧 Each picture, with its background removed — a **cut-out**.
4256
+ *
4257
+ * The step after `core:oracle/generate-image@1` when the pair could not draw a
4258
+ * transparent background itself (`cutOut: native-or-task`). The host runs a
4259
+ * local matting model (BiRefNet-lite, ONNX) over each picture and stores the
4260
+ * result as a new PNG with an alpha channel; the source picture is left as it
4261
+ * was.
4262
+ *
4263
+ * ## Same list in, same list out
4264
+ *
4265
+ * One item out per item in, in order. An item that was cut out is replaced by
4266
+ * a reference to its cut-out; every other field the item carried — its series
4267
+ * `key` included — travels across unchanged, so a keyed outlet downstream
4268
+ * files each cut-out under the label it was drawn for. An item that is not an
4269
+ * image passes through untouched.
4270
+ *
4271
+ * ## `mode`
4272
+ *
4273
+ * - `auto` (default) skips a picture that already has a transparent
4274
+ * background: its media meta says `transparent: 'native'` (the pair drew
4275
+ * it), it is itself a cut-out (`cutOutOf`), or its pixels already carry
4276
+ * transparency.
4277
+ * - `always` cuts every picture out, whatever it says about itself.
4278
+ * - `off` hands the list on unchanged — the switch a spec author flips to see
4279
+ * the raw pictures without rewiring.
4280
+ *
4281
+ * Pure given its input: the same pictures make the same cut-outs (the media
4282
+ * store dedupes identical bytes). The first run on a machine downloads the
4283
+ * matting model once, which is why the timeout is idle rather than wall.
4284
+ * @experimental
4285
+ */
4286
+ export const cutOut = pin(describeTaskDefinition({
4287
+ id: 'core:task/cut-out@1',
4288
+ i18n: {
4289
+ name: { en: 'Cut out' },
4290
+ description: {
4291
+ en: 'Removes the background from each picture, leaving it transparent. Downloads a small background-removal model the first time.',
4292
+ },
4293
+ },
4294
+ timeoutMs: 120000,
4295
+ timeoutKind: 'idle',
4296
+ slots: {
4297
+ params: {
4298
+ kind: 'parameters',
4299
+ schema: {
4300
+ mode: {
4301
+ type: 'enum',
4302
+ of: ['auto', 'always', 'off'],
4303
+ members: [
4304
+ {
4305
+ key: 'auto',
4306
+ label: { en: 'When needed' },
4307
+ description: { en: 'Skips pictures that already have a transparent background.' },
4308
+ },
4309
+ {
4310
+ key: 'always',
4311
+ label: { en: 'Always' },
4312
+ description: { en: 'Cuts every picture out, even one that is already transparent.' },
4313
+ },
4314
+ {
4315
+ key: 'off',
4316
+ label: { en: 'Off' },
4317
+ description: { en: 'Hands the pictures on unchanged.' },
4318
+ },
4319
+ ],
4320
+ default: 'auto',
4321
+ quick: true,
4322
+ description: 'Which pictures get their background removed.',
4323
+ },
4324
+ },
4325
+ },
4326
+ },
4327
+ ports: {
4328
+ in: { media: S.mediaList },
4329
+ out: { main: S.mediaList, media: S.mediaList },
4330
+ },
4331
+ }));
4332
+ // ── Pictures: the sprite series (image generation I5, 2026-10-12) ──────────
4333
+ /**
4334
+ * 🚧 The pictures a **Sprite set fill** asks for — one image series item per
4335
+ * sprite label.
4336
+ *
4337
+ * Each item is `{ key, vars }`:
4338
+ *
4339
+ * - `key` is the label made filename-safe (trimmed, case-folded, spaces to
4340
+ * `-`, anything else dropped, collisions suffixed `joy`, `joy-2`). A key
4341
+ * is an address, never prose: the picture's description comes from
4342
+ * `vars.labelPhrase`, never from the key.
4343
+ * - `vars.label` is the sprite label as the card spells it, which is what
4344
+ * `core:outlet/attach-sprite@1` files the picture under.
4345
+ * - `vars.labelPhrase` is the label's **sprite label phrase** — the
4346
+ * `phrases` prompt field, one `label: phrase` per line (*Sprite label
4347
+ * phrases*, editable like any prompt row). A label with no line falls back
4348
+ * to the label word itself.
4349
+ * - `vars.likeness` / `vars.likenessNegative` carry the card's likeness, so
4350
+ * the picture step's prompt rows can say `{{likeness}}` per item.
4351
+ *
4352
+ * The phrases and the sprite picker's labels stay two vocabularies, never
4353
+ * merged: the picker never reads a phrase. Pure given its input — no read, no call.
4354
+ * @experimental
4355
+ */
4356
+ export const buildSpriteSeries = pin(describeTaskDefinition({
4357
+ id: 'core:task/build-sprite-series@1',
4358
+ i18n: {
4359
+ name: { en: 'Sprite series' },
4360
+ description: {
4361
+ en: 'Turns the sprite labels to draw into one picture request each, with a short description of each expression.',
4362
+ },
4363
+ },
4364
+ timeoutMs: 5000,
4365
+ slots: {
4366
+ prompts: {
4367
+ kind: 'prompts',
4368
+ quick: true,
4369
+ facet: 'prompts',
4370
+ description: 'How each sprite label is described to the picture model: one "label: phrase" per line.',
4371
+ fields: {
4372
+ phrases: { type: 'text' },
4373
+ },
4374
+ },
4375
+ },
4376
+ ports: {
4377
+ in: {
4378
+ /** The sprite labels to draw, as the card spells them. */
4379
+ labels: S.json,
4380
+ likeness: S.text,
4381
+ likenessNegative: S.text,
4382
+ },
4383
+ out: {
4384
+ main: S.imageSeries,
4385
+ series: S.imageSeries,
4386
+ /** The labels kept, in order — blanks and repeats dropped. */
4387
+ labels: S.json,
4388
+ },
4389
+ },
4390
+ }));
4391
+ // ── Pictures: proofs (image generation I8, 2026-10-12) ─────────────────────
4392
+ /**
4393
+ * 🚧 **Proofs** — *n* identical pictures to choose from, as an image
4394
+ * series. A photographer's proof prints: the
4395
+ * same shot several times, one kept. Not a retrieval **candidate**, which is
4396
+ * something that might reach a prompt.
4397
+ *
4398
+ * Each item is `{ key, vars: {} }` with keys `"1"` … `"n"`: the same picture
4399
+ * asked for *n* times, so every item renders the same prompt. That sameness
4400
+ * is what lets the host pack the series as ONE batch call on a pair whose
4401
+ * drawing sheet takes `perCall ≥ n` (a hosted API's `n`, a ComfyUI graph's
4402
+ * batch size); a pair that draws one picture per call loops. The spec never
4403
+ * knows which.
4404
+ *
4405
+ * `count` is read as a whole number and clamped to 1–8 (the default
4406
+ * `seriesMax`); anything that is not a number is 1. The Portrait form offers
4407
+ * 1–4. Pure given its input — no read, no call.
4408
+ * @experimental
4409
+ */
4410
+ export const buildProofs = pin(describeTaskDefinition({
4411
+ id: 'core:task/build-proofs@1',
4412
+ i18n: {
4413
+ name: { en: 'Proofs' },
4414
+ description: {
4415
+ en: 'Asks for the same picture several times, so there are a few to choose from.',
4416
+ },
4417
+ },
4418
+ timeoutMs: 5000,
4419
+ ports: {
4420
+ in: {
4421
+ /** How many pictures: a whole number, clamped to 1–8. */
4422
+ count: S.json,
4423
+ },
4424
+ out: {
4425
+ main: S.imageSeries,
4426
+ series: S.imageSeries,
4427
+ },
4428
+ },
4429
+ }));
4430
+ // ── The Scene action (DESIGN-image-generation §6.4, I9, 2026-10-12) ─────────
4431
+ /**
4432
+ * 🚧 A model's reply, cleaned into a picture prompt — the step between the
4433
+ * Scene action's **scene prompt** (a quiet text call asked for a tag list)
4434
+ * and the picture step.
4435
+ *
4436
+ * A text model asked for "a comma-separated tag list and nothing else"
4437
+ * still answers with a fence, a `Prompt:` label, quotes round the whole
4438
+ * line or a list one tag per line. Each is undone here: fences and the
4439
+ * label dropped, wrapping quotes stripped, line breaks and bullets turned
4440
+ * into commas, empty tags and repeated commas and spaces collapsed, a
4441
+ * trailing full stop removed. Prose survives as prose — only its line
4442
+ * breaks become commas. Pure: no read, no model.
4443
+ *
4444
+ * An empty result halts: a picture of nothing is not a picture.
4445
+ * @experimental
4446
+ */
4447
+ export const cleanImagePrompt = pin(describeTaskDefinition({
4448
+ id: 'core:task/clean-image-prompt@1',
4449
+ i18n: {
4450
+ name: { en: 'Clean picture prompt' },
4451
+ description: { en: "Tidies a model's reply into one line a picture model can read." },
4452
+ },
4453
+ timeoutMs: 500,
4454
+ ports: {
4455
+ in: { text: S.text },
4456
+ out: { main: S.text, prompt: S.text },
4457
+ },
4458
+ }));
4459
+ /**
4460
+ * 🚧 Where the Scene action's picture goes — its **placement**: posted as a
4461
+ * message, set as the session's backdrop, or both.
4462
+ *
4463
+ * The `placement` parameter is the admin's (Admin › Pipelines, the Scene
4464
+ * pipeline's config); a press may name its own in its payload
4465
+ * (`{ placement: 'backdrop' }` — the Backdrop widget's *Illustrate*), and a
4466
+ * named one wins. Published as two flags, `message` and `backdrop`, because
4467
+ * a junction branch reads one truthy value: each outlet sits behind its own.
4468
+ * Pure: no read, no model.
4469
+ * @experimental
4470
+ */
4471
+ export const picturePlacement = pin(describeTaskDefinition({
4472
+ id: 'core:task/picture-placement@1',
4473
+ i18n: {
4474
+ name: { en: 'Placement' },
4475
+ description: { en: 'Decides whether the picture is posted, set as the backdrop, or both.' },
4476
+ },
4477
+ timeoutMs: 500,
4478
+ slots: {
4479
+ params: {
4480
+ kind: 'parameters',
4481
+ facet: 'behavior',
4482
+ schema: {
4483
+ placement: {
4484
+ type: 'enum',
4485
+ of: ['message', 'backdrop', 'both'],
4486
+ members: [
4487
+ {
4488
+ key: 'message',
4489
+ label: { en: 'Post it' },
4490
+ description: { en: 'Posts the picture in the session as a message.' },
4491
+ },
4492
+ {
4493
+ key: 'backdrop',
4494
+ label: { en: 'Backdrop' },
4495
+ description: { en: "Sets the picture as the session's backdrop, and posts nothing." },
4496
+ },
4497
+ {
4498
+ key: 'both',
4499
+ label: { en: 'Both' },
4500
+ description: { en: 'Posts the picture and sets it as the backdrop.' },
4501
+ },
4502
+ ],
4503
+ default: 'both',
4504
+ label: { en: 'Placement' },
4505
+ description: 'Where the picture goes. A press that names its own placement uses that.',
4506
+ },
4507
+ },
4508
+ },
4509
+ },
4510
+ ports: {
4511
+ in: {
4512
+ /** The press's payload; its `placement`, when one of the three, wins. */
4513
+ payload: S.json,
4514
+ },
4515
+ out: {
4516
+ main: S.json,
4517
+ /** `message`, `backdrop` or `both` — what was decided. */
4518
+ placement: S.text,
4519
+ /** True when the picture is posted as a message. */
4520
+ message: S.json,
4521
+ /** True when the picture is set as the backdrop. */
4522
+ backdrop: S.json,
4523
+ },
4524
+ },
4525
+ }));
4526
+ /**
4527
+ * 🚧 A **clock step**: how far the story clock moves, decided — `{ by, unit }`
4528
+ * and whether it moves at all (2026-10-13, PROPOSAL-live-scenes §6).
4529
+ *
4530
+ * Two uses, one shape. *Time passes…* hands it the press's collected
4531
+ * `step` (`input.clockStep`), which wins. Chat's reply hands it nothing and
4532
+ * reads its own parameters — **By** (0, the default, is off) and **Unit** —
4533
+ * exposed as the session setting *Each reply advances the clock by …*. Either
4534
+ * way the step publishes `moves` (true when `by` is a whole number other than
4535
+ * zero), and the *Advance story clock* outlet sits behind a junction on it,
4536
+ * so a step of nothing is never written and never refused. Pure: no read, no
4537
+ * model, never the clock itself.
4538
+ * @experimental
4539
+ */
4540
+ export const clockStep = pin(describeTaskDefinition({
4541
+ id: 'core:task/clock-step@1',
4542
+ i18n: {
4543
+ name: { en: 'Clock step' },
4544
+ description: { en: 'Decides how far the story clock moves: a number of minutes, hours, days, months or years.' },
4545
+ },
4546
+ timeoutMs: 500,
4547
+ slots: {
4548
+ params: {
4549
+ kind: 'parameters',
4550
+ facet: 'behavior',
4551
+ schema: {
4552
+ by: {
4553
+ type: 'integer',
4554
+ default: 0,
4555
+ label: { en: 'By' },
4556
+ description: { en: 'How many units the clock moves. 0 moves nothing; negative goes back.' },
4557
+ },
4558
+ unit: {
4559
+ type: 'enum',
4560
+ of: ['minutes', 'hours', 'days', 'months', 'years'],
4561
+ members: [
4562
+ { key: 'minutes', label: { en: 'Minutes' } },
4563
+ { key: 'hours', label: { en: 'Hours' } },
4564
+ { key: 'days', label: { en: 'Days' } },
4565
+ { key: 'months', label: { en: 'Months' } },
4566
+ { key: 'years', label: { en: 'Years' } },
4567
+ ],
4568
+ default: 'minutes',
4569
+ label: { en: 'Unit' },
4570
+ description: { en: 'What to count.' },
4571
+ },
4572
+ },
4573
+ },
4574
+ },
4575
+ ports: {
4576
+ in: {
4577
+ /** A collected step, `{ by, unit }` — wins over the parameters when it reads. */
4578
+ step: S.json,
4579
+ /**
4580
+ * When truthy, the clock does not move (`moves` false). Chat's
4581
+ * reply wires the row it re-drives (`input.messageId`), so a
4582
+ * regenerate, a swipe or an extend never ticks the clock twice.
4583
+ */
4584
+ unless: S.json,
4585
+ },
4586
+ out: {
4587
+ main: S.json,
4588
+ /** True when the clock moves: `by` is a whole number other than zero. */
4589
+ moves: S.json,
4590
+ /** The signed amount — what *Advance story clock* takes on its `by` port. */
4591
+ by: S.json,
4592
+ /** The unit — what *Advance story clock* takes on its `unit` port. */
4593
+ unit: S.text,
4594
+ },
4595
+ },
4596
+ }));
4597
+ /**
4598
+ * **Run a script** — the script step (2026-10-12).
4599
+ *
4600
+ * The node itself does nothing: it passes its input through to `main`, and
4601
+ * the `core:script:data/transform@1` scripts attached after `main` transform
4602
+ * it in order, each handed the value the one before returned. That is what
4603
+ * lets an admin write a custom task in-app without a plugin — the body is a
4604
+ * sandboxed script, the contract is JSON in, JSON out.
4605
+ * @experimental
4606
+ */
4607
+ export const runScript = pin(describeTaskDefinition({
4608
+ id: 'core:task/run-script@1',
4609
+ i18n: {
4610
+ name: { en: 'Run a script' },
4611
+ description: {
4612
+ en: 'Passes its input through; the scripts attached after it transform the value, each handed what the one before returned.',
4613
+ },
4614
+ },
4615
+ timeoutMs: 2000,
4616
+ slots: {
4617
+ scripts: {
4618
+ kind: 'scripts',
4619
+ accepts: ['core:script:data/transform@1'],
4620
+ port: 'main',
4621
+ phase: 'after',
4622
+ description: 'The script, or scripts, this step runs over its input. Each is handed the value the one before returned.',
4623
+ },
4624
+ /**
4625
+ * The time each script in the chain may take.
4626
+ * Read by the HOST's script applier off the scope chain, not by the
4627
+ * binding — the binding never sees the chain. A script past it is
4628
+ * stopped and recorded `err` with the time in its reason, and the
4629
+ * value it was handed goes on. Unset, the seam default applies (the
4630
+ * same 250 ms).
4631
+ */
4632
+ params: {
4633
+ kind: 'parameters',
4634
+ facet: 'weights',
4635
+ schema: {
4636
+ budgetMs: {
4637
+ type: 'integer',
4638
+ min: 1,
4639
+ max: 1000,
4640
+ default: 250,
4641
+ label: { en: 'Script time limit (ms)' },
4642
+ description: {
4643
+ en: 'How long each script in this step may run. A script that runs longer is stopped, and the value it was handed goes on unchanged.',
4644
+ },
4645
+ },
4646
+ },
4647
+ },
4648
+ },
4649
+ ports: {
4650
+ in: { input: S.json },
4651
+ out: { main: S.json },
4652
+ },
4653
+ }));
4654
+ //# sourceMappingURL=tasks.js.map