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

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