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,441 @@
1
+ /**
2
+ * The surfacing gate — the one place a candidate becomes an intrusion.
3
+ *
4
+ * The named deviation from the brain (constitution line 12, contract §2):
5
+ * **surfacing is judged relative to THIS TURN'S OWN BACKGROUND distribution**,
6
+ * not against an absolute threshold. *Where a design wants `if x > threshold`,
7
+ * suspect a flattened gradient.*
8
+ *
9
+ * Three hard gates salience cannot touch (§9 G7), checked in this order and no
10
+ * other — the order IS the guarantee:
11
+ *
12
+ * (a) **an uncued memory is dark**, whatever its salience: the salience
13
+ * arithmetic is never even evaluated;
14
+ * (b) an **absolute floor** is checked BEFORE any salience adjustment;
15
+ * (c) the loud tier requires a **minimum fraction of activation from cues**, so
16
+ * recency alone can never carry a memory there no matter how sacred it is.
17
+ *
18
+ * Two boundary gates sit in front of all three, and salience cannot touch them
19
+ * either: **confidentiality** (sensitive material returns only in the owner's own
20
+ * session, and an observer is a non-owner — observer-mode.md G7) and **session
21
+ * dedup** (this session already saw it).
22
+ *
23
+ * `protected` grants NO surfacing privilege. A protected memory is one revision
24
+ * may not overwrite; that is a write-side property and it buys nothing here.
25
+ *
26
+ * Every verdict names its REASON. A bare boolean cannot be told apart from a bug,
27
+ * and the per-turn decision record is the richest replay comparison surface
28
+ * (contract §5 G14, scar §2.4).
29
+ */
30
+ import { tokenize } from "../store/index.js";
31
+ import type { Candidate } from "./activate.js";
32
+ import { MIN_RARITY_STORE, informativeness } from "./cues.js";
33
+ import type { GateState } from "./session.js";
34
+ import { strongFloor } from "./tunables.js";
35
+ import type { RecallTunables } from "./tunables.js";
36
+
37
+ export type Verdict =
38
+ /** Admitted, loud tier: "came to mind". */
39
+ | "surfaced"
40
+ /** Admitted, quiet tier: "quietly available". */
41
+ | "footnoted"
42
+ /** Boundary: sensitive material, non-owner session. */
43
+ | "confidential-withheld"
44
+ /** Boundary: this session already saw it. */
45
+ | "dedup-suppressed"
46
+ /** Hard gate (a). */
47
+ | "dark-uncued"
48
+ /** Hard gate (b), evaluated before any salience adjustment. */
49
+ | "below-floor"
50
+ /** Below this turn's own background bar. */
51
+ | "below-bar"
52
+ /** Hard gate (c): too little of the activation came from cues. */
53
+ | "cue-fraction"
54
+ /** The per-candidate ceiling: the only cue was a remembered date, and a date
55
+ * may make a memory quietly available, never loud (prospective §12 G5). */
56
+ | "cue-only-temporal"
57
+ /** The store is smaller than `MIN_RARITY_STORE`, so the rarity channel cannot
58
+ * discriminate: every token in the only memory is maximally rare and a turn
59
+ * sharing nothing but function words scores like a turn that is about it.
60
+ * Arrival makes it warm; nothing at this size can make it loud. */
61
+ | "cold-start-undiscriminating"
62
+ /** Reached the bar, but not the loud tier's per-kind floor. */
63
+ | "below-strong-floor"
64
+ /** Lateral inhibition: a near-duplicate of a stronger admitted candidate. */
65
+ | "inhibited"
66
+ /** Admitted but past the tier cap. An empty slot stays quiet; a full one closes. */
67
+ | "capped";
68
+
69
+ export type Regime = "relative" | "absolute-cold-start" | "absolute-thin-background";
70
+
71
+ export interface CandidateVerdict {
72
+ readonly id: string;
73
+ readonly kind: string;
74
+ readonly verdict: Verdict;
75
+ readonly activation: number;
76
+ readonly cue: number;
77
+ /** The temporal portion of `cue` (already inside it) — SEAMS item D. */
78
+ readonly temporal: number;
79
+ readonly semantic: number;
80
+ readonly arrival: number;
81
+ /** Spreading activation (SEAMS item L) — in `activation`, not in cues. */
82
+ readonly hops: number;
83
+ readonly cueFraction: number;
84
+ readonly sal: number;
85
+ readonly strength: number;
86
+ /** False ⇒ this memory may never be credited from this turn (§9 G5). */
87
+ readonly trains: boolean;
88
+ /** The admission bar this candidate actually faced, after leave-one-out and
89
+ * salience modulation. Two candidates in one turn face different numbers; a
90
+ * single turn-level bar in the record would be a fiction. */
91
+ readonly bar: number;
92
+ /** For an admitted-but-quiet candidate: which loud-tier check stopped it.
93
+ * "The footnote tier is where the loud tier said no" is a question replay
94
+ * asks constantly; a bare tier label cannot answer it. */
95
+ readonly loudBlockedBy?: Verdict;
96
+ }
97
+
98
+ export interface Background {
99
+ readonly regime: Regime;
100
+ readonly n: number;
101
+ /** Whole-sample statistics — the turn-level summary the decision record
102
+ * reports. The bar each candidate FACES is leave-one-out (see `barsFor`). */
103
+ readonly mean: number;
104
+ readonly sd: number;
105
+ /** Whole-sample admission bar, before leave-one-out and salience. Reported for
106
+ * replay comparison; not the number any candidate is judged against in the
107
+ * relative regime. */
108
+ readonly bar: number;
109
+ readonly strongBar: number;
110
+ readonly floor: number;
111
+ }
112
+
113
+ export interface GateInput {
114
+ readonly candidates: readonly Candidate[];
115
+ readonly state: GateState;
116
+ readonly storeSize: number;
117
+ readonly owner: boolean;
118
+ /** The turn stated a feeling (any subject) — the affect flag's turn gate. */
119
+ readonly affectStated: boolean;
120
+ readonly turn: number;
121
+ }
122
+
123
+ export interface GateResult {
124
+ readonly background: Background;
125
+ readonly verdicts: CandidateVerdict[];
126
+ readonly surfaced: Candidate[];
127
+ readonly footnotes: Candidate[];
128
+ /** One content-free line: no ids, no bodies, no feeling named. */
129
+ readonly affectFlag: boolean;
130
+ readonly affectReason: "fired" | "no-feeling-in-turn" | "refractory" | "nothing-charged";
131
+ }
132
+
133
+ /** Jaccard over indexed tokens — the similarity the cache itself would compute. */
134
+ export function similarity(a: Candidate, b: Candidate): number {
135
+ const sa = new Set(tokenize(`${a.doc.title ?? ""}\n${a.doc.body}`));
136
+ const sb = new Set(tokenize(`${b.doc.title ?? ""}\n${b.doc.body}`));
137
+ if (sa.size === 0 || sb.size === 0) return 0;
138
+ let inter = 0;
139
+ for (const tok of sa) if (sb.has(tok)) inter += 1;
140
+ return inter / (sa.size + sb.size - inter);
141
+ }
142
+
143
+ /**
144
+ * **The unit the absolute floors are denominated in: ONE MAXIMALLY-RARE CUE.**
145
+ *
146
+ * `informativeness(1, storeSize)` is the weight a cue matching exactly one
147
+ * memory carries — the largest rarity weight the model can produce, and the
148
+ * model's own natural unit. A floor of `2.0` therefore means the same sentence
149
+ * at every scale: *a candidate needs two maximally-rare cues' worth of evidence
150
+ * before it may be admitted.*
151
+ *
152
+ * Why a unit at all (scar §2.8, CONTRACT §7 OQ5). v1's activation was a
153
+ * normalized cosine in 0-1 and its floors were absolute numbers in that space.
154
+ * v2's is a SUM of `idf × length-normalized evidence`, so the same numeral means
155
+ * "everything passes" on a 15,000-memory store (where `informativeness(1, N)` is
156
+ * 8.9) and "nothing passes" on a seventeen-memory one (where it is 2.2). The
157
+ * floors were consequently decorative — MEASURED 2026-09-04: scaling them ×1 to
158
+ * ×15 changed not one delivered item on `tools/recall-bench` — and the loud tier
159
+ * fired on 13 of 13 real turns because only the RELATIVE bar was gating it, and
160
+ * a relative bar cannot keep a low-evidence turn quiet (a thin turn's top
161
+ * candidate stands FURTHER above its own thin background, not nearer).
162
+ *
163
+ * This is ACT-R's retrieval threshold τ, restored to the model's own units: below
164
+ * τ a chunk is not retrieved however distinctive it looks against its neighbours.
165
+ * The relative bar (contract §2's named deviation) is unchanged and still does
166
+ * the discriminating; the floor only says how weak is too weak to be worth
167
+ * anyone's attention.
168
+ *
169
+ * The one thing that made this possible is not in this file: rarity had to be
170
+ * MEASURED before it could be a unit. `activate.ts` was reading document
171
+ * frequency off the length of a bounded top-K, so on a large store every common
172
+ * word looked rare and every turn's activation was inflated by roughly the same
173
+ * amount its rare words were (`store/cache.ts#docFrequency`).
174
+ */
175
+ export function floorUnit(storeSize: number): number {
176
+ return informativeness(1, storeSize);
177
+ }
178
+
179
+ /**
180
+ * The background statistic stays GLOBAL across kinds — v1 measured per-kind
181
+ * backgrounds to rescue nothing — and so, as of 2026-09-04, is the loud-tier
182
+ * FLOOR: see `tunables.ts#FLOOR_STRONG_BY_KIND_UNITS` for the measurement that
183
+ * retired v1's per-kind shape without retiring the mechanism (§9 G12).
184
+ *
185
+ * Two degeneracies force the absolute regime, and naming them is the point:
186
+ * a store too small for the variance estimate to mean anything (cold start —
187
+ * *small stores over-surface*, so cold start is STRICTER, not looser), and a
188
+ * background too thin to be a distribution at all, where `mean + k·sd` collapses
189
+ * to the lone candidate's own activation and nothing could ever clear its own bar.
190
+ */
191
+ export function background(
192
+ activations: readonly number[],
193
+ storeSize: number,
194
+ t: RecallTunables,
195
+ ): Background {
196
+ const n = activations.length;
197
+ const mean = n === 0 ? 0 : activations.reduce((a, b) => a + b, 0) / n;
198
+ const varSum = activations.reduce((acc, x) => acc + (x - mean) * (x - mean), 0);
199
+ const sd = n === 0 ? 0 : Math.sqrt(varSum / n);
200
+ const unit = floorUnit(storeSize);
201
+
202
+ if (storeSize < t.COLD_START_MIN_STORE) {
203
+ const cold = t.COLD_START_FLOOR_UNITS * unit;
204
+ return {
205
+ regime: "absolute-cold-start",
206
+ n,
207
+ mean,
208
+ sd,
209
+ bar: cold,
210
+ strongBar: cold,
211
+ floor: cold,
212
+ };
213
+ }
214
+ const floor = t.FLOOR_GLOBAL_UNITS * unit;
215
+ if (n < t.MIN_BACKGROUND_SAMPLE || sd === 0) {
216
+ return {
217
+ regime: "absolute-thin-background",
218
+ n,
219
+ mean,
220
+ sd,
221
+ bar: floor,
222
+ strongBar: floor,
223
+ floor,
224
+ };
225
+ }
226
+ return {
227
+ regime: "relative",
228
+ n,
229
+ mean,
230
+ sd,
231
+ bar: mean + t.SNR_GLOBAL * sd,
232
+ strongBar: mean + t.SNR_STRONG * sd,
233
+ floor,
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Two-sided salience modulation of the RELATIVE bar only. Salience lowers the bar
239
+ * for what already passed relevance and raises it for what barely registers; it
240
+ * never bypasses relevance and it never touches the absolute regimes, whose whole
241
+ * purpose is to be un-negotiable.
242
+ */
243
+ function modulate(bar: number, sal: number, regime: Regime, t: RecallTunables): number {
244
+ if (regime !== "relative") return bar;
245
+ return bar * (1 - t.SAL_BAR_WEIGHT * (2 * sal - 1));
246
+ }
247
+
248
+ /**
249
+ * The bar one candidate faces, computed LEAVE-ONE-OUT: the background is the
250
+ * turn's OTHER activations, never the candidate's own.
251
+ *
252
+ * This is a correction v1's shape invites and does not make. Including the
253
+ * candidate in its own background means the strongest hit drags `mean + k·sd` up
254
+ * by roughly the amount it stands out — so a lone, perfectly-cued memory is
255
+ * measured against itself and can never clear its own bar. "Relative to this
256
+ * turn's background" only means anything if the candidate is not the background.
257
+ */
258
+ export function looBar(
259
+ activation: number,
260
+ sum: number,
261
+ sumSq: number,
262
+ n: number,
263
+ snr: number,
264
+ ): number {
265
+ const m = n - 1;
266
+ if (m <= 0) return activation;
267
+ const mean = (sum - activation) / m;
268
+ const variance = Math.max(0, (sumSq - activation * activation) / m - mean * mean);
269
+ return mean + snr * Math.sqrt(variance);
270
+ }
271
+
272
+ export function gate(input: GateInput, t: RecallTunables): GateResult {
273
+ const acts = input.candidates.filter((c) => c.cue + c.semantic > 0).map((c) => c.activation);
274
+ const bg = background(acts, input.storeSize, t);
275
+ /** The loud-tier floors are in the same unit as hard gate (b)'s (`floorUnit`). */
276
+ const loudUnit = floorUnit(input.storeSize);
277
+ const sum = acts.reduce((a, b) => a + b, 0);
278
+ const sumSq = acts.reduce((a, b) => a + b * b, 0);
279
+ const n = acts.length;
280
+ const barsFor = (c: Candidate): { admit: number; loud: number } =>
281
+ bg.regime === "relative"
282
+ ? {
283
+ admit: modulate(looBar(c.activation, sum, sumSq, n, t.SNR_GLOBAL), c.sal, bg.regime, t),
284
+ loud: modulate(looBar(c.activation, sum, sumSq, n, t.SNR_STRONG), c.sal, bg.regime, t),
285
+ }
286
+ : { admit: bg.bar, loud: bg.strongBar };
287
+
288
+ const verdicts: CandidateVerdict[] = [];
289
+ const admitted: { c: Candidate; loud: boolean }[] = [];
290
+ const loudBlock = new Map<string, Verdict>();
291
+ const faced = new Map<string, number>();
292
+ const record = (c: Candidate, verdict: Verdict): void => {
293
+ const blocked = loudBlock.get(c.id);
294
+ verdicts.push({
295
+ bar: faced.get(c.id) ?? bg.bar,
296
+ id: c.id,
297
+ kind: c.kind,
298
+ verdict,
299
+ activation: c.activation,
300
+ cue: c.cue,
301
+ temporal: c.temporal,
302
+ semantic: c.semantic,
303
+ arrival: c.arrival,
304
+ hops: c.hops,
305
+ cueFraction: c.cueFraction,
306
+ sal: c.sal,
307
+ strength: c.strength,
308
+ trains: c.trains,
309
+ ...(blocked !== undefined ? { loudBlockedBy: blocked } : {}),
310
+ });
311
+ };
312
+
313
+ /** Charged candidates feed the affect flag even when they never surface —
314
+ * a content-free line leaks nothing, and that is what makes it the cheapest
315
+ * tier. */
316
+ let charged = false;
317
+
318
+ for (const c of input.candidates) {
319
+ // Boundary gate 1 — confidentiality. Silent in a list (§9.1 G5); the
320
+ // decision record still counts it, so withholding is measurable.
321
+ if (c.confidential && !input.owner) {
322
+ record(c, "confidential-withheld");
323
+ continue;
324
+ }
325
+ // Hard gate (a) — uncued is dark. Salience is never evaluated below here
326
+ // for such a candidate, which is the guarantee, not an optimization.
327
+ if (c.cue + c.semantic <= 0) {
328
+ record(c, "dark-uncued");
329
+ continue;
330
+ }
331
+ // The affect flag is charged BEFORE dedup, deliberately: the flag is about
332
+ // what THIS TURN touches, and it names nothing — no id, no body, no feeling.
333
+ // A memory already sitting in this session's context still means the turn is
334
+ // near something that carries weight.
335
+ if (c.physics.salience.emotional >= t.AFFECT_MIN_EMOTION) charged = true;
336
+ // Boundary gate 2 — session dedup. It is already in this session's context.
337
+ if (input.state.surfaced[c.id] !== undefined) {
338
+ record(c, "dedup-suppressed");
339
+ continue;
340
+ }
341
+ // Hard gate (b) — the absolute floor, BEFORE any salience adjustment.
342
+ if (c.activation < bg.floor) {
343
+ record(c, "below-floor");
344
+ continue;
345
+ }
346
+ const bars = barsFor(c);
347
+ faced.set(c.id, bars.admit);
348
+ if (c.activation < bars.admit) {
349
+ record(c, "below-bar");
350
+ continue;
351
+ }
352
+ // Loud-tier eligibility. Hard gate (c) first: arrival makes a memory warm,
353
+ // only relevance makes it loud.
354
+ let loud = true;
355
+ // The per-candidate ceiling is checked FIRST among the loud-tier rules, so a
356
+ // capped candidate's record NAMES the cap rather than whichever other rule
357
+ // happened to fire second.
358
+ if (c.maxTier === "footnoted") {
359
+ loud = false;
360
+ loudBlock.set(c.id, "cue-only-temporal");
361
+ } else if (input.storeSize < MIN_RARITY_STORE) {
362
+ // Cold start is STRICTER, not looser — and below `MIN_RARITY_STORE` the
363
+ // strictness the floors provide is not available, because the unit the
364
+ // floors are denominated in is itself the thing that has stopped
365
+ // discriminating. On a one-memory store every token the memory holds is
366
+ // maximally rare (`cues.ts#MIN_RARITY_STORE`), so an ordinary note and a
367
+ // turn sharing only `the`/`that`/`and`/`not` reach the loud tier:
368
+ // MEASURED 2026-09-04, a three-sentence note against five unrelated
369
+ // turns went `surfaced` on all five at activation 1.82-2.24 against a
370
+ // loud floor of 4.5 x 0.4055 = 1.8246. The same five turns at N=2
371
+ // footnote at 0.36-0.62. So the tier is capped rather than the floor
372
+ // retuned: arrival makes a memory warm, only relevance makes it loud,
373
+ // and at this size there is no relevance to measure.
374
+ loud = false;
375
+ loudBlock.set(c.id, "cold-start-undiscriminating");
376
+ } else if (c.cueFraction < t.MIN_CUE_FRACTION) {
377
+ loud = false;
378
+ loudBlock.set(c.id, "cue-fraction");
379
+ } else if (c.activation < strongFloor(t, c.kind, loudUnit)) {
380
+ loud = false;
381
+ loudBlock.set(c.id, "below-strong-floor");
382
+ } else if (c.activation < bars.loud) {
383
+ loud = false;
384
+ loudBlock.set(c.id, "below-bar");
385
+ }
386
+ admitted.push({ c, loud });
387
+ }
388
+
389
+ // ── lateral inhibition on PURE activation (§9 G8: admission, inhibition and
390
+ // the footnote tier never see salience — that is what keeps the footnote tier
391
+ // a recency DISCOVERY channel rather than a second salience ranking).
392
+ admitted.sort((a, b) => b.c.activation - a.c.activation || (a.c.id < b.c.id ? -1 : 1));
393
+ const kept: { c: Candidate; loud: boolean }[] = [];
394
+ for (const a of admitted) {
395
+ const dup = kept.some((k) => similarity(k.c, a.c) >= t.NEAR_DUPLICATE);
396
+ if (dup) {
397
+ record(a.c, "inhibited");
398
+ continue;
399
+ }
400
+ kept.push(a);
401
+ }
402
+
403
+ // ── tiers: disjoint by construction, and capped ─────────────────────────
404
+ const loudPool = kept.filter((k) => k.loud);
405
+ loudPool.sort(
406
+ (a, b) =>
407
+ b.c.activation + t.SAL_SORT_WEIGHT * b.c.sal - (a.c.activation + t.SAL_SORT_WEIGHT * a.c.sal) ||
408
+ (a.c.id < b.c.id ? -1 : 1),
409
+ );
410
+ const surfaced = loudPool.slice(0, t.MAX_SURFACED).map((k) => k.c);
411
+ const surfacedIds = new Set(surfaced.map((c) => c.id));
412
+
413
+ const footnotePool = kept.filter((k) => !surfacedIds.has(k.c.id));
414
+ const footnotes = footnotePool.slice(0, t.MAX_FOOTNOTES).map((k) => k.c);
415
+ const footnoteIds = new Set(footnotes.map((c) => c.id));
416
+
417
+ for (const c of surfaced) record(c, "surfaced");
418
+ for (const c of footnotes) record(c, "footnoted");
419
+ for (const k of kept) {
420
+ if (!surfacedIds.has(k.c.id) && !footnoteIds.has(k.c.id)) record(k.c, "capped");
421
+ }
422
+
423
+ // ── the affect flag: turn-gated, then refractory-gated ──────────────────
424
+ let affectFlag = false;
425
+ let affectReason: GateResult["affectReason"] = "nothing-charged";
426
+ if (!input.affectStated) {
427
+ affectReason = "no-feeling-in-turn";
428
+ } else if (!charged) {
429
+ affectReason = "nothing-charged";
430
+ } else if (
431
+ input.state.affectFiredTurn !== null &&
432
+ input.turn - input.state.affectFiredTurn < t.AFFECT_REFRACTORY_TURNS
433
+ ) {
434
+ affectReason = "refractory";
435
+ } else {
436
+ affectFlag = true;
437
+ affectReason = "fired";
438
+ }
439
+
440
+ return { background: bg, verdicts, surfaced, footnotes, affectFlag, affectReason };
441
+ }