counterparts 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +326 -0
  2. package/docs/QUICKSTART.md +5 -0
  3. package/docs/README.md +2 -2
  4. package/docs/module-map.md +3 -3
  5. package/package.json +1 -1
  6. package/src/adapters/claude-code/CONTRACT.md +36 -10
  7. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  8. package/src/adapters/claude-code/NOTES.md +182 -0
  9. package/src/adapters/claude-code/bin/hook.ts +46 -12
  10. package/src/adapters/claude-code/bin/runner.ts +7 -1
  11. package/src/adapters/claude-code/doctor.ts +632 -18
  12. package/src/adapters/claude-code/hooks.ts +61 -16
  13. package/src/adapters/claude-code/index.ts +11 -0
  14. package/src/adapters/claude-code/night-run.ts +150 -14
  15. package/src/adapters/claude-code/transcript.ts +268 -1
  16. package/src/adapters/cli/CONTRACT.md +5 -0
  17. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  18. package/src/adapters/cli/NOTES.md +111 -0
  19. package/src/adapters/cli/commands.ts +134 -92
  20. package/src/adapters/cli/dream-core.ts +57 -42
  21. package/src/adapters/cli/export.ts +320 -21
  22. package/src/adapters/cli/help.ts +2 -1
  23. package/src/adapters/cli/index.ts +1 -0
  24. package/src/adapters/cli/install.ts +39 -7
  25. package/src/adapters/cli/mechanisms.ts +7 -1
  26. package/src/adapters/cli/uninstall.ts +13 -5
  27. package/src/adapters/cli/wire.ts +189 -63
  28. package/src/adapters/config.ts +2 -0
  29. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  30. package/src/adapters/dashboard/NOTES.md +79 -0
  31. package/src/adapters/dashboard/registries.ts +34 -2
  32. package/src/adapters/dashboard/web/README.md +19 -14
  33. package/src/adapters/dashboard/web/actions.ts +23 -1
  34. package/src/adapters/dashboard/web/flow.ts +14 -0
  35. package/src/adapters/dashboard/web/lanes.ts +10 -0
  36. package/src/adapters/dashboard/web/narrate.ts +88 -2
  37. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  38. package/src/adapters/dashboard/web/pages/health/sections/checks.js +2 -0
  39. package/src/adapters/dashboard/web/pages/health/sections/wake.js +3 -1
  40. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  41. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  42. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  43. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  44. package/src/adapters/dashboard/web/server.ts +0 -5
  45. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  46. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  47. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  48. package/src/adapters/dashboard/web/views/health.ts +21 -3
  49. package/src/adapters/dashboard/web/views/search.ts +4 -45
  50. package/src/adapters/dashboard/web/views.ts +2 -2
  51. package/src/adapters/fired.ts +430 -28
  52. package/src/adapters/host-wiring.ts +300 -0
  53. package/src/adapters/hosts.ts +11 -0
  54. package/src/adapters/lifecycle.ts +42 -2
  55. package/src/adapters/log/index.ts +9 -0
  56. package/src/adapters/mcp/CONTRACT.md +151 -11
  57. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  58. package/src/adapters/mcp/NOTES.md +313 -1
  59. package/src/adapters/mcp/bin/serve.ts +74 -1
  60. package/src/adapters/mcp/deliberate.ts +169 -651
  61. package/src/adapters/mcp/facts.ts +1094 -0
  62. package/src/adapters/mcp/index.ts +25 -7
  63. package/src/adapters/mcp/meaning.ts +1610 -0
  64. package/src/adapters/mcp/server.ts +835 -150
  65. package/src/adapters/mcp/stdio.ts +3 -1
  66. package/src/adapters/mcp/stood-down.ts +51 -0
  67. package/src/adapters/mcp/tools.ts +167 -41
  68. package/src/adapters/plugin-run.sh +133 -0
  69. package/src/adapters/plugin.ts +329 -0
  70. package/src/adapters/sessions.ts +18 -4
  71. package/src/core/associate/CONTRACT.md +2 -1
  72. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  73. package/src/core/associate/NOTES.md +45 -0
  74. package/src/core/briefing.ts +12 -3
  75. package/src/core/contradictions.ts +184 -0
  76. package/src/core/counterpart.ts +797 -51
  77. package/src/core/dream/CONTRACT.md +36 -4
  78. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  79. package/src/core/dream/NOTES.md +107 -0
  80. package/src/core/dream/feeling-weeks.ts +198 -0
  81. package/src/core/dream/index.ts +109 -18
  82. package/src/core/dream/reflect.ts +346 -87
  83. package/src/core/dream/tunables.ts +24 -4
  84. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  85. package/src/core/encode/NOTES.md +7 -0
  86. package/src/core/encode/words.ts +45 -0
  87. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  88. package/src/core/fit/NOTES.md +39 -1
  89. package/src/core/fit/index.ts +40 -0
  90. package/src/core/handoff/CONTRACT.md +37 -2
  91. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  92. package/src/core/handoff/NOTES.md +72 -0
  93. package/src/core/handoff/index.ts +214 -12
  94. package/src/core/handoff/last-here.ts +6 -4
  95. package/src/core/mint.ts +12 -2
  96. package/src/core/physics/CONTRACT.md +14 -2
  97. package/src/core/physics/NOTES.md +33 -1
  98. package/src/core/physics/index.ts +28 -5
  99. package/src/core/prospective/CONTRACT.md +45 -6
  100. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  101. package/src/core/prospective/NOTES.md +138 -0
  102. package/src/core/prospective/derive.ts +33 -5
  103. package/src/core/prospective/index.ts +90 -5
  104. package/src/core/prospective/windows.ts +72 -1
  105. package/src/core/recall/CONTRACT.md +31 -12
  106. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  107. package/src/core/recall/NOTES.md +70 -1
  108. package/src/core/recall/feeling-ask.ts +10 -1
  109. package/src/core/recall/index.ts +3 -1
  110. package/src/core/recall/probe.ts +58 -0
  111. package/src/core/recall/session.ts +46 -2
  112. package/src/core/recall/time-ask.ts +487 -0
  113. package/src/core/remember/CONTRACT.md +4 -1
  114. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  115. package/src/core/remember/NOTES.md +8 -0
  116. package/src/core/remember/proposals.ts +47 -5
  117. package/src/core/revision.ts +18 -1
  118. package/src/core/schemas/CONTRACT.md +21 -1
  119. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  120. package/src/core/schemas/NOTES.md +144 -0
  121. package/src/core/schemas/aliases.ts +55 -5
  122. package/src/core/schemas/index.ts +93 -1
  123. package/src/core/schemas/types.ts +2 -0
  124. package/src/core/self/CONTRACT.md +32 -5
  125. package/src/core/self/INTERFACE-GAPS.md +7 -2
  126. package/src/core/self/NOTES.md +102 -1
  127. package/src/core/self/behind.ts +43 -3
  128. package/src/core/self/briefing.ts +12 -2
  129. package/src/core/self/chapter-address.ts +254 -0
  130. package/src/core/self/episodes.ts +27 -0
  131. package/src/core/self/index.ts +83 -8
  132. package/src/core/self/page.ts +88 -0
  133. package/src/core/self/tunables.ts +5 -0
  134. package/src/core/self/work.ts +35 -2
  135. package/src/core/self/writer.ts +30 -0
  136. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  137. package/src/core/sleep/NOTES.md +20 -1
  138. package/src/core/sleep/consolidate.ts +59 -7
  139. package/src/core/sleep/index.ts +3 -0
  140. package/src/core/sleep/prune.ts +6 -2
  141. package/src/core/sleep/types.ts +7 -0
  142. package/src/core/store/CONTRACT.md +16 -0
  143. package/src/core/store/NOTES.md +66 -0
  144. package/src/core/store/feelings.ts +14 -1
  145. package/src/core/store/index.ts +483 -16
  146. package/src/core/store/operational.ts +95 -2
  147. package/src/core/store/owner-op-seam.ts +23 -0
  148. package/src/core/time.ts +152 -0
  149. package/tools/install-loop/run.sh +48 -12
  150. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -0,0 +1,1610 @@
1
+ /**
2
+ * MEANING MODE — deliberate recall's second path (Release B, 2026-10-03).
3
+ *
4
+ * `recall` with `mode: "meaning"` answers "what has X been to me", "how have
5
+ * things gone between us", "when was I uneasy": questions about a SUBJECT
6
+ * over time, or a feeling, rather than a fact. Facts mode (`facts.ts`) finds
7
+ * the memories that say something; this one ARRANGES what memory holds about
8
+ * a subject so the reader can interpret it. Recall runs without a language
9
+ * model, so the tool lays the material out and the counterpart writes "what
10
+ * it adds up to" in its own reply, as today's reading (the design of
11
+ * 2026-10-03, `~/counterparts-notes/2026-10-03-deliberate-recall-design.md`).
12
+ *
13
+ * **What an answer is**, in order:
14
+ *
15
+ * 1. A header: the subject, how many chapters and moments hold it, the page,
16
+ * the other subjects the question named (one line each, to ask for), and
17
+ * what makes the evidence thin when it is.
18
+ * 2. The ARC: the chapters (`epi_…#N`, `self/chapter-address.ts`) that hold
19
+ * the subject, ranked by how much of it they hold and SHOWN IN TIME
20
+ * ORDER; under each, a line of what happened, the feelings recorded in
21
+ * it — whose they are, side by side, never merged — and two or three of
22
+ * its moments by id. A long arc keeps its start, its end and its turns;
23
+ * the stretches between fold to one line each. Moments a session wrote
24
+ * with no chapter — or under none of its chapters, when their moments
25
+ * are unknown or come after the last — are an entry per session,
26
+ * labelled which.
27
+ * 3. Faded moments: a few title lines, labelled, after the arc.
28
+ * 4. Earlier readings: dream gists and reflection entries that touched the
29
+ * subject, dated. The dream journal stays outside (dream CONTRACT).
30
+ * 5. Still open with the subject: unresolved threads and dated reminders.
31
+ * 6. Recurring: the subjects and feelings that come back across several
32
+ * chapters, side by side. Nothing names the pattern; the reader does.
33
+ *
34
+ * **The subject.** The question's names, read through the alias index
35
+ * (`Schemas#subjectsIn`), reach their cards' memories (`memory_subjects`,
36
+ * v12); the card the question is ABOUT is the arc — read off its grammar and
37
+ * the order of its names, counts only breaking a tie (`subjectOf`, since
38
+ * 2026-10-09; it was the card holding the most) — and the rest are
39
+ * one-liners. The owner's "I" asked about ("what have you been like", in the
40
+ * counterpart's voice) is his own card. "us"
41
+ * is the memories marked `about: us`. A question about feeling
42
+ * (`recall/feeling-ask.ts#readFeelingAsk`, ranked) with no card is answered
43
+ * by the stamps that match it — word, core, whose — and, when it names a
44
+ * topic no card holds, by those of them the topic's words reach (none: all of
45
+ * them, said so); with a card, it keeps the
46
+ * chapters where the card's moments carry the feeling. Nothing named and no
47
+ * feeling: the question's rarer words (BM25) and its meaning (the in-line
48
+ * vector) find the moments, and the answer says no card named it.
49
+ *
50
+ * **What it never does.** It writes nothing (no physics, no memory, no host
51
+ * state): a search credits nothing. Opening a moment by id, or quoting one
52
+ * the caller was shown (`MeaningResult.shown`), is what credits. Confidential
53
+ * material is left out of a non-owner's answer SILENTLY — not counted, not
54
+ * hinted at (§9.1 G5's list rule). Corrected (archived), superseded and
55
+ * removed memories are not moments. Ambient recall is untouched.
56
+ *
57
+ * **Reads, bounded.** Indexed reads only: `memoriesNaming`, `feelingsOn`,
58
+ * `list` + `row`, `copiesOf`, `memoriesOfSession` for the chapters shown,
59
+ * one prose read per subject memory (the `unresolved` flag). No scan of
60
+ * every memory's prose.
61
+ */
62
+ import type { Counterpart } from "../../core/counterpart.js";
63
+ import { nameRegex, wholeWordRegex } from "../../core/encode/words.js";
64
+ import { OTHER_EMOTION, wheelEntry } from "../../core/feelings-wheel.js";
65
+ import { wireChars } from "../../core/fit/index.js";
66
+ import { chaptersOf } from "../../core/handoff/last-here.js";
67
+ import { UNRESOLVED_META_KEY } from "../../core/mint.js";
68
+ import { softenedFeeling, strength } from "../../core/physics/index.js";
69
+ import type { MemoryPhysics } from "../../core/physics/index.js";
70
+ import { askedNames, feelingTokens, isFeelingFrameWord, readFeelingAsk, semanticTuning, stampCores } from "../../core/recall/index.js";
71
+ import type { FeelingWhose, SemanticSource } from "../../core/recall/index.js";
72
+ import { chapterAddress, chapterAt, chapterTimesOf, findIdentityCore, identityCoreName } from "../../core/self/index.js";
73
+ import type { ChapterTimes } from "../../core/self/index.js";
74
+ import { RECURRING_META, feelingValence, tokenize } from "../../core/store/index.js";
75
+ import type { FeelingRow, MemoryRow } from "../../core/store/index.js";
76
+ import { calendarOverlaps, daysBetween, isDay, isRecurrence, localDate, occurrenceOnOrAfter, readableRecurrence } from "../../core/time.js";
77
+ import { RECALL_RESULT_CHARS, hasFaded } from "./deliberate.js";
78
+
79
+ // ── the numbers (working defaults, 2026-10-03; tune at the revisit) ──────────
80
+
81
+ /** Entries in the arc on one page. Past it, `page: 2`. */
82
+ export const MEANING_CHAPTERS_SHOWN = 8;
83
+ /** Moment ids under one chapter. */
84
+ export const MEANING_MOMENTS_PER_CHAPTER = 3;
85
+ /** Faded moments listed after the arc. */
86
+ export const MEANING_FADED_SHOWN = 4;
87
+ /** Earlier readings listed (the newest). */
88
+ export const MEANING_READINGS_SHOWN = 4;
89
+ /** Open items listed. */
90
+ export const MEANING_OPEN_SHOWN = 5;
91
+ /** Recurring subjects, and recurring feelings, listed (each). */
92
+ export const MEANING_PATTERNS_SHOWN = 4;
93
+ /** The meaning channel's reach on a question with no card: the nearest this many. */
94
+ export const MEANING_SEMANTIC_MAX = 100;
95
+ /** The words channel's reach on a question with no card. */
96
+ export const MEANING_WORDS_MAX = 200;
97
+ /** The rendered answer's room, in `wireChars`: the list budget every deliberate answer keeps. */
98
+ export const MEANING_RESULT_CHARS = RECALL_RESULT_CHARS;
99
+ /** A word held by more than this share of the indexed memories says nothing about a subject. */
100
+ const COMMON_SHARE = 0.25;
101
+ /** How long a chapter's line may be, before the fit trims it. */
102
+ const LINE_CHARS = 220;
103
+ /** How long a title line may be. */
104
+ const TITLE_CHARS = 90;
105
+
106
+ // ── the shapes ───────────────────────────────────────────────────────────────
107
+
108
+ /**
109
+ * What the server holds that this path needs (`server.ts#recallTool`): the
110
+ * brain, who is asking, whether it is the owner's session, and the question's
111
+ * embedding — computed IN LINE by the caller (`deliberate.ts#embedQuestion`),
112
+ * because this function is synchronous. Field names follow
113
+ * `deliberate.ts#DeliberateOptions`.
114
+ */
115
+ export interface MeaningContext {
116
+ readonly counterpart: Counterpart;
117
+ readonly sessionId: string;
118
+ /** The owner's own session? Confidential material is left out otherwise, silently. */
119
+ readonly owner: boolean;
120
+ /** The question's embedding, or null / absent: the meaning channel is then off, and a no-card answer says so. */
121
+ readonly vector?: readonly number[] | null;
122
+ /** Why there is no vector, when there is none. Defaults to `embedder-off`. */
123
+ readonly semantic?: SemanticSource;
124
+ /** Whose "I" a question about feeling means: `self` (the default) for the counterpart's `recall`. */
125
+ readonly asker?: FeelingWhose;
126
+ /** The lived day, for a test; the store's own otherwise. */
127
+ readonly day?: number;
128
+ }
129
+
130
+ /** What the arc is about. */
131
+ export type MeaningLens =
132
+ | { readonly kind: "card"; readonly id: string; readonly name: string }
133
+ | { readonly kind: "us"; readonly name: string }
134
+ | { readonly kind: "feeling"; readonly name: string }
135
+ | { readonly kind: "words"; readonly name: string };
136
+
137
+ export interface MeaningMoment {
138
+ readonly id: string;
139
+ readonly title: string;
140
+ /** `YYYY-MM-DD`, local, when it was written. */
141
+ readonly date: string;
142
+ }
143
+
144
+ export interface MeaningFeeling {
145
+ readonly word: string;
146
+ /** As recorded, 0..1. */
147
+ readonly strength: number;
148
+ }
149
+
150
+ /** One entry of the arc: a chapter, or the moments of a session that wrote no chapter. */
151
+ export interface MeaningEntry {
152
+ /** `epi_…#N` for a chapter; `session <id>` for a session's moments outside any chapter. */
153
+ readonly address: string;
154
+ readonly kind: "chapter" | "session";
155
+ /**
156
+ * A session entry whose session DID write chapters, these moments under
157
+ * none of them: the chapters' moments are unknown (an episode from before
158
+ * v12 whose versions are gone) or they were written after the last one (a
159
+ * write-up). False for a session that wrote no chapter, and for a chapter.
160
+ */
161
+ readonly unplaced: boolean;
162
+ /** The episode id, which opens the chapter's words; null for a session entry. */
163
+ readonly episodeId: string | null;
164
+ readonly chapter: number | null;
165
+ readonly of: number | null;
166
+ readonly title: string | null;
167
+ /** `YYYY-MM-DD`, or null when nothing dates it. */
168
+ readonly date: string | null;
169
+ /** A line of what happened: the chapter's first sentence that names the subject, else its first. Empty for a session entry. */
170
+ readonly line: string;
171
+ /** How much of the subject it holds — what the ranking reads. */
172
+ readonly hold: number;
173
+ /** The subject's moments in it (not faded), and how many there are. */
174
+ readonly moments: readonly MeaningMoment[];
175
+ readonly momentCount: number;
176
+ /** The feelings recorded in it, strongest first: the asker's, and the other's. Never merged. */
177
+ readonly feelings: { readonly self: readonly MeaningFeeling[]; readonly owner: readonly MeaningFeeling[] };
178
+ /** Where the feelings turn (valence flips from the entry before), or the first or last of a long arc. */
179
+ readonly marks: readonly ("start" | "end" | "turn")[];
180
+ }
181
+
182
+ /** A stretch of the arc not shown on this page, folded to one line. */
183
+ export interface MeaningFold {
184
+ readonly count: number;
185
+ readonly from: string | null;
186
+ readonly to: string | null;
187
+ }
188
+
189
+ export type MeaningArcLine = { readonly fold: false; readonly entry: MeaningEntry } | ({ readonly fold: true } & MeaningFold);
190
+
191
+ export interface MeaningReading {
192
+ readonly id: string;
193
+ readonly by: "dreamed" | "reflected";
194
+ readonly date: string;
195
+ readonly title: string;
196
+ readonly excerpt: string;
197
+ }
198
+
199
+ export interface MeaningOpen {
200
+ readonly id: string;
201
+ readonly title: string;
202
+ /** `open` — an unresolved thread; `dated` — a reminder on or after today. */
203
+ readonly why: "open" | "dated";
204
+ readonly date: string | null;
205
+ /** A repeating reminder (2026-10-09): how often, in words — `date` is then
206
+ * its next occurrence. Absent on a date that happens once. */
207
+ readonly every?: string;
208
+ }
209
+
210
+ export interface MeaningPattern {
211
+ readonly label: string;
212
+ /** In how many entries of the arc it recurs, of `of`. */
213
+ readonly entries: number;
214
+ readonly of: number;
215
+ }
216
+
217
+ export interface MeaningResult {
218
+ readonly mode: "meaning";
219
+ readonly reason: "answered" | "nothing-came";
220
+ readonly semantic: SemanticSource;
221
+ readonly lens: MeaningLens | null;
222
+ /** The other subjects the question named, as one-liners to ask for. */
223
+ readonly others: readonly { readonly name: string; readonly memories: number }[];
224
+ /** A question about feeling: the words it named and whose ("mine", "Mike's"), or null. */
225
+ readonly feeling: { readonly words: readonly string[]; readonly whose: string | null } | null;
226
+ readonly counts: {
227
+ /** Chapters in the whole arc (all pages). */
228
+ readonly chapters: number;
229
+ /** Sessions with the subject's moments and no chapter for them. */
230
+ readonly sessions: number;
231
+ /** Of those, the sessions that did write chapters, the moments under none of them. */
232
+ readonly unplaced: number;
233
+ /** The subject's moments (not faded). */
234
+ readonly moments: number;
235
+ readonly faded: number;
236
+ readonly readings: number;
237
+ readonly open: number;
238
+ };
239
+ readonly page: number;
240
+ readonly pages: number;
241
+ readonly arc: readonly MeaningArcLine[];
242
+ readonly faded: readonly MeaningMoment[];
243
+ readonly readings: readonly MeaningReading[];
244
+ readonly open: readonly MeaningOpen[];
245
+ readonly patterns: { readonly subjects: readonly MeaningPattern[]; readonly feelings: readonly MeaningPattern[] };
246
+ /** What makes the evidence thin, and other plain notes ("no card names it"). */
247
+ readonly notes: readonly string[];
248
+ /** Whose labels the renderer prints: the asker's and the other's. */
249
+ readonly whose: { readonly self: string; readonly owner: string };
250
+ /**
251
+ * Every id the rendered answer shows — memories and episodes — for the
252
+ * seen set (`server.ts#markSeen`, which `note.feelingsNow` reads) and quote
253
+ * credit. Exactly what `renderMeaning` prints, after the fit.
254
+ */
255
+ readonly shown: readonly string[];
256
+ /** The rendered size, `wireChars`, and whether the fit had to trim. */
257
+ readonly chars: number;
258
+ readonly trimmed: boolean;
259
+ }
260
+
261
+ // ── the path ─────────────────────────────────────────────────────────────────
262
+
263
+ /** Words a question is built from rather than about (the no-card words channel only). */
264
+ const FRAME = new Set([
265
+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "whats", "was", "were", "is", "are", "am",
266
+ "be", "been", "being", "do", "does", "did", "have", "has", "had", "can", "could", "will", "would", "should", "may",
267
+ "ive", "im", "the", "an", "this", "that", "these", "those", "some", "any", "them", "they", "their", "of", "to", "in",
268
+ "on", "at", "for", "with", "about", "from", "by", "as", "into", "and", "or", "but", "if", "than", "then", "not",
269
+ "very", "really", "me", "my", "mine", "you", "your", "yours", "we", "us", "our", "ours", "it", "its", "there",
270
+ "been", "since", "ever", "over", "time", "times", "things", "thing", "between", "together", "keeps", "keep",
271
+ "coming", "come", "comes", "up", "happened", "happen", "mean", "means", "meant", "think", "felt", "feel", "feeling",
272
+ "feelings", "most", "all", "so", "far", "lately", "recently", "tell", "story", "arc", "been",
273
+ // The asking itself ("what do I know about Will", review of #323).
274
+ "know", "knew", "known", "remember", "remembered",
275
+ ]);
276
+
277
+ /**
278
+ * A feeling question's frame beyond `feeling-ask.ts#isFeelingFrameWord`: the
279
+ * owner named as a role, and the recent past ("what have I felt lately") —
280
+ * never a topic to read moments by.
281
+ */
282
+ const FEELING_FRAME_MORE = new Set([
283
+ "owner", "user", "recent", "recently", "lately", "latest", "last", "today", "yesterday", "tonight", "now",
284
+ ]);
285
+
286
+ /** Words that make "us" the subject: the two of them together. Not "we" or "our", which a question uses for joint work. */
287
+ const US_WORDS = new Set(["us", "ourselves", "together"]);
288
+
289
+ /**
290
+ * Just before a name, words that make it what the question is ABOUT: "what has
291
+ * X been", "how has X changed", "who was X", "how did X take it", "tell me
292
+ * about X", "my arc with X", "between X and Y" (and "between you and X").
293
+ */
294
+ const ABOUT_BEFORE: readonly RegExp[] = [
295
+ /\b(?:what|who|how)\s+(?:has|have|had|is|are|was|were)\s+$/i,
296
+ /\bhow\s+did\s+$/i,
297
+ /\babout\s+$/i,
298
+ /\b(?:my|our|your)\s+(?:arc|history|story|relationship|time|work|things)\s+with\s+$/i,
299
+ /\bbetween\s+$/i,
300
+ /\bbetween\s+(?:you|me|him|her|them)\s+and\s+$/i,
301
+ ];
302
+ /**
303
+ * Just before a name, words that make it an ASIDE: who the subject matters to
304
+ * ("been to Y", "meant for Y"), or when ("since Y arrived", "after Y left").
305
+ * Not a bare "to": "what happened to X" asks about X.
306
+ */
307
+ const ASIDE_BEFORE = /\b(?:(?:be|been|is|was|are|were|mean|means|meant|matter|matters|mattered)\s+(?:to|for)|since|after|before|until|than)\s+$/i;
308
+ /** What lies between two names asked about alike: "X and Y", "X, Y", "X or Y". */
309
+ const JOINED = /^(?:\s*,\s*(?:(?:and|or)\s+)?|\s+(?:and|or|&)\s+)$/i;
310
+ /** The owner's "I" when the asker is the counterpart (`asker: "self"`): "you". Not "your", which owns a topic ("your garden plan"). */
311
+ const OWNER_AS_YOU = /\b(?:you|yourself)\b(?!['’])/gi;
312
+ /** The owner's "I" when the asker is the owner. Not "my", for the same reason. */
313
+ const OWNER_AS_I = /\b(?:i|me|myself)\b(?!['’])/gi;
314
+
315
+ /** A card the question names, and its memories the asker may see. */
316
+ interface NamedCard {
317
+ readonly id: string;
318
+ readonly name: string;
319
+ readonly ids: readonly string[];
320
+ }
321
+
322
+ interface Held {
323
+ readonly row: MemoryRow;
324
+ /** How strongly this memory holds the subject (1 for a card's; a stamp's value; a word/meaning score). */
325
+ weight: number;
326
+ }
327
+
328
+ interface EpisodeInfo {
329
+ readonly id: string;
330
+ readonly session: string | null;
331
+ readonly title: string | null;
332
+ readonly createdAt: number;
333
+ readonly chapters: readonly { text: string; date: string | null; heading: string | null }[];
334
+ }
335
+
336
+ interface Entry {
337
+ readonly key: string;
338
+ readonly kind: "chapter" | "session";
339
+ readonly episode: EpisodeInfo | null;
340
+ readonly chapter: number | null;
341
+ readonly session: string | null;
342
+ /** A session entry whose session did write chapters, these moments under none of them. */
343
+ readonly unplaced: boolean;
344
+ /** When it sits in time, UTC ms — what the arc is ordered by; +∞ when nothing dates it. */
345
+ at: number;
346
+ date: string | null;
347
+ hold: number;
348
+ textHold: number;
349
+ readonly moments: Held[];
350
+ }
351
+
352
+ /**
353
+ * Answer a question in meaning mode. Never throws on a store that will not
354
+ * answer one of its reads: that part is empty and the rest stands. `page`
355
+ * picks the arc's page (from 1); `roomChars` is the rendered room,
356
+ * `MEANING_RESULT_CHARS` unless a test passes a small one to reach the trim.
357
+ */
358
+ export function meaningRecall(ctx: MeaningContext, question: string, opts: { page?: number; roomChars?: number } = {}): MeaningResult {
359
+ const c = ctx.counterpart;
360
+ const store = c.store;
361
+ const owner = ctx.owner;
362
+ const day = ctx.day ?? safe(() => store.livedDay(), 0);
363
+ const zone = safe(() => store.zone(), undefined);
364
+ const today = safe(() => store.today(), localDate(Date.now(), zone));
365
+ const vector = ctx.vector ?? null;
366
+ const semantic: SemanticSource = vector !== null && vector.length > 0 ? "in-line" : (ctx.semantic ?? "embedder-off");
367
+ const asker: FeelingWhose = ctx.asker ?? "self";
368
+ const ownerName = ownerDisplayName(c);
369
+ const whose = {
370
+ self: asker === "self" ? "mine" : "the counterpart's",
371
+ owner: asker === "owner" ? "mine" : ownerName === null ? "the owner's" : `${ownerName}'s`,
372
+ };
373
+ const page = Number.isInteger(opts.page) && (opts.page as number) >= 1 ? (opts.page as number) : 1;
374
+ const denied = new Set(safe(() => store.deniedIds(), [] as string[]));
375
+ const rows = new Map<string, MemoryRow | null>();
376
+ /** A memory row the asker may see, or null: live, not superseded, not removed, not confidential to a non-owner. */
377
+ const usable = (id: string): MemoryRow | null => {
378
+ if (rows.has(id)) return rows.get(id) ?? null;
379
+ let out: MemoryRow | null = null;
380
+ try {
381
+ const row = store.row(id);
382
+ if (
383
+ row !== undefined &&
384
+ row.type === "memory" &&
385
+ row.archived === 0 &&
386
+ row.superseded_by === null &&
387
+ !denied.has(id) &&
388
+ (owner || row.confidential !== 1)
389
+ ) {
390
+ out = row;
391
+ }
392
+ } catch {
393
+ out = null;
394
+ }
395
+ rows.set(id, out);
396
+ return out;
397
+ };
398
+
399
+ // ── 1. the question: feeling, cards, "us" ──────────────────────────────────
400
+ const stamps = safe(() => store.feelingsLive(), [] as (FeelingRow & { birth_day: number })[]);
401
+ const tokensOf = stamps.map((f) => feelingTokens(f));
402
+ const stored = new Set(tokensOf.flatMap((x) => [...x]));
403
+ const minLen = c.recall.tunables.MIN_CUE_LENGTH;
404
+ const ask = safe(
405
+ () => readFeelingAsk(question, { asker, ownerNames: ownerNamesLower(c), owner }, stored, minLen),
406
+ null,
407
+ );
408
+ const feelingAsked = ask !== null && ask.ranked;
409
+ /** memory -> the strongest matching stamp's value (a core-tier match counts half). */
410
+ const felt = new Map<string, number>();
411
+ if (feelingAsked && ask !== null) {
412
+ const every = ask.named.size === 0;
413
+ stamps.forEach((f, i) => {
414
+ if (ask.whose !== null && f.whose !== ask.whose) return;
415
+ const answers = tokensOf[i] as Set<string>;
416
+ const exact = every || [...ask.named].some((w) => answers.has(w));
417
+ const core = !exact && stampCores(f).some((x) => ask.cores.has(x));
418
+ if (!exact && !core) return;
419
+ const soft = softenedFeeling(f.strength, day - f.birth_day, feelingValence(f));
420
+ const value = (ask.strongest ? f.strength : soft) * (exact ? 1 : 0.5);
421
+ if (!(value > 0)) return;
422
+ if (usable(f.memory_id) === null) return;
423
+ felt.set(f.memory_id, Math.max(felt.get(f.memory_id) ?? 0, value));
424
+ });
425
+ }
426
+
427
+ const cardOf = (id: string): NamedCard | null => {
428
+ const name = safe(() => c.schemas.entity(id)?.name ?? null, null);
429
+ if (name === null) return null;
430
+ return { id, name, ids: safe(() => store.memoriesNaming(id), [] as string[]).filter((m) => usable(m) !== null) };
431
+ };
432
+ const cards = safe(() => c.schemas.subjectsIn(question), [] as string[])
433
+ .map(cardOf)
434
+ .filter((x): x is NamedCard => x !== null)
435
+ .sort((a, b) => b.ids.length - a.ids.length || a.name.localeCompare(b.name));
436
+ const usAsked = tokenize(question).some((w) => US_WORDS.has(w)) || /\bbetween\s+(you\s+and\s+me|me\s+and\s+you)\b/i.test(question);
437
+ const usIds = usAsked
438
+ ? safe(() => store.list({ type: "memory", archived: false, about: "us" }), [] as string[]).filter((m) => usable(m) !== null)
439
+ : [];
440
+ const usName = ownerName === null ? "us" : `us (${ownerName} and me)`;
441
+
442
+ // ── 2. the lens, and the memories that hold it ─────────────────────────────
443
+ const held = new Map<string, Held>();
444
+ const hold = (id: string, weight: number): void => {
445
+ const row = usable(id);
446
+ if (row === null || !(weight > 0)) return;
447
+ const had = held.get(id);
448
+ if (had === undefined) held.set(id, { row, weight });
449
+ else had.weight = Math.max(had.weight, weight);
450
+ };
451
+ let lens: MeaningLens | null = null;
452
+ /** A chapter's words hold the subject too: the card's terms, or the question's words. */
453
+ let textMatch: ((text: string) => number) | null = null;
454
+ /** The regexes a chapter's line is picked by. */
455
+ let lineMatch: readonly RegExp[] = [];
456
+ const others: { name: string; memories: number }[] = [];
457
+ const notes: string[] = [];
458
+ // THE SUBJECT IS THE CARD THE QUESTION IS ABOUT (2026-10-09), read off its
459
+ // grammar and the order of its names; memory counts only break a tie. The
460
+ // owner's "I" — "you" in my voice — asked about is his own card
461
+ // (`subjectOf`). It was the card with the most memories, which on a real
462
+ // store is usually the owner's: "what has Ilya been to Mike" answered
463
+ // about Mike.
464
+ const ownerCard = safe(() => findIdentityCore(store), null);
465
+ const subject = subjectOf(question, cards, {
466
+ terms: (id) => cardTerms(c, id),
467
+ ownerCard,
468
+ ownerPronoun: feelingAsked || usAsked ? null : asker === "self" ? OWNER_AS_YOU : OWNER_AS_I,
469
+ ownerCardOf: () => (ownerCard === null ? null : cardOf(ownerCard)),
470
+ });
471
+ const bestCard = subject.card;
472
+ if (bestCard !== null && subject.alike.length > 0) {
473
+ notes.push(`it asks about ${andList([bestCard.name, ...subject.alike])} alike: this follows ${bestCard.name}, named first`);
474
+ }
475
+
476
+ if (bestCard !== null) {
477
+ lens = { kind: "card", id: bestCard.id, name: bestCard.name };
478
+ for (const id of bestCard.ids) hold(id, 1);
479
+ // By the alias index's own name rule: "Han's" names Han.
480
+ const terms = cardTerms(c, bestCard.id);
481
+ const res = terms.map((t) => nameRegex(t, "giu"));
482
+ lineMatch = terms.map((t) => nameRegex(t));
483
+ if (res.length > 0) {
484
+ textMatch = (text) => {
485
+ let n = 0;
486
+ for (const re of res) n += (text.match(re) ?? []).length;
487
+ return Math.min(n, 4) * 0.5;
488
+ };
489
+ }
490
+ for (const x of cards) if (x.id !== bestCard.id) others.push({ name: x.name, memories: x.ids.length });
491
+ if (usIds.length > 0) others.push({ name: usName, memories: usIds.length });
492
+ } else if (usIds.length > 0) {
493
+ lens = { kind: "us", name: usName };
494
+ for (const id of usIds) hold(id, 1);
495
+ for (const x of cards) others.push({ name: x.name, memories: x.ids.length });
496
+ } else if (feelingAsked && ask !== null) {
497
+ // A FEELING ABOUT A TOPIC NO CARD NAMES ("how did I feel about the garden
498
+ // plan", review of #323): the felt moments the topic's words reach are the
499
+ // answer. None reached: every felt moment, and the answer says plainly that
500
+ // no card names the topic and none of them say it. Only the words — the
501
+ // question's embedding carries the feeling, not the topic — and not a
502
+ // "since …" clause, which is a time ("since I started living here"), not
503
+ // a topic. Unstamped memories the words reach are never moments here: a
504
+ // note ABOUT feelings is not a feeling (lane 6, item 3).
505
+ const feelingAs = feelingName(ask.named, ask.whose, whose);
506
+ const asked = question.replace(/\bsince\b[^?.!;]*/gi, " ");
507
+ const proper = safe(() => askedNames(asked), new Set<string>());
508
+ const owners = new Set(ownerNamesLower(c).flatMap((n) => tokenize(n)));
509
+ const topic = contentWords(
510
+ c,
511
+ asked,
512
+ minLen,
513
+ ask.named,
514
+ (w) => isFeelingFrameWord(w, stored, proper) || owners.has(w) || FEELING_FRAME_MORE.has(w),
515
+ );
516
+ const reached = new Map<string, number>();
517
+ if (topic.words.length > 0) {
518
+ holdByWords(store, topic, usable, (id) => {
519
+ const v = felt.get(id);
520
+ if (v !== undefined) reached.set(id, v);
521
+ });
522
+ }
523
+ const topicName = `"${topic.shown.join(" ")}"`;
524
+ if (reached.size > 0) {
525
+ lens = { kind: "feeling", name: `${feelingAs} about ${topicName}` };
526
+ for (const [id, v] of reached) hold(id, v);
527
+ notes.push(`no card names ${topicName}: the moments that carry ${feelingAs} and say it`);
528
+ } else {
529
+ lens = { kind: "feeling", name: feelingAs };
530
+ for (const [id, v] of felt) hold(id, v);
531
+ if (topic.words.length > 0) {
532
+ notes.push(`no card names ${topicName}, and no moment that carries ${feelingAs} says it: every one follows`);
533
+ }
534
+ }
535
+ for (const x of cards) others.push({ name: x.name, memories: x.ids.length });
536
+ } else {
537
+ const topic = contentWords(c, question, minLen, ask?.named ?? new Set());
538
+ const words = topic.words;
539
+ if (words.length > 0 || (vector !== null && vector.length > 0)) {
540
+ lens = { kind: "words", name: words.length > 0 ? `"${topic.shown.join(" ")}"` : "the question's meaning" };
541
+ if (words.length > 0) {
542
+ const byWords = holdByWords(store, topic, usable, hold);
543
+ textMatch = byWords.textMatch;
544
+ lineMatch = byWords.lineMatch;
545
+ }
546
+ if (vector !== null && vector.length > 0) {
547
+ const floor = safe(() => semanticTuning(c.recall.tunables, store.rankingIdentity(), "inline").floor, 0.45);
548
+ for (const h of safe(() => store.nearestTo(vector, MEANING_SEMANTIC_MAX), [])) {
549
+ if (h.score >= floor) hold(h.id, Math.min(1, h.score));
550
+ }
551
+ }
552
+ notes.push(
553
+ `no card names it: matched by its words${vector !== null && vector.length > 0 ? " and its meaning" : ` only (meaning search off: ${semantic})`}`,
554
+ );
555
+ }
556
+ for (const x of cards) others.push({ name: x.name, memories: x.ids.length });
557
+ }
558
+
559
+ // Readings and chapter copies are not moments: set aside.
560
+ const readingIds = new Set<string>();
561
+ const copies = new Map<string, Held>();
562
+ for (const [id, h] of held) {
563
+ if (h.row.source === "dreamed" || h.row.source === "reflection") {
564
+ readingIds.add(id);
565
+ held.delete(id);
566
+ } else if (h.row.source === "episode" && h.row.origin_ref !== null && h.row.origin_ref.startsWith("epi_")) {
567
+ copies.set(id, h);
568
+ held.delete(id);
569
+ }
570
+ }
571
+
572
+ // Faded moments: listed after the arc, not in its slots.
573
+ const strengthOf = new Map<string, number>();
574
+ const fadedIds: string[] = [];
575
+ for (const [id] of held) {
576
+ const physics = safe(() => store.physicsOf(id), null);
577
+ if (physics === null) continue;
578
+ strengthOf.set(id, strength(physics, day));
579
+ if (isFaded(physics, day)) fadedIds.push(id);
580
+ }
581
+ for (const id of fadedIds) held.delete(id);
582
+
583
+ // A question about feeling WITH a subject keeps the subject's moments that
584
+ // carry the feeling — if any do; otherwise the whole arc, and it says so.
585
+ // Read after the readings, copies and faded are set aside: a gist or a
586
+ // faded moment carrying it would keep nothing on the arc.
587
+ let feelingFilter: ReadonlyMap<string, number> | null = null;
588
+ if (feelingAsked && ask !== null && lens !== null && lens.kind !== "feeling") {
589
+ const kept = [...held.keys()].filter((id) => felt.has(id));
590
+ if (kept.length > 0) feelingFilter = felt;
591
+ else notes.push(`none of ${lens.name}'s moments carry ${feelingName(ask.named, ask.whose, whose)}: the whole arc follows`);
592
+ }
593
+
594
+ // ── 3. the arc: place each moment under its chapter ────────────────────────
595
+ const episodes = episodeIndex(c, owner, denied);
596
+ const bySession = new Map<string, EpisodeInfo[]>();
597
+ for (const e of episodes) {
598
+ if (e.session === null) continue;
599
+ const list = bySession.get(e.session) ?? [];
600
+ list.push(e);
601
+ bySession.set(e.session, list);
602
+ }
603
+ const times = new Map<string, ChapterTimes | null>();
604
+ const timesOf = (id: string): ChapterTimes | null => {
605
+ if (!times.has(id)) times.set(id, chapterTimesOf(store, id));
606
+ return times.get(id) ?? null;
607
+ };
608
+ const entries = new Map<string, Entry>();
609
+ const chapterEntry = (e: EpisodeInfo, k: number): Entry => {
610
+ const key = chapterAddress(e.id, k);
611
+ let entry = entries.get(key);
612
+ if (entry === undefined) {
613
+ const t = timesOf(e.id);
614
+ const date = e.chapters[k - 1]?.date ?? null;
615
+ const at = t?.moments[k] ?? (date !== null ? Date.parse(`${date}T12:00:00Z`) : e.createdAt);
616
+ entry = { key, kind: "chapter", episode: e, chapter: k, session: e.session, unplaced: false, at, date: date ?? localDay(at, zone), hold: 0, textHold: 0, moments: [] };
617
+ entries.set(key, entry);
618
+ }
619
+ return entry;
620
+ };
621
+ const momentList = [...held.values()].filter((h) => feelingFilter === null || feelingFilter.has(h.row.id));
622
+ for (const h of momentList) {
623
+ const session = h.row.origin_session;
624
+ const at = h.row.created_at;
625
+ let placed: Entry | null = null;
626
+ if (session !== null && at !== null) {
627
+ for (const e of bySession.get(session) ?? []) {
628
+ const t = timesOf(e.id);
629
+ const k = t === null ? null : chapterAt(t, at);
630
+ if (k !== null) {
631
+ placed = chapterEntry(e, k);
632
+ break;
633
+ }
634
+ }
635
+ }
636
+ if (placed === null) {
637
+ // Keyed by the whole session id: two sessions never share an entry.
638
+ const key = `session ${session === null || session.length === 0 ? "unrecorded" : session}`;
639
+ placed = entries.get(key) ?? null;
640
+ if (placed === null) {
641
+ // A session that did write chapters, these moments under none of them
642
+ // (the chapters' moments unknown — an episode from before v12 — or a
643
+ // later write-up), is not a session that wrote none.
644
+ const unplaced = session !== null && bySession.has(session);
645
+ placed = {
646
+ key,
647
+ kind: "session",
648
+ episode: null,
649
+ chapter: null,
650
+ session,
651
+ unplaced,
652
+ at: at ?? Number.POSITIVE_INFINITY,
653
+ date: at === null ? emptyNull(h.row.learned_on) : localDay(at, zone),
654
+ hold: 0,
655
+ textHold: 0,
656
+ moments: [],
657
+ };
658
+ entries.set(key, placed);
659
+ }
660
+ if (at !== null && at < placed.at) {
661
+ placed.at = at;
662
+ placed.date = localDay(at, zone);
663
+ }
664
+ }
665
+ placed.moments.push(h);
666
+ placed.hold += feelingFilter !== null ? (feelingFilter.get(h.row.id) ?? 0) : h.weight;
667
+ }
668
+ // The chapters' own words (a card's terms, the question's words). Not on a
669
+ // feeling-filtered arc: a chapter that names the subject without the feeling
670
+ // is not where it was felt.
671
+ if (textMatch !== null && feelingFilter === null) {
672
+ for (const e of episodes) {
673
+ e.chapters.forEach((ch, i) => {
674
+ const n = textMatch(ch.text);
675
+ if (n > 0) {
676
+ const entry = chapterEntry(e, i + 1);
677
+ entry.textHold += n;
678
+ entry.hold += n;
679
+ }
680
+ });
681
+ }
682
+ } else if (feelingFilter === null) {
683
+ // No words to read a chapter by ("us", a feeling): a chapter copy the lens
684
+ // reached holds it in its episode's latest chapter (the copy's mark is the
685
+ // latest chapter's, `self/episodes.ts#EPISODE_ABOUT_META`).
686
+ const byId = new Map(episodes.map((e) => [e.id, e]));
687
+ for (const h of copies.values()) {
688
+ const e = byId.get(h.row.origin_ref ?? "");
689
+ if (e === undefined) continue;
690
+ const entry = chapterEntry(e, e.chapters.length);
691
+ entry.hold += h.weight;
692
+ }
693
+ }
694
+ // Time order; an entry nothing dates (at = +∞) goes last.
695
+ const all = [...entries.values()].filter((e) => e.hold > 0).sort((a, b) => (a.at === b.at ? 0 : a.at < b.at ? -1 : 1) || a.key.localeCompare(b.key));
696
+
697
+ // Feelings on the subject's moments, for the turns and the patterns.
698
+ const momentIds = all.flatMap((e) => e.moments.map((m) => m.row.id));
699
+ const feelingsAll = safe(() => store.feelingsOn(momentIds), new Map<string, (FeelingRow & { birth_day: number })[]>());
700
+ const marks = new Map<string, ("start" | "end" | "turn")[]>();
701
+ const mark = (key: string, m: "start" | "end" | "turn"): void => {
702
+ const list = marks.get(key) ?? [];
703
+ if (!list.includes(m)) list.push(m);
704
+ marks.set(key, list);
705
+ };
706
+ // A TURN (working default): the entry where the feelings' valence flips
707
+ // sign from the last entry that had a clear one.
708
+ let lastSign = 0;
709
+ for (const e of all) {
710
+ const fs = e.moments.flatMap((m) => feelingsAll.get(m.row.id) ?? []);
711
+ const sign = valenceSign(fs);
712
+ if (sign !== 0) {
713
+ if (lastSign !== 0 && sign !== lastSign) mark(e.key, "turn");
714
+ lastSign = sign;
715
+ }
716
+ }
717
+ const long = all.length > MEANING_CHAPTERS_SHOWN;
718
+ if (long) {
719
+ mark((all[0] as Entry).key, "start");
720
+ mark((all[all.length - 1] as Entry).key, "end");
721
+ }
722
+
723
+ // Ranked: on a long arc its start and end first, then the turns, then by
724
+ // how much each holds (the newer first on a tie). Shown in time order.
725
+ const ranked = long
726
+ ? [...all].sort((a, b) => {
727
+ const ra = rankOf(marks.get(a.key));
728
+ const rb = rankOf(marks.get(b.key));
729
+ if (ra !== rb) return ra - rb;
730
+ if (b.hold !== a.hold) return b.hold - a.hold;
731
+ return a.at === b.at ? 0 : b.at < a.at ? -1 : 1;
732
+ })
733
+ : all;
734
+ const pages = Math.max(1, Math.ceil(all.length / MEANING_CHAPTERS_SHOWN));
735
+ const onPage = new Set(ranked.slice((page - 1) * MEANING_CHAPTERS_SHOWN, page * MEANING_CHAPTERS_SHOWN).map((e) => e.key));
736
+ if (page > pages) notes.push(`page ${String(page)} is past the end: the arc has ${String(pages)} page${pages === 1 ? "" : "s"}`);
737
+
738
+ // ── 4. the entries shown, in full ─────────────────────────────────────────
739
+ const arc: MeaningArcLine[] = [];
740
+ let gap: Entry[] = [];
741
+ const flush = (): void => {
742
+ if (gap.length === 0) return;
743
+ arc.push({ fold: true, count: gap.length, from: (gap[0] as Entry).date, to: (gap[gap.length - 1] as Entry).date });
744
+ gap = [];
745
+ };
746
+ for (const e of all) {
747
+ if (!onPage.has(e.key)) {
748
+ gap.push(e);
749
+ continue;
750
+ }
751
+ flush();
752
+ arc.push({ fold: false, entry: showEntry(c, e, { usable, strengthOf, lineMatch, zone, feelingFilter, marks: marks.get(e.key) ?? [], day }) });
753
+ }
754
+ flush();
755
+ // A page past the end shows no entry, and so no fold either.
756
+ const shownArc = arc.some((l) => !l.fold) ? arc : [];
757
+
758
+ // ── 5. faded, readings, open, patterns ────────────────────────────────────
759
+ const faded = fadedIds
760
+ .map((id) => usable(id))
761
+ .filter((r): r is MemoryRow => r !== null)
762
+ .sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))
763
+ .map((r) => momentOf(r, zone));
764
+
765
+ const subjectSet = new Set([...momentList.map((h) => h.row.id), ...fadedIds, ...copies.keys()]);
766
+ const readingsAll = readingsFor(c, subjectSet, readingIds, usable, zone);
767
+ const openAll = openFor(c, [...momentList.map((h) => h.row.id), ...fadedIds], usable, today, zone);
768
+ const patterns = patternsOf(c, all, lens, feelingsAll, whose);
769
+
770
+ // ── 6. what makes the evidence thin ───────────────────────────────────────
771
+ const chapters = all.filter((e) => e.kind === "chapter");
772
+ const sessions = all.filter((e) => e.kind === "session");
773
+ const momentCount = all.reduce((n, e) => n + e.moments.length, 0);
774
+ if (lens !== null && all.length > 0) {
775
+ if (chapters.length === 0) {
776
+ notes.push(
777
+ sessions.some((e) => e.unplaced)
778
+ ? `no chapter holds it: ${plural(momentCount, "moment")} outside any chapter`
779
+ : `no chapter holds it: ${plural(momentCount, "moment")} from sessions that wrote none`,
780
+ );
781
+ }
782
+ else if (chapters.length <= 3) {
783
+ const dates = chapters.map((e) => e.date).filter((d): d is string => d !== null).sort();
784
+ const first = dates[0];
785
+ const last = dates[dates.length - 1];
786
+ if (chapters.length === 1) notes.push("one chapter");
787
+ else if (first !== undefined && last !== undefined && daysApart(first, last) <= 7) notes.push(`${plural(chapters.length, "chapter")}, all from one week`);
788
+ }
789
+ const feltAny = all.some((e) => e.moments.some((m) => (feelingsAll.get(m.row.id) ?? []).length > 0));
790
+ if (!feltAny) notes.push("no feelings recorded");
791
+ }
792
+
793
+ const result: MeaningResult = {
794
+ mode: "meaning",
795
+ reason: lens === null || (all.length === 0 && faded.length === 0 && readingsAll.length === 0 && openAll.length === 0) ? "nothing-came" : "answered",
796
+ semantic,
797
+ lens,
798
+ others: others.filter((o) => o.memories > 0),
799
+ feeling: feelingAsked && ask !== null ? { words: [...ask.named], whose: ask.whose === null ? null : whose[ask.whose] } : null,
800
+ counts: {
801
+ chapters: chapters.length,
802
+ sessions: sessions.length,
803
+ unplaced: sessions.filter((e) => e.unplaced).length,
804
+ moments: momentCount,
805
+ faded: faded.length,
806
+ readings: readingsAll.length,
807
+ open: openAll.length,
808
+ },
809
+ page,
810
+ pages,
811
+ arc: shownArc,
812
+ faded: faded.slice(0, MEANING_FADED_SHOWN),
813
+ readings: readingsAll.slice(-MEANING_READINGS_SHOWN),
814
+ open: openAll.slice(0, MEANING_OPEN_SHOWN),
815
+ patterns,
816
+ notes,
817
+ whose,
818
+ shown: [],
819
+ chars: 0,
820
+ trimmed: false,
821
+ };
822
+ return fit(result, opts.roomChars ?? MEANING_RESULT_CHARS);
823
+ }
824
+
825
+ // ── showing one entry ────────────────────────────────────────────────────────
826
+
827
+ function showEntry(
828
+ c: Counterpart,
829
+ e: Entry,
830
+ opts: {
831
+ usable: (id: string) => MemoryRow | null;
832
+ strengthOf: ReadonlyMap<string, number>;
833
+ lineMatch: readonly RegExp[];
834
+ zone: string | undefined;
835
+ feelingFilter: ReadonlyMap<string, number> | null;
836
+ marks: readonly ("start" | "end" | "turn")[];
837
+ day: number;
838
+ },
839
+ ): MeaningEntry {
840
+ const store = c.store;
841
+ // The subject's moments, the ones holding it most first, then the stronger.
842
+ const own = [...e.moments].sort(
843
+ (a, b) =>
844
+ (opts.feelingFilter?.get(b.row.id) ?? b.weight) - (opts.feelingFilter?.get(a.row.id) ?? a.weight) ||
845
+ (opts.strengthOf.get(b.row.id) ?? 0) - (opts.strengthOf.get(a.row.id) ?? 0) ||
846
+ (a.row.created_at ?? 0) - (b.row.created_at ?? 0),
847
+ );
848
+ // Chosen by how much they hold, shown in the order they were written.
849
+ let shown = own
850
+ .slice(0, MEANING_MOMENTS_PER_CHAPTER)
851
+ .sort((a, b) => (a.row.created_at ?? 0) - (b.row.created_at ?? 0) || a.row.id.localeCompare(b.row.id))
852
+ .map((h) => momentOf(h.row, opts.zone));
853
+ // Every memory the stretch wrote, for its feelings (and to fill a chapter
854
+ // that holds the subject by its words alone with two of its own moments).
855
+ let span: MemoryRow[] = [];
856
+ if (e.kind === "chapter" && e.episode !== null && e.session !== null && e.chapter !== null) {
857
+ const t = chapterTimesOf(store, e.episode.id);
858
+ if (t !== null) {
859
+ span = safe(() => store.memoriesOfSession(e.session as string), [])
860
+ .filter((m) => chapterAt(t, m.at) === e.chapter)
861
+ .map((m) => opts.usable(m.id))
862
+ .filter((r): r is MemoryRow => r !== null && !(r.source === "episode" && (r.origin_ref ?? "").startsWith("epi_")));
863
+ }
864
+ } else {
865
+ span = e.moments.map((h) => h.row);
866
+ }
867
+ if (own.length === 0 && span.length > 0) {
868
+ const have = new Set(shown.map((m) => m.id));
869
+ const extra = span
870
+ .filter((r) => !have.has(r.id))
871
+ .map((r) => ({ r, p: safe(() => store.physicsOf(r.id), null) }))
872
+ .filter((x): x is { r: MemoryRow; p: NonNullable<typeof x.p> } => x.p !== null && !isFaded(x.p, opts.day))
873
+ .map((x) => ({ r: x.r, s: strength(x.p, opts.day) }))
874
+ .sort((a, b) => b.s - a.s)
875
+ .slice(0, 2 - shown.length)
876
+ .map((x) => momentOf(x.r, opts.zone));
877
+ shown = [...shown, ...extra];
878
+ }
879
+ const ids = [...new Set([...span.map((r) => r.id), ...e.moments.map((h) => h.row.id)])];
880
+ const fs = [...safe(() => store.feelingsOn(ids), new Map<string, (FeelingRow & { birth_day: number })[]>()).values()].flat();
881
+ const ep = e.episode;
882
+ const text = ep !== null && e.chapter !== null ? (ep.chapters[e.chapter - 1]?.text ?? "") : "";
883
+ return {
884
+ address: e.key,
885
+ kind: e.kind,
886
+ unplaced: e.unplaced,
887
+ episodeId: ep?.id ?? null,
888
+ chapter: e.chapter,
889
+ of: ep?.chapters.length ?? null,
890
+ title: ep?.title ?? null,
891
+ date: e.date,
892
+ line: text.length === 0 ? "" : lineOf(text, opts.lineMatch, LINE_CHARS),
893
+ hold: round2(e.hold),
894
+ moments: shown,
895
+ momentCount: e.moments.length,
896
+ feelings: { self: topFeelings(fs, "self"), owner: topFeelings(fs, "owner") },
897
+ marks: opts.marks,
898
+ };
899
+ }
900
+
901
+ /** Faded: one rule for both question modes (`deliberate.ts#hasFaded`, decay × fade ≤ `FADED_RETAINED`). */
902
+ function isFaded(p: MemoryPhysics, day: number): boolean {
903
+ return hasFaded(p, day);
904
+ }
905
+
906
+ /** The strongest three distinct feeling words of one person. */
907
+ function topFeelings(fs: readonly FeelingRow[], who: FeelingWhose): MeaningFeeling[] {
908
+ const best = new Map<string, number>();
909
+ for (const f of fs) {
910
+ if (f.whose !== who) continue;
911
+ const word = feelingWord(f);
912
+ best.set(word, Math.max(best.get(word) ?? 0, f.strength));
913
+ }
914
+ return [...best]
915
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
916
+ .slice(0, 3)
917
+ .map(([word, s]) => ({ word, strength: round2(s) }));
918
+ }
919
+
920
+ /** A stamp's word as the wheel prints it, or the writer's own. */
921
+ function feelingWord(f: Pick<FeelingRow, "emotion" | "other_word">): string {
922
+ if (f.emotion === OTHER_EMOTION) return f.other_word ?? "other";
923
+ return wheelEntry(f.emotion)?.word ?? f.emotion.split(".").pop() ?? f.emotion;
924
+ }
925
+
926
+ /** −1, 0 or +1: the feelings' strength-weighted valence, with a dead band. */
927
+ function valenceSign(fs: readonly FeelingRow[]): number {
928
+ let sum = 0;
929
+ let weight = 0;
930
+ for (const f of fs) {
931
+ sum += f.strength * feelingValence(f);
932
+ weight += f.strength;
933
+ }
934
+ if (!(weight > 0)) return 0;
935
+ const v = sum / weight;
936
+ return v > 0.15 ? 1 : v < -0.15 ? -1 : 0;
937
+ }
938
+
939
+ function rankOf(m: readonly string[] | undefined): number {
940
+ if (m === undefined) return 3;
941
+ if (m.includes("start") || m.includes("end")) return 0;
942
+ if (m.includes("turn")) return 1;
943
+ return 3;
944
+ }
945
+
946
+ // ── readings, open, patterns ─────────────────────────────────────────────────
947
+
948
+ /**
949
+ * Dream gists and reflection entries that touched the subject — linked to it
950
+ * themselves, or citing one of its memories (a gist's `sources`, an entry's
951
+ * `cites`) — oldest first. The dream journal is not one of them.
952
+ */
953
+ function readingsFor(
954
+ c: Counterpart,
955
+ subject: ReadonlySet<string>,
956
+ linked: ReadonlySet<string>,
957
+ usable: (id: string) => MemoryRow | null,
958
+ zone: string | undefined,
959
+ ): MeaningReading[] {
960
+ const store = c.store;
961
+ const out = new Map<string, MemoryRow>();
962
+ for (const id of linked) {
963
+ const r = usable(id);
964
+ if (r !== null) out.set(id, r);
965
+ }
966
+ if (subject.size > 0) {
967
+ for (const source of ["dreamed", "reflection"] as const) {
968
+ for (const id of safe(() => store.list({ type: "memory", archived: false, source }), [] as string[])) {
969
+ if (out.has(id)) continue;
970
+ const r = usable(id);
971
+ if (r === null) continue;
972
+ const meta = parseMeta(r.meta);
973
+ const cited = source === "dreamed" ? meta["sources"] : meta["cites"];
974
+ if (Array.isArray(cited) && cited.some((x) => typeof x === "string" && subject.has(x))) out.set(id, r);
975
+ }
976
+ }
977
+ }
978
+ return [...out.values()]
979
+ .sort((a, b) => (a.created_at ?? 0) - (b.created_at ?? 0) || a.id.localeCompare(b.id))
980
+ .map((r) => ({
981
+ id: r.id,
982
+ by: r.source === "dreamed" ? ("dreamed" as const) : ("reflected" as const),
983
+ date: r.created_at === null ? r.learned_on : localDay(r.created_at, zone) ?? r.learned_on,
984
+ title: clip(oneLine(r.title ?? firstLine(r.body)), TITLE_CHARS),
985
+ excerpt: clip(oneLine(r.body), 160),
986
+ }));
987
+ }
988
+
989
+ /** The subject's open threads (`unresolved`) and its reminders dated today or later. Dated first, soonest first. */
990
+ function openFor(
991
+ c: Counterpart,
992
+ ids: readonly string[],
993
+ usable: (id: string) => MemoryRow | null,
994
+ today: string,
995
+ zone: string | undefined,
996
+ ): MeaningOpen[] {
997
+ const dated: (MeaningOpen & { sort: string })[] = [];
998
+ const open: (MeaningOpen & { at: number })[] = [];
999
+ for (const id of new Set(ids)) {
1000
+ const r = usable(id);
1001
+ if (r === null) continue;
1002
+ const title = clip(oneLine(r.title ?? firstLine(r.body)), TITLE_CHARS);
1003
+ // A REPEATING reminder (2026-10-09) is dated by its next occurrence — a
1004
+ // birthday stated in 1990 is still coming — and says how often.
1005
+ const meta = r.event_date !== null && isDay(r.event_date) ? parseMeta(r.meta) : null;
1006
+ const rule = meta === null ? null : meta[RECURRING_META];
1007
+ if (r.event_date !== null && isRecurrence(rule)) {
1008
+ const next = occurrenceOnOrAfter(r.event_date, rule, today);
1009
+ if (next !== null) {
1010
+ dated.push({ id, title, why: "dated", date: next.date, every: readableRecurrence(r.event_date, rule), sort: next.date });
1011
+ continue;
1012
+ }
1013
+ }
1014
+ if (r.event_date !== null && calendarOverlaps(r.event_date, today, "9999-12-31")) {
1015
+ dated.push({ id, title, why: "dated", date: r.event_date, sort: r.event_date });
1016
+ continue;
1017
+ }
1018
+ if (parseMeta(r.meta)[UNRESOLVED_META_KEY] === true) {
1019
+ open.push({ id, title, why: "open", date: r.created_at === null ? emptyNull(r.learned_on) : localDay(r.created_at, zone), at: r.created_at ?? 0 });
1020
+ }
1021
+ }
1022
+ dated.sort((a, b) => a.sort.localeCompare(b.sort) || a.id.localeCompare(b.id));
1023
+ open.sort((a, b) => b.at - a.at || a.id.localeCompare(b.id));
1024
+ return [...dated.map(({ sort: _s, ...x }) => x), ...open.map(({ at: _a, ...x }) => x)];
1025
+ }
1026
+
1027
+ /**
1028
+ * THE SIMPLE PATTERNS (the design's "likeliest to disappoint", first thing to
1029
+ * check at the revisit): other subjects named by the moments of several
1030
+ * entries, and feelings recorded in several, side by side. Several: 2 on an
1031
+ * arc of up to 5 entries, 3 past that; nothing on an arc of fewer than 3.
1032
+ */
1033
+ function patternsOf(
1034
+ c: Counterpart,
1035
+ all: readonly Entry[],
1036
+ lens: MeaningLens | null,
1037
+ feelings: ReadonlyMap<string, readonly FeelingRow[]>,
1038
+ whose: { readonly self: string; readonly owner: string },
1039
+ ): MeaningResult["patterns"] {
1040
+ const n = all.length;
1041
+ if (n < 3) return { subjects: [], feelings: [] };
1042
+ const min = n <= 5 ? 2 : 3;
1043
+ const subjectIn = new Map<string, Set<string>>();
1044
+ const feelingIn = new Map<string, Set<string>>();
1045
+ let looked = 0;
1046
+ for (const e of all) {
1047
+ for (const h of e.moments) {
1048
+ if (looked < 600) {
1049
+ looked += 1;
1050
+ for (const s of safe(() => c.store.subjectsOf(h.row.id), [] as string[])) {
1051
+ if (lens?.kind === "card" && s === lens.id) continue;
1052
+ const set = subjectIn.get(s) ?? new Set<string>();
1053
+ set.add(e.key);
1054
+ subjectIn.set(s, set);
1055
+ }
1056
+ }
1057
+ for (const f of feelings.get(h.row.id) ?? []) {
1058
+ const label = `${f.whose === "owner" ? whose.owner : whose.self} ${feelingWord(f)}`;
1059
+ const set = feelingIn.get(label) ?? new Set<string>();
1060
+ set.add(e.key);
1061
+ feelingIn.set(label, set);
1062
+ }
1063
+ }
1064
+ }
1065
+ const subjects = [...subjectIn]
1066
+ .filter(([, set]) => set.size >= min)
1067
+ .map(([id, set]) => ({ label: safe(() => c.schemas.entity(id)?.name ?? null, null), entries: set.size }))
1068
+ .filter((x): x is { label: string; entries: number } => x.label !== null)
1069
+ .sort((a, b) => b.entries - a.entries || a.label.localeCompare(b.label))
1070
+ .slice(0, MEANING_PATTERNS_SHOWN)
1071
+ .map((x) => ({ ...x, of: n }));
1072
+ const felt = [...feelingIn]
1073
+ .filter(([, set]) => set.size >= min)
1074
+ .map(([label, set]) => ({ label, entries: set.size, of: n }))
1075
+ .sort((a, b) => b.entries - a.entries || a.label.localeCompare(b.label))
1076
+ .slice(0, MEANING_PATTERNS_SHOWN);
1077
+ return { subjects, feelings: felt };
1078
+ }
1079
+
1080
+ // ── the fit ──────────────────────────────────────────────────────────────────
1081
+
1082
+ /**
1083
+ * Keep the rendered answer inside `MEANING_RESULT_CHARS`, trimming in a fixed
1084
+ * order — fewer moments per entry, shorter lines, fewer readings and open
1085
+ * items, no patterns, then entries off the page's ranked tail (each becomes
1086
+ * part of a fold) — and set `shown` to exactly what is printed.
1087
+ */
1088
+ function fit(r: MeaningResult, room: number): MeaningResult {
1089
+ const levels: ((x: MeaningResult) => MeaningResult)[] = [
1090
+ (x) => x,
1091
+ (x) => ({ ...x, arc: mapEntries(x.arc, (e) => ({ ...e, moments: e.moments.slice(0, 2), line: clip(e.line, 140) })) }),
1092
+ (x) => ({
1093
+ ...x,
1094
+ arc: mapEntries(x.arc, (e) => ({ ...e, moments: e.moments.slice(0, 1), line: clip(e.line, 100) })),
1095
+ readings: x.readings.slice(-2).map((g) => ({ ...g, excerpt: clip(g.excerpt, 80) })),
1096
+ faded: x.faded.slice(0, 2),
1097
+ open: x.open.slice(0, 3),
1098
+ }),
1099
+ (x) => ({ ...x, patterns: { subjects: [], feelings: [] }, others: x.others.slice(0, 2), arc: mapEntries(x.arc, (e) => ({ ...e, line: clip(e.line, 60) })) }),
1100
+ ];
1101
+ let cur = r;
1102
+ for (const level of levels) {
1103
+ cur = level(cur);
1104
+ const text = renderMeaning(cur);
1105
+ if (wireChars(text) <= room) return finish(cur, text, cur !== r);
1106
+ }
1107
+ // Still too big: drop entries from the page, the last-ranked first (an
1108
+ // entry's place in time stays a fold).
1109
+ let arc = cur.arc;
1110
+ while (arc.some((l) => !l.fold)) {
1111
+ const entries = arc.filter((l): l is { fold: false; entry: MeaningEntry } => !l.fold);
1112
+ const victim = [...entries].sort((a, b) => a.entry.hold - b.entry.hold)[0];
1113
+ if (victim === undefined) break;
1114
+ arc = refold(arc, victim.entry.address);
1115
+ cur = { ...cur, arc };
1116
+ const text = renderMeaning(cur);
1117
+ if (wireChars(text) <= room) return finish(cur, text, true);
1118
+ }
1119
+ cur = { ...cur, readings: [], open: [], faded: [], patterns: { subjects: [], feelings: [] } };
1120
+ return finish(cur, renderMeaning(cur), true);
1121
+ }
1122
+
1123
+ function finish(r: MeaningResult, text: string, trimmed: boolean): MeaningResult {
1124
+ const shown = new Set<string>();
1125
+ for (const l of r.arc) {
1126
+ if (l.fold) continue;
1127
+ if (l.entry.episodeId !== null) shown.add(l.entry.episodeId);
1128
+ for (const m of l.entry.moments) shown.add(m.id);
1129
+ }
1130
+ for (const m of r.faded) shown.add(m.id);
1131
+ for (const g of r.readings) shown.add(g.id);
1132
+ for (const o of r.open) shown.add(o.id);
1133
+ return { ...r, shown: [...shown], chars: wireChars(text), trimmed: r.trimmed || trimmed };
1134
+ }
1135
+
1136
+ function mapEntries(arc: readonly MeaningArcLine[], fn: (e: MeaningEntry) => MeaningEntry): MeaningArcLine[] {
1137
+ return arc.map((l) => (l.fold ? l : { fold: false, entry: fn(l.entry) }));
1138
+ }
1139
+
1140
+ /** The arc with one entry folded into its neighbours' folds. */
1141
+ function refold(arc: readonly MeaningArcLine[], address: string): MeaningArcLine[] {
1142
+ const out: MeaningArcLine[] = [];
1143
+ for (const l of arc) {
1144
+ const asFold: MeaningFold | null = l.fold ? l : l.entry.address === address ? { count: 1, from: l.entry.date, to: l.entry.date } : null;
1145
+ const prev = out[out.length - 1];
1146
+ if (asFold !== null && prev !== undefined && prev.fold) {
1147
+ out[out.length - 1] = { fold: true, count: prev.count + asFold.count, from: prev.from ?? asFold.from, to: asFold.to ?? prev.to };
1148
+ } else if (asFold !== null) {
1149
+ out.push({ fold: true, ...asFold });
1150
+ } else {
1151
+ out.push(l);
1152
+ }
1153
+ }
1154
+ return out;
1155
+ }
1156
+
1157
+ // ── the words ────────────────────────────────────────────────────────────────
1158
+
1159
+ /**
1160
+ * What the tool returns: labelled lines, not prose. The reader interprets;
1161
+ * nothing here says what the arc means.
1162
+ */
1163
+ export function renderMeaning(r: MeaningResult): string {
1164
+ const out: string[] = [];
1165
+ if (r.lens === null) {
1166
+ out.push("Nothing came: the question names no card, asks about no feeling, and none of its words reach a memory.");
1167
+ out.push("Try a person's or project's name, or facts mode for a single fact.");
1168
+ return out.join("\n");
1169
+ }
1170
+ const head = [r.lens.name];
1171
+ if (r.counts.chapters > 0) head.push(plural(r.counts.chapters, "chapter"));
1172
+ const chapterless = r.counts.sessions - r.counts.unplaced;
1173
+ if (chapterless > 0) head.push(`${plural(chapterless, "session")} with no chapter`);
1174
+ if (r.counts.unplaced > 0) head.push(`${plural(r.counts.unplaced, "session")} with moments outside its chapters`);
1175
+ head.push(`${plural(r.counts.moments, "moment")}${r.counts.faded > 0 ? ` (+${String(r.counts.faded)} faded)` : ""}`);
1176
+ out.push(head.join(" · "));
1177
+ if (r.feeling !== null) {
1178
+ out.push(`feeling asked: ${r.feeling.words.length > 0 ? r.feeling.words.join(", ") : "any"} · ${r.feeling.whose ?? "both of us"}`);
1179
+ }
1180
+ const total = r.counts.chapters + r.counts.sessions;
1181
+ if (r.pages > 1) {
1182
+ const showing = r.arc.filter((l) => !l.fold).length;
1183
+ out.push(
1184
+ `${plural(total, "entry", "entries")} · page ${String(r.page)} of ${String(r.pages)}, showing ${String(showing)}${r.page < r.pages ? ` → page ${String(r.page + 1)}` : ""}`,
1185
+ );
1186
+ }
1187
+ if (r.others.length > 0) {
1188
+ out.push(`also named: ${r.others.map((o) => `${o.name} (${plural(o.memories, "memory", "memories")})`).join(", ")} — ask about one by name for its arc`);
1189
+ }
1190
+ if (r.notes.length > 0) out.push(`note: ${r.notes.join("; ")}`);
1191
+ if (r.reason === "nothing-came") {
1192
+ out.push("Nothing holds it yet.");
1193
+ return out.join("\n");
1194
+ }
1195
+
1196
+ if (r.arc.length > 0) {
1197
+ out.push("");
1198
+ out.push("ARC (time order; a chapter opens by its episode id, a moment by its mem_ id)");
1199
+ for (const l of r.arc) {
1200
+ if (l.fold) {
1201
+ const span = l.from === null ? "" : l.to === null || l.to === l.from ? `, ${short(l.from)}` : `, ${short(l.from)} → ${short(l.to)}`;
1202
+ out.push(` · ${plural(l.count, r.page === 1 ? "quieter entry" : "entry", r.page === 1 ? "quieter entries" : "entries")} not shown here${span}`);
1203
+ continue;
1204
+ }
1205
+ const e = l.entry;
1206
+ const where =
1207
+ e.kind === "chapter"
1208
+ ? `${e.address}${e.of !== null && e.of > 1 ? ` (chapter ${String(e.chapter)} of ${String(e.of)})` : ""}${e.title !== null ? ` "${clip(oneLine(e.title), 60)}"` : ""}`
1209
+ : `${e.address} · ${e.unplaced ? "not under a chapter (its chapters' moments unknown, or written after the last)" : "no chapter written"}`;
1210
+ const flags = e.marks.length > 0 ? ` · ${e.marks.join(", ")}` : "";
1211
+ out.push(`${e.date === null ? "undated" : e.date} ${where}${flags}`);
1212
+ if (e.line.length > 0) out.push(` ${e.line}`);
1213
+ const mine = e.feelings.self.map((f) => `${f.word} ${num(f.strength)}`).join(", ");
1214
+ const theirs = e.feelings.owner.map((f) => `${f.word} ${num(f.strength)}`).join(", ");
1215
+ if (mine.length > 0 || theirs.length > 0) {
1216
+ const sides = [mine.length > 0 ? `${r.whose.self}: ${mine}` : null, theirs.length > 0 ? `${r.whose.owner}: ${theirs}` : null].filter((x) => x !== null);
1217
+ out.push(` feelings — ${sides.join(" | ")}`);
1218
+ }
1219
+ for (const m of e.moments) out.push(` ${m.id} ${m.title}`);
1220
+ if (e.momentCount > e.moments.length) out.push(` (+${String(e.momentCount - e.moments.length)} more of its moments hold it)`);
1221
+ }
1222
+ }
1223
+ if (r.faded.length > 0) {
1224
+ out.push("");
1225
+ out.push(`FADED (${String(r.counts.faded)}; still readable by id)`);
1226
+ for (const m of r.faded) out.push(` ${short(m.date)} ${m.id} ${m.title}`);
1227
+ }
1228
+ if (r.readings.length > 0) {
1229
+ out.push("");
1230
+ out.push(`EARLIER READINGS (${String(r.counts.readings)}${r.counts.readings > r.readings.length ? `, the newest ${String(r.readings.length)}` : ""})`);
1231
+ for (const g of r.readings) out.push(` ${short(g.date)} ${g.by} ${g.id} ${g.title} — ${g.excerpt}`);
1232
+ }
1233
+ if (r.open.length > 0) {
1234
+ out.push("");
1235
+ out.push(`STILL OPEN (${String(r.counts.open)})`);
1236
+ for (const o of r.open) out.push(` ${o.id} ${o.title} · ${o.why === "dated" ? `dated ${o.date ?? "?"}${o.every === undefined ? "" : `, ${o.every}`}` : `open since ${o.date === null ? "?" : short(o.date)}`}`);
1237
+ }
1238
+ if (r.patterns.subjects.length > 0 || r.patterns.feelings.length > 0) {
1239
+ out.push("");
1240
+ out.push("RECURRING (across entries of the arc)");
1241
+ if (r.patterns.subjects.length > 0) out.push(` with: ${r.patterns.subjects.map((p) => `${p.label} (${String(p.entries)} of ${String(p.of)})`).join(", ")}`);
1242
+ if (r.patterns.feelings.length > 0) out.push(` feelings: ${r.patterns.feelings.map((p) => `${p.label} (${String(p.entries)} of ${String(p.of)})`).join(", ")}`);
1243
+ }
1244
+ return out.join("\n");
1245
+ }
1246
+
1247
+ // ── small readers ────────────────────────────────────────────────────────────
1248
+
1249
+ /** Every live, readable episode: its session, title and chapters. Confidential ones are left out for a non-owner. */
1250
+ function episodeIndex(c: Counterpart, owner: boolean, denied: ReadonlySet<string>): EpisodeInfo[] {
1251
+ const store = c.store;
1252
+ const ids = safe(() => store.list({ type: "episode", archived: false }), [] as string[]).filter((id) => !denied.has(id));
1253
+ const copies = owner ? null : safe(() => store.copiesOf(ids), null);
1254
+ const out: EpisodeInfo[] = [];
1255
+ for (const id of ids) {
1256
+ try {
1257
+ const row = store.row(id);
1258
+ if (row === undefined || row.superseded_by !== null || row.body.length === 0) continue;
1259
+ // A store that will not say is read as confidential (`chaptersBySession`'s rule).
1260
+ if (!owner && (row.confidential === 1 || copies === null || (copies.get(id) ?? []).some((x) => x.confidential))) continue;
1261
+ let session = row.origin_session;
1262
+ if (session === null || session.length === 0) {
1263
+ const s = parseMeta(row.meta)["sessionId"];
1264
+ session = typeof s === "string" ? s : null;
1265
+ }
1266
+ out.push({
1267
+ id,
1268
+ session,
1269
+ title: row.title === null || row.title.trim().length === 0 ? null : row.title,
1270
+ createdAt: row.created_at ?? 0,
1271
+ chapters: chaptersOf(row.body),
1272
+ });
1273
+ } catch {
1274
+ continue;
1275
+ }
1276
+ }
1277
+ return out;
1278
+ }
1279
+
1280
+ /** A card's own terms, the ones it alone holds (a handle two cards hold names neither). */
1281
+ function cardTerms(c: Counterpart, id: string): string[] {
1282
+ try {
1283
+ const index = c.schemas.aliasIndex();
1284
+ const terms = index.termsFor(id);
1285
+ if (terms === undefined) return [];
1286
+ return [terms.name, ...terms.aliases].filter((t) => t.trim().length >= 2 && index.lookup(t).length === 1);
1287
+ } catch {
1288
+ return [];
1289
+ }
1290
+ }
1291
+
1292
+ /** Where a name sits in the question: what it is about, a plain mention, or an aside. */
1293
+ type Slot = "about" | "plain" | "aside";
1294
+ const SLOT_RANK: Readonly<Record<Slot, number>> = { about: 2, plain: 1, aside: 0 };
1295
+
1296
+ /**
1297
+ * How strongly one mention says the question is about its card (review of
1298
+ * #334). A name: twice its place's rank, plus one when it is typed as its card
1299
+ * writes it — so "will" for a card named Will, or "hope" for Hope, sits a step
1300
+ * under a name in the same place typed with its capital ("how will Driftwood
1301
+ * go" is Driftwood's, not Will's); in a question typed all in lower case every
1302
+ * name loses the same step and the grammar still decides. The owner's
1303
+ * pronoun asked about: under every name in a plain or about place (2 and up),
1304
+ * over every aside (1 at most) — "what have I done on Driftwood" is
1305
+ * Driftwood's, "how have I been since Driftwood" is his.
1306
+ */
1307
+ function mentionRank(m: { readonly slot: Slot; readonly pronoun: boolean; readonly lowered: boolean }): number {
1308
+ if (m.pronoun) return 1.5;
1309
+ return SLOT_RANK[m.slot] * 2 + (m.lowered ? 0 : 1);
1310
+ }
1311
+
1312
+ /**
1313
+ * WHICH CARD THE QUESTION IS ABOUT (2026-10-09). Deterministic; no model.
1314
+ *
1315
+ * 1. Each name the question gives a card is read in place: ABOUT when the
1316
+ * words just before it ask about it ("what has X been", "how has X
1317
+ * changed", "about X", `ABOUT_BEFORE`), an ASIDE when they say who it
1318
+ * matters to or since when ("been to Y", "since Y arrived"), plain
1319
+ * otherwise. A name joined to the one before it ("X and Y", "X, Y")
1320
+ * takes that one's place. A name typed in lower case where its card
1321
+ * writes a capital ("will" for Will) is a step under the same place
1322
+ * (`mentionRank`). A card's place is its best mention's.
1323
+ * 2. Of the cards with memories, those in the best place are the field. The
1324
+ * owner's own card leaves a field it shares — every memory here is his,
1325
+ * so the other one says more ("Rosalind's arc with Ilya").
1326
+ * 3. The first named wins the field; a longer name at the same spot, then
1327
+ * more memories, then the name, break a tie. More than one left in the
1328
+ * field is asked about alike, and `alike` names the rest so the answer
1329
+ * can say so.
1330
+ *
1331
+ * The owner's "I" — "you" in the counterpart's voice, as `feeling-ask.ts`
1332
+ * reads whose — names his card (by its id, not his name) where it sits in an
1333
+ * about place: "what have you been like", "how have I changed", "how have you
1334
+ * and Ilya been". It ranks under any card named in a plain or about place and
1335
+ * over an aside, so "what have I done on Driftwood" is still Driftwood's (as
1336
+ * it was before the pronoun counted) and "how have I been since Driftwood" is
1337
+ * his. Anywhere else a pronoun names nothing, so "do you remember
1338
+ * the budget" is still read by its words. Off (`ownerPronoun` null) for a
1339
+ * question about feeling, where the pronoun says whose feeling, and for "us".
1340
+ */
1341
+ function subjectOf(
1342
+ question: string,
1343
+ cards: readonly NamedCard[],
1344
+ o: {
1345
+ readonly terms: (id: string) => readonly string[];
1346
+ readonly ownerCard: string | null;
1347
+ readonly ownerPronoun: RegExp | null;
1348
+ readonly ownerCardOf: () => NamedCard | null;
1349
+ },
1350
+ ): { card: NamedCard | null; alike: readonly string[] } {
1351
+ const live = cards.filter((x) => x.ids.length > 0);
1352
+ // Every mention of every card, in the order they are named.
1353
+ const mentions: { card: NamedCard; at: number; end: number; slot: Slot; pronoun: boolean; lowered: boolean }[] = [];
1354
+ for (const card of live) {
1355
+ for (const term of o.terms(card.id)) {
1356
+ // Typed in lower case where the card writes a capital: "will" for Will.
1357
+ const capital = term !== term.toLowerCase();
1358
+ for (const m of question.matchAll(nameRegex(term, "giu"))) {
1359
+ const lowered = capital && m[0] === m[0].toLowerCase();
1360
+ mentions.push({ card, at: m.index, end: m.index + m[0].length, slot: slotAt(question, m.index), pronoun: false, lowered });
1361
+ }
1362
+ }
1363
+ }
1364
+ if (o.ownerCard !== null && o.ownerPronoun !== null) {
1365
+ const asked = [...question.matchAll(o.ownerPronoun)].filter((m) => slotAt(question, m.index) === "about");
1366
+ const own = asked.length === 0 ? null : (live.find((x) => x.id === o.ownerCard) ?? o.ownerCardOf());
1367
+ if (own !== null && own.ids.length > 0) {
1368
+ if (!live.includes(own)) live.push(own);
1369
+ for (const m of asked) {
1370
+ mentions.push({ card: own, at: m.index, end: m.index + m[0].length, slot: "about", pronoun: true, lowered: false });
1371
+ }
1372
+ }
1373
+ }
1374
+ if (live.length === 0) return { card: null, alike: [] };
1375
+ mentions.sort((a, b) => a.at - b.at || b.end - a.end);
1376
+ const kept: typeof mentions = [];
1377
+ for (const m of mentions) {
1378
+ const prev = kept[kept.length - 1];
1379
+ // A name inside a longer one ("Han" in "Han Seo") is not a mention of its own.
1380
+ if (prev !== undefined && m.at < prev.end) continue;
1381
+ // Joined to the owner's pronoun ("how have you and Ilya been"), a name
1382
+ // takes the place the grammar gives, not the pronoun's lower rank.
1383
+ if (prev !== undefined && JOINED.test(question.slice(prev.end, m.at))) m.slot = prev.slot;
1384
+ kept.push(m);
1385
+ }
1386
+ const place = new Map<string, { rank: number; at: number; length: number }>();
1387
+ for (const m of kept) {
1388
+ const had = place.get(m.card.id);
1389
+ const rank = mentionRank(m);
1390
+ if (had === undefined || rank > had.rank) place.set(m.card.id, { rank, at: m.at, length: m.end - m.at });
1391
+ }
1392
+ // A card named only inside another's longer name: the least of them.
1393
+ const placeOf = (x: NamedCard) => place.get(x.id) ?? { rank: -1, at: Number.POSITIVE_INFINITY, length: 0 };
1394
+ const best = Math.max(...live.map((x) => placeOf(x).rank));
1395
+ let field = live.filter((x) => placeOf(x).rank === best);
1396
+ if (field.length > 1 && o.ownerCard !== null) field = field.filter((x) => x.id !== o.ownerCard);
1397
+ field.sort((a, b) => {
1398
+ const pa = placeOf(a);
1399
+ const pb = placeOf(b);
1400
+ return pa.at - pb.at || pb.length - pa.length || b.ids.length - a.ids.length || a.name.localeCompare(b.name);
1401
+ });
1402
+ const [card, ...rest] = field;
1403
+ return { card: card ?? null, alike: rest.map((x) => x.name) };
1404
+ }
1405
+
1406
+ /** The place a name at `index` sits in: about, aside, or plain. */
1407
+ function slotAt(question: string, index: number): Slot {
1408
+ const before = question.slice(0, index);
1409
+ if (ABOUT_BEFORE.some((re) => re.test(before))) return "about";
1410
+ return ASIDE_BEFORE.test(before) ? "aside" : "plain";
1411
+ }
1412
+
1413
+ /** "A", "A and B", "A, B and C". */
1414
+ function andList(names: readonly string[]): string {
1415
+ if (names.length <= 1) return names.join("");
1416
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1] as string}`;
1417
+ }
1418
+
1419
+ /**
1420
+ * The question's words a topic is read by. `words` are lower-case tokens;
1421
+ * `names` maps the ones the asker CAPITALISED mid-sentence (a name or a
1422
+ * proper noun, `feeling-ask.ts#askedNames`) to a regex for the word as typed,
1423
+ * case kept; `shown` is the words as a header prints them.
1424
+ */
1425
+ interface TopicWords {
1426
+ readonly words: readonly string[];
1427
+ readonly names: ReadonlyMap<string, RegExp>;
1428
+ readonly shown: readonly string[];
1429
+ }
1430
+
1431
+ /**
1432
+ * The question's rarer words: not its frame, not a feeling word, not held by a
1433
+ * quarter of the store. A word the asker capitalised mid-sentence is kept
1434
+ * whatever it is ("what do I know about Will": lower-case "will" is frame, the
1435
+ * asker's Will is a name, as `feeling-ask.ts#askedNames` reads it), and is
1436
+ * matched as typed, case kept, so the modal "will" in a hundred memories does
1437
+ * not stand in for him (review of #323). `skip` leaves out more (a feeling
1438
+ * question's own frame).
1439
+ */
1440
+ function contentWords(
1441
+ c: Counterpart,
1442
+ question: string,
1443
+ minLen: number,
1444
+ feelingNamed: ReadonlySet<string>,
1445
+ skip: (w: string) => boolean = () => false,
1446
+ ): TopicWords {
1447
+ const proper = safe(() => askedNames(question), new Set<string>());
1448
+ const asTyped = new Map<string, string>();
1449
+ for (const m of question.matchAll(/[A-Za-z0-9][A-Za-z0-9'’]*/g)) {
1450
+ const tok = m[0].replace(/['’]s?$/, "");
1451
+ const low = tok.toLowerCase();
1452
+ if (proper.has(low) && /^[A-Z]/.test(tok) && !asTyped.has(low)) asTyped.set(low, tok);
1453
+ }
1454
+ const names = new Map<string, RegExp>();
1455
+ for (const [low, typed] of asTyped) names.set(low, nameRegex(typed, "gu"));
1456
+ const candidates = [...new Set(tokenize(question))].filter(
1457
+ (w) => !skip(w) && (names.has(w) || (w.length >= minLen && !FRAME.has(w) && !feelingNamed.has(w))),
1458
+ );
1459
+ const out = (words: string[]): TopicWords => ({ words, names, shown: words.map((w) => asTyped.get(w) ?? w) });
1460
+ if (candidates.length === 0) return out([]);
1461
+ const total = safe(() => c.store.countMemories({ archived: false }), 0);
1462
+ if (total < 20) return out(candidates);
1463
+ const df = safe(() => c.store.docFrequency(candidates), new Map<string, number>());
1464
+ return out(candidates.filter((w) => names.has(w) || (df.get(w) ?? 0) <= total * COMMON_SHARE));
1465
+ }
1466
+
1467
+ /** How many times `text` names the asker's capitalised word, case kept. */
1468
+ function namedCount(text: string, re: RegExp): number {
1469
+ re.lastIndex = 0;
1470
+ return (text.match(re) ?? []).length;
1471
+ }
1472
+
1473
+ /**
1474
+ * HOLD WHAT THE QUESTION'S WORDS REACH (BM25, `MEANING_WORDS_MAX`), and the
1475
+ * matchers a chapter's words and line are read by. A memory the search reached
1476
+ * only through a capitalised word must name it as typed: "Will" is not "will".
1477
+ * Returns how many memories it held.
1478
+ */
1479
+ function holdByWords(
1480
+ store: Counterpart["store"],
1481
+ topic: TopicWords,
1482
+ usable: (id: string) => MemoryRow | null,
1483
+ hold: (id: string, weight: number) => void,
1484
+ ): { textMatch: (text: string) => number; lineMatch: RegExp[]; held: number } {
1485
+ const words = topic.words;
1486
+ const plain = words.filter((w) => !topic.names.has(w));
1487
+ const hits = safe(() => store.search(words.join(" "), MEANING_WORDS_MAX), []).filter((h) => {
1488
+ if (topic.names.size === 0) return true;
1489
+ const row = usable(h.id);
1490
+ if (row === null) return false;
1491
+ const text = `${row.title ?? ""}\n${row.body}`;
1492
+ if ([...topic.names.values()].some((re) => namedCount(text, re) > 0)) return true;
1493
+ const have = new Set(tokenize(text));
1494
+ return plain.some((w) => have.has(w));
1495
+ });
1496
+ const top = hits[0]?.score ?? 0;
1497
+ let held = 0;
1498
+ for (const h of hits) {
1499
+ if (top > 0 && usable(h.id) !== null) {
1500
+ hold(h.id, h.score / top);
1501
+ held += 1;
1502
+ }
1503
+ }
1504
+ const need = Math.max(1, Math.ceil(words.length / 2));
1505
+ const textMatch = (text: string): number => {
1506
+ const have = new Set(tokenize(text));
1507
+ const n = words.filter((w) => {
1508
+ const re = topic.names.get(w);
1509
+ return re === undefined ? have.has(w) : namedCount(text, re) > 0;
1510
+ }).length;
1511
+ return n >= need ? n / words.length : 0;
1512
+ };
1513
+ const lineMatch = words.map((w) => {
1514
+ const re = topic.names.get(w);
1515
+ return re === undefined ? wholeWordRegex(w) : new RegExp(re.source, "u");
1516
+ });
1517
+ return { textMatch, lineMatch, held };
1518
+ }
1519
+
1520
+ function feelingName(named: ReadonlySet<string>, who: FeelingWhose | null, whose: { readonly self: string; readonly owner: string }): string {
1521
+ const words = [...named].filter((w) => w.length > 0);
1522
+ const what = words.length > 0 ? words.slice(0, 3).join(" / ") : "feelings";
1523
+ return who === null ? what : `${what} (${whose[who]})`;
1524
+ }
1525
+
1526
+ /** The owner's name as written on the identity core, or null. */
1527
+ function ownerDisplayName(c: Counterpart): string | null {
1528
+ const name = safe(() => identityCoreName(c.store), null);
1529
+ return name === null || name.length < 2 ? null : (name.split(/\s+/)[0] ?? null);
1530
+ }
1531
+
1532
+ function ownerNamesLower(c: Counterpart): string[] {
1533
+ const n = ownerDisplayName(c);
1534
+ return n === null ? [] : [n.toLowerCase()];
1535
+ }
1536
+
1537
+ function momentOf(r: MemoryRow, zone: string | undefined): MeaningMoment {
1538
+ return {
1539
+ id: r.id,
1540
+ title: clip(oneLine(r.title !== null && r.title.trim().length > 0 ? r.title : firstLine(r.body)), TITLE_CHARS),
1541
+ date: (r.created_at === null ? null : localDay(r.created_at, zone)) ?? r.learned_on,
1542
+ };
1543
+ }
1544
+
1545
+ /** A chapter's line: the first sentence a matcher finds, else its first; headings and markup off. */
1546
+ function lineOf(text: string, matchers: readonly RegExp[], max: number): string {
1547
+ const flat = oneLine(text.replace(/^#{1,6}[^\n]*$/gm, " ").replace(/[*_`>]+/g, ""));
1548
+ const sentences = flat.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
1549
+ const hit = sentences.find((s) => matchers.some((re) => re.test(s)));
1550
+ return clip(hit ?? sentences[0] ?? flat, max);
1551
+ }
1552
+
1553
+ function parseMeta(meta: string): Record<string, unknown> {
1554
+ try {
1555
+ const v = JSON.parse(meta || "{}") as unknown;
1556
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
1557
+ } catch {
1558
+ return {};
1559
+ }
1560
+ }
1561
+
1562
+ function localDay(at: number, zone: string | undefined): string | null {
1563
+ const d = localDate(at, zone);
1564
+ return d.length === 0 ? null : d;
1565
+ }
1566
+
1567
+ function emptyNull(s: string): string | null {
1568
+ return s.length === 0 ? null : s;
1569
+ }
1570
+
1571
+ function daysApart(a: string, b: string): number {
1572
+ return safe(() => Math.abs(daysBetween(a, b)), Number.POSITIVE_INFINITY);
1573
+ }
1574
+
1575
+ /** `MM-DD` for a whole day (the arc's own entries keep the year); ranges and months as written. */
1576
+ function short(ymd: string): string {
1577
+ return /^\d{4}-\d{2}-\d{2}$/.test(ymd) ? ymd.slice(5) : ymd;
1578
+ }
1579
+
1580
+ function firstLine(body: string): string {
1581
+ return body.split("\n").find((l) => l.trim().length > 0) ?? body;
1582
+ }
1583
+
1584
+ function oneLine(s: string): string {
1585
+ return s.replace(/\s+/g, " ").trim();
1586
+ }
1587
+
1588
+ function clip(s: string, max: number): string {
1589
+ return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
1590
+ }
1591
+
1592
+ function plural(n: number, one: string, many = `${one}s`): string {
1593
+ return `${String(n)} ${n === 1 ? one : many}`;
1594
+ }
1595
+
1596
+ function num(x: number): string {
1597
+ return x.toFixed(1).replace(/^0\./, ".");
1598
+ }
1599
+
1600
+ function round2(x: number): number {
1601
+ return Math.round(x * 100) / 100;
1602
+ }
1603
+
1604
+ function safe<T>(fn: () => T, fallback: T): T {
1605
+ try {
1606
+ return fn();
1607
+ } catch {
1608
+ return fallback;
1609
+ }
1610
+ }