counterparts 0.1.0

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 (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,1740 @@
1
+ /**
2
+ * The MCP server: messages in, tool results out, one brain underneath.
3
+ *
4
+ * **It composes, it does not re-wire** (CLAUDE.md, `counterpart.ts`'s header).
5
+ * Every durable thing this file does goes through a `Counterpart` method —
6
+ * `captureJot`, `submitJot`, `submitSessionEnd` — so the gate battery, the
7
+ * engine-set authorship channel, the `updates:` resolution and the observer
8
+ * stand-down all ride along without this adapter knowing they exist. The MCP
9
+ * tools are therefore two more entrances on `claude-code/INTERFACE-GAPS.md`
10
+ * §4's table, and they inherit its coverage rather than needing their own.
11
+ *
12
+ * **The three refusals that live HERE**, because no core module can know them:
13
+ *
14
+ * 1. **The bound session.** `session_end` is the return channel for ONE
15
+ * session's Stop ask (`claude-code/INTERFACE-GAPS.md` §7). `chapter` binds
16
+ * by the same rules, through the same one code path. A server
17
+ * launched for session A may not accept session B's dump, and a server
18
+ * bound to nothing may not accept a bare claim — "unbound" is a refusal,
19
+ * not a wildcard. A host that lets a model pick the session id it writes
20
+ * under has handed the model the ability to write into another session's
21
+ * day.
22
+ *
23
+ * **The lazy bind, added 2026-09-04.** Measured on the live host: Claude
24
+ * Code registers an MCP server from a STATIC config (command, args, env),
25
+ * so `--session` never arrives and every dump for the whole run was
26
+ * refused `no-bound-session`. So a server launched without one may bind
27
+ * ONCE, from the model's claim, and only when the claim is CORROBORATED by
28
+ * host state the model cannot write: `adapters/sessions.ts`'s registry,
29
+ * written by the hooks, must hold that id, it must be live, and its scope
30
+ * must be this server's scope. The first valid claim binds for the
31
+ * process's lifetime; a second, different id is refused exactly as it
32
+ * always was. The explicit `--session` path is unchanged and still wins:
33
+ * a server told which session it is never consults the registry.
34
+ * 2. **Stand-down over the wire** (§5 G5, scar E7/§2.4). Under observer every
35
+ * tool returns a result that SAYS it stood down, plus telemetry. A silent
36
+ * no-op would be indistinguishable from a broken server, which is the
37
+ * exact failure §2.4 records.
38
+ * 3. **Owner-scoped confidentiality** (§5 G6). The host is the only thing
39
+ * that knows whose session this is; it says so at construction, and the
40
+ * value travels into `Recall`'s own owner logic rather than being
41
+ * re-derived from anything the model can influence.
42
+ *
43
+ * Telemetry is content-by-reference throughout: ids, counts, tiers, reasons.
44
+ * No body text, no question text, no note text ever reaches an event.
45
+ */
46
+ import { MCP_RECALL_EVENT } from "../../core/counterpart.js";
47
+ import type { ChapterResult, Counterpart, DepositResult } from "../../core/counterpart.js";
48
+ import type { SemanticSource } from "../../core/recall/index.js";
49
+ import { AUTHOR_DIMENSIONS } from "../../core/remember/index.js";
50
+ import type { Band, Kind } from "../../core/types.js";
51
+ import { recordHandleResolution } from "../expansions.js";
52
+ import {
53
+ lookupScope,
54
+ readScopes,
55
+ ownEntry,
56
+ resumeTarget,
57
+ setScope,
58
+ stanceOfMode,
59
+ writeScopes,
60
+ } from "../scopes.js";
61
+ import type { ScopeMode, ScopeRegistry, ScopeVerdict } from "../scopes.js";
62
+ import {
63
+ PAGE_WRITER_ENV,
64
+ SESSION_TTL_MS,
65
+ canonicalScope,
66
+ isLive,
67
+ readSession,
68
+ sameScope,
69
+ } from "../sessions.js";
70
+ import {
71
+ JOURNAL_GLOSS,
72
+ RECALL_BODY_CHARS,
73
+ RECALL_EXCERPT_CHARS,
74
+ RECALL_MAX_IDS,
75
+ RECALL_RESULT_CHARS,
76
+ boundMemories,
77
+ deliberateRecall,
78
+ } from "./deliberate.js";
79
+ import type { DeliberateResult } from "./deliberate.js";
80
+ import {
81
+ ERROR_CODES,
82
+ failure,
83
+ negotiateVersion,
84
+ success,
85
+ } from "./protocol.js";
86
+ import type { Id, Request, Response } from "./protocol.js";
87
+ import { NO_PAGE_VERSION } from "../../core/self/index.js";
88
+ import type { PageWriterMode } from "../../core/self/index.js";
89
+ import { TOOL_NAMES, toolDefinitions, toolSpec } from "./tools.js";
90
+ import type { ToolName } from "./tools.js";
91
+
92
+ export const SERVER_NAME = "counterparts";
93
+ /**
94
+ * What `initialize` tells the client it is talking to. It is the PACKAGE's
95
+ * version, and `test/mcp.test.ts` reads `package.json` and asserts the two are
96
+ * the same string — a literal here that drifted would make the one number a
97
+ * client can see about this server a lie, and the handshake is exactly where a
98
+ * host decides whether to trust what follows. Read from a constant rather than
99
+ * from disk so the server opens no file to answer its first message.
100
+ */
101
+ export const SERVER_VERSION = "0.1.0";
102
+
103
+ /** Telemetry: ids, counts, reasons, flags. NEVER body text (store §5 G10). */
104
+ export interface McpEvent {
105
+ at: number;
106
+ name: string;
107
+ ref?: string;
108
+ data?: Record<string, string | number | boolean | null>;
109
+ }
110
+
111
+ export interface McpServerOptions {
112
+ counterpart: Counterpart;
113
+ /**
114
+ * The ONE session this server may deposit under, when the host can say so at
115
+ * launch. Absent ⇒ the lazy bind (`requireBoundSession`) is the only way in.
116
+ */
117
+ session?: string;
118
+ /**
119
+ * The project this server's sessions belong to. Defaults to `process.cwd()`,
120
+ * which is MEASURED to be the project directory on this host: `lsof` on four
121
+ * running servers, 2026-09-04, showed each one's cwd was the directory its
122
+ * session ran in. The store's dir is the last resort, and it is a bad scope —
123
+ * every memory authored through this server carried the store path as
124
+ * `origin_scope` for the whole run because it was the only default.
125
+ */
126
+ scope?: string;
127
+ /** Is this the owner's own session? Withholding is the safe direction. */
128
+ owner?: boolean;
129
+ /**
130
+ * This process's environment, injected. Read for exactly one thing today —
131
+ * `COUNTERPARTS_PAGE_WRITER`, the date a windowless nightly writer is writing
132
+ * about (`claude-code/page-writer.ts`) — and injected rather than reached for
133
+ * so a test can prove that path without exporting anything into the suite's
134
+ * own environment.
135
+ */
136
+ env?: Readonly<Record<string, string | undefined>>;
137
+ /**
138
+ * The embedder, for ONE purpose: embedding a deliberate question in line.
139
+ *
140
+ * The ruling of 2026-09-04 splits the two paths — the ambient hot path may not
141
+ * embed (it has a 1200 ms budget and a person mid-sentence), the deliberate
142
+ * ask may (someone typed a question and is waiting). This is that half.
143
+ *
144
+ * The server never sees a credential: the ENTRY POINT loads the file the
145
+ * package's own config names and hands over an opened embedder or null
146
+ * (`bin/serve.ts`), exactly as `bin/hook.ts` does for the hook adapter. Null
147
+ * degrades the ask to lexical-only and the result SAYS so.
148
+ */
149
+ embedder?: QuestionEmbedder | null;
150
+ /**
151
+ * Where the hooks' live-session registry lives. Defaults to the store's own
152
+ * data dir — the one path both adapters resolve independently and agree on.
153
+ */
154
+ registryDir?: string;
155
+ /** **CAL.** Liveness window for a lazily-bound claim (`adapters/sessions.ts`). */
156
+ sessionTtlMs?: number;
157
+ /**
158
+ * THE SCOPE REGISTRY this server consults — `<config dir>/scopes.json`,
159
+ * resolved by the entry point from the same `--config` rule everything else
160
+ * uses (`bin/serve.ts`). Absent means "nobody told us", which reads as `unset`
161
+ * and behaves exactly as this server always has.
162
+ *
163
+ * It is read PER CALL rather than pinned at construction, and deliberately:
164
+ * the file is a few hundred bytes, and a session whose directory was switched
165
+ * back on — from the console in another terminal, or by this server's own
166
+ * `scope` tool — must get its memory back without the host restarting the
167
+ * process. The launch stderr line is the one thing computed once.
168
+ */
169
+ scopesFile?: string;
170
+ onEvent?: (e: McpEvent) => void;
171
+ now?: () => number;
172
+ }
173
+
174
+ /** The narrow face of `claude-code/embed-client.ts`'s `LiveEmbedder` this
175
+ * adapter needs — structural, so `mcp/` imports no other adapter. */
176
+ export interface QuestionEmbedder {
177
+ vector(text: string): Promise<number[] | null>;
178
+ }
179
+
180
+ /** MCP's tool-result shape. A refusal is a RESULT, never a JSON-RPC error. */
181
+ export interface ToolResult {
182
+ content: { type: "text"; text: string }[];
183
+ structuredContent: Record<string, unknown>;
184
+ isError?: boolean;
185
+ }
186
+
187
+ const EVENT_RING = 200;
188
+
189
+ /**
190
+ * THE SCOPE THE HOST OFFERED, or null when it offered none.
191
+ *
192
+ * In order: what the launch declared (`--scope` / `COUNTERPARTS_SCOPE`), then
193
+ * `CLAUDE_PROJECT_DIR`, then this process's working directory.
194
+ *
195
+ * **`CLAUDE_PROJECT_DIR` is second, and it is what makes the two adapters agree
196
+ * without either one telling the other.** The host documents it as the project
197
+ * root where the session started, exports it to hook processes AND to stdio MCP
198
+ * servers, and keeps it put when the agent enters a worktree or runs `cd` — so
199
+ * the hooks' `sessionScope` and this resolve the same string from the same
200
+ * variable. What the server's own working directory is, this host does not
201
+ * document at all: `lsof` on four running servers measured it as the session's
202
+ * directory on 2026-09-04, and a measurement is what it remains. It stays as the
203
+ * fallback it has always been.
204
+ *
205
+ * CANONICAL, because the scope is not only compared — it is the KEY. Span
206
+ * streams, cursors and coverage files are named from a hash of this exact string
207
+ * (`remember/spans.ts#keyFor`), so a deposit whose scope says `/tmp/x` claims
208
+ * coverage in a different directory from spans captured under `/private/tmp/x`.
209
+ * `sameScope` was already canonicalising for the BIND; this makes the filing
210
+ * agree too.
211
+ */
212
+ export function hostScope(
213
+ declared: string | undefined,
214
+ env: NodeJS.ProcessEnv = process.env,
215
+ ): { scope: string; source: Exclude<ScopeSource, "store"> } | null {
216
+ if (declared !== undefined && declared.length > 0) {
217
+ return { scope: canonicalScope(declared), source: "flag" };
218
+ }
219
+ const projectDir = env["CLAUDE_PROJECT_DIR"];
220
+ if (typeof projectDir === "string" && projectDir.length > 0) {
221
+ return { scope: canonicalScope(projectDir), source: "project" };
222
+ }
223
+ try {
224
+ const cwd = process.cwd();
225
+ if (cwd.length > 0) return { scope: canonicalScope(cwd), source: "cwd" };
226
+ } catch {
227
+ /* no working directory — the caller falls through to the store's own dir */
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * The scope default: whatever the host offered, and — only if it offered
234
+ * nothing at all — the store's own dir.
235
+ *
236
+ * The last resort is a bad answer and is kept only because a server with no
237
+ * scope at all cannot deposit: from 2026-09-03 it was the ONLY answer, so every
238
+ * memory authored through this server was stamped with the store path instead of
239
+ * the project. `process.cwd()` can throw (a deleted working directory), which is
240
+ * the one case the fallback is actually for.
241
+ */
242
+ export function resolveScope(
243
+ declared: string | undefined,
244
+ storeDir: string,
245
+ env: NodeJS.ProcessEnv = process.env,
246
+ ): { scope: string; source: ScopeSource } {
247
+ return hostScope(declared, env) ?? { scope: storeDir, source: "store" };
248
+ }
249
+
250
+ /** How this server learned which project it is serving. Reported at startup. */
251
+ export type ScopeSource = "flag" | "project" | "cwd" | "store";
252
+
253
+ /** The kind enum, for a refusal that names it (session_end). Derived from
254
+ * `Kind` so that adding a kind without listing it here fails `tsc`. */
255
+ /**
256
+ * Why a page write did not land, in the words the model needs to do something
257
+ * about it. The keys are `self/`'s own refusal vocabulary, so a reason it can
258
+ * return and this map does not carry falls back to one plain sentence rather
259
+ * than to silence.
260
+ */
261
+ const PAGE_REFUSAL_DETAIL: Record<string, string> = {
262
+ empty: "A page has to say something. Nothing worth writing is a real answer — leave the page alone instead.",
263
+ "too-large":
264
+ "That page is past the hard limit, so it was refused rather than cut: what gets cut at write time is the only copy. Say the same thing shorter and send it again.",
265
+ "gate-refused":
266
+ "The gate battery turned it away — most often because what was sent was nothing but a credential, or too short to be a page. Nothing was written.",
267
+ "forged-markers":
268
+ "That page contains the wake's own structural markers (`<!-- counterparts:wake`). Those lines are the bundle's bookkeeping, and a page carrying them reads to the next session as the end of its memory. Write the page in ordinary prose; headings are fine.",
269
+ "version-moved":
270
+ "Somebody else wrote the page after the version you read — another session, the owner, or the nightly writer. Nothing was written, and nothing of theirs was lost. `currentVersion` and `currentBody` here are what is actually there: fold your change into that and send it back with the new `ifVersion`.",
271
+ "no-page":
272
+ "You named a version and there is no page here at all — nobody wrote over you. Omit `ifVersion` to write the first page, or pass -1, which is the version a read of an empty store reports.",
273
+ "page-appeared":
274
+ "You wrote as if there were no page, and one has appeared since you looked. Nothing was written. `currentVersion` and `currentBody` are what is there: read it, fold your change into it, and send it back with that version.",
275
+ };
276
+
277
+ const KIND_SET: Record<Kind, true> = { self: true, person: true, entity: true, skill: true, place: true, fact: true };
278
+ const MEMORY_KINDS = Object.keys(KIND_SET) as readonly Kind[];
279
+
280
+ export class McpServer {
281
+ readonly counterpart: Counterpart;
282
+ /** The session the HOST named at launch, if it could. Never changes. */
283
+ readonly launchedSession: string | null;
284
+ readonly scope: string;
285
+ readonly scopeSource: ScopeSource;
286
+ readonly owner: boolean;
287
+ /** One predicate, one definition: the store's (observer-mode G7). */
288
+ readonly observer: boolean;
289
+
290
+ private readonly embedder: QuestionEmbedder | null;
291
+ private readonly registryDir: string;
292
+ private readonly scopesFile: string | null;
293
+ private readonly sessionTtlMs: number;
294
+ private readonly onEvent: ((e: McpEvent) => void) | undefined;
295
+ private readonly nowFn: () => number;
296
+ private readonly env: Readonly<Record<string, string | undefined>>;
297
+ private readonly ring: McpEvent[] = [];
298
+ private initialized = false;
299
+ /** The lazy bind's result: null until a claim is corroborated, then frozen. */
300
+ private lazySession: string | null = null;
301
+
302
+ constructor(opts: McpServerOptions) {
303
+ this.counterpart = opts.counterpart;
304
+ this.launchedSession =
305
+ opts.session !== undefined && opts.session.length > 0 ? opts.session : null;
306
+ const scope = resolveScope(opts.scope, opts.counterpart.store.dir);
307
+ this.scope = scope.scope;
308
+ this.scopeSource = scope.source;
309
+ this.registryDir = opts.registryDir ?? opts.counterpart.store.dir;
310
+ this.scopesFile =
311
+ opts.scopesFile !== undefined && opts.scopesFile.length > 0 ? opts.scopesFile : null;
312
+ this.sessionTtlMs = opts.sessionTtlMs ?? SESSION_TTL_MS;
313
+ this.observer = opts.counterpart.observer;
314
+ // An observer is a non-owner regardless of what the host claimed
315
+ // (observer-mode G7): an instrument reading somebody's store is not them.
316
+ this.owner = opts.owner === true && !this.observer;
317
+ // An instrument opens no sockets, whatever the host handed it (scar E7).
318
+ this.embedder = this.observer ? null : opts.embedder ?? null;
319
+ this.onEvent = opts.onEvent;
320
+ this.nowFn = opts.now ?? ((): number => Date.now());
321
+ this.env = opts.env ?? process.env;
322
+ // LAST in the constructor — `emit` needs `nowFn`. A scope nobody chose is
323
+ // the bug this run measured, so which default won is on the record from the
324
+ // first event rather than inferable only from the memories it stamped.
325
+ this.emit("mcp.scope", undefined, {
326
+ scope: this.scope,
327
+ source: this.scopeSource,
328
+ boundSession: this.launchedSession !== null,
329
+ });
330
+ }
331
+
332
+ /** The session this server may deposit under: the host's, else the bound claim. */
333
+ get session(): string | null {
334
+ return this.launchedSession ?? this.lazySession;
335
+ }
336
+
337
+ events(name?: string): McpEvent[] {
338
+ return this.ring.filter((e) => name === undefined || e.name === name).map((e) => ({ ...e }));
339
+ }
340
+
341
+ // ── the wire ───────────────────────────────────────────────────────────────
342
+
343
+ /**
344
+ * One request in, one response out — or `null` for a notification, which is
345
+ * answered with nothing at all.
346
+ */
347
+ async handle(request: Request): Promise<Response | null> {
348
+ const id = request.id;
349
+ const params = request.params ?? {};
350
+
351
+ switch (request.method) {
352
+ case "initialize": {
353
+ if (id === undefined) return null;
354
+ this.initialized = true;
355
+ const version = negotiateVersion(params["protocolVersion"]);
356
+ this.emit("mcp.initialize", undefined, {
357
+ protocolVersion: version,
358
+ observer: this.observer,
359
+ owner: this.owner,
360
+ boundSession: this.session !== null,
361
+ });
362
+ return success(id, {
363
+ protocolVersion: version,
364
+ capabilities: { tools: { listChanged: false } },
365
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
366
+ });
367
+ }
368
+ case "notifications/initialized":
369
+ case "initialized":
370
+ this.initialized = true;
371
+ return null;
372
+ case "ping":
373
+ return id === undefined ? null : success(id, {});
374
+ case "tools/list": {
375
+ if (id === undefined) return null;
376
+ this.emit("mcp.tools.list", undefined, { tools: TOOL_NAMES.length });
377
+ return success(id, { tools: toolDefinitions() });
378
+ }
379
+ case "tools/call": {
380
+ if (id === undefined) return null;
381
+ return this.callFromParams(id, params);
382
+ }
383
+ default:
384
+ if (id === undefined) return null;
385
+ return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `unknown method: ${request.method}`);
386
+ }
387
+ }
388
+
389
+ private async callFromParams(id: Id, params: Record<string, unknown>): Promise<Response> {
390
+ const name = params["name"];
391
+ if (typeof name !== "string") {
392
+ return failure(id, ERROR_CODES.INVALID_PARAMS, "tools/call requires a string name");
393
+ }
394
+ if (toolSpec(name) === undefined) {
395
+ // An unknown TOOL is a protocol fault (the client called something that
396
+ // does not exist); an unusable ARGUMENT is the tool's own answer.
397
+ return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `unknown tool: ${name}`);
398
+ }
399
+ const args = params["arguments"];
400
+ if (args !== undefined && (args === null || typeof args !== "object" || Array.isArray(args))) {
401
+ return failure(id, ERROR_CODES.INVALID_PARAMS, "arguments must be an object");
402
+ }
403
+ const result = await this.call(name, (args as Record<string, unknown>) ?? {});
404
+ return success(id, result as unknown as Record<string, unknown>);
405
+ }
406
+
407
+ // ── the tools ──────────────────────────────────────────────────────────────
408
+
409
+ /** Direct tool invocation, transport-free. The wire calls this; so do tests. */
410
+ async call(name: string, args: Record<string, unknown>): Promise<ToolResult> {
411
+ // THE SCOPE GATE, BEFORE EVERYTHING — before the observer stand-down and
412
+ // before any session bind. A directory somebody switched `off` gets no
413
+ // deposits, no reads and no census, and the refusal is NAMED (`scope-off`)
414
+ // so it is not mistaken for a broken server, an unbound session or a
415
+ // stand-down. The one exception is `scope` itself: every other tool
416
+ // refusing there means a door that refused too would lock from the outside,
417
+ // and turning a directory back on from inside the session that wants it is
418
+ // the whole point of the tool.
419
+ if (name !== "scope") {
420
+ const verdict = this.scopeVerdict();
421
+ if (stanceOfMode(verdict.mode) === "off") return this.refuseScopeOff(name, verdict);
422
+ }
423
+ switch (name) {
424
+ case "note":
425
+ return this.noteTool(args);
426
+ case "recall":
427
+ return await this.recallTool(args);
428
+ case "status":
429
+ return this.statusTool();
430
+ case "session_end":
431
+ return this.sessionEndTool(args);
432
+ case "chapter":
433
+ return this.chapterTool(args);
434
+ case "scope":
435
+ return this.scopeTool(args);
436
+ case "self_page":
437
+ return this.selfPageTool(args);
438
+ default:
439
+ return this.refuse(name, "unknown-tool", { tool: name });
440
+ }
441
+ }
442
+
443
+ // ── the scope registry ─────────────────────────────────────────────────────
444
+
445
+ /**
446
+ * What `<config dir>/scopes.json` says about THIS server's directory, read
447
+ * fresh. Absent registry, absent file, unreadable file: all `unset`, which is
448
+ * on — the same fail direction the hooks take, and for the same reason (a
449
+ * tool may not fail on host trivia).
450
+ */
451
+ private scopeVerdict(): ScopeVerdict {
452
+ if (this.scopesFile === null) return { mode: "unset", matched: null, entry: null };
453
+ return lookupScope(readScopes(this.scopesFile).registry, this.scope);
454
+ }
455
+
456
+ /** The named refusal every tool but `scope` gets in a directory set `off`. */
457
+ private refuseScopeOff(tool: string, verdict: ScopeVerdict): ToolResult {
458
+ this.emit("mcp.scope.off", undefined, { tool, matched: verdict.matched, mode: verdict.mode });
459
+ return this.refuse(tool, "scope-off", {
460
+ scope: this.scope,
461
+ ...(verdict.matched === null ? {} : { setBy: verdict.matched }),
462
+ detail:
463
+ verdict.mode === "paused"
464
+ ? "Counterparts is paused for this directory. Nothing is recorded or read here until it is resumed — call `scope` with mode `resume`, or run `counterparts scope . --resume`."
465
+ : "Counterparts is off for this directory. Nothing is recorded or read here — call `scope` with mode `on`, or run `counterparts scope . --on`.",
466
+ });
467
+ }
468
+
469
+ /**
470
+ * `scope` — read, or set, what this directory is for (owner asks G41–G43).
471
+ *
472
+ * The path is `this.scope` and there is no argument for one: a model that
473
+ * could name the directory could switch off a project it is not in. Reading
474
+ * is allowed in every stance, including observer and `off`, because "why did
475
+ * this session record nothing" must always be answerable; writing refuses
476
+ * under observer exactly as every other write does.
477
+ */
478
+ private scopeTool(args: Record<string, unknown>): ToolResult {
479
+ const mode = args["mode"];
480
+ const file = this.scopesFile;
481
+ const verdict = this.scopeVerdict();
482
+ const read = file === null ? null : readScopes(file);
483
+
484
+ if (mode === undefined) {
485
+ this.emit("mcp.scope.read", undefined, { mode: verdict.mode, matched: verdict.matched });
486
+ return this.result(
487
+ {
488
+ scope: this.scope,
489
+ mode: verdict.mode,
490
+ stance: stanceOfMode(verdict.mode),
491
+ ...(verdict.matched === null ? {} : { setBy: verdict.matched }),
492
+ ...(verdict.entry?.since === undefined ? {} : { since: verdict.entry.since }),
493
+ ...(verdict.entry?.note === undefined ? {} : { note: verdict.entry.note }),
494
+ ...(verdict.mode === "paused" ? { resumesTo: resumeTarget(verdict.entry) } : {}),
495
+ ...(file === null ? {} : { registry: file }),
496
+ // A registry in trouble is never silent, on any surface that has a
497
+ // reader (#92 review, F2): entries nobody can honour read as unset,
498
+ // which is ON, and this is the one place a model can see that.
499
+ ...(read === null || read.error === null ? {} : { registryError: read.error }),
500
+ ...(read === null || read.refused.length === 0
501
+ ? {}
502
+ : { registryRefused: read.refused.map((r) => `${r.key} (${r.detail})`) }),
503
+ detail:
504
+ verdict.mode === "unset"
505
+ ? "Nothing is set for this directory or any parent, so it is on by default. Ask the user before setting it."
506
+ : "This is what the host's scope registry says about this directory.",
507
+ },
508
+ false,
509
+ );
510
+ }
511
+
512
+ if (typeof mode !== "string" || !["on", "observer", "off", "pause", "resume"].includes(mode)) {
513
+ return this.refuse("scope", "mode-unusable", {
514
+ detail: "`mode` takes on, observer, off, pause or resume — or omit it to read the setting.",
515
+ });
516
+ }
517
+ if (this.observer) return this.standDown("scope");
518
+ if (file === null) {
519
+ return this.refuse("scope", "no-registry", {
520
+ detail:
521
+ "This server was launched without a scope registry to write, so it can only read. Use `counterparts scope <path> --on|--observer|--off` instead.",
522
+ });
523
+ }
524
+ if (read !== null && read.error !== null) {
525
+ return this.refuse("scope", "registry-unreadable", {
526
+ registry: file,
527
+ detail: `The registry could not be read — ${read.error}. Nothing was changed; a person has to fix it (\`counterparts scope <path> --off --force\` replaces it).`,
528
+ });
529
+ }
530
+ // ENTRIES THIS READ REFUSED (#92 review, F2). The file parses, so this tool
531
+ // COULD write — and a write rewrites the whole file from what parsed, which
532
+ // would silently delete another directory's `off`. A model may not make that
533
+ // trade on somebody's behalf: it refuses, names them, and leaves it to the
534
+ // person at the console (`counterparts scope <path> --off --force`).
535
+ if (read !== null && read.refused.length > 0) {
536
+ return this.refuse("scope", "registry-partly-unreadable", {
537
+ registry: file,
538
+ refused: read.refused.map((r) => `${r.key} (${r.detail})`),
539
+ detail: `${String(read.refused.length)} ${read.refused.length === 1 ? "entry" : "entries"} in this registry could not be read, and every write rewrites the whole file — so writing here would drop ${read.refused.length === 1 ? "it" : "them"}. Nothing was changed. Tell the user; fixing the file, or \`counterparts scope <path> --<mode> --force\`, is a person's call.`,
540
+ });
541
+ }
542
+
543
+ let target: ScopeMode;
544
+ if (mode === "resume") {
545
+ const own = ownEntry(read?.registry ?? null, this.scope);
546
+ if (own === null) {
547
+ return this.refuse("scope", "nothing-to-resume", {
548
+ detail:
549
+ verdict.entry === null
550
+ ? "Nothing is set for this directory, so it is already on."
551
+ : `Nothing is set for this directory itself — it inherits ${verdict.matched ?? "?"}. Set this one directly instead.`,
552
+ });
553
+ }
554
+ target = resumeTarget(own);
555
+ } else {
556
+ target = mode === "pause" ? "paused" : (mode as ScopeMode);
557
+ }
558
+
559
+ // ONE function for the change, applied to the registry this call read and —
560
+ // if the file moved under it — to what is there now (#92 review, F3). The
561
+ // other writer is the console `scope` command, in another process.
562
+ const apply = (from: ScopeRegistry | null): ScopeRegistry =>
563
+ setScope(from, this.scope, target, {
564
+ at: new Date(this.nowFn()).toISOString(),
565
+ // ONE RULE FOR THE NOTE ON BOTH SURFACES (#92 review, F5): an omitted
566
+ // note CARRIES what is there, an empty string CLEARS it. The filter here
567
+ // used to drop `""` as though it had not been given, so the console
568
+ // cleared a note and this tool silently kept it — the same two words
569
+ // meaning different things depending on which door you used.
570
+ ...(typeof args["note"] === "string" ? { note: args["note"] } : {}),
571
+ });
572
+ const next = apply(read?.registry ?? null);
573
+ try {
574
+ if (read === null) writeScopes(file, next);
575
+ else writeScopes(file, next, { basedOn: read, reapply: apply });
576
+ } catch (err) {
577
+ return this.refuse("scope", "registry-unwritable", {
578
+ registry: file,
579
+ detail: `The registry could not be written (${err instanceof Error ? err.message : String(err)}). Nothing was changed.`,
580
+ });
581
+ }
582
+ this.emit("mcp.scope.set", undefined, { mode: target, scope: this.scope });
583
+ return this.result(
584
+ {
585
+ set: true,
586
+ scope: this.scope,
587
+ mode: target,
588
+ stance: stanceOfMode(target),
589
+ registry: file,
590
+ detail:
591
+ target === "off" || target === "paused"
592
+ ? "This directory is no longer recorded or read. The hooks will produce nothing here and every other tool will refuse until it is turned back on — including in a new session, which is the point."
593
+ : // WHAT TURNING IT BACK ON ACTUALLY DOES, said exactly (#92 review,
594
+ // F1). It is not "the next session": the hooks act at their next
595
+ // boundary in THIS one. What they do not do is reach back — a
596
+ // session that started outside the memory has its first boundary
597
+ // move the read cursor past everything already said, recording
598
+ // none of it, so the stretch that ran while this directory was
599
+ // off or paused stays out of the memory for good.
600
+ "Recorded. This takes effect for the tools immediately, and for the hooks at their next boundary in this session. Nothing said before now is recorded — the conversation that happened while this directory was off or paused is passed over, not collected — and remembering starts from here.",
601
+ },
602
+ false,
603
+ );
604
+ }
605
+
606
+ /**
607
+ * `note` — deliberate remembering, the ambient exception (constitution 8).
608
+ *
609
+ * Two steps, and the ORDER is the point: the words ride the buffer as their
610
+ * own span first, then the deposit claims that span by hash. Without the
611
+ * claim the end-of-session sweep would find the jot's own text sitting in the
612
+ * buffer and mint it a second time, so the deliberate note would cost two
613
+ * memories — which is how a "remember this" channel becomes a duplication
614
+ * engine.
615
+ */
616
+ private async noteTool(args: Record<string, unknown>): Promise<ToolResult> {
617
+ if (this.observer) return this.standDown("note");
618
+ const text = args["text"];
619
+ if (typeof text !== "string" || text.trim().length === 0) {
620
+ return this.refuse("note", "text-required", {});
621
+ }
622
+ const salience = args["salience"];
623
+ if (salience !== undefined && (typeof salience !== "number" || !Number.isFinite(salience))) {
624
+ return this.refuse("note", "salience-not-a-number", {});
625
+ }
626
+ const dims = readDimensions(args);
627
+ if (dims === null) {
628
+ return this.refuse("note", "dimension-out-of-range", {
629
+ detail: "relevance, emotional and predictive are each a number from 0 to 1.",
630
+ });
631
+ }
632
+ const session = this.session ?? "mcp";
633
+
634
+ const captured = this.counterpart.captureJot({ session, scope: this.scope, text });
635
+ const ownSpanHash = captured.spans[0]?.hash ?? null;
636
+
637
+ const draft: Record<string, unknown> = { content: text };
638
+ if (typeof args["kind"] === "string") draft["kind"] = args["kind"];
639
+ if (typeof args["title"] === "string") draft["title"] = args["title"];
640
+ // `updates` travels as a FIELD, exactly as it does on a `session_end` entry
641
+ // (added 2026-09-04: the Stop ask told the model to write `updates: <id>`
642
+ // and this tool had nowhere to put it, so four notes landed as prose with no
643
+ // link). The declaration is resolved downstream — `remember/updates.ts`
644
+ // validates it, `mint.ts` writes the RESOLVED id — and one that resolves to
645
+ // nothing lands unlinked rather than refusing the note.
646
+ if (typeof args["updates"] === "string") draft["updates"] = args["updates"];
647
+ if (salience !== undefined) draft["claimed"] = salience;
648
+ if (Object.keys(dims).length > 0) draft["salience"] = dims;
649
+
650
+ const deposit = await this.counterpart.submitJot(draft, {
651
+ session,
652
+ scope: this.scope,
653
+ ownSpanHash,
654
+ });
655
+ return this.depositResult("note", deposit);
656
+ }
657
+
658
+ /**
659
+ * `recall` — the deeper look. Deposits no memory and touches no physics; see
660
+ * `deliberate.ts`. The ONE thing it writes is host state: a handle path that
661
+ * was answered leaves a line in `adapters/expansions.ts`'s resolution log, so
662
+ * the boundary's credit pass can tell which memory a TITLE reached
663
+ * (`noteHandleResolution`, and `mcp/INTERFACE-GAPS` §9).
664
+ */
665
+ private async recallTool(args: Record<string, unknown>): Promise<ToolResult> {
666
+ if (this.observer) return this.standDown("recall");
667
+ const handle = args["handle"];
668
+ const question = args["question"];
669
+ const ids = args["ids"];
670
+ if (handle !== undefined && typeof handle !== "string") {
671
+ return this.refuse("recall", "handle-not-a-string", {});
672
+ }
673
+ if (question !== undefined && typeof question !== "string") {
674
+ return this.refuse("recall", "question-not-a-string", {});
675
+ }
676
+ if (ids !== undefined && (!Array.isArray(ids) || ids.some((v) => typeof v !== "string"))) {
677
+ return this.refuse("recall", "ids-not-a-string-array", {});
678
+ }
679
+ const askedIds = ((ids as string[] | undefined) ?? []).map((s) => s.trim()).filter((s) => s.length > 0);
680
+ // IN LINE, and only for a question: the handle and `ids` paths are exact
681
+ // addresses and embedding them would buy nothing but a round trip. A refusal
682
+ // is a NAME, not a narrower answer — `deliberateRecall` degrades to lexical
683
+ // and says which.
684
+ const asked = typeof question === "string" && question.trim().length > 0;
685
+ const embedded = asked ? await this.embedQuestion(question) : { vector: null, semantic: "none" as SemanticSource };
686
+ const result = deliberateRecall(
687
+ this.counterpart,
688
+ {
689
+ ...(typeof handle === "string" ? { handle } : {}),
690
+ ...(typeof question === "string" ? { question } : {}),
691
+ ...(askedIds.length > 0 ? { ids: askedIds } : {}),
692
+ },
693
+ {
694
+ sessionId: this.session ?? "mcp",
695
+ owner: this.owner,
696
+ vector: embedded.vector,
697
+ semantic: embedded.semantic,
698
+ },
699
+ );
700
+ const resolved = this.noteHandleResolution(handle, result);
701
+ const payload = this.recallPayload(result);
702
+ this.emit("mcp.recall", undefined, {
703
+ path: result.path,
704
+ reason: result.reason,
705
+ // G50: did this call earn credit that `reference.ts` could not have given
706
+ // it on its own? Ring-only, like every other number on this row.
707
+ handleResolved: resolved,
708
+ semantic: result.semantic,
709
+ returned: result.memories.length,
710
+ considered: result.considered,
711
+ storeSize: result.storeSize,
712
+ owner: this.owner,
713
+ // Scar §2.4: a budget gets an event when it is APPROACHED, not only when
714
+ // it blows. The three overflowed calls of 2026-09-04 emitted nothing.
715
+ chars: payload["chars"] as number,
716
+ truncated: payload["truncated"] === true,
717
+ droppedForBudget: (payload["droppedForBudget"] as number | undefined) ?? 0,
718
+ });
719
+ this.noteRecall(result, askedIds.length, question, resolved, payload);
720
+ const bad =
721
+ result.reason === "no-argument" ||
722
+ result.reason === "both-arguments" ||
723
+ result.reason === "handle-unknown" ||
724
+ result.reason === "ids-too-many" ||
725
+ result.reason === "handle-confidential-withheld";
726
+ return this.result(payload, bad);
727
+ }
728
+
729
+ /**
730
+ * THE DURABLE ROW for one deliberate recall (2026-09-20, E2).
731
+ *
732
+ * `docs/recall-surfacing-diagnosis-2026-09-18.md`: this adapter wrote no
733
+ * durable row at all, so "the session went looking and nothing came" and "the
734
+ * session never went looking" were the same silence, and the fired view could
735
+ * only call the mechanism blind. The ring emit above is unchanged — it is the
736
+ * live debugging channel and it dies with the process; this is the fact that
737
+ * outlives it.
738
+ *
739
+ * **Never the question.** `queryChars` is its LENGTH: a deliberate question
740
+ * is the one string on this path that could carry somebody's private words,
741
+ * and a row in a store that will be read months later may not hold it (scar
742
+ * §2.20). No memory ids either — the counts answer this row's question, and a
743
+ * durable pairing of ids with the moment somebody asked for them is a link
744
+ * the store has no need of.
745
+ *
746
+ * `blockedBy` DOES carry `confidential-withheld`, which the wire deliberately
747
+ * does not (§9.1 G5). The two audiences are different: the caller may be any
748
+ * session, and the row is the owner's own store, where the memory itself is
749
+ * already sitting. Without it the confidentiality gate stays exactly as
750
+ * unreadable as the inventory found it — a withholding that happened and one
751
+ * that never had to, the same absence.
752
+ *
753
+ * Never throws: a tool answer may not fail because its telemetry did.
754
+ */
755
+ private noteRecall(
756
+ result: DeliberateResult,
757
+ askedIds: number,
758
+ question: unknown,
759
+ handleResolved: boolean,
760
+ payload: Record<string, unknown>,
761
+ ): void {
762
+ const byAddress = result.path === "handle";
763
+ const blockedBy: Record<string, number> = { ...(result.blockedBy ?? {}) };
764
+ // The address paths' refusals are their own `reason` — one per id on the
765
+ // `ids` path, so three unknown ids read as three and not as one.
766
+ if (byAddress) {
767
+ const reasons =
768
+ result.perId === undefined
769
+ ? result.reason === "expanded"
770
+ ? []
771
+ : [result.reason]
772
+ : result.perId.filter((p) => p.reason !== "expanded").map((p) => p.reason);
773
+ for (const r of reasons) blockedBy[r] = (blockedBy[r] ?? 0) + 1;
774
+ } else if (result.path === "none") {
775
+ blockedBy[result.reason] = (blockedBy[result.reason] ?? 0) + 1;
776
+ }
777
+ try {
778
+ this.counterpart.noteAdapterEvent(MCP_RECALL_EVENT, {
779
+ path: result.path,
780
+ reason: result.reason,
781
+ // WHAT WAS ASKED, as shapes and sizes. Never the words.
782
+ queryChars: typeof question === "string" ? question.trim().length : 0,
783
+ askedIds,
784
+ handleResolved,
785
+ semantic: result.semantic,
786
+ // What came back, split the way the reader's question splits: an
787
+ // expansion answered an address, a surfacing answered a question.
788
+ surfaced: byAddress ? 0 : result.memories.filter((m) => m.tier !== "dim").length,
789
+ dim: byAddress ? 0 : result.memories.filter((m) => m.tier === "dim").length,
790
+ expanded: byAddress ? result.memories.length : 0,
791
+ considered: result.considered,
792
+ storeSize: result.storeSize,
793
+ owner: this.owner,
794
+ chars: payload["chars"] ?? 0,
795
+ truncated: payload["truncated"] === true,
796
+ droppedForBudget: payload["droppedForBudget"] ?? 0,
797
+ // THE POINT OF THE ROW: what kept the rest out, by name.
798
+ blockedBy,
799
+ });
800
+ } catch {
801
+ // The ring emit above already carries this call; a telemetry write that
802
+ // failed must not become the answer the model receives.
803
+ }
804
+ }
805
+
806
+ /**
807
+ * THE HANDLE-EXPANSION CREDIT SEAM (LAUNCH-STATUS G50), the tool half.
808
+ *
809
+ * A deliberate expansion BY TITLE read the whole memory and earned nothing:
810
+ * the boundary's credit pass takes its expansions from the transcript, and
811
+ * `recall/reference.ts` credits literal `mem_…` addresses only — a title is
812
+ * counted `unresolvedHandles` and credits nothing, because that module
813
+ * resolves nothing fuzzily and must not start. The resolution belongs to
814
+ * whoever performed it, which is this tool, so this tool records it
815
+ * (`adapters/expansions.ts`) and the hook translates the transcript's own
816
+ * handle with it.
817
+ *
818
+ * EVERY OUTCOME OF THIS PATH IS RECORDED, and the refusals are recorded as
819
+ * `null` — a shadow that translates nothing and, being the newest answer,
820
+ * overrides an earlier resolution of the same handle IN THE SAME PROJECT.
821
+ * That is not tidiness, it is §5 G6: the log is keyed by the handle, because
822
+ * RESOLUTION is deterministic, but a REFUSAL is not. The owner's own session
823
+ * resolves a confidential title; a stranger's session asking the same title
824
+ * is told nothing. `handle-unknown` and `handle-ambiguous` shadow for the same
825
+ * reason — a title since renamed away, or gone ambiguous, must not go on
826
+ * crediting the memory it used to name.
827
+ *
828
+ * **THE SHADOW IS NOT THE CONFIDENTIALITY BOUNDARY, and the first draft of
829
+ * this method said it was.** A shadow only exists where an answer was given.
830
+ * Three askings get no answer and leave no shadow — a call that never reached
831
+ * `expandHandle`, a `{ handle, question }` the dispatcher refuses as
832
+ * `both-arguments` before this path exists, and a refusal whose write failed
833
+ * (`recordHandleResolution` returns false; it may not throw at a tool). Each
834
+ * of those still puts the title in the transcript, so each still reaches a
835
+ * boundary looking for a translation. What stops them is the SCOPE recorded on
836
+ * every line, which `readHandleResolutions` filters on: another project's
837
+ * resolution cannot answer this project's handle. `scope` is therefore
838
+ * load-bearing here, not forensics.
839
+ *
840
+ * Filtering also retires the price the first draft accepted — a stranger's
841
+ * refusal between the owner's call and the owner's Stop costing the owner the
842
+ * credit — because that shadow now carries the stranger's scope.
843
+ *
844
+ * The `ids` path is out of scope: those are literal addresses the credit pass
845
+ * already sees, and a per-id account of what each resolved to is `perId`'s
846
+ * job, not this one's.
847
+ *
848
+ * Never throws and never changes the answer. A write that FAILED is not
849
+ * symmetrical, though, and the asymmetry is worth naming: a lost RESOLUTION
850
+ * costs credit (safe), a lost REFUSAL leaves an older resolution standing
851
+ * where a shadow should have been (not safe). Across projects the scope filter
852
+ * makes that moot — the older resolution belongs to a directory the next
853
+ * boundary is not in. Within one project directory it is the residual this
854
+ * seam is known to carry.
855
+ */
856
+ private noteHandleResolution(handle: unknown, result: DeliberateResult): boolean {
857
+ if (typeof handle !== "string" || handle.trim().length === 0) return false;
858
+ if (result.path !== "handle") return false;
859
+ const id = resolvedIdOf(result);
860
+ if (id === undefined) return false;
861
+ const written = recordHandleResolution(this.registryDir, {
862
+ handle,
863
+ id,
864
+ scope: this.scope,
865
+ at: this.nowFn(),
866
+ });
867
+ return written && id !== null;
868
+ }
869
+
870
+ /**
871
+ * One embedding call, and every way it can decline, by name. The credential
872
+ * itself never appears here — `openEmbedder` was handed one at the entry point
873
+ * and this file only ever sees vectors or null.
874
+ */
875
+ private async embedQuestion(
876
+ question: string,
877
+ ): Promise<{ vector: number[] | null; semantic: SemanticSource }> {
878
+ if (this.embedder === null) return { vector: null, semantic: "embedder-off" };
879
+ try {
880
+ const vector = await this.embedder.vector(question);
881
+ return vector === null || vector.length === 0
882
+ ? { vector: null, semantic: "embed-failed" }
883
+ : { vector, semantic: "in-line" };
884
+ } catch {
885
+ return { vector: null, semantic: "embed-failed" };
886
+ }
887
+ }
888
+
889
+ /**
890
+ * The payload, BOUNDED. A list answers "which memories" and ships excerpts;
891
+ * an address (`handle`, or `ids`) answers "what did it say" and ships as much
892
+ * body as the total budget allows. See `deliberate.ts`'s size constants for
893
+ * the measurement that set them.
894
+ */
895
+ private recallPayload(result: DeliberateResult): Record<string, unknown> {
896
+ const byAddress = result.path === "handle";
897
+ const bounded = boundMemories(
898
+ result.memories,
899
+ byAddress ? RECALL_BODY_CHARS : RECALL_EXCERPT_CHARS,
900
+ );
901
+ return {
902
+ path: result.path,
903
+ reason: result.reason,
904
+ /** Said out loud, never inferred from a thinner answer: when the semantic
905
+ * channel could not run, the asker is told which channel answered. */
906
+ semantic: result.semantic,
907
+ /** The two numbers §9.1 G3 exists for: a count here is never a top-K. */
908
+ considered: result.considered,
909
+ /** `considered` is `MAX_CANDIDATES`, and saying so is the difference
910
+ * between a bound and a census (§9.1 G3). Read from the recall instance
911
+ * in force, not the module default, or a calibration override would be
912
+ * invisible in the one place the number is explained. */
913
+ consideredCap: this.counterpart.recall.tunables.MAX_CANDIDATES,
914
+ storeSize: result.storeSize,
915
+ returned: bounded.memories.length,
916
+ chars: bounded.chars,
917
+ truncated: bounded.truncated,
918
+ ...(bounded.droppedForBudget > 0 ? { droppedForBudget: bounded.droppedForBudget } : {}),
919
+ ...(bounded.truncated || bounded.droppedForBudget > 0
920
+ ? {
921
+ budget: `Result bounded to ${RECALL_RESULT_CHARS} characters (${RECALL_EXCERPT_CHARS} per memory in a list, ${RECALL_BODY_CHARS} when asked for by id). Ask again with ids: [...] for up to ${RECALL_MAX_IDS} full bodies.`,
922
+ }
923
+ : {}),
924
+ ...(result.ambiguous.length > 0 ? { ambiguous: [...result.ambiguous] } : {}),
925
+ ...(result.perId === undefined ? {} : { perId: result.perId.map((p) => ({ ...p })) }),
926
+ ...(result.reason === "ids-too-many"
927
+ ? { refused: `At most ${RECALL_MAX_IDS} ids per call. Effort is not enumeration.` }
928
+ : {}),
929
+ ...(result.reason === "handle-confidential-withheld"
930
+ ? {
931
+ withheld:
932
+ "That memory is marked confidential and this is not the owner's own session. It exists; it is not being shown.",
933
+ }
934
+ : {}),
935
+ memories: bounded.memories.map((m) => ({ ...m })),
936
+ /** The label the ruling of 2026-09-04 put on every delivered chapter,
937
+ * glossed once here so `journal: true` on a row is not a bare boolean the
938
+ * reader has to guess the meaning of (`deliberate.ts#JOURNAL_GLOSS`).
939
+ * CONDITIONAL, like `budget`, `refused` and `withheld` beside it: 207
940
+ * bytes explaining a flag that is not on any row is the wire budget spent
941
+ * on a word nobody read. */
942
+ ...(bounded.memories.some((m) => m.journal) ? { journal: JOURNAL_GLOSS } : {}),
943
+ tiers: {
944
+ vivid: "came clearly to mind",
945
+ quiet: "quietly available — the ambient path would have footnoted this",
946
+ dim: "reached only because you asked deliberately; lower confidence, and labeled so",
947
+ },
948
+ };
949
+ }
950
+
951
+ /**
952
+ * `status` — the census (§5 G7). Counts, kinds, bands, dates. No ids, no
953
+ * bodies, and NO CONTENT HASHES: a hash of low-entropy content is
954
+ * brute-forceable, so a hash in the record of a removal is a leak of the
955
+ * thing removed (scar §2.20).
956
+ *
957
+ * The symmetry counters are the useful minimum CONTRACT §7 OQ2 names —
958
+ * created versus exited per kind. They are the numbers that made v1's
959
+ * pathologies visible; a store census on its own never did.
960
+ */
961
+ private statusTool(): ToolResult {
962
+ if (this.observer) return this.standDown("status");
963
+ const census = this.census();
964
+ this.emit("mcp.status", undefined, {
965
+ live: census["live"] as number,
966
+ removed: (census["removed"] as Record<string, unknown>)["count"] as number,
967
+ });
968
+ return this.result(census, false);
969
+ }
970
+
971
+ private census(): Record<string, unknown> {
972
+ const store = this.counterpart.store;
973
+ const kinds: Kind[] = ["self", "person", "entity", "skill", "place", "fact"];
974
+ const bands: Band[] = ["episodic", "semantic", "identity"];
975
+
976
+ const denied = new Set(store.deniedIds());
977
+ const created: Record<string, number> = {};
978
+ const exited: Record<string, number> = {};
979
+ const byBand: Record<string, number> = {};
980
+ let live = 0;
981
+ let archived = 0;
982
+ let superseded = 0;
983
+ // Journal entries, counted APART. An episode is the source a memory was
984
+ // made from, not a memory: it is outside every sleep phase
985
+ // (`sleep/types.ts#isJournal`), so counting it among the memories would
986
+ // report as "held" a row that neither decays nor exits. Reported rather
987
+ // than dropped, because a number that quietly excludes something is the
988
+ // kind of census §16 forbids.
989
+ let journal = 0;
990
+
991
+ for (const kind of kinds) {
992
+ const ids = store.list({ kind });
993
+ let born = 0;
994
+ let gone = 0;
995
+ for (const id of ids) {
996
+ const row = store.row(id);
997
+ if (row === undefined) continue;
998
+ if (row.type === "episode") {
999
+ if (row.archived === 0 && !denied.has(id)) journal += 1;
1000
+ continue;
1001
+ }
1002
+ born += 1;
1003
+ if (denied.has(id)) {
1004
+ gone += 1;
1005
+ continue;
1006
+ }
1007
+ if (row.archived === 1) {
1008
+ gone += 1;
1009
+ archived += 1;
1010
+ continue;
1011
+ }
1012
+ if (row.superseded_by !== null) {
1013
+ gone += 1;
1014
+ superseded += 1;
1015
+ continue;
1016
+ }
1017
+ live += 1;
1018
+ byBand[row.band] = (byBand[row.band] ?? 0) + 1;
1019
+ }
1020
+ created[kind] = born;
1021
+ exited[kind] = gone;
1022
+ }
1023
+ for (const band of bands) byBand[band] = byBand[band] ?? 0;
1024
+
1025
+ // Removals: counts, kinds, dates. Never an id — the enumeration of what was
1026
+ // removed is the CLI's owner-side surface, not the model's.
1027
+ const dates = new Set<string>();
1028
+ const removedKinds: Record<string, number> = {};
1029
+ const removedIds = new Set<string>();
1030
+ for (const row of store.removalRecord()) {
1031
+ if (row.stage !== "complete") continue;
1032
+ removedIds.add(row.memory_id);
1033
+ dates.add(new Date(row.at).toISOString().slice(0, 10));
1034
+ const kind = store.row(row.memory_id)?.kind ?? "unknown";
1035
+ removedKinds[kind] = (removedKinds[kind] ?? 0) + 1;
1036
+ }
1037
+
1038
+ return {
1039
+ live,
1040
+ archived,
1041
+ superseded,
1042
+ journal,
1043
+ byKind: created,
1044
+ byBand,
1045
+ /** OQ2's symmetry counters: born versus left, per kind. */
1046
+ symmetry: { created, exited },
1047
+ removed: {
1048
+ count: removedIds.size,
1049
+ kinds: removedKinds,
1050
+ dates: [...dates].sort(),
1051
+ note: "Counts, kinds and dates only. No ids, no bodies, no hashes.",
1052
+ },
1053
+ counts: "Every number above is MEMORIES. `journal` is the first-person episodes those memories were made from: it is the source, not a memory, and it neither decays nor is pruned.",
1054
+ clock: {
1055
+ livedDay: store.livedDay(),
1056
+ lastActiveDate: store.getMeta("lastActiveDate") ?? null,
1057
+ },
1058
+ stance: { observer: this.observer, owner: this.owner },
1059
+ };
1060
+ }
1061
+
1062
+ /**
1063
+ * `session_end` — the MEMORIES half of the Stop ask's return channel.
1064
+ *
1065
+ * Per-entry failure isolation (scar E1): one refused entry announces itself
1066
+ * and its siblings still land. A single bad item failing the whole dump is
1067
+ * how a session's memory becomes all-or-nothing at exactly the moment there
1068
+ * is no second chance to write it.
1069
+ */
1070
+ private async sessionEndTool(args: Record<string, unknown>): Promise<ToolResult> {
1071
+ if (this.observer) return this.standDown("session_end");
1072
+ const bound = this.requireBoundSession(args["session"], "session_end");
1073
+ if (bound !== null) return bound;
1074
+
1075
+ // THE HANDOFF FIRST, and before the memories check on purpose (E1). It is a
1076
+ // FIELD on this call and not one of the entries, so a dump whose `memories`
1077
+ // array is malformed must not also throw away the one line telling the next
1078
+ // session in this directory where the work stands. The outcome rides out on
1079
+ // the refusal too, so nothing is lost silently either way.
1080
+ const handoff = this.writeHandoffField(args["handoff"]);
1081
+
1082
+ const raw = args["memories"];
1083
+ if (!Array.isArray(raw) || raw.length === 0) {
1084
+ return this.refuse("session_end", "memories-required", {
1085
+ ...(handoff === null ? {} : { handoff }),
1086
+ });
1087
+ }
1088
+ const session = this.session as string;
1089
+ const entries: Record<string, unknown>[] = [];
1090
+ for (const item of raw) {
1091
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
1092
+ entries.push({ content: "" });
1093
+ continue;
1094
+ }
1095
+ const rec = item as Record<string, unknown>;
1096
+ const draft: Record<string, unknown> = { content: rec["content"] };
1097
+ if (typeof rec["kind"] === "string") draft["kind"] = rec["kind"];
1098
+ if (typeof rec["title"] === "string") draft["title"] = rec["title"];
1099
+ if (typeof rec["updates"] === "string") draft["updates"] = rec["updates"];
1100
+ if (rec["salience"] !== undefined) draft["claimed"] = rec["salience"];
1101
+ // A bad dimension does NOT fail the batch and is not silently dropped:
1102
+ // the dimensions ride into the draft and `remember/intake` refuses that
1103
+ // one entry as malformed, which is this tool's per-entry isolation rule.
1104
+ const entryDims = readDimensions(rec) ?? pickDimensions(rec);
1105
+ if (Object.keys(entryDims).length > 0) draft["salience"] = entryDims;
1106
+ entries.push(draft);
1107
+ }
1108
+
1109
+ const outcomes: Record<string, unknown>[] = [];
1110
+ let deposited = 0;
1111
+ for (const draft of entries) {
1112
+ let result: DepositResult;
1113
+ try {
1114
+ result = await this.counterpart.submitSessionEnd(draft, {
1115
+ session,
1116
+ scope: this.scope,
1117
+ });
1118
+ } catch (err) {
1119
+ // Isolation, not a lost dump: this entry failed, the rest still run.
1120
+ outcomes.push({ stored: false, reason: "threw", detail: String((err as Error).message ?? err) });
1121
+ continue;
1122
+ }
1123
+ if (result.deposited) deposited += 1;
1124
+ // A refusal names what to fix. `malformed` alone sent the author back to
1125
+ // guess (IMPROVEMENTS U11: a kind outside the enum came back as a bare
1126
+ // "malformed"); intake's own reason rides out, and an unknown kind lists
1127
+ // the kinds that exist.
1128
+ const malformed = result.malformed ?? null;
1129
+ outcomes.push({
1130
+ stored: result.deposited,
1131
+ reason: result.reason,
1132
+ ...(result.memoryId === null ? {} : { id: result.memoryId }),
1133
+ ...(result.gate === null ? {} : { gate: result.gate }),
1134
+ ...(malformed === null ? {} : { malformed }),
1135
+ ...(malformed === "KIND_UNKNOWN" ? { kinds: [...MEMORY_KINDS] } : {}),
1136
+ });
1137
+ }
1138
+ this.emit("mcp.session_end", session, {
1139
+ entries: entries.length,
1140
+ deposited,
1141
+ refused: entries.length - deposited,
1142
+ handoff: handoff === null ? false : handoff["written"] === true,
1143
+ });
1144
+ return this.result(
1145
+ {
1146
+ session,
1147
+ entries: entries.length,
1148
+ deposited,
1149
+ refused: entries.length - deposited,
1150
+ outcomes,
1151
+ ...(handoff === null ? {} : { handoff }),
1152
+ },
1153
+ deposited === 0,
1154
+ );
1155
+ }
1156
+
1157
+ /**
1158
+ * The optional `handoff` field, written or refused, as the shape the tool
1159
+ * result carries back. Null when the caller passed none — which is the
1160
+ * ordinary case, and says nothing about this directory either way.
1161
+ *
1162
+ * **Three answers, and only the first is silence.**
1163
+ *
1164
+ * - **Absent** — the ordinary case. Nothing is written and nothing is said:
1165
+ * leaving the field out means "leave what stands", which is right.
1166
+ * - **Present and blank** — `handoff: ""` or `" "`. This is a CLEAR. It is
1167
+ * the shape a model reaches for when it means "the work here is finished",
1168
+ * and until 2026-09-20 it was total silence while the stale pointer stood
1169
+ * (adversarial review MAJOR-2b). It retires the directory's pointer and
1170
+ * leaves a durable row.
1171
+ * - **Present and not a string** — a named, durable refusal, because a
1172
+ * caller that sent the wrong type wants to know rather than to be ignored.
1173
+ *
1174
+ * The NO-SCOPE REFUSAL IS NOW DURABLE, which is what MAJOR-2a was: the
1175
+ * short-circuit that used to live here emitted a ring-only event and wrote no
1176
+ * row, so guarantee 3 was false on the only live door. The rule is asked in
1177
+ * two places on purpose and they are not duplicates — `handoff/` refuses an
1178
+ * empty scope and a scope that IS the store's directory, as a belt no caller
1179
+ * can get past; this file asks `sameScope`, which canonicalises (`/var` →
1180
+ * `/private/var` on this host), because it is the side that has the
1181
+ * canonicaliser and knows what `scopeSource` said. Either way the durable row
1182
+ * is written by `handoff/`, which owns guarantee 3.
1183
+ */
1184
+ private writeHandoffField(raw: unknown): Record<string, unknown> | null {
1185
+ if (raw === undefined || raw === null) return null;
1186
+ let out: ReturnType<Counterpart["writeHandoff"]>;
1187
+ try {
1188
+ if (typeof raw !== "string") {
1189
+ out = this.counterpart.refuseHandoff("not-text", { session: this.session });
1190
+ } else if (
1191
+ this.scopeSource === "store" ||
1192
+ sameScope(this.scope, this.counterpart.store.dir)
1193
+ ) {
1194
+ out = this.counterpart.refuseHandoff("no-scope", { session: this.session });
1195
+ } else if (raw.trim().length === 0) {
1196
+ out = this.counterpart.clearHandoff({ scope: this.scope, session: this.session });
1197
+ } else {
1198
+ out = this.counterpart.writeHandoff(raw, { scope: this.scope, session: this.session });
1199
+ }
1200
+ } catch (err) {
1201
+ return { written: false, reason: "threw", detail: String((err as Error).message ?? err) };
1202
+ }
1203
+ this.emit("mcp.handoff", out.id ?? undefined, {
1204
+ written: out.written,
1205
+ reason: out.reason,
1206
+ bytes: out.bytes,
1207
+ });
1208
+ return {
1209
+ written: out.written,
1210
+ reason: out.reason,
1211
+ ...(out.id === null ? {} : { id: out.id }),
1212
+ bytes: out.bytes,
1213
+ ...(out.version === null ? {} : { version: out.version }),
1214
+ ...(out.gate === null ? {} : { gate: out.gate }),
1215
+ ...(out.redacted === null ? {} : { redacted: true }),
1216
+ ...(out.showsForDays === null ? {} : { showsForDays: out.showsForDays }),
1217
+ };
1218
+ }
1219
+
1220
+ /**
1221
+ * `chapter` — the journal's door (self/CONTRACT §3: *which door reaches this?*).
1222
+ *
1223
+ * It composes, like everything else here: `Counterpart.appendEpisode` runs the
1224
+ * gate, `self/` decides whether this append opens a chapter or continues the
1225
+ * one already open, and the number that comes back is the number the store
1226
+ * WROTE. The ask reads the same counter, so the two sides cannot drift the way
1227
+ * they did for a fortnight — the model wrote eleven chapters as notes while
1228
+ * the hook's count said seven.
1229
+ */
1230
+ private async chapterTool(args: Record<string, unknown>): Promise<ToolResult> {
1231
+ if (this.observer) return this.standDown("chapter");
1232
+ const bound = this.requireBoundSession(args["session"], "chapter");
1233
+ if (bound !== null) return bound;
1234
+
1235
+ const text = args["text"];
1236
+ if (typeof text !== "string" || text.trim().length === 0) {
1237
+ return this.refuse("chapter", "text-required", {
1238
+ detail: "A chapter has to say something. Nothing worth writing is a real answer — say nothing at all instead.",
1239
+ });
1240
+ }
1241
+ const session = this.session as string;
1242
+ const title = args["title"];
1243
+ let written: ChapterResult;
1244
+ try {
1245
+ written = this.counterpart.appendEpisode(session, text, {
1246
+ ...(typeof title === "string" && title.length > 0 ? { title } : {}),
1247
+ });
1248
+ } catch (err) {
1249
+ // A journal that throws must not look like a journal that refused.
1250
+ return this.refuse("chapter", "threw", { detail: String((err as Error).message ?? err) });
1251
+ }
1252
+ this.emit("mcp.chapter", written.episodeId ?? undefined, {
1253
+ session,
1254
+ stored: written.appended,
1255
+ reason: written.reason,
1256
+ chapter: written.chapter,
1257
+ created: written.created,
1258
+ });
1259
+ return this.result(
1260
+ {
1261
+ stored: written.appended,
1262
+ reason: written.reason,
1263
+ session,
1264
+ episodeId: written.episodeId,
1265
+ // From the STORE, never from the ask count.
1266
+ chapter: written.chapter,
1267
+ created: written.created,
1268
+ ...(written.gate === null ? {} : { gate: written.gate }),
1269
+ },
1270
+ !written.appended,
1271
+ );
1272
+ }
1273
+
1274
+ /**
1275
+ * `self_page` — read the page, or write it whole.
1276
+ *
1277
+ * **It binds no session, exactly as `note` does not.** The page is not one
1278
+ * session's account of itself the way a chapter is; it is the standing one,
1279
+ * and a session that can write a note about the world can write the page about
1280
+ * itself. The `by` field on the row says `session` for everything that comes
1281
+ * through here, and no argument can change it: the console writes `owner` and
1282
+ * the nightly writer will write `writer`, from their own doors.
1283
+ *
1284
+ * READING is allowed in every stance the tool answers in at all, including
1285
+ * observer — "what does my page say" must always be answerable — and the
1286
+ * stand-down guards the WRITE alone, which is the shape `scope` already has.
1287
+ */
1288
+ private selfPageTool(args: Record<string, unknown>): ToolResult {
1289
+ const body = args["body"];
1290
+ if (body === undefined) return this.selfPageRead();
1291
+ if (this.observer) return this.standDown("self_page");
1292
+ // A NON-STRING body is a malformed call and stops here; an EMPTY one goes
1293
+ // THROUGH the seam, because the seam is what writes the durable refusal row
1294
+ // this tool's own description promises. The short-circuit that used to catch
1295
+ // both left `self_page({ body: " " })` as the one refusal on this path
1296
+ // with no row behind it (adversarial review m4).
1297
+ if (typeof body !== "string") {
1298
+ return this.refuse("self_page", "body-required", {
1299
+ detail:
1300
+ "A page has to say something. Pass the whole page as text; omit `body` entirely to read the one that is there.",
1301
+ });
1302
+ }
1303
+ const reason = args["reason"];
1304
+ const ifVersion = args["ifVersion"];
1305
+ if (
1306
+ ifVersion !== undefined &&
1307
+ (typeof ifVersion !== "number" || !Number.isInteger(ifVersion) || ifVersion < NO_PAGE_VERSION)
1308
+ ) {
1309
+ return this.refuse("self_page", "if-version-not-a-number", {
1310
+ detail:
1311
+ "`ifVersion` is the whole number the read gave you as `version` (-1 when there was no page), or leave it out.",
1312
+ });
1313
+ }
1314
+ // BIND FIRST, AND NON-FATALLY. This server is launched from a static host
1315
+ // configuration and never learns which session it serves; it binds lazily,
1316
+ // on the first tool call that carries an id (`requireBoundSession`). Every
1317
+ // other tool that needs one REFUSES without it — but this one has always
1318
+ // worked unbound, so a session claim here is honoured when it corroborates
1319
+ // and simply not honoured when it does not. The page is never refused over
1320
+ // it: what a bad claim costs is the `writer` label, and the ring says why.
1321
+ //
1322
+ // Without this, the page-writer ask could not work at all in session mode.
1323
+ // A session answering it right after its wake has called nothing else, so
1324
+ // `this.session` is null, so the registry mark is never read, so every
1325
+ // night's revision was filed as an ordinary amendment and the night read
1326
+ // as "nothing to say" — the exact inverse of the honesty this is for.
1327
+ const claimedSession = this.bindForPageWriter(args["session"]);
1328
+ // WHICH DOOR THIS IS. `by` is the door's and is not claimable from outside
1329
+ // (`self/page.ts`), so the model's word for "I am the nightly writer" is
1330
+ // worth nothing here. What the server reads instead is the mark the
1331
+ // SessionStart hook left on this session's registry record when it handed
1332
+ // over the page-writer ask, and it is a DATE: a session asked to write
1333
+ // about 09-19 writes `writer` for that run and nothing else, and a stale
1334
+ // mark cannot relabel a write made two days later (`adapters/sessions.ts`).
1335
+ const writerFor = this.pageWriterMark(claimedSession);
1336
+ const written = this.counterpart.revisePage(body, {
1337
+ reason: typeof reason === "string" && reason.trim().length > 0 ? reason.trim() : "amended",
1338
+ by: writerFor === null ? "session" : "writer",
1339
+ // WHICH SESSION, when this server has one. `note` resolves it the same
1340
+ // way; null is recorded rather than a guess (adversarial review M3).
1341
+ session: this.session,
1342
+ ...(ifVersion === undefined ? {} : { ifVersion }),
1343
+ });
1344
+ this.emit("mcp.self_page", written.id ?? undefined, {
1345
+ stored: written.written,
1346
+ reason: written.reason,
1347
+ bytes: written.bytes,
1348
+ version: written.version,
1349
+ writerFor: writerFor?.about ?? null,
1350
+ writerMode: writerFor?.mode ?? null,
1351
+ });
1352
+ // THE NIGHT'S OWN ROW, closed here because this is where the answer arrives.
1353
+ // Both arms are recorded: a refused revision is the writer having run and
1354
+ // been turned away, which is a different fact from a night that never
1355
+ // started, and only the row can tell them apart afterwards. A recording
1356
+ // failure costs the row and never the write (§5 G7).
1357
+ if (writerFor !== null) {
1358
+ try {
1359
+ this.counterpart.recordPageWriterRun({
1360
+ about: writerFor.about,
1361
+ mode: writerFor.mode,
1362
+ outcome: written.written ? "revised" : "refused",
1363
+ detail: written.written ? "" : written.reason,
1364
+ bytesAfter: written.written ? written.bytes : 0,
1365
+ });
1366
+ } catch {
1367
+ /* the page is written; the bookkeeping is not worth the answer */
1368
+ }
1369
+ }
1370
+ if (!written.written) {
1371
+ return this.refuse("self_page", written.reason, {
1372
+ bytes: written.bytes,
1373
+ ...(written.gate === null ? {} : { gate: written.gate }),
1374
+ // On a stale write, hand back what is actually there so the session can
1375
+ // merge rather than guess — the whole point of the check.
1376
+ ...(written.current === null
1377
+ ? {}
1378
+ : { currentVersion: written.current.version, currentBody: written.current.body }),
1379
+ detail: PAGE_REFUSAL_DETAIL[written.reason] ?? "The page was not written.",
1380
+ });
1381
+ }
1382
+ return this.result(
1383
+ {
1384
+ stored: true,
1385
+ reason: written.reason,
1386
+ id: written.id,
1387
+ version: written.version,
1388
+ bytes: written.bytes,
1389
+ // THE GATE CHANGED IT. Accepted is not the same as unaltered, and a
1390
+ // session told only `stored: true` would go on believing it wrote what
1391
+ // it sent (m1).
1392
+ ...(written.redacted === null
1393
+ ? {}
1394
+ : {
1395
+ redacted: true,
1396
+ redactedBy: written.redacted.gate,
1397
+ bytesBeforeRedaction: written.redacted.bytesBefore,
1398
+ }),
1399
+ ...(written.warning === null ? {} : { warning: written.warning }),
1400
+ // WHEN IT WILL BE READ, precisely. The bundle every session wakes with
1401
+ // is composed at a boundary and served unchanged until the next one, so
1402
+ // "it is live now" would be false for as long as this session lasts —
1403
+ // and the briefing phase is cadenced once per LIVED day, so a second
1404
+ // boundary today renders nothing at all.
1405
+ appearsAtWake: "the next boundary that re-renders the wake — once per lived day",
1406
+ },
1407
+ false,
1408
+ );
1409
+ }
1410
+
1411
+ private selfPageRead(): ToolResult {
1412
+ const page = this.counterpart.selfPage();
1413
+ if (page === null) {
1414
+ return this.result(
1415
+ {
1416
+ present: false,
1417
+ reason: "still-forming",
1418
+ // THE VERSION OF "NOTHING", so a session that was told to pass the
1419
+ // version back can do it on a first write too. Without a value here,
1420
+ // the natural `0` was refused with a sentence saying somebody else had
1421
+ // written the page, which was untrue (adversarial review MINOR-C).
1422
+ version: NO_PAGE_VERSION,
1423
+ detail:
1424
+ "No page has been written here yet. Write one when you have something true to say about yourself; while there is nothing, the honest page says it is still forming. Pass this `version` back as `ifVersion` if you want the write refused should one appear meanwhile.",
1425
+ },
1426
+ false,
1427
+ );
1428
+ }
1429
+ return this.result(
1430
+ {
1431
+ present: true,
1432
+ body: page.body,
1433
+ bytes: page.bytes,
1434
+ revisedOn: page.revisedOn,
1435
+ by: page.by,
1436
+ version: page.version,
1437
+ stale: this.counterpart.self.pageStale(page),
1438
+ // COUNTED, not read: `selfPageVersions().length` read every archived
1439
+ // body off disk to print one number, on every read a session makes
1440
+ // (adversarial review m9).
1441
+ versions: this.counterpart.selfPageVersionCount(),
1442
+ },
1443
+ false,
1444
+ );
1445
+ }
1446
+
1447
+ /**
1448
+ * The bound-session refusal, and the ONE way a server binds itself.
1449
+ *
1450
+ * Three states, in order:
1451
+ *
1452
+ * 1. **The host said so at launch** (`--session`). Unchanged and preferred:
1453
+ * the registry is never consulted, and a claim for another id is refused.
1454
+ * 2. **Already bound** — by launch or by an earlier claim. The bind is for
1455
+ * the process's lifetime, so a second, DIFFERENT id is refused with the
1456
+ * reason that says why.
1457
+ * 3. **Unbound.** The claim must name an id (never inferred — see the
1458
+ * CONTRACT's residual risk: two live sessions in one directory are
1459
+ * distinguishable only by the id the ask named), and that id must be in
1460
+ * the hooks' registry, live, and in THIS server's scope. Every refusal
1461
+ * says which of the four it was, because a model that cannot tell
1462
+ * "unknown id" from "wrong project" cannot do anything about either.
1463
+ */
1464
+ /**
1465
+ * IS THIS SESSION THE NIGHT'S WRITER, and for which day?
1466
+ *
1467
+ * `by` on a page revision is the DOOR's and is not claimable from outside
1468
+ * (`self/page.ts`), so this server may not take a tool argument's word for it.
1469
+ * The evidence is a mark only the SessionStart hook writes — `pageWriterFor`,
1470
+ * a DATE, on this session's registry record (`adapters/sessions.ts`) — and it
1471
+ * counts only while that night's claim is still open: a session that lives
1472
+ * past midnight, or one whose night has already been answered, writes as an
1473
+ * ordinary session again. Null on every other path, including an unbound
1474
+ * server, which is the direction that never over-claims.
1475
+ */
1476
+ /**
1477
+ * A session claim on the PAGE's door: corroborated if it can be, ignored if
1478
+ * it cannot, and never a refusal.
1479
+ *
1480
+ * `requireBoundSession` is reused rather than reimplemented — it is the only
1481
+ * place that knows what corroboration means (known to the hooks' registry,
1482
+ * live, and in this server's scope) and it already emits the reason on every
1483
+ * arm. Its refusal VALUE is discarded here, which is the whole difference
1484
+ * between this door and `chapter`'s: a page amendment has never needed a
1485
+ * session and must not start being refused for lack of one.
1486
+ */
1487
+ private bindForPageWriter(claimed: unknown): string | null {
1488
+ if (typeof claimed !== "string" || claimed.length === 0) return null;
1489
+ if (this.session !== null) return this.session === claimed ? claimed : null;
1490
+ // CORROBORATE WITHOUT BINDING (S2 review, MINOR-3). The first version called
1491
+ // `requireBoundSession`, which sets `lazySession` and FREEZES it for the
1492
+ // life of the process — so a page write naming another live in-scope
1493
+ // session would have bound this server to that session, and every later
1494
+ // `note` and `chapter` from it would have been attributed there. The page's
1495
+ // door needs one thing and one thing only: is this id a session I may
1496
+ // label a write with. That is a question, not a binding.
1497
+ const ok = this.corroborate(claimed);
1498
+ if (!ok) {
1499
+ this.emit("mcp.session.unbound", undefined, { reason: "page-writer-claim" });
1500
+ return null;
1501
+ }
1502
+ return claimed;
1503
+ }
1504
+
1505
+ /** Known to the hooks' registry, live, and in THIS server's scope — the same
1506
+ * three tests `requireBoundSession` makes, asked without the side effect. */
1507
+ private corroborate(claimed: string): boolean {
1508
+ const record = readSession(this.registryDir, claimed);
1509
+ if (record === null) return false;
1510
+ if (!isLive(record, this.nowFn(), this.sessionTtlMs)) return false;
1511
+ return sameScope(record.scope, this.scope);
1512
+ }
1513
+
1514
+ private pageWriterMark(
1515
+ claimedSession: string | null,
1516
+ ): { about: string; mode: PageWriterMode } | null {
1517
+ try {
1518
+ const about = this.pageWriterClaim(claimedSession);
1519
+ if (about === null) return null;
1520
+ // THE MODE COMES FROM THE CLAIM THIS IS CLOSING, not from the channel the
1521
+ // mark arrived by (S2 review, MINOR-2). The env var used to assert
1522
+ // `mode: "host"` on its own, so a session-mode night closed by a process
1523
+ // with that variable exported wrote `mode: host` on a durable row about a
1524
+ // night nothing started in host mode. The open claim knows which it was.
1525
+ const open = this.counterpart
1526
+ .pageWriterRuns({ about })
1527
+ .find((r) => r.outcome === "asked" || r.outcome === "started");
1528
+ if (open === undefined || !this.counterpart.pageWriterClaimOpen(about)) return null;
1529
+ return { about, mode: open.mode };
1530
+ } catch {
1531
+ return null;
1532
+ }
1533
+ }
1534
+
1535
+ /**
1536
+ * The two channels the mark can arrive by, and neither is the tool call.
1537
+ *
1538
+ * The ENVIRONMENT is host mode's: the launcher pins the date onto the
1539
+ * windowless child (`claude-code/page-writer.ts`), whose session id the host
1540
+ * mints after the launcher is gone, so there is no registry record to mark.
1541
+ * The REGISTRY is session mode's, written by the SessionStart hook at the
1542
+ * moment it hands the ask over. Both are checked against the night's claim by
1543
+ * the caller, so a value left lying in a shell reaches nothing.
1544
+ */
1545
+ private pageWriterClaim(claimedSession: string | null): string | null {
1546
+ const pinned = (this.env[PAGE_WRITER_ENV] ?? "").trim();
1547
+ if (/^\d{4}-\d{2}-\d{2}$/.test(pinned)) return pinned;
1548
+ // The session this call NAMED and that corroborated, else the one this
1549
+ // server was launched bound to. Never an uncorroborated claim.
1550
+ const id = claimedSession ?? this.session;
1551
+ if (id === null) return null;
1552
+ const about = readSession(this.registryDir, id)?.pageWriterFor;
1553
+ return about === undefined || about.length === 0 ? null : about;
1554
+ }
1555
+
1556
+ private requireBoundSession(claimed: unknown, tool: ToolName): ToolResult | null {
1557
+ const bound = this.session;
1558
+ if (bound !== null) {
1559
+ if (claimed !== undefined && claimed !== bound) {
1560
+ this.emit("mcp.session.mismatch", undefined, {
1561
+ bound: true,
1562
+ source: this.launchedSession !== null ? "launch" : "registry",
1563
+ });
1564
+ return this.refuse(tool, "session-mismatch", {
1565
+ detail:
1566
+ "This server is already bound to a different session, for the life of the process. A dump belongs to the session that lived it.",
1567
+ });
1568
+ }
1569
+ return null;
1570
+ }
1571
+
1572
+ if (typeof claimed !== "string" || claimed.length === 0) {
1573
+ this.emit("mcp.session.unbound", undefined, { reason: "no-claim" });
1574
+ return this.refuse(tool, "session-required", {
1575
+ detail:
1576
+ "This server was launched without a session. Pass `session` — the session id the end-of-session ask named — and it will bind to it.",
1577
+ });
1578
+ }
1579
+
1580
+ const record = readSession(this.registryDir, claimed);
1581
+ if (record === null) {
1582
+ this.emit("mcp.session.unbound", undefined, { reason: "unknown" });
1583
+ return this.refuse(tool, "session-unknown", {
1584
+ detail:
1585
+ "No live session by that id has been recorded by this host's hooks. Use the id the end-of-session ask named, exactly.",
1586
+ });
1587
+ }
1588
+ if (!isLive(record, this.nowFn(), this.sessionTtlMs)) {
1589
+ this.emit("mcp.session.unbound", undefined, {
1590
+ reason: record.endedAt === null ? "stale" : "ended",
1591
+ });
1592
+ return this.refuse(tool, "session-not-live", {
1593
+ detail:
1594
+ "That session has ended or has been silent too long to still be writing its own day. Its memories belong to the sweep now.",
1595
+ });
1596
+ }
1597
+ if (!sameScope(record.scope, this.scope)) {
1598
+ this.emit("mcp.session.unbound", undefined, { reason: "scope-mismatch" });
1599
+ return this.refuse(tool, "scope-mismatch", {
1600
+ detail:
1601
+ "That session is running in a different project than this server. A dump belongs to the project that lived it.",
1602
+ });
1603
+ }
1604
+
1605
+ this.lazySession = claimed;
1606
+ this.emit("mcp.session.bound", claimed, { source: "registry", scope: this.scope });
1607
+ return null;
1608
+ }
1609
+
1610
+ // ── result shapes ──────────────────────────────────────────────────────────
1611
+
1612
+ private depositResult(tool: string, deposit: DepositResult): ToolResult {
1613
+ this.emit(`mcp.${tool}`, deposit.memoryId ?? undefined, {
1614
+ stored: deposit.deposited,
1615
+ reason: deposit.reason,
1616
+ gate: deposit.gate,
1617
+ covers: deposit.covers.length,
1618
+ });
1619
+ const lifted = deposit.mint?.lifted ?? false;
1620
+ return this.result(
1621
+ {
1622
+ stored: deposit.deposited,
1623
+ reason: deposit.reason,
1624
+ ...(deposit.memoryId === null ? {} : { id: deposit.memoryId }),
1625
+ ...(deposit.gate === null ? {} : { gate: deposit.gate }),
1626
+ ...(lifted ? { salienceLifted: true } : {}),
1627
+ },
1628
+ !deposit.deposited,
1629
+ );
1630
+ }
1631
+
1632
+ /**
1633
+ * The stand-down (§5 G5, scars E7/§2.4). It is loud on purpose: a tool that
1634
+ * returned nothing under observer would be indistinguishable from a tool that
1635
+ * crashed, and v1 shipped exactly that ambiguity.
1636
+ */
1637
+ private standDown(tool: string): ToolResult {
1638
+ this.emit("mcp.observer.standdown", undefined, { tool });
1639
+ return this.result(
1640
+ {
1641
+ stoodDown: true,
1642
+ tool,
1643
+ stance: "observer",
1644
+ reason:
1645
+ "This session is an observer: it reads the store as an instrument and changes nothing in it. The tool did not run.",
1646
+ },
1647
+ true,
1648
+ );
1649
+ }
1650
+
1651
+ private refuse(
1652
+ tool: string,
1653
+ reason: string,
1654
+ extra: Record<string, unknown>,
1655
+ ): ToolResult {
1656
+ this.emit("mcp.refused", undefined, { tool, reason });
1657
+ return this.result({ stored: false, tool, reason, ...extra }, true);
1658
+ }
1659
+
1660
+ private result(payload: Record<string, unknown>, isError: boolean): ToolResult {
1661
+ return {
1662
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
1663
+ structuredContent: payload,
1664
+ ...(isError ? { isError: true } : {}),
1665
+ };
1666
+ }
1667
+
1668
+ private emit(
1669
+ name: string,
1670
+ ref?: string,
1671
+ data?: Record<string, string | number | boolean | null>,
1672
+ ): void {
1673
+ const event: McpEvent = { at: this.nowFn(), name };
1674
+ if (ref !== undefined) event.ref = ref;
1675
+ if (data !== undefined) event.data = data;
1676
+ this.ring.push(event);
1677
+ if (this.ring.length > EVENT_RING) this.ring.shift();
1678
+ this.onEvent?.(event);
1679
+ }
1680
+
1681
+ /** True once a client has completed the handshake. Host trivia, checkable. */
1682
+ ready(): boolean {
1683
+ return this.initialized;
1684
+ }
1685
+ }
1686
+
1687
+ /**
1688
+ * What one handle-path answer should leave in the resolution log, as a TOTAL
1689
+ * table over the reasons that path can produce:
1690
+ *
1691
+ * an id — it expanded, and this is what it reached
1692
+ * `null` — it was asked and answered with nothing (the shadow)
1693
+ * `undefined` — not this path's outcome at all; record nothing
1694
+ *
1695
+ * Total on purpose. A new handle-path reason added without a line here records
1696
+ * nothing rather than guessing, which fails in the under-credit direction.
1697
+ */
1698
+ function resolvedIdOf(result: DeliberateResult): string | null | undefined {
1699
+ switch (result.reason) {
1700
+ case "expanded":
1701
+ return result.memories.length === 1 ? (result.memories[0]?.id ?? null) : undefined;
1702
+ case "handle-unknown":
1703
+ case "handle-ambiguous":
1704
+ case "handle-confidential-withheld":
1705
+ return null;
1706
+ default:
1707
+ return undefined;
1708
+ }
1709
+ }
1710
+
1711
+ /**
1712
+ * The three dimensions an author may claim, off the wire. `null` means "one of
1713
+ * them was present and unusable" — a refusal, not a silent drop, because a
1714
+ * dimension that quietly vanishes is worse than one that was never offered:
1715
+ * both leave a 0 in the row and only one of them tells anybody.
1716
+ *
1717
+ * `novelty` is deliberately not readable here. It is prediction error, computed
1718
+ * at encoding against the store's own context; an author claiming it is exactly
1719
+ * the door PR-3 closed in `remember/proposals.ts`.
1720
+ */
1721
+ function readDimensions(rec: Record<string, unknown>): Record<string, number> | null {
1722
+ const out: Record<string, number> = {};
1723
+ for (const dim of AUTHOR_DIMENSIONS) {
1724
+ const v = rec[dim];
1725
+ if (v === undefined) continue;
1726
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 1) return null;
1727
+ out[dim] = v;
1728
+ }
1729
+ return out;
1730
+ }
1731
+
1732
+ /** The unvalidated read, used only where the refusal must be per-entry: the
1733
+ * values ride to `remember/intake`, which refuses that entry by name. */
1734
+ function pickDimensions(rec: Record<string, unknown>): Record<string, unknown> {
1735
+ const out: Record<string, unknown> = {};
1736
+ for (const dim of AUTHOR_DIMENSIONS) {
1737
+ if (rec[dim] !== undefined) out[dim] = rec[dim];
1738
+ }
1739
+ return out;
1740
+ }