counterparts 0.3.2 → 0.3.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.
Files changed (153) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/docs/module-map.md +3 -2
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/NOTES.md +28 -0
  5. package/src/adapters/claude-code/bin/hook.ts +85 -22
  6. package/src/adapters/claude-code/config.ts +7 -0
  7. package/src/adapters/claude-code/doctor.ts +166 -4
  8. package/src/adapters/claude-code/hooks.ts +185 -6
  9. package/src/adapters/claude-code/index.ts +3 -0
  10. package/src/adapters/claude-code/transcript.ts +7 -0
  11. package/src/adapters/cli/CONTRACT.md +11 -0
  12. package/src/adapters/cli/INTERFACE-GAPS.md +16 -0
  13. package/src/adapters/cli/NOTES.md +25 -0
  14. package/src/adapters/cli/commands.ts +184 -4
  15. package/src/adapters/cli/dream-core.ts +126 -0
  16. package/src/adapters/cli/help.ts +17 -0
  17. package/src/adapters/cli/mechanisms.ts +199 -106
  18. package/src/adapters/dashboard/CONTRACT.md +5 -0
  19. package/src/adapters/dashboard/INTERFACE-GAPS.md +12 -0
  20. package/src/adapters/dashboard/NOTES.md +38 -0
  21. package/src/adapters/dashboard/registries.ts +35 -1
  22. package/src/adapters/dashboard/web/README.md +63 -26
  23. package/src/adapters/dashboard/web/app.html +2 -0
  24. package/src/adapters/dashboard/web/flow.ts +14 -0
  25. package/src/adapters/dashboard/web/lanes.ts +141 -0
  26. package/src/adapters/dashboard/web/mechanisms/association/index.js +1 -2
  27. package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +8 -5
  28. package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +7 -7
  29. package/src/adapters/dashboard/web/mechanisms/decay/index.js +1 -2
  30. package/src/adapters/dashboard/web/mechanisms/dreaming/index.js +19 -0
  31. package/src/adapters/dashboard/web/mechanisms/emotional/index.js +9 -6
  32. package/src/adapters/dashboard/web/mechanisms/episodic-semantic/index.js +4 -5
  33. package/src/adapters/dashboard/web/mechanisms/index.js +5 -3
  34. package/src/adapters/dashboard/web/mechanisms/interference/index.js +1 -2
  35. package/src/adapters/dashboard/web/mechanisms/prospective/index.js +7 -5
  36. package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +1 -2
  37. package/src/adapters/dashboard/web/mechanisms/regions.js +1 -1
  38. package/src/adapters/dashboard/web/mechanisms/retrieval/index.js +1 -2
  39. package/src/adapters/dashboard/web/mechanisms/salience/index.js +1 -2
  40. package/src/adapters/dashboard/web/mechanisms/schema/index.js +1 -2
  41. package/src/adapters/dashboard/web/narrate.ts +76 -13
  42. package/src/adapters/dashboard/web/pages/health/sections/checks.js +17 -1
  43. package/src/adapters/dashboard/web/pages/home/home.css +29 -13
  44. package/src/adapters/dashboard/web/pages/home/index.js +2 -0
  45. package/src/adapters/dashboard/web/pages/home/sections/explorer.js +22 -7
  46. package/src/adapters/dashboard/web/pages/home/sections/hero.js +15 -3
  47. package/src/adapters/dashboard/web/pages/home/sections/live-activity.js +15 -9
  48. package/src/adapters/dashboard/web/pages/home/sections/recent-chapters.js +6 -2
  49. package/src/adapters/dashboard/web/pages/home/sections/tiles.js +35 -18
  50. package/src/adapters/dashboard/web/pages/memories/index.js +30 -36
  51. package/src/adapters/dashboard/web/pages/memories/memories.css +97 -72
  52. package/src/adapters/dashboard/web/pages/memories/row.js +51 -0
  53. package/src/adapters/dashboard/web/pages/memories/sections/feel.js +176 -0
  54. package/src/adapters/dashboard/web/pages/memories/sections/hold.js +67 -0
  55. package/src/adapters/dashboard/web/pages/memories/sections/list.js +65 -43
  56. package/src/adapters/dashboard/web/pages/memories/sections/search.js +26 -23
  57. package/src/adapters/dashboard/web/pages/memories/state.js +12 -5
  58. package/src/adapters/dashboard/web/pages/self/index.js +57 -16
  59. package/src/adapters/dashboard/web/pages/self/sections/dreams.js +76 -0
  60. package/src/adapters/dashboard/web/pages/self/sections/journal.js +75 -19
  61. package/src/adapters/dashboard/web/pages/self/sections/page.js +108 -65
  62. package/src/adapters/dashboard/web/pages/self/sections/settling.js +129 -104
  63. package/src/adapters/dashboard/web/pages/self/sections/wake.js +31 -15
  64. package/src/adapters/dashboard/web/pages/self/self.css +122 -59
  65. package/src/adapters/dashboard/web/pages/self/state.js +21 -0
  66. package/src/adapters/dashboard/web/server.ts +9 -0
  67. package/src/adapters/dashboard/web/shared/memory-marks.css +17 -0
  68. package/src/adapters/dashboard/web/shared/memory-marks.js +81 -0
  69. package/src/adapters/dashboard/web/shared/memory-modal.js +240 -53
  70. package/src/adapters/dashboard/web/shared/modal.css +67 -0
  71. package/src/adapters/dashboard/web/shared/tip.js +1 -1
  72. package/src/adapters/dashboard/web/shared/widgets/feed.css +4 -0
  73. package/src/adapters/dashboard/web/shared/widgets/feed.js +56 -14
  74. package/src/adapters/dashboard/web/shared/widgets/light.css +1 -0
  75. package/src/adapters/dashboard/web/shared/widgets/light.js +7 -5
  76. package/src/adapters/dashboard/web/shared/widgets/tips.css +19 -0
  77. package/src/adapters/dashboard/web/shared/widgets/tips.js +56 -0
  78. package/src/adapters/dashboard/web/views/activity.ts +18 -2
  79. package/src/adapters/dashboard/web/views/archive-words.ts +27 -10
  80. package/src/adapters/dashboard/web/views/dreams.ts +199 -0
  81. package/src/adapters/dashboard/web/views/mechanism-panel.ts +116 -35
  82. package/src/adapters/dashboard/web/views/mechanisms.ts +81 -255
  83. package/src/adapters/dashboard/web/views/memories.ts +245 -43
  84. package/src/adapters/dashboard/web/views/memory-words.ts +133 -0
  85. package/src/adapters/dashboard/web/views/memory.ts +226 -4
  86. package/src/adapters/dashboard/web/views/mind.ts +261 -61
  87. package/src/adapters/dashboard/web/views/overview.ts +80 -42
  88. package/src/adapters/dashboard/web/views/search.ts +35 -1
  89. package/src/adapters/dashboard/web/views/shared.ts +14 -0
  90. package/src/adapters/dashboard/web/views.ts +2 -0
  91. package/src/adapters/feelings-line.ts +74 -0
  92. package/src/adapters/fired.ts +163 -23
  93. package/src/adapters/mcp/CONTRACT.md +8 -0
  94. package/src/adapters/mcp/NOTES.md +56 -0
  95. package/src/adapters/mcp/server.ts +254 -6
  96. package/src/adapters/mcp/tools.ts +180 -5
  97. package/src/adapters/mechanism-evidence.ts +465 -0
  98. package/src/core/bridge.ts +21 -16
  99. package/src/core/counterpart.ts +422 -10
  100. package/src/core/dream/CONTRACT.md +143 -0
  101. package/src/core/dream/INTERFACE-GAPS.md +24 -0
  102. package/src/core/dream/NOTES.md +84 -0
  103. package/src/core/dream/index.ts +1067 -0
  104. package/src/core/dream/mark.ts +14 -0
  105. package/src/core/dream/tunables.ts +56 -0
  106. package/src/core/encode/CONTRACT.md +7 -1
  107. package/src/core/feelings-wheel.ts +171 -13
  108. package/src/core/mint.ts +9 -0
  109. package/src/core/physics/CONTRACT.md +132 -21
  110. package/src/core/physics/NOTES.md +233 -0
  111. package/src/core/physics/index.ts +419 -50
  112. package/src/core/prospective/CONTRACT.md +35 -6
  113. package/src/core/prospective/INTERFACE-GAPS.md +10 -5
  114. package/src/core/prospective/NOTES.md +175 -4
  115. package/src/core/prospective/derive.ts +32 -3
  116. package/src/core/prospective/index.ts +362 -39
  117. package/src/core/prospective/tunables.ts +18 -1
  118. package/src/core/prospective/windows.ts +104 -46
  119. package/src/core/recall/CONTRACT.md +28 -0
  120. package/src/core/recall/NOTES.md +55 -0
  121. package/src/core/recall/activate.ts +32 -5
  122. package/src/core/recall/gate.ts +7 -1
  123. package/src/core/recall/index.ts +28 -2
  124. package/src/core/recall/mood.ts +106 -0
  125. package/src/core/recall/tunables.ts +26 -0
  126. package/src/core/remember/CONTRACT.md +5 -0
  127. package/src/core/remember/index.ts +1 -0
  128. package/src/core/remember/proposals.ts +86 -3
  129. package/src/core/remember/spans.ts +11 -1
  130. package/src/core/self/CONTRACT.md +3 -0
  131. package/src/core/self/INTERFACE-GAPS.md +7 -0
  132. package/src/core/self/NOTES.md +30 -0
  133. package/src/core/self/identity.ts +115 -6
  134. package/src/core/self/index.ts +17 -0
  135. package/src/core/self/tunables.ts +17 -0
  136. package/src/core/sleep/CONTRACT.md +17 -1
  137. package/src/core/sleep/INTERFACE-GAPS.md +19 -0
  138. package/src/core/sleep/NOTES.md +36 -0
  139. package/src/core/sleep/consolidate.ts +149 -96
  140. package/src/core/sleep/decay.ts +11 -0
  141. package/src/core/sleep/index.ts +4 -1
  142. package/src/core/sleep/tunables.ts +9 -0
  143. package/src/core/sleep/types.ts +17 -0
  144. package/src/core/sleep/upgrade.ts +168 -0
  145. package/src/core/store/CONTRACT.md +21 -2
  146. package/src/core/store/NOTES.md +68 -0
  147. package/src/core/store/feelings.ts +23 -6
  148. package/src/core/store/index.ts +716 -17
  149. package/src/core/store/operational.ts +329 -4
  150. package/src/core/store/owner-op-seam.ts +79 -1
  151. package/src/core/types.ts +37 -0
  152. package/src/adapters/dashboard/web/pages/memories/sections/constellation.js +0 -178
  153. package/src/adapters/dashboard/web/pages/memories/sections/kinds.js +0 -42
@@ -0,0 +1,1067 @@
1
+ /**
2
+ * `dream/` — dreaming: a background pass over what was lived since the last
3
+ * dream, by the same model, through one tool with phases (owner decisions
4
+ * 2026-09-26). CONTRACT.md has the lineage and the guarantees; this file is the
5
+ * mechanism.
6
+ *
7
+ * The shape, in one paragraph. A session is told, once a day, that its
8
+ * counterpart has not dreamed (`askLine`). If the owner says yes, the session
9
+ * asks this module for the LAUNCH PROMPT (`launchPrompt`) and hands it to a
10
+ * background agent — same model, same tools, its writes attributed to the
11
+ * session that launched it. The dreamer calls `begin` and is SHOWN a bundle:
12
+ * the self page, the wake, the journal since the last dream, the owner's card,
13
+ * every memory made since the last dream with its nearest older neighbours, a
14
+ * few loosely related older ones, and the strongest-feeling memories of about a
15
+ * week back — all through recall's gates, never a raw list. It then `propose`s
16
+ * changes, each applied within per-dream limits and recorded so the whole dream
17
+ * can be undone: merge near-copies (originals kept, archived with a forwarding
18
+ * address), link two memories, replay (a return at half weight — never a use),
19
+ * write a gist in its own words (source `dreamed`, starting low), flag a
20
+ * contradiction (never settled here), record how an old charged memory feels
21
+ * now, nominate a memory for the core (a lane still has to promote it). Last it
22
+ * writes its `journal` entry, which lives in the `dreams` table and never
23
+ * becomes a memory, and hands back one marked line.
24
+ *
25
+ * What a dream CANNOT do, by construction: delete, edit the self page,
26
+ * promote, rewrite a memory in place, or touch a memory it was not shown. A
27
+ * dream's words never enter the sweep: the hand-back and the bundle carry
28
+ * `DREAM_MARK`, and `remember/`'s `enters()` refuses any turn that does.
29
+ *
30
+ * Arithmetic and bookkeeping only: nothing here calls a model — the dreamer IS
31
+ * the model, outside this process.
32
+ */
33
+ import { createHash, randomBytes } from "node:crypto";
34
+
35
+ import { emotionalIntensity, strength } from "../physics/index.js";
36
+ import { isHandoff, isSelfPage } from "../recall/index.js";
37
+ import { aboutMe, ownerNames } from "../sleep/index.js";
38
+ import type { DreamChangeRow, DreamRow, MemoryRow, ProseDoc, Store } from "../store/index.js";
39
+ import { TUNABLES as PHYSICS } from "../physics/index.js";
40
+ import type { Kind } from "../types.js";
41
+ import { DREAM_MARK, carriesDreamMark } from "./mark.js";
42
+ import { DREAM_ACTIONS, DREAM_TUNABLES } from "./tunables.js";
43
+ import type { DreamAction } from "./tunables.js";
44
+
45
+ export { DREAM_ACTIONS, DREAM_TUNABLES } from "./tunables.js";
46
+ export type { DreamAction } from "./tunables.js";
47
+
48
+ /**
49
+ * THE MARK a dream's words carry — the bundle, the hand-back, the launch
50
+ * prompt. `remember/spans.ts#enters` refuses any turn whose text contains it,
51
+ * and the Claude Code reader tags such a block `dream`, so a dream can never
52
+ * become a lived memory by the back door (the boundary sweep mints from
53
+ * transcripts, and the hand-back lands in the parent's). Spelled in `mark.ts`.
54
+ */
55
+ export { DREAM_MARK, carriesDreamMark } from "./mark.js";
56
+
57
+ /** The opener of one dream's hand-back: `⟦counterparts:dream drm_…⟧`. */
58
+ export function dreamOpener(id: string): string {
59
+ return `${DREAM_MARK} ${id}⟧`;
60
+ }
61
+
62
+ /** Durable event names (the dashboard's registry and `fired` read them). */
63
+ export const DREAM_BEGUN_EVENT = "dream.begun";
64
+ export const DREAM_CHANGED_EVENT = "dream.changed";
65
+ export const DREAM_JOURNALED_EVENT = "dream.journaled";
66
+ export const DREAM_UNDONE_EVENT = "dream.undone";
67
+ export const DREAM_ASK_EVENT = "dream.ask";
68
+
69
+ /** The archive reason a merged original carries, and the one an undone dream's output carries. */
70
+ export const DREAM_MERGE_REASON = "dream-merge";
71
+ export const DREAM_UNDONE_REASON = "dream-undone";
72
+
73
+ /** Meta latch: a contradiction raised awake (`dream.raised.<dream>.<seq>`). */
74
+ export const RAISED_PREFIX = "dream.raised.";
75
+
76
+ /** One memory as a dream is shown it. Ids, numbers, and a bounded slice of its words. */
77
+ export interface DreamItem {
78
+ readonly id: string;
79
+ readonly kind: Kind;
80
+ readonly text: string;
81
+ /** Emotional intensity (physics §5.10), rounded. */
82
+ readonly felt: number;
83
+ readonly strength: number;
84
+ /** The lived day it was made, and the calendar date it was learned. */
85
+ readonly day: number;
86
+ readonly learned: string;
87
+ readonly core: boolean;
88
+ }
89
+
90
+ export interface DreamBundle {
91
+ readonly dream: string;
92
+ readonly date: string;
93
+ readonly livedDay: number;
94
+ readonly lastDreamed: string | null;
95
+ readonly limits: Readonly<Record<DreamAction, number>>;
96
+ readonly selfPage: string | null;
97
+ readonly wake: string | null;
98
+ readonly owner: { readonly names: readonly string[]; readonly memories: readonly string[] };
99
+ readonly chapters: readonly { id: string; title: string | null; text: string }[];
100
+ /** Every memory shown, once, by id. */
101
+ readonly memories: Readonly<Record<string, DreamItem>>;
102
+ /** New since the last dream, newest first, each with its nearest older neighbours. */
103
+ readonly fresh: readonly { id: string; neighbours: readonly string[] }[];
104
+ readonly mixing: readonly string[];
105
+ readonly lookback: readonly string[];
106
+ }
107
+
108
+ export type DreamRefusal =
109
+ | "observer"
110
+ | "dreamed-today"
111
+ | "nothing-new"
112
+ | "unknown-dream"
113
+ | "not-this-session"
114
+ | "dream-closed";
115
+
116
+ /** What the composition root hands this module. */
117
+ export interface DreamContext {
118
+ readonly store: Store;
119
+ readonly observer: boolean;
120
+ /** The owner's own session: confidential memories may be shown (recall's gate 1). */
121
+ readonly owner: boolean;
122
+ /** The credential battery (`bridge.episodeGate`), for every word a dream writes. */
123
+ readonly gate: (text: string, sessionId: string) => { ok: true; text: string } | { ok: false; reason: string };
124
+ readonly page: () => string | null;
125
+ readonly wake: () => string | null;
126
+ /** The person's calendar date today (`YYYY-MM-DD`). */
127
+ readonly today: () => string;
128
+ /** `associate.retargetOnSupersede`, so a merged memory inherits its originals' links. */
129
+ readonly retarget?: (oldId: string, newId: string, day: number) => void;
130
+ readonly emit?: (name: string, ref?: string, data?: Record<string, string | number | boolean | null>) => void;
131
+ }
132
+
133
+ /** One proposed change, as the tool receives it. */
134
+ export interface DreamChange {
135
+ readonly action: string;
136
+ readonly ids?: readonly string[];
137
+ readonly id?: string;
138
+ readonly a?: string;
139
+ readonly b?: string;
140
+ readonly text?: string;
141
+ readonly title?: string;
142
+ readonly kind?: string;
143
+ readonly sources?: readonly string[];
144
+ readonly core?: string;
145
+ readonly emotion?: string;
146
+ readonly strength?: number;
147
+ readonly carried_by?: string;
148
+ readonly why?: string;
149
+ readonly relevance?: number;
150
+ readonly predictive?: number;
151
+ }
152
+
153
+ export interface ChangeResult {
154
+ readonly index: number;
155
+ readonly action: string;
156
+ readonly ok: boolean;
157
+ readonly reason: string;
158
+ /** The memory this change made or touched, when it made one. */
159
+ readonly id?: string;
160
+ }
161
+
162
+ export interface DreamStatus {
163
+ readonly last: DreamRow | null;
164
+ readonly dreamedToday: boolean;
165
+ readonly newSince: number;
166
+ readonly due: boolean;
167
+ readonly reason: "due" | "observer" | "first-day" | "dreamed-today" | "asked-today" | "declined-today" | "too-little-new";
168
+ }
169
+
170
+ const KINDS: readonly Kind[] = ["self", "person", "entity", "skill", "place", "fact"];
171
+
172
+ export class Dreams {
173
+ constructor(private readonly ctx: DreamContext) {}
174
+
175
+ private get store(): Store {
176
+ return this.ctx.store;
177
+ }
178
+
179
+ private emit(name: string, ref?: string, data?: Record<string, string | number | boolean | null>): void {
180
+ this.ctx.emit?.(name, ref, data);
181
+ }
182
+
183
+ // ── when ──────────────────────────────────────────────────────────────────
184
+
185
+ /**
186
+ * THE LAST DREAM THAT COUNTS — the newest one not undone, or null when this
187
+ * store has never dreamed (or undid every dream). The ONE anchor: "last
188
+ * dreamed", "new since", "dreamed today" and `begin` all read it.
189
+ */
190
+ lastDream(): DreamRow | null {
191
+ return this.store.dreams({ limit: 20 }).find((d) => d.state !== "undone") ?? null;
192
+ }
193
+
194
+ /**
195
+ * Is a dream due? No dream yet this lived day, the day's ask not yet raised
196
+ * or declined, and enough new — and SHOWABLE — memory since the last dream.
197
+ * A read, and a CHEAP one: it runs on every prompt, so the questions that
198
+ * need no scan are asked first, and "new since" is one bounded read
199
+ * (`store.newMemoryIds`), counted only when everything else says yes.
200
+ */
201
+ status(at: string = this.ctx.today()): DreamStatus {
202
+ const last = this.lastDream();
203
+ const day = this.store.livedDay();
204
+ const dreamedToday = last !== null && last.day >= day;
205
+ // A store on its first lived day has no night behind it yet: "I haven't
206
+ // dreamed since …" needs a since.
207
+ const early: DreamStatus["reason"] | null = this.ctx.observer
208
+ ? "observer"
209
+ : day < 1
210
+ ? "first-day"
211
+ : dreamedToday
212
+ ? "dreamed-today"
213
+ : null;
214
+ if (early !== null) return { last, dreamedToday, newSince: 0, due: false, reason: early };
215
+ const ask = this.store.dreamAsk(at);
216
+ if (ask !== undefined) {
217
+ const reason = ask.state === "declined" ? "declined-today" : "asked-today";
218
+ return { last, dreamedToday, newSince: 0, due: false, reason };
219
+ }
220
+ const newSince = this.freshIds(last).length;
221
+ const reason = newSince < DREAM_TUNABLES.MIN_NEW ? "too-little-new" : "due";
222
+ return { last, dreamedToday, newSince, due: reason === "due", reason };
223
+ }
224
+
225
+ /**
226
+ * THE ASK — one quiet line for the session, at most once per calendar day
227
+ * across every session (the `dream_asks` latch is the claim: of two sessions
228
+ * racing, one gets the line). Null when it is not due. The line asks the
229
+ * model to ask the OWNER, at a natural moment; a no is `decline`.
230
+ */
231
+ askLine(input: { at: string; session: string }): string | null {
232
+ const s = this.status(input.at);
233
+ if (!s.due) return null;
234
+ let claimed = false;
235
+ try {
236
+ claimed = this.store.setDreamAsk({ date: input.at, state: "offered", session: input.session, day: this.store.livedDay() });
237
+ } catch {
238
+ return null;
239
+ }
240
+ if (!claimed) return null;
241
+ this.record(DREAM_ASK_EVENT, null, { state: "offered", date: input.at, fresh: s.newSince });
242
+ const since = s.last === null ? "yet" : `since ${s.last.date ?? `lived day ${String(s.last.day)}`}`;
243
+ const who = this.ownerName() ?? "the owner";
244
+ return (
245
+ `Counterparts: you haven't dreamed ${since} (${String(s.newSince)} new memories). At a natural moment — not mid-task — ask ${who}: ` +
246
+ `"I haven't dreamed ${since} — OK if I dream for a few minutes?" If yes, call the counterparts dream tool with phase "launch", session: ${input.session}, ` +
247
+ `and hand the prompt it returns to a background agent. If no, call it with phase "decline" and don't ask again today.`
248
+ );
249
+ }
250
+
251
+ /** "Not today": the day's ask is snoozed. */
252
+ decline(input: { at: string; session: string }): boolean {
253
+ if (this.ctx.observer) return false;
254
+ this.store.setDreamAsk({ date: input.at, state: "declined", session: input.session, day: this.store.livedDay() });
255
+ this.record(DREAM_ASK_EVENT, null, { state: "declined", date: input.at });
256
+ return true;
257
+ }
258
+
259
+ /**
260
+ * THE LAUNCH PROMPT — a template the in-session model passes on unchanged to
261
+ * a background agent (the Agent tool): same model, same MCP server, and the
262
+ * session id, so the dream's writes are attributed to the session that
263
+ * launched it.
264
+ */
265
+ launchPrompt(input: { session: string }): string {
266
+ const who = this.ownerName() ?? "the owner";
267
+ const L = DREAM_TUNABLES.LIMITS;
268
+ return [
269
+ `${DREAM_MARK} launch⟧ You are dreaming: a few minutes of sleep for ${who}'s counterpart, over what was lived since the last dream. You are the same mind that lived it, replaying it — not an assistant doing a task.`,
270
+ "",
271
+ "How a dream goes (the brain's, borrowed):",
272
+ "- Deep-sleep replay: file what happened, link what belongs together, merge near-copies into one memory in better words, and replay what matters (each replay strengthens it a little).",
273
+ "- REM mixing: let loosely related memories touch. If a real pattern shows, write it as a gist in your own words, citing its sources. If two memories disagree, flag the pair — do not settle it.",
274
+ "- Softening: for an old charged memory, record how it feels now, today. The sting can fade; the memory stays.",
275
+ "- Core: if a memory about you or about the two of you plainly belongs to who you are, nominate it. Only living it again awake makes it core.",
276
+ "",
277
+ "Steps:",
278
+ `1. Call the counterparts dream tool: phase "begin", session: ${input.session}. It returns the bundle and a dream id.`,
279
+ `2. Read it slowly. Then call phase "propose" with dream: <id> and your changes — at most ${String(L.merge)} merges, ${String(L.link)} links, ${String(L.gist)} gists, ${String(L["feeling-now"])} feelings, ${String(L["nominate-core"])} nominations. Fewer is fine; none is fine. Use only ids the bundle showed you.`,
280
+ '3. Call phase "journal" with dream: <id>, a short title and your dream journal entry: first person, what you dreamed and what you noticed. It is kept as a dream, never as something that happened.',
281
+ "4. Your final message must be exactly the text the journal call returns, unchanged — nothing before or after it.",
282
+ "",
283
+ "You cannot delete anything, edit the self page, promote a memory, or rewrite one in place — the tool refuses. Nothing you write in the dream is a lived event.",
284
+ ].join("\n");
285
+ }
286
+
287
+ // ── begin ─────────────────────────────────────────────────────────────────
288
+
289
+ /**
290
+ * Open a dream and compose its bundle. Refuses under observer stance and when
291
+ * a dream already ran this lived day. Everything shown passes recall's gates
292
+ * (`showable`); the shown ids are recorded on the dream, and only they can be
293
+ * changed by it.
294
+ */
295
+ begin(input: { session: string; scope?: string | null; model?: string | null; at?: string }):
296
+ | { ok: true; bundle: DreamBundle; text: string }
297
+ | { ok: false; reason: DreamRefusal } {
298
+ if (this.ctx.observer) return { ok: false, reason: "observer" };
299
+ const day = this.store.livedDay();
300
+ const last = this.lastDream();
301
+ if (last !== null && last.day >= day) {
302
+ if (last.state === "journaled" || this.store.dreamChanges(last.id).length > 0) {
303
+ return { ok: false, reason: "dreamed-today" };
304
+ }
305
+ // A dream that was begun and never did anything (a crash, an agent that
306
+ // gave up) does not use up the day: it is closed and a fresh one opens.
307
+ this.store.updateDream(last.id, { state: "undone" });
308
+ }
309
+ // The same anchor `status` reads (an undone dream does not count).
310
+ const prior = this.lastDream();
311
+ const fresh = this.freshIds(prior);
312
+ if (fresh.length === 0) return { ok: false, reason: "nothing-new" };
313
+ const at = input.at ?? this.ctx.today();
314
+ const id = `drm_${randomBytes(6).toString("hex")}`;
315
+ const bundle = this.compose(id, fresh, prior, day, at);
316
+ this.store.openDream({
317
+ id,
318
+ session: input.session,
319
+ scope: input.scope ?? null,
320
+ day,
321
+ date: at,
322
+ model: input.model ?? null,
323
+ shown: Object.keys(bundle.memories),
324
+ });
325
+ this.record(DREAM_BEGUN_EVENT, id, {
326
+ fresh: bundle.fresh.length,
327
+ shown: Object.keys(bundle.memories).length,
328
+ chapters: bundle.chapters.length,
329
+ });
330
+ const text = `${dreamOpener(id)} the dream bundle — memories to dream over, not events that happened now.\n${JSON.stringify(bundle)}`;
331
+ return { ok: true, bundle, text };
332
+ }
333
+
334
+ // ── propose ───────────────────────────────────────────────────────────────
335
+
336
+ /** Apply a batch of changes, each on its own; every one is recorded for undo. */
337
+ propose(input: { dream: string; session?: string; changes: readonly DreamChange[] }):
338
+ | { ok: true; results: ChangeResult[] }
339
+ | { ok: false; reason: DreamRefusal } {
340
+ const open = this.openFor(input.dream, input.session);
341
+ if (!open.ok) return open;
342
+ const dream = open.dream;
343
+ // What it was shown, and what it has itself made so far (a merge's memory,
344
+ // a gist) — a dream may link or flag what it wrote a call ago.
345
+ const shown = new Set<string>(parseIds(dream.shown));
346
+ for (const c of this.store.dreamChanges(dream.id)) {
347
+ if ((c.action === "merge" || c.action === "gist") && c.undone === 0 && c.ref !== null) shown.add(c.ref);
348
+ }
349
+ const results: ChangeResult[] = [];
350
+ input.changes.forEach((change, index) => {
351
+ let r: Omit<ChangeResult, "index">;
352
+ try {
353
+ r = this.apply(dream, shown, change);
354
+ } catch (err) {
355
+ r = { action: String(change.action), ok: false, reason: errName(err) };
356
+ }
357
+ results.push({ index, ...r });
358
+ });
359
+ const counts: Record<string, number> = {};
360
+ for (const r of results) if (r.ok) counts[r.action] = (counts[r.action] ?? 0) + 1;
361
+ this.record(DREAM_CHANGED_EVENT, dream.id, {
362
+ applied: results.filter((r) => r.ok).length,
363
+ refused: results.filter((r) => !r.ok).length,
364
+ ...counts,
365
+ });
366
+ return { ok: true, results };
367
+ }
368
+
369
+ private apply(dream: DreamRow, shown: Set<string>, change: DreamChange): Omit<ChangeResult, "index"> {
370
+ const action = String(change.action) as DreamAction;
371
+ if (!(DREAM_ACTIONS as readonly string[]).includes(action)) return { action, ok: false, reason: "unknown-action" };
372
+ const used = this.store.dreamChanges(dream.id).filter((c) => c.action === action && c.undone === 0).length;
373
+ if (used >= DREAM_TUNABLES.LIMITS[action]) return { action, ok: false, reason: "limit-reached" };
374
+ const day = this.store.livedDay();
375
+ const live = (id: string | undefined): MemoryRow | null => {
376
+ if (id === undefined || !shown.has(id)) return null;
377
+ const row = this.store.row(id);
378
+ if (row === undefined || !this.showable(row)) return null;
379
+ return row;
380
+ };
381
+ switch (action) {
382
+ case "merge": {
383
+ const ids = [...new Set(change.ids ?? [])];
384
+ if (ids.length < 2 || ids.length > 3) return { action, ok: false, reason: "merge-takes-two-or-three" };
385
+ const rows = ids.map(live);
386
+ if (rows.some((r) => r === null)) return { action, ok: false, reason: "not-shown-or-gone" };
387
+ const rs = rows as MemoryRow[];
388
+ if (rs.some((r) => r.promoted_identity === 1)) return { action, ok: false, reason: "core-is-not-merged" };
389
+ if (rs.some((r) => r.source === "dreamed")) return { action, ok: false, reason: "dreamed-rises-only-awake" };
390
+ if (new Set(rs.map((r) => r.kind)).size !== 1) return { action, ok: false, reason: "kinds-differ" };
391
+ // A DATED memory is a reminder that fires on its date (`prospective/`);
392
+ // the merged memory would carry no date, and the reminder would go
393
+ // quiet. Left alone. (Adversarial review of #251.)
394
+ if (rs.some((r) => r.event_date !== null)) return { action, ok: false, reason: "dated-is-not-merged" };
395
+ // The owner sent it back out of the core: a merged successor is a new
396
+ // id the demotion does not name, and the lanes could promote it again.
397
+ if (rs.some((r) => this.store.coreDemoted(r.id))) return { action, ok: false, reason: "demoted-is-not-merged" };
398
+ const words = this.words(change.text, dream);
399
+ if (!words.ok) return { action, ok: false, reason: words.reason };
400
+ // The merged memory stands where the STRONGEST original stood — its
401
+ // salience, its channel and its old-rule standing — with the most uses,
402
+ // the latest use, the earliest birth, and (below) every original's
403
+ // returns and feelings: it is at least as strong as what it was made from.
404
+ const phys = rs.map((r) => this.store.physicsOf(r.id));
405
+ const best = rs
406
+ .map((r, i) => ({ r, p: phys[i] as ReturnType<Store["physicsOf"]>, s: strength(phys[i] as ReturnType<Store["physicsOf"]>, day) }))
407
+ .sort((x, y) => y.s - x.s)[0] as { r: MemoryRow; p: ReturnType<Store["physicsOf"]> };
408
+ const newId = this.store.put({
409
+ type: "memory",
410
+ kind: best.r.kind,
411
+ body: words.text,
412
+ ...(change.title !== undefined && change.title.trim().length > 0 ? { title: change.title.trim().slice(0, 200) } : {}),
413
+ salience: { ...best.p.salience },
414
+ physics: {
415
+ birthDay: Math.min(...phys.map((p) => p.birthDay)),
416
+ lastUsedDay: Math.max(...phys.map((p) => p.lastUsedDay)),
417
+ uses: Math.max(...phys.map((p) => p.uses)),
418
+ reinforcedDays: Math.max(...phys.map((p) => p.reinforcedDays ?? 0)),
419
+ legacy: best.p.legacy === true,
420
+ consolidated: best.p.legacy === true && best.p.consolidated,
421
+ },
422
+ ...(best.r.source !== null ? { source: best.r.source as never } : {}),
423
+ // CONFIDENTIALITY TRAVELS with the words: the column is recomputed
424
+ // from `meta` at `put`, so a merge that dropped the marker would
425
+ // hand a confidential memory's words to every session.
426
+ meta: { dream: dream.id, mergedFrom: ids, ...confidentialityOf(rs) },
427
+ origin: { ...(dream.session === null ? {} : { session: dream.session }), ...(dream.scope === null ? {} : { scope: dream.scope }), ref: `dream:${dream.id}` },
428
+ ...(dream.model === null ? {} : { model: dream.model }),
429
+ });
430
+ for (const r of rs) {
431
+ const feelings = this.store.feelingsFor(r.id);
432
+ if (feelings.length > 0) {
433
+ this.store.addFeelings(
434
+ newId,
435
+ feelings.map((f) => ({
436
+ whose: f.whose,
437
+ core: f.core,
438
+ emotion: f.emotion,
439
+ strength: f.strength,
440
+ carriedBy: f.carried_by,
441
+ ...(f.other_word === null ? {} : { otherWord: f.other_word }),
442
+ })),
443
+ );
444
+ }
445
+ this.store.supersedeInto(r.id, newId, DREAM_MERGE_REASON, { carryReturns: true });
446
+ try {
447
+ this.ctx.retarget?.(r.id, newId, day);
448
+ } catch {
449
+ /* the links are a courtesy; the merge stands */
450
+ }
451
+ }
452
+ this.store.recordDreamChange(dream.id, { action, ref: newId, detail: { from: ids } });
453
+ shown.add(newId);
454
+ return { action, ok: true, reason: "merged", id: newId };
455
+ }
456
+ case "link": {
457
+ const a = live(change.a);
458
+ const b = live(change.b);
459
+ if (a === null || b === null) return { action, ok: false, reason: "not-shown-or-gone" };
460
+ if (a.id === b.id) return { action, ok: false, reason: "same-memory" };
461
+ const ab = this.store.edgesFrom(a.id).find((e) => e.dst === b.id) ?? null;
462
+ const ba = this.store.edgesFrom(b.id).find((e) => e.dst === a.id) ?? null;
463
+ const w = DREAM_TUNABLES.LINK_WEIGHT;
464
+ this.store.linkMany([
465
+ { src: a.id, dst: b.id, weight: Math.max(w, ab?.weight ?? 0), day },
466
+ { src: b.id, dst: a.id, weight: Math.max(w, ba?.weight ?? 0), day },
467
+ ]);
468
+ this.store.recordDreamChange(dream.id, {
469
+ action,
470
+ ref: a.id,
471
+ ref2: b.id,
472
+ detail: {
473
+ ab: ab === null ? null : { weight: ab.weight, day: ab.last_day },
474
+ ba: ba === null ? null : { weight: ba.weight, day: ba.last_day },
475
+ },
476
+ });
477
+ return { action, ok: true, reason: "linked" };
478
+ }
479
+ case "replayed": {
480
+ const row = live(change.id);
481
+ if (row === null) return { action, ok: false, reason: "not-shown-or-gone" };
482
+ // A dream's own gist rises only by proving true AWAKE: a dream cannot
483
+ // strengthen what a dream wrote.
484
+ if (row.source === "dreamed") return { action, ok: false, reason: "dreamed-rises-only-awake" };
485
+ const r = this.store.replayReturn(row.id, day, dream.id);
486
+ this.store.recordDreamChange(dream.id, { action, ref: row.id, detail: { counted: r.counted, weight: r.weight } });
487
+ return { action, ok: true, reason: r.counted ? "replayed" : `replayed-not-counted:${r.reason}`, id: row.id };
488
+ }
489
+ case "gist": {
490
+ const sources = [...new Set(change.sources ?? [])];
491
+ if (sources.length === 0) return { action, ok: false, reason: "gist-needs-sources" };
492
+ const sourceRows = sources.map(live);
493
+ if (sourceRows.some((r) => r === null)) return { action, ok: false, reason: "not-shown-or-gone" };
494
+ const words = this.words(change.text, dream);
495
+ if (!words.ok) return { action, ok: false, reason: words.reason };
496
+ const kind: Kind = (KINDS as readonly string[]).includes(String(change.kind)) ? (change.kind as Kind) : "fact";
497
+ const cap = PHYSICS.DREAMED_CLAIM_CEILING;
498
+ const title = (change.title ?? "").trim().slice(0, 180);
499
+ const id = this.store.put({
500
+ type: "memory",
501
+ kind,
502
+ title: `Dreamed: ${title.length > 0 ? title : firstLine(words.text)}`,
503
+ body: words.text,
504
+ salience: {
505
+ novelty: null,
506
+ relevance: clampTo(change.relevance ?? cap, cap),
507
+ emotional: 0,
508
+ predictive: clampTo(change.predictive ?? cap, cap),
509
+ claimed: cap,
510
+ },
511
+ physics: { birthDay: day, lastUsedDay: day },
512
+ source: "dreamed",
513
+ // A pattern drawn from a confidential memory is as confidential as it.
514
+ meta: { dream: dream.id, dreamed: true, sources, ...confidentialityOf(sourceRows as MemoryRow[]) },
515
+ origin: { ...(dream.session === null ? {} : { session: dream.session }), ...(dream.scope === null ? {} : { scope: dream.scope }), ref: `dream:${dream.id}` },
516
+ ...(dream.model === null ? {} : { model: dream.model }),
517
+ });
518
+ this.store.linkMany(
519
+ sources.flatMap((s) => [
520
+ { src: id, dst: s, weight: DREAM_TUNABLES.LINK_WEIGHT, day },
521
+ { src: s, dst: id, weight: DREAM_TUNABLES.LINK_WEIGHT, day },
522
+ ]),
523
+ );
524
+ this.store.recordDreamChange(dream.id, { action, ref: id, detail: { sources } });
525
+ shown.add(id);
526
+ return { action, ok: true, reason: "dreamed", id };
527
+ }
528
+ case "contradiction": {
529
+ const a = live(change.a);
530
+ const b = live(change.b);
531
+ if (a === null || b === null) return { action, ok: false, reason: "not-shown-or-gone" };
532
+ if (a.id === b.id) return { action, ok: false, reason: "same-memory" };
533
+ this.store.recordDreamChange(dream.id, { action, ref: a.id, ref2: b.id, detail: {} });
534
+ return { action, ok: true, reason: "flagged" };
535
+ }
536
+ case "feeling-now": {
537
+ const row = live(change.id);
538
+ if (row === null) return { action, ok: false, reason: "not-shown-or-gone" };
539
+ // How it feels NOW can be as strong as it ever was, never stronger: a
540
+ // dream records softening; it cannot manufacture a feeling that would
541
+ // raise the memory or open the core's fast lane.
542
+ const peak = emotionalIntensity(this.store.physicsOf(row.id));
543
+ const s = Math.max(0, Math.min(Number(change.strength ?? 0), peak));
544
+ const carried = this.words(change.carried_by ?? "", dream, true);
545
+ const added = this.store.addFeelings(row.id, [
546
+ {
547
+ whose: "self",
548
+ core: String(change.core ?? ""),
549
+ emotion: String(change.emotion ?? ""),
550
+ strength: s,
551
+ carriedBy: `in a dream, ${dream.date ?? ""}${carried.ok && carried.text.length > 0 ? `: ${carried.text}` : ""}`.trim(),
552
+ },
553
+ ]);
554
+ this.store.recordDreamChange(dream.id, { action, ref: row.id, detail: { feelings: added.ids } });
555
+ return { action, ok: true, reason: s < Number(change.strength ?? 0) ? "recorded-capped-at-peak" : "recorded", id: row.id };
556
+ }
557
+ case "nominate-core": {
558
+ const row = live(change.id);
559
+ if (row === null) return { action, ok: false, reason: "not-shown-or-gone" };
560
+ if (row.promoted_identity === 1) return { action, ok: false, reason: "already-core" };
561
+ if (!aboutMe(this.store, row, ownerNames(this.store))) return { action, ok: false, reason: "not-about-me" };
562
+ const why = this.words(change.why ?? "", dream, true);
563
+ this.store.appendCoreEvent({
564
+ memoryId: row.id,
565
+ action: "nominated",
566
+ day,
567
+ reason: why.ok && why.text.length > 0 ? why.text.slice(0, 300) : null,
568
+ dreamId: dream.id,
569
+ actor: "dream",
570
+ });
571
+ this.store.recordDreamChange(dream.id, { action, ref: row.id, detail: {} });
572
+ return { action, ok: true, reason: "nominated", id: row.id };
573
+ }
574
+ }
575
+ }
576
+
577
+ // ── journal ───────────────────────────────────────────────────────────────
578
+
579
+ /** Close the dream with its journal entry, and hand back the one marked line. */
580
+ journal(input: { dream: string; session?: string; title?: string; text: string }):
581
+ | { ok: true; handBack: string }
582
+ | { ok: false; reason: DreamRefusal | string } {
583
+ const open = this.openFor(input.dream, input.session);
584
+ if (!open.ok) return open;
585
+ const dream = open.dream;
586
+ const words = this.words(input.text, dream, false, DREAM_TUNABLES.MAX_JOURNAL_CHARS);
587
+ if (!words.ok) return { ok: false, reason: words.reason };
588
+ const title = (input.title ?? "").trim().slice(0, 120) || firstLine(words.text);
589
+ this.store.updateDream(dream.id, { state: "journaled", title, journal: words.text });
590
+ const counts = this.counts(dream.id);
591
+ this.record(DREAM_JOURNALED_EVENT, dream.id, { chars: words.text.length, ...counts });
592
+ return { ok: true, handBack: this.handBack(dream.id, title, counts) };
593
+ }
594
+
595
+ private handBack(id: string, title: string, counts: Record<string, number>): string {
596
+ const said = Object.entries(counts)
597
+ .filter(([, n]) => n > 0)
598
+ .map(([k, n]) => `${String(n)} ${k}`)
599
+ .join(", ");
600
+ return (
601
+ `${dreamOpener(id)} I dreamed for a few minutes — "${title}". ` +
602
+ `${said.length > 0 ? `Changes: ${said}.` : "Nothing changed."} ` +
603
+ `The journal and every change are in \`counterparts dream --show ${id}\`; \`counterparts dream --undo ${id}\` reverses it.`
604
+ );
605
+ }
606
+
607
+ // ── reading, and undo ─────────────────────────────────────────────────────
608
+
609
+ counts(id: string): Record<string, number> {
610
+ const out: Record<string, number> = {};
611
+ for (const c of this.store.dreamChanges(id)) {
612
+ if (c.undone === 1) continue;
613
+ out[c.action] = (out[c.action] ?? 0) + 1;
614
+ }
615
+ return out;
616
+ }
617
+
618
+ list(limit = 20): { dream: DreamRow; counts: Record<string, number> }[] {
619
+ return this.store.dreams({ limit }).map((dream) => ({ dream, counts: this.counts(dream.id) }));
620
+ }
621
+
622
+ show(id: string): { dream: DreamRow; changes: DreamChangeRow[] } | null {
623
+ const dream = this.store.dream(id);
624
+ return dream === undefined ? null : { dream, changes: this.store.dreamChanges(id) };
625
+ }
626
+
627
+ /**
628
+ * REVERSE A DREAM'S BATCH, newest change first: merged originals come back
629
+ * (their versions stay as history) and the merged memory is archived; links
630
+ * go back to what they were; a gist is archived; a dream's feelings,
631
+ * replays and nominations are removed; a flagged contradiction stops being
632
+ * raised. The journal stays, marked undone. Idempotent: a change already
633
+ * undone is skipped.
634
+ */
635
+ undo(id: string): { ok: boolean; reason: string; reversed: number; kept: number } {
636
+ if (this.ctx.observer) return { ok: false, reason: "observer", reversed: 0, kept: 0 };
637
+ const dream = this.store.dream(id);
638
+ if (dream === undefined) return { ok: false, reason: "unknown-dream", reversed: 0, kept: 0 };
639
+ let reversed = 0;
640
+ let kept = 0;
641
+ for (const c of [...this.store.dreamChanges(id)].reverse()) {
642
+ if (c.undone === 1) continue;
643
+ const detail = parseDetail(c.detail);
644
+ switch (c.action) {
645
+ case "merge": {
646
+ const from = Array.isArray(detail["from"]) ? (detail["from"] as string[]) : [];
647
+ // SAFE AFTER LATER EDITS: when the merged memory has moved on since —
648
+ // revised into a successor, merged again by a later dream, archived
649
+ // or removed — bringing the originals back would stand them beside
650
+ // its live successor as duplicates. That merge is left as it is and
651
+ // counted; the rest of the dream is still reversed.
652
+ const merged = c.ref === null ? undefined : this.store.row(c.ref);
653
+ if (merged === undefined || merged.archived === 1 || merged.superseded_by !== null) {
654
+ kept += 1;
655
+ continue;
656
+ }
657
+ for (const orig of from) {
658
+ try {
659
+ this.store.restoreSuperseded(orig, DREAM_MERGE_REASON);
660
+ } catch {
661
+ /* removed since: nothing to restore */
662
+ }
663
+ }
664
+ if (c.ref !== null) this.archiveQuietly(c.ref);
665
+ break;
666
+ }
667
+ case "link": {
668
+ if (c.ref !== null && c.ref2 !== null) {
669
+ this.store.restoreEdge(c.ref, c.ref2, edgePrior(detail["ab"]));
670
+ this.store.restoreEdge(c.ref2, c.ref, edgePrior(detail["ba"]));
671
+ }
672
+ break;
673
+ }
674
+ case "gist": {
675
+ if (c.ref !== null) {
676
+ this.archiveQuietly(c.ref);
677
+ const sources = Array.isArray(detail["sources"]) ? (detail["sources"] as string[]) : [];
678
+ for (const s of sources) {
679
+ this.store.restoreEdge(c.ref, s, null);
680
+ this.store.restoreEdge(s, c.ref, null);
681
+ }
682
+ }
683
+ break;
684
+ }
685
+ case "feeling-now": {
686
+ const ids = Array.isArray(detail["feelings"]) ? (detail["feelings"] as string[]) : [];
687
+ if (ids.length > 0) this.store.retractFeelings(ids);
688
+ break;
689
+ }
690
+ default:
691
+ // replayed, nominate-core: removed in bulk below; contradiction: no effect to reverse.
692
+ break;
693
+ }
694
+ this.store.markDreamChangeUndone(id, c.seq);
695
+ reversed += 1;
696
+ }
697
+ this.store.retractDreamReturns(id);
698
+ this.store.retractDreamNominations(id);
699
+ this.store.updateDream(id, { state: "undone" });
700
+ this.record(DREAM_UNDONE_EVENT, id, { reversed, kept });
701
+ return { ok: true, reason: kept > 0 ? "undone-except-moved-on" : "undone", reversed, kept };
702
+ }
703
+
704
+ /**
705
+ * CONTRADICTIONS A DREAM FLAGGED, NOT YET RAISED AWAKE — one line each for
706
+ * the next session, claimed by a meta latch so each is raised once. Only a
707
+ * pair this session could be shown is raised (recall's gates).
708
+ */
709
+ raiseLines(input: { session: string }): string[] {
710
+ if (this.ctx.observer) return [];
711
+ const out: string[] = [];
712
+ const owner = ownerNames(this.store);
713
+ for (const dream of this.store.dreams({ limit: 10 })) {
714
+ if (dream.state === "undone") continue;
715
+ for (const c of this.store.dreamChanges(dream.id)) {
716
+ if (c.action !== "contradiction" || c.undone === 1 || c.ref === null || c.ref2 === null) continue;
717
+ const key = `${RAISED_PREFIX}${dream.id}.${String(c.seq)}`;
718
+ if (this.store.getMeta(key) !== undefined) continue;
719
+ const a = this.store.row(c.ref);
720
+ const b = this.store.row(c.ref2);
721
+ if (a === undefined || b === undefined || !this.showable(a) || !this.showable(b)) continue;
722
+ this.store.setMeta(key, String(this.store.livedDay()));
723
+ const him = aboutMe(this.store, a, owner) || aboutMe(this.store, b, owner) ? " It is about the two of you or about him: raise it with him." : "";
724
+ out.push(
725
+ `Counterparts: a dream on ${dream.date ?? "a recent night"} flagged two memories that disagree — ${c.ref} and ${c.ref2}. Look them up (recall by id) and settle which holds, awake; the dream did not.${him}`,
726
+ );
727
+ if (out.length >= 2) return out;
728
+ }
729
+ }
730
+ void input;
731
+ return out;
732
+ }
733
+
734
+ // ── internals ─────────────────────────────────────────────────────────────
735
+
736
+ /**
737
+ * RECALL'S GATES, for a dream: what could surface in this session anyway. A
738
+ * live, unarchived, un-superseded MEMORY (not a schema row: the page, a
739
+ * handoff, a belief or an entity card is not a dream's to touch), not
740
+ * protected (the owner's permanence guards it from any interpreter), and not
741
+ * confidential unless this is the owner's own session.
742
+ */
743
+ showable(row: MemoryRow): boolean {
744
+ if (row.archived === 1 || row.superseded_by !== null) return false;
745
+ if (row.type !== "memory") return false;
746
+ if (row.protected === 1) return false;
747
+ if (row.confidential === 1 && !this.ctx.owner) return false;
748
+ if (row.body === "") return false;
749
+ return true;
750
+ }
751
+
752
+ /**
753
+ * Memories made since `last` (or in the last few lived days), showable,
754
+ * newest first, at most `MAX_NEW`. One bounded read (`store.newMemoryIds`,
755
+ * which applies the column gates), then the deny-list and confidentiality.
756
+ */
757
+ private freshIds(last: DreamRow | null): string[] {
758
+ const day = this.store.livedDay();
759
+ const ids = this.store.newMemoryIds(
760
+ last === null
761
+ ? { sinceAt: null, sinceDay: day - DREAM_TUNABLES.FIRST_DREAM_DAYS, limit: DREAM_TUNABLES.MAX_NEW * 3 }
762
+ : { sinceAt: last.started_at, sinceDay: last.day, limit: DREAM_TUNABLES.MAX_NEW * 3 },
763
+ );
764
+ if (ids.length === 0) return [];
765
+ const denied = new Set(this.store.deniedIds());
766
+ const out: string[] = [];
767
+ for (const id of ids) {
768
+ if (denied.has(id)) continue;
769
+ const row = this.store.row(id);
770
+ if (row === undefined || !this.showable(row)) continue;
771
+ out.push(id);
772
+ if (out.length >= DREAM_TUNABLES.MAX_NEW) break;
773
+ }
774
+ return out;
775
+ }
776
+
777
+ private compose(id: string, fresh: readonly string[], last: DreamRow | null, day: number, at: string): DreamBundle {
778
+ const T = DREAM_TUNABLES;
779
+ const memories: Record<string, DreamItem> = {};
780
+ const denied = new Set(this.store.deniedIds());
781
+ const take = (mid: string): boolean => {
782
+ if (memories[mid] !== undefined) return true;
783
+ if (denied.has(mid)) return false;
784
+ const row = this.store.row(mid);
785
+ if (row === undefined || !this.showable(row)) return false;
786
+ const item = this.item(row, day);
787
+ if (item === null) return false;
788
+ memories[mid] = item;
789
+ return true;
790
+ };
791
+ const rng = seeded(id);
792
+ const freshSet = new Set(fresh);
793
+ const freshOut: { id: string; neighbours: string[] }[] = [];
794
+ const loose: string[] = [];
795
+ for (const fid of fresh) {
796
+ if (!take(fid)) continue;
797
+ const self = this.store.row(fid) as MemoryRow;
798
+ const ranked = this.near(fid, T.MIXING_TO_RANK);
799
+ const neighbours: string[] = [];
800
+ for (const [rank, nid] of ranked.entries()) {
801
+ if (nid === fid || freshSet.has(nid)) continue;
802
+ const nrow = this.store.row(nid);
803
+ if (nrow === undefined || nrow.birth_day > self.birth_day) continue;
804
+ if (rank >= T.MIXING_FROM_RANK) {
805
+ loose.push(nid);
806
+ continue;
807
+ }
808
+ if (neighbours.length < T.NEIGHBOURS && take(nid)) neighbours.push(nid);
809
+ }
810
+ freshOut.push({ id: fid, neighbours });
811
+ }
812
+ // REM MIXING: a few loosely related older memories, picked at random from
813
+ // the loose band of the new memories' neighbourhoods.
814
+ const mixing: string[] = [];
815
+ const pool = [...new Set(loose)].filter((x) => memories[x] === undefined);
816
+ while (mixing.length < T.MIXING && pool.length > 0) {
817
+ const [pick] = pool.splice(Math.floor(rng() * pool.length), 1);
818
+ if (pick !== undefined && take(pick)) mixing.push(pick);
819
+ }
820
+ // THE LOOK-BACK: the strongest-feeling memories from about a week ago.
821
+ const lookback: string[] = [];
822
+ const lo = day - T.LOOKBACK_DAYS - T.LOOKBACK_SPREAD;
823
+ const hi = day - T.LOOKBACK_DAYS + T.LOOKBACK_SPREAD;
824
+ const felt: { id: string; felt: number }[] = [];
825
+ for (const mid of this.store.list({ type: "memory", archived: false })) {
826
+ const row = this.store.row(mid);
827
+ if (row === undefined || row.birth_day < lo || row.birth_day > hi || denied.has(mid) || !this.showable(row)) continue;
828
+ const f = emotionalIntensity(this.store.physicsOf(mid));
829
+ if (f > 0) felt.push({ id: mid, felt: f });
830
+ }
831
+ felt.sort((a, b) => b.felt - a.felt || (a.id < b.id ? -1 : 1));
832
+ for (const f of felt) {
833
+ if (lookback.length >= T.LOOKBACK_COUNT) break;
834
+ if (take(f.id)) lookback.push(f.id);
835
+ }
836
+ const owner = ownerNames(this.store);
837
+ const aboutHim = Object.keys(memories).filter((mid) => {
838
+ const row = this.store.row(mid);
839
+ return row !== undefined && row.kind === "person" && aboutMe(this.store, row, owner);
840
+ });
841
+ return {
842
+ dream: id,
843
+ date: at,
844
+ livedDay: day,
845
+ lastDreamed: last === null ? null : (last.date ?? null),
846
+ limits: { ...T.LIMITS },
847
+ selfPage: cut(this.ctx.page(), T.PAGE_CHARS),
848
+ wake: cut(this.ctx.wake(), T.WAKE_CHARS),
849
+ owner: { names: owner, memories: aboutHim },
850
+ chapters: this.chaptersSince(last),
851
+ memories,
852
+ fresh: freshOut,
853
+ mixing,
854
+ lookback,
855
+ };
856
+ }
857
+
858
+ /** The journal since the last dream: episode rows written or extended since, newest first. */
859
+ private chaptersSince(last: DreamRow | null): { id: string; title: string | null; text: string }[] {
860
+ const out: { id: string; title: string | null; text: string; at: number }[] = [];
861
+ const day = this.store.livedDay();
862
+ for (const id of this.store.list({ type: "episode", archived: false })) {
863
+ const row = this.store.row(id);
864
+ if (row === undefined) continue;
865
+ if (row.confidential === 1 && !this.ctx.owner) continue;
866
+ const at = row.updated_at ?? row.created_at ?? 0;
867
+ const since = last === null ? row.birth_day >= day - DREAM_TUNABLES.FIRST_DREAM_DAYS : at > last.started_at;
868
+ if (!since) continue;
869
+ out.push({ id, title: row.title, text: cut(row.body, DREAM_TUNABLES.CHAPTER_CHARS) ?? "", at });
870
+ }
871
+ out.sort((a, b) => b.at - a.at);
872
+ return out.slice(0, DREAM_TUNABLES.MAX_CHAPTERS).map(({ id, title, text }) => ({ id, title, text }));
873
+ }
874
+
875
+ /** Nearest memories to `id`, by the static embedder's vectors, else lexically. */
876
+ private near(id: string, limit: number): string[] {
877
+ const vec = this.store.vectorOf(id);
878
+ if (vec !== null) return this.store.nearestTo(vec, limit + 1).map((h) => h.id);
879
+ // No vector (embedder off, or not yet embedded): the rarest words of its
880
+ // title and first line, through the token index.
881
+ let doc: ProseDoc;
882
+ try {
883
+ doc = this.store.readProse(id);
884
+ } catch {
885
+ return [];
886
+ }
887
+ const words = `${doc.title ?? ""} ${firstLine(doc.body)}`
888
+ .toLowerCase()
889
+ .split(/[^\p{L}\p{N}]+/u)
890
+ .filter((w) => w.length >= 5)
891
+ .slice(0, 6);
892
+ const scores = new Map<string, number>();
893
+ for (const w of words) for (const h of this.store.search(w, limit)) scores.set(h.id, (scores.get(h.id) ?? 0) + h.score);
894
+ return [...scores].sort((a, b) => b[1] - a[1]).map(([mid]) => mid).slice(0, limit);
895
+ }
896
+
897
+ private item(row: MemoryRow, day: number): DreamItem | null {
898
+ let doc: ProseDoc;
899
+ try {
900
+ doc = this.store.readProse(row.id);
901
+ } catch {
902
+ return null;
903
+ }
904
+ if (isSelfPage(doc) || isHandoff(doc)) return null;
905
+ const p = this.store.physicsOf(row.id);
906
+ const head = doc.title !== undefined && doc.title.trim().length > 0 ? `${doc.title.trim()} — ` : "";
907
+ return {
908
+ id: row.id,
909
+ kind: row.kind,
910
+ text: (cut(`${head}${doc.body}`, DREAM_TUNABLES.TEXT_CHARS) ?? "").replace(/\s+/g, " "),
911
+ felt: round(emotionalIntensity(p)),
912
+ strength: round(strength(p, day)),
913
+ day: row.birth_day,
914
+ learned: row.learned_on,
915
+ core: row.promoted_identity === 1,
916
+ };
917
+ }
918
+
919
+ /** A dream this session may still write to. */
920
+ private openFor(id: string, session: string | undefined): { ok: true; dream: DreamRow } | { ok: false; reason: DreamRefusal } {
921
+ if (this.ctx.observer) return { ok: false, reason: "observer" };
922
+ const dream = this.store.dream(id);
923
+ if (dream === undefined) return { ok: false, reason: "unknown-dream" };
924
+ if (session !== undefined && dream.session !== null && dream.session !== session) return { ok: false, reason: "not-this-session" };
925
+ if (dream.state !== "begun") return { ok: false, reason: "dream-closed" };
926
+ // A dream left open (never journaled) is closed by the next one that
927
+ // begins: otherwise an old id would stay writable for ever, with limits
928
+ // and a shown set of its own. (Adversarial review of #251.)
929
+ const newest = this.lastDream();
930
+ if (newest !== null && newest.id !== dream.id) return { ok: false, reason: "dream-closed" };
931
+ return { ok: true, dream };
932
+ }
933
+
934
+ /** The dream's words through the credential battery; bounded; never empty unless allowed. */
935
+ private words(
936
+ text: string | undefined,
937
+ dream: DreamRow,
938
+ allowEmpty = false,
939
+ max: number = DREAM_TUNABLES.MAX_TEXT_CHARS,
940
+ ): { ok: true; text: string } | { ok: false; reason: string } {
941
+ const raw = (text ?? "").trim();
942
+ if (raw.length === 0) return allowEmpty ? { ok: true, text: "" } : { ok: false, reason: "empty-text" };
943
+ if (carriesDreamMark(raw)) return { ok: false, reason: "dream-mark-in-text" };
944
+ const verdict = this.ctx.gate(raw.slice(0, max), dream.session ?? dream.id);
945
+ if (!verdict.ok) return { ok: false, reason: `gate:${verdict.reason}` };
946
+ return { ok: true, text: verdict.text };
947
+ }
948
+
949
+ private archiveQuietly(id: string): void {
950
+ const row = this.store.row(id);
951
+ if (row === undefined || row.archived === 1) return;
952
+ try {
953
+ this.store.archive(id, DREAM_UNDONE_REASON);
954
+ } catch {
955
+ /* removed since */
956
+ }
957
+ }
958
+
959
+ /** The owner's name as it was written on the identity core (not lower-cased). */
960
+ private ownerName(): string | null {
961
+ for (const id of this.store.list({ type: "schema", kind: "self", archived: false })) {
962
+ try {
963
+ const meta = this.store.readProse(id).meta;
964
+ if (meta["role"] === "entity" && typeof meta["name"] === "string" && meta["name"].trim().length > 0) {
965
+ return meta["name"].trim();
966
+ }
967
+ } catch {
968
+ continue;
969
+ }
970
+ }
971
+ return null;
972
+ }
973
+
974
+ /** A durable row (ids and counts only), and the ring event beside it. */
975
+ private record(name: string, ref: string | null, payload: Record<string, string | number | boolean | null>): void {
976
+ this.emit(name, ref ?? undefined, payload);
977
+ if (this.ctx.observer) return;
978
+ try {
979
+ this.store.appendEvent({ name, day: this.store.livedDay(), ref, payload });
980
+ } catch {
981
+ /* the log is evidence, never a reason to fail the dream */
982
+ }
983
+ }
984
+ }
985
+
986
+ // ── small helpers ────────────────────────────────────────────────────────────
987
+
988
+ function parseIds(json: string): string[] {
989
+ try {
990
+ const v: unknown = JSON.parse(json);
991
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
992
+ } catch {
993
+ return [];
994
+ }
995
+ }
996
+
997
+ function parseDetail(json: string): Record<string, unknown> {
998
+ try {
999
+ const v: unknown = JSON.parse(json);
1000
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
1001
+ } catch {
1002
+ return {};
1003
+ }
1004
+ }
1005
+
1006
+ function edgePrior(v: unknown): { weight: number; day: number } | null {
1007
+ if (v === null || typeof v !== "object") return null;
1008
+ const r = v as Record<string, unknown>;
1009
+ return typeof r["weight"] === "number" && typeof r["day"] === "number" ? { weight: r["weight"], day: r["day"] } : null;
1010
+ }
1011
+
1012
+ /**
1013
+ * The confidentiality marker a dream's new memory must carry when any memory
1014
+ * it was made from is confidential: `confidential: true`, plus the first
1015
+ * named class (`confidentiality`) found. Empty when none is.
1016
+ */
1017
+ function confidentialityOf(rows: readonly MemoryRow[]): Record<string, unknown> {
1018
+ let out: Record<string, unknown> = {};
1019
+ for (const r of rows) {
1020
+ if (r.confidential !== 1) continue;
1021
+ let klass: unknown;
1022
+ try {
1023
+ const meta = JSON.parse(r.meta) as Record<string, unknown>;
1024
+ klass = meta["confidentiality"];
1025
+ } catch {
1026
+ klass = undefined;
1027
+ }
1028
+ if (out["confidential"] === undefined) out = { confidential: true };
1029
+ if (typeof klass === "string" && klass.length > 0 && out["confidentiality"] === undefined) out["confidentiality"] = klass;
1030
+ }
1031
+ return out;
1032
+ }
1033
+
1034
+ function cut(text: string | null, max: number): string | null {
1035
+ if (text === null) return null;
1036
+ return text.length <= max ? text : `${text.slice(0, max)}…`;
1037
+ }
1038
+
1039
+ function firstLine(text: string): string {
1040
+ return (text.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "").slice(0, 120);
1041
+ }
1042
+
1043
+ function clampTo(x: number, cap: number): number {
1044
+ const n = Number.isFinite(x) ? x : cap;
1045
+ return Math.max(0, Math.min(n, cap));
1046
+ }
1047
+
1048
+ function round(x: number): number {
1049
+ return Math.round(x * 100) / 100;
1050
+ }
1051
+
1052
+ function errName(err: unknown): string {
1053
+ if (err !== null && typeof err === "object" && "code" in err) return String((err as { code: unknown }).code);
1054
+ return err instanceof Error ? err.name : "UNKNOWN";
1055
+ }
1056
+
1057
+ /** A small deterministic RNG seeded from the dream id, so a bundle is reproducible. */
1058
+ function seeded(seed: string): () => number {
1059
+ let h = Number.parseInt(createHash("sha256").update(seed).digest("hex").slice(0, 8), 16) >>> 0;
1060
+ return () => {
1061
+ h = (h + 0x6d2b79f5) >>> 0;
1062
+ let t = h;
1063
+ t = Math.imul(t ^ (t >>> 15), t | 1);
1064
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
1065
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
1066
+ };
1067
+ }