@hviana/sema 0.1.0 → 0.1.2

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