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,692 @@
1
+ /**
2
+ * `recall/` — retrieval and priming. Cues → activation → the surfacing gate → a
3
+ * bounded injection, plus the footnote tier, plus noticing afterwards whether a
4
+ * surfaced memory was actually used.
5
+ *
6
+ * The module's spine, and where each piece lives:
7
+ *
8
+ * `cues.ts` strip host boilerplate, then rarity-weighted, word-bounded cues
9
+ * `activate.ts` three channels — cue, semantic, arrival — against the cache box
10
+ * `gate.ts` the hard gates, this turn's own background bar, the tiers
11
+ * `session.ts` per-session gate state, PERSISTED (the ruling this module exists to honor)
12
+ * `render.ts` composed budget, explicit trim order, tail sentinel
13
+ * `tunables.ts` every knob, in one visible place
14
+ *
15
+ * Two properties are structural here and worth stating at the top:
16
+ *
17
+ * **BUILD and RECORD are separate steps** (contract §5 G3). `build()` is pure with
18
+ * respect to durable state: it reads, scores, gates and composes, and writes
19
+ * nothing — not gate state, not telemetry. `recall()` calls it and then records.
20
+ * That split is what makes guarantee 2 achievable: **a latency-budget abort has
21
+ * zero side effects** — nothing injected, nothing buffered, no telemetry, no fire
22
+ * budget spent. *A slow subconscious is worse than a quiet one.*
23
+ *
24
+ * **NO GENERATIVE MODEL CALL, EVER, on this path.** There is no client, no fetch,
25
+ * no URL in this directory, and a test enumerates that. An embedding may be
26
+ * consulted — but only as an INPUT the caller supplies, and its absence degrades
27
+ * to lexical-only rather than failing (contract §5 G1).
28
+ */
29
+ import type { Kind } from "../types.js";
30
+ import { USE_TIER_WEIGHT } from "../physics/index.js";
31
+ import type { CreditOutcome, UseTier } from "../physics/index.js";
32
+ import type { ProseDoc, Store } from "../store/index.js";
33
+ import { activate } from "./activate.js";
34
+ import type { Candidate } from "./activate.js";
35
+ import { detectAffect, stripBoilerplate } from "./cues.js";
36
+ import { floorUnit, gate } from "./gate.js";
37
+ import type { Background, CandidateVerdict, Verdict } from "./gate.js";
38
+ import { loadGateState, saveGateState } from "./session.js";
39
+ import type { GateState, SemanticSource } from "./session.js";
40
+ import { render } from "./render.js";
41
+ import type { RenderResult, Resolve, Resolved } from "./render.js";
42
+ import { withTunables } from "./tunables.js";
43
+ import type { RecallTunables } from "./tunables.js";
44
+
45
+ export * from "./cues.js";
46
+ export * from "./gate.js";
47
+ export * from "./render.js";
48
+ export * from "./session.js";
49
+ export * from "./tunables.js";
50
+ export { activate, isConfidential, isHandoff, isSelfPage, gatedSal } from "./activate.js";
51
+ export type { Candidate, ActivationResult } from "./activate.js";
52
+
53
+ /** Telemetry: ids, counts, scores, tiers, reasons. NEVER body text or turn text. */
54
+ export interface RecallEvent {
55
+ at: number;
56
+ name: string;
57
+ ref?: string;
58
+ data?: Record<string, string | number | boolean | null>;
59
+ }
60
+
61
+ export interface RecallOptions {
62
+ store: Store;
63
+ /** Overrides on the CAL table. Every one is a calibration claim (scar §2.8). */
64
+ tunables?: Partial<RecallTunables>;
65
+ /** The host's injection ceiling (scar §2.18 — the ceiling is a host capability). */
66
+ budgetBytes?: number;
67
+ /** Latency budget for the build pass, ms. */
68
+ budgetMs?: number;
69
+ /**
70
+ * Is this the owner's own session? Defaults to FALSE: withholding is the safe
71
+ * direction, and an observer is a non-owner regardless (observer-mode.md G7).
72
+ */
73
+ owner?: boolean;
74
+ onEvent?: (e: RecallEvent) => void;
75
+ /** Injectable clock, so the latency budget is testable without sleeping. */
76
+ now?: () => number;
77
+ }
78
+
79
+ export interface Turn {
80
+ sessionId: string;
81
+ text: string;
82
+ /** The turn's embedding, supplied by the caller. NEVER fetched here. */
83
+ vector?: readonly number[];
84
+ /**
85
+ * The semantic channel ALREADY RANKED — the lagged cue the detached worker
86
+ * resolved after the previous turn (`session.ts`). It exists because ranking
87
+ * is the expensive half: `Store.nearestTo` over a live-sized vector index
88
+ * measured 590-1040 ms, which no 1200 ms budget survives. Supplied hits
89
+ * replace the scan; an empty array means "nothing was near" and degrades.
90
+ */
91
+ semanticHits?: readonly { id: string; score: number }[];
92
+ /** Where the semantic input came from, for the decision record. Defaults to
93
+ * `in-line` when a vector is supplied and `none` when nothing is. */
94
+ semanticSource?: SemanticSource;
95
+ /** The turn a lagged cue was computed from. Provenance, not a knob. */
96
+ semanticFromTurn?: number;
97
+ /** handle -> memory ids; >= 2 ids makes the handle ambiguous (INTERFACE-GAPS #2). */
98
+ aliases?: ReadonlyMap<string, readonly string[]>;
99
+ /** Temporal cues — `prospective.arrivals()`, mapped to `{id, weight}` at the
100
+ * composition root (`src/core/retrieval.ts`, SEAMS item D). They enter through
101
+ * the CUE channel and no other; see `activate.ts`'s header for why the word
102
+ * "arrival" means two different things on the two sides of this seam. */
103
+ temporal?: readonly { id: string; weight: number }[];
104
+ /** Spreading activation (SEAMS item L), injected at the composition root.
105
+ * Hops MODULATE candidates the conversation already reached; they never mint
106
+ * one, which is what keeps hard gate (a) structural. */
107
+ spread?: (
108
+ seeds: readonly { id: string; activation: number }[],
109
+ day: number,
110
+ ) => { contributions: readonly { id: string; activation: number }[] };
111
+ /** Lived day. Defaults to the store's clock (scar E8 — lived, not calendar). */
112
+ day?: number;
113
+ /** Per-turn override of the session's owner stance. */
114
+ owner?: boolean;
115
+ budgetBytes?: number;
116
+ /**
117
+ * Per-turn override of the LATENCY budget. It exists for one caller: the
118
+ * deliberate ask, which is "a deeper effort with different thresholds, on
119
+ * purpose" (§9.1) and has no host turn waiting on it. The ambient budget is a
120
+ * promise to a person mid-sentence; a question someone typed and is waiting
121
+ * for is a different promise, and the semantic channel it may pay for costs
122
+ * 590-1040 ms of vector scan on a live-sized index all by itself.
123
+ */
124
+ budgetMs?: number;
125
+ }
126
+
127
+ export type DecisionReason =
128
+ | "rendered"
129
+ | "empty-turn"
130
+ | "no-candidates"
131
+ | "all-gated"
132
+ | "budget-quiet"
133
+ | "latency-abort";
134
+
135
+ /**
136
+ * The per-turn surfacing decision record — content-by-reference from day one
137
+ * (contract §5 G14, scar §2.20). Ids, counts, scores, reasons. No bodies, and no
138
+ * cue TOKENS either: a cue token is a word the user typed, and turn text is
139
+ * exactly what telemetry may not carry.
140
+ */
141
+ export interface RecallDecision {
142
+ readonly sessionId: string;
143
+ readonly turn: number;
144
+ readonly day: number;
145
+ readonly observer: boolean;
146
+ readonly owner: boolean;
147
+ readonly reason: DecisionReason;
148
+ readonly aborted: boolean;
149
+ readonly storeSize: number;
150
+ readonly background: Background;
151
+ /** Which boilerplate strippers fired, by NAME (§9 G3). */
152
+ readonly stripped: string[];
153
+ readonly cueCount: number;
154
+ readonly ambiguousCueCount: number;
155
+ readonly carriedCueCount: number;
156
+ readonly semanticUsed: boolean;
157
+ readonly semanticDegraded: boolean;
158
+ /**
159
+ * WHERE the semantic channel's input came from, by name — including every way
160
+ * it was dark. The measured failure this closes: both live paths built their
161
+ * turn without a vector, so `semanticUsed: false` was written on every real
162
+ * turn and said nothing about why (scar §2.4 — "did not fire" and "was never
163
+ * asked" are different records).
164
+ *
165
+ * NOT in `RECALL_DECISION_FIELDS`: the durable surface set is hashed to decide
166
+ * whether a human rating carries across a code change (parallel §5 G12), and
167
+ * moving it mid-run would invalidate every carried verdict. This rides the
168
+ * adapter's own `adapter.recall` row instead, like `semanticUsed` before it.
169
+ */
170
+ readonly semanticSource: SemanticSource;
171
+ /** For a lagged cue: the turn it was computed from. Null otherwise. */
172
+ readonly semanticFromTurn: number | null;
173
+ readonly candidates: number;
174
+ readonly verdicts: CandidateVerdict[];
175
+ readonly surfaced: string[];
176
+ readonly footnotes: string[];
177
+ readonly affectFlag: boolean;
178
+ readonly affectReason: string;
179
+ readonly bytes: number;
180
+ readonly budgetBytes: number;
181
+ readonly sentinel: string | null;
182
+ readonly trimmed: { lane: string; id: string | null }[];
183
+ readonly elapsedMs: number;
184
+ }
185
+
186
+ export interface RecallResult {
187
+ /** The empty string on a quiet turn — never an empty block. */
188
+ readonly injection: string;
189
+ readonly decision: RecallDecision;
190
+ }
191
+
192
+ export type CreditReason =
193
+ | "credited"
194
+ | "observer"
195
+ | "ambiguous-handle-trains-nothing"
196
+ | "already-credited-at-or-above"
197
+ | "physics-refused";
198
+
199
+ export interface CreditResult {
200
+ readonly credited: boolean;
201
+ readonly reason: CreditReason;
202
+ readonly tier: UseTier;
203
+ readonly w: number;
204
+ /** Physics' own verdict, when it was consulted. */
205
+ readonly outcome: CreditOutcome | null;
206
+ }
207
+
208
+ interface BuildOutput {
209
+ decision: RecallDecision;
210
+ injection: string;
211
+ state: GateState;
212
+ /** Cue tokens to carry into the next turn. State, not telemetry (see NOTES.md). */
213
+ carry: string[];
214
+ render: RenderResult | null;
215
+ gateStatus: "loaded" | "absent" | "unreadable";
216
+ }
217
+
218
+ export class Recall {
219
+ readonly store: Store;
220
+ readonly tunables: RecallTunables;
221
+ /** One predicate, one definition: the store's. Never re-derived here. */
222
+ readonly observer: boolean;
223
+
224
+ private readonly defaultOwner: boolean;
225
+ private readonly budgetBytes: number;
226
+ private readonly budgetMs: number;
227
+ private readonly onEvent: ((e: RecallEvent) => void) | undefined;
228
+ private readonly now: () => number;
229
+ /** Observer-only: gate state that may never be deposited, so it lives here. */
230
+ private readonly volatile = new Map<string, GateState>();
231
+
232
+ constructor(opts: RecallOptions) {
233
+ this.store = opts.store;
234
+ this.tunables = withTunables(opts.tunables ?? {});
235
+ this.observer = opts.store.observer;
236
+ this.defaultOwner = opts.owner === true && !this.observer;
237
+ this.budgetBytes = opts.budgetBytes ?? this.tunables.BUDGET_BYTES;
238
+ this.budgetMs = opts.budgetMs ?? this.tunables.BUDGET_MS;
239
+ this.onEvent = opts.onEvent;
240
+ this.now = opts.now ?? (() => Date.now());
241
+ }
242
+
243
+ // ── the hot path ─────────────────────────────────────────────────────────
244
+
245
+ /**
246
+ * BUILD: read, score, gate, compose. Writes nothing durable and emits nothing.
247
+ * Exposed because "build and record are separate steps" is only a real property
248
+ * if the build is separately callable — a private half is a promise, not a seam.
249
+ */
250
+ build(turn: Turn): BuildOutput {
251
+ const started = this.now();
252
+ const day = turn.day ?? this.store.livedDay();
253
+ const owner = (turn.owner ?? this.defaultOwner) && !this.observer;
254
+ const budgetBytes = turn.budgetBytes ?? this.budgetBytes;
255
+ const budgetMs = turn.budgetMs ?? this.budgetMs;
256
+
257
+ const loaded = this.observer
258
+ ? { state: this.volatileState(turn.sessionId), status: "loaded" as const }
259
+ : loadGateState(this.store, turn.sessionId, this.tunables.MAX_SESSION_RECORDS);
260
+ const state = loaded.state;
261
+ const turnNo = state.turn + 1;
262
+
263
+ // The semantic channel's input, judged ONCE: a vector this caller embedded,
264
+ // or a ranking somebody else already did. Both are "the channel had input";
265
+ // the SOURCE says which, and when there was none, why not.
266
+ const semanticOffered =
267
+ (turn.vector !== undefined && turn.vector.length > 0) || turn.semanticHits !== undefined;
268
+ const semanticSource: SemanticSource =
269
+ turn.semanticSource ?? (semanticOffered ? "in-line" : "none");
270
+ const semanticFromTurn = turn.semanticFromTurn ?? null;
271
+
272
+ const { text, stripped } = stripBoilerplate(turn.text);
273
+ const affect = detectAffect(text);
274
+ const carriedIn =
275
+ state.carriedFromTurn === turnNo - 1 && state.carriedCues.length > 0
276
+ ? state.carriedCues
277
+ : [];
278
+
279
+ const quiet = (
280
+ reason: DecisionReason,
281
+ partial: Partial<RecallDecision> = {},
282
+ ): BuildOutput => ({
283
+ decision: {
284
+ sessionId: turn.sessionId,
285
+ turn: turnNo,
286
+ day,
287
+ observer: this.observer,
288
+ owner,
289
+ reason,
290
+ aborted: reason === "latency-abort",
291
+ storeSize: 0,
292
+ background: {
293
+ regime: "absolute-thin-background",
294
+ n: 0,
295
+ mean: 0,
296
+ sd: 0,
297
+ // The floors are in CUE UNITS now (`gate.ts#floorUnit`), and a quiet
298
+ // turn reports `storeSize: 0` — it never counted one. Quoting the
299
+ // floor at that store size is the honest reading of this record: no
300
+ // store, no unit, no bar anything was judged against.
301
+ bar: this.tunables.FLOOR_GLOBAL_UNITS * floorUnit(0),
302
+ strongBar: this.tunables.FLOOR_GLOBAL_UNITS * floorUnit(0),
303
+ floor: this.tunables.FLOOR_GLOBAL_UNITS * floorUnit(0),
304
+ },
305
+ stripped,
306
+ cueCount: 0,
307
+ ambiguousCueCount: 0,
308
+ carriedCueCount: carriedIn.length,
309
+ semanticUsed: semanticOffered,
310
+ semanticDegraded: false,
311
+ semanticSource,
312
+ semanticFromTurn,
313
+ candidates: 0,
314
+ verdicts: [],
315
+ surfaced: [],
316
+ footnotes: [],
317
+ affectFlag: false,
318
+ affectReason: "no-feeling-in-turn",
319
+ bytes: 0,
320
+ budgetBytes,
321
+ sentinel: null,
322
+ trimmed: [],
323
+ elapsedMs: this.now() - started,
324
+ ...partial,
325
+ },
326
+ injection: "",
327
+ state,
328
+ carry: [],
329
+ render: null,
330
+ gateStatus: loaded.status,
331
+ });
332
+
333
+ if (text.trim().length === 0) return quiet("empty-turn");
334
+
335
+ // Cold start is STRICTER, not looser: below a minimum store size the variance
336
+ // estimate is meaningless and small stores over-surface (§9 G13).
337
+ const storeSize = this.store.list({ archived: false }).length;
338
+ const maxCandidates =
339
+ storeSize < this.tunables.COLD_START_MIN_STORE
340
+ ? this.tunables.COLD_START_MAX_CANDIDATES
341
+ : this.tunables.MAX_CANDIDATES;
342
+
343
+ const act = activate(
344
+ this.store,
345
+ {
346
+ text,
347
+ vector: turn.vector,
348
+ hits: turn.semanticHits,
349
+ carried: carriedIn,
350
+ aliases: turn.aliases,
351
+ temporal: turn.temporal,
352
+ spread: turn.spread,
353
+ day,
354
+ selfFelt: affect.selfFelt,
355
+ maxCandidates,
356
+ storeSize,
357
+ },
358
+ this.tunables,
359
+ );
360
+
361
+ if (this.now() - started > budgetMs) return quiet("latency-abort");
362
+
363
+ const carry = act.cues
364
+ .filter((c) => !c.carried)
365
+ .slice(0, this.tunables.MAX_CUES)
366
+ .map((c) => c.token);
367
+ const cueStats = {
368
+ cueCount: act.cues.length,
369
+ ambiguousCueCount: act.cues.filter((c) => c.ambiguous).length,
370
+ carriedCueCount: carriedIn.length,
371
+ storeSize: act.storeSize,
372
+ semanticDegraded: act.semanticDegraded,
373
+ };
374
+
375
+ if (act.candidates.length === 0) {
376
+ return { ...quiet("no-candidates", cueStats), carry };
377
+ }
378
+
379
+ const gated = gate(
380
+ {
381
+ candidates: act.candidates,
382
+ state,
383
+ storeSize: act.storeSize,
384
+ owner,
385
+ affectStated: affect.stated,
386
+ turn: turnNo,
387
+ },
388
+ this.tunables,
389
+ );
390
+
391
+ if (this.now() - started > budgetMs) return quiet("latency-abort");
392
+
393
+ const docs = new Map<string, ProseDoc>();
394
+ for (const c of act.candidates) docs.set(c.id, c.doc);
395
+ const resolve: Resolve = (id) => resolveDoc(docs.get(id), id);
396
+
397
+ const rendered = render(
398
+ {
399
+ turn: turnNo,
400
+ affectFlag: gated.affectFlag,
401
+ surfaced: gated.surfaced.map((c) => c.id),
402
+ footnotes: gated.footnotes.map((c) => c.id),
403
+ budgetBytes,
404
+ gistBytes: this.tunables.GIST_BYTES,
405
+ titleBytes: this.tunables.FOOTNOTE_TITLE_BYTES,
406
+ pressureRatio: this.tunables.BUDGET_PRESSURE,
407
+ },
408
+ resolve,
409
+ );
410
+
411
+ const nothingAdmitted =
412
+ gated.surfaced.length === 0 && gated.footnotes.length === 0 && !gated.affectFlag;
413
+ const reason: DecisionReason = nothingAdmitted
414
+ ? "all-gated"
415
+ : rendered.text === ""
416
+ ? "budget-quiet"
417
+ : "rendered";
418
+
419
+ const decision: RecallDecision = {
420
+ sessionId: turn.sessionId,
421
+ turn: turnNo,
422
+ day,
423
+ observer: this.observer,
424
+ owner,
425
+ reason,
426
+ aborted: false,
427
+ storeSize: act.storeSize,
428
+ background: gated.background,
429
+ stripped,
430
+ cueCount: cueStats.cueCount,
431
+ ambiguousCueCount: cueStats.ambiguousCueCount,
432
+ carriedCueCount: cueStats.carriedCueCount,
433
+ semanticUsed: semanticOffered,
434
+ semanticDegraded: act.semanticDegraded,
435
+ semanticSource,
436
+ semanticFromTurn,
437
+ candidates: act.candidates.length,
438
+ verdicts: gated.verdicts,
439
+ surfaced: rendered.surfaced,
440
+ footnotes: rendered.footnotes,
441
+ affectFlag: rendered.affectFlag,
442
+ affectReason: gated.affectReason,
443
+ bytes: rendered.bytes,
444
+ budgetBytes,
445
+ sentinel: rendered.sentinel,
446
+ trimmed: rendered.trimmed.map((x) => ({ lane: x.lane, id: x.id })),
447
+ elapsedMs: this.now() - started,
448
+ };
449
+
450
+ return {
451
+ decision,
452
+ injection: rendered.text,
453
+ state,
454
+ carry,
455
+ render: rendered,
456
+ gateStatus: loaded.status,
457
+ };
458
+ }
459
+
460
+ /**
461
+ * BUILD, then RECORD. The record step is where gate state is persisted and
462
+ * telemetry is emitted — and it is skipped entirely on a latency abort, which
463
+ * is what makes the abort side-effect-free.
464
+ */
465
+ recall(turn: Turn): RecallResult {
466
+ const built = this.build(turn);
467
+ const d = built.decision;
468
+
469
+ if (d.aborted) {
470
+ // Zero side effects on loss: nothing injected, nothing buffered, no
471
+ // telemetry, no state advanced (contract §5 G2).
472
+ return { injection: "", decision: d };
473
+ }
474
+
475
+ if (built.gateStatus === "unreadable") {
476
+ this.emit("recall.gate.reset", turn.sessionId, { status: built.gateStatus });
477
+ }
478
+
479
+ const next: GateState = {
480
+ ...built.state,
481
+ turn: d.turn,
482
+ lastDay: d.day,
483
+ surfaced: { ...built.state.surfaced },
484
+ affectFiredTurn: d.affectFlag ? d.turn : built.state.affectFiredTurn,
485
+ carriedCues: built.carry,
486
+ carriedFromTurn: d.turn,
487
+ };
488
+ for (const id of d.surfaced) {
489
+ next.surfaced[id] = { turn: d.turn, tier: "surfaced", trains: trainsOf(d.verdicts, id) };
490
+ }
491
+ for (const id of d.footnotes) {
492
+ next.surfaced[id] = { turn: d.turn, tier: "footnoted", trains: trainsOf(d.verdicts, id) };
493
+ }
494
+ this.persist(next, "recall");
495
+
496
+ this.emitTelemetry(d, built.render);
497
+ return { injection: built.injection, decision: d };
498
+ }
499
+
500
+ /**
501
+ * Retrospective reinforcement. Which memories the reply actually USED is the
502
+ * caller's judgment (§9.2 owns that rule and its precision bias); this method
503
+ * routes a decided tier to physics through the store seam and applies the two
504
+ * refusals that belong to the gate state it owns.
505
+ *
506
+ * The footnoted tier is deliberately NOT short-circuited: it goes through
507
+ * `store.reinforce` and comes back `credited: false, reason: "ignorable-tier"`,
508
+ * so "the ignorable tier trains nothing" is proved by the seam that would have
509
+ * trained it, not by an early return that never asked.
510
+ */
511
+ resolveUse(sessionId: string, memoryId: string, tier: UseTier): CreditResult {
512
+ const w = USE_TIER_WEIGHT[tier];
513
+ // Checked FIRST, before any other work (contract §5 G11, scar E7).
514
+ if (this.observer) {
515
+ this.emit("recall.observer.standdown", memoryId, { site: "resolveUse", tier });
516
+ return { credited: false, reason: "observer", tier, w, outcome: null };
517
+ }
518
+
519
+ const { state } = loadGateState(this.store, sessionId, this.tunables.MAX_SESSION_RECORDS);
520
+ const surfaced = state.surfaced[memoryId];
521
+ if (surfaced !== undefined && !surfaced.trains) {
522
+ // Both halves of §9 G5, and this is the consumer scar §2.6 demands: v1
523
+ // documented "ambiguous handles train nothing" in three places, enforced it
524
+ // in one, and a repo-wide grep found ZERO consumers of the flag.
525
+ this.emit("recall.credit.refused", memoryId, {
526
+ reason: "ambiguous-handle-trains-nothing",
527
+ tier,
528
+ });
529
+ return { credited: false, reason: "ambiguous-handle-trains-nothing", tier, w, outcome: null };
530
+ }
531
+ const today = this.store.livedDay();
532
+ const prior = state.credited[memoryId];
533
+ // Never downgrades an already-credited item (contract §5 G10) — WITHIN A
534
+ // LIVED DAY. Owner ruling 2026-09-14 (R2): a session that spans days and
535
+ // uses the same memory on each is a distinct occasion each day, exactly as
536
+ // physics §5.5 counts it; keyed to the session alone, the first consumer
537
+ // of this gate (#99) credited a memory once EVER per session.
538
+ if (prior !== undefined && prior.day === today && USE_TIER_WEIGHT[prior.tier] >= w) {
539
+ this.emit("recall.credit.refused", memoryId, {
540
+ reason: "already-credited-at-or-above",
541
+ tier,
542
+ prior: prior.tier,
543
+ });
544
+ return { credited: false, reason: "already-credited-at-or-above", tier, w, outcome: null };
545
+ }
546
+
547
+ const outcome = this.store.reinforce(memoryId, today, tier);
548
+ if (outcome.credited) {
549
+ state.credited[memoryId] = { turn: state.turn, tier, day: today };
550
+ this.persist(state, "resolveUse");
551
+ }
552
+ this.emit("recall.credit", memoryId, {
553
+ tier,
554
+ w,
555
+ credited: outcome.credited,
556
+ reason: outcome.reason,
557
+ });
558
+ return {
559
+ credited: outcome.credited,
560
+ reason: outcome.credited ? "credited" : "physics-refused",
561
+ tier,
562
+ w,
563
+ outcome,
564
+ };
565
+ }
566
+
567
+ /**
568
+ * The DELIVERY-side event (scar §2.3: "we rendered it" is not "they received
569
+ * it"). The host calls this with the last line it actually saw in context; a
570
+ * mismatch is the only way to tell a delivered injection from a truncated one.
571
+ */
572
+ noteDelivered(sessionId: string, sentinelSeen: string | null, expected: string | null): boolean {
573
+ const ok = expected !== null && sentinelSeen === expected;
574
+ this.emit("recall.delivered", sessionId, {
575
+ ok,
576
+ sawSentinel: sentinelSeen !== null,
577
+ expected: expected !== null,
578
+ });
579
+ return ok;
580
+ }
581
+
582
+ /** Read-only view of the persisted gate state — for tests, replay and the dashboard. */
583
+ gateState(sessionId: string): GateState {
584
+ return this.observer
585
+ ? this.volatileState(sessionId)
586
+ : loadGateState(this.store, sessionId, this.tunables.MAX_SESSION_RECORDS).state;
587
+ }
588
+
589
+ events(): RecallEvent[] {
590
+ return this.ring.map((e) => ({ ...e }));
591
+ }
592
+
593
+ // ── internals ────────────────────────────────────────────────────────────
594
+
595
+ private readonly ring: RecallEvent[] = [];
596
+
597
+ private emit(
598
+ name: string,
599
+ ref?: string,
600
+ data?: Record<string, string | number | boolean | null>,
601
+ ): void {
602
+ const e: RecallEvent = { at: this.now(), name };
603
+ if (ref !== undefined) e.ref = ref;
604
+ if (data !== undefined) e.data = data;
605
+ this.ring.push(e);
606
+ if (this.ring.length > 500) this.ring.shift();
607
+ this.onEvent?.(e);
608
+ }
609
+
610
+ private volatileState(sessionId: string): GateState {
611
+ let s = this.volatile.get(sessionId);
612
+ if (s === undefined) {
613
+ s = loadGateState(this.store, sessionId, this.tunables.MAX_SESSION_RECORDS).state;
614
+ this.volatile.set(sessionId, s);
615
+ }
616
+ return s;
617
+ }
618
+
619
+ /**
620
+ * The one write site for gate state. Under observer it stands down BEFORE the
621
+ * store seam is touched and keeps the state in-process instead: an instrument
622
+ * deposits nothing, and every stand-down is observable (observer-mode.md G6).
623
+ */
624
+ private persist(state: GateState, site: string): void {
625
+ if (this.observer) {
626
+ this.volatile.set(state.sessionId, state);
627
+ this.emit("recall.observer.standdown", state.sessionId, { site: `persist:${site}` });
628
+ return;
629
+ }
630
+ saveGateState(this.store, state, this.tunables.MAX_SESSION_RECORDS);
631
+ }
632
+
633
+ private emitTelemetry(d: RecallDecision, r: RenderResult | null): void {
634
+ const counts = new Map<Verdict, number>();
635
+ for (const v of d.verdicts) counts.set(v.verdict, (counts.get(v.verdict) ?? 0) + 1);
636
+ for (const [verdict, count] of counts) {
637
+ if (verdict === "surfaced" || verdict === "footnoted") continue;
638
+ this.emit("recall.withheld", undefined, { reason: verdict, count });
639
+ }
640
+ for (const t of d.trimmed) this.emit("recall.trim", t.id ?? undefined, { lane: t.lane });
641
+
642
+ if (d.reason === "rendered") {
643
+ // §2.9: context assembly logs WHAT IT SHOWED, by id.
644
+ this.emit("recall.rendered", d.sessionId, {
645
+ turn: d.turn,
646
+ regime: d.background.regime,
647
+ candidates: d.candidates,
648
+ surfaced: d.surfaced.length,
649
+ footnotes: d.footnotes.length,
650
+ affect: d.affectFlag,
651
+ bytes: d.bytes,
652
+ budget: d.budgetBytes,
653
+ ids: [...d.surfaced, ...d.footnotes].join(","),
654
+ elapsedMs: d.elapsedMs,
655
+ });
656
+ if (r?.pressure === true) {
657
+ this.emit("recall.budget.pressure", d.sessionId, {
658
+ bytes: d.bytes,
659
+ budget: d.budgetBytes,
660
+ });
661
+ }
662
+ } else {
663
+ this.emit("recall.quiet", d.sessionId, {
664
+ turn: d.turn,
665
+ reason: d.reason,
666
+ candidates: d.candidates,
667
+ regime: d.background.regime,
668
+ });
669
+ }
670
+ }
671
+ }
672
+
673
+ function trainsOf(verdicts: readonly CandidateVerdict[], id: string): boolean {
674
+ return verdicts.find((v) => v.id === id)?.trains ?? true;
675
+ }
676
+
677
+ /**
678
+ * Id → text, at render time only. A missing doc renders as its own id.
679
+ *
680
+ * The journal flag is read off the doc's own `type` — the same field
681
+ * `sleep/types.ts#isJournal` reads off the row — so the label cannot disagree
682
+ * with what the rest of the system calls a chapter, and nothing had to be added
683
+ * to the candidate, the verdict or the decision record to carry it.
684
+ */
685
+ function resolveDoc(doc: ProseDoc | undefined, id: string): Resolved {
686
+ if (doc === undefined) return { title: id, gist: id };
687
+ const firstLine = doc.body.split("\n").find((l) => l.trim().length > 0) ?? "";
688
+ const paragraph = doc.body.split(/\n\s*\n/).find((p) => p.trim().length > 0) ?? doc.body;
689
+ return { title: doc.title ?? firstLine, gist: paragraph, journal: doc.type === "episode" };
690
+ }
691
+
692
+ export type { Kind, CandidateVerdict, Verdict, Background, GateState, UseTier, CreditOutcome };