@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.
@@ -0,0 +1,3335 @@
1
+ /**
2
+ * Core's **query** node definitions — reads.
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, BAND_PRIORITIES } from '@serene-pub/sdk';
8
+ import { describeQueryDefinition, pin } from '@serene-pub/sdk';
9
+ import { varWorldLore, varCharacterLore, varHistory, varDocsExcerpts, varRecalledLines, } from '@serene-pub/sdk';
10
+ /**
11
+ * `BAND_PRIORITIES` as a person reads them. A factory for the reason
12
+ * `streamingParam` is: each declaration gets its own objects.
13
+ */
14
+ const bandPriorityMembers = () => [
15
+ {
16
+ key: 'low',
17
+ label: { en: 'Low' },
18
+ description: { en: 'Its entries go behind the others when leftover room is handed out.' },
19
+ },
20
+ {
21
+ key: 'normal',
22
+ label: { en: 'Normal' },
23
+ description: { en: 'No ordering: leftover room follows relevance alone.' },
24
+ },
25
+ {
26
+ key: 'high',
27
+ label: { en: 'High' },
28
+ description: { en: 'Its entries go ahead of the others when leftover room is handed out.' },
29
+ },
30
+ {
31
+ key: 'always',
32
+ label: { en: 'Always' },
33
+ description: { en: 'Every entry the window can hold is kept, ahead of the scored fill.' },
34
+ },
35
+ ];
36
+ // ── Queries ─────────────────────────────────────────────────────────────────
37
+ /** @public */
38
+ export const sessionHistory = pin(describeQueryDefinition({
39
+ id: 'core:query/session-history@1',
40
+ i18n: { name: { en: 'Session history' } },
41
+ timeoutMs: 2000,
42
+ slots: {
43
+ /**
44
+ * ⚠ No `template` slot, and there was one.
45
+ *
46
+ * It declared "how each chat message is written into the context",
47
+ * and three things were true of it: no binding ever read it, no row
48
+ * was ever seeded for its pool, and so the panel rendered a picker
49
+ * with **nothing in it** on every pipeline that used this node. A
50
+ * control that cannot be given a value and would not be used if it
51
+ * could is worse than the absence of the feature.
52
+ *
53
+ * If per-message wording becomes configurable, it belongs on
54
+ * `core:task/process-messages@1`, which is what actually formats a
55
+ * line. This node fetches rows.
56
+ */
57
+ params: {
58
+ kind: 'parameters',
59
+ facet: 'weights',
60
+ schema: {
61
+ /**
62
+ * ⚠ The default is **100 because 100 is what every install
63
+ * has been getting**, not because 100 was chosen.
64
+ *
65
+ * It read 40 here and nothing read it: the binding took
66
+ * `input.limit`, a key nothing supplies, and fell through to
67
+ * a literal 100 on every run. Wiring the control while
68
+ * leaving the declared number at 40 would have moved the
69
+ * transcript window from 100 to 40 on every install at
70
+ * defaults — a retrieval change smuggled in behind a typing
71
+ * fix. So the declaration is corrected to the effective
72
+ * value first; changing the number is a separate decision,
73
+ * made against the measure corpus.
74
+ *
75
+ * Exactly the ruling `topK` got (2026-09-07), for exactly
76
+ * the same defect.
77
+ *
78
+ * ⚠ **Not read when `budget` is wired** (history window,
79
+ * 2026-10-03): that read is sized by the context window,
80
+ * which belongs to the sampling config — a count
81
+ * of rows beside it is the same number entered twice, and
82
+ * the count is what moved the prompt's first line on every
83
+ * turn once a session passed it. Every shipped reply wires
84
+ * the budget; the asking steps (a form's answer, Adventure's
85
+ * Ask, the Lair's room drafting), the turn order and any
86
+ * spec that does not keep reading this.
87
+ */
88
+ limit: {
89
+ type: 'integer',
90
+ default: 100,
91
+ description: 'How many recent messages are read. Not used where the read is sized by the context window — every shipped reply — which reads as much as the window could hold twice over and lets the prompt decide where the conversation starts.',
92
+ },
93
+ /**
94
+ * The channel this history reads. A session's
95
+ * lanes are the mode's declaration; a pipeline chooses
96
+ * which one builds its context — the map narrator reads
97
+ * `map`, the chat pipeline reads `main`, and a custom
98
+ * spec may do otherwise on purpose.
99
+ */
100
+ channel: {
101
+ type: 'string',
102
+ default: 'main',
103
+ description: "Which of the session's channels this history reads. The chat log is 'main'.",
104
+ },
105
+ /**
106
+ * **Only the unplayed talk** (2026-09-28):
107
+ * the rows of a side channel written since the story's
108
+ * newest generated line — the newest visible `main` row
109
+ * whose role is not `user`. Of those it keeps a person's own
110
+ * lines and the replies a run fired ON this channel wrote
111
+ * there (its inlet's `channel` is this one); a row a create
112
+ * run wrote (a greeting) or a story turn wrote (the Lair's
113
+ * beats row) is left out, read off the run artifacts, never
114
+ * a row's metadata. `limit` still caps it, newest kept.
115
+ *
116
+ * Refused with `channel: 'main'`: the story's own rows are
117
+ * the bound, never the talk.
118
+ */
119
+ unplayedOnly: {
120
+ type: 'boolean',
121
+ default: false,
122
+ label: { en: 'Only since the last story line' },
123
+ description: {
124
+ en: "Read only what was said on this channel since the story's newest generated line: people's lines and the replies to them. Cannot be used with the 'main' channel.",
125
+ },
126
+ },
127
+ /**
128
+ * **Side channels as talk** (2026-09-28): on every channel but
129
+ * `main`, keep only the talk — a person's own lines and the
130
+ * replies a run fired ON that channel wrote there — by the
131
+ * rule `unplayedOnly` uses, without its bound. A row a
132
+ * create run wrote (a greeting) or a story turn wrote (the
133
+ * Lair's Sanctum beats row) is left out, read off the run
134
+ * artifacts, never a row's metadata. `main` rows are kept
135
+ * whole. The window is the newest `limit` rows before the
136
+ * filter, so it may hand on fewer.
137
+ *
138
+ * The Lair's room check reads every channel with it
139
+ * (`exitProse`): a beats list naming a room is the
140
+ * Castellan's plan, not a description of the room.
141
+ */
142
+ talkOnly: {
143
+ type: 'boolean',
144
+ default: false,
145
+ label: { en: 'Side channels: talk only' },
146
+ description: {
147
+ en: "On every channel but 'main', read only what was said there: people's lines and the replies to them — never a greeting or a turn's notes.",
148
+ },
149
+ },
150
+ /**
151
+ * The transcript's intent, on the node that produces the
152
+ * transcript (built 2026-09-16 — see
153
+ * `bandIntentFields`). `weight: 0.4` and `minInclude: 6`
154
+ * were here once, moved to the ranker's per-source map as
155
+ * `share.messages` and `minEntries.messages`, and are back
156
+ * on the source, where a source's intent belongs, at the numbers
157
+ * the map held: half the window is `MESSAGE_FILL_FRACTION`,
158
+ * and six is the minimum the map carried for the one band
159
+ * allowed a minimum (recent conversation; lore has none).
160
+ *
161
+ * ⚠ **No shipped spec ranks a message candidate** —
162
+ * `main` carries the transcript rows for
163
+ * `process-messages`, and `assemble` builds the transcript
164
+ * from those, never from ranked candidates. Two things
165
+ * keep it so: `entity-search`'s past lines publish on
166
+ * their own `recalledLines` band, and `vector-search`
167
+ * asks the index for lorebook entries only (the app's
168
+ * binding names them). Its intent
169
+ * still reaches the ranker, on the `band` out-port a spec
170
+ * concatenates in with the lore, and its `share` is what
171
+ * halves the pool the lore sources divide: the
172
+ * conversation's slice is reserved and whatever it does
173
+ * not spend is swept to the others, exactly as the map's
174
+ * `messages: 0.5` did. `maxEntries` and `minEntries` bind
175
+ * only when a spec does rank message candidates (a
176
+ * compression region, or a plugin source publishing on
177
+ * this band); they are declared at the map's values so
178
+ * that spec inherits what every install has stored, not
179
+ * so a person moving them today sees a prompt change —
180
+ * they will not.
181
+ */
182
+ share: {
183
+ type: 'number',
184
+ min: 0,
185
+ default: 0.5,
186
+ quick: true,
187
+ label: { en: 'Share — conversation' },
188
+ description: {
189
+ en: 'How much of the context window the conversation may take, relative to every other source. What it does not spend is handed to the lore. Set to zero to give the whole window to the other sources.',
190
+ },
191
+ },
192
+ maxEntries: {
193
+ type: 'integer',
194
+ min: 0,
195
+ default: 50,
196
+ label: { en: 'Most entries — conversation' },
197
+ description: {
198
+ en: 'A ceiling on how many retrieved messages may reach the prompt as ranked entries, whatever the share. The transcript itself is sized by the window, not by this.',
199
+ },
200
+ },
201
+ minEntries: {
202
+ type: 'integer',
203
+ min: 0,
204
+ default: 6,
205
+ label: { en: 'Always keep at least' },
206
+ description: {
207
+ en: 'Recent messages kept as ranked entries whatever the shares say, so a lore-heavy chat stays readable. Dropped when there is no room. Lore has no minimum — it competes on score (R6).',
208
+ },
209
+ },
210
+ /**
211
+ * Read, at last (it was declared and read by nothing
212
+ * from the day it was written, allow-listed in the
213
+ * declared-reads guard until this landed). `normal` is no
214
+ * ordering at all; see `BAND_PRIORITIES` in the SDK for
215
+ * what the other three do to the ranker's sweep.
216
+ */
217
+ priority: {
218
+ type: 'enum',
219
+ of: BAND_PRIORITIES,
220
+ members: bandPriorityMembers(),
221
+ default: 'normal',
222
+ label: { en: 'Priority — conversation' },
223
+ description: {
224
+ en: "How strongly the conversation resists being trimmed once the shares are spent — 'always' keeps every message the window can hold.",
225
+ },
226
+ },
227
+ },
228
+ },
229
+ },
230
+ ports: {
231
+ in: {
232
+ scope: S.sessionScope,
233
+ /**
234
+ * **The window this read is sized by** (history window,
235
+ * 2026-10-03) — `$.contextBudget.available`, the same value
236
+ * the prompt's `assemble` is handed. Wired, the read is the
237
+ * newest rows until a deliberately generous estimate
238
+ * (characters ÷ 4, nothing for names or scaffolding) reaches
239
+ * **twice** the budget's `total`, or every row — never more
240
+ * than 2000 — and `limit` is not read. Fitting those rows to
241
+ * the window stays `assemble`'s (its transcript fit, which
242
+ * cuts the oldest lines in a chunk and holds the cut across
243
+ * turns): reading twice what fits is what lets that held cut,
244
+ * not a row count, decide where the conversation starts.
245
+ * Unwired, the window is the newest `limit` rows, as it
246
+ * always was.
247
+ *
248
+ * Not read with `unplayedOnly` (the talk keeps its `limit`)
249
+ * or a wired `messageId` (one row). There was a `budget`
250
+ * in-port once (culled 2026-09-16): declared and read by
251
+ * nothing. This one has a reader.
252
+ */
253
+ budget: S.budget,
254
+ /**
255
+ * **One row, by id** (2026-09-28): wired —
256
+ * `$.input.messageId`, the message a press on a message's ⋮
257
+ * was made on — the read is exactly that row, whatever its
258
+ * channel, as a one-row transcript; `limit`, `budget`,
259
+ * `channel`, `unplayedOnly` and `talkOnly` do not apply. The row must be
260
+ * this session's, and a hidden or still-generating row reads
261
+ * as nothing, the same as in any window. Unwired, the window
262
+ * reads as it always did. For an action that acts on the row
263
+ * it was pressed on (the Lair's *File as a room*): the inlet
264
+ * carries the id, never the text, so the row is read here.
265
+ */
266
+ messageId: S.rowIds,
267
+ },
268
+ out: {
269
+ /**
270
+ * Transcript rows, on both — `messages@1` (was
271
+ * `context-candidates@1` until 2026-09-17: the
272
+ * value had always been rows, for `process-messages` and
273
+ * `prose-transcript`, and the intent rides `band` alone).
274
+ * Neither is a candidates list (ruled the same day): a spec that
275
+ * wires either into a merge, a concat or `assemble`'s
276
+ * `candidates` gets a `validate()` warning naming `band` — the
277
+ * host drops rows handed as candidates rather than ranking them.
278
+ */
279
+ main: S.messages,
280
+ messages: S.messages,
281
+ /**
282
+ * The conversation's **band intent**, alone — a candidates
283
+ * list holding one element and no items (`BandIntent`), for a
284
+ * spec to concatenate in with the lore so the ranker reserves
285
+ * the transcript's slice. Its own port because `main` and
286
+ * `messages` carry transcript rows for `process-messages`, and
287
+ * an intent element ahead of them would be read as a message.
288
+ * Opens with a band-intent element (and holds nothing else)
289
+ * — readers call `splitCandidates()`.
290
+ */
291
+ band: S.candidates,
292
+ },
293
+ },
294
+ }));
295
+ /**
296
+ * How much non-key evidence brings an entry in when no keyword matched.
297
+ *
298
+ * The scan admits a candidate on `pinned || keyword > 0 || nameMatch > 0`, and
299
+ * every other signal is computed *before* that line — so tf-idf and entity
300
+ * co-occurrence could only ever reorder what an author's keys had already let
301
+ * through. An entry with no matching key could not reach the prompt however
302
+ * relevant it was, which is the whole reason a lorebook has to be hand-indexed:
303
+ * "the Riders", "them" and "the order" are all the Ashguard, and only the
304
+ * author writing each of them down makes the entry fire.
305
+ *
306
+ * This opens that line to evidence:
307
+ *
308
+ * admit ⟸ pinned ∨ keyword > 0 ∨ nameMatch > 0 ∨ evidence ≥ admitThreshold
309
+ *
310
+ * **Keys keep guaranteeing.** Evidence only ever *adds* — an authored key fires
311
+ * exactly as it did, and `constant` still bypasses retrieval entirely rather
312
+ * than becoming a large number. Nothing here needs an embedding model: the
313
+ * evidence is proper-noun overlap and rarity-weighted vocabulary overlap, both
314
+ * computed from the rows and the conversation already in hand.
315
+ *
316
+ * **0 is off, and is the shipped default** — the same convention
317
+ * `maxRecursionDepth` uses, and for the same reason: this changes what reaches
318
+ * the model, so it is a thing somebody turns on rather than a thing that
319
+ * happens to them on upgrade. Reading 0 as "admit everything, since every
320
+ * evidence score clears zero" would be the one value that cannot be a default.
321
+ *
322
+ * The two kinds of evidence combine so that **either admits on its own** — a
323
+ * sum would divide one budget between them and leave whichever got the smaller
324
+ * share unable to bring anything in by itself, which is not what "tf-idf can
325
+ * admit" means. So the scale is calibrated on each separately: ~0.3 is *one
326
+ * thing the conversation is naming that not every entry names*, or *about a
327
+ * third of what an entry is about being under discussion*. 1 admits almost
328
+ * nothing.
329
+ */
330
+ /**
331
+ * How the entry side of the vocabulary overlap is read.
332
+ *
333
+ * The signal asks *is the conversation talking about this entry's subject right
334
+ * now*, and it answers by weighting each of the entry's terms by how often the
335
+ * recent window says it and how rare the term is. `overlap` adds that weight
336
+ * once **per occurrence in the entry** — so a word written three times counts
337
+ * three times, and an entry with more words has more of them to count. Lorebook
338
+ * entries vary wildly in length, which is precisely the case that reading
339
+ * handles worst: twelve near-identical entries end up ordered by how many times
340
+ * each happened to repeat itself.
341
+ *
342
+ * `balanced` is BM25 over the same inputs. The query half does not move at all;
343
+ * what changes is that the entry's own term count saturates (the fifth
344
+ * occurrence of a word is worth about a tenth of the first) and is divided by
345
+ * the entry's length relative to the rest of the lorebook. A long entry stops
346
+ * winning for being long and a repeated word stops counting linearly.
347
+ *
348
+ * `overlap` is the shipped default, on the `admitThreshold` convention: this
349
+ * changes the order lore reaches the model in, so it is turned on rather than
350
+ * arrived at on upgrade.
351
+ *
352
+ * `members` rather than `of` because the stored values are not readable: a
353
+ * picker offering "bm25" is offering the name of a paper rather than a choice.
354
+ * (The convention was `RETRIEVAL_MODE`'s before that declaration was culled;
355
+ * `TRIGRAM_FOLDING` and the entry-side strategy picker keep it.)
356
+ */
357
+ const LEXICAL_SCORING = {
358
+ type: 'enum',
359
+ default: 'overlap',
360
+ label: { en: 'Relevance balance' },
361
+ members: [
362
+ {
363
+ key: 'overlap',
364
+ label: { en: 'Raw overlap' },
365
+ description: {
366
+ en: 'Every repeat of a word counts again, so a longer entry has more chances to score.',
367
+ },
368
+ },
369
+ {
370
+ key: 'balanced',
371
+ label: { en: 'Length-aware' },
372
+ description: {
373
+ en: 'A repeated word stops adding as much, and an entry is judged against how long lorebook entries usually are. Better when entries differ a lot in length.',
374
+ },
375
+ },
376
+ ],
377
+ description: {
378
+ en: "How an entry's own wording is weighed when deciding how relevant it is to what is being said.",
379
+ },
380
+ };
381
+ /**
382
+ * How much a fuzzy, character-trigram hit on a keyword is worth, 0 being off.
383
+ *
384
+ * Word matching is not merely imprecise for unsegmented scripts — Japanese,
385
+ * Chinese and Thai have no spaces for "whole word" to mean anything against —
386
+ * so trigrams are not a refinement there, they are the only thing that works.
387
+ * Everywhere else they absorb inflection and typos: `riders` fires a key
388
+ * written `rider`, `Ashgaurd` fires `Ashguard`.
389
+ *
390
+ * A strength rather than a switch, because a fuzzy hit is genuinely weaker
391
+ * evidence than an exact one and the useful question is *how much weaker*. An
392
+ * exact match still counts 1 whatever this is, so raising it can only ever add
393
+ * matches — never move or remove one.
394
+ *
395
+ * ⚠ **0 is off and is the shipped default.** A regex key is exempt at any
396
+ * value: a pattern is not text, and folding `\b(ash|em)ber\b` into trigrams
397
+ * would match on the punctuation of the pattern rather than on anything it
398
+ * describes.
399
+ */
400
+ const TRIGRAM_FOLDING = {
401
+ type: 'number',
402
+ default: 0,
403
+ min: 0,
404
+ max: 1,
405
+ label: { en: 'Match near-misses' },
406
+ description: {
407
+ en: 'How much a keyword that is nearly present counts — a different ending, a typo, or a language that does not put spaces between words. 0 requires an exact match; try 0.5 to turn it on.',
408
+ },
409
+ };
410
+ /**
411
+ * How much a term in an entry's title counts against the same term among its
412
+ * keywords.
413
+ *
414
+ * ⚠ **1 is neutral, not off.** The title and the keywords are read as one bag
415
+ * of words today, so 1 is what already happens rather than a feature switched
416
+ * off. Above 1, an entry *about* the thing being discussed outranks one that
417
+ * merely lists it as a keyword.
418
+ *
419
+ * The other half is the **keywords**, not the entry's content. What is scored
420
+ * is the author's index; widening it to the body would change the order of
421
+ * every keyed book there is, which is a different change from this one.
422
+ */
423
+ const TITLE_WEIGHT = {
424
+ type: 'number',
425
+ default: 1,
426
+ min: 0,
427
+ max: 5,
428
+ label: { en: 'Title counts extra' },
429
+ description: {
430
+ en: "How much more a word in an entry's title counts than the same word among its keywords. 1 treats them alike.",
431
+ },
432
+ };
433
+ /**
434
+ * How much recent conversation the *presence* questions are asked over.
435
+ *
436
+ * ⚠ **Engine-read and load-bearing since long before it was declared.**
437
+ * `keywordQuery` has always taken this number off `RetrievalParams`, where it
438
+ * sat as a hardcoded 10 that nothing could reach: it sets the window
439
+ * `speakerCooccurrenceSignal` asks "did this character's own lore-bound
440
+ * character actually speak" over, and it sets the term-frequency window tf-idf
441
+ * scores an entry against. Two of the ranker's live signals, tuned by a
442
+ * constant, with no control anywhere. That is the same defect as a declared
443
+ * control nothing reads, pointed the other way.
444
+ *
445
+ * ⚠ **Not `scanDepth`, and the split is the point.** `scanDepth` is how far
446
+ * back a *keyword* may fire from; this is how much conversation counts as
447
+ * *now*. A session of long posts wants a deep scan and a short guarantee, and a
448
+ * terse one wants the reverse. `RetrievalParams` says the split is
449
+ * "behaviour-preserving while both default to 10", and this is the half that
450
+ * makes the sentence testable rather than aspirational — so it defaults to 10,
451
+ * exactly as it has silently run.
452
+ */
453
+ const GUARANTEED_MESSAGES = {
454
+ type: 'integer',
455
+ default: 10,
456
+ min: 1,
457
+ label: { en: 'Messages that count as "now"' },
458
+ description: 'How much of the recent conversation counts as the current moment when judging relevance — which characters are present, and which words the scene is actually using. Separate from how far back a keyword may fire from.',
459
+ };
460
+ const ADMIT_THRESHOLD = {
461
+ type: 'number',
462
+ default: 0,
463
+ min: 0,
464
+ max: 1,
465
+ quick: true,
466
+ label: { en: 'Find without keywords' },
467
+ description: {
468
+ en: 'How readily an entry is brought in on relevance alone when none of its keywords matched — the names the conversation is using, and the distinctive words it shares with the entry. 0 keeps keywords the only way in; try 0.3 to turn it on.',
469
+ },
470
+ };
471
+ /**
472
+ * Where a source's intent lives: **on the source** (ruled
473
+ * 2026-09-15, built 2026-09-16).
474
+ *
475
+ * `share`, `maxEntries`, `minEntries` and `priority` used to be five-band maps
476
+ * on `core:task/rank-hybrid@1`. That design was rejected, and for this
477
+ * reason: a per-source map on the ranker has to be kept in step by hand with
478
+ * whichever sources exist, goes silently stale when one is added, and a
479
+ * plugin's retrieval definition cannot take part at all without somebody
480
+ * editing the ranker. So each of the five retrieval definitions declares its
481
+ * own — the four fields below, labelled with the band they speak for — and
482
+ * publishes them as one **band intent** element at the head of its
483
+ * candidates (`BandIntent` in the SDK); `lorebook-triggers@1`, which produces
484
+ * three bands through one port, declares three (`bandIntentFieldsOf`) and
485
+ * publishes three. The ranker reads the intents off the list it is handed
486
+ * and keeps only what is cross-source.
487
+ *
488
+ * **Every default here is the number the ranker's map held**, so an install
489
+ * that tuned nothing selects exactly what it selected before: `messages` 0.5
490
+ * (which is `MESSAGE_FILL_FRACTION`), the three lore bands 0.1667 / 0.1667 /
491
+ * 0.1666, relationships 0; ceilings 50 / 20 / 15 / 10 and none; a minimum of 6
492
+ * on the conversation alone. Migration 0135 moves every stored value to
493
+ * the node that owns it now.
494
+ *
495
+ * ⚠ **`minEntries` is declared on `session-history` alone.** The ruling:
496
+ * *per-source minimums are removed everywhere except recent
497
+ * conversation*. A minimum is a promise to spend budget on a source whether or
498
+ * not it scored, and the one way an entry the ranker turned down could come
499
+ * back in; declaring one on a lore lane would reopen exactly that door, so
500
+ * the field is not declared there rather than declared at zero.
501
+ *
502
+ * `share` is a plain relative number, not the `share` control type: that
503
+ * type divides ONE value over its members, and there is no one value any
504
+ * more — each source states its own and the ranker normalises across
505
+ * whatever arrived (its `shareNormalisation`). Zero is still the off switch.
506
+ */
507
+ const bandIntentFields = (band, defaults) => ({
508
+ share: {
509
+ type: 'number',
510
+ min: 0,
511
+ default: defaults.share,
512
+ quick: true,
513
+ label: { en: `Share — ${band.label}` },
514
+ description: {
515
+ en: `How much of the context window ${band.noun} may take, relative to every other source. The ranker normalises the shares it is handed; set this to zero to leave ${band.noun} out.`,
516
+ },
517
+ },
518
+ maxEntries: {
519
+ type: 'integer',
520
+ min: 0,
521
+ ...(defaults.maxEntries === undefined ? {} : { default: defaults.maxEntries }),
522
+ label: { en: `Most entries — ${band.label}` },
523
+ description: {
524
+ en: `A ceiling on how many entries ${band.noun} may contribute, whatever its share.`,
525
+ },
526
+ },
527
+ priority: {
528
+ type: 'enum',
529
+ of: BAND_PRIORITIES,
530
+ members: bandPriorityMembers(),
531
+ default: 'normal',
532
+ label: { en: `Priority — ${band.label}` },
533
+ description: {
534
+ en: `How strongly ${band.noun} resists being trimmed once the shares are spent — 'high' and 'low' sort its entries ahead of or behind the others when leftover room is handed out; 'always' keeps every entry the window can hold.`,
535
+ },
536
+ },
537
+ });
538
+ /**
539
+ * The three lore bands, as ONE table: the label each band's controls wear and
540
+ * the numbers it ships at. Read by the three lanes (`worldLore`,
541
+ * `characterLore`, `historyEntries` — one band each) AND by
542
+ * `lorebook-triggers@1` (all three, namespaced — `bandIntentFieldsOf`), so
543
+ * the two shapes cannot ship a band at two numbers: a person moving from the
544
+ * narrator's one-node scan to `respond`'s three lanes finds the same defaults
545
+ * under the same labels, and migration 0135's `shipped` table has one set to
546
+ * agree with.
547
+ *
548
+ * 0.1666 on history, not 0.1667: the three lore shares summed to exactly 0.5
549
+ * on the ranker's map and still do — the migrated value is the declared one,
550
+ * so nobody's split moves by a ten-thousandth on upgrade.
551
+ */
552
+ const LORE_BANDS = {
553
+ worldLore: {
554
+ band: { label: 'world lore', noun: 'world lore' },
555
+ defaults: { share: 0.1667, maxEntries: 20 },
556
+ },
557
+ characterLore: {
558
+ band: { label: 'character lore', noun: 'character lore' },
559
+ defaults: { share: 0.1667, maxEntries: 15 },
560
+ },
561
+ history: {
562
+ band: { label: 'history', noun: 'history entries' },
563
+ defaults: { share: 0.1666, maxEntries: 10 },
564
+ },
565
+ };
566
+ /**
567
+ * One band's intent, **namespaced by band** — `worldLoreShare`,
568
+ * `worldLoreMaxEntries`, `worldLorePriority` — for a definition that produces
569
+ * more than one band through one port and so has to declare more than one
570
+ * intent in ONE `params` slot (`lorebook-triggers@1`).
571
+ *
572
+ * Flat camel-case keys rather than a nested `object` field per band, and the
573
+ * reason is the storage contract: a config value is addressed by
574
+ * `(node, slot, path)` with `path` a single field name, the panel renders one
575
+ * control per top-level field, and migration 0135 moves the ranker's old
576
+ * `share.worldLore` member to exactly one row at `<band><Field>` — a nested
577
+ * shape would have needed a second addressing scheme on three definitions
578
+ * for the benefit of none. The label is the band's own ("Share — world
579
+ * lore"), so a person sees the same words on this node as on the lane.
580
+ */
581
+ const bandIntentFieldsOf = (band) => {
582
+ const f = bandIntentFields(LORE_BANDS[band].band, LORE_BANDS[band].defaults);
583
+ return {
584
+ [`${band}Share`]: f.share,
585
+ [`${band}MaxEntries`]: f.maxEntries,
586
+ [`${band}Priority`]: f.priority,
587
+ };
588
+ };
589
+ /** @public */
590
+ export const lorebookTriggers = pin(describeQueryDefinition({
591
+ id: 'core:query/lorebook-triggers@1',
592
+ i18n: { name: { en: 'Lorebook triggers' } },
593
+ timeoutMs: 2000,
594
+ /**
595
+ * All three lore lanes through one port, so all three bands — each a
596
+ * top-level template name with its variable.
597
+ * Policy, not contract: the candidates are the same either side of it.
598
+ */
599
+ bands: { worldLore: varWorldLore, characterLore: varCharacterLore, history: varHistory },
600
+ slots: {
601
+ /**
602
+ * ⚠ No `template` slot, and there was one — a *source* template for
603
+ * "how one triggered entry is written into the context".
604
+ *
605
+ * Nothing read it and nothing seeded a row for it, so it rendered as
606
+ * an empty picker. A source template belongs on the node whose job
607
+ * is the rendering — a `render-entries` task, when one is bound
608
+ * (culled: declared, never bound); two declarations of one idea, one
609
+ * of them inert, is how they drift.
610
+ */
611
+ params: {
612
+ kind: 'parameters',
613
+ facet: 'weights',
614
+ schema: {
615
+ /**
616
+ * The three bands' intents, first, as on the lanes
617
+ * (2026-09-16). This node produces world
618
+ * lore, character lore AND history through one port, so it
619
+ * declares all three — namespaced, `worldLoreShare` … —
620
+ * and publishes three band intents at the head of its
621
+ * candidates. Same defaults and labels as the three lanes,
622
+ * from `LORE_BANDS`, so the narrator's split is the reply's
623
+ * split until somebody moves one. Before this the node
624
+ * declared no intent at all and the ranker fell back to its
625
+ * own table for every lore band — the same numbers, but a
626
+ * tuned share on `narrate`'s ranker had nowhere to move to
627
+ * (0135 culled it) and nothing on this node could be tuned.
628
+ */
629
+ ...bandIntentFieldsOf('worldLore'),
630
+ ...bandIntentFieldsOf('characterLore'),
631
+ ...bandIntentFieldsOf('history'),
632
+ /**
633
+ * 10, matching `DEFAULT_RETRIEVAL.scanDepth` — the value the
634
+ * scan actually ran on while this declaration said 3 and
635
+ * nothing read it.
636
+ *
637
+ * Round-sized on purpose. A group session with five
638
+ * characters takes five messages to come back round, so a
639
+ * depth of 3 cannot see the turn it belongs to: the window
640
+ * has already slid past where the round began. Scan depth
641
+ * has to be at least a round, and a round grows with the
642
+ * cast.
643
+ */
644
+ scanDepth: {
645
+ type: 'integer',
646
+ default: 10,
647
+ label: { en: 'Messages scanned for keywords' },
648
+ description: 'How many recent messages are scanned for lorebook keywords.',
649
+ },
650
+ /**
651
+ * On this type as well as on `loreSlots`, for the reason its
652
+ * three siblings below give: the narrator runs its lore
653
+ * through this type, and this number reaches the same
654
+ * `keywordQuery` from the same `retrievalParamsFrom` seam —
655
+ * so a control that exists on the reply pipeline and not on
656
+ * the narrator is a difference no user could discover a
657
+ * reason for.
658
+ */
659
+ guaranteedMessages: GUARANTEED_MESSAGES,
660
+ /**
661
+ * The ceiling, spelled the way its three siblings spell it.
662
+ *
663
+ * ⚠ This was `recursionDepth`, and the one letter of
664
+ * difference is why it looked wired and was not:
665
+ * `retrievalParamsFrom` reads `maxRecursionDepth`, so the
666
+ * number this node stored was handed to nothing and the
667
+ * narrator ran on `DEFAULT_RETRIEVAL` whatever anybody
668
+ * typed. `narrate@1.10.0`'s own note says "Scan Depth and
669
+ * Max Recursion Depth rendered, validated and saved here
670
+ * without ever being read" — half of that was fixed by
671
+ * wiring the slot, and this is the other half, because the
672
+ * control it names was never called that here.
673
+ *
674
+ * Renamed rather than read under both spellings: two names
675
+ * for one ceiling is how the four lore types drift apart
676
+ * again, and `loreSlots` below has the older claim on the
677
+ * name. Migration 0195 carries the stored values across so
678
+ * a number somebody typed keeps its meaning — it simply
679
+ * starts working, which is the 0186 rule.
680
+ *
681
+ * Same default and same words as `loreSlots`': the narrator
682
+ * runs its lore through this type, and a ceiling that
683
+ * exists on the reply pipeline and not on the narrator is a
684
+ * difference no user could discover a reason for.
685
+ */
686
+ maxRecursionDepth: {
687
+ type: 'integer',
688
+ default: 0,
689
+ label: { en: 'Follow keyword chains this deep' },
690
+ description: 'A ceiling on how far entries may trigger further entries via keywords found in their text, however deep an individual entry asks to go. It never follows links between entries.',
691
+ },
692
+ /**
693
+ * ⚠ `caseSensitive`, `useRegex`, `weight` and `minInclude`
694
+ * were here, and are gone rather than wired. All four
695
+ * rendered, validated, stored a row and resolved through
696
+ * every scope layer while `retrievalParamsFrom` read none
697
+ * of them — plan bug 15, and the last of the dead-control
698
+ * clusters bug 12 found the first of.
699
+ *
700
+ * They divide cleanly in two, and neither half is a control
701
+ * this node should own:
702
+ *
703
+ * · `caseSensitive` and `useRegex` describe how an *entry*
704
+ * matches. `loreSlots` below already states the rule —
705
+ * the entry is what somebody is looking at when they
706
+ * want to change that — and the entry is where they
707
+ * live: `signals.ts` reads `entry.caseSensitive` and
708
+ * folds `entry.useRegex` into `entry.matchMode`, both
709
+ * columns with their own editor control. A node-level
710
+ * copy could only ever be a second answer to a question
711
+ * the row already answers.
712
+ * · `weight` and `minInclude` are the ranker's, and this
713
+ * is the same pair `core:query/session-history@1` lost
714
+ * for the same reason: they ask how one source fares
715
+ * against everything else, and a node that fetches rows
716
+ * cannot see everything else to answer it. They are
717
+ * `share` / `signal*` and `minEntries` on
718
+ * `core:task/rank-hybrid@1` now, beside their peers,
719
+ * where a share is normalised against the others rather
720
+ * than free to disagree with them.
721
+ *
722
+ * Deleting an address culls it: `reconcileConfigs` removes
723
+ * the stored value and writes a notice carrying what it
724
+ * was, which the admin workspace renders. That is the
725
+ * whole reason a cull is allowed to be the answer here —
726
+ * before the notices surface had a reader, "delete it" and
727
+ * "lose it silently" were the same act.
728
+ */
729
+ admitThreshold: ADMIT_THRESHOLD,
730
+ /**
731
+ * The three lexical-quality controls, on this type as well
732
+ * as on `loreSlots` and for `admitThreshold`'s reason: the
733
+ * narrator runs its lore through this type, and a control
734
+ * that exists on the reply pipeline and not on the narrator
735
+ * is a difference no user could discover a reason for.
736
+ */
737
+ lexicalScoring: LEXICAL_SCORING,
738
+ trigramFolding: TRIGRAM_FOLDING,
739
+ titleWeight: TITLE_WEIGHT,
740
+ },
741
+ },
742
+ },
743
+ ports: {
744
+ /**
745
+ * ⚠ No `text` in-port, and this and the three lore lanes had one
746
+ * (culled 2026-09-16). It was filled by no spec and read by
747
+ * no handler — the scan derives its window from `scope`, which is
748
+ * where it actually comes from — and each of the four carried a
749
+ * standing excuse in `wiring.test.ts` saying so.
750
+ */
751
+ in: {
752
+ scope: S.sessionScope,
753
+ /**
754
+ * **Whose private lore this read is for** — a participant
755
+ * reference (`character:<id>`), additive, 2026-09-17.
756
+ *
757
+ * Character-lore visibility is decided at the host read against
758
+ * ONE subject, and until this port existed that subject was the
759
+ * run's scope — so every voice of a multi-agent turn was handed
760
+ * every character's private lore, because one gather ran once for
761
+ * all of them. Wired inside a repeating clause
762
+ * (`speaker: $.voices.item.context.speaker`) it names the speaker
763
+ * THIS iteration is writing as, and the host applies the same
764
+ * binding-visibility gate for that character instead of the
765
+ * scope's.
766
+ *
767
+ * Unwired, `null` or empty, the scope decides exactly as it
768
+ * always did (a scope of nobody is the omniscient narrator's
769
+ * read). Any other reference that names no character row — an
770
+ * envoy, a role, a row that does not exist — reads no private
771
+ * lore at all. A reference is never *widened* here: the port
772
+ * chooses whose secrets are readable, never whether the gate runs.
773
+ */
774
+ speaker: S.participantRef,
775
+ },
776
+ // Both open with band-intent elements — three, one per lore band
777
+ // — ahead of the items; readers call `splitCandidates()`.
778
+ out: {
779
+ main: S.candidates,
780
+ hits: S.candidates,
781
+ /**
782
+ * The entries this scan **found and then excluded** — an
783
+ * entry's own selective logic said *not here* — as verdicts
784
+ * `{ source, id, reason }` (2026-10-02). A copy of one that
785
+ * another mechanism brings in (by meaning, by name) is the
786
+ * same entry the author ruled out, and
787
+ * `core:task/eligibility@1` marks it ineligible with this
788
+ * reason instead of letting it through by the side door.
789
+ */
790
+ exclusions: S.json,
791
+ },
792
+ },
793
+ }));
794
+ /**
795
+ * World lore and character lore, as two queries rather than one.
796
+ *
797
+ * `lorebook-triggers@1` returns both through a single port, and for a long
798
+ * time they shared a weight, a minimum and a share of the window there. They
799
+ * are not alike: character lore is bound to whoever is speaking and world
800
+ * lore is not, and an install that wants a lot of one and little of the
801
+ * other had no way to say so. (Since 2026-09-16 it can on either shape:
802
+ * that node declares one intent per band it produces, namespaced —
803
+ * `bandIntentFieldsOf` — from the same `LORE_BANDS` table these read.)
804
+ *
805
+ * The retrieval itself is unchanged — candidates already carry
806
+ * `source: 'worldLore' | 'characterLore'`, so each of these is the same scan
807
+ * with one filter, not a second implementation to keep in step.
808
+ *
809
+ * `scanDepth` stays: how far back the conversation is read is a property of the
810
+ * conversation, not of any entry. `useRegex`, `caseSensitive` and
811
+ * `recursionDepth` do not — they describe how an *entry* matches, and the entry
812
+ * is what somebody is looking at when they want to change that. What the node
813
+ * keeps is `maxRecursionDepth`, a ceiling over whatever entries ask for.
814
+ *
815
+ * `lorebook-triggers@1` kept its own copies of all three for as long as nothing
816
+ * read any of them; they are gone from it now, and its ceiling is spelled
817
+ * `maxRecursionDepth` like this one. The two declarations stay separate — they
818
+ * overlap in field names and nothing else — but they no longer disagree about
819
+ * which controls a lore node owns.
820
+ */
821
+ /**
822
+ * ⚠ **`retrievalMode` was declared here and is gone (migration 0203).**
823
+ *
824
+ * It named which mechanism might surface an entry that had not decided for itself —
825
+ * `rag`, `keyword` or `both` — and it was declared twice, on `loreSlots` and on
826
+ * `vector-search`, so that the two mechanisms could not disagree about the same entry.
827
+ *
828
+ * It went because the question stopped having an answer. The mechanisms
829
+ * **contribute additively to one score** rather than routing exclusively, so
830
+ * `rag` and `both` had already collapsed into the same behaviour, and the third
831
+ * value was a way to switch a mechanism off in bulk that nobody should have to
832
+ * reach for: every mechanism this app has runs by default, and one it cannot run
833
+ * subtracts a signal and reports that it did. The receipt says so in words —
834
+ * *"Vector search: no embedding model is loaded and validated"*, *"Entity links:
835
+ * nothing was embedded"* — which is what a person can act on, where a picker
836
+ * defaulted to a mode was a control that mostly described the install rather
837
+ * than a preference.
838
+ *
839
+ * ⚠ **The per-entry `retrievalStrategy` column went too, one migration later.**
840
+ * This comment used to say it was untouched and stayed, on the argument that it
841
+ * held choices real authors had made. It held none: there was no editor control
842
+ * for it in any released build, no importer set it and no seed set it, so every
843
+ * row was NULL and resolved to `rag`. Migration **0204** dropped it, and the
844
+ * last exclusive routing in the retrieval path went with it — a `keyword` entry
845
+ * had stayed out of the vector mechanism with a model loaded and a cosine of 1, which
846
+ * is this same shape one scope down.
847
+ *
848
+ * Do not reintroduce either of them under another name. A mechanism that can be
849
+ * routed away from is a mechanism that can take a candidate with it, and that is
850
+ * the one thing the governing rule forbids.
851
+ *
852
+ * If per-entry mechanism preference is wanted, it is a **weight**, not a gate:
853
+ * the mechanism-weight axis (keyword / semantic / name) already exists at
854
+ * pipeline scope, and the same concept at entry scope subtracts a signal's
855
+ * contribution while leaving the candidate in the pool — where every other
856
+ * mechanism can still find it and the receipt can still explain it.
857
+ */
858
+ /**
859
+ * The seven lore knobs, declared once and worn by all three lore lanes —
860
+ * every one of them **`shared`** (ruled 2026-09-15; the marker
861
+ * 2026-09-16, see `FieldDecl.shared`): a spec wires the three lanes' `params`
862
+ * to ONE node — core's `respond` puts them on `gather.worldLore.read` and the
863
+ * other two lanes read that slot through `slot.params({ node })` — so a person
864
+ * tuning them tunes them once, for world lore, character lore and history
865
+ * together. The wording below says so: it is the owner's label a panel shows,
866
+ * and an owner labelled "world lore" while governing three sources was the
867
+ * lie a review found.
868
+ *
869
+ * The lane's own intent (`bandIntentFields` above) sits beside them in the
870
+ * same slot, UNMARKED: through the same reference a lane's share is the
871
+ * lane's, resolved at its own address, and rendered on its own step.
872
+ */
873
+ const loreScanFields = () => ({
874
+ /**
875
+ * 10, matching `DEFAULT_RETRIEVAL.scanDepth` — the value every scan
876
+ * has actually run on. This said 3 for as long as the three lore
877
+ * lanes shipped without a wired `params` slot, so the number was
878
+ * never handed to anything and the two could not be seen to
879
+ * disagree.
880
+ *
881
+ * Round-sized on purpose. A group session with five characters
882
+ * takes five messages to come back round, so a depth of 3 cannot
883
+ * see the turn it belongs to: the window has already slid past
884
+ * where the round began. Scan depth has to be at least a round,
885
+ * and a round grows with the cast.
886
+ */
887
+ scanDepth: {
888
+ type: 'integer',
889
+ default: 10,
890
+ quick: true,
891
+ shared: true,
892
+ label: { en: 'Messages scanned for lore triggers' },
893
+ description: 'How many recent messages are scanned for lore triggers in the conversation. One setting for the three lore lanes — it applies to world lore, character lore and history. An entry is not reached through its links to other entries.',
894
+ },
895
+ /**
896
+ * Beside `scanDepth` because the pair is only legible together:
897
+ * one is how far back a key may fire from, the other is how much
898
+ * conversation counts as the present moment. See
899
+ * `GUARANTEED_MESSAGES`.
900
+ */
901
+ guaranteedMessages: { ...GUARANTEED_MESSAGES, shared: true },
902
+ maxRecursionDepth: {
903
+ type: 'integer',
904
+ default: 0,
905
+ shared: true,
906
+ label: { en: 'Follow keyword chains this deep' },
907
+ description: 'A ceiling on how far entries may trigger further entries via keywords found in their text, however deep an individual entry asks to go. It never follows links between entries.',
908
+ },
909
+ /**
910
+ * Declared on all three lanes, held by one: since 2026-09-15 a spec
911
+ * names ONE owner for the seven knobs and the other lanes read the
912
+ * owner's slot, so this is one row governing world lore, character
913
+ * lore and history alike — not one row per lane. World lore
914
+ * without keys is the case it exists for; the other two sources
915
+ * take the same answer. A per-source answer is a weight, and
916
+ * weights live on the source (`bandIntentFields`), not here.
917
+ */
918
+ admitThreshold: { ...ADMIT_THRESHOLD, shared: true },
919
+ /**
920
+ * One row for the three lanes, like `admitThreshold`: the owner's
921
+ * value reaches world lore, where entry lengths differ most,
922
+ * character lore, already narrowed to whoever is speaking, and
923
+ * dated history — which has no title at all, so the value reaches
924
+ * it and moves nothing. That is the honest state rather than a
925
+ * fourth declaration.
926
+ */
927
+ lexicalScoring: { ...LEXICAL_SCORING, shared: true },
928
+ trigramFolding: { ...TRIGRAM_FOLDING, shared: true },
929
+ titleWeight: { ...TITLE_WEIGHT, shared: true },
930
+ });
931
+ const loreSlots = (band, defaults) => ({
932
+ params: {
933
+ kind: 'parameters',
934
+ facet: 'weights',
935
+ schema: {
936
+ // The lane's own intent first: `share` is the knob a person
937
+ // reaches for, and on a lane that reads the scan knobs through
938
+ // the owner it is all the panel shows.
939
+ ...bandIntentFields(band, defaults),
940
+ ...loreScanFields(),
941
+ },
942
+ },
943
+ });
944
+ /** @experimental */
945
+ export const worldLore = pin(describeQueryDefinition({
946
+ id: 'core:query/world-lore@1',
947
+ /** The band this lane publishes — a top-level template name. */
948
+ bands: { worldLore: varWorldLore },
949
+ i18n: { name: { en: 'World lore' } },
950
+ timeoutMs: 2000,
951
+ /**
952
+ * A chat with no world lore is an ordinary chat, so nothing downstream
953
+ * needs this to have produced anything — which is also what makes it
954
+ * safe to switch off entirely. The template guards the block and the
955
+ * ranker simply has one fewer source.
956
+ */
957
+ optional: true,
958
+ slots: loreSlots(LORE_BANDS.worldLore.band, LORE_BANDS.worldLore.defaults),
959
+ ports: {
960
+ // No `text` in-port — see `lorebookTriggers`: the scan reads its
961
+ // window through `scope` (culled 2026-09-16, R-12).
962
+ in: { scope: S.sessionScope },
963
+ // Both open with a band-intent element — this lane's own — ahead
964
+ // of the items; readers call `splitCandidates()`.
965
+ out: {
966
+ main: S.candidates,
967
+ hits: S.candidates,
968
+ /**
969
+ * The entries this scan **found and then excluded** — an
970
+ * entry's own selective logic said *not here* — as verdicts
971
+ * `{ source, id, reason }` (2026-10-02). A copy of one that
972
+ * another mechanism brings in (by meaning, by name) is the
973
+ * same entry the author ruled out, and
974
+ * `core:task/eligibility@1` marks it ineligible with this
975
+ * reason instead of letting it through by the side door.
976
+ */
977
+ exclusions: S.json,
978
+ },
979
+ },
980
+ }));
981
+ /** @experimental */
982
+ export const characterLore = pin(describeQueryDefinition({
983
+ id: 'core:query/character-lore@1',
984
+ /** The band this lane publishes — a top-level template name. */
985
+ bands: { characterLore: varCharacterLore },
986
+ i18n: { name: { en: 'Character lore' } },
987
+ timeoutMs: 2000,
988
+ /** As `worldLore`: absent is a normal state, so off is a safe state. */
989
+ optional: true,
990
+ slots: loreSlots(LORE_BANDS.characterLore.band, LORE_BANDS.characterLore.defaults),
991
+ ports: {
992
+ // No `text` in-port — see `lorebookTriggers`: the scan reads its
993
+ // window through `scope` (culled 2026-09-16, R-12).
994
+ in: {
995
+ scope: S.sessionScope,
996
+ /**
997
+ * **Whose private lore this read is for** — a participant
998
+ * reference (`character:<id>`), additive, 2026-09-17.
999
+ *
1000
+ * Character-lore visibility is decided at the host read against
1001
+ * ONE subject, and until this port existed that subject was the
1002
+ * run's scope — so every voice of a multi-agent turn was handed
1003
+ * every character's private lore, because one gather ran once for
1004
+ * all of them. Wired inside a repeating clause
1005
+ * (`speaker: $.voices.item.context.speaker`) it names the speaker
1006
+ * THIS iteration is writing as, and the host applies the same
1007
+ * binding-visibility gate for that character instead of the
1008
+ * scope's.
1009
+ *
1010
+ * Unwired, `null` or empty, the scope decides exactly as it
1011
+ * always did (a scope of nobody is the omniscient narrator's
1012
+ * read). Any other reference that names no character row — an
1013
+ * envoy, a role, a row that does not exist — reads no private
1014
+ * lore at all. A reference is never *widened* here: the port
1015
+ * chooses whose secrets are readable, never whether the gate runs.
1016
+ */
1017
+ speaker: S.participantRef,
1018
+ },
1019
+ // Both open with a band-intent element — this lane's own — ahead
1020
+ // of the items; readers call `splitCandidates()`.
1021
+ out: {
1022
+ main: S.candidates,
1023
+ hits: S.candidates,
1024
+ /**
1025
+ * The entries this scan **found and then excluded** — an
1026
+ * entry's own selective logic said *not here* — as verdicts
1027
+ * `{ source, id, reason }` (2026-10-02). A copy of one that
1028
+ * another mechanism brings in (by meaning, by name) is the
1029
+ * same entry the author ruled out, and
1030
+ * `core:task/eligibility@1` marks it ineligible with this
1031
+ * reason instead of letting it through by the side door.
1032
+ */
1033
+ exclusions: S.json,
1034
+ },
1035
+ },
1036
+ }));
1037
+ /**
1038
+ * Dated summaries of earlier events.
1039
+ *
1040
+ * ⚠ **This lane did not exist between spec 1.8.0 and 1.10.0, and history was
1041
+ * silently absent from every prompt in that window.**
1042
+ *
1043
+ * `lorebook-triggers@1` returned all three sources through one port. Splitting
1044
+ * world and character lore into two nodes replaced it with two lanes that each
1045
+ * filter the shared scan to their own `source` — and nothing filtered for
1046
+ * `history`, so those candidates were built, scored, and then dropped on the
1047
+ * floor. Nothing failed: the ranker kept a `history` band, `assemble` kept
1048
+ * asking for history blocks, and both got nothing.
1049
+ *
1050
+ * The parity corpus stayed green throughout because its harness renders through
1051
+ * `lorebook-triggers@1` rather than the shipped document — the exact divergence
1052
+ * a comment in that file warns about. The corpus mirrors the three lanes now.
1053
+ *
1054
+ * Same retrieval as its two siblings: one scan, one filter.
1055
+ * @experimental
1056
+ */
1057
+ export const historyEntries = pin(describeQueryDefinition({
1058
+ id: 'core:query/history-entries@1',
1059
+ /** The band this lane publishes — a top-level template name. */
1060
+ bands: { history: varHistory },
1061
+ i18n: { name: { en: 'History entries' } },
1062
+ timeoutMs: 2000,
1063
+ /** As the lore queries: a chat with no history is an ordinary chat. */
1064
+ optional: true,
1065
+ // 0.1666, not 0.1667 — see `LORE_BANDS`.
1066
+ slots: loreSlots(LORE_BANDS.history.band, LORE_BANDS.history.defaults),
1067
+ ports: {
1068
+ // No `text` in-port — see `lorebookTriggers`: the scan reads its
1069
+ // window through `scope` (culled 2026-09-16, R-12).
1070
+ in: { scope: S.sessionScope },
1071
+ // Both open with a band-intent element — this lane's own — ahead
1072
+ // of the items; readers call `splitCandidates()`.
1073
+ out: {
1074
+ main: S.candidates,
1075
+ hits: S.candidates,
1076
+ /**
1077
+ * The entries this scan **found and then excluded** — an
1078
+ * entry's own selective logic said *not here* — as verdicts
1079
+ * `{ source, id, reason }` (2026-10-02). A copy of one that
1080
+ * another mechanism brings in (by meaning, by name) is the
1081
+ * same entry the author ruled out, and
1082
+ * `core:task/eligibility@1` marks it ineligible with this
1083
+ * reason instead of letting it through by the side door.
1084
+ */
1085
+ exclusions: S.json,
1086
+ },
1087
+ },
1088
+ }));
1089
+ /**
1090
+ * **Who is in the world, and when** — the cast's presences, as the session's
1091
+ * reading sees them (built 2026-10-02).
1092
+ *
1093
+ * A presence says *this member, at this point of their own life, is here from
1094
+ * this date until that one* (`cast_presences`). The host reads the scope
1095
+ * session's book and resolves the line before returning: only presences on the
1096
+ * session's line (its own, and an ancestor's that begin at or before the fork
1097
+ * cut) — another line's spans never reach a node. `until` is exclusive: gone at
1098
+ * Y6 is present at Y5 and absent at Y6.
1099
+ *
1100
+ * `main` is the rows `{ bindingId, from, until, position }` (`from` / `until`
1101
+ * a story date `{ year, month?, day? }` or null); `at` is the moment the
1102
+ * session reads at — its story clock, or null for the head ("now", where every
1103
+ * presence with an `until` has ended). A member with **no** rows is always
1104
+ * present: declaring nothing means being here, as it always has.
1105
+ *
1106
+ * What it is for: `core:task/eligibility@1`'s presence rule, which gates the
1107
+ * lore of a member who is not in the world at `at`. A custom retrieval reads it
1108
+ * the same way.
1109
+ * @experimental
1110
+ */
1111
+ export const castPresences = pin(describeQueryDefinition({
1112
+ id: 'core:query/cast-presences@1',
1113
+ i18n: { name: { en: 'Cast presences' } },
1114
+ timeoutMs: 2000,
1115
+ /** A session with no book, or a book that dates nobody, reads nothing — a normal state. */
1116
+ optional: true,
1117
+ ports: {
1118
+ in: { scope: S.sessionScope },
1119
+ out: {
1120
+ /** `{ bindingId, from, until, position }[]`, on the session's line. */
1121
+ main: S.json,
1122
+ /** The story date the session reads at, or null for the head. */
1123
+ at: S.json,
1124
+ },
1125
+ },
1126
+ }));
1127
+ /** @experimental */
1128
+ export const vectorSearch = pin(describeQueryDefinition({
1129
+ id: 'core:query/vector-search@1',
1130
+ i18n: { name: { en: 'Semantic search' } },
1131
+ timeoutMs: 3000,
1132
+ /**
1133
+ * A session whose install has no embedding model is an ordinary
1134
+ * session, so producing nothing is a normal outcome and the mechanism can be
1135
+ * switched off entirely — exactly as the lore queries and the entity
1136
+ * mechanism are.
1137
+ */
1138
+ optional: true,
1139
+ slots: {
1140
+ params: {
1141
+ kind: 'parameters',
1142
+ facet: 'weights',
1143
+ schema: {
1144
+ /**
1145
+ * A **ceiling, not the mechanism's switch** (2026-09-29) — see
1146
+ * `query-windows.searchByMeaning`, which is. Non-zero so that
1147
+ * turning the mechanism on with one control does something:
1148
+ * a feature whose two controls both default to off is one
1149
+ * where turning the first one on appears to do nothing.
1150
+ *
1151
+ * It *was* the switch — 0, the shipped default, was off — and
1152
+ * that was the defect: this is the chain's last node, so the
1153
+ * probes had already been embedded by the time 0 said
1154
+ * nothing was wanted. Every turn with an embedding model
1155
+ * ready paid for an embed it threw away.
1156
+ *
1157
+ * A **cap on what this mechanism contributes**, not a cap on what
1158
+ * it looks at — `topK` is that, one field down. 0 still
1159
+ * contributes nothing, and the binding returns before its
1160
+ * reads for it, but it is not how the mechanism is turned off.
1161
+ */
1162
+ maxEntries: {
1163
+ type: 'integer',
1164
+ default: 5,
1165
+ min: 0,
1166
+ label: { en: 'Entries found by meaning' },
1167
+ description: 'The most lorebook entries a search by meaning may bring in on one turn. The switch is Search by meaning, on the retrieval queries step. A pipeline that ranks this arm separately reads its per-query lists instead, which this does not cut.',
1168
+ },
1169
+ /**
1170
+ * ⚠ **40, and it was 12.** The number never reached the
1171
+ * host: the binding read `input?.topK` — an *in-port* name
1172
+ * this node does not declare — and fell through to a
1173
+ * literal `?? 40` on every run since the mechanism was
1174
+ * written. So 40 is the value every install has actually
1175
+ * been searching at, and 12 is a number that was rendered,
1176
+ * validated, saved and resolved through the whole scope
1177
+ * chain without ever being handed to anything.
1178
+ *
1179
+ * Defaulted to the effective behaviour rather than to the
1180
+ * declared one on purpose. Wiring a control is not a licence
1181
+ * to re-tune every install that never touched it: the fix is
1182
+ * that the number now *means* something, and it means what
1183
+ * it has been doing.
1184
+ *
1185
+ * A cap on what each query *looks at*, which is a different
1186
+ * question from `maxEntries` one field up — that one caps
1187
+ * what the mechanism *contributes*. Raising this widens the
1188
+ * pool the ranker's other signals get to score; raising
1189
+ * `maxEntries` lets more of it through. Neither decides
1190
+ * whether the mechanism runs at all — that is
1191
+ * `query-windows.searchByMeaning`, Automatic by default
1192
+ * (on whenever an embedding model is set up).
1193
+ */
1194
+ topK: {
1195
+ type: 'integer',
1196
+ default: 40,
1197
+ min: 1,
1198
+ label: { en: 'Closest matches per query' },
1199
+ description: 'How many of the closest matches each retrieval query returns. A wider pool for the ranker to score, not a cap on what this arm contributes.',
1200
+ },
1201
+ /**
1202
+ * How sharply a weak resemblance is discounted — and
1203
+ * emphatically **not** a minimum.
1204
+ *
1205
+ * ⚠ **This replaced `minScore: 0.35`, and the replacement is
1206
+ * a ruling rather than a rename.** A minimum similarity
1207
+ * removes a row from the pool outright, and a row that is not
1208
+ * in the pool can no longer be found by keyword, by name or
1209
+ * by proximity either — one mechanism's opinion silently
1210
+ * disabling four others. The governing rule is that a weak or
1211
+ * unavailable mechanism *subtracts a signal* and never
1212
+ * removes a candidate, so the cutoff could not stay whatever
1213
+ * number it was set to. (It was never read either; nothing
1214
+ * anywhere consumed `minScore`.)
1215
+ *
1216
+ * What replaces it shapes the **contribution** instead:
1217
+ *
1218
+ * semantic = cos ** similarityFalloff
1219
+ *
1220
+ * 1 is the raw cosine and is the off position. Above 1 the
1221
+ * curve is convex, fixed at both ends (0→0, 1→1), so a
1222
+ * near-miss loses most of its contribution while a strong
1223
+ * match keeps nearly all of its own — and the row stays in
1224
+ * the pool at every value, which is the whole point.
1225
+ *
1226
+ * ⚠ **Chosen as a shape because a threshold is not
1227
+ * portable.** Cosine distributions are not comparable across
1228
+ * embedding models: one model puts unrelated text at 0.1 and
1229
+ * another at 0.6, so `0.35` means "almost everything" on the
1230
+ * first and "almost nothing" on the second, and an install
1231
+ * that swaps models silently changes what its lorebook
1232
+ * retrieves. An exponent has no cliff to move. It is
1233
+ * strictly monotonic, so it can never reorder this
1234
+ * mechanism's own hits or turn one off — it only decides how
1235
+ * much the semantic signal is allowed to outweigh a keyword
1236
+ * that actually fired.
1237
+ */
1238
+ similarityFalloff: {
1239
+ type: 'number',
1240
+ default: 1,
1241
+ min: 1,
1242
+ max: 8,
1243
+ label: { en: 'Discount weak matches' },
1244
+ description: 'How sharply a loose resemblance counts for less than a close one. 1 takes the similarity as it comes; higher pushes vague matches down without ever removing them, so they can still be found by a keyword or a name.',
1245
+ },
1246
+ },
1247
+ },
1248
+ },
1249
+ ports: {
1250
+ in: {
1251
+ /**
1252
+ * Several query vectors, one ranked list each — a list, so
1253
+ * `json@1` (was `vector@1` until 2026-09-17):
1254
+ * what `embed-text@1`'s `vectors` publishes and what the
1255
+ * host's search reads.
1256
+ */
1257
+ vectors: S.json,
1258
+ scope: S.sessionScope,
1259
+ /**
1260
+ * **Whose private lore this search may return** — a participant
1261
+ * reference, with `core:query/character-lore@1`'s exact
1262
+ * semantics (2026-10-02): unwired, `null` or empty, the
1263
+ * scope decides as it always did; a `character:<id>` reads
1264
+ * that character's own private lore and nobody else's; any
1265
+ * other reference reads none. The leak guard for a search
1266
+ * wired inside a repeating clause, where the run's scope is
1267
+ * not the voice being written.
1268
+ */
1269
+ speaker: S.participantRef,
1270
+ },
1271
+ out: {
1272
+ main: S.candidates,
1273
+ hits: S.candidates,
1274
+ /** One ranked list per query vector, in the order they were given. */
1275
+ lists: S.json,
1276
+ /**
1277
+ * `cos(i, j)` over `hits`, by index. What MMR needs, without any
1278
+ * embedding leaving the host.
1279
+ */
1280
+ similarity: S.json,
1281
+ },
1282
+ },
1283
+ }));
1284
+ /**
1285
+ * The third mechanism — retrieval by the names a scene is using.
1286
+ *
1287
+ * The keyword mechanism matches an author's written keys against a window; the vector
1288
+ * mechanism matches an embedding. This one matches **entities**: the characters,
1289
+ * places and things the recent conversation named, against the same entities
1290
+ * found in every lorebook entry and every earlier message. A peer of the other
1291
+ * two rather than a signal inside one, because it queries a different index and
1292
+ * ranks on a different question.
1293
+ *
1294
+ * Three things follow, and they are why it exists:
1295
+ *
1296
+ * 1. **It is how a book with no keywords works.** An entry nobody indexed is
1297
+ * reached because the scene is naming the same people it names. The
1298
+ * `admitThreshold` control on the lore nodes does this *inside* the keyword
1299
+ * scan; this does it as a source of candidates in its own right.
1300
+ * 2. **It searches the transcript**, which nothing else does. The keyword scan
1301
+ * reads only a bounded recent window and the semantic mechanism never
1302
+ * searches messages (its binding asks the index for lorebook entries
1303
+ * only), so this is the one way to retrieve an *older message* by what it
1304
+ * was about.
1305
+ * 3. **It needs no embedding model.** Names are matched, not encoded, so this
1306
+ * is available on every install rather than only on the ones with a model
1307
+ * loaded.
1308
+ *
1309
+ * It reads annotations written in the background, so it is cheap per turn: the
1310
+ * work of finding names in a lorebook happens when the lorebook is written, not
1311
+ * when a turn is taken.
1312
+ * @experimental
1313
+ */
1314
+ export const entitySearch = pin(describeQueryDefinition({
1315
+ id: 'core:query/entity-search@1',
1316
+ i18n: { name: { en: 'Entity search' } },
1317
+ /**
1318
+ * Recalled lines are their own declared band (owner ruling
1319
+ * 2026-09-27, option b): a template places them as
1320
+ * `{{{recalledLines}}}`, per genre, and nothing places them
1321
+ * automatically. Carried on `messages` alone (`bandPorts`), so a spec
1322
+ * wiring only `main` — every shipped one — does not offer a name that
1323
+ * can never fill.
1324
+ */
1325
+ bands: { recalledLines: varRecalledLines },
1326
+ bandPorts: { recalledLines: ['messages'] },
1327
+ timeoutMs: 2000,
1328
+ /**
1329
+ * Off by default, so a session with nothing to find is a normal session
1330
+ * and the mechanism can be switched off entirely without anything downstream
1331
+ * noticing — exactly as the two lore queries are.
1332
+ */
1333
+ optional: true,
1334
+ slots: {
1335
+ params: {
1336
+ kind: 'parameters',
1337
+ facet: 'weights',
1338
+ schema: {
1339
+ /**
1340
+ * **On by default — 5** (ruled 2026-09-30: all supported
1341
+ * retrieval is on by default; built 2026-10-02). It was 0,
1342
+ * the `maxRecursionDepth` / `admitThreshold` convention of
1343
+ * "turned on rather than arrived at"; the ruling replaced
1344
+ * that convention for retrieval. 0 still turns it off — a
1345
+ * preset that wants keys only says so.
1346
+ */
1347
+ maxEntries: {
1348
+ type: 'integer',
1349
+ default: 5,
1350
+ min: 0,
1351
+ quick: true,
1352
+ label: { en: 'Entries found by name' },
1353
+ description: 'How many lorebook entries this may bring in because the conversation is naming the same people, places and things they do. 0 turns it off.',
1354
+ },
1355
+ /**
1356
+ * Separate from `maxEntries`, because the two answer
1357
+ * different questions and only one of them has somewhere to
1358
+ * go today.
1359
+ */
1360
+ maxMessages: {
1361
+ type: 'integer',
1362
+ default: 20,
1363
+ min: 0,
1364
+ label: { en: 'Earlier messages found by name' },
1365
+ description: "How many earlier messages this may return, as recalled lines, for naming what the scene is naming. They reach the prompt only where a pipeline ranks them and its context template places {{{recalledLines}}}. 0 turns this half off.",
1366
+ },
1367
+ /**
1368
+ * The recalled lines' **share** — a band-namespaced field,
1369
+ * because this definition publishes lore on `main`
1370
+ * and its own band on `messages`. Published as the band's
1371
+ * intent at the head of `messages` whenever `maxMessages`
1372
+ * turns the half on; the cap is `maxMessages`, which
1373
+ * already says it. The default is one lore lane's.
1374
+ */
1375
+ recalledLinesShare: {
1376
+ type: 'number',
1377
+ min: 0,
1378
+ default: 0.1667,
1379
+ label: { en: 'Share — recalled lines' },
1380
+ description: {
1381
+ en: 'How much of the context window recalled lines may take, relative to every other source. The ranker normalises the shares it is handed; set this to zero to leave recalled lines out.',
1382
+ },
1383
+ },
1384
+ scanDepth: {
1385
+ type: 'integer',
1386
+ default: 10,
1387
+ label: { en: 'Messages read for names' },
1388
+ description: 'How many recent messages are read to decide what the scene is currently about.',
1389
+ },
1390
+ /**
1391
+ * The mechanism's strength, and it is declared rather than
1392
+ * constant because the graded overlap *compresses* what it
1393
+ * measures: one strongly-shared name saturates around 0.63
1394
+ * and two around 0.86, so a weight sized for a 0/1 signal
1395
+ * would leave the improvement invisible.
1396
+ *
1397
+ * The default is deliberately the keyword weight: one thing
1398
+ * the conversation is naming that not every entry names is
1399
+ * worth about as much as one of an entry's own keys firing,
1400
+ * and the saturation then keeps it strictly below a full
1401
+ * keyword match — so authored keys still win, and this only
1402
+ * ever adds.
1403
+ */
1404
+ entityWeight: {
1405
+ type: 'number',
1406
+ default: 0.35,
1407
+ min: 0,
1408
+ max: 1,
1409
+ label: { en: 'Strength' },
1410
+ description: 'How much weight a shared name carries against the other ways an entry can be found. 0 leaves the arm finding things and ranking them last.',
1411
+ },
1412
+ },
1413
+ },
1414
+ },
1415
+ ports: {
1416
+ /**
1417
+ * ⚠ **No `text` in-port.** The four lore queries declared one that
1418
+ * nothing filled and nothing read — `loreFor` derives its window
1419
+ * from `scope` — and this declaration refused to ship a fifth with
1420
+ * the same standing excuse written for it. Theirs are culled now
1421
+ * (2026-09-16); the window comes from `scope`, which is where
1422
+ * it actually comes from.
1423
+ */
1424
+ in: {
1425
+ scope: S.sessionScope,
1426
+ /**
1427
+ * **Whose private lore this search may return** — a participant
1428
+ * reference, with `core:query/character-lore@1`'s exact
1429
+ * semantics (2026-10-02): unwired, `null` or empty, the
1430
+ * scope decides as it always did; a `character:<id>` reads
1431
+ * that character's own private lore and nobody else's; any
1432
+ * other reference reads none. The leak guard for a search
1433
+ * wired inside a repeating clause, where the run's scope is
1434
+ * not the voice being written.
1435
+ */
1436
+ speaker: S.participantRef,
1437
+ },
1438
+ out: {
1439
+ main: S.candidates,
1440
+ hits: S.candidates,
1441
+ /**
1442
+ * Earlier messages, as candidates in the declared
1443
+ * **`recalledLines`** band, headed by that band's intent
1444
+ * (2026-09-27; they sat in the transcript's `messages` band
1445
+ * before, budgeted and rendered nowhere).
1446
+ *
1447
+ * A port of its own rather than part of `main`, because the two
1448
+ * are budgeted separately and a pipeline that wants lore found
1449
+ * by name almost certainly does not want its context window
1450
+ * spent on retrieved transcript by accident.
1451
+ */
1452
+ messages: S.candidates,
1453
+ },
1454
+ },
1455
+ }));
1456
+ /**
1457
+ * Documentation search — the guide genre's one retrieval mechanism (built
1458
+ * 2026-09-16).
1459
+ *
1460
+ * The app compiles its docs — its own guides and the SDK's — into a section
1461
+ * index at build time (title, anchor, body text per heading). This reads the
1462
+ * person's most recent messages, ranks every section against them, and
1463
+ * publishes the relevant ones as candidates in its own declared band,
1464
+ * **`docsExcerpts`** (2026-09-27; it borrowed `worldLore` before) — so the
1465
+ * ranker budgets them and a template places them as `{{{docsExcerpts}}}`,
1466
+ * framed as the app's manual rather than as a story's lore, with an `{{else}}`
1467
+ * for the turn nothing matched. Each excerpt starts with its page's path.
1468
+ *
1469
+ * A question the docs do not cover publishes the band's intent and nothing
1470
+ * else — on purpose: an empty band is what lets the prompt say "nothing in the
1471
+ * docs matched" instead of handing a model loosely related text to extrapolate
1472
+ * from.
1473
+ *
1474
+ * `optional`, and it degrades to nothing: an install whose docs were never
1475
+ * compiled (a fresh checkout, `npm test`) publishes an empty band with its
1476
+ * intent, and the turn loses excerpts rather than failing.
1477
+ * @internal
1478
+ */
1479
+ export const docsSearch = pin(describeQueryDefinition({
1480
+ id: 'core:query/docs-search@1',
1481
+ i18n: {
1482
+ name: { en: 'Docs search' },
1483
+ description: {
1484
+ en: "Finds the documentation sections that answer the person's latest question, so the guide can ground its answer in them — and finds none when the docs do not cover it.",
1485
+ },
1486
+ },
1487
+ /** Its own band, a top-level template name. */
1488
+ bands: { docsExcerpts: varDocsExcerpts },
1489
+ timeoutMs: 2000,
1490
+ optional: true,
1491
+ slots: {
1492
+ params: {
1493
+ kind: 'parameters',
1494
+ facet: 'weights',
1495
+ schema: {
1496
+ ...bandIntentFields({ label: 'documentation', noun: 'documentation excerpts' }, { share: 0.25, maxEntries: 6 }),
1497
+ scanDepth: {
1498
+ type: 'integer',
1499
+ min: 1,
1500
+ default: 4,
1501
+ quick: true,
1502
+ label: { en: 'Messages searched' },
1503
+ description: {
1504
+ en: "How many of the most recent messages are read for the person's questions. Only their own messages are searched, never the guide's replies, and the newest counts most.",
1505
+ },
1506
+ },
1507
+ },
1508
+ },
1509
+ },
1510
+ ports: {
1511
+ // The scope, like the lore lanes: the newest rows are read through
1512
+ // the host's one message seam (hidden and generating rows excluded
1513
+ // there), so this can sit beside `history` in a parallel gather
1514
+ // rather than after it.
1515
+ in: { scope: S.sessionScope },
1516
+ out: { main: S.candidates, candidates: S.candidates },
1517
+ },
1518
+ }));
1519
+ /**
1520
+ * The mention detector — the query half of the entity-vector space.
1521
+ *
1522
+ * What the current scene refers to by **describing** it rather than by naming
1523
+ * it: *"the captain"*, *"the order"*, *"that bridge"*. Nothing in the lexical
1524
+ * stack can see these — no key matches them, no trigram folds them onto a
1525
+ * title, and the gazetteer has nothing to look up — and they are, as the plan
1526
+ * puts it, the references people actually write.
1527
+ *
1528
+ * A Query and not a Task, because the answer depends on the world's own
1529
+ * vocabulary: a description that turns out to be an authored lower-case name
1530
+ * (*"the ashguard"*) is dropped here, since the exact matcher owns it.
1531
+ * @experimental
1532
+ */
1533
+ export const mentionSpans = pin(describeQueryDefinition({
1534
+ id: 'core:query/mention-spans@1',
1535
+ i18n: { name: { en: 'Descriptive mentions' } },
1536
+ timeoutMs: 1000,
1537
+ /**
1538
+ * Producing nothing is the ordinary outcome — most windows describe
1539
+ * nothing — and an install that has not switched the mechanism on must not
1540
+ * be able to lose a turn to it.
1541
+ */
1542
+ optional: true,
1543
+ slots: {
1544
+ params: {
1545
+ kind: 'parameters',
1546
+ facet: 'weights',
1547
+ schema: {
1548
+ /**
1549
+ * **On by default — 8** (ruled 2026-09-30: all supported
1550
+ * retrieval is on by default; built 2026-10-02). It was 0.
1551
+ * Still the mechanism's one switch: 0 turns it off.
1552
+ *
1553
+ * **This is the entity-vector mechanism's one switch**, and it is
1554
+ * on the first node of the chain on purpose: switched off,
1555
+ * this returns before reading anything, `embed-text` is
1556
+ * handed no texts and makes no model call, and `entity-link`
1557
+ * returns before its own read. The mechanism costs literally
1558
+ * nothing until somebody asks for it — not a message read,
1559
+ * not an embedding.
1560
+ *
1561
+ * `entity-link.maxLinks` is therefore a ceiling rather than
1562
+ * a second switch and ships non-zero: a feature whose two
1563
+ * controls both default to off is one where turning the
1564
+ * first one up appears to do nothing.
1565
+ */
1566
+ maxMentions: {
1567
+ type: 'integer',
1568
+ default: 8,
1569
+ min: 0,
1570
+ quick: true,
1571
+ label: { en: 'Descriptions to follow up' },
1572
+ description: 'How many descriptive references in the recent messages — "the captain", "the order" — are matched against what your entries are called, for entries no keyword reached. Needs an embedding model; 0 turns the whole arm off.',
1573
+ },
1574
+ scanDepth: {
1575
+ type: 'integer',
1576
+ default: 10,
1577
+ label: { en: 'Messages read for descriptions' },
1578
+ description: 'How many recent messages are read for descriptions. A description points at what is being discussed now, so this is deliberately short.',
1579
+ },
1580
+ },
1581
+ },
1582
+ },
1583
+ ports: {
1584
+ /** The window comes from `scope`, like the entity mechanism's. */
1585
+ in: { scope: S.sessionScope },
1586
+ out: {
1587
+ main: S.json,
1588
+ /** The mentions with their offsets, for a receipt to point at. */
1589
+ mentions: S.json,
1590
+ /** The same strings in the same order, for the embed Provider. */
1591
+ texts: S.json,
1592
+ },
1593
+ },
1594
+ }));
1595
+ /**
1596
+ * The entity-vector mechanism — mention → name linking.
1597
+ *
1598
+ * A second named vector space holding **one vector per name** rather than one
1599
+ * per entry: an entry's title, the aliases its body declares, and for a
1600
+ * character-anchored entry the bound character's names. Queried with the
1601
+ * descriptions `core:query/mention-spans@1` found, so *"the captain"* reaches
1602
+ * Captain Vell and *"the order"* reaches The Ashguard Riders.
1603
+ *
1604
+ * ## A separate space, not a second use of the content vectors
1605
+ *
1606
+ * Different text at different lengths means different similarity
1607
+ * distributions, so a cutoff tuned for two-word names is wrong for
1608
+ * two-hundred-word passages. The two want different weights, because *"is
1609
+ * called that"* and *"is about that"* are different evidence. And they
1610
+ * invalidate independently — renaming re-embeds the names and not the content;
1611
+ * rewriting the body re-embeds the content and not the names. Comparing a short
1612
+ * string to a short string is also what embeddings are most reliable at, where
1613
+ * a two-word mention against a whole-entry vector is a granularity mismatch.
1614
+ *
1615
+ * ## ⚠ It may only reorder. It may never admit.
1616
+ *
1617
+ * The pool is the `candidates` in-port, and this returns that same list with a
1618
+ * signal attached to whatever linked. There is no id it can emit that some
1619
+ * other mechanism did not already produce, and that is a wiring guarantee
1620
+ * rather than a promise in a comment.
1621
+ *
1622
+ * It matters because invented proper nouns are where embeddings are least
1623
+ * reliable: "Vell" has no learned meaning, so its vector is assembled from
1624
+ * subword fragments and Vell, Vall and Vela cluster. A confident wrong link is
1625
+ * worse than a miss — it would inject wrong lore at high confidence into a
1626
+ * fixed budget, displacing right lore. Constrained to reordering, the same
1627
+ * wrong link costs a position and a line in the receipt naming it.
1628
+ *
1629
+ * So: exact and trigram matching own invented names; entity vectors own
1630
+ * descriptive references.
1631
+ *
1632
+ * ## No threshold, anywhere
1633
+ *
1634
+ * Links rank, they do not gate. What bounds this is a **count**, over links
1635
+ * ordered by match quality — never a similarity cutoff, because *"is 0.62 a
1636
+ * match"* has no answer that survives changing the encoder, and a number that
1637
+ * needs per-corpus calibration is a number nobody can set.
1638
+ * @experimental
1639
+ */
1640
+ export const entityLink = pin(describeQueryDefinition({
1641
+ id: 'core:query/entity-link@1',
1642
+ i18n: { name: { en: 'Entries called by a description' } },
1643
+ /**
1644
+ * `embed-text`'s budget rather than `vector-search`'s, because this node
1645
+ * can *embed*: it brings a bounded slice of the name index up to date
1646
+ * before it reads. Being cut short costs the remainder of that pass and
1647
+ * nothing else — each entry is written before the next is embedded, so
1648
+ * progress survives and the mechanism links whatever is already indexed.
1649
+ */
1650
+ timeoutMs: 5000,
1651
+ /**
1652
+ * Empty from this node means *the ranker sees the candidate list
1653
+ * unchanged*, never *the ranker sees nothing*: it is wired as the first
1654
+ * source of a concatenation whose second source is the unenriched list.
1655
+ * So every way it can produce nothing — off, no model, an error the
1656
+ * executor recovered as empty — lands on exactly what the ranker would
1657
+ * have seen without it.
1658
+ */
1659
+ optional: true,
1660
+ slots: {
1661
+ params: {
1662
+ kind: 'parameters',
1663
+ facet: 'weights',
1664
+ schema: {
1665
+ /**
1666
+ * A **ceiling, not the mechanism's switch** — see
1667
+ * `mention-spans.maxMentions`, which is. Non-zero so that
1668
+ * turning the mechanism on with one control does something.
1669
+ */
1670
+ maxLinks: {
1671
+ type: 'integer',
1672
+ default: 5,
1673
+ min: 0,
1674
+ label: { en: 'Most entries linked' },
1675
+ description: 'A ceiling on how many entries one turn may have matched to a description. The best matches are kept; this never brings in an entry nothing else found, it only changes where one comes in the order.',
1676
+ },
1677
+ },
1678
+ },
1679
+ },
1680
+ ports: {
1681
+ in: {
1682
+ scope: S.sessionScope,
1683
+ /**
1684
+ * ⚠ **The pool, and the reason this mechanism cannot admit.** It
1685
+ * scores what arrives here and returns it; an entry no other
1686
+ * mechanism produced is not in this list and therefore cannot
1687
+ * be in the output.
1688
+ */
1689
+ candidates: S.candidates,
1690
+ /** The descriptions, from `core:query/mention-spans@1`. */
1691
+ mentions: S.json,
1692
+ /** Their embeddings, in the same order. Index alignment is the contract. */
1693
+ vectors: S.json,
1694
+ /**
1695
+ * **Whose private lore this search may return** — a participant
1696
+ * reference, with `core:query/character-lore@1`'s exact
1697
+ * semantics (2026-10-02): unwired, `null` or empty, the
1698
+ * scope decides as it always did; a `character:<id>` reads
1699
+ * that character's own private lore and nobody else's; any
1700
+ * other reference reads none. The leak guard for a search
1701
+ * wired inside a repeating clause, where the run's scope is
1702
+ * not the voice being written.
1703
+ */
1704
+ speaker: S.participantRef,
1705
+ },
1706
+ out: {
1707
+ main: S.candidates,
1708
+ candidates: S.candidates,
1709
+ /** Each link as text — *matched "the captain" → Captain Vell*. */
1710
+ links: S.json,
1711
+ },
1712
+ },
1713
+ }));
1714
+ /** Illegal by construction elsewhere; used to prove the purity probe. @internal */
1715
+ export const network = pin(describeQueryDefinition({
1716
+ id: 'test:query/network@1',
1717
+ timeoutMs: 1000,
1718
+ ports: { out: { main: S.json } },
1719
+ }));
1720
+ /**
1721
+ * Builds the object a context template renders against.
1722
+ *
1723
+ * A Task, not a Query, even though it reads the cast: what it *is* is the
1724
+ * resolution — which characters appear, which get named, which scenario wins —
1725
+ * and that is a decision anyone should be able to replace. The read reaches the
1726
+ * host like any other (a Task never holds host services itself).
1727
+ *
1728
+ * Separate from Assemble on purpose. Assemble allocates a budget and renders;
1729
+ * this decides what there is to render. A plugin that wants different character
1730
+ * cards should not have to reimplement token allocation to get them.
1731
+ * @public
1732
+ */
1733
+ export const sessionCast = pin(describeQueryDefinition({
1734
+ id: 'core:query/session-cast@1',
1735
+ i18n: { name: { en: 'Session cast' } },
1736
+ timeoutMs: 2000,
1737
+ ports: {
1738
+ in: { scope: S.sessionScope },
1739
+ out: {
1740
+ main: S.sessionCast,
1741
+ cast: S.sessionCast,
1742
+ /**
1743
+ * The seated envoys on their own (additive
1744
+ * 2026-09-21): `{ slug, key, origin, name, speaks,
1745
+ * default, position, removedAt }` per seat, live and departed,
1746
+ * in seat order — the rows `main` already carries under
1747
+ * `envoys`, offered as a port so a pool or a strategy can be
1748
+ * wired to them without taking the whole cast. There is no
1749
+ * separate envoy query node, and none should be made.
1750
+ */
1751
+ envoys: S.json,
1752
+ },
1753
+ },
1754
+ }));
1755
+ /**
1756
+ * The session's settings document, re-read.
1757
+ *
1758
+ * Every core inlet that takes a session already publishes the document on
1759
+ * its `session` port, resolved once by the host at run start. This node is
1760
+ * the second way in: placed **after a write that may have moved a value** —
1761
+ * a turn-order write, an annex write — so the rest of the graph reads what
1762
+ * is stored now rather than what the run began with. Same document, same
1763
+ * resolver (`resolveSessionSettings`), no other table read.
1764
+ * @experimental
1765
+ */
1766
+ export const sessionSettings = pin(describeQueryDefinition({
1767
+ id: 'core:query/session-settings@1',
1768
+ i18n: { name: { en: 'Session settings' } },
1769
+ timeoutMs: 2000,
1770
+ ports: {
1771
+ in: { scope: S.sessionScope },
1772
+ out: { main: S.sessionSettings },
1773
+ },
1774
+ }));
1775
+ /**
1776
+ * The narrative graph's relationships, as two nodes.
1777
+ *
1778
+ * ⚠ Replaced `core:query/graph-context@1`, which emitted all of it through one
1779
+ * port as one variable. Two things were wrong with that. The prompt showed a
1780
+ * single "Your relationships:" block containing both what the speaker thinks
1781
+ * of everyone and what everyone thinks of the speaker, which are opposite
1782
+ * claims that a model reads as one list; and being one variable, they shared a
1783
+ * layout, a priority and an on/off switch, so "include how others see me but
1784
+ * not my own view" could not be said.
1785
+ *
1786
+ * Two nodes rather than two out-ports on one, following the split of
1787
+ * `lorebook-triggers` into world and character lore: each can then be switched
1788
+ * off, weighted and laid out on its own, which is the entire reason for
1789
+ * separating them. They run in the same `async` block, so the second traversal
1790
+ * costs concurrency rather than wall-clock.
1791
+ *
1792
+ * ⚠ Neither carries a retrieval control of any kind, and that was already true
1793
+ * when the lore lanes still declared `retrievalMode`. A graph relationship is
1794
+ * reached by walking edges from the speaker's node — there is no keyword mechanism and
1795
+ * no vector mechanism to choose between, so a picker here would have been a control
1796
+ * that reads well and does nothing, which is what `session-history@1`'s dead
1797
+ * `template` slot already cost this codebase once.
1798
+ */
1799
+ const relationshipSlots = (what) => ({
1800
+ params: {
1801
+ kind: 'parameters',
1802
+ facet: 'weights',
1803
+ schema: {
1804
+ maxEntries: {
1805
+ type: 'integer',
1806
+ /**
1807
+ * ⚠ **No `default:`, and its absence is the declaration.**
1808
+ *
1809
+ * Neither spec ever named this slot, so `resolveInput` never
1810
+ * resolved it and `bindings.ts` called `capRelationships` with
1811
+ * `undefined` on every run this node type has ever made — which
1812
+ * that function reads as *no ceiling at all* and returns the
1813
+ * section whole. `respond` wires `params: slot.params()` now, so
1814
+ * whatever is declared here becomes live; under ruling D-8 the
1815
+ * declared default must therefore BE the value every run has
1816
+ * actually used, and that value is "uncapped".
1817
+ *
1818
+ * Uncapped is not expressible as a number here. `0` is already
1819
+ * taken and means the opposite — `capRelationships` returns
1820
+ * `null` for it, so the section is dropped entirely, which is the
1821
+ * `admitThreshold` / `maxEntries` off-switch convention this
1822
+ * package uses everywhere. A negative sentinel IS what
1823
+ * `capRelationships` reads as "no cap" (`cap < 0` returns the
1824
+ * section), but `min: 0` forbids one and no other parameter in
1825
+ * this package uses a negative sentinel; inventing the convention
1826
+ * here would be a design decision riding in on a wiring fix. And
1827
+ * a large finite number is not the value either — it is a
1828
+ * different value that is *usually* indistinguishable, which is
1829
+ * the kind of nearly-right that D-8 exists to refuse.
1830
+ *
1831
+ * So: no default. `resolveSlot`'s params branch copies a schema
1832
+ * default only `if (v?.default !== undefined)`, and
1833
+ * `reconcileConfigs` back-fills a row only when a declaration
1834
+ * carries one — so an untouched install resolves `undefined` and
1835
+ * stays uncapped, exactly as before. The control renders as an
1836
+ * empty box, which `NumberControl` and the panel already treat as
1837
+ * "unset" (an emptied box commits `undefined` and clears the
1838
+ * row), so the empty state round-trips rather than being a hole.
1839
+ */
1840
+ min: 0,
1841
+ quick: true,
1842
+ label: { en: 'Most relationships' },
1843
+ description: {
1844
+ en: `A ceiling on how many ${what} reach the prompt, closest first. Leave it empty for no ceiling; 0 leaves the section out altogether.`,
1845
+ },
1846
+ },
1847
+ },
1848
+ },
1849
+ });
1850
+ /**
1851
+ * ⚠ Both are `optional`, and the reason is not that the graph is unimportant.
1852
+ *
1853
+ * A slow or failing relationship read must never cost somebody their reply: the
1854
+ * executor turns an `err` from an optional node into an empty result, records
1855
+ * the failure on the receipt as `recoveredAsEmpty`, and the template's `{{#if}}`
1856
+ * renders nothing — which is exactly what a chat with no narrative graph gets
1857
+ * anyway. It is also what makes them safe to switch off outright.
1858
+ */
1859
+ const RELATIONSHIP_TIMEOUT = 5000;
1860
+ /** How the speaking character regards everyone else. @experimental */
1861
+ export const relationshipsPerspectives = pin(describeQueryDefinition({
1862
+ id: 'core:query/relationships-perspectives@1',
1863
+ i18n: {
1864
+ name: { en: 'Relationships: their perspective' },
1865
+ description: {
1866
+ en: 'How the speaking character regards the others, read from the narrative graph. Produces nothing when the chat has no lorebook or the speaker has no node in it.',
1867
+ },
1868
+ },
1869
+ optional: true,
1870
+ timeoutMs: RELATIONSHIP_TIMEOUT,
1871
+ slots: relationshipSlots('of their own views'),
1872
+ ports: {
1873
+ in: { scope: S.sessionScope },
1874
+ /**
1875
+ * `json`, not `text`. The summary used to be stringified inside
1876
+ * `buildGraphContext` and handed on as a finished blob, which made
1877
+ * it the one context value a layout could do nothing with — you
1878
+ * cannot render relationships as prose, drop a section, or even
1879
+ * change the indent if the shape was flattened upstream. The node
1880
+ * emits the structure and the variable layout renders it.
1881
+ */
1882
+ out: { main: S.json, relationshipsPerspectives: S.json },
1883
+ },
1884
+ }));
1885
+ /**
1886
+ * How everyone else regards the speaking character, and who is known to all.
1887
+ *
1888
+ * `legendaryFigures` rides here rather than on the other node, and the choice
1889
+ * is arguable enough to write down: it is neither the speaker's view nor a view
1890
+ * of the speaker, it is what is *publicly known* — which is the same kind of
1891
+ * claim as "how others regard you" and the opposite kind from "what you think
1892
+ * of them". Splitting it into a third node would put a mostly-empty block in
1893
+ * every prompt on every install that has never marked a node legendary.
1894
+ * @experimental
1895
+ */
1896
+ export const relationshipsKnown = pin(describeQueryDefinition({
1897
+ id: 'core:query/relationships-known@1',
1898
+ i18n: {
1899
+ name: { en: 'Relationships: how others see them' },
1900
+ description: {
1901
+ en: 'How the others regard the speaking character, plus any figures known to everyone. Read from the narrative graph.',
1902
+ },
1903
+ },
1904
+ optional: true,
1905
+ timeoutMs: RELATIONSHIP_TIMEOUT,
1906
+ slots: relationshipSlots('views of them'),
1907
+ ports: {
1908
+ in: { scope: S.sessionScope },
1909
+ out: { main: S.json, relationshipsKnown: S.json },
1910
+ },
1911
+ }));
1912
+ /**
1913
+ * The narrative graph as a retrieval **mechanism** (ruling 2026-09-10).
1914
+ *
1915
+ * ⚠ The ruling calls this an *arm*, and the id deliberately does not. Two
1916
+ * reasons, and the second is the stronger: the project's vocabulary retires *arm* in
1917
+ * favour of **mechanism**, and every sibling in this package is named for what
1918
+ * it retrieves rather than for the machinery — `entity-search`,
1919
+ * `vector-search`, `world-lore`. The word survives in the *descriptions* on
1920
+ * those siblings, which is prose a user reads; an id is a frozen
1921
+ * contract, which is the one place a retired word should not land.
1922
+ *
1923
+ * The two nodes above are a *dump*: they hand the whole graph section to the
1924
+ * template, in whatever order the database returned the rows, and the only
1925
+ * control over it is a ceiling. Every other source the prompt is built from is
1926
+ * shared, ranked and allocated — which is what makes "world lore matters more
1927
+ * than history in this chat" sayable, and what makes "why is this entry here"
1928
+ * answerable. Relationships were the one source none of that reached.
1929
+ *
1930
+ * This is the same three sections read as **candidates**, one per relationship,
1931
+ * in the `relationships` band the ranker and the budget have carried since they
1932
+ * were written. What it buys is the whole retrieval surface at once: the band's
1933
+ * share divides the window, `select` decides what fits, and every relationship
1934
+ * arrives on the receipt with a reason.
1935
+ *
1936
+ * ## Ranked here, not by a second ranker
1937
+ *
1938
+ * `core:task/rank-hybrid@1` takes this like any other candidate source — the
1939
+ * band exists, the share exists, the entry cap exists — so there is no new rank
1940
+ * node and no new signal weight. What this node contributes is the **order**,
1941
+ * as a `presetScore` the ranker uses directly: scene presence first, then
1942
+ * whether the speaker is party to the tie, then how recently it changed. The
1943
+ * arithmetic is deterministic and the receipt states each term, which is the
1944
+ * standard `presetScore` carries — `core:query/entity-search@1` ranks its own
1945
+ * hits the same way for the same reason.
1946
+ *
1947
+ * ⚠ **It does not duplicate the two nodes above.** All three reach
1948
+ * `core:task/build-template-context@1`, on the same two in-ports and never
1949
+ * twice: this band is what those sections are built from on a run that
1950
+ * allocated any of it, and the two nodes' own dump is what they are built from
1951
+ * on a run that did not — which is every run until somebody raises the
1952
+ * relationships share. See docs/embeddings-and-rag.md.
1953
+ *
1954
+ * `relationshipSlots` rather than a declaration of its own, so the ceiling here
1955
+ * means exactly what it means on the two nodes above: on/off plus a ceiling,
1956
+ * with an absent value uncapped and 0 leaving it out altogether.
1957
+ *
1958
+ * ## Nobody speaking: the cast-wide read (2026-09-29)
1959
+ *
1960
+ * The three sections are claims about a SPEAKER, and a scope whose
1961
+ * `currentCharacterId` is null has none — an Adventure turn is the narrator's
1962
+ * entry, and its planner and narrator are nobody's voice. Such a scope reads
1963
+ * the **cast-wide read** instead: every relationship a cast member holds, one
1964
+ * candidate each in the `castRelationships` lane, headed by its holder and
1965
+ * naming the other end. A host decides what it may carry; Serene Pub withholds
1966
+ * a member's secrets, since nobody's voice is not the holder's. Ordered
1967
+ * the same way — presence (both ends in the cast), then recency; no tie
1968
+ * touches a speaker. Which agents are handed that band is the spec's choice:
1969
+ * a voice is somebody speaking, and wires none of it.
1970
+ *
1971
+ * `loreLinks` switches the one-hop walk from the entries the turn chose (a
1972
+ * room's ways out, what an item belongs to). On by default, which is what this
1973
+ * node has always done; a genre whose places say their own ways out ("From
1974
+ * here:") turns it off, so a place link is said once, by the place.
1975
+ * @experimental
1976
+ */
1977
+ export const relationshipSearch = pin(describeQueryDefinition({
1978
+ id: 'core:query/relationship-search@1',
1979
+ i18n: {
1980
+ name: { en: 'Relationships: ranked' },
1981
+ description: {
1982
+ en: 'The narrative graph as ranked candidates that compete for the context window, ordered by who is in the scene, who is speaking, and what changed most recently.',
1983
+ },
1984
+ },
1985
+ optional: true,
1986
+ timeoutMs: RELATIONSHIP_TIMEOUT,
1987
+ slots: {
1988
+ params: {
1989
+ ...relationshipSlots('graph relationships').params,
1990
+ schema: {
1991
+ /**
1992
+ * The band's intent, on the one relationship read
1993
+ * that ranks. `share` is 0, which is what the ranker's map
1994
+ * held: the band ships inert and the share is its switch —
1995
+ * every candidate leaves as `excluded_group_disabled` with
1996
+ * that reason until somebody raises it, and the two dump
1997
+ * nodes render the graph whole meanwhile.
1998
+ *
1999
+ * `maxEntries` is `relationshipSlots`' own — the ceiling
2000
+ * this node already applies before it publishes — and it is
2001
+ * the band's ceiling too: one number, the query's, rather
2002
+ * than a second on the ranker free to disagree. Absent
2003
+ * means uncapped, as it always has here, where the map's
2004
+ * `relationships: 0` was a cap of nothing sitting behind a
2005
+ * share of nothing — raising the share alone used to
2006
+ * exclude every relationship as over its ceiling. It does
2007
+ * not now. Migration 0135 culls a stored 0 for that reason
2008
+ * and moves anything else.
2009
+ */
2010
+ ...bandIntentFields({ label: 'relationships', noun: 'the narrative graph' }, { share: 0 }),
2011
+ // Declared second so the query's own wording and `min: 0`
2012
+ // win over the generic ceiling above.
2013
+ ...relationshipSlots('graph relationships').params.schema,
2014
+ /**
2015
+ * The lore-link hop: relationships one edge from an entry
2016
+ * this turn's keyword scan chose, with an entry at an end
2017
+ * (a *lore link*).
2018
+ *
2019
+ * `true` is what every run before it did, so the default
2020
+ * moves nothing. Off, the hop is not walked at all — no
2021
+ * link read, no second scan — and the band holds cast ties
2022
+ * only. Adventure's preset turns it off: a place
2023
+ * link belongs to the place ("From here:"), and a hop would
2024
+ * spend the band on a door no section renders.
2025
+ */
2026
+ loreLinks: {
2027
+ type: 'boolean',
2028
+ default: true,
2029
+ label: { en: 'Follow lore links' },
2030
+ description: {
2031
+ en: 'Also offer the links one step from the lore this turn found — a room’s ways out, what an item belongs to. Off keeps the band to relationships between characters.',
2032
+ },
2033
+ },
2034
+ },
2035
+ },
2036
+ },
2037
+ ports: {
2038
+ /**
2039
+ * ⚠ **No `text` in-port**, for `core:query/entity-search@1`'s
2040
+ * reason: the four lore queries declared one that nothing filled
2041
+ * and nothing read (culled 2026-09-16), and shipping a fifth with
2042
+ * the same standing excuse written for it would have been adding
2043
+ * the defect on purpose. A relationship is reached by walking edges
2044
+ * from the speaker's node, so the scope is the whole of the
2045
+ * question.
2046
+ */
2047
+ in: { scope: S.sessionScope },
2048
+ out: {
2049
+ // Both open with a band-intent element — the graph's own,
2050
+ // published whether or not a tie was found — ahead of the
2051
+ // items; readers call `splitCandidates()`.
2052
+ main: S.candidates,
2053
+ hits: S.candidates,
2054
+ /**
2055
+ * How many ties were walked, how many the scene was present
2056
+ * for, and what the ceiling did — the mechanism-level half of
2057
+ * the trail, which no per-candidate row can carry.
2058
+ *
2059
+ * Declared rather than merely published, unlike the lore lanes'
2060
+ * own diagnostics: an undeclared out-port is invisible to
2061
+ * `validate.ts` and unreadable by a plugin, which is the finding
2062
+ * `core:task/rank-hybrid@1`'s `groups` cost a release.
2063
+ */
2064
+ diagnostics: S.json,
2065
+ },
2066
+ },
2067
+ }));
2068
+ /**
2069
+ * 🚧 **A transcript's attachments** (2026-10-02).
2070
+ *
2071
+ * Takes the history read's rows and publishes, per message id, the files its
2072
+ * active revision shows — `core:image` and `core:file` parts, in part order —
2073
+ * as `HistoryAttachmentV1` references (`core:shape/media-by-message@1`). One
2074
+ * query for the whole transcript. A text file arrives with its body (up to
2075
+ * `textFileBytes`), because a text file reaches every model as text and the
2076
+ * placement step after this one cannot read a disk.
2077
+ *
2078
+ * Reads only rows of the run's own session; a message of any other session
2079
+ * contributes nothing. A message with no files is absent from the record.
2080
+ * @experimental
2081
+ */
2082
+ export const historyAttachments = pin(describeQueryDefinition({
2083
+ id: 'core:query/history-attachments@1',
2084
+ i18n: { name: { en: 'History attachments' } },
2085
+ timeoutMs: 2000,
2086
+ slots: {
2087
+ params: {
2088
+ kind: 'parameters',
2089
+ facet: 'weights',
2090
+ schema: {
2091
+ textFileBytes: {
2092
+ type: 'integer',
2093
+ min: 0,
2094
+ default: 65536,
2095
+ label: { en: 'Text file read limit (bytes)' },
2096
+ description: {
2097
+ en: 'How much of each attached text file is read for the prompt. The placement step trims it further to its own token budget and says when it did.',
2098
+ },
2099
+ },
2100
+ },
2101
+ },
2102
+ },
2103
+ ports: {
2104
+ in: { messages: S.messages },
2105
+ out: { main: S.mediaByMessage, attachments: S.mediaByMessage },
2106
+ },
2107
+ }));
2108
+ /**
2109
+ * Which tools this session can call, and how each one is described to a model.
2110
+ *
2111
+ * A Query rather than a literal on `advertise-tools`, because the answer is
2112
+ * not a property of the spec: the core tools are fixed, but an install's
2113
+ * extensions are not, and a spec that listed its tools by hand would advertise
2114
+ * a tool an uninstalled plugin no longer provides — and refuse, by name, the
2115
+ * one that was installed yesterday.
2116
+ *
2117
+ * Each entry is `{ name, description, parameters }` with `parameters` as JSON
2118
+ * Schema, which is the shape `advertise-tools` takes and the shape every
2119
+ * native tool API wants. Nothing here executes anything; `run-tool` does that,
2120
+ * and refuses any name this list did not carry.
2121
+ * @experimental
2122
+ */
2123
+ export const availableTools = pin(describeQueryDefinition({
2124
+ id: 'core:query/available-tools@1',
2125
+ i18n: { name: { en: 'Available tools' } },
2126
+ timeoutMs: 2000,
2127
+ slots: {
2128
+ params: {
2129
+ kind: 'parameters',
2130
+ schema: {
2131
+ include: {
2132
+ type: 'string[]',
2133
+ description: 'Offer only these tools, by name, in this order. Empty offers every tool the session has.',
2134
+ },
2135
+ plugins: {
2136
+ type: 'boolean',
2137
+ default: true,
2138
+ description: "Offer tools contributed by the session's enabled extensions, as well as the built-in ones.",
2139
+ },
2140
+ },
2141
+ },
2142
+ },
2143
+ ports: { in: { scope: S.sessionScope }, out: { main: S.json, tools: S.json } },
2144
+ }));
2145
+ // ── Consumers ───────────────────────────────────────────────────────────────
2146
+ /**
2147
+ * Create a message.
2148
+ *
2149
+ * Split from the old `commitMessage`, which decided new-vs-update from whether an id
2150
+ * happened to be present. That was an implicit branch, and specs may not branch because
2151
+ * implicit branches are unreadable: two specs that did different things looked identical,
2152
+ * and the receipt could not tell you which had happened. Two ids, two names, no inference.
2153
+ *
2154
+ * Gate-eligible, so it publishes the discriminated write result rather than raw ids.
2155
+ * Under async review this is a proposal a reviewer may still reject.
2156
+ */
2157
+ /**
2158
+ * The create pipeline's read: what the session's cast wants to
2159
+ * say first — one entry per character in position order, each carrying the
2160
+ * full greeting history (the first text seeds the message, the rest become
2161
+ * swipes), interpolated against the session's first persona.
2162
+ *
2163
+ * A Query, because deciding what a greeting *is* — group-only lists, the
2164
+ * interpolation, the fallback line — is exactly the kind of decision a
2165
+ * custom genre should be able to replace without reimplementing the write.
2166
+ * @experimental
2167
+ */
2168
+ export const sessionGreetings = pin(describeQueryDefinition({
2169
+ id: 'core:query/session-greetings@1',
2170
+ i18n: { name: { en: 'Session greetings' } },
2171
+ timeoutMs: 2000,
2172
+ ports: {
2173
+ in: { scope: S.sessionScope },
2174
+ out: { main: S.json, greetings: S.json },
2175
+ },
2176
+ }));
2177
+ /**
2178
+ * A seated envoy's **declared greeting**, interpolated
2179
+ * (2026-09-28) — the line an envoy opens a new session with
2180
+ * (`EnvoyDecl.greeting`): the Lair's Castellan introduces the game.
2181
+ *
2182
+ * The create pipeline's read, beside `session-greetings@1`, which stays the
2183
+ * CARDS' greetings. A Query for the same reason that one is: what a greeting
2184
+ * says is a decision a custom genre may replace without reimplementing the
2185
+ * write.
2186
+ *
2187
+ * **Absent** — `text` empty — when the envoy is not seated in the session
2188
+ * or declares no greeting, so a spec writes behind a junction on `text` and
2189
+ * a session whose envoy was never seated gets no line under its name.
2190
+ * Interpolated with the envoy as `{{char}}`, the session's `{{playerLabel}}`
2191
+ * and the party as `{{characterNames}}` (empty at creation for a genre that
2192
+ * seats nobody yet, so the copy writes `{{#if characterNames}}`).
2193
+ *
2194
+ * No model call: a create run is a person waiting (`lair-create`).
2195
+ * @experimental
2196
+ */
2197
+ export const envoyGreeting = pin(describeQueryDefinition({
2198
+ id: 'core:query/envoy-greeting@1',
2199
+ i18n: {
2200
+ name: { en: 'Envoy greeting' },
2201
+ description: {
2202
+ en: "The opening line a seated envoy declares, filled in for this session. Empty when the envoy is not seated or declares none.",
2203
+ },
2204
+ },
2205
+ timeoutMs: 2000,
2206
+ slots: {
2207
+ params: {
2208
+ kind: 'parameters',
2209
+ schema: {
2210
+ /** The envoy, by its genre-local key (`castellan`). */
2211
+ envoy: {
2212
+ type: 'text',
2213
+ label: { en: 'Envoy' },
2214
+ description: "Which of the genre's envoys greets, by its key.",
2215
+ },
2216
+ },
2217
+ },
2218
+ },
2219
+ ports: {
2220
+ in: { scope: S.sessionScope },
2221
+ out: { main: S.text, text: S.text },
2222
+ },
2223
+ }));
2224
+ // ── The built-in writes (R-15, ruled 2026-09-15, built 2026-09-16) ──────────
2225
+ /**
2226
+ * 🚧 The **standing turn plan** a character turn plays from (Lair character
2227
+ * turns, owner ruling 2026-09-30).
2228
+ *
2229
+ * A planner's row carries the turns it planned (`create-message@1`'s
2230
+ * `turnPlan`, stored as `metadata.turnPlan`). Each named member then takes a
2231
+ * **character turn** of their own — a separate run, fired off the turn order
2232
+ * — and that run reads the plan back here: the planner's document (where the
2233
+ * scene is, what was planned) and the prose describing a room nobody filed.
2234
+ *
2235
+ * The plan that **stands** is the newest planner's row in the session's
2236
+ * history, unless a person's line on `main` is newer than it — a person
2237
+ * speaking after a plan has moved the story past it. With `messageId` (a
2238
+ * regenerate or swipe re-voicing that row) only rows older than it count, so
2239
+ * a re-voiced line reads the plan it was played from. No plan standing, every
2240
+ * port reads absent and the turn plays from the scene as it stands.
2241
+ * @experimental
2242
+ */
2243
+ export const turnPlan = pin(describeQueryDefinition({
2244
+ id: 'core:query/turn-plan@1',
2245
+ i18n: { name: { en: 'Turn plan' } },
2246
+ timeoutMs: 2000,
2247
+ ports: {
2248
+ in: {
2249
+ scope: S.sessionScope,
2250
+ /** The row a regenerate or swipe re-voices — the inlet's `messageId`. Absent on a fresh turn. */
2251
+ messageId: S.rowIds,
2252
+ },
2253
+ out: {
2254
+ main: S.json,
2255
+ /** The planner's document, as the planner's row stored it. */
2256
+ plan: S.json,
2257
+ /** Prose describing the room the plan heads into, when the plan carried any. */
2258
+ locationPassage: S.text,
2259
+ },
2260
+ },
2261
+ }));
2262
+ /**
2263
+ * The session's **annex**: read one owner's
2264
+ * document out of `sessions.annex`.
2265
+ *
2266
+ * The annex is the pipeline layer's free field, namespaced by owner key — a
2267
+ * genre id, a plugin id, or a user-authored spec's slug. `metadata` is
2268
+ * core's own and read-only from here; this is where a spec keeps what it
2269
+ * needs to remember without core ever reinterpreting it.
2270
+ *
2271
+ * The owner defaults to the running spec's own namespace, which is the
2272
+ * whole safety of it: a spec reads its own document by default and has to
2273
+ * say `sharedAnnex` out loud to read anybody else's.
2274
+ * @experimental
2275
+ */
2276
+ export const sessionAnnex = pin(describeQueryDefinition({
2277
+ id: 'core:query/session-annex@1',
2278
+ i18n: { name: { en: 'Session annex' } },
2279
+ timeoutMs: 1000,
2280
+ slots: {
2281
+ params: {
2282
+ kind: 'parameters',
2283
+ facet: 'behavior',
2284
+ schema: {
2285
+ owner: {
2286
+ type: 'string',
2287
+ default: '',
2288
+ label: { en: 'Owner' },
2289
+ description: {
2290
+ en: "Whose document to read. Blank means this pipeline's own.",
2291
+ },
2292
+ },
2293
+ sharedAnnex: {
2294
+ type: 'boolean',
2295
+ default: false,
2296
+ label: { en: 'Read another owner' },
2297
+ description: {
2298
+ en: "Allow reading a document this pipeline does not own. Off refuses, with a note on the receipt.",
2299
+ },
2300
+ },
2301
+ },
2302
+ },
2303
+ },
2304
+ ports: {
2305
+ in: {
2306
+ scope: S.sessionScope,
2307
+ /**
2308
+ * `'ai'` for the prompt-safe view: only the values the
2309
+ * model's context may carry — those whose audience holds `ai`,
2310
+ * `participant`, or the `speaker` below. Absent is everything,
2311
+ * as a pipeline reads it. A literal.
2312
+ *
2313
+ * `'template'` reads what a template may
2314
+ * reference: every DECLARED key of every owner in scope — core
2315
+ * and the enabled plugins, for the session's genre — as
2316
+ * `{ <owner>: { <key>: value } }`. `owner` and `sharedAnnex`
2317
+ * do not apply; a key no declaration covers is left out. Law
2318
+ * T2 lets it feed only a template node's `annex` in-port.
2319
+ */
2320
+ view: S.text,
2321
+ /** Whose prompt, for `view: 'ai'` — a `character:` or `envoy:` reference. */
2322
+ speaker: S.participantRef,
2323
+ },
2324
+ out: { main: S.json },
2325
+ },
2326
+ }));
2327
+ // ── Summarization ───────────────────────────────────────────────────────────
2328
+ /** The messages a summary is drawn from, already scoped and ordered (`@1`). */
2329
+ const summarizeSourceAt1 = pin(describeQueryDefinition({
2330
+ id: 'core:query/summarize-source@1',
2331
+ i18n: { name: { en: 'Messages to summarize' } },
2332
+ timeoutMs: 5000,
2333
+ ports: {
2334
+ in: { scope: S.sessionScope, request: S.summarizeRequest },
2335
+ out: { main: S.messages, messages: S.messages },
2336
+ },
2337
+ }));
2338
+ /**
2339
+ * 🚧 A **scene's** messages, by range and lane — the source a genre-owned
2340
+ * summarize-scene spec reads (live scenes §13–§14, 2026-10-13).
2341
+ *
2342
+ * ## Why a second version, not a widened first
2343
+ *
2344
+ * `@1` hands on one flat list of the rows a request named. A scene is a
2345
+ * RANGE on one lane (`openedAt` … `closedAt`, message ids), and what the
2346
+ * genre counts as story and as aside differs by genre: the Lair's Sanctum is
2347
+ * talk the party never hear, which a summary should read as context and never
2348
+ * as events. So this version splits its output — `messages` (the story) and
2349
+ * `asides` (each side-channel row, attached by the host to the story line
2350
+ * before it) — and that is a different contract, not a wider one. `@1`
2351
+ * stays for the shared summarize specs that resolve against it.
2352
+ *
2353
+ * ## Who decides which channels
2354
+ *
2355
+ * The SPEC, through `params` (`channel`, `asides`) — the builder writes its
2356
+ * genre's choice onto its Default preset, exactly as `session-history@1`'s
2357
+ * `channel` already works. A request may name `channel` / `asides` too (the
2358
+ * scene row's own lane, say), and a value the request carries wins over the
2359
+ * param, because it is the narrower statement.
2360
+ *
2361
+ * ## The request
2362
+ *
2363
+ * `{ sceneId?, messageIds?, channel?, asides?: string[], openedAt?,
2364
+ * closedAt?, limit? }` on the `summarize-request@1` payload. `openedAt` /
2365
+ * `closedAt` are message ids bounding the range, inclusive; `closedAt` absent
2366
+ * reads to the newest row (an open scene). `messageIds` is the transition
2367
+ * path (`scenes:create`'s ticked rows) and wins when present. An empty span
2368
+ * is not an error: the source hands on two empty lists and the drafting map
2369
+ * runs zero times. A channel the session has never written is the same — an
2370
+ * aside on a lane with no rows contributes nothing, never a refusal.
2371
+ *
2372
+ * ## The rows
2373
+ *
2374
+ * `@1`'s `summarize_source` row shape — `id`, `role`, `senderName` (the
2375
+ * sender as the session names them), `content` — plus `channel` on every
2376
+ * row, so the transcript template's `aside` section can say where a line was
2377
+ * written. `render-transcript@1` reads these and nothing else.
2378
+ * @experimental
2379
+ */
2380
+ const summarizeSourceAt2 = pin(describeQueryDefinition({
2381
+ id: 'core:query/summarize-source@2',
2382
+ i18n: { name: { en: 'Scene to summarize' } },
2383
+ timeoutMs: 5000,
2384
+ slots: {
2385
+ params: {
2386
+ kind: 'parameters',
2387
+ facet: 'behavior',
2388
+ schema: {
2389
+ /** The story's lane — `main` for every core genre. */
2390
+ channel: {
2391
+ type: 'string',
2392
+ default: 'main',
2393
+ label: { en: 'Story channel' },
2394
+ description: {
2395
+ en: "Which of the session's channels holds the story. The chat log is 'main'.",
2396
+ },
2397
+ },
2398
+ /**
2399
+ * Channels read as asides: rows matched by prefix
2400
+ * (`sanctum` matches `sanctum:2`), each attached to the
2401
+ * story line before it. Empty reads the story alone.
2402
+ */
2403
+ asides: {
2404
+ type: 'list',
2405
+ item: { type: 'text' },
2406
+ label: { en: 'Aside channels' },
2407
+ description: {
2408
+ en: "Side channels whose lines the summary reads as context, not as events — the Lair's 'sanctum'. Leave it empty to read the story alone.",
2409
+ },
2410
+ },
2411
+ },
2412
+ },
2413
+ },
2414
+ ports: {
2415
+ in: { scope: S.sessionScope, request: S.summarizeRequest },
2416
+ out: {
2417
+ main: S.messages,
2418
+ /** The story's rows on the story channel, oldest first. */
2419
+ messages: S.messages,
2420
+ /** The aside rows inside the range, oldest first, each carrying its channel. */
2421
+ asides: S.messages,
2422
+ },
2423
+ },
2424
+ }));
2425
+ /**
2426
+ * The messages a summary is drawn from — both pins on one export, the way a
2427
+ * pinned constructor carries its version at the call site (04 §4b):
2428
+ * `C.summarizeSource.v1(…)` for the shared summarize specs,
2429
+ * `C.summarizeSource.v2(…)` for a genre's summarize-scene. `id` and
2430
+ * `descriptor` stay `@1`'s, so nothing that held this export changes
2431
+ * meaning; `@2`'s descriptor rides its constructor
2432
+ * (`typeof C.summarizeSource.v2` types a binding).
2433
+ * @internal
2434
+ */
2435
+ export const summarizeSource = {
2436
+ ...summarizeSourceAt1,
2437
+ v2: Object.assign(summarizeSourceAt2.v2, { descriptor: summarizeSourceAt2.descriptor }),
2438
+ };
2439
+ /**
2440
+ * The keywords an entry is proposed to be found by — **without a model**.
2441
+ *
2442
+ * ## The defect it exists for
2443
+ *
2444
+ * The summarizer writes a history entry with `keys: []`. Keyword matching is the
2445
+ * only retrieval mechanism on by shipped default, and a history row carries no
2446
+ * title for `nameMatch` to read either, so a summary a user made *so the model
2447
+ * would remember* cannot be found by anything. Measured on the core corpus:
2448
+ * with no keys, **0 of 12** history entries are reachable by any conversation
2449
+ * about them.
2450
+ *
2451
+ * ## ⚠ Why it is not a Provider, and why that is the whole point
2452
+ *
2453
+ * Every sibling in this section calls a model — `name-entry@1` writes the title,
2454
+ * `extract-cast@1` reads the cast. This one is `core:query`, computes from the
2455
+ * lorebook it already has, and **cannot invent a keyword**: every key it emits
2456
+ * is a substring of the text it was given. A proposal that cannot hallucinate
2457
+ * needs no review for hallucination, only for judgement, which is a far cheaper
2458
+ * review — and it costs no tokens, no connection and no wait.
2459
+ *
2460
+ * ## ⚠ The failure mode it is built against
2461
+ *
2462
+ * **Character names are the worst possible keys for a scene.** They are also
2463
+ * what any extractor finds first, and if every scene's entry is keyed on who was
2464
+ * in it then every one of them fires whenever that person is mentioned. That
2465
+ * replaces *"history entries never fire"* with *"all history entries fire
2466
+ * together"*, which is worse — one entry crowding out the rest, across a whole
2467
+ * lane, in a fixed budget where a wrong entry displaces a right one.
2468
+ *
2469
+ * Measured, on ten messages that name two cast members and nothing else:
2470
+ * **0 of 12** history entries fire, and **11 of 12** with the guards against it
2471
+ * removed. Everything the node does is downstream of that number.
2472
+ *
2473
+ * ⚠ There are two guards, not one, and the measurement needed both removed. A
2474
+ * name in every scene also fails the *statistical* test — it already matches
2475
+ * most of the book — so on a lorebook with entries to count over, either one
2476
+ * holds the line. On a lorebook with two entries in it, only the structural
2477
+ * rule can, and that is the lorebook a user has when they start making
2478
+ * summaries.
2479
+ *
2480
+ * ## What a consumer gets
2481
+ *
2482
+ * `keys` carries each proposal with its evidence — where in the text it occurs,
2483
+ * the sentence around it, how distinctive it is in this lorebook, and how many
2484
+ * other entries it already matches — and `rejected` carries every candidate
2485
+ * turned away with the rule that turned it away. Both exist because this node
2486
+ * **proposes and never writes**: what it emits is meant to reach a person who
2487
+ * can edit it before `core:outlet/create-lore-entry@1` stores anything, and a
2488
+ * reviewer who has to hunt for the reason will approve without reading.
2489
+ *
2490
+ * ⚠ It never proposes **secondary** keys. Those carry a user's `selectiveLogic`
2491
+ * conditions — *"fire on dragon, but not when statue is present"* — which is an
2492
+ * author saying *not here*, and nothing that guesses is entitled to say it.
2493
+ * @internal
2494
+ */
2495
+ export const entryKeys = pin(describeQueryDefinition({
2496
+ id: 'core:query/entry-keys@1',
2497
+ i18n: {
2498
+ name: { en: 'Suggest keywords' },
2499
+ description: {
2500
+ en: 'Proposes the keywords an entry should be found by, taken from its own text. Runs on your machine, calls no model, and can only ever suggest words the text actually contains.',
2501
+ },
2502
+ },
2503
+ /**
2504
+ * Pure computation over rows already in the database — one pass over the
2505
+ * lorebook per candidate word. It reads no network and loads no model, so
2506
+ * the only way it can take long is a very large book.
2507
+ */
2508
+ timeoutMs: 5000,
2509
+ /**
2510
+ * Producing nothing is an ordinary and correct outcome — a passage with
2511
+ * nothing distinctive in it gets no keys rather than the five least
2512
+ * common words it happens to contain — and a suggestion must never be
2513
+ * able to cost somebody their summary. Both are the same `optional`.
2514
+ */
2515
+ optional: true,
2516
+ slots: {
2517
+ params: {
2518
+ kind: 'parameters',
2519
+ facet: 'weights',
2520
+ schema: {
2521
+ /**
2522
+ * ⚠ **A ceiling on firing opportunities, not a display
2523
+ * preference.** Any single key matching admits the entry, so
2524
+ * this is how wide the entry's door is — and the keyword
2525
+ * signal is `matched / keys.length`, so a longer list also
2526
+ * makes the entry *rank* worse for the same single hit.
2527
+ *
2528
+ * Five: a scene is about a place, a thing and an event or
2529
+ * two. Measured at eight, with the ordinary-word cap opened
2530
+ * with it, **six of twelve** history entries fire on
2531
+ * narrative prose naming nothing from any scene — against
2532
+ * one at five — and the shared-name probe stops being clean.
2533
+ * **0 is off**, in the `admitThreshold` convention.
2534
+ *
2535
+ * It is a ceiling and never a target — fewer is the normal
2536
+ * result and none is a valid one.
2537
+ */
2538
+ maxKeys: {
2539
+ type: 'integer',
2540
+ default: 5,
2541
+ min: 0,
2542
+ max: 20,
2543
+ quick: true,
2544
+ label: { en: 'Most keywords suggested' },
2545
+ description: 'A ceiling on how many keywords are proposed for one entry. Each one is another way the entry can be pulled into a prompt, so a short list is usually a better one. 0 suggests none.',
2546
+ },
2547
+ /**
2548
+ * ⚠ **The one calibration a user can actually reason about**,
2549
+ * and the reason the others are not here. How rare a word has
2550
+ * to be, how short it may be, how much of a name to keep —
2551
+ * those are measurements, not preferences, and a settings
2552
+ * panel cannot perform them.
2553
+ *
2554
+ * This one is a preference, because it trades two things a
2555
+ * user can feel: an ordinary word like "watch" or "left" is
2556
+ * how an entry gets found when it names nothing proper, and
2557
+ * it is also how an entry starts firing on any scene at all.
2558
+ * Two ordinary words of five; 0 restricts suggestions to
2559
+ * names and places, which measured cleanest and left two of
2560
+ * twelve summaries with no keys at all.
2561
+ */
2562
+ maxOrdinaryWords: {
2563
+ type: 'integer',
2564
+ default: 2,
2565
+ min: 0,
2566
+ max: 20,
2567
+ label: { en: 'Ordinary words allowed' },
2568
+ description: 'How many of the suggestions may be everyday words rather than names of people, places or things. Names are far less likely to pull the entry into an unrelated scene; 0 suggests names only.',
2569
+ },
2570
+ },
2571
+ },
2572
+ },
2573
+ ports: {
2574
+ in: {
2575
+ /** The lorebook and the cast — what distinctiveness is measured against. */
2576
+ scope: S.sessionScope,
2577
+ /**
2578
+ * The passage keys are proposed for.
2579
+ *
2580
+ * `content`, matching `name-entry@1`, so both proposal steps take
2581
+ * the drafted summary off the same out-port under the same name.
2582
+ */
2583
+ content: S.text,
2584
+ },
2585
+ out: {
2586
+ main: S.json,
2587
+ /** The proposals, each with the evidence for it. */
2588
+ keys: S.json,
2589
+ /** Every candidate turned away, and the rule that turned it away. */
2590
+ rejected: S.json,
2591
+ },
2592
+ },
2593
+ }));
2594
+ // ── Graph build ─────────────────────────────────────────────────────────────
2595
+ //
2596
+ // Five LLM steps, each already independently configurable in
2597
+ // `graph_build_configs` as a `<step>_system_prompt` / `<step>_connection_id` /
2598
+ // `<step>_sampling_config_id` triple. Five Providers is the same statement with
2599
+ // the enumeration removed.
2600
+ /** @internal */
2601
+ export const graphScenes = pin(describeQueryDefinition({
2602
+ id: 'core:query/graph-scenes@1',
2603
+ i18n: { name: { en: 'Scenes to build from' } },
2604
+ timeoutMs: 5000,
2605
+ ports: {
2606
+ in: { scope: S.sessionScope },
2607
+ out: { main: S.graphScenes, scenes: S.graphScenes },
2608
+ },
2609
+ }));
2610
+ // ── Stats and states ────────────────────────────────────────────────────────
2611
+ //
2612
+ // A stat is declared once (`defineAttributeSlot`, SDK attributes.ts), attached where it
2613
+ // is true by default, and valued where play happens. These two nodes are the
2614
+ // pipeline's whole share of that: one reads the resolved state, one writes it.
2615
+ // Everything about *what* a slot is lives in the SDK registry, so neither node
2616
+ // carries a vocabulary that could drift from the one the app validates against.
2617
+ /**
2618
+ * The session's stats and states, resolved — an inventory is one, the
2619
+ * `inventory` list stat (phase 3b retired possessions as edges).
2620
+ *
2621
+ * `{ world, cast, slots, who, version }` — the same object `stateFor(sessionId)`
2622
+ * returns and the shape `state` on `core:task/build-template-context@1` takes.
2623
+ * Every value is already resolved down session → lorebook → card →
2624
+ * declaration default, with absence meaning **inherit** rather than zero, and
2625
+ * derived slots computed rather than read.
2626
+ *
2627
+ * A Query, and a plain one: what it is is a read. There is no as-of parameter
2628
+ * — this is the `current` view, and the temporal registry that would give the
2629
+ * other one is not built (see docs/stats-and-states.md).
2630
+ *
2631
+ * `version` is the session's **state version**: a counter every applied change moves, in turn order,
2632
+ * under a lock. A run that reads state here and later asks to change it
2633
+ * hands the version back as `base` on `resolve-state-changes@1` /
2634
+ * `set-state@1`, so a change proposed against a state that has since moved
2635
+ * is rebased or superseded rather than applied blind. The same number rides
2636
+ * the resolved document as `state.version`, where an enabled-when can name it.
2637
+ * @experimental
2638
+ */
2639
+ export const sessionState = pin(describeQueryDefinition({
2640
+ id: 'core:query/session-state@1',
2641
+ i18n: { name: { en: 'Session state' } },
2642
+ timeoutMs: 2000,
2643
+ ports: {
2644
+ in: { scope: S.sessionScope },
2645
+ out: { main: S.json, state: S.json, version: S.json },
2646
+ },
2647
+ }));
2648
+ /**
2649
+ * 🚧 How many of an item are held, and how many are left (attributes phase 3a,
2650
+ * 2026-09-26).
2651
+ *
2652
+ * An item is a `core:entry/item@1` lore entry whose **supply** is unique,
2653
+ * limited to N, or unlimited; a holder's **held count** rides the list item
2654
+ * that references it (`{ entryId, count }`) in any list slot the session
2655
+ * tracks — usually `inventory`. This answers, per entry asked about:
2656
+ * `{ entryId, name, supply, limit, held, remaining, holders }` —
2657
+ * `held` = Σ count across the session's owners (the world and every cast
2658
+ * member), `remaining` = limit − held, never below zero, and `null` for an
2659
+ * unlimited supply.
2660
+ *
2661
+ * ⚠ **It answers; it never enforces.** The owner ruled that supply is enforced
2662
+ * by genre pipelines: a pipeline that hands out the last key reads this first
2663
+ * and decides what a zero means (refuse, swap, narrate a shortage). The host
2664
+ * writes whatever the gate accepts.
2665
+ *
2666
+ * `entryIds` optional: with none it answers for every item entry in the
2667
+ * session's lorebook. An entry outside that lorebook is not answered for — the
2668
+ * scoping refusal, as for every Query.
2669
+ * @experimental
2670
+ */
2671
+ export const itemSupply = pin(describeQueryDefinition({
2672
+ id: 'core:query/item-supply@1',
2673
+ i18n: { name: { en: 'Item supply' } },
2674
+ timeoutMs: 2000,
2675
+ ports: {
2676
+ in: { scope: S.sessionScope, entryIds: S.json },
2677
+ out: { main: S.json, supply: S.json },
2678
+ },
2679
+ }));
2680
+ /**
2681
+ * 🚧 The stats a **lorebook** holds — for its world, each cast member and each
2682
+ * place — as durable values (owner-confirmed 2026-09-27: "Pipelines should be
2683
+ * allowed to query stats from the lorebook as well").
2684
+ *
2685
+ * ## The book's layer, and no session needed
2686
+ *
2687
+ * What write-back recorded onto the book's timeline, plus what an author set
2688
+ * on the lorebook, a cast member or a place: the row in force per owner and
2689
+ * slot, the same one a new session played in the book would inherit. Nothing
2690
+ * falls through to a card or a declaration default — a slot the book never
2691
+ * valued is an absent key, not the default — and no session is read, so a
2692
+ * pipeline with no session in play (a run the scope grants the book to) can
2693
+ * read it.
2694
+ *
2695
+ * `{ lorebookId, branchId, slots, world, cast, locations }`, keyed like
2696
+ * `session-state@1`'s document: `world.hp`; `cast.byId[castMemberId]` and
2697
+ * `cast[slug]` over one set of objects, each carrying `id` (the **cast
2698
+ * member's** id — `lorebook_bindings.id`, never the card's), `key` and `name`;
2699
+ * `locations` the same by location entry id. `branchId` is the line read
2700
+ * (null is main).
2701
+ *
2702
+ * ## Only what the book tracks
2703
+ *
2704
+ * A lorebook has no genre, so its vocabulary is phase 1's **world
2705
+ * attributes**: the sheets on the lorebook, its cast members and its places,
2706
+ * plus every declared, pickable slot the book holds a durable value for. It
2707
+ * fails closed: an undeclared slot, or one a mechanism keeps, is never read.
2708
+ *
2709
+ * ## Where on the book
2710
+ *
2711
+ * By default: the scope session's own line and moment when the book is that
2712
+ * session's; otherwise the book's **most recently used** line (the line of
2713
+ * the session played most recently) at the **head** of its timeline. On a
2714
+ * branch, main's dated values count only up to the fork date. The document
2715
+ * says where it read: `branchId`, `moment` (null = head), `forkedAt` — where
2716
+ * main was cut, which on a fork of a fork is the EARLIEST fork date along the
2717
+ * parent chain, not the branch's own (null = no cut).
2718
+ *
2719
+ * 🚧 A custom reading, all optional: `branch` — `'main'`, `'mostRecent'`,
2720
+ * `'session'` or a branch id of this book; `at` — `'head'` or a story date
2721
+ * `{ year, month?, day? }`, keeping only values dated on or before it;
2722
+ * `forkCut: false` — let all of main through on a branch. A branch of
2723
+ * another book is refused like the book.
2724
+ *
2725
+ * ## Scope
2726
+ *
2727
+ * The scope session's own lorebook by default. `lorebookId` may name that
2728
+ * book, or one the run's scope grants; any other is **refused** with a
2729
+ * sentence, never read as empty — and so is an owner filter naming a cast
2730
+ * member or place of another book.
2731
+ * @experimental
2732
+ */
2733
+ export const lorebookState = pin(describeQueryDefinition({
2734
+ id: 'core:query/lorebook-state@1',
2735
+ i18n: {
2736
+ name: { en: 'Lorebook state' },
2737
+ description: {
2738
+ en: 'Reads the stats a lorebook holds for its world, its cast members and its places — what earlier sessions recorded and what the author set. No session is needed.',
2739
+ },
2740
+ },
2741
+ timeoutMs: 2000,
2742
+ slots: {
2743
+ params: {
2744
+ kind: 'parameters',
2745
+ schema: {
2746
+ /**
2747
+ * Which stats to read, by full id (`core:slot/hp@1`) or
2748
+ * local name (`hp`). Empty or absent reads every stat the
2749
+ * book tracks; a name it does not track reads nothing.
2750
+ */
2751
+ slotIds: {
2752
+ type: 'list',
2753
+ item: { type: 'text' },
2754
+ label: { en: 'Only these stats' },
2755
+ description: 'Which stats to read, by name. Leave it empty for every stat the lorebook tracks.',
2756
+ },
2757
+ },
2758
+ },
2759
+ },
2760
+ ports: {
2761
+ in: {
2762
+ /** Which session's lorebook, when `lorebookId` does not say. Optional. */
2763
+ scope: S.sessionScope,
2764
+ /** A lorebook id: the scope session's own, or one the run's scope grants. Optional. */
2765
+ lorebookId: S.json,
2766
+ /**
2767
+ * One owner: `"world"`, `{ kind: 'cast_member', id }` or
2768
+ * `{ kind: 'location', id }` (the session kinds `session`,
2769
+ * `session_cast`, `session_location` are translated). Optional.
2770
+ */
2771
+ owner: S.json,
2772
+ /** 🚧 `'main'`, `'mostRecent'`, `'session'` or a branch id of this book. Optional. */
2773
+ branch: S.json,
2774
+ /** 🚧 `'head'` or a story date `{ year, month?, day? }`. Optional. */
2775
+ at: S.json,
2776
+ /** 🚧 `false` lets all of main through on a branch. Optional. */
2777
+ forkCut: S.json,
2778
+ },
2779
+ out: { main: S.json, state: S.json },
2780
+ },
2781
+ }));
2782
+ /**
2783
+ * 🚧 The **stat trail**: one stat's values over time, for one owner — the
2784
+ * world, a cast member or a place (owner-confirmed 2026-09-27: "stats over
2785
+ * time / over cast progression"). Its document is on `trail` (and `main`).
2786
+ *
2787
+ * ## Two clocks
2788
+ *
2789
+ * - `messages` — the scope session's own changes, in message order. A swiped
2790
+ * or regenerated reply's changes are gone (the swipe retracts them), and a
2791
+ * branched session holds its own copies, so neither leaks in.
2792
+ * - `timeline` — what the lorebook recorded across every session, ordered by
2793
+ * the date of the history entry each hangs from (the one story-date
2794
+ * comparator). An undated value — an author's, or one recorded before any
2795
+ * capture — sorts first.
2796
+ * - `both` (default) — the timeline, then the session's messages: the session
2797
+ * is played at the book's present. A timeline value this session itself
2798
+ * recorded is dropped here, since it is already one of its points.
2799
+ *
2800
+ * Each point: `{ value, layer: 'session' | 'timeline', anchor, provenance }` —
2801
+ * `anchor` is `{ messageId }` or `{ historyEntryId, date }`; `provenance` is
2802
+ * `{ updatedBy, sessionId, messageId, sceneId, note, createdAt }` (who wrote
2803
+ * it: `user`, `run:<id>`, or `session:<id>` for write-back). The document is
2804
+ * `{ lorebookId, sessionId, branchId, owner, slotId, mode, tracked, points }`;
2805
+ * `tracked: false` with no points when neither the book nor the session tracks
2806
+ * the slot (fails closed).
2807
+ *
2808
+ * ## Limits
2809
+ *
2810
+ * `last` keeps the newest N points after every other cut. `since` is
2811
+ * `{ messageId?, date? }`: `messageId` keeps session points AFTER that
2812
+ * message (and drops the timeline in `both`, which precedes it); `date` keeps
2813
+ * timeline points dated ON or after it (a date is a period).
2814
+ *
2815
+ * ## Where on the book
2816
+ *
2817
+ * The timeline stands where `lorebook-state@1` does, with the same optional
2818
+ * `branch`, `at` and `forkCut` ports: on a branch, main's values after the
2819
+ * fork date are not points; at a date, nothing dated after it is. The
2820
+ * session's own messages are its own and are not cut. The document adds
2821
+ * `moment` and `forkedAt` (the effective cut, as in `lorebook-state@1`).
2822
+ *
2823
+ * Scoped like `lorebook-state@1`: the scope session's lorebook, or one the
2824
+ * run's scope grants; any other, or an owner of another book, is refused.
2825
+ * @experimental
2826
+ */
2827
+ export const statTrail = pin(describeQueryDefinition({
2828
+ id: 'core:query/stat-trail@1',
2829
+ i18n: {
2830
+ name: { en: 'Stat trail' },
2831
+ description: {
2832
+ en: 'Lists one stat’s values over time for the world, a cast member or a place — by message in this session, across sessions by story date, or both.',
2833
+ },
2834
+ },
2835
+ timeoutMs: 2000,
2836
+ slots: {
2837
+ params: {
2838
+ kind: 'parameters',
2839
+ schema: {
2840
+ /** The stat, by full id or local name. */
2841
+ slotId: {
2842
+ type: 'text',
2843
+ quick: true,
2844
+ label: { en: 'Stat' },
2845
+ description: 'Which stat to follow, by name — for example hp.',
2846
+ },
2847
+ mode: {
2848
+ type: 'enum',
2849
+ of: ['both', 'messages', 'timeline'],
2850
+ members: [
2851
+ {
2852
+ key: 'both',
2853
+ label: { en: 'Both' },
2854
+ description: { en: 'Across sessions, then this session.' },
2855
+ },
2856
+ {
2857
+ key: 'messages',
2858
+ label: { en: 'This session' },
2859
+ description: { en: 'This session, message by message.' },
2860
+ },
2861
+ {
2862
+ key: 'timeline',
2863
+ label: { en: 'Across sessions' },
2864
+ description: {
2865
+ en: 'What the lorebook recorded across sessions, by story date.',
2866
+ },
2867
+ },
2868
+ ],
2869
+ default: 'both',
2870
+ quick: true,
2871
+ label: { en: 'Which trail' },
2872
+ description: 'This session message by message, what the lorebook recorded across sessions by story date, or both.',
2873
+ },
2874
+ last: {
2875
+ type: 'integer',
2876
+ default: 50,
2877
+ min: 1,
2878
+ max: 1000,
2879
+ label: { en: 'Most changes listed' },
2880
+ description: 'Keep only the most recent changes, up to this many.',
2881
+ },
2882
+ },
2883
+ },
2884
+ },
2885
+ ports: {
2886
+ in: {
2887
+ scope: S.sessionScope,
2888
+ /** A lorebook id: the scope session's own, or one the run's scope grants. Optional. */
2889
+ lorebookId: S.json,
2890
+ /** `"world"` (default), `{ kind: 'cast_member', id }` or `{ kind: 'location', id }`. */
2891
+ owner: S.json,
2892
+ /** `{ messageId?, date?: { year, month?, day? } }`. Optional. */
2893
+ since: S.json,
2894
+ /** 🚧 `'main'`, `'mostRecent'`, `'session'` or a branch id of this book. Optional. */
2895
+ branch: S.json,
2896
+ /** 🚧 `'head'` or a story date `{ year, month?, day? }`. Optional. */
2897
+ at: S.json,
2898
+ /** 🚧 `false` lets all of main through on a branch. Optional. */
2899
+ forkCut: S.json,
2900
+ },
2901
+ out: { main: S.json, trail: S.json, points: S.json },
2902
+ },
2903
+ }));
2904
+ /**
2905
+ * Change state — or ask to.
2906
+ *
2907
+ * ## Why `propose` is the default
2908
+ *
2909
+ * The three writers do not have equal authority.
2910
+ * A person editing a bar is authoritative; a genre's own script rolling damage
2911
+ * is authoritative because the genre author wrote the arithmetic; a **model**
2912
+ * is neither, and a model that could set a number silently is a model that can
2913
+ * rewrite the fiction between two messages with no receipt a player can
2914
+ * refuse. Defaulting to `propose` means a spec that wires a model's output
2915
+ * straight into this node produces a pending line with Accept / Reject, and a
2916
+ * genre that wants the other behaviour says so in one parameter.
2917
+ *
2918
+ * ## Why it is a Task
2919
+ *
2920
+ * It writes, which a Task is not otherwise supposed to do, and the alternative
2921
+ * is worse: the one-live-row rule allows a spec **one** write-class Consumer and that one is the
2922
+ * message. A damage roll that also saves a reply would be unspecifiable. What
2923
+ * makes it defensible rather than a hole is that these rows are not the run's
2924
+ * primary artifact — every one of them is anchored to a message and retracted
2925
+ * with it, so a rejected turn takes its state changes with it.
2926
+ *
2927
+ * `changes` is one ordered list of `{ owner, slotId, value }` — or, for a
2928
+ * list slot, `{ owner, slotId, op: 'add' | 'remove', items }`. An item
2929
+ * changing hands is exactly that on the owner's `inventory` stat (phase 3b
2930
+ * retired the `{ owner, entryId, delta }` possession edge; the model-facing
2931
+ * item line survives on `resolve-state-changes@1`, which turns it into this). One
2932
+ * port because one turn's changes are one ordered list, and splitting them
2933
+ * would let a spec apply half of them.
2934
+ *
2935
+ * 🚧 A **clock line** `{ kind: 'clock', by, unit }` (live scenes §6, ★3) is
2936
+ * the state-keeper asking to move the session's story clock forward. `propose`
2937
+ * holds it as a **clock proposal** (`state_proposals.kind` `clock`), whose
2938
+ * Accept advances the clock; `apply` passes it over — neither applied nor
2939
+ * refused — because a moved clock is announced through a host seam a task does
2940
+ * not have: a spec that applies the keeper's clock wires *Advance story clock*
2941
+ * from `resolve-state-changes@1`'s `clock` out-port (Adventure's trusted arm).
2942
+ */
2943
+ /**
2944
+ * Changes a model NAMED, turned into changes `set-state` can write.
2945
+ *
2946
+ * ## A Query, because resolving a name is a READ
2947
+ *
2948
+ * "Verity" becomes a cast row by looking her up in this session's cast, which
2949
+ * is a read of the host and therefore a Query's job — a Task is handed no
2950
+ * services. That also buys the scoping refusal for free: the cast it
2951
+ * matches against is the cast of the session on the `scope` port and no other.
2952
+ *
2953
+ * ## Why this is a node and not a leniency inside `set-state`
2954
+ *
2955
+ * `core:task/set-state@1` takes an owner as `{ kind, id }` — a row, resolved,
2956
+ * unambiguous. A model has no row ids: it has the names the transcript gave it
2957
+ * ("Verity", "the world") and the local name of a stat ("hp"). Something has to
2958
+ * resolve one into the other, and the two candidates were this node or a
2959
+ * widened `set-state`.
2960
+ *
2961
+ * It is this node, because the two callers are genuinely different. A genre's
2962
+ * own script that rolled damage knows which cast row it hit and must not have
2963
+ * its exact owner re-guessed by a fuzzy name match; a model's proposal has
2964
+ * nothing else to offer. Widening `set-state` would make every writer pay for
2965
+ * the model's ambiguity, and would move a resolution failure inside the node
2966
+ * that writes — where it can only be a refusal, never a line on the receipt.
2967
+ *
2968
+ * The same resolution the three state tools do (`set_state`, `give_item`,
2969
+ * `take_item`), reached from a structured block instead of from a tool call.
2970
+ * An item line (`{ owner, entryId, delta }`) resolves to an `add` / `remove`
2971
+ * with a held count on the owner's `inventory` stat, refused as a sentence
2972
+ * when the session does not track inventory (phase 3b).
2973
+ *
2974
+ * ## A name it cannot resolve is a RESULT, not a halt
2975
+ *
2976
+ * A keeper that named five changes and got one character's name wrong should
2977
+ * land four proposals and a sentence about the fifth. `refused` carries those
2978
+ * sentences so the receipt can show them; `changes` carries what resolved.
2979
+ * Halting the turn over one bad name would lose the other four, which is the
2980
+ * same argument `set-state`'s own per-change refusal makes.
2981
+ * @experimental
2982
+ */
2983
+ export const resolveStateChanges = pin(describeQueryDefinition({
2984
+ id: 'core:query/resolve-state-changes@1',
2985
+ i18n: { name: { en: 'Resolve state changes' } },
2986
+ timeoutMs: 5000,
2987
+ ports: {
2988
+ in: {
2989
+ /**
2990
+ * `[{ owner, slot, value } | { owner, entryId, delta }]` as a
2991
+ * model writes them: `owner` is a name from the conversation or
2992
+ * `world`, `slot` is a stat's local name (`hp`) or its full id,
2993
+ * and an item line moves `delta` of a lore entry into (+) or
2994
+ * out of (−) the owner's inventory.
2995
+ */
2996
+ changes: S.json,
2997
+ /**
2998
+ * Who a change that names no `owner` is for, as participant
2999
+ * references (2026-09-28): each such change
3000
+ * is made once per reference, the same slot and value on each —
3001
+ * the Lair's Whisper writes its one line on every recipient the
3002
+ * press collected (`core:inlet/user-message@1.recipients`). A
3003
+ * `character:<id>` resolves to that seated cast member; any
3004
+ * other reference, or a character this session does not seat,
3005
+ * is a sentence on `refused`. A change that names its own
3006
+ * `owner` keeps it. Optional: unwired, an owner-less change is
3007
+ * the world's, as before.
3008
+ */
3009
+ owners: S.participantRefs,
3010
+ /**
3011
+ * 🚧 **Whose stats this keeper keeps** (stat ownership, owner
3012
+ * ruling 2026-09-30): `'world'` — the world and its places, so
3013
+ * a change naming a cast member is refused; or one participant
3014
+ * reference (`character:<id>`) — that member alone, so a change
3015
+ * to the world, a place or anybody else is refused. Either may
3016
+ * also be a party speaker (`{ characterId }`, or `{ name }` as a
3017
+ * plan writes it, resolved like a change's `owner`), and a list
3018
+ * keeps every item it holds, read flat — an absent item keeps
3019
+ * nobody more. Each refusal is a sentence on `refused`. Unwired,
3020
+ * any owner may be named, as before. The Lair's Castellan keeper
3021
+ * wires `'world'` and the delvers it voiced this turn; each
3022
+ * character turn's keeper wires its own speaker.
3023
+ */
3024
+ keeps: S.json,
3025
+ /** Which session's cast the names are resolved against. */
3026
+ scope: S.sessionScope,
3027
+ /**
3028
+ * The planner's document, whose `worldHints` are a second,
3029
+ * smaller set of named changes: where this turn happens, the
3030
+ * time of day and the weather.
3031
+ *
3032
+ * Its own port rather than more entries on `changes`, because
3033
+ * a reference is `{node, port}` with no sub-path — a spec
3034
+ * cannot join one node's list to another node's object on one
3035
+ * port, and the two are written by different agents answering
3036
+ * different questions. A hint that repeats what the world
3037
+ * already says proposes nothing, which is what makes "repeat
3038
+ * the state when this turn changes none of it" safe to ask of
3039
+ * the planner.
3040
+ */
3041
+ plan: S.json,
3042
+ /**
3043
+ * 🚧 **A clock proposal** (live scenes §6, ★3, 2026-10-13): the
3044
+ * keeper's answer, whose `clock` list (`[{ by, unit }]`, empty
3045
+ * on the ordinary turn) is how much story time the scene took.
3046
+ * The whole answer for `plan`'s reason — a reference has no
3047
+ * sub-path — and a bare `{ by, unit }` reads the same. The
3048
+ * first entry resolves onto `changes` as `{ kind: 'clock', by,
3049
+ * unit }` (what `set-state` proposes) and onto the `clock`
3050
+ * out-port; forward only — a whole `by` above zero, within
3051
+ * `CLOCK_STEP_MAX`, in one of `STORY_TIME_UNITS` — and only
3052
+ * when the session's clock could move by it. Anything else is
3053
+ * a sentence on `refused`. 🚧 A well-formed ask the story
3054
+ * cannot take (no clock yet, a date the calendar cannot place)
3055
+ * also rides `changes` as `{ kind: 'clock', by, unit, skipped
3056
+ * }`, `skipped` saying why, for `set-state` to write to the
3057
+ * ledger (live scenes §15 G16) — never onto `clock`.
3058
+ * Optional: unwired, no clock move.
3059
+ * ⚠ Not the planner's `timeOfDay` hint, which is a world stat.
3060
+ */
3061
+ clock: S.json,
3062
+ /**
3063
+ * The **state version** this turn read: the session-state
3064
+ * query's `version`. Passed through onto every resolved change
3065
+ * as `base`, so `set-state` can tell a delta against the state
3066
+ * the model saw from one against a state that has since moved.
3067
+ * Optional: a spec that wires none proposes against whatever
3068
+ * is current at the write.
3069
+ */
3070
+ base: S.json,
3071
+ /**
3072
+ * 🚧 `core:query/item-supply@1`'s answer (phase 3b). Optional,
3073
+ * and the only way supply is ever checked: core never enforces
3074
+ * it (owner ruling 2026-09-25), so a genre that wants a unique
3075
+ * item to stay unique wires this, and an item line granting
3076
+ * more than is left lands on `refused` as a sentence. A take
3077
+ * frees what that owner held before the turn's gives are
3078
+ * counted.
3079
+ */
3080
+ supply: S.json,
3081
+ },
3082
+ out: {
3083
+ main: S.json,
3084
+ /** Ready for `core:task/set-state@1`'s `changes` port — each carrying `base` when one was wired. */
3085
+ changes: S.json,
3086
+ /** One sentence per change that named something not here. */
3087
+ refused: S.json,
3088
+ /**
3089
+ * 🚧 The clock move the `clock` port resolved, `{ by, unit }` —
3090
+ * absent when there is none. What `core:task/clock-step@1`'s
3091
+ * `step` takes, so a spec that applies the keeper's clock
3092
+ * (Trust the narrator) moves it through *Advance story
3093
+ * clock*; the same move rides `changes` for `propose`.
3094
+ */
3095
+ clock: S.json,
3096
+ },
3097
+ },
3098
+ }));
3099
+ // ── core:query/lorebook-entries@1 ───────────────────────────────── begin ────
3100
+ // Appended as a delimited block rather than placed beside the four lore
3101
+ // definitions above (≈ line 930–1345), because another session is editing this
3102
+ // file. It belongs after `historyEntries`; move it there once that lands.
3103
+ /**
3104
+ * The session's attached lorebook, **listed** — every entry, or the one with a
3105
+ * given name.
3106
+ *
3107
+ * ## Not a retrieval, and that is the whole point
3108
+ *
3109
+ * The four entries-shaped definitions above — `lorebook-triggers@1`,
3110
+ * `world-lore@1`, `character-lore@1`, `history-entries@1` — are one keyword
3111
+ * scan over the conversation, and an entry reaches a prompt through them only
3112
+ * by matching a key, by clearing `admitThreshold` on other evidence, or by
3113
+ * declaring itself `constant`. That is right for a reply and it is no use at
3114
+ * all to a genre that needs to see the book: on a **create** run there is no
3115
+ * conversation to scan, so the window is empty and only always-on entries are
3116
+ * admitted — and a genre asking *is there a room called the Cellar?*, *pick one
3117
+ * of these as the secret*, or *who are the suspects?* had no door at all.
3118
+ *
3119
+ * This is that door, and it is deliberately dull: **no mechanism runs, nothing
3120
+ * is scored, nothing is ranked.** `main` and `entries` carry one bare list of
3121
+ * rows — a **listing**, never `core:shape/context-candidates@1` — so there is
3122
+ * no order of merit in it for a reader to mistake for one. A spec that wants
3123
+ * the book ranked concatenates it into the ranker like any other source; this
3124
+ * node will not do it for them.
3125
+ *
3126
+ * ## The rows are retrieval's rows
3127
+ *
3128
+ * Same fields, from the same host read and the same `toLoreEntry` projection
3129
+ * the four definitions above publish on each candidate's `payload` — `id`,
3130
+ * `source`, `name`, `content`, `keys`, `constant`, `enabled`, `position`,
3131
+ * `priority`, the matcher set, `bindingCharacterId`,
3132
+ * `fingerprint`, and history's `year` / `month` / `day`. That is the contract
3133
+ * worth having: a task written against a retrieved entry reads a listed one
3134
+ * without a second shape to learn, and there is no second projection to keep in
3135
+ * step (the vocabularies are reconciled at the host's read, not merged).
3136
+ * The one addition is asked for: `withLinks` puts each row's lore links on it
3137
+ * as `links` (`LoreLinkRow[]`), said from that row.
3138
+ *
3139
+ * ## What it will not hand over
3140
+ *
3141
+ * · **Another session's lorebook.** `scope` decides which session, and a
3142
+ * `sessionId` that disagrees with the run's is refused with a sentence
3143
+ * (`assertScoped`), never filtered down to an empty list.
3144
+ * · **Disabled or archived entries.** `enabled: false` is a switch the author
3145
+ * left off and `archived` is the column whose stated meaning is *don't
3146
+ * retrieve it and don't show it to me*; a listing that offered either would
3147
+ * make a switched-off room exist and a shelved suspect answer for a crime.
3148
+ * Both are filtered at the read. (The scan above still *sees* disabled rows,
3149
+ * on purpose — it reports them on `skipped` so a person can be told why their
3150
+ * lore did not come in. Nothing here changes that.)
3151
+ * · **Character lore that is private from the current speaker.** The read
3152
+ * applies the same binding-visibility policy the four definitions above run
3153
+ * under, so this is not a way around it. In the case this node exists for —
3154
+ * a create run, an oracle, anything narrator-shaped — `currentCharacterId` is
3155
+ * null, the policy is omniscient, and the whole book comes back.
3156
+ *
3157
+ * ## No `optional`
3158
+ *
3159
+ * Absent, so a failure is the run's failure. A genre that picked its secret
3160
+ * from this list cannot be handed an empty one and carry on: `optional: true`
3161
+ * turns an error into an empty `ok`, and an empty book and a book that failed
3162
+ * to load are the same value to every reader downstream. It is also not a node
3163
+ * a person should be able to switch off — a Twenty Questions pipeline without
3164
+ * it has nothing to play with.
3165
+ * @experimental
3166
+ */
3167
+ export const lorebookEntries = pin(describeQueryDefinition({
3168
+ id: 'core:query/lorebook-entries@1',
3169
+ i18n: {
3170
+ name: { en: 'Lorebook entries' },
3171
+ description: {
3172
+ en: 'Lists the entries of the session’s lorebook — all of them, or the one with a given name. Retrieval is not involved: nothing is matched against the conversation, nothing is scored and nothing is ranked.',
3173
+ },
3174
+ },
3175
+ /**
3176
+ * The lore definitions' number. One indexed read of one book plus the
3177
+ * bindings it hydrates, which is the same work their shared scan pays
3178
+ * for before it scans anything.
3179
+ */
3180
+ timeoutMs: 2000,
3181
+ slots: {
3182
+ params: {
3183
+ kind: 'parameters',
3184
+ schema: {
3185
+ /**
3186
+ * Which entry types to list — `core:entry/world-lore`,
3187
+ * `core:entry/character-lore`, `core:entry/history`, or a
3188
+ * plugin's own. Bare ids, no `@version`: the version is a
3189
+ * separate column and a type's rows are its rows across
3190
+ * versions.
3191
+ *
3192
+ * A `list` of `text` rather than an `enum` of the three
3193
+ * core ids, because the set is open — an install with a
3194
+ * plugin entry type has more of them, and an enum frozen
3195
+ * into this definition's content hash could not grow
3196
+ * without a re-projection. An id no type declares matches
3197
+ * nothing, which is the honest answer to a typo.
3198
+ *
3199
+ * Empty or absent lists every entry type.
3200
+ *
3201
+ * Named `entryTypes` rather than `types`: *type* alone
3202
+ * is the word four other vocabularies use — a node type, a
3203
+ * session type, a part type — and a parameter may not take
3204
+ * the bare noun.
3205
+ */
3206
+ entryTypes: {
3207
+ type: 'list',
3208
+ item: { type: 'text' },
3209
+ label: { en: 'Entry types listed' },
3210
+ description: 'Which kinds of entry to list, by type id — world lore, character lore, history, or a type an extension declares. Leave it empty for all of them.',
3211
+ },
3212
+ /**
3213
+ * The *does it exist* case: one exact name, matched
3214
+ * case-insensitively with surrounding whitespace trimmed
3215
+ * on both sides.
3216
+ *
3217
+ * Exact and never a substring or a pattern. A genre asking
3218
+ * "is there a room called the Cellar?" needs *yes* or *no*,
3219
+ * and a match that also returned "Cellar Door" and "The
3220
+ * Wine Cellars" would answer a question nobody asked — the
3221
+ * search-shaped reading of this node is the keyword scan
3222
+ * above, which already exists and is better at it.
3223
+ *
3224
+ * History entries have no name at all (the type declares no
3225
+ * title role), so naming one lists nothing.
3226
+ *
3227
+ * Absent lists every entry of the chosen types.
3228
+ */
3229
+ name: {
3230
+ type: 'text',
3231
+ quick: true,
3232
+ label: { en: 'Only the entry named' },
3233
+ description: 'List only the entry with exactly this name, ignoring capitalisation and surrounding spaces. Leave it empty to list them all.',
3234
+ },
3235
+ /**
3236
+ * A ceiling on rows read, not a page: there is no offset
3237
+ * and no cursor, so raising it is the only way to see more.
3238
+ *
3239
+ * 500 is a large lorebook and 2000 is a ceiling on the
3240
+ * ceiling — this list is usually on its way into a prompt,
3241
+ * and a book that would not fit in a context window is not
3242
+ * made to fit by asking for all of it. The cap is enforced
3243
+ * at the read as well as declared here; a node's parameter
3244
+ * is a control, never a promise the host takes on trust.
3245
+ */
3246
+ limit: {
3247
+ type: 'integer',
3248
+ default: 500,
3249
+ min: 1,
3250
+ max: 2000,
3251
+ label: { en: 'Most entries listed' },
3252
+ description: 'A ceiling on how many entries are listed. When there are more, the newest are listed. There is no second page — raising this is the only way to see more.',
3253
+ },
3254
+ /**
3255
+ * Each row's **lore links**, on the row as `links`
3256
+ * (`LoreLinkRow[]`) — 2026-09-29. Drizzle's
3257
+ * `with: { … }` in spirit: the listing stays a listing, and a
3258
+ * reader that wants a room's ways out says so.
3259
+ *
3260
+ * Each link is said **from the listed entry** — its wording
3261
+ * from here, the far end named — and only a link that is a
3262
+ * way out of here is listed: between two entries, standing
3263
+ * (active, not secret) on the session's line at its moment,
3264
+ * both ends live, and never one drawn *into* here with no
3265
+ * wording back (one way, inbound). The far end passes the
3266
+ * visibility gate for the WIRED `speaker`; with none wired,
3267
+ * a far end the listing does not itself carry is named only
3268
+ * when every voice may see it — an unwired listing may be
3269
+ * read once and shared by every voice in a turn (the Lair's
3270
+ * rooms). Never a way round the gate.
3271
+ *
3272
+ * Off by default: a row read without it carries no `links`
3273
+ * at all, so every spec written before it reads exactly what
3274
+ * it did.
3275
+ */
3276
+ withLinks: {
3277
+ type: 'boolean',
3278
+ default: false,
3279
+ label: { en: 'With each entry’s links' },
3280
+ description: 'Also list, on each entry, the links that lead from it to other entries — a room’s ways out, what it is inside — each said from that entry.',
3281
+ },
3282
+ },
3283
+ },
3284
+ },
3285
+ ports: {
3286
+ /**
3287
+ * Which session's lorebook, and — through `currentCharacterId` —
3288
+ * who is speaking, which is what the binding-visibility policy
3289
+ * reads. No `text` in-port: there is nothing here to match text
3290
+ * against.
3291
+ */
3292
+ in: { scope: S.sessionScope },
3293
+ /**
3294
+ * One bare list of rows on both ports, `main` for a spec that
3295
+ * wires the node's output and `entries` for one that names what it
3296
+ * is reading. Same value, same order — world lore, then character
3297
+ * lore, then history, each by row id.
3298
+ *
3299
+ * ⚠ `S.json` and deliberately **not** `S.candidates`. A candidate
3300
+ * is something a mechanism proposed, carrying signals a ranker
3301
+ * reads; these rows were proposed by nothing and carry no signals,
3302
+ * and publishing them as candidates would let a spec wire a
3303
+ * whole lorebook into `select` as if a scan had found it.
3304
+ */
3305
+ out: { main: S.json, entries: S.json },
3306
+ },
3307
+ }));
3308
+ // ── core:query/lorebook-entries@1 ───────────────────────────────── end ──────
3309
+ // ── core:query/likeness-images@1 (DESIGN-image-generation §5, §6.4) ──────────
3310
+ /**
3311
+ * 🚧 The **likeness images** of everyone on stage, as one media list — the
3312
+ * Scene action's references.
3313
+ *
3314
+ * Stage order: the switched-on cast in seat order, then the personas in
3315
+ * theirs — the order `core:var/likenesses@1` lays the tag lines out in, so
3316
+ * the n-th picture and the n-th tag line are the same person. Each one's
3317
+ * likeness image, else their avatar (`likenessOf`); someone with neither,
3318
+ * or whose file is gone or is not an image, is skipped. Not capped here:
3319
+ * the picture step's host caps references at the drawing sheet's maximum
3320
+ * and says so.
3321
+ * @experimental
3322
+ */
3323
+ export const likenessImages = pin(describeQueryDefinition({
3324
+ id: 'core:query/likeness-images@1',
3325
+ i18n: {
3326
+ name: { en: 'Likeness images' },
3327
+ description: { en: "Everyone on stage's likeness image, in stage order." },
3328
+ },
3329
+ timeoutMs: 2000,
3330
+ ports: {
3331
+ in: { scope: S.sessionScope },
3332
+ out: { main: S.mediaList, references: S.mediaList },
3333
+ },
3334
+ }));
3335
+ //# sourceMappingURL=queries.js.map