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,619 @@
1
+ /**
2
+ * Deliberate recall — effortful, voluntary retrieval, as distinct from the
3
+ * ambient reminding `recall/` already performs every turn.
4
+ *
5
+ * **Brain analog.** Ambient recall is cue-driven reminding; this is a directed
6
+ * search of memory — slower, more effortful, and able to reach material the
7
+ * automatic path left below threshold. What it CANNOT do is reach material that
8
+ * was never cued at all: effort lowers a threshold, it does not conjure an
9
+ * association that does not exist. That is why the hard gates below survive the
10
+ * deeper look and the soft ones do not.
11
+ *
12
+ * **Built on `Recall.build()`, deliberately.** `build` is the pure half of the
13
+ * ambient path: it reads, scores, gates and composes, and writes nothing —
14
+ * `recall()` is the half that records. Reusing `build` means deliberate recall
15
+ * faces the same activation model, the same background bar and the same
16
+ * confidentiality verdict the ambient path does, and gets G4 ("ranking is not
17
+ * recording — this path trains nothing and deposits nothing") for free rather
18
+ * than by promising it. Nothing here calls `resolveUse` or `coactivate`.
19
+ *
20
+ * **The two paths never blur** (§9.1 G1). A handle EXPANDS: `store.resolve`,
21
+ * exact title match, and if neither answers, not-found — there is no search
22
+ * fallback in this file, and a test asserts a near-miss handle returns nothing
23
+ * rather than the memory a fuzzy match would have found. Expansion degrading
24
+ * into fuzzy search is how a precise question quietly becomes a vibe.
25
+ */
26
+ import type { Counterpart } from "../../core/counterpart.js";
27
+ import { strength } from "../../core/physics/index.js";
28
+ import { isConfidential, isSelfPage } from "../../core/recall/index.js";
29
+ import type { CandidateVerdict, SemanticSource, Verdict } from "../../core/recall/index.js";
30
+
31
+ /**
32
+ * The confidence tiers this adapter reports. Named, not numeric: v1 labeled its
33
+ * fallback tier and left the rest implicit, which made "how sure was it" a
34
+ * question only a replay could answer (CONTRACT §7 OQ3 — answered here as tier
35
+ * names, because a number implies a calibration nobody has done).
36
+ */
37
+ export type Tier = "vivid" | "quiet" | "dim";
38
+
39
+ /**
40
+ * Verdicts the deeper look ADMITS, at the `dim` tier. Every one of them is a
41
+ * SOFT gate in the ambient path: a bar this turn's background happened to set,
42
+ * a per-kind loud-tier floor, a tier cap, a session-dedup, the rule that a
43
+ * remembered date may make a memory quiet but never loud, or the rule that a
44
+ * store too small for rarity to discriminate may not go loud. Deliberate effort
45
+ * is exactly the license to look under those.
46
+ *
47
+ * The last three are loud-tier BLOCKS: they reach the caller as
48
+ * `loudBlockedBy` on an admitted candidate rather than as a final verdict, so
49
+ * listing them changes no behavior today. They are listed because this is a
50
+ * named table and a named table is total — a loud block that later becomes a
51
+ * final verdict must not be silently dropped by `tierOf`.
52
+ */
53
+ export const DELIBERATE_TIERS: readonly Verdict[] = [
54
+ "below-bar",
55
+ "below-strong-floor",
56
+ "capped",
57
+ "dedup-suppressed",
58
+ "cue-only-temporal",
59
+ "cold-start-undiscriminating",
60
+ ];
61
+
62
+ /**
63
+ * Verdicts effort does NOT overturn, and why each one holds:
64
+ * `dark-uncued` — hard gate (a). Nothing in the question reached it; a
65
+ * memory reached by nothing is not being remembered, it is
66
+ * being enumerated.
67
+ * `below-floor` — hard gate (b). Below the global floor is below the floor.
68
+ * `cue-fraction` — hard gate (c). Too little of the activation came from the
69
+ * words actually asked; admitting it is drift, not recall.
70
+ * `inhibited` — a near-duplicate of something already returned. Nothing is
71
+ * withheld by including only the stronger twin.
72
+ * `confidential-withheld` — the boundary of the ask, handled separately below.
73
+ */
74
+ export const HARD_GATES: readonly Verdict[] = ["dark-uncued", "below-floor", "cue-fraction"];
75
+
76
+ /** Adapter-owned, not a memory property: how many dim items are worth reading. */
77
+ export const DELIBERATE_DIM_CAP = 5;
78
+
79
+ // ── the result's size, which is a capability of the HOST, not a preference ──
80
+ //
81
+ // MEASURED 2026-09-04: three `recall` calls in one session returned 7, 8 and 12
82
+ // memories as FULL BODIES — 73,000 to 122,000 characters — and every one of the
83
+ // three overflowed the host's tool-result ceiling. An answer the host truncates
84
+ // is not a smaller answer, it is no answer, and the model that asked cannot tell
85
+ // the difference between "nothing came" and "too much came".
86
+ //
87
+ // This is scar §2.18's rule (the injection ceiling is a host capability) applied
88
+ // to the OTHER direction of the same wire. The ambient path has had a byte
89
+ // budget since day one (`BUDGET_BYTES`); the deliberate path had none.
90
+ //
91
+ // The numbers: a LIST answers "which memories", so 300 characters is enough to
92
+ // recognize one and decide whether to ask for it; the id path answers "what did
93
+ // it say", so it gets an order of magnitude more each; and the total is bounded
94
+ // below the smallest tool-result ceiling this package has met.
95
+
96
+ /** Characters of body per memory in a LIST answer (the question path). */
97
+ export const RECALL_EXCERPT_CHARS = 300;
98
+ /** Characters of body per memory when the caller asked for it BY ID. */
99
+ export const RECALL_BODY_CHARS = 4000;
100
+ /** Total characters of memory content in one result, across every memory. */
101
+ export const RECALL_RESULT_CHARS = 12_000;
102
+ /** How many ids one `ids` call may expand. Effort, not enumeration. */
103
+ export const RECALL_MAX_IDS = 3;
104
+
105
+ /** One memory as it goes on the wire: an excerpt, plus what was left off. */
106
+ export interface BoundedMemory {
107
+ readonly id: string;
108
+ readonly tier: Tier;
109
+ readonly kind: string;
110
+ readonly title: string | null;
111
+ /** A journal entry, not a memory — see `Recalled.journal`. */
112
+ readonly journal: boolean;
113
+ /** The body, cut to the applicable budget. */
114
+ readonly excerpt: string;
115
+ /** The full body's length, so "there is more" is a number, not a guess. */
116
+ readonly bodyChars: number;
117
+ /** True when `excerpt` is shorter than the body. */
118
+ readonly truncated: boolean;
119
+ readonly admittedUnder?: Verdict;
120
+ }
121
+
122
+ export interface BoundedResult {
123
+ readonly memories: readonly BoundedMemory[];
124
+ /** Any body was cut. */
125
+ readonly truncated: boolean;
126
+ /** Memories dropped whole because the TOTAL budget ran out. Ranked order is
127
+ * preserved, so what is dropped is always the least activated. */
128
+ readonly droppedForBudget: number;
129
+ readonly chars: number;
130
+ }
131
+
132
+ function cut(body: string, limit: number): string {
133
+ if (body.length <= limit) return body;
134
+ // Cut at a word boundary when one is near, so an excerpt ends as text rather
135
+ // than mid-token. The ellipsis is part of the budget, not extra.
136
+ const hard = body.slice(0, Math.max(0, limit - 1));
137
+ const space = hard.lastIndexOf(" ");
138
+ return `${space > limit * 0.6 ? hard.slice(0, space) : hard}…`;
139
+ }
140
+
141
+ /**
142
+ * Bound a ranked list of memories to the wire budget. Ranked order is preserved
143
+ * and truncation is stated: an answer that quietly drops its tail is the same
144
+ * failure as an answer the host truncates, moved one layer inward.
145
+ */
146
+ export function boundMemories(
147
+ memories: readonly Recalled[],
148
+ perMemoryChars: number,
149
+ totalChars: number = RECALL_RESULT_CHARS,
150
+ ): BoundedResult {
151
+ const out: BoundedMemory[] = [];
152
+ let chars = 0;
153
+ let truncated = false;
154
+ let dropped = 0;
155
+ for (const m of memories) {
156
+ const remaining = totalChars - chars;
157
+ if (remaining <= 0) {
158
+ dropped += 1;
159
+ continue;
160
+ }
161
+ const excerpt = cut(m.body, Math.min(perMemoryChars, remaining));
162
+ if (excerpt.length < m.body.length) truncated = true;
163
+ chars += excerpt.length;
164
+ out.push({
165
+ id: m.id,
166
+ tier: m.tier,
167
+ kind: m.kind,
168
+ title: m.title,
169
+ journal: m.journal,
170
+ excerpt,
171
+ bodyChars: m.body.length,
172
+ truncated: excerpt.length < m.body.length,
173
+ ...(m.admittedUnder === undefined ? {} : { admittedUnder: m.admittedUnder }),
174
+ });
175
+ }
176
+ return { memories: out, truncated, droppedForBudget: dropped, chars };
177
+ }
178
+
179
+ /**
180
+ * The latency budget for the DEEPER LOOK, in ms — deliberately generous, and
181
+ * deliberately not the ambient one.
182
+ *
183
+ * The ambient 1200 ms is a promise to somebody mid-sentence; this is a question
184
+ * a person typed and is waiting for an answer to. It matters because this is the
185
+ * one path allowed to embed IN LINE (the ruling of 2026-09-04: the hot path may
186
+ * not, the ask may), and the vector scan that follows measured 590-1040 ms on a
187
+ * live-sized index all by itself — under the ambient budget the semantic channel
188
+ * would buy the ask nothing but a `latency-abort`.
189
+ */
190
+ export const DELIBERATE_BUDGET_MS = 15_000;
191
+
192
+ /**
193
+ * A journal entry, not a memory — the owner's ruling of 2026-09-04 (§I14).
194
+ *
195
+ * The chapter stays RECALLABLE: a chapter about the lighthouse conversation may
196
+ * rightly come to mind, and filtering it would answer a question worse than
197
+ * labelling it does. What it must never be is mistaken for a memory — it is the
198
+ * first-person ACCOUNT a memory was made from, it sits outside every sleep phase
199
+ * (`sleep/types.ts#isJournal`), and the physics printed beside it is recorded and
200
+ * never acted on. The dashboard has said so on the row since #33; this is the
201
+ * same sentence at the other two doors.
202
+ *
203
+ * The predicate is `ProseDoc.type`, the same field `isJournal` reads off the row,
204
+ * so the label cannot disagree with the rest of the system about what a chapter
205
+ * is. `kind` stays PHYSICS kind: a chapter is usually `kind: "self"`, which is
206
+ * exactly the ambiguity this boolean resolves rather than overwrites.
207
+ */
208
+ export const JOURNAL_GLOSS =
209
+ "A row marked journal: true is a chapter — the first-person account a memory was made from, not a memory. It is outside decay, dedup and the prune, and it is not a claim about the world the way a memory is.";
210
+
211
+ export interface Recalled {
212
+ readonly id: string;
213
+ readonly tier: Tier;
214
+ readonly kind: string;
215
+ readonly title: string | null;
216
+ /** True for an `epi_` chapter (`ProseDoc.type === "episode"`). See `JOURNAL_GLOSS`. */
217
+ readonly journal: boolean;
218
+ /** The body. The quiet tier returns bodies here, not a count (§9.1 G2). */
219
+ readonly body: string;
220
+ readonly strength: number;
221
+ readonly activation: number;
222
+ /** For a dim item: which loud-tier check the ambient path stopped it at. */
223
+ readonly admittedUnder?: Verdict;
224
+ }
225
+
226
+ export type DeliberateReason =
227
+ | "expanded"
228
+ | "answered"
229
+ | "handle-unknown"
230
+ | "handle-ambiguous"
231
+ | "handle-confidential-withheld"
232
+ | "nothing-came"
233
+ | "no-argument"
234
+ | "both-arguments"
235
+ | "ids-too-many";
236
+
237
+ export interface DeliberateResult {
238
+ readonly path: "handle" | "question" | "none";
239
+ /** How the semantic channel got its input on THIS ask — `in-line` when the
240
+ * caller embedded the question, `unavailable` when it could not, `none` on
241
+ * the handle path, which does no scoring at all. */
242
+ readonly semantic: SemanticSource;
243
+ readonly reason: DeliberateReason;
244
+ readonly memories: readonly Recalled[];
245
+ /** Candidates the deeper look actually considered — NOT the number returned.
246
+ * §9.1 G3: a top-K tuned for surfacing is the wrong answer to "how many". */
247
+ readonly considered: number;
248
+ /**
249
+ * LIVE ROWS in the store — the denominator an aggregation question needs, and
250
+ * not the same number as the wake preface's "N memories".
251
+ *
252
+ * `store.list({ archived: false })` returns every unarchived row: memories,
253
+ * the schemas (entities, beliefs, and the identity core `install --name`
254
+ * mints), and the journal's episodes. A store a reader made by following the
255
+ * documented path and then wrote two notes into answers `3 live`, not `2` —
256
+ * the third row is the identity core (found 2026-09-04, when a captured
257
+ * example reproduced one higher than the page said).
258
+ *
259
+ * The COUNT is right for what it is; the word was the problem, so every label
260
+ * over this field says "live rows".
261
+ */
262
+ readonly storeSize: number;
263
+ /** Ids a handle matched when the handle was ambiguous. Ids only, no bodies. */
264
+ readonly ambiguous: readonly string[];
265
+ /** The `ids` path only: what happened to each id asked for, in the order
266
+ * asked. A multi-id lookup is still a DIRECT lookup, so each id's refusal is
267
+ * stated by name rather than folded into one total (§9.1 G5). */
268
+ readonly perId?: readonly { id: string; reason: DeliberateReason }[];
269
+ /**
270
+ * WHAT KEPT SOMETHING OUT, by verdict, counted (2026-09-20, E2).
271
+ *
272
+ * Every candidate the deeper look considered and did not admit. It is the
273
+ * answer to "nothing came back — was there nothing, or was it all gated",
274
+ * which nothing could answer before: the verdicts lived for the length of one
275
+ * `build()` call and were then discarded.
276
+ *
277
+ * **It does not go on the wire.** §9.1 G5 is unchanged: a list that announces
278
+ * its gaps leaks their existence, and `confidential-withheld` in particular is
279
+ * silent to the caller. This field exists for the DURABLE ROW in the owner's
280
+ * own store, which `server.ts` writes and `recallPayload` does not read.
281
+ */
282
+ readonly blockedBy?: Readonly<Record<string, number>>;
283
+ }
284
+
285
+ export interface DeliberateInput {
286
+ readonly handle?: string;
287
+ readonly question?: string;
288
+ /** Full bodies for memories the caller already has the ids of — the follow-up
289
+ * to a list, and the reason the list can afford to be excerpts. */
290
+ readonly ids?: readonly string[];
291
+ }
292
+
293
+ export interface DeliberateOptions {
294
+ readonly sessionId: string;
295
+ /** The owner's own session? Confidentiality turns on this and nothing else. */
296
+ readonly owner: boolean;
297
+ readonly day?: number;
298
+ /**
299
+ * The question's embedding, computed IN LINE by the caller (`server.ts`).
300
+ * Absent means the semantic channel degrades to lexical-only and the result
301
+ * SAYS so — never a silently narrower answer (contract §5 G1).
302
+ */
303
+ readonly vector?: readonly number[] | null;
304
+ /** Why there is no vector, when there is none — the caller knows and this
305
+ * file cannot. Defaults to `embedder-off`, the ordinary case. */
306
+ readonly semantic?: SemanticSource;
307
+ }
308
+
309
+ const EMPTY = {
310
+ semantic: "none" as SemanticSource,
311
+ memories: [] as readonly Recalled[],
312
+ considered: 0,
313
+ storeSize: 0,
314
+ ambiguous: [] as readonly string[],
315
+ };
316
+
317
+ /** Live memories, the same count every answering path reports. Never throws:
318
+ * a refusal must not become a crash because the census failed. */
319
+ function liveCount(counterpart: Counterpart): number {
320
+ try {
321
+ return counterpart.store.list({ archived: false }).length;
322
+ } catch {
323
+ return 0;
324
+ }
325
+ }
326
+
327
+ /**
328
+ * The dispatcher. EXACTLY ONE argument: two is a caller who does not know which
329
+ * question they are asking, and answering the more convenient one is how the
330
+ * expansion path quietly becomes the search path.
331
+ */
332
+ export function deliberateRecall(
333
+ counterpart: Counterpart,
334
+ input: DeliberateInput,
335
+ opts: DeliberateOptions,
336
+ ): DeliberateResult {
337
+ const hasHandle = typeof input.handle === "string" && input.handle.trim().length > 0;
338
+ const hasQuestion = typeof input.question === "string" && input.question.trim().length > 0;
339
+ const askedIds = (input.ids ?? []).map((s) => s.trim()).filter((s) => s.length > 0);
340
+ const hasIds = askedIds.length > 0;
341
+ // THREE paths now, still exactly one per call. `ids` is the follow-up to a
342
+ // list — "give me those in full" — and mixing it with a question is the same
343
+ // caller confusion `both-arguments` already refuses.
344
+ if ([hasHandle, hasQuestion, hasIds].filter(Boolean).length > 1) {
345
+ return { path: "none", reason: "both-arguments", ...EMPTY, storeSize: liveCount(counterpart) };
346
+ }
347
+ if (hasHandle) return expandHandle(counterpart, (input.handle as string).trim(), opts);
348
+ if (hasIds) return expandIds(counterpart, askedIds, opts);
349
+ if (hasQuestion) return answerQuestion(counterpart, (input.question as string).trim(), opts);
350
+ // The REAL store size, even on a refusal. A caller who misspelled the argument
351
+ // name got `storeSize: 0` here until 2026-09-04, which reads as "your store is
352
+ // empty" — the wrong problem, stated confidently, at exactly the moment the
353
+ // caller is already unsure what they did wrong (cold-stranger review, §6.9).
354
+ return { path: "none", reason: "no-argument", ...EMPTY, storeSize: liveCount(counterpart) };
355
+ }
356
+
357
+ /**
358
+ * THE EXPANSION PATH. Exact by construction: an id that resolves, or a title
359
+ * that matches exactly after trimming and case-folding. No scoring, no cues, no
360
+ * `store.search` — this function does not import one.
361
+ *
362
+ * Withholding is STATED here (§9.1 G5): a direct lookup that answers "nothing"
363
+ * where something exists would be a lie, so the refusal names itself. In the
364
+ * list path below, the same material is dropped silently, because a list that
365
+ * announces its gaps is a list that leaks their existence.
366
+ */
367
+ export function expandHandle(
368
+ counterpart: Counterpart,
369
+ handle: string,
370
+ opts: DeliberateOptions,
371
+ ): DeliberateResult {
372
+ const store = counterpart.store;
373
+ const storeSize = store.list({ archived: false }).length;
374
+ // The expansion path scores nothing, so no channel is consulted and none is
375
+ // reported dark: `none` here means "not asked", not "asked and empty".
376
+ const base = {
377
+ path: "handle" as const,
378
+ semantic: "none" as SemanticSource,
379
+ storeSize,
380
+ ambiguous: [] as readonly string[],
381
+ };
382
+
383
+ const matches: string[] = [];
384
+ try {
385
+ matches.push(store.resolve(handle));
386
+ } catch {
387
+ // Not an id, or an id that no longer resolves. Fall through to titles —
388
+ // which is NOT a fuzzy fallback: it is the other exact address a memory has.
389
+ }
390
+ if (matches.length === 0) {
391
+ const wanted = handle.toLowerCase();
392
+ for (const id of store.list({ archived: false })) {
393
+ const row = store.row(id);
394
+ if (row === undefined || row.superseded_by !== null) continue;
395
+ let title: string | null = null;
396
+ try {
397
+ title = store.readProse(id).title ?? null;
398
+ } catch {
399
+ continue;
400
+ }
401
+ if (title !== null && title.trim().toLowerCase() === wanted) matches.push(id);
402
+ }
403
+ }
404
+
405
+ if (matches.length === 0) {
406
+ return { ...base, reason: "handle-unknown", memories: [], considered: 0 };
407
+ }
408
+ if (matches.length > 1) {
409
+ // Ids only: an ambiguous handle names the choice without making it, and
410
+ // returning every body would hand back the thing the ambiguity conceals.
411
+ return {
412
+ ...base,
413
+ reason: "handle-ambiguous",
414
+ memories: [],
415
+ considered: matches.length,
416
+ ambiguous: matches,
417
+ };
418
+ }
419
+
420
+ const id = matches[0] as string;
421
+ const read = store.read(id);
422
+ // THE SELF PAGE IS NOT EXPANDED HERE either (2026-09-18). It is excluded from
423
+ // activation, so it never appears in a result to be followed up — and the one
424
+ // way left to reach it was to pass its id, which would credit a use for a row
425
+ // that is delivered whole at every wake. `self_page` is its door, and it has
426
+ // no cap and no tier.
427
+ if (isSelfPage(read.doc)) {
428
+ return { ...base, reason: "handle-unknown", memories: [], considered: 0 };
429
+ }
430
+ if (!opts.owner && isConfidential(read.doc)) {
431
+ return { ...base, reason: "handle-confidential-withheld", memories: [], considered: 1 };
432
+ }
433
+ return {
434
+ ...base,
435
+ reason: "expanded",
436
+ considered: 1,
437
+ memories: [
438
+ {
439
+ id,
440
+ tier: "vivid",
441
+ kind: read.physics.kind,
442
+ title: read.doc.title ?? null,
443
+ journal: read.doc.type === "episode",
444
+ body: read.doc.body,
445
+ // The SAME number the question path reports: base-level activation from
446
+ // `physics/`, not a raw use count. Two paths reporting different
447
+ // quantities under one field name is a measurement bug waiting to be
448
+ // compared across them.
449
+ strength: strength(read.physics, store.livedDay()),
450
+ activation: 1,
451
+ },
452
+ ],
453
+ };
454
+ }
455
+
456
+ /**
457
+ * THE ID PATH — "those three, in full", after a list.
458
+ *
459
+ * It is `expandHandle` in a loop and deliberately nothing more: each id crosses
460
+ * the same exact-address resolution and the same confidentiality boundary, so
461
+ * withholding is still STATED per id (§9.1 G5) and no id fuzzes into a search.
462
+ * Writing a second resolver here to save a loop is how the expansion path
463
+ * quietly becomes the search path.
464
+ *
465
+ * The count is capped because effort is not enumeration: a caller who wants
466
+ * twenty bodies is asking for the store, and `status` is the tool for that.
467
+ */
468
+ export function expandIds(
469
+ counterpart: Counterpart,
470
+ ids: readonly string[],
471
+ opts: DeliberateOptions,
472
+ ): DeliberateResult {
473
+ const unique = [...new Set(ids)];
474
+ const storeSize = counterpart.store.list({ archived: false }).length;
475
+ // Same as `expandHandle`: an exact address consults no channel, so `none`
476
+ // here means "not asked", never "asked and empty".
477
+ const base = { path: "handle" as const, semantic: "none" as SemanticSource, storeSize };
478
+ if (unique.length > RECALL_MAX_IDS) {
479
+ return {
480
+ ...base,
481
+ reason: "ids-too-many",
482
+ memories: [],
483
+ considered: unique.length,
484
+ ambiguous: [],
485
+ perId: unique.map((id) => ({ id, reason: "ids-too-many" as const })),
486
+ };
487
+ }
488
+ const memories: Recalled[] = [];
489
+ const ambiguous: string[] = [];
490
+ const perId: { id: string; reason: DeliberateReason }[] = [];
491
+ for (const id of unique) {
492
+ const one = expandHandle(counterpart, id, opts);
493
+ perId.push({ id, reason: one.reason });
494
+ memories.push(...one.memories);
495
+ ambiguous.push(...one.ambiguous);
496
+ }
497
+ return {
498
+ ...base,
499
+ reason: memories.length > 0 ? "expanded" : (perId[0]?.reason ?? "handle-unknown"),
500
+ memories,
501
+ considered: unique.length,
502
+ ambiguous,
503
+ perId,
504
+ };
505
+ }
506
+
507
+ /**
508
+ * THE QUESTION PATH. `Recall.build()` does the work; this function re-tiers its
509
+ * verdicts under the deliberate rule and fetches bodies for what it admits.
510
+ *
511
+ * `considered` is `decision.candidates` — every candidate the activation pass
512
+ * scored, not the handful that came back. Together with `storeSize` — LIVE ROWS,
513
+ * schemas and journal included — that is §9.1 G3's whole content: the caller can
514
+ * tell "three matched" from "three were returned" from "three exist".
515
+ */
516
+ export function answerQuestion(
517
+ counterpart: Counterpart,
518
+ question: string,
519
+ opts: DeliberateOptions,
520
+ ): DeliberateResult {
521
+ const store = counterpart.store;
522
+ // THE ONE PATH ALLOWED TO EMBED IN LINE. The caller did the round trip; this
523
+ // pass does the ranking, under a budget that can afford it.
524
+ const vector = opts.vector ?? null;
525
+ const semantic: SemanticSource =
526
+ vector !== null && vector.length > 0 ? "in-line" : opts.semantic ?? "embedder-off";
527
+ const built = counterpart.recall.build({
528
+ sessionId: opts.sessionId,
529
+ text: question,
530
+ owner: opts.owner,
531
+ budgetMs: DELIBERATE_BUDGET_MS,
532
+ ...(vector === null || vector.length === 0 ? {} : { vector }),
533
+ ...(opts.day === undefined ? {} : { day: opts.day }),
534
+ });
535
+ const decision = built.decision;
536
+ const surfaced = new Set(decision.surfaced);
537
+ const footnoted = new Set(decision.footnotes);
538
+
539
+ const admitted: { verdict: CandidateVerdict; tier: Tier }[] = [];
540
+ const dim: CandidateVerdict[] = [];
541
+ // The refusal column, for the durable row only — never for the wire.
542
+ const blockedBy: Record<string, number> = {};
543
+ const blocked = (reason: string): void => {
544
+ blockedBy[reason] = (blockedBy[reason] ?? 0) + 1;
545
+ };
546
+ for (const v of decision.verdicts) {
547
+ if (surfaced.has(v.id)) {
548
+ admitted.push({ verdict: v, tier: "vivid" });
549
+ continue;
550
+ }
551
+ if (footnoted.has(v.id)) {
552
+ admitted.push({ verdict: v, tier: "quiet" });
553
+ continue;
554
+ }
555
+ // Silent for the list (§9.1 G5): confidential material is not mentioned,
556
+ // not counted back to the caller, and not hinted at by a gap in a total.
557
+ if (v.verdict === "confidential-withheld") {
558
+ blocked(v.verdict);
559
+ continue;
560
+ }
561
+ if (HARD_GATES.includes(v.verdict)) {
562
+ blocked(v.verdict);
563
+ continue;
564
+ }
565
+ if (DELIBERATE_TIERS.includes(v.verdict)) dim.push(v);
566
+ // A verdict in neither table reached the caller as nothing and was counted
567
+ // as nothing. `inhibited` is the one that lands here today; naming it beats
568
+ // an unexplained gap between `considered` and what came back.
569
+ else blocked(v.verdict);
570
+ }
571
+ dim.sort((a, b) => b.activation - a.activation);
572
+ for (const v of dim.slice(0, DELIBERATE_DIM_CAP)) admitted.push({ verdict: v, tier: "dim" });
573
+ // The dim tier's own cap is a refusal like any other: these were reachable by
574
+ // effort and the cap is what stopped them.
575
+ for (const v of dim.slice(DELIBERATE_DIM_CAP)) blocked(`dim-cap:${v.verdict}`);
576
+
577
+ const memories: Recalled[] = [];
578
+ for (const { verdict, tier } of admitted) {
579
+ let doc;
580
+ try {
581
+ doc = store.readProse(verdict.id);
582
+ } catch {
583
+ // A row whose prose has gone is not an answer; it is also not a failure
584
+ // worth throwing at a model that asked a question.
585
+ continue;
586
+ }
587
+ memories.push({
588
+ id: verdict.id,
589
+ tier,
590
+ kind: verdict.kind,
591
+ title: doc.title ?? null,
592
+ journal: doc.type === "episode",
593
+ body: doc.body,
594
+ strength: verdict.strength,
595
+ activation: verdict.activation,
596
+ ...(tier === "dim" ? { admittedUnder: verdict.verdict } : {}),
597
+ });
598
+ }
599
+
600
+ return {
601
+ path: "question",
602
+ semantic,
603
+ reason: memories.length === 0 ? "nothing-came" : "answered",
604
+ memories,
605
+ considered: decision.candidates,
606
+ storeSize: decision.storeSize,
607
+ ambiguous: [],
608
+ blockedBy,
609
+ };
610
+ }
611
+
612
+ /** The tier a verdict earns, exposed for the audit test's mechanization proof. */
613
+ export function tierOf(verdict: Verdict, surfaced: boolean, footnoted: boolean): Tier | null {
614
+ if (surfaced) return "vivid";
615
+ if (footnoted) return "quiet";
616
+ if (verdict === "confidential-withheld") return null;
617
+ if (HARD_GATES.includes(verdict)) return null;
618
+ return DELIBERATE_TIERS.includes(verdict) ? "dim" : null;
619
+ }