@hviana/sema 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 (110) hide show
  1. package/AGENTS.md +470 -0
  2. package/AUTHORS.md +12 -0
  3. package/COMMERCIAL-LICENSE.md +19 -0
  4. package/CONTRIBUTING.md +15 -0
  5. package/HOW_IT_WORKS.md +4210 -0
  6. package/LICENSE.md +117 -0
  7. package/README.md +290 -0
  8. package/TRADEMARKS.md +19 -0
  9. package/example/demo.ts +46 -0
  10. package/example/train_base.ts +2675 -0
  11. package/index.html +893 -0
  12. package/package.json +25 -0
  13. package/src/alphabet.ts +34 -0
  14. package/src/alu/README.md +332 -0
  15. package/src/alu/src/alu.ts +541 -0
  16. package/src/alu/src/expr.ts +339 -0
  17. package/src/alu/src/index.ts +115 -0
  18. package/src/alu/src/kernel-arith.ts +377 -0
  19. package/src/alu/src/kernel-bits.ts +199 -0
  20. package/src/alu/src/kernel-logic.ts +102 -0
  21. package/src/alu/src/kernel-nd.ts +235 -0
  22. package/src/alu/src/kernel-numeric.ts +466 -0
  23. package/src/alu/src/operation.ts +344 -0
  24. package/src/alu/src/parser.ts +574 -0
  25. package/src/alu/src/resonance.ts +161 -0
  26. package/src/alu/src/text.ts +83 -0
  27. package/src/alu/src/value.ts +327 -0
  28. package/src/alu/test/alu.test.ts +1004 -0
  29. package/src/bytes.ts +62 -0
  30. package/src/config.ts +227 -0
  31. package/src/derive/README.md +295 -0
  32. package/src/derive/src/deduction.ts +263 -0
  33. package/src/derive/src/index.ts +24 -0
  34. package/src/derive/src/priority-queue.ts +70 -0
  35. package/src/derive/src/rewrite.ts +127 -0
  36. package/src/derive/src/trie.ts +242 -0
  37. package/src/derive/test/derive.test.ts +137 -0
  38. package/src/extension.ts +42 -0
  39. package/src/geometry.ts +511 -0
  40. package/src/index.ts +38 -0
  41. package/src/ingest-cache.ts +224 -0
  42. package/src/mind/articulation.ts +137 -0
  43. package/src/mind/attention.ts +1061 -0
  44. package/src/mind/canonical.ts +107 -0
  45. package/src/mind/graph-search.ts +1100 -0
  46. package/src/mind/index.ts +18 -0
  47. package/src/mind/junction.ts +347 -0
  48. package/src/mind/learning.ts +246 -0
  49. package/src/mind/match.ts +507 -0
  50. package/src/mind/mechanisms/alu.ts +33 -0
  51. package/src/mind/mechanisms/cast.ts +568 -0
  52. package/src/mind/mechanisms/confluence.ts +268 -0
  53. package/src/mind/mechanisms/cover.ts +248 -0
  54. package/src/mind/mechanisms/extraction.ts +422 -0
  55. package/src/mind/mechanisms/recall.ts +241 -0
  56. package/src/mind/mind.ts +483 -0
  57. package/src/mind/pipeline-mechanism.ts +326 -0
  58. package/src/mind/pipeline.ts +300 -0
  59. package/src/mind/primitives.ts +201 -0
  60. package/src/mind/rationale.ts +275 -0
  61. package/src/mind/reasoning.ts +198 -0
  62. package/src/mind/recognition.ts +234 -0
  63. package/src/mind/resonance.ts +0 -0
  64. package/src/mind/trace.ts +108 -0
  65. package/src/mind/traverse.ts +556 -0
  66. package/src/mind/types.ts +281 -0
  67. package/src/rabitq-hnsw/README.md +303 -0
  68. package/src/rabitq-hnsw/src/database.ts +492 -0
  69. package/src/rabitq-hnsw/src/heap.ts +90 -0
  70. package/src/rabitq-hnsw/src/hnsw.ts +514 -0
  71. package/src/rabitq-hnsw/src/index.ts +15 -0
  72. package/src/rabitq-hnsw/src/prng.ts +39 -0
  73. package/src/rabitq-hnsw/src/rabitq.ts +308 -0
  74. package/src/rabitq-hnsw/src/store.ts +994 -0
  75. package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
  76. package/src/store-sqlite.ts +928 -0
  77. package/src/store.ts +2148 -0
  78. package/src/vec.ts +124 -0
  79. package/test/00-extract.test.mjs +151 -0
  80. package/test/01-floor.test.mjs +20 -0
  81. package/test/02-roundtrip.test.mjs +83 -0
  82. package/test/03-recall.test.mjs +98 -0
  83. package/test/04-think.test.mjs +627 -0
  84. package/test/05-concepts.test.mjs +84 -0
  85. package/test/08-storage.test.mjs +948 -0
  86. package/test/09-edges.test.mjs +65 -0
  87. package/test/11-universality.test.mjs +180 -0
  88. package/test/13-conversation.test.mjs +228 -0
  89. package/test/14-scaling.test.mjs +503 -0
  90. package/test/15-decomposition-gap.test.mjs +0 -0
  91. package/test/16-bridge.test.mjs +250 -0
  92. package/test/17-intelligence.test.mjs +240 -0
  93. package/test/18-alu.test.mjs +209 -0
  94. package/test/19-nd.test.mjs +254 -0
  95. package/test/20-stability.test.mjs +489 -0
  96. package/test/21-partial.test.mjs +158 -0
  97. package/test/22-multihop.test.mjs +130 -0
  98. package/test/23-rationale.test.mjs +316 -0
  99. package/test/24-generalization.test.mjs +416 -0
  100. package/test/25-embedding.test.mjs +75 -0
  101. package/test/26-cooperative.test.mjs +89 -0
  102. package/test/27-saturation-drop.test.mjs +637 -0
  103. package/test/28-unknowable.test.mjs +88 -0
  104. package/test/29-counterfactual.test.mjs +476 -0
  105. package/test/30-conflict-resolution.test.mjs +166 -0
  106. package/test/31-audit.test.mjs +288 -0
  107. package/test/32-confluence.test.mjs +173 -0
  108. package/test/33-multi-candidate.test.mjs +222 -0
  109. package/test/34-cross-region.test.mjs +252 -0
  110. package/tsconfig.json +16 -0
@@ -0,0 +1,1061 @@
1
+ // attention.ts — Consensus climb / attention pipeline (Section 4 of the mind).
2
+ //
3
+ // Every region of the query's perceived tree casts a resonance vote for the
4
+ // context (learnt fact) it best climbs to. Votes are pooled through the very
5
+ // deduction engine (lightestDerivation) that GraphSearch covers with — so a
6
+ // pooled-evidence decision is one weighted rule of the SAME deduction system,
7
+ // not a hand-rolled tally. The result is one or more independent points of
8
+ // attention for the rest of the pipeline to follow.
9
+
10
+ import { isChunk } from "../sema.js";
11
+ import type { Hit } from "../store.js";
12
+ import {
13
+ type DeductionSystem,
14
+ lightestDerivation,
15
+ type PooledConclusion,
16
+ } from "../derive/src/index.js";
17
+ import type { DerivationItem, DerivationStep } from "./graph-search.js";
18
+ import type {
19
+ AItem,
20
+ AncestorReach,
21
+ Attention,
22
+ AttentionRead,
23
+ DFMode,
24
+ MindContext,
25
+ Region,
26
+ RegionVote,
27
+ SaturationInfo,
28
+ } from "./types.js";
29
+ import { consensusFloor, dominates, estimatorNoise } from "../geometry.js";
30
+ import { foldTree, gistOf, perceive, read } from "./primitives.js";
31
+ import { recognise } from "./recognition.js";
32
+ import { leafIdRun } from "./canonical.js";
33
+ import { corpusN, edgeAncestors } from "./traverse.js";
34
+ import {
35
+ cachedRead,
36
+ junctionContainersFrom,
37
+ junctionSeeds,
38
+ junctionSynonyms,
39
+ walkCache,
40
+ } from "./junction.js";
41
+ import { indexOf } from "../bytes.js";
42
+ import type { RationaleItem } from "./rationale.js";
43
+ import { rDeriv, rItem, rNode, traceDerivation } from "./trace.js";
44
+
45
+ // ── Public entry points ───────────────────────────────────────────────────
46
+
47
+ /** Climb the query's perceived byte regions up the structural DAG via
48
+ * resonance, pool the evidence, and return only the ROOT points of
49
+ * attention — those that cleared commitVotes' significance floor. */
50
+ export async function climbAttention(
51
+ ctx: MindContext,
52
+ query: Uint8Array,
53
+ k: number,
54
+ mode: DFMode = "inverse",
55
+ ): Promise<Attention[]> {
56
+ return (await climbAttentionAll(ctx, query, k, mode)).roots;
57
+ }
58
+
59
+ /** Full read-out of one consensus climb: both the roots (dominant points of
60
+ * attention) and the entire ranked list. Cached via ctx.climbMemo when
61
+ * ctx.trace is null. */
62
+ export async function climbAttentionAll(
63
+ ctx: MindContext,
64
+ query: Uint8Array,
65
+ k: number,
66
+ mode: DFMode = "inverse",
67
+ ): Promise<AttentionRead> {
68
+ if (ctx.climbMemo && !ctx.trace) {
69
+ const key = `${k}:${mode}`;
70
+ let byRead = ctx.climbMemo.get(query);
71
+ if (byRead === undefined) ctx.climbMemo.set(query, byRead = new Map());
72
+ const hit = byRead.get(key);
73
+ if (hit !== undefined) return hit;
74
+ const read = await computeAttention(ctx, query, k, mode);
75
+ byRead.set(key, read);
76
+ return read;
77
+ }
78
+ return computeAttention(ctx, query, k, mode);
79
+ }
80
+
81
+ // ── Pipeline ──────────────────────────────────────────────────────────────
82
+
83
+ export async function computeAttention(
84
+ ctx: MindContext,
85
+ query: Uint8Array,
86
+ k: number,
87
+ mode: DFMode,
88
+ ): Promise<AttentionRead> {
89
+ const regions = collectRegions(ctx, query);
90
+
91
+ // Recognised sites carry structural evidence that perceived sub-regions
92
+ // miss: a word crossing a W-boundary is split into chunks whose partial
93
+ // gists may not resonate distinctively, but the SITE (content-addressed,
94
+ // exact) names the whole form. Adding sites as climb regions lets the
95
+ // consensus vote with the full word, at zero cost — recognition is already
96
+ // memoised per response (ctx.recogniseMemo), and gistOf for short sites is
97
+ // O(|span|·D). Sites that overlap perceived regions add corroborating
98
+ // evidence; sites in gaps (like cross-boundary words) fill them.
99
+ const rec = recognise(ctx, query);
100
+ for (const s of rec.sites) {
101
+ regions.push({
102
+ v: gistOf(ctx, query.subarray(s.start, s.end)),
103
+ start: s.start,
104
+ end: s.end,
105
+ chunk: false,
106
+ known: true, // a recognised site IS a stored form
107
+ });
108
+ }
109
+
110
+ if (regions.length === 0) return { roots: [], ranked: [] };
111
+
112
+ const N = corpusN(ctx);
113
+ // One climb per distinct anchor for the WHOLE query: regions sharing a
114
+ // chunk, and canonicalChunkId's prefix probes, all hit this memo instead of
115
+ // re-reading the anchor's full edge fan-out from the store.
116
+ const reachMemo = new Map<number, AncestorReach>();
117
+ const rvs = await voteRegions(ctx, query, regions, k, mode, N, reachMemo);
118
+
119
+ // ── Cross-region: DIRECT region-to-region interaction ─────────────────
120
+ // Two regions whose individual climbs land on DIFFERENT contexts leave
121
+ // their JOINT context — the learnt whole that contains BOTH — with no
122
+ // vote. crossRegionVotes recovers it by the bridge's content-addressed
123
+ // junction ascent (see the note above the function).
124
+ const cross = await crossRegionVotes(
125
+ ctx,
126
+ query,
127
+ regions,
128
+ rvs,
129
+ k,
130
+ N,
131
+ reachMemo,
132
+ );
133
+ // A vote SUPERSEDED by exact joint evidence (its bytes literally live
134
+ // inside the joint container, yet it climbed elsewhere — grid aliasing)
135
+ // is dropped, not down-weighted: the joint container explains it away.
136
+ const allVotes = cross.votes.length > 0
137
+ ? [
138
+ ...rvs.votes.filter((v) => !cross.superseded.has(v)),
139
+ ...cross.votes,
140
+ ]
141
+ : rvs.votes;
142
+ // ──────────────────────────────────────────────────────────────────────
143
+
144
+ if (allVotes.length === 0) {
145
+ traceAttention(ctx, regions, rvs.voters, []);
146
+ return { roots: [], ranked: [] };
147
+ }
148
+
149
+ const sat = detectSaturated(ctx, regions, rvs.saturated);
150
+ const pooled = poolVotes(ctx, allVotes, sat, N);
151
+ return commitVotes(ctx, pooled, sat, regions, rvs.voters, N);
152
+ }
153
+
154
+ export function collectRegions(ctx: MindContext, query: Uint8Array): Region[] {
155
+ const regions: Region[] = [];
156
+ // A region that DOMINATES the query (covers more than half — the shared
157
+ // {@link dominates} test liftAnswer uses for a span that swallows its
158
+ // surroundings) can never itself discriminate between several topics the
159
+ // query weaves; voting with it only when it is the sole structure (no
160
+ // narrower region exists) keeps a flat/short query's single point of
161
+ // attention intact without letting a broad, non-discriminative wrapper
162
+ // dilute a multi-topic query's vote or masquerade as a genuine second
163
+ // point of attention.
164
+ // foldTree (not walkTree): the same post-order walk, but each node also
165
+ // resolves content-addressed against the store — `known` is what lets the
166
+ // climb keep exact evidence at full weight while margin-damping the
167
+ // approximate kind (see voteRegions). One findLeaf/findBranch per tree
168
+ // node, the same lookups a deposit pays.
169
+ foldTree(ctx, perceive(ctx, query), 0, (n, start, end, node) => {
170
+ if (n.kids === null) return;
171
+ if (!dominates(end - start, query.length) || regions.length === 0) {
172
+ regions.push({
173
+ v: n.v,
174
+ start,
175
+ end,
176
+ chunk: isChunk(n),
177
+ known: node !== null,
178
+ });
179
+ }
180
+ });
181
+ return regions;
182
+ }
183
+
184
+ export async function voteRegions(
185
+ ctx: MindContext,
186
+ query: Uint8Array,
187
+ regions: readonly Region[],
188
+ k: number,
189
+ mode: DFMode,
190
+ N: number,
191
+ reachMemo?: Map<number, AncestorReach>,
192
+ ): Promise<{
193
+ votes: RegionVote[];
194
+ saturated: boolean[];
195
+ voters: Array<{ id: number; score: number; w: number } | null>;
196
+ }> {
197
+ const regionSaturated: boolean[] = new Array(regions.length).fill(false);
198
+ const regionVotes: RegionVote[] = [];
199
+ const regionVoter: Array<{ id: number; score: number; w: number } | null> =
200
+ ctx.trace ? regions.map(() => null) : [];
201
+
202
+ for (let ri = 0; ri < regions.length; ri++) {
203
+ const { v, start, end, chunk, known } = regions[ri];
204
+
205
+ // EXACT-FIRST: a chunk whose canonical anchor is content-addressed needs
206
+ // no estimator — identity is exact, so its score is 1 BY DEFINITION (the
207
+ // estimated cosine of a form with itself, minus quantisation noise, and
208
+ // the caveat atop geometry.ts forbids trusting the estimate over the
209
+ // exact resolution anyway). The ANN query is deferred behind
210
+ // `ensureHits` and paid only when actually consulted: the orphan
211
+ // fallback, the contrastive margin (approximate regions only), or a
212
+ // region with no usable canonical. On chunk-heavy queries this removes
213
+ // the resonate() call for most exact regions — the single largest
214
+ // remaining inference sink — with the anchor choice unchanged (the
215
+ // canonical branch already ignored hits[0]).
216
+ const canonicalId = chunk
217
+ ? canonicalChunkId(ctx, query.subarray(start, end), N, reachMemo)
218
+ : null;
219
+ const canonicalUsable = canonicalId !== null &&
220
+ (ctx.store.hasParents(canonicalId) ||
221
+ ctx.store.hasContainers(canonicalId));
222
+ let hits: readonly Hit[] | null = null;
223
+ const ensureHits = async (): Promise<readonly Hit[]> =>
224
+ hits ??= await ctx.store.resonate(v, k);
225
+
226
+ const canonicalFailed = chunk && canonicalId === null;
227
+ let voterId: number;
228
+ let score: number;
229
+ let scoreId: number; // the node the score was measured against
230
+ if (canonicalUsable) {
231
+ voterId = canonicalId!;
232
+ score = 1;
233
+ scoreId = canonicalId!;
234
+ } else {
235
+ const h = await ensureHits();
236
+ if (h.length === 0) continue;
237
+ voterId = h[0].id;
238
+ score = h[0].score;
239
+ scoreId = h[0].id;
240
+ }
241
+
242
+ let reach = edgeAncestors(ctx, voterId, N, reachMemo);
243
+ // A region's vote must not die with the TOP hit: `hits[1..k]` were
244
+ // already fetched, and the top-ranked anchor being a structural orphan
245
+ // (no edge-bearing ancestors) is an accident of the approximate ranking,
246
+ // not evidence the region relates to nothing. Walk the remaining hits —
247
+ // nearest first, climbs memoised — until one climbs. A SATURATED reach
248
+ // is not an orphan: it is a deliberate abstention, kept as-is.
249
+ if (reach.roots.length === 0 && !reach.saturated) {
250
+ for (const h of await ensureHits()) {
251
+ if (h.id === voterId) continue;
252
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
253
+ if (r2.saturated || r2.roots.length > 0) {
254
+ ctx.trace?.step(
255
+ "anchorFallback",
256
+ [rNode(ctx, voterId, "orphan-anchor", score)],
257
+ [rNode(ctx, h.id, "anchor", h.score)],
258
+ "the top-ranked anchor climbs to no context — a lower-ranked hit votes instead",
259
+ );
260
+ reach = r2;
261
+ voterId = h.id;
262
+ score = h.score;
263
+ scoreId = h.id;
264
+ break;
265
+ }
266
+ }
267
+ } else if (!canonicalUsable && reach.saturated) {
268
+ // TIE-BAND saturation fallback. A saturated top hit abstains the whole
269
+ // region (a hub's reach concludes nothing) — but the hub may only CLAIM
270
+ // that abstention when it is DISTINGUISHABLY the nearest anchor. The
271
+ // resonance ranking is an estimate: the difference between two scores
272
+ // against the same query carries √2× the estimator's per-score error,
273
+ // ≈ 1/√D ({@link estimatorNoise}) — so any hit within that band of the
274
+ // top is the SAME rank at measurement resolution, and letting the hub
275
+ // win the tie decides the region by quantisation accident (observed:
276
+ // a 0.1σ rank inversion flipped a pinned behaviour when the query
277
+ // estimator sharpened from 4 to 8 bits). Walk the tied hits, nearest
278
+ // first; the first that climbs somewhere non-saturated votes for the
279
+ // region. Beyond the band the hub is genuinely nearest and its
280
+ // abstention stands. A KNOWN (content-addressed) region never enters:
281
+ // its anchor is exact, not an estimate.
282
+ const band = estimatorNoise(ctx.store.D);
283
+ for (const h of await ensureHits()) {
284
+ if (h.id === voterId) continue;
285
+ if (h.score < score - band) break; // hits are nearest-first
286
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
287
+ if (!r2.saturated && r2.roots.length > 0) {
288
+ ctx.trace?.step(
289
+ "anchorFallback",
290
+ [rNode(ctx, voterId, "saturated-anchor", score)],
291
+ [rNode(ctx, h.id, "anchor", h.score)],
292
+ "the top-ranked anchor is a saturated hub tied within estimator noise — the tied hit votes instead",
293
+ );
294
+ reach = r2;
295
+ voterId = h.id;
296
+ score = h.score;
297
+ scoreId = h.id;
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ regionSaturated[ri] = reach.saturated;
303
+ if (reach.roots.length === 0) continue;
304
+ if (reach.saturated) continue;
305
+
306
+ // One IDF per region — dfWeight() and the focus weight used to compute
307
+ // the same logarithm independently.
308
+ const idf = Math.log(N / Math.max(1, reach.contextsReached));
309
+ const df = Math.log(1 + reach.contextsReached);
310
+ const wf = mode === "direct" ? df : mode === "combined" ? idf + df : idf;
311
+ if (wf <= 0) continue;
312
+
313
+ // CONTRASTIVE-MARGIN GATE — the compensation the linear (byte-proportional)
314
+ // fold demands, applied to APPROXIMATE evidence only. Under the linear
315
+ // fold a resonance score reads "fraction of aligned shared bytes", so a
316
+ // NOVEL span sharing a frame with several stored exemplars scores high
317
+ // against each of them without being evidence of ANY of them: the shared
318
+ // scaffolding, not the span's own content, carries the similarity. Such a
319
+ // frame region resonates ~equally to every framed exemplar, so its top hit
320
+ // barely beats the best DIFFERENT-conclusion rival (a different climb
321
+ // root-set) — its discriminative margin, score MINUS that rival, collapses
322
+ // toward zero. A region votes only when that margin clears the estimator's
323
+ // own noise floor (1/√D — see {@link estimatorNoise}); below it the margin
324
+ // is quantisation noise, not evidence. A KNOWN region (content-addressed,
325
+ // exact) skips the contrast: it IS learnt content, not an approximation.
326
+ //
327
+ // The margin GATES; it does NOT scale the weight. A surviving region votes
328
+ // at its genuine strength (score²·wf) — the SAME scale {@link
329
+ // consensusFloor} is derived for. Using the margin as a MULTIPLIER
330
+ // (score·margin) conflated "discriminative" with "strong": a genuinely
331
+ // discriminative span whose frame-rival happened to score close got a tiny
332
+ // vote, systematically compressing correct scaffolding-dominated groundings
333
+ // (reordered / paraphrased queries) below the floor so they grounded
334
+ // nothing. Gating at the noise floor keeps frame-echo suppression (a frame
335
+ // region's margin ≈ 0 is gated out) without penalising honest evidence.
336
+ if (!known) {
337
+ let margin = score;
338
+ for (const h of await ensureHits()) {
339
+ if (h.id === voterId) continue;
340
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
341
+ if (r2.saturated || r2.roots.length === 0) continue; // concludes nothing
342
+ if (sameRoots(r2.roots, reach.roots)) continue; // same conclusion
343
+ margin = score - h.score; // hits are nearest-first: the best rival
344
+ break;
345
+ }
346
+ if (margin <= estimatorNoise(ctx.store.D)) continue;
347
+ }
348
+
349
+ // MUTUAL-EXPLANATION WEIGHT (angle + magnitude). Under the linear fold
350
+ // cos = shared/(‖r‖·‖h‖) with ‖·‖² = content bytes, so the old score²
351
+ // was already — implicitly — (shared/len_r)·(shared/len_h): the fraction
352
+ // of the REGION the hit explains times the fraction of the HIT the
353
+ // region pins down. Made explicit, each factor is computed from the two
354
+ // magnitudes (the region's own span; the hit's, read from the store —
355
+ // contentLen, √bytes being the linear fold's gist norm) and CAPPED at 1:
356
+ // the estimated cosine can imply more shared content than the smaller
357
+ // side even holds, and the uncapped square silently credited that
358
+ // impossible surplus — a small region echoing inside a large context, or
359
+ // the reverse, voted above its physical evidence. In the uncapped
360
+ // regime this is exactly score², the scale {@link consensusFloor} is
361
+ // derived for. (The margin gate above deliberately stays in raw cosine
362
+ // units: it tests the ESTIMATOR's noise floor, which lives in cosine
363
+ // space; converting each side by its own hit's magnitude would compare
364
+ // noise floors of different scales.)
365
+ const lenR = Math.max(1, end - start);
366
+ // Cap the magnitude read at lenR·D: past it s/ratio ≤ s/√D — below the
367
+ // estimator's own noise floor — so the mutual weight is ~0 regardless
368
+ // and the clamped value yields exactly that; no full walk of a huge hit.
369
+ const ratio = Math.sqrt(
370
+ Math.max(1, ctx.store.contentLen(scoreId, lenR * ctx.store.D)) / lenR,
371
+ );
372
+ const mutual = Math.min(1, score * ratio) * Math.min(1, score / ratio);
373
+ const w = (mutual * wf) / reach.roots.length;
374
+ const wFocus = (mutual * idf) / reach.roots.length;
375
+ regionVotes.push({
376
+ start,
377
+ end,
378
+ canonicalFailed,
379
+ roots: reach.roots,
380
+ w,
381
+ wFocus,
382
+ });
383
+ if (ctx.trace) {
384
+ regionVoter[ri] = { id: voterId, score, w: wf };
385
+ }
386
+ }
387
+ return {
388
+ votes: regionVotes,
389
+ saturated: regionSaturated,
390
+ voters: regionVoter,
391
+ };
392
+ }
393
+
394
+ /** The consensus vote as EVIDENCE POOLING, not shortest path: each surviving
395
+ * region is an axiom; it contributes to every root it climbed to (or, for a
396
+ * terminal answer node, to the contexts that lead to it) by a `combine:
397
+ * "sum"` rule, so independent regions corroborating the same anchor ADD
398
+ * rather than compete to be the cheapest route (see {@link Rule.combine} in
399
+ * derive/src/deduction.ts). Run through the very engine {@link
400
+ * GraphSearch} covers with — `lightestDerivation` — so a pooled-evidence
401
+ * decision is, like a followed edge or a spliced connector, one weighted
402
+ * rule of the SAME deduction system, not a separate hand-rolled tally that
403
+ * merely logs alongside it. `votesIdf`/`support` are the same two
404
+ * read-outs {@link commitVotes} always gated on; only how they accumulate
405
+ * changed. */
406
+ export function poolVotes(
407
+ ctx: MindContext,
408
+ regionVotes: readonly RegionVote[],
409
+ sat: SaturationInfo,
410
+ N: number,
411
+ ): {
412
+ votes: Map<number, number>;
413
+ votesIdf: Map<number, number>;
414
+ support: Map<number, { start: number; end: number; w: number }>;
415
+ steps: DerivationStep[];
416
+ } {
417
+ const eligible: number[] = [];
418
+ for (let ri = 0; ri < regionVotes.length; ri++) {
419
+ const rv = regionVotes[ri];
420
+ if (
421
+ rv.canonicalFailed &&
422
+ sat.intervals.some((iv) => rv.start >= iv.start && rv.end <= iv.end)
423
+ ) {
424
+ continue;
425
+ }
426
+ eligible.push(ri);
427
+ }
428
+
429
+ const key = (it: AItem) =>
430
+ it.kind === "region"
431
+ ? `r${it.ri}`
432
+ : it.kind === "anchor"
433
+ ? `a${it.id}`
434
+ : `x${it.id}`;
435
+ const pool = new Map<string, PooledConclusion<AItem>>();
436
+ const system: DeductionSystem<AItem> = {
437
+ key,
438
+ *axioms() {
439
+ for (const ri of eligible) {
440
+ yield { item: { kind: "region", ri }, cost: 0 };
441
+ }
442
+ },
443
+ isGoal: () => false, // exhaust every axiom; there is no single goal to stop at
444
+ // Every region axiom ties at cost 0, so the agenda's pop order among them
445
+ // is otherwise unspecified; ordering by `ri` here only steers the HEAP
446
+ // (never added to a stored cost — see relax's use of h) so pooling fires
447
+ // in exactly the regionVotes array order the original loop used, byte-for-
448
+ // byte reproducing its accumulation and tie-break order.
449
+ heuristic: (it) => it.kind === "region" ? it.ri : 0,
450
+ *rules(it) {
451
+ if (it.kind !== "region") return;
452
+ const rv = regionVotes[it.ri];
453
+ // The same hub bound the rest of the system uses (edgeAncestors' parent
454
+ // cutoff, chooseNext's candidate cap): a terminal answer followed by
455
+ // more than √N contexts is a non-discriminative hub — spreading a
456
+ // region's vote across its FULL corpus-sized fan-in yields O(corpus)
457
+ // rule applications per region and near-zero per-target weight anyway.
458
+ // Cap the redistribution at the first √N contexts (insertion order,
459
+ // the same convention chooseNext caps by).
460
+ const hubBound = Math.ceil(Math.sqrt(N));
461
+ for (const r of rv.roots) {
462
+ // CAPPED read: only the first hubBound targets are ever credited, so
463
+ // only they are read — a common continuation's full reverse fan-in
464
+ // is corpus-sized and is never materialised.
465
+ const pv = ctx.store.prevFirst(r, hubBound);
466
+ const isAnswer = pv.length > 0 && !ctx.store.hasNext(r);
467
+ const targets = isAnswer ? pv : [r];
468
+ for (const t of targets) {
469
+ yield {
470
+ premises: [it],
471
+ conclusion: { kind: "anchor", id: t },
472
+ cost: rv.w / targets.length,
473
+ combine: "sum",
474
+ };
475
+ yield {
476
+ premises: [it],
477
+ conclusion: { kind: "anchorFocus", id: t },
478
+ cost: rv.wFocus / targets.length,
479
+ combine: "sum",
480
+ };
481
+ }
482
+ }
483
+ },
484
+ pool,
485
+ };
486
+ lightestDerivation(system);
487
+
488
+ const votes = new Map<number, number>();
489
+ const votesIdf = new Map<number, number>();
490
+ const support = new Map<
491
+ number,
492
+ { start: number; end: number; w: number }
493
+ >();
494
+ const steps: DerivationStep[] = [];
495
+ let order = 0;
496
+ for (const pc of pool.values()) {
497
+ if (pc.item.kind === "anchor") {
498
+ votes.set(pc.item.id, pc.cost);
499
+ const premises: DerivationItem[] = [];
500
+ const seenRi = new Set<number>();
501
+ for (const c of pc.contributions) {
502
+ const p0 = c.premises[0].item;
503
+ if (p0.kind !== "region" || seenRi.has(p0.ri)) continue;
504
+ seenRi.add(p0.ri);
505
+ const rv = regionVotes[p0.ri];
506
+ premises.push({ kind: "form", span: [rv.start, rv.end] });
507
+ }
508
+ steps.push({
509
+ order: order++,
510
+ move: "pool-vote",
511
+ premises,
512
+ conclusion: { kind: "form", span: [-1, -1], node: pc.item.id },
513
+ cost: pc.cost,
514
+ producers: [],
515
+ });
516
+ } else if (pc.item.kind === "anchorFocus") {
517
+ votesIdf.set(pc.item.id, pc.cost);
518
+ let bestRv: RegionVote | null = null;
519
+ for (const c of pc.contributions) {
520
+ const p0 = c.premises[0].item;
521
+ if (p0.kind !== "region") continue;
522
+ const rv = regionVotes[p0.ri];
523
+ if (!bestRv || rv.wFocus > bestRv.wFocus) bestRv = rv;
524
+ }
525
+ if (bestRv) {
526
+ support.set(pc.item.id, {
527
+ start: bestRv.start,
528
+ end: bestRv.end,
529
+ w: bestRv.wFocus,
530
+ });
531
+ }
532
+ }
533
+ }
534
+ return { votes, votesIdf, support, steps };
535
+ }
536
+
537
+ export function commitVotes(
538
+ ctx: MindContext,
539
+ pooled: {
540
+ votes: Map<number, number>;
541
+ votesIdf: Map<number, number>;
542
+ support: Map<number, { start: number; end: number; w: number }>;
543
+ steps: DerivationStep[];
544
+ },
545
+ sat: SaturationInfo,
546
+ regions: readonly Region[],
547
+ regionVoter: ReadonlyArray<{ id: number; score: number; w: number } | null>,
548
+ N: number,
549
+ ): AttentionRead {
550
+ const { votes, votesIdf, support, steps } = pooled;
551
+ if (votes.size === 0) {
552
+ traceAttention(ctx, regions, regionVoter, [], steps);
553
+ return { roots: [], ranked: [] };
554
+ }
555
+
556
+ const ranked = [...votes.entries()]
557
+ .map(([anchor, vote]) => {
558
+ const s = support.get(anchor)!;
559
+ return { anchor, vote, start: s.start, end: s.end };
560
+ })
561
+ .sort((a, b) => b.vote - a.vote);
562
+
563
+ const overlaps = (a: Attention, b: Attention) =>
564
+ a.start < b.end && b.start < a.end;
565
+ const idfDesc = [...votesIdf.values()].sort((a, b) => b - a);
566
+ const rootCut = naturalBreak(idfDesc);
567
+ // A FURTHER point of attention (beyond the dominant one, which always
568
+ // grounds) must clear the same absolute significance floor
569
+ // recallByResonance trusts a climb anchor with — log(N) + 1/2, three-ish
570
+ // halvings of confidence above pure chance at this corpus scale — not
571
+ // merely beat whatever its immediate neighbour in the ratio happens to be.
572
+ // Without it, naturalBreak's ratio is scale-free but not FLOOR-free: on a
573
+ // large, topic-diverse corpus the steepest ratio in a long noise tail can
574
+ // sit far below any real signal, admitting scaffolding echoes as if they
575
+ // were genuine further topics.
576
+ const floor = consensusFloor(N);
577
+ const placed: Attention[] = [];
578
+ const roots: Attention[] = [];
579
+ for (const point of ranked) {
580
+ const absorbed = placed.some((p) => overlaps(point, p));
581
+ if (!absorbed) {
582
+ const pastLeading = !sat.hasLeading ||
583
+ roots.length === 0 || point.start >= sat.leadingEnd;
584
+ const vote = votesIdf.get(point.anchor) ?? 0;
585
+ if (
586
+ (roots.length === 0 || (vote >= rootCut && vote >= floor)) &&
587
+ pastLeading
588
+ ) {
589
+ roots.push(point);
590
+ } else {
591
+ continue;
592
+ }
593
+ }
594
+ placed.push(point);
595
+ }
596
+
597
+ traceAttention(ctx, regions, regionVoter, roots, steps);
598
+ return { roots, ranked };
599
+ }
600
+
601
+ export function detectSaturated(
602
+ ctx: MindContext,
603
+ regions: ReadonlyArray<{ start: number; end: number; chunk?: boolean }>,
604
+ saturated: ReadonlyArray<boolean>,
605
+ ): SaturationInfo {
606
+ // Intervals are built from CHUNK regions only. collectRegions emits the
607
+ // tree in POST-ORDER — a parent region arrives AFTER its children and
608
+ // shares its first child's `start` — so the raw array is not monotone in
609
+ // byte position, and a saturated parent would fuse with a later saturated
610
+ // chunk into an interval swallowing a NON-saturated child. Chunk regions
611
+ // (leaf-parents) are disjoint and already in byte order, and saturation
612
+ // masking exists to drop canonicalFailed CHUNK votes (see poolVotes), so
613
+ // chunks are both the sufficient and the safe basis. A region without a
614
+ // `chunk` flag (a bare {start,end} from a direct caller) is treated as a
615
+ // chunk.
616
+ const intervals: Array<{ start: number; end: number }> = [];
617
+ let intStart = -1;
618
+ let intEnd = -1;
619
+ let totalLen = 0;
620
+ for (let ri = 0; ri < regions.length; ri++) {
621
+ const r = regions[ri];
622
+ totalLen = Math.max(totalLen, r.end);
623
+ if (r.chunk === false) continue;
624
+ if (saturated[ri]) {
625
+ if (intStart === -1) intStart = r.start;
626
+ intEnd = r.end;
627
+ } else {
628
+ if (intStart !== -1) {
629
+ intervals.push({ start: intStart, end: intEnd });
630
+ intStart = -1;
631
+ }
632
+ }
633
+ }
634
+ if (intStart !== -1) {
635
+ intervals.push({ start: intStart, end: intEnd });
636
+ }
637
+
638
+ const leading = intervals.length > 0 && intervals[0].start === 0
639
+ ? intervals[0]
640
+ : null;
641
+ const hasLeading = leading !== null &&
642
+ leading.end >= ctx.space.maxGroup &&
643
+ leading.end < totalLen;
644
+ const leadingEnd = leading !== null ? leading.end : 0;
645
+
646
+ return { leadingEnd, hasLeading, intervals };
647
+ }
648
+
649
+ /** Set equality of two climb root lists (the "same conclusion" test the
650
+ * contrastive margin skips rivals by). */
651
+ function sameRoots(a: readonly number[], b: readonly number[]): boolean {
652
+ if (a.length !== b.length) return false;
653
+ const s = new Set(a);
654
+ for (const x of b) if (!s.has(x)) return false;
655
+ return true;
656
+ }
657
+
658
+ export function canonicalChunkId(
659
+ ctx: MindContext,
660
+ regionBytes: Uint8Array,
661
+ N: number,
662
+ reachMemo?: Map<number, AncestorReach>,
663
+ ): number | null {
664
+ const len = Math.min(regionBytes.length, ctx.space.maxGroup);
665
+ for (let off = 0; off + len <= regionBytes.length; off++) {
666
+ const ids = leafIdRun(ctx, regionBytes, off, off + len);
667
+ if (ids === null) return null;
668
+ const flatId = ctx.store.findBranch(ids);
669
+ if (flatId === null) continue;
670
+ if (len < 2) return flatId;
671
+
672
+ let bestId = flatId;
673
+ let bestReach = edgeAncestors(ctx, flatId, N, reachMemo);
674
+ for (let k2 = 1; k2 < len; k2++) {
675
+ const shortIds = ids.slice(0, len - k2);
676
+ const shortId = ctx.store.findBranch(shortIds);
677
+ if (shortId === null) continue;
678
+ const shortReach = edgeAncestors(ctx, shortId, N, reachMemo);
679
+ if (
680
+ shortReach.saturated ||
681
+ shortReach.contextsReached > bestReach.contextsReached
682
+ ) {
683
+ bestId = shortId;
684
+ bestReach = shortReach;
685
+ }
686
+ }
687
+ return bestId;
688
+ }
689
+ return null;
690
+ }
691
+
692
+ export function naturalBreak(votes: number[]): number {
693
+ if (votes.length <= 1) return votes[0] ?? 0;
694
+ let breakAt = 1;
695
+ let steepest = Infinity;
696
+ for (let i = 1; i < votes.length; i++) {
697
+ if (votes[i - 1] <= 0) break;
698
+ const ratio = votes[i] / votes[i - 1];
699
+ if (ratio < steepest) {
700
+ steepest = ratio;
701
+ breakAt = i;
702
+ }
703
+ }
704
+ return votes[breakAt - 1];
705
+ }
706
+
707
+ // ═══════════════════════════════════════════════════════════════════════════
708
+ // Cross-region attention — DIRECT region-to-region interaction.
709
+ //
710
+ // voteRegions climbs each region INDEPENDENTLY; poolVotes then ADDS those
711
+ // independent votes. Additive pooling is a soft conjunction, but it can only
712
+ // ever surface a context at least one region already votes for. Two regions
713
+ // whose individual climbs land on DIFFERENT contexts leave their JOINT context
714
+ // — the learnt whole that contains BOTH — with no vote at all, and no amount
715
+ // of pooling can recover it. ("red" climbs to `red square`, "circle" to
716
+ // `circle`; nothing votes for `red circle`, the only fact holding both.)
717
+ //
718
+ // This is the attention counterpart of the bridge, and it ascends by the SAME
719
+ // content-addressed junction walk (junction.ts): "which learnt whole contains
720
+ // region A then region B?" is a bounded DAG ascent from the two forms'
721
+ // canonical identities — NOT a resonance guess on a synthesised gist. Folding
722
+ // two region vectors cannot even reconstruct the stored joint form: Sema builds
723
+ // a multi-word gist from BYTE-chunk folds, so isolated word vectors superpose
724
+ // into a different direction and resonate to `red circle` and `red square`
725
+ // indistinguishably. The ascent sidesteps this by matching BYTES, not vectors.
726
+ //
727
+ // A joint container is EXACT evidence (it literally holds both forms), so it
728
+ // votes at full strength — the exact-first discipline voteRegions gives a
729
+ // content-addressed chunk. Each junction search is a bounded walk with NO
730
+ // ANN query, and searches are capped at k. Three further disciplines make
731
+ // the composition ORDER-FREE, N-ARY, and CORPUS-INDEPENDENT:
732
+ //
733
+ // • ORDER-FREE — a junction is evidence the forms were LEARNT TOGETHER;
734
+ // which one the query mentioned first is a fact about the query, not the
735
+ // learnt whole. The walk tests both byte orders at no extra walk cost
736
+ // (see junctionContainersFrom's `unordered`).
737
+ // • N-ARY — binding is not intrinsically pairwise. A pair's containers are
738
+ // FILTERED by the remaining candidate forms: the container covering the
739
+ // MOST of the query's composable forms wins, so three cross-cutting
740
+ // attributes (each pair ambiguous) still resolve to their unique triple —
741
+ // at the cost of one cached byte read + indexOf per (container, extra),
742
+ // never an extra walk.
743
+ // • CORPUS-INDEPENDENT — candidates are ANY voted region, not just
744
+ // recognised sites. A word never learnt standalone has no site, but its
745
+ // stored chunks still vote and their BYTES still compose: the ascent
746
+ // matches byte containment, so a fragment pair evidences the same joint
747
+ // container the whole word would. Contiguous shards of one word cannot
748
+ // pair (the adjacency skip), and a pair covered by a single KNOWN region
749
+ // is skipped — that whole form already votes directly, and re-deriving it
750
+ // from its own pieces would only double-count.
751
+ //
752
+ // EXPLAINING AWAY (the aliasing complement of corpus independence): a chunk
753
+ // of the query can straddle the byte grid so that it exists verbatim in the
754
+ // WRONG deposit (" cir" of "red then circle" is a stored chunk of `blue
755
+ // circle`, never of `red circle` — a pure alignment accident) and its
756
+ // independent climb then votes for a context the query gives no reason to
757
+ // believe. When a junction binds, any individual vote whose bytes the joint
758
+ // container LITERALLY CONTAINS yet whose climb disagrees with the junction's
759
+ // is superseded: the exact joint evidence explains those bytes, so their
760
+ // disagreeing vote is grid aliasing, not signal. Votes whose bytes the
761
+ // container does not hold (a genuine second topic) are untouched.
762
+ // ═══════════════════════════════════════════════════════════════════════════
763
+
764
+ async function crossRegionVotes(
765
+ ctx: MindContext,
766
+ query: Uint8Array,
767
+ regions: readonly Region[],
768
+ rvs: { votes: readonly RegionVote[]; saturated: readonly boolean[] },
769
+ k: number,
770
+ N: number,
771
+ reachMemo: Map<number, AncestorReach>,
772
+ ): Promise<{ votes: RegionVote[]; superseded: Set<RegionVote> }> {
773
+ // Candidate regions: every region that ALREADY CAST ITS OWN VOTE in
774
+ // voteRegions — individually idf > 0, genuinely discriminative on its own,
775
+ // just not necessarily for the SAME context as its partner. This is the
776
+ // exact shape of the binding problem: "red" alone votes for `red square`,
777
+ // "circle" alone for `circle` — each independently informative, disagreeing
778
+ // on the conclusion — and only their CONJUNCTION resolves to the one
779
+ // context, `red circle`, that actually holds both.
780
+ //
781
+ // A region that never voted (idf == 0 — e.g. a repeated system-prompt
782
+ // prefix shared by every deposit) carries NO individual signal, and must be
783
+ // excluded here too: ascending from a non-discriminative fragment's seeds
784
+ // can still land on some deeper, incidentally-unique DESCENDANT container —
785
+ // its rarity would come entirely from context OUTSIDE the fragments
786
+ // actually composed, manufacturing confidence the query gave no reason to
787
+ // have. Requiring a prior individual vote is the same discipline the noise
788
+ // drop already applies to single regions, extended to compositions — with
789
+ // one graded relaxation: a KNOWN region that did NOT vote (saturated, or
790
+ // idf ≤ 0) may still serve as the WEAK side of a pair whose other side DID
791
+ // vote. Saturation is an abstention about where the region CLIMBS; its
792
+ // content-addressed identity is still exact, and the junction asks a
793
+ // different question — "which whole holds both?" — whose conclusion the
794
+ // container's own idf gate below still guards. Two non-voting regions
795
+ // never pair (that is exactly the shared-prefix trap above), so at least
796
+ // one side is always individually discriminative.
797
+ //
798
+ // Only MAXIMAL spans compose: a span contained in another candidate is a
799
+ // fragment of that candidate's evidence, never independent of it.
800
+ const votedSpans = new Set<string>();
801
+ for (const rv of rvs.votes) votedSpans.add(`${rv.start},${rv.end}`);
802
+ const seen = new Set<string>();
803
+ const eligible: number[] = [];
804
+ const strong = new Set<number>();
805
+ for (let ri = 0; ri < regions.length; ri++) {
806
+ const r = regions[ri];
807
+ const key = `${r.start},${r.end}`;
808
+ const isStrong = votedSpans.has(key);
809
+ if ((!isStrong && !r.known) || seen.has(key)) continue;
810
+ seen.add(key);
811
+ eligible.push(ri);
812
+ if (isStrong) strong.add(ri);
813
+ }
814
+ const cand = eligible.filter((x) =>
815
+ !eligible.some((y) =>
816
+ y !== x &&
817
+ regions[y].start <= regions[x].start &&
818
+ regions[x].end <= regions[y].end &&
819
+ regions[y].end - regions[y].start > regions[x].end - regions[x].start
820
+ )
821
+ );
822
+ const none = { votes: [], superseded: new Set<RegionVote>() };
823
+ if (cand.length < 2) return none;
824
+ cand.sort((x, y) =>
825
+ regions[x].start - regions[y].start || regions[x].end - regions[y].end
826
+ );
827
+
828
+ const dec = (b: Uint8Array): string =>
829
+ new TextDecoder().decode(b).replace(/\s+/g, " ").trim();
830
+ const cache = walkCache(ctx);
831
+ // One junctionSeeds per candidate for the WHOLE pairing loop — a candidate
832
+ // recurs in up to |cand|−1 pairs, and its seeds are a pure function of its
833
+ // bytes.
834
+ const seedsMemo = new Map<number, number[]>();
835
+ const seedsOf = (ri: number): number[] => {
836
+ let s = seedsMemo.get(ri);
837
+ if (s === undefined) {
838
+ const r = regions[ri];
839
+ s = junctionSeeds(ctx, query.subarray(r.start, r.end));
840
+ seedsMemo.set(ri, s);
841
+ }
842
+ return s;
843
+ };
844
+ const overlapsSpan = (
845
+ e: Region,
846
+ s: { start: number; end: number },
847
+ ): boolean => e.start < s.end && s.start < e.end;
848
+
849
+ const out: RegionVote[] = [];
850
+ const superseded = new Set<RegionVote>();
851
+ // A candidate consumed by one junction does not seed another: its evidence
852
+ // is already composed at full joint strength, and re-pairing it would vote
853
+ // the same container (or a sub-container of it) twice.
854
+ const consumed = new Set<number>();
855
+ let probes = 0;
856
+
857
+ for (let a = 0; a < cand.length && probes < k; a++) {
858
+ if (consumed.has(cand[a])) continue;
859
+ const ra = regions[cand[a]];
860
+ for (let b = a + 1; b < cand.length && probes < k; b++) {
861
+ if (consumed.has(cand[b])) continue;
862
+ const rb = regions[cand[b]];
863
+ if (!strong.has(cand[a]) && !strong.has(cand[b])) continue;
864
+ if (ra.end >= rb.start) continue; // overlap or adjacent — nothing between
865
+ // A single KNOWN region covering both: the whole form is already a
866
+ // stored identity that votes directly; its pieces add nothing.
867
+ if (
868
+ regions.some((r) => r.known && r.start <= ra.start && rb.end <= r.end)
869
+ ) continue;
870
+ probes++;
871
+
872
+ const left = query.subarray(ra.start, ra.end);
873
+ const right = query.subarray(rb.start, rb.end);
874
+ // Phrase-scale contract, exactly as the bridge: the glue between the two
875
+ // forms may be up to W× the content it joins.
876
+ const maxInterior = (left.length + right.length) * ctx.space.maxGroup;
877
+ const cap = left.length + right.length + maxInterior;
878
+
879
+ // Tier 1 — exact containers (both forms as substrings, either order, by
880
+ // DAG ascent). Exact evidence first; only falls through to synonyms
881
+ // when the exact ascent finds nothing — the SAME graded ladder the
882
+ // bridge uses.
883
+ let containers = junctionContainersFrom(
884
+ ctx,
885
+ left,
886
+ right,
887
+ cap,
888
+ seedsOf(cand[a]),
889
+ seedsOf(cand[b]),
890
+ undefined,
891
+ true,
892
+ );
893
+ if (containers.length === 0) {
894
+ // Tier 2.5 — synonym containers (halo sibling of one side + the other).
895
+ containers = await junctionSynonyms(
896
+ ctx,
897
+ left,
898
+ right,
899
+ maxInterior,
900
+ true,
901
+ );
902
+ }
903
+ if (containers.length === 0) continue;
904
+
905
+ // N-ARY selection: the container covering the MOST remaining candidate
906
+ // forms wins (then tightest interior, then lowest id). Reads are
907
+ // cache hits — every container's bytes were already read by the walk.
908
+ //
909
+ // SELF-EVIDENCE GUARD: a junction is BINDING evidence only when the
910
+ // container joins forms the query mentions APART. When the container's
911
+ // own joined occurrence (left..right including its interior) is a
912
+ // literal substring of the query, the query already spells that phrase
913
+ // out contiguously — perception already voted with it, and grid shards
914
+ // of one phrase pairing "around" a gap chunk would merely rediscover
915
+ // the phrase they are shards of, then explain away its rivals.
916
+ let best: (typeof containers)[number] | null = null;
917
+ let bestExtras: number[] = [];
918
+ let bestCov = -1;
919
+ for (const c of containers) {
920
+ const bytes = cachedRead(ctx, cache, c.id, cap);
921
+ const li = indexOf(bytes, left, 0);
922
+ const ri = indexOf(bytes, right, 0);
923
+ if (li >= 0 && ri >= 0) {
924
+ const joined = bytes.subarray(
925
+ Math.min(li, ri),
926
+ Math.max(li + left.length, ri + right.length),
927
+ );
928
+ if (indexOf(query, joined, 0) >= 0) continue; // query says it itself
929
+ }
930
+ let cov = left.length + right.length;
931
+ const extras: number[] = [];
932
+ for (const ei of cand) {
933
+ if (ei === cand[a] || ei === cand[b] || consumed.has(ei)) continue;
934
+ const e = regions[ei];
935
+ if (overlapsSpan(e, ra) || overlapsSpan(e, rb)) continue;
936
+ const eb = query.subarray(e.start, e.end);
937
+ if (indexOf(bytes, eb, 0) >= 0) {
938
+ extras.push(ei);
939
+ cov += eb.length;
940
+ }
941
+ }
942
+ if (
943
+ cov > bestCov ||
944
+ (cov === bestCov && best !== null &&
945
+ (c.interior.length < best.interior.length ||
946
+ (c.interior.length === best.interior.length && c.id < best.id)))
947
+ ) {
948
+ best = c;
949
+ bestExtras = extras;
950
+ bestCov = cov;
951
+ }
952
+ }
953
+ if (best === null) continue; // every container was self-evidence
954
+
955
+ const reach = edgeAncestors(ctx, best.id, N, reachMemo);
956
+ if (reach.saturated || reach.roots.length === 0) continue;
957
+ const idf = Math.log(N / Math.max(1, reach.contextsReached));
958
+ if (idf <= 0) continue;
959
+
960
+ // EXACT joint evidence (score = 1): the container literally contains
961
+ // every composed form. Mutual-explanation weight over their COMBINED
962
+ // byte length — the same magnitude reading voteRegions uses, here with
963
+ // the estimator collapsed to certainty, so mutual = min(ratio, 1/ratio).
964
+ const lenR = Math.max(1, bestCov);
965
+ const ratio = Math.sqrt(
966
+ Math.max(1, ctx.store.contentLen(best.id, lenR * ctx.store.D)) / lenR,
967
+ );
968
+ const mutual = Math.min(1, ratio) * Math.min(1, 1 / ratio);
969
+ const w = (mutual * idf) / reach.roots.length;
970
+ let spanStart = ra.start;
971
+ let spanEnd = rb.end;
972
+ for (const ei of bestExtras) {
973
+ spanStart = Math.min(spanStart, regions[ei].start);
974
+ spanEnd = Math.max(spanEnd, regions[ei].end);
975
+ }
976
+ out.push({
977
+ start: spanStart,
978
+ end: spanEnd,
979
+ canonicalFailed: false, // content-addressed: never saturation-masked
980
+ roots: reach.roots,
981
+ w,
982
+ wFocus: w,
983
+ });
984
+ consumed.add(cand[a]);
985
+ consumed.add(cand[b]);
986
+ for (const ei of bestExtras) consumed.add(ei);
987
+
988
+ // EXPLAINING AWAY — see the block comment above the function. Byte
989
+ // containment in the joint container is the relatedness test (the
990
+ // vote's bytes are literally part of the learnt whole), and FULL root
991
+ // disjointness is the disagreement test: a vote sharing even one root
992
+ // with the junction corroborates it and keeps its say elsewhere.
993
+ const containerBytes = cachedRead(ctx, cache, best.id, cap);
994
+ const jointRoots = new Set(reach.roots);
995
+ for (const rv of rvs.votes) {
996
+ if (rv.roots.some((r) => jointRoots.has(r))) continue;
997
+ const bytes = query.subarray(rv.start, rv.end);
998
+ if (indexOf(containerBytes, bytes, 0) >= 0) superseded.add(rv);
999
+ }
1000
+
1001
+ const label = [cand[a], cand[b], ...bestExtras]
1002
+ .sort((x, y) => regions[x].start - regions[y].start)
1003
+ .map((ri) => dec(query.subarray(regions[ri].start, regions[ri].end)))
1004
+ .join(" ▸ ");
1005
+ ctx.trace?.step(
1006
+ "crossRegion",
1007
+ [{ text: label, role: "pair" }],
1008
+ reach.roots.map((r) => ({
1009
+ text: dec(read(ctx, r)).slice(0, 60),
1010
+ node: r,
1011
+ role: "joint-context",
1012
+ })),
1013
+ `${label} → junction node ${best.id}` +
1014
+ (best.interior.length === 0
1015
+ ? " (adjacent)"
1016
+ : ` (interior "${dec(best.interior)}")`) +
1017
+ ` → ${reach.roots.length} context(s), by content-addressed ascent` +
1018
+ (superseded.size > 0
1019
+ ? `; ${superseded.size} aliasing vote(s) explained away`
1020
+ : ""),
1021
+ );
1022
+ break; // ra is consumed — move to the next unconsumed candidate
1023
+ }
1024
+ }
1025
+
1026
+ return { votes: out, superseded };
1027
+ }
1028
+
1029
+ export function traceAttention(
1030
+ ctx: MindContext,
1031
+ regions: ReadonlyArray<{ start: number; end: number }>,
1032
+ regionVoter: ReadonlyArray<{ id: number; score: number; w: number } | null>,
1033
+ roots: ReadonlyArray<Attention>,
1034
+ steps: ReadonlyArray<DerivationStep> = [],
1035
+ ): void {
1036
+ if (!ctx.trace) return;
1037
+ const voters: RationaleItem[] = [];
1038
+ for (let i = 0; i < regions.length; i++) {
1039
+ const rv = regionVoter[i];
1040
+ if (rv == null) continue;
1041
+ const item = rNode(ctx, rv.id, "sub-region", rv.score);
1042
+ item.text = `${item.text} (df-w ${rv.w.toFixed(2)})`;
1043
+ voters.push(item);
1044
+ }
1045
+ const t = ctx.trace.enter("climbConsensus", voters);
1046
+ // The pooled-evidence decision, one DerivationStep per anchor — the same
1047
+ // shape {@link GraphSearch}'s own cover steps take (see traceDerivation).
1048
+ if (steps.length > 0) traceDerivation(ctx, steps);
1049
+ t.done(
1050
+ roots.map((r) => rNode(ctx, r.anchor, "anchor", r.vote)),
1051
+ roots.length === 0
1052
+ ? `${regions.length} sub-regions climbed the DAG, but none agreed on a context`
1053
+ : roots.length === 1
1054
+ ? `${voters.length} of ${regions.length} sub-regions voted; IDF-weighted consensus picked one context (vote ${
1055
+ roots[0].vote.toFixed(2)
1056
+ })`
1057
+ : `${voters.length} of ${regions.length} sub-regions voted; consensus ordered ${roots.length} INDEPENDENT points of attention (votes ${
1058
+ roots.map((r) => r.vote.toFixed(2)).join(", ")
1059
+ })`,
1060
+ );
1061
+ }