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,521 @@
1
+ /**
2
+ * Activation — from cues to a scored candidate set.
3
+ *
4
+ * Three channels, and the difference between them is the whole design:
5
+ *
6
+ * **cue** (lexical, plus TEMPORAL) and **semantic** (embedding) are the
7
+ * CONVERSATION. Either one makes a memory a candidate at all.
8
+ *
9
+ * A **temporal cue** — the calendar reached a window a memory remembers — is
10
+ * folded into the cue channel and into nothing else (SEAMS item D,
11
+ * `prospective/INTERFACE-GAPS.md` §1). It is "one more cue, like the user typing
12
+ * 'Portland'": same map, same activation number, same background bar, and it
13
+ * COUNTS AS CUE in `cueFraction`, or hard gate (c) would silently change
14
+ * meaning. It is emphatically NOT the `arrival` channel below, which shares its
15
+ * English name and nothing else — wiring a temporal arrival into
16
+ * `ARRIVAL_WEIGHT` would turn a recency MULTIPLIER into an ADMISSION channel and
17
+ * break hard gate (a) for every dated memory.
18
+ * **arrival** (base-level strength) is RECENCY. It modulates a candidate that
19
+ * the conversation already reached, and it can never create one — which is how
20
+ * hard gate (a), *an uncued memory is dark whatever its salience*, is enforced
21
+ * structurally rather than checked: an uncued memory is not fetched, so its
22
+ * salience arithmetic is never evaluated (§9 G7a).
23
+ * **hops** (spreading activation, SEAMS item L) MODULATE ONLY, exactly like
24
+ * arrival. `associate/INTERFACE-GAPS.md` §1 names three defensible answers and
25
+ * SEAMS L records the one chosen: the conservative default, which is the only
26
+ * one that keeps hard gate (a) STRUCTURAL — a hop reaches "a memory no cue and
27
+ * no embedding touched", and in this contract's vocabulary that memory is
28
+ * uncued and therefore dark. So a hop is added to a candidate that already
29
+ * exists, never mints one, and is excluded from `cueFraction`'s NUMERATOR —
30
+ * which is what makes "spreading never creates a loud-tier candidate without a
31
+ * cue" arithmetic rather than a promise: hop weight sits in the denominator and
32
+ * pushes the candidate AWAY from the loud tier, never toward it.
33
+ *
34
+ * The candidate set is exactly the union of the token index's hits and the vector
35
+ * index's hits. NO MODEL CALL: the turn's vector is an INPUT. Its absence degrades
36
+ * to lexical-only, which is guarantee 1's precise v2 form — the ambient path may
37
+ * consult an embedding, never a generative model, and must degrade rather than
38
+ * fail.
39
+ */
40
+ import type { Kind, MemoryPhysics } from "../types.js";
41
+ import { sal, strength } from "../physics/index.js";
42
+ import type { Hit, ProseDoc, Store } from "../store/index.js";
43
+ import { confidentialByMeta, rowToPhysics, tokenize } from "../store/index.js";
44
+ import { buildCues, informativeness } from "./cues.js";
45
+ import type { Cue } from "./cues.js";
46
+ import type { RecallTunables } from "./tunables.js";
47
+
48
+ export interface Candidate {
49
+ readonly id: string;
50
+ readonly kind: Kind;
51
+ readonly doc: ProseDoc;
52
+ readonly physics: MemoryPhysics;
53
+ readonly strength: number;
54
+ /** Salience as the GATE sees it: emotional dimension included only when the
55
+ * turn itself carries first-person feeling (§9 G10/G11 — emotion is
56
+ * turn-gated, and that gate is the safety property). */
57
+ readonly sal: number;
58
+ readonly cue: number;
59
+ /** The portion of `cue` that came from a temporal window (already included in
60
+ * `cue`; carried separately only so the ceiling below can be decided). */
61
+ readonly temporal: number;
62
+ readonly semantic: number;
63
+ readonly arrival: number;
64
+ /** Spreading activation from `associate/`. In `activation`, never in
65
+ * `cueFraction`'s numerator, and never able to mint a candidate. */
66
+ readonly hops: number;
67
+ readonly activation: number;
68
+ /** (cue + semantic) / activation — hard gate (c)'s input. */
69
+ readonly cueFraction: number;
70
+ readonly matched: number;
71
+ /** Every matching cue was an ambiguous handle and nothing corroborated it:
72
+ * it fires at reduced weight (already applied) and TRAINS NOTHING. */
73
+ readonly trains: boolean;
74
+ /** A per-candidate tier CEILING. `"footnoted"` for a candidate whose only cue
75
+ * is temporal: a remembered date may make a memory quietly available and must
76
+ * never make it loud (prospective §12 G5). Absent from the gate's other rules
77
+ * by design — it caps, it never admits. */
78
+ readonly maxTier: "surfaced" | "footnoted";
79
+ readonly confidential: boolean;
80
+ }
81
+
82
+ export interface ActivationInput {
83
+ readonly text: string;
84
+ readonly vector?: readonly number[] | undefined;
85
+ /** A ranking somebody else already computed — the lagged semantic cue the
86
+ * worker resolved one turn ago (`session.ts`). Supplied hits REPLACE the
87
+ * `nearestTo` scan; an empty array is "nothing was near", which degrades. */
88
+ readonly hits?: readonly Hit[] | undefined;
89
+ readonly carried?: readonly string[] | undefined;
90
+ readonly aliases?: ReadonlyMap<string, readonly string[]> | undefined;
91
+ /** Temporal cues from `prospective.arrivals()`: memory id and cue weight.
92
+ * Folded into `cueScore`, never into `arrival` (see the header). */
93
+ readonly temporal?: readonly { id: string; weight: number }[] | undefined;
94
+ /** INJECTED traversal (`Associate.spreadFrom`), because `recall/` must not
95
+ * import `associate/`. Seeded with the CUED candidates and their own
96
+ * activation; contributions to anything that is not already a candidate are
97
+ * DROPPED here, which is where "hops modulate only" is enforced. */
98
+ readonly spread?:
99
+ | ((seeds: readonly { id: string; activation: number }[], day: number) => {
100
+ contributions: readonly { id: string; activation: number }[];
101
+ })
102
+ | undefined;
103
+ readonly day: number;
104
+ /** Whether the turn stated a FIRST-PERSON feeling. Gates emotional salience. */
105
+ readonly selfFelt: boolean;
106
+ readonly maxCandidates: number;
107
+ /** Live memory count, for informativeness and the cold-start regime. */
108
+ readonly storeSize: number;
109
+ }
110
+
111
+ export interface ActivationResult {
112
+ readonly cues: Cue[];
113
+ readonly candidates: Candidate[];
114
+ readonly storeSize: number;
115
+ /** Candidates dropped before scoring because they are not live memory. */
116
+ readonly skipped: number;
117
+ /** True when a vector was supplied but the index answered nothing — the
118
+ * lexical-only degradation, recorded rather than silent. */
119
+ readonly semanticDegraded: boolean;
120
+ /** Documents whose cue sum hit the per-document ceiling (`CUE_DOC_CAP`).
121
+ * Reported, not recorded: it is the number `tools/recall-bench` reads to
122
+ * tell "the cap did the work" from "normalization did the work". It is
123
+ * deliberately NOT a `RecallDecision` field — that record's field list is a
124
+ * hashed surface set the parallel run carries ratings across, and a new
125
+ * column there would invalidate a live instrument mid-run. */
126
+ readonly capped: number;
127
+ }
128
+
129
+ /**
130
+ * THE SELF PAGE IS NOT A RECALL CANDIDATE (2026-09-18, S1).
131
+ *
132
+ * The page is `self/`'s one row of standing prose about the self, and it is
133
+ * already delivered — whole, first, at every wake. Leaving it in the candidate
134
+ * pool means it can be quoted back to the model on a turn it is ALSO carrying in
135
+ * its own wake, can accrue use credit and association edges for being what it
136
+ * always is, and — since a schema row has no project scope — can surface under a
137
+ * project the owner never wrote it in. It is up to 16 KB against a bounded
138
+ * result, and it is the one row whose surfacing tells the reader nothing they
139
+ * were not already told.
140
+ *
141
+ * The role string is read STRUCTURALLY rather than imported: `recall/` does not
142
+ * depend on `self/`, and a shape check that fails reads as "not the page", which
143
+ * is the direction that only ever costs a candidate slot. The owner of the
144
+ * constant is `self/page.ts#SELF_PAGE_ROLE`.
145
+ *
146
+ * One line to reverse, if the page should come back to mind.
147
+ */
148
+ export function isSelfPage(doc: ProseDoc): boolean {
149
+ return doc.type === "schema" && doc.meta["role"] === "page";
150
+ }
151
+
152
+ /** `isSelfPage` by id, for the scan, which holds rows rather than documents. A
153
+ * page whose prose will not read is not the page for this purpose: the safe
154
+ * direction is to let it compete, not to drop a row nobody could identify. */
155
+ function isPageRow(store: Store, id: string): boolean {
156
+ try {
157
+ return isSelfPage(store.readProse(id));
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * THE PER-DIRECTORY HANDOFF IS NOT A RECALL CANDIDATE (2026-09-20, E1).
165
+ *
166
+ * A handoff is working context for one directory — "what I was doing here" —
167
+ * delivered as a pointer at the wake of that directory and expandable by id
168
+ * from there. It is not an interpretation of what was learned, it carries no
169
+ * project scope a search could honour, and it expires. Surfacing one inside a
170
+ * turn would put another directory's unfinished business in front of this one.
171
+ *
172
+ * Read STRUCTURALLY for `isSelfPage`'s reason: `recall/` depends on no other
173
+ * core module, and a shape check that fails reads as "not a handoff", which only
174
+ * ever costs a candidate slot. The constant's owner is
175
+ * `handoff/index.ts#HANDOFF_ROLE`.
176
+ */
177
+ export function isHandoff(doc: ProseDoc): boolean {
178
+ return doc.type === "schema" && doc.meta["role"] === "handoff";
179
+ }
180
+
181
+ /** `isHandoff` by id, for the scan. */
182
+ function isHandoffRow(store: Store, id: string): boolean {
183
+ try {
184
+ return isHandoff(store.readProse(id));
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * A memory's confidentiality class, as the surfacing gate asks it.
192
+ *
193
+ * The truth table itself is `store/index.ts#confidentialByMeta`, which is also
194
+ * what `StoredMemory.confidential` carries — one answer, so a caller holding a
195
+ * `StoredMemory` and a caller holding a bare `ProseDoc` can never disagree. This
196
+ * wrapper is the door for the second kind (`dashboard/web/reveal.ts`,
197
+ * `mcp/deliberate.ts`); prefer the flag where a read already produced one.
198
+ */
199
+ export function isConfidential(doc: ProseDoc): boolean {
200
+ return confidentialByMeta(doc.meta);
201
+ }
202
+
203
+ /** Salience with the emotional dimension gated on the turn (§9 G10). */
204
+ export function gatedSal(p: MemoryPhysics, selfFelt: boolean): number {
205
+ if (selfFelt) return sal(p.salience);
206
+ return sal({ ...p.salience, emotional: 0 });
207
+ }
208
+
209
+ export function activate(
210
+ store: Store,
211
+ input: ActivationInput,
212
+ t: RecallTunables,
213
+ ): ActivationResult {
214
+ const storeSize = input.storeSize;
215
+
216
+ // ── the token channel: one index probe per distinct cue token ────────────
217
+ const searchTokens: string[] = [];
218
+ const seenTok = new Set<string>();
219
+ for (const tok of tokenize(input.text)) {
220
+ if (tok.length < t.MIN_CUE_LENGTH || seenTok.has(tok)) continue;
221
+ seenTok.add(tok);
222
+ searchTokens.push(tok);
223
+ if (searchTokens.length >= t.MAX_CUES * 3) break;
224
+ }
225
+ for (const tok of input.carried ?? []) {
226
+ if (tok.length < t.MIN_CUE_LENGTH || seenTok.has(tok)) continue;
227
+ seenTok.add(tok);
228
+ searchTokens.push(tok);
229
+ }
230
+
231
+ // ── rarity FIRST, postings second ───────────────────────────────────────
232
+ //
233
+ // The order is the fix. This pass used to probe the index for every search
234
+ // token and take `df = hits.length` — but `hits` is a top-`PER_CUE_FETCH`,
235
+ // and a bounded top-K's length is `min(trueDf, K)`, never a document
236
+ // frequency. On a 15,421-document index that made every word occurring in 24
237
+ // or more memories measure as equally rare: `the` and `conversation` drew
238
+ // `informativeness` 5.7 against a ceiling of 8.95 where their true
239
+ // frequencies put them at 0-3. §9 G4's "informativeness weighting replaces
240
+ // stop-lists" was therefore true on a fixture (where `trueDf` cannot reach K)
241
+ // and false on the live store — the rule silently switched off as the store
242
+ // grew. `store.docFrequency` counts instead of measuring a limit.
243
+ //
244
+ // Asking for rarity first also means the index is probed only for the tokens
245
+ // that BECAME cues (at most `MAX_CUES`), rather than for every candidate
246
+ // token (up to `MAX_CUES * 3`). Nothing downstream reads a non-cue's
247
+ // postings, so that is an equivalence and strictly less work — it pays for
248
+ // the df query several times over.
249
+ const df = store.docFrequency(searchTokens);
250
+
251
+ const cues = buildCues(
252
+ {
253
+ text: input.text,
254
+ carried: input.carried ?? [],
255
+ ...(input.aliases !== undefined ? { aliases: input.aliases } : {}),
256
+ storeSize,
257
+ df,
258
+ },
259
+ t,
260
+ );
261
+
262
+ /**
263
+ * token -> (memoryId -> the token's LENGTH-NORMALIZED evidence in that
264
+ * document). The store applies the normalization before its own
265
+ * `ORDER BY … LIMIT`, so what arrives here is both scored and SELECTED
266
+ * length-fairly; re-ranking a raw-tf top-24 in this file would have left the
267
+ * long documents holding every slot (see `store/cache.ts#searchIndex`).
268
+ */
269
+ const postings = new Map<string, Map<string, number>>();
270
+ const norm = {
271
+ k1: t.CUE_TF_SATURATION,
272
+ b: t.CUE_LENGTH_NORM,
273
+ oneSided: t.CUE_LENGTH_ONE_SIDED,
274
+ };
275
+ for (const cue of cues) {
276
+ if (postings.has(cue.token)) continue;
277
+ const byDoc = new Map<string, number>();
278
+ for (const h of store.search(cue.token, t.PER_CUE_FETCH, norm)) byDoc.set(h.id, h.score);
279
+ postings.set(cue.token, byDoc);
280
+ }
281
+
282
+ const cueScore = new Map<string, number>();
283
+ const matchCount = new Map<string, number>();
284
+ const unambiguousMatch = new Set<string>();
285
+ /** The single strongest cue each document received — the cap's yardstick. */
286
+ const bestCue = new Map<string, number>();
287
+ for (const cue of cues) {
288
+ const byDoc = postings.get(cue.token);
289
+ if (byDoc === undefined) continue;
290
+ for (const [id, evidence] of byDoc) {
291
+ // `evidence` already carries the tf saturation AND the length
292
+ // normalization, applied by the index (`store/cache.ts#searchIndex`).
293
+ // Applying `tfFactor` again here would saturate a saturated number.
294
+ const add = cue.weight * evidence;
295
+ if (add <= 0) continue;
296
+ cueScore.set(id, (cueScore.get(id) ?? 0) + add);
297
+ bestCue.set(id, Math.max(bestCue.get(id) ?? 0, add));
298
+ matchCount.set(id, (matchCount.get(id) ?? 0) + 1);
299
+ if (!cue.ambiguous) unambiguousMatch.add(id);
300
+ }
301
+ }
302
+
303
+ // ── the per-document ceiling ────────────────────────────────────────────
304
+ // Length normalization damps how loudly ONE cue speaks for a long memory; it
305
+ // does not stop a memory that mentions everything from being touched by
306
+ // twenty cues at once. This is the second half of the same rule: a document's
307
+ // cue evidence may reach `CUE_DOC_CAP` times its own strongest single cue and
308
+ // no further. Three converging cues is corroboration; twenty is coverage, and
309
+ // coverage is a property of the document rather than of the turn.
310
+ //
311
+ // It is applied HERE, to the lexical sum only — before the temporal channel
312
+ // adds to the same map. A temporal cue is id-addressed and has no length, so
313
+ // capping it would be capping the calendar.
314
+ let capped = 0;
315
+ if (t.CUE_DOC_CAP > 0 && Number.isFinite(t.CUE_DOC_CAP)) {
316
+ for (const [id, sum] of cueScore) {
317
+ const ceiling = (bestCue.get(id) ?? 0) * t.CUE_DOC_CAP;
318
+ if (sum > ceiling) {
319
+ cueScore.set(id, ceiling);
320
+ capped += 1;
321
+ }
322
+ }
323
+ }
324
+
325
+ // ── the temporal channel: the same map, so one activation number ────────
326
+ // A temporal cue can CREATE a candidate (that is what a cue is) and is counted
327
+ // as cue by `cueFraction` below. Its ceiling is applied when the candidate is
328
+ // assembled, not here — this stage scores, it does not decide tiers.
329
+ //
330
+ // The weight arrives in CUE UNITS and is converted here, for the same reason
331
+ // the gate's floors are: `prospective.CUE_STRENGTH` is 0.5 on v1's normalized
332
+ // scale, and v2's cue channel is a sum of idf x evidence whose size grows with
333
+ // the store. Left absolute, a temporal cue would be worth 0.23 of a
334
+ // maximally-rare word on a seventeen-memory store and 0.056 of one on a
335
+ // fifteen-thousand-memory store — the calendar going quiet as the owner
336
+ // remembers more, which is the exact shape of scar §2.8 in the other
337
+ // direction. Converted, `CUE_STRENGTH` finally means what its comment says:
338
+ // *one more cue, like the user typing "Portland"* — half of one, at full ramp.
339
+ const temporalScore = new Map<string, number>();
340
+ const cueUnit = informativeness(1, storeSize);
341
+ for (const t0 of input.temporal ?? []) {
342
+ if (!(t0.weight > 0)) continue;
343
+ const w = t0.weight * cueUnit;
344
+ temporalScore.set(t0.id, (temporalScore.get(t0.id) ?? 0) + w);
345
+ cueScore.set(t0.id, (cueScore.get(t0.id) ?? 0) + w);
346
+ }
347
+
348
+ // ── the embedding channel: an INPUT, never a fetched one ────────────────
349
+ //
350
+ // TWO ways in, one scoring rule. `vector` is the caller's own embedding and
351
+ // this pass ranks it (the deliberate ask, which has no latency budget);
352
+ // `hits` is a ranking somebody else already did — the detached worker, one
353
+ // turn ago (`session.ts`, the lagged semantic cue), because the RANK is what
354
+ // costs 600-1000 ms on a live-sized index, not the arithmetic below. Supplied
355
+ // hits win: a caller that has both meant the resolved one.
356
+ const semScore = new Map<string, number>();
357
+ let semanticDegraded = false;
358
+ const ranked: readonly Hit[] | null =
359
+ input.hits !== undefined
360
+ ? input.hits
361
+ : input.vector !== undefined && input.vector.length > 0
362
+ ? store.nearestTo(input.vector, t.SEMANTIC_TOP_M)
363
+ : null;
364
+ if (ranked !== null) {
365
+ if (ranked.length === 0) semanticDegraded = true;
366
+ const floor = t.SEMANTIC_SEED_FLOOR;
367
+ for (const h of ranked.slice(0, t.SEMANTIC_TOP_M)) {
368
+ if (h.score < floor) continue;
369
+ const scaled = floor >= 1 ? h.score : (h.score - floor) / (1 - floor);
370
+ semScore.set(h.id, t.SEMANTIC_WEIGHT * scaled);
371
+ }
372
+ }
373
+
374
+ // ── assemble: only live, resolvable, non-removed memory ─────────────────
375
+ const denied = new Set(store.deniedIds());
376
+ const ids = new Set<string>([...cueScore.keys(), ...semScore.keys()]);
377
+
378
+ // ── the hop channel: modulate only (SEAMS item L) ───────────────────────
379
+ // The seeds are the candidates the CONVERSATION reached; a contribution to
380
+ // anything outside that set is dropped right here, so a hop can never be the
381
+ // reason a memory is fetched at all.
382
+ // The SEEDS are the CUED candidates (`associate/INTERFACE-GAPS.md` §1's own
383
+ // wording). A seed receives no contribution of its own — a round trip a→b→a
384
+ // would hand a memory its own activation back as new evidence — so what the
385
+ // graph can actually raise is a candidate the OTHER channels reached: a
386
+ // semantic hit, or a temporal one, that the conversation's own words did not.
387
+ const hopScore = new Map<string, number>();
388
+ if (input.spread !== undefined && cueScore.size > 0) {
389
+ const seeds = [...cueScore.entries()].map(([id, activation]) => ({ id, activation }));
390
+ for (const c of input.spread(seeds, input.day).contributions) {
391
+ // Dropped unless it is ALREADY a candidate. This line is hard gate (a):
392
+ // a hop is not a cue, and an uncued memory is dark whatever reached it.
393
+ if (!ids.has(c.id) || !(c.activation > 0)) continue;
394
+ hopScore.set(c.id, (hopScore.get(c.id) ?? 0) + c.activation);
395
+ }
396
+ }
397
+
398
+ // Two passes: SCORE from box 2, then READ the survivors' prose.
399
+ //
400
+ // Every number in the sort key — cue, semantic, arrival, hops — is available
401
+ // from the operational row alone. The prose body is not in that row, and is
402
+ // needed only for the confidentiality class and for whatever the renderer
403
+ // prints. So the ranking happens first and the FILE READS happen only for the
404
+ // candidates that survive `maxCandidates`.
405
+ //
406
+ // This is an equivalence, not a heuristic: same candidates, same order, same
407
+ // `skipped` count. It is here because length normalization widened the union
408
+ // of the token index's hits by an order of magnitude — the old scorer's nine
409
+ // hubs occupied most of every cue's top-`PER_CUE_FETCH`, so the union was
410
+ // small by ACCIDENT, and the accident was the bug. Reading a prose file for
411
+ // each of ~1,000 ids and discarding all but 24 measured ~600 ms of a 1200 ms
412
+ // budget on the live store; it is now 24 reads whatever the union's width.
413
+ interface Scored {
414
+ readonly id: string;
415
+ readonly physics: MemoryPhysics;
416
+ readonly strength: number;
417
+ readonly cue: number;
418
+ readonly temporal: number;
419
+ readonly semantic: number;
420
+ readonly arrival: number;
421
+ readonly hops: number;
422
+ readonly activation: number;
423
+ }
424
+ const scored: Scored[] = [];
425
+ let skipped = 0;
426
+ for (const id of ids) {
427
+ if (denied.has(id)) {
428
+ skipped += 1;
429
+ continue;
430
+ }
431
+ const row = store.row(id);
432
+ // Archive is a state, not a deletion: it keeps its id and simply never
433
+ // surfaces (§4.2 G3). A superseded head forwards; the successor is reached
434
+ // on its own merits, never by dragging the old id along.
435
+ if (row === undefined || row.archived === 1 || row.superseded_by !== null) {
436
+ skipped += 1;
437
+ continue;
438
+ }
439
+ // The self page, which is delivered at wake and never here (`isSelfPage`).
440
+ // The prose read is gated on the row's own columns, so only a SCHEMA row of
441
+ // the self kind pays for it — the page, the identity core, and the handful
442
+ // of beliefs held about the self.
443
+ if (row.type === "schema" && row.kind === "self" && isPageRow(store, id)) {
444
+ skipped += 1;
445
+ continue;
446
+ }
447
+ // The per-directory handoff (E1), for the page's reason and one of its own:
448
+ // it is already delivered as a pointer at the wake of the directory it
449
+ // belongs to, and it has no project scope of its own that a search could
450
+ // honour — so left in the pool it would surface one directory's working
451
+ // context inside another's turn. Gated on the row's own columns, as above,
452
+ // so only a SCHEMA row of the place kind pays for the prose read.
453
+ if (row.type === "schema" && row.kind === "place" && isHandoffRow(store, id)) {
454
+ skipped += 1;
455
+ continue;
456
+ }
457
+ const physics = rowToPhysics(row);
458
+ const cue = cueScore.get(id) ?? 0;
459
+ const temporal = temporalScore.get(id) ?? 0;
460
+ const semantic = semScore.get(id) ?? 0;
461
+ const s = strength(physics, input.day);
462
+ const arrival = cue + semantic > 0 ? t.ARRIVAL_WEIGHT * s : 0;
463
+ const hops = cue + semantic > 0 ? hopScore.get(id) ?? 0 : 0;
464
+ scored.push({
465
+ id,
466
+ physics,
467
+ strength: s,
468
+ cue,
469
+ temporal,
470
+ semantic,
471
+ arrival,
472
+ hops,
473
+ activation: cue + semantic + arrival + hops,
474
+ });
475
+ }
476
+ scored.sort((a, b) => b.activation - a.activation || (a.id < b.id ? -1 : 1));
477
+
478
+ const candidates: Candidate[] = [];
479
+ for (const c of scored.slice(0, input.maxCandidates)) {
480
+ const { id, physics, cue, temporal, semantic, arrival, hops, activation } = c;
481
+ // `readProse` is `read().doc`, so taking the whole read costs nothing and
482
+ // brings the confidentiality flag with it instead of re-deriving it.
483
+ const stored = store.read(id);
484
+ const doc = stored.doc;
485
+ candidates.push({
486
+ id,
487
+ kind: physics.kind,
488
+ doc,
489
+ physics,
490
+ strength: c.strength,
491
+ sal: gatedSal(physics, input.selfFelt),
492
+ cue,
493
+ temporal,
494
+ semantic,
495
+ arrival,
496
+ hops,
497
+ activation,
498
+ // Hops are in the DENOMINATOR only: they can raise a candidate's standing
499
+ // and can never buy it the loud tier.
500
+ cueFraction: activation > 0 ? (cue + semantic) / activation : 0,
501
+ matched: matchCount.get(id) ?? 0,
502
+ // A temporal cue is id-addressed: no handle is involved, so nothing about
503
+ // it is ambiguous, and an unambiguous cue trains. Without this clause a
504
+ // temporal-only surface would be refused as "ambiguous-handle-trains-
505
+ // nothing" — a true refusal under a false name (scar §2.4).
506
+ trains: unambiguousMatch.has(id) || semantic > 0 || temporal > 0,
507
+ // §12 G5: temporal ALONE reaches the footnote tier at most.
508
+ maxTier: temporal > 0 && cue - temporal <= 0 && semantic <= 0 ? "footnoted" : "surfaced",
509
+ confidential: stored.confidential,
510
+ });
511
+ }
512
+
513
+ return {
514
+ cues,
515
+ candidates,
516
+ storeSize,
517
+ skipped,
518
+ semanticDegraded,
519
+ capped,
520
+ };
521
+ }