@hviana/sema 0.2.6 → 0.2.8

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 (133) 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 +2252 -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 +221 -0
  26. package/dist/src/alu/src/parser.js +577 -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/canon.d.ts +26 -0
  38. package/dist/src/canon.js +57 -0
  39. package/dist/src/config.d.ts +111 -0
  40. package/dist/src/config.js +91 -0
  41. package/dist/src/derive/src/deduction.d.ts +125 -0
  42. package/dist/src/derive/src/deduction.js +155 -0
  43. package/dist/src/derive/src/index.d.ts +7 -0
  44. package/dist/src/derive/src/index.js +11 -0
  45. package/dist/src/derive/src/priority-queue.d.ts +20 -0
  46. package/dist/src/derive/src/priority-queue.js +73 -0
  47. package/dist/src/derive/src/rewrite.d.ts +56 -0
  48. package/dist/src/derive/src/rewrite.js +100 -0
  49. package/dist/src/derive/src/trie.d.ts +90 -0
  50. package/dist/src/derive/src/trie.js +217 -0
  51. package/dist/src/derive/test/derive.test.d.ts +1 -0
  52. package/dist/src/derive/test/derive.test.js +122 -0
  53. package/dist/src/extension.d.ts +37 -0
  54. package/dist/src/extension.js +7 -0
  55. package/dist/src/geometry.d.ts +202 -0
  56. package/dist/src/geometry.js +575 -0
  57. package/dist/src/index.d.ts +16 -0
  58. package/dist/src/index.js +18 -0
  59. package/dist/src/ingest-cache.d.ts +41 -0
  60. package/dist/src/ingest-cache.js +161 -0
  61. package/dist/src/mind/articulation.d.ts +6 -0
  62. package/dist/src/mind/articulation.js +99 -0
  63. package/dist/src/mind/attention.d.ts +405 -0
  64. package/dist/src/mind/attention.js +1829 -0
  65. package/dist/src/mind/bridge.d.ts +30 -0
  66. package/dist/src/mind/bridge.js +569 -0
  67. package/dist/src/mind/canonical.d.ts +29 -0
  68. package/dist/src/mind/canonical.js +88 -0
  69. package/dist/src/mind/graph-search.d.ts +285 -0
  70. package/dist/src/mind/graph-search.js +956 -0
  71. package/dist/src/mind/index.d.ts +7 -0
  72. package/dist/src/mind/index.js +5 -0
  73. package/dist/src/mind/junction.d.ts +124 -0
  74. package/dist/src/mind/junction.js +317 -0
  75. package/dist/src/mind/learning.d.ts +47 -0
  76. package/dist/src/mind/learning.js +248 -0
  77. package/dist/src/mind/match.d.ts +126 -0
  78. package/dist/src/mind/match.js +441 -0
  79. package/dist/src/mind/mechanisms/alu.d.ts +4 -0
  80. package/dist/src/mind/mechanisms/alu.js +36 -0
  81. package/dist/src/mind/mechanisms/cast.d.ts +89 -0
  82. package/dist/src/mind/mechanisms/cast.js +716 -0
  83. package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
  84. package/dist/src/mind/mechanisms/confluence.js +225 -0
  85. package/dist/src/mind/mechanisms/cover.d.ts +6 -0
  86. package/dist/src/mind/mechanisms/cover.js +203 -0
  87. package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
  88. package/dist/src/mind/mechanisms/extraction.js +387 -0
  89. package/dist/src/mind/mechanisms/recall.d.ts +13 -0
  90. package/dist/src/mind/mechanisms/recall.js +325 -0
  91. package/dist/src/mind/mind.d.ts +276 -0
  92. package/dist/src/mind/mind.js +572 -0
  93. package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
  94. package/dist/src/mind/pipeline-mechanism.js +213 -0
  95. package/dist/src/mind/pipeline.d.ts +20 -0
  96. package/dist/src/mind/pipeline.js +217 -0
  97. package/dist/src/mind/primitives.d.ts +70 -0
  98. package/dist/src/mind/primitives.js +287 -0
  99. package/dist/src/mind/rationale.d.ts +139 -0
  100. package/dist/src/mind/rationale.js +163 -0
  101. package/dist/src/mind/reasoning.d.ts +34 -0
  102. package/dist/src/mind/reasoning.js +240 -0
  103. package/dist/src/mind/recognition.d.ts +20 -0
  104. package/dist/src/mind/recognition.js +390 -0
  105. package/dist/src/mind/resonance.d.ts +23 -0
  106. package/dist/src/mind/resonance.js +0 -0
  107. package/dist/src/mind/trace.d.ts +15 -0
  108. package/dist/src/mind/trace.js +73 -0
  109. package/dist/src/mind/traverse.d.ts +113 -0
  110. package/dist/src/mind/traverse.js +568 -0
  111. package/dist/src/mind/types.d.ts +289 -0
  112. package/dist/src/mind/types.js +130 -0
  113. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  114. package/dist/src/rabitq-ivf/src/database.js +201 -0
  115. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  116. package/dist/src/rabitq-ivf/src/index.js +4 -0
  117. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  118. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  119. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  120. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  121. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  122. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  123. package/dist/src/sema.d.ts +31 -0
  124. package/dist/src/sema.js +63 -0
  125. package/dist/src/store-sqlite.d.ts +184 -0
  126. package/dist/src/store-sqlite.js +942 -0
  127. package/dist/src/store.d.ts +663 -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
  132. package/src/mind/attention.ts +178 -63
  133. package/test/51-structural-resonance-ladder.test.mjs +6 -3
@@ -0,0 +1,1829 @@
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 { composeStructuralGist, consensusFloor, dominates, estimatorNoise, } from "../geometry.js";
12
+ import { foldTree, gistOf, latin1Key, perceive, read } from "./primitives.js";
13
+ import { recognise } from "./recognition.js";
14
+ import { leafIdRun } from "./canonical.js";
15
+ import { corpusN, edgeAncestors, hubBound } from "./traverse.js";
16
+ import { cachedRead, junctionContainersFrom, junctionSeeds, junctionSynonyms, loadJunctionSynonymSides, walkCache, } from "./junction.js";
17
+ import { indexOf } from "../bytes.js";
18
+ import { rItem, rNode, traceDerivation } from "./trace.js";
19
+ function newTraceDraft(perceivedCount) {
20
+ return {
21
+ perceivedCount,
22
+ regions: [],
23
+ crossRegionJunctionVotes: [],
24
+ crossRegionProbes: [],
25
+ supersededOrdinaryVotes: 0,
26
+ anchors: [],
27
+ };
28
+ }
29
+ /** Serialise the shared `reachMemo` into the plain, authoritative saturation
30
+ * profile (spec §5) — every distinct node any tier's `edgeAncestors` call
31
+ * climbed from during this response, in insertion (first-consulted) order. */
32
+ function serialiseReaches(reachMemo) {
33
+ const out = [];
34
+ for (const [node, r] of reachMemo) {
35
+ out.push({
36
+ node,
37
+ roots: [...r.roots],
38
+ contextsReached: r.contextsReached,
39
+ saturated: r.saturated,
40
+ ...(r.saturation ? { saturation: r.saturation } : {}),
41
+ });
42
+ }
43
+ return out;
44
+ }
45
+ // ── Public entry points ───────────────────────────────────────────────────
46
+ /** Climb the query's perceived byte regions up the structural DAG via
47
+ * resonance, pool the evidence, and return only the ROOT points of
48
+ * attention — those that cleared commitVotes' significance floor. */
49
+ export async function climbAttention(ctx, query, k, mode = "inverse") {
50
+ return (await climbAttentionAll(ctx, query, k, mode)).roots;
51
+ }
52
+ /** Full read-out of one consensus climb: both the roots (dominant points of
53
+ * attention) and the entire ranked list. Cached via ctx.climbMemo, ALWAYS —
54
+ * see {@link recognise} for why this memo (and recognise()'s own) must
55
+ * never be skipped while tracing: computeAttention's collectRegions walks
56
+ * the query's perceived tree via the same foldTree whose subtree-resolution
57
+ * fast path makes a second call on identical bytes non-idempotent once
58
+ * ctx._resolvedSubtrees is warm (which a multi-turn conversation's shared
59
+ * prefix subtrees guarantee by the second turn). A cache hit still emits
60
+ * a trace step — abbreviated, since the full per-sub-region voting detail
61
+ * {@link traceAttention} builds isn't preserved by the cached read-out —
62
+ * so a traced response is never silently blacked out for a repeated
63
+ * query. */
64
+ export async function climbAttentionAll(ctx, query, k, mode = "inverse") {
65
+ // Content-keyed memo — works for both single-turn respond() and multi-turn
66
+ // respondTurn().
67
+ if (ctx.climbMemo) {
68
+ const contentKey = latin1Key(query);
69
+ const modeKey = `${k}:${mode}`;
70
+ let byRead = ctx.climbMemo.get(contentKey);
71
+ if (byRead === undefined) {
72
+ ctx.climbMemo.set(contentKey, byRead = new Map());
73
+ }
74
+ const hit = byRead.get(modeKey);
75
+ if (hit !== undefined) {
76
+ // Cache-hit exit (spec §9): the abbreviated payload shape — only what
77
+ // is actually stored in the cached AttentionRead is reported. No
78
+ // candidate, reach, saturation, pooling or anchor detail is fabricated
79
+ // (that per-region detail was never retained by the memo).
80
+ const data = ctx.trace
81
+ ? {
82
+ version: 1,
83
+ cache: { hit: true, detailAvailable: false },
84
+ config: { annK: k, crossRegionProbeLimit: k, mode },
85
+ candidates: { perceived: 0, recognised: 0, total: 0 },
86
+ result: hit,
87
+ }
88
+ : undefined;
89
+ ctx.trace?.step("climbConsensus", [rItem(query, "query")], hit.roots.map((r) => rNode(ctx, r.anchor, "anchor", r.vote)), `(cached) consensus already computed for this query — ` +
90
+ `${hit.roots.length} point(s) of attention`, undefined, data);
91
+ return hit;
92
+ }
93
+ const read = await computeAttention(ctx, query, k, mode);
94
+ byRead.set(modeKey, read);
95
+ return read;
96
+ }
97
+ return computeAttention(ctx, query, k, mode);
98
+ }
99
+ // ── Pipeline ──────────────────────────────────────────────────────────────
100
+ export async function computeAttention(ctx, query, k, mode) {
101
+ const regions = collectRegions(ctx, query);
102
+ const perceivedCount = regions.length;
103
+ // Recognised sites carry structural evidence that perceived sub-regions
104
+ // miss: a word crossing a W-boundary is split into chunks whose partial
105
+ // gists may not resonate distinctively, but the SITE (content-addressed,
106
+ // exact) names the whole form. Adding sites as climb regions lets the
107
+ // consensus vote with the full word, at zero cost — recognition is already
108
+ // memoised per response (ctx.recogniseMemo), and gistOf for short sites is
109
+ // O(|span|·D). Sites that overlap perceived regions add corroborating
110
+ // evidence; sites in gaps (like cross-boundary words) fill them.
111
+ const rec = recognise(ctx, query);
112
+ for (const s of rec.sites) {
113
+ regions.push({
114
+ v: gistOf(ctx, query.subarray(s.start, s.end)),
115
+ start: s.start,
116
+ end: s.end,
117
+ chunk: false,
118
+ known: true, // a recognised site IS a stored form
119
+ });
120
+ }
121
+ // The trace draft (spec §9): allocated ONLY when a trace was requested —
122
+ // every downstream consumer gates its own writes on `td?` / `if (td)`, so
123
+ // an untraced climb pays zero allocation for this instrumentation.
124
+ const td = ctx.trace
125
+ ? newTraceDraft(perceivedCount)
126
+ : undefined;
127
+ const cfg0 = {
128
+ k,
129
+ mode,
130
+ perceivedCount,
131
+ totalRegions: regions.length,
132
+ };
133
+ if (regions.length === 0) {
134
+ traceAttention(ctx, [], [], [], undefined, td, cfg0);
135
+ return { roots: [], ranked: [] };
136
+ }
137
+ const N = corpusN(ctx);
138
+ // One climb per distinct anchor for the WHOLE query: regions sharing a
139
+ // chunk, and canonicalChunkId's prefix probes, all hit this memo instead of
140
+ // re-reading the anchor's full edge fan-out from the store.
141
+ const reachMemo = new Map();
142
+ const rvs = await voteRegions(ctx, query, regions, k, mode, N, reachMemo, td);
143
+ // ── Cross-region: DIRECT region-to-region interaction ─────────────────
144
+ // Two regions whose individual climbs land on DIFFERENT contexts leave
145
+ // their JOINT context — the learnt whole that contains BOTH — with no
146
+ // vote. crossRegionVotes recovers it by the bridge's content-addressed
147
+ // junction ascent (see the note above the function).
148
+ const cross = await crossRegionVotes(ctx, query, regions, rvs, k, N, reachMemo, td);
149
+ // A vote SUPERSEDED by exact joint evidence (its bytes literally live
150
+ // inside the joint container, yet it climbed elsewhere — grid aliasing)
151
+ // is dropped, not down-weighted: the joint container explains it away.
152
+ const allVotes = cross.votes.length > 0
153
+ ? [
154
+ ...rvs.votes.filter((v) => !cross.superseded.has(v)),
155
+ ...cross.votes,
156
+ ]
157
+ : rvs.votes;
158
+ // Mark, on the per-region trace, the source region of every superseded
159
+ // ordinary vote (spec §4's final rule) — an explicit pass over the exact
160
+ // set crossRegionVotes' explaining-away logic removed, never inferred
161
+ // from `absorbed`.
162
+ if (td && cross.superseded.size > 0) {
163
+ for (const rv of cross.superseded) {
164
+ const region = td.regions.find((r) => r.span[0] === rv.start && r.span[1] === rv.end);
165
+ if (region)
166
+ region.superseded = true;
167
+ }
168
+ }
169
+ // ──────────────────────────────────────────────────────────────────────
170
+ const cfg = { ...cfg0, N, reachMemo };
171
+ if (allVotes.length === 0) {
172
+ traceAttention(ctx, regions, rvs.voters, [], undefined, td, cfg);
173
+ return { roots: [], ranked: [] };
174
+ }
175
+ const sat = detectSaturated(ctx, regions, rvs.saturated);
176
+ if (td) {
177
+ td.saturation = {
178
+ regionIntervals: sat.intervals.map((iv) => ({ ...iv })),
179
+ hasLeading: sat.hasLeading,
180
+ leadingEnd: sat.leadingEnd,
181
+ };
182
+ }
183
+ const pooled = poolVotes(ctx, allVotes, sat, N, td);
184
+ return commitVotes(ctx, pooled, sat, regions, rvs.voters, N, td, cfg);
185
+ }
186
+ export function collectRegions(ctx, query) {
187
+ const regions = [];
188
+ // A region that DOMINATES the query (covers more than half — the shared
189
+ // {@link dominates} test liftAnswer uses for a span that swallows its
190
+ // surroundings) can never itself discriminate between several topics the
191
+ // query weaves; voting with it only when it is the sole structure (no
192
+ // narrower region exists) keeps a flat/short query's single point of
193
+ // attention intact without letting a broad, non-discriminative wrapper
194
+ // dilute a multi-topic query's vote or masquerade as a genuine second
195
+ // point of attention.
196
+ // foldTree (not walkTree): the same post-order walk, but each node also
197
+ // resolves content-addressed against the store — `known` is what lets the
198
+ // climb keep exact evidence at full weight while margin-damping the
199
+ // approximate kind (see voteRegions). One findLeaf/findBranch per tree
200
+ // node, the same lookups a deposit pays.
201
+ foldTree(ctx, perceive(ctx, query), 0, (n, start, end, node) => {
202
+ if (n.kids === null)
203
+ return;
204
+ if (!dominates(end - start, query.length) || regions.length === 0) {
205
+ regions.push({
206
+ v: n.v,
207
+ start,
208
+ end,
209
+ chunk: isChunk(n),
210
+ known: node !== null,
211
+ });
212
+ }
213
+ });
214
+ return regions;
215
+ }
216
+ export async function voteRegions(ctx, query, regions, k, mode, N, reachMemo, td) {
217
+ const regionSaturated = new Array(regions.length).fill(false);
218
+ const regionVotes = [];
219
+ const regionVoter = ctx.trace ? regions.map(() => null) : [];
220
+ for (let ri = 0; ri < regions.length; ri++) {
221
+ const { v, start, end, chunk, known } = regions[ri];
222
+ // Trace-only bookkeeping for this region — allocated only under `td`
223
+ // (i.e. only when ctx.trace is set); see ConsensusRegionTrace/
224
+ // RegionOutcome (spec §4). `examinedIds` tracks distinct ANN hits
225
+ // whose edgeAncestors reach was actually CONSULTED here (not merely
226
+ // returned by resonate) — the fallback/margin loops below add to it.
227
+ const examinedIds = td ? new Set() : undefined;
228
+ let annQueried = false;
229
+ let fallbackKind;
230
+ const recordRegion = (outcome, extra = {}) => {
231
+ if (!td)
232
+ return;
233
+ td.regions[ri] = {
234
+ index: ri,
235
+ source: ri < td.perceivedCount ? "perceived" : "recognised",
236
+ span: [start, end],
237
+ chunk,
238
+ known,
239
+ canonicalId: canonicalId ?? undefined,
240
+ canonicalUsable,
241
+ canonicalFailed,
242
+ annQueried,
243
+ annHitsReturned: hits ? hits.length : 0,
244
+ annHitsExamined: examinedIds ? examinedIds.size : 0,
245
+ outcome,
246
+ ordinaryVoteProduced: outcome === "voted",
247
+ superseded: false,
248
+ ...extra,
249
+ };
250
+ };
251
+ // EXACT-FIRST: a chunk whose canonical anchor is content-addressed needs
252
+ // no estimator — identity is exact, so its score is 1 BY DEFINITION (the
253
+ // estimated cosine of a form with itself, minus quantisation noise, and
254
+ // the caveat atop geometry.ts forbids trusting the estimate over the
255
+ // exact resolution anyway). The ANN query is deferred behind
256
+ // `ensureHits` and paid only when actually consulted: the orphan
257
+ // fallback, the contrastive margin (approximate regions only), or a
258
+ // region with no usable canonical. On chunk-heavy queries this removes
259
+ // the resonate() call for most exact regions — the single largest
260
+ // remaining inference sink — with the anchor choice unchanged (the
261
+ // canonical branch already ignored hits[0]).
262
+ const canonicalId = chunk
263
+ ? canonicalChunkId(ctx, query.subarray(start, end), N, reachMemo)
264
+ : null;
265
+ const canonicalUsable = canonicalId !== null &&
266
+ (ctx.store.hasParents(canonicalId) ||
267
+ ctx.store.hasContainers(canonicalId));
268
+ let hits = null;
269
+ const ensureHits = async () => {
270
+ if (hits === null) {
271
+ hits = await ctx.store.resonate(v, k);
272
+ annQueried = true;
273
+ }
274
+ return hits;
275
+ };
276
+ const canonicalFailed = chunk && canonicalId === null;
277
+ let voterId;
278
+ let score;
279
+ let scoreId; // the node the score was measured against
280
+ let selectedSource;
281
+ if (canonicalUsable) {
282
+ voterId = canonicalId;
283
+ score = 1;
284
+ scoreId = canonicalId;
285
+ selectedSource = "canonical";
286
+ }
287
+ else {
288
+ const h = await ensureHits();
289
+ if (h.length === 0) {
290
+ recordRegion("no-ann-hit");
291
+ continue;
292
+ }
293
+ voterId = h[0].id;
294
+ score = h[0].score;
295
+ scoreId = h[0].id;
296
+ selectedSource = "ann";
297
+ examinedIds?.add(voterId);
298
+ }
299
+ let reach = edgeAncestors(ctx, voterId, N, reachMemo);
300
+ // A region's vote must not die with the TOP hit: `hits[1..k]` were
301
+ // already fetched, and the top-ranked anchor being a structural orphan
302
+ // (no edge-bearing ancestors) is an accident of the approximate ranking,
303
+ // not evidence the region relates to nothing. Walk the remaining hits —
304
+ // nearest first, climbs memoised — until one climbs. A SATURATED reach
305
+ // is not an orphan: it is a deliberate abstention, kept as-is.
306
+ if (reach.roots.length === 0 && !reach.saturated) {
307
+ for (const h of await ensureHits()) {
308
+ if (h.id === voterId)
309
+ continue;
310
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
311
+ examinedIds?.add(h.id);
312
+ if (r2.saturated || r2.roots.length > 0) {
313
+ 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");
314
+ reach = r2;
315
+ voterId = h.id;
316
+ score = h.score;
317
+ scoreId = h.id;
318
+ selectedSource = "ann";
319
+ fallbackKind = "orphan";
320
+ break;
321
+ }
322
+ }
323
+ }
324
+ else if (!canonicalUsable && reach.saturated) {
325
+ // TIE-BAND saturation fallback. A saturated top hit abstains the whole
326
+ // region (a hub's reach concludes nothing) — but the hub may only CLAIM
327
+ // that abstention when it is DISTINGUISHABLY the nearest anchor. The
328
+ // resonance ranking is an estimate: the difference between two scores
329
+ // against the same query carries √2× the estimator's per-score error,
330
+ // ≈ 1/√D ({@link estimatorNoise}) — so any hit within that band of the
331
+ // top is the SAME rank at measurement resolution, and letting the hub
332
+ // win the tie decides the region by quantisation accident (observed:
333
+ // a 0.1σ rank inversion flipped a pinned behaviour when the query
334
+ // estimator sharpened from 4 to 8 bits). Walk the tied hits, nearest
335
+ // first; the first that climbs somewhere non-saturated votes for the
336
+ // region. Beyond the band the hub is genuinely nearest and its
337
+ // abstention stands. A KNOWN (content-addressed) region never enters:
338
+ // its anchor is exact, not an estimate.
339
+ const band = estimatorNoise(ctx.store.D);
340
+ for (const h of await ensureHits()) {
341
+ if (h.id === voterId)
342
+ continue;
343
+ if (h.score < score - band)
344
+ break; // hits are nearest-first
345
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
346
+ examinedIds?.add(h.id);
347
+ if (!r2.saturated && r2.roots.length > 0) {
348
+ 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");
349
+ reach = r2;
350
+ voterId = h.id;
351
+ score = h.score;
352
+ scoreId = h.id;
353
+ selectedSource = "ann";
354
+ fallbackKind = "saturated-tie";
355
+ break;
356
+ }
357
+ }
358
+ }
359
+ regionSaturated[ri] = reach.saturated;
360
+ const selected = !td
361
+ ? undefined
362
+ : (() => {
363
+ const rank = selectedSource === "ann"
364
+ ? hits?.findIndex((h) => h.id === voterId)
365
+ : undefined;
366
+ return {
367
+ source: selectedSource,
368
+ node: voterId,
369
+ score,
370
+ ...(rank !== undefined ? { rank } : {}),
371
+ ...(fallbackKind ? { fallback: fallbackKind } : {}),
372
+ };
373
+ })();
374
+ if (reach.roots.length === 0) {
375
+ recordRegion("no-structural-reach", { selected, reachNode: voterId });
376
+ continue;
377
+ }
378
+ if (reach.saturated) {
379
+ recordRegion("saturated-abstention", { selected, reachNode: voterId });
380
+ continue;
381
+ }
382
+ // One IDF per region — dfWeight() and the focus weight used to compute
383
+ // the same logarithm independently.
384
+ const idf = Math.log(N / Math.max(1, reach.contextsReached));
385
+ const df = Math.log(1 + reach.contextsReached);
386
+ const wf = mode === "direct" ? df : mode === "combined" ? idf + df : idf;
387
+ if (wf <= 0) {
388
+ recordRegion("nonpositive-df-weight", {
389
+ selected,
390
+ reachNode: voterId,
391
+ idf,
392
+ dfWeight: wf,
393
+ });
394
+ continue;
395
+ }
396
+ // CONTRASTIVE-MARGIN GATE — the compensation the linear (byte-proportional)
397
+ // fold demands, applied to APPROXIMATE evidence only. Under the linear
398
+ // fold a resonance score reads "fraction of aligned shared bytes", so a
399
+ // NOVEL span sharing a frame with several stored exemplars scores high
400
+ // against each of them without being evidence of ANY of them: the shared
401
+ // scaffolding, not the span's own content, carries the similarity. Such a
402
+ // frame region resonates ~equally to every framed exemplar, so its top hit
403
+ // barely beats the best DIFFERENT-conclusion rival (a different climb
404
+ // root-set) — its discriminative margin, score MINUS that rival, collapses
405
+ // toward zero. A region votes only when that margin clears the estimator's
406
+ // own noise floor (1/√D — see {@link estimatorNoise}); below it the margin
407
+ // is quantisation noise, not evidence. A KNOWN region (content-addressed,
408
+ // exact) skips the contrast: it IS learnt content, not an approximation.
409
+ //
410
+ // The margin GATES; it does NOT scale the weight. A surviving region votes
411
+ // at its genuine strength (score²·wf) — the SAME scale {@link
412
+ // consensusFloor} is derived for. Using the margin as a MULTIPLIER
413
+ // (score·margin) conflated "discriminative" with "strong": a genuinely
414
+ // discriminative span whose frame-rival happened to score close got a tiny
415
+ // vote, systematically compressing correct scaffolding-dominated groundings
416
+ // (reordered / paraphrased queries) below the floor so they grounded
417
+ // nothing. Gating at the noise floor keeps frame-echo suppression (a frame
418
+ // region's margin ≈ 0 is gated out) without penalising honest evidence.
419
+ let contrastiveMargin;
420
+ let contrastiveRival;
421
+ if (!known) {
422
+ let margin = score;
423
+ const hitsForRival = await ensureHits();
424
+ for (let hi = 0; hi < hitsForRival.length; hi++) {
425
+ const h = hitsForRival[hi];
426
+ if (h.id === voterId)
427
+ continue;
428
+ const r2 = edgeAncestors(ctx, h.id, N, reachMemo);
429
+ examinedIds?.add(h.id);
430
+ if (r2.saturated || r2.roots.length === 0)
431
+ continue; // concludes nothing
432
+ if (sameRoots(r2.roots, reach.roots))
433
+ continue; // same conclusion
434
+ margin = score - h.score; // hits are nearest-first: the best rival
435
+ if (td) {
436
+ contrastiveRival = { node: h.id, rank: hi, score: h.score };
437
+ }
438
+ break;
439
+ }
440
+ contrastiveMargin = margin;
441
+ const noiseFloor = estimatorNoise(ctx.store.D);
442
+ if (margin <= noiseFloor) {
443
+ recordRegion("contrastive-margin-rejection", {
444
+ selected,
445
+ reachNode: voterId,
446
+ idf,
447
+ dfWeight: wf,
448
+ contrastiveMargin: margin,
449
+ contrastiveNoiseFloor: noiseFloor,
450
+ ...(contrastiveRival ? { contrastiveRival } : {}),
451
+ });
452
+ continue;
453
+ }
454
+ }
455
+ // MUTUAL-EXPLANATION WEIGHT (angle + magnitude). Under the linear fold
456
+ // cos = shared/(‖r‖·‖h‖) with ‖·‖² = content bytes, so the old score²
457
+ // was already — implicitly — (shared/len_r)·(shared/len_h): the fraction
458
+ // of the REGION the hit explains times the fraction of the HIT the
459
+ // region pins down. Made explicit, each factor is computed from the two
460
+ // magnitudes (the region's own span; the hit's, read from the store —
461
+ // contentLen, √bytes being the linear fold's gist norm) and CAPPED at 1:
462
+ // the estimated cosine can imply more shared content than the smaller
463
+ // side even holds, and the uncapped square silently credited that
464
+ // impossible surplus — a small region echoing inside a large context, or
465
+ // the reverse, voted above its physical evidence. In the uncapped
466
+ // regime this is exactly score², the scale {@link consensusFloor} is
467
+ // derived for. (The margin gate above deliberately stays in raw cosine
468
+ // units: it tests the ESTIMATOR's noise floor, which lives in cosine
469
+ // space; converting each side by its own hit's magnitude would compare
470
+ // noise floors of different scales.)
471
+ const lenR = Math.max(1, end - start);
472
+ // Cap the magnitude read at lenR·D: past it s/ratio ≤ s/√D — below the
473
+ // estimator's own noise floor — so the mutual weight is ~0 regardless
474
+ // and the clamped value yields exactly that; no full walk of a huge hit.
475
+ const ratio = Math.sqrt(Math.max(1, ctx.store.contentLen(scoreId, lenR * ctx.store.D)) / lenR);
476
+ const mutual = Math.min(1, score * ratio) * Math.min(1, score / ratio);
477
+ const w = (mutual * wf) / reach.roots.length;
478
+ const wFocus = (mutual * idf) / reach.roots.length;
479
+ regionVotes.push({
480
+ start,
481
+ end,
482
+ canonicalFailed,
483
+ roots: reach.roots,
484
+ w,
485
+ wFocus,
486
+ });
487
+ if (ctx.trace) {
488
+ regionVoter[ri] = { id: voterId, score, w: wf };
489
+ }
490
+ recordRegion("voted", {
491
+ selected,
492
+ reachNode: voterId,
493
+ idf,
494
+ dfWeight: wf,
495
+ ...(contrastiveMargin !== undefined
496
+ ? {
497
+ contrastiveMargin,
498
+ contrastiveNoiseFloor: estimatorNoise(ctx.store.D),
499
+ ...(contrastiveRival ? { contrastiveRival } : {}),
500
+ }
501
+ : {}),
502
+ mutualWeight: mutual,
503
+ voteWeightPerRoot: w,
504
+ focusWeightPerRoot: wFocus,
505
+ });
506
+ }
507
+ return {
508
+ votes: regionVotes,
509
+ saturated: regionSaturated,
510
+ voters: regionVoter,
511
+ };
512
+ }
513
+ /** The consensus vote as EVIDENCE POOLING, not shortest path: each surviving
514
+ * region is an axiom; it contributes to every root it climbed to (or, for a
515
+ * terminal answer node, to the contexts that lead to it) by a `combine:
516
+ * "sum"` rule, so independent regions corroborating the same anchor ADD
517
+ * rather than compete to be the cheapest route (see {@link Rule.combine} in
518
+ * derive/src/deduction.ts). Run through the very engine {@link
519
+ * GraphSearch} covers with — `lightestDerivation` — so a pooled-evidence
520
+ * decision is, like a followed edge or a spliced connector, one weighted
521
+ * rule of the SAME deduction system, not a separate hand-rolled tally that
522
+ * merely logs alongside it. `votesIdf`/`support` are the same two
523
+ * read-outs {@link commitVotes} always gated on; only how they accumulate
524
+ * changed. */
525
+ export function poolVotes(ctx, regionVotes, sat, N, td) {
526
+ const eligible = [];
527
+ for (let ri = 0; ri < regionVotes.length; ri++) {
528
+ const rv = regionVotes[ri];
529
+ if (rv.canonicalFailed &&
530
+ sat.intervals.some((iv) => rv.start >= iv.start && rv.end <= iv.end)) {
531
+ continue;
532
+ }
533
+ eligible.push(ri);
534
+ }
535
+ if (td) {
536
+ td.pooling = {
537
+ inputVotes: regionVotes.length,
538
+ eligibleVotes: eligible.length,
539
+ saturationMaskedVotes: regionVotes.length - eligible.length,
540
+ };
541
+ }
542
+ const key = (it) => it.kind === "region"
543
+ ? `r${it.ri}`
544
+ : it.kind === "anchor"
545
+ ? `a${it.id}`
546
+ : `x${it.id}`;
547
+ const pool = new Map();
548
+ const system = {
549
+ key,
550
+ *axioms() {
551
+ for (const ri of eligible) {
552
+ yield { item: { kind: "region", ri }, cost: 0 };
553
+ }
554
+ },
555
+ isGoal: () => false, // exhaust every axiom; there is no single goal to stop at
556
+ // Every region axiom ties at cost 0, so the agenda's pop order among them
557
+ // is otherwise unspecified; ordering by `ri` here only steers the HEAP
558
+ // (never added to a stored cost — see relax's use of h) so pooling fires
559
+ // in exactly the regionVotes array order the original loop used, byte-for-
560
+ // byte reproducing its accumulation and tie-break order.
561
+ heuristic: (it) => it.kind === "region" ? it.ri : 0,
562
+ *rules(it) {
563
+ if (it.kind !== "region")
564
+ return;
565
+ const rv = regionVotes[it.ri];
566
+ // The same hub bound the rest of the system uses (edgeAncestors' parent
567
+ // cutoff, chooseNext's candidate cap): a terminal answer followed by
568
+ // more than √N contexts is a non-discriminative hub — spreading a
569
+ // region's vote across its FULL corpus-sized fan-in yields O(corpus)
570
+ // rule applications per region and near-zero per-target weight anyway.
571
+ // Cap the redistribution at the first √N contexts (insertion order,
572
+ // the same convention chooseNext caps by).
573
+ const hubBound = Math.ceil(Math.sqrt(N));
574
+ for (const r of rv.roots) {
575
+ // CAPPED read: only the first hubBound targets are ever credited, so
576
+ // only they are read — a common continuation's full reverse fan-in
577
+ // is corpus-sized and is never materialised.
578
+ const pv = ctx.store.prevFirst(r, hubBound);
579
+ const isAnswer = pv.length > 0 && !ctx.store.hasNext(r);
580
+ const targets = isAnswer ? pv : [r];
581
+ for (const t of targets) {
582
+ yield {
583
+ premises: [it],
584
+ conclusion: { kind: "anchor", id: t },
585
+ cost: rv.w / targets.length,
586
+ combine: "sum",
587
+ };
588
+ yield {
589
+ premises: [it],
590
+ conclusion: { kind: "anchorFocus", id: t },
591
+ cost: rv.wFocus / targets.length,
592
+ combine: "sum",
593
+ };
594
+ }
595
+ }
596
+ },
597
+ pool,
598
+ };
599
+ lightestDerivation(system);
600
+ const votes = new Map();
601
+ const votesIdf = new Map();
602
+ const support = new Map();
603
+ const regionSupport = new Map();
604
+ const regionSpans = new Map();
605
+ const steps = [];
606
+ let order = 0;
607
+ for (const pc of pool.values()) {
608
+ if (pc.item.kind === "anchor") {
609
+ votes.set(pc.item.id, pc.cost);
610
+ const premises = [];
611
+ const seenRi = new Set();
612
+ let breadthSum = 0;
613
+ const spans = [];
614
+ for (const c of pc.contributions) {
615
+ const p0 = c.premises[0].item;
616
+ if (p0.kind !== "region" || seenRi.has(p0.ri))
617
+ continue;
618
+ seenRi.add(p0.ri);
619
+ const rv = regionVotes[p0.ri];
620
+ breadthSum += rv.absorbed ?? 1;
621
+ premises.push({ kind: "form", span: [rv.start, rv.end] });
622
+ spans.push([rv.start, rv.end]);
623
+ }
624
+ regionSupport.set(pc.item.id, breadthSum);
625
+ regionSpans.set(pc.item.id, spans);
626
+ steps.push({
627
+ order: order++,
628
+ move: "pool-vote",
629
+ premises,
630
+ conclusion: { kind: "form", span: [-1, -1], node: pc.item.id },
631
+ cost: pc.cost,
632
+ producers: [],
633
+ });
634
+ }
635
+ else if (pc.item.kind === "anchorFocus") {
636
+ votesIdf.set(pc.item.id, pc.cost);
637
+ let bestRv = null;
638
+ for (const c of pc.contributions) {
639
+ const p0 = c.premises[0].item;
640
+ if (p0.kind !== "region")
641
+ continue;
642
+ const rv = regionVotes[p0.ri];
643
+ if (!bestRv || rv.wFocus > bestRv.wFocus)
644
+ bestRv = rv;
645
+ }
646
+ if (bestRv) {
647
+ support.set(pc.item.id, {
648
+ start: bestRv.start,
649
+ end: bestRv.end,
650
+ w: bestRv.wFocus,
651
+ });
652
+ }
653
+ }
654
+ }
655
+ return { votes, votesIdf, support, regionSupport, regionSpans, steps };
656
+ }
657
+ /** The number of DISTINCT clusters a root's contributing regions form —
658
+ * see Attention.clusters. Two regions belong to the same cluster iff the
659
+ * gap between them is strictly less than one river-fold quantum W: at
660
+ * that distance there is no room for a genuinely separate, independently
661
+ * perceivable unit of content between them (the same "smallest meaningful
662
+ * distinction" quantum {@link reachThreshold}'s own doc invokes). A gap
663
+ * of a full quantum or more means real, separate structure could sit
664
+ * between the two spans, so they count as independent corroboration.
665
+ * Strict `<` (not `<=`): verified against gap 3.1's own "gender equality"
666
+ * root, whose two genuine clusters sit EXACTLY W bytes apart — `<= W`
667
+ * would wrongly merge them into one and break that pinned requirement. */
668
+ function countClusters(spans, W) {
669
+ if (spans.length === 0)
670
+ return 0;
671
+ const sorted = [...spans].sort((a, b) => a[0] - b[0]);
672
+ let clusters = 1;
673
+ let curEnd = sorted[0][1];
674
+ for (let i = 1; i < sorted.length; i++) {
675
+ const [s, e] = sorted[i];
676
+ if (s - curEnd < W) {
677
+ curEnd = Math.max(curEnd, e);
678
+ }
679
+ else {
680
+ clusters++;
681
+ curEnd = e;
682
+ }
683
+ }
684
+ return clusters;
685
+ }
686
+ export function commitVotes(ctx, pooled, sat, regions, regionVoter, N, td, cfg) {
687
+ const { votes, votesIdf, support, regionSupport, regionSpans, steps } = pooled;
688
+ if (votes.size === 0) {
689
+ traceAttention(ctx, regions, regionVoter, [], steps, td, cfg);
690
+ return { roots: [], ranked: [] };
691
+ }
692
+ // SCALE-INVARIANT confidence — see Attention.breadth's doc. regions.length
693
+ // is the query's OWN full candidate count (most never vote at all), the
694
+ // same denominator the "N of M sub-regions voted" rationale text already
695
+ // reports; regionSupport is that same accounting read PER ANCHOR.
696
+ const totalRegions = Math.max(1, regions.length);
697
+ const ranked = [...votes.entries()]
698
+ .map(([anchor, vote]) => {
699
+ const s = support.get(anchor);
700
+ return {
701
+ anchor,
702
+ vote,
703
+ start: s.start,
704
+ end: s.end,
705
+ breadth: (regionSupport.get(anchor) ?? 0) / totalRegions,
706
+ clusters: countClusters(regionSpans.get(anchor) ?? [], ctx.space.maxGroup),
707
+ };
708
+ })
709
+ .sort((a, b) => b.vote - a.vote);
710
+ const overlaps = (a, b) => a.start < b.end && b.start < a.end;
711
+ const idfDesc = [...votesIdf.values()].sort((a, b) => b - a);
712
+ const rootCut = naturalBreak(idfDesc);
713
+ // A FURTHER point of attention (beyond the dominant one, which always
714
+ // grounds) must clear the same absolute significance floor
715
+ // recallByResonance trusts a climb anchor with — log(N) + 1/2, three-ish
716
+ // halvings of confidence above pure chance at this corpus scale — not
717
+ // merely beat whatever its immediate neighbour in the ratio happens to be.
718
+ // Without it, naturalBreak's ratio is scale-free but not FLOOR-free: on a
719
+ // large, topic-diverse corpus the steepest ratio in a long noise tail can
720
+ // sit far below any real signal, admitting scaffolding echoes as if they
721
+ // were genuine further topics.
722
+ const floor = consensusFloor(N);
723
+ const placed = [];
724
+ const roots = [];
725
+ const recordAnchor = (point, rank, status, dominant, passesNaturalBreak, passesConsensusFloor, pastLeadingSaturation, rejectionReasons) => {
726
+ if (!td)
727
+ return;
728
+ td.anchors.push({
729
+ anchor: point.anchor,
730
+ rank,
731
+ pooledVote: point.vote,
732
+ idfVote: votesIdf.get(point.anchor) ?? 0,
733
+ candidateBreadth: regions.length,
734
+ contributingVotes: regionSpans.get(point.anchor)?.length ?? 0,
735
+ contributingEvidence: regionSupport.get(point.anchor) ?? 0,
736
+ breadth: point.breadth,
737
+ contributingSpans: regionSpans.get(point.anchor) ?? [],
738
+ clusters: point.clusters,
739
+ commit: {
740
+ status,
741
+ dominant,
742
+ passesNaturalBreak,
743
+ passesConsensusFloor,
744
+ pastLeadingSaturation,
745
+ rejectionReasons,
746
+ },
747
+ });
748
+ };
749
+ for (let rank = 0; rank < ranked.length; rank++) {
750
+ const point = ranked[rank];
751
+ const absorbed = placed.some((p) => overlaps(point, p));
752
+ // Commit decisions are recorded LIVE, inside this loop, in the exact
753
+ // shape the gates below apply them — never reconstructed afterward from
754
+ // the final `roots` (spec §8's explicit requirement).
755
+ let status;
756
+ let dominant = false;
757
+ let passesNaturalBreak;
758
+ let passesConsensusFloor;
759
+ let pastLeadingSaturation;
760
+ const rejectionReasons = [];
761
+ if (absorbed) {
762
+ status = "overlap";
763
+ }
764
+ else {
765
+ const pastLeading = !sat.hasLeading ||
766
+ roots.length === 0 || point.start >= sat.leadingEnd;
767
+ pastLeadingSaturation = pastLeading;
768
+ const vote = votesIdf.get(point.anchor) ?? 0;
769
+ if (roots.length === 0) {
770
+ // The first non-overlapping root is DOMINANT and bypasses the two
771
+ // vote thresholds (it always grounds) — only the leading-saturation
772
+ // gate still applies to it.
773
+ dominant = true;
774
+ if (pastLeading) {
775
+ status = "root";
776
+ }
777
+ else {
778
+ status = "rejected";
779
+ rejectionReasons.push("leading-saturation");
780
+ }
781
+ }
782
+ else {
783
+ passesNaturalBreak = vote >= rootCut;
784
+ passesConsensusFloor = vote >= floor;
785
+ if (passesNaturalBreak && passesConsensusFloor && pastLeading) {
786
+ status = "root";
787
+ }
788
+ else {
789
+ status = "rejected";
790
+ if (!passesNaturalBreak)
791
+ rejectionReasons.push("below-natural-break");
792
+ if (!passesConsensusFloor) {
793
+ rejectionReasons.push("below-consensus-floor");
794
+ }
795
+ if (!pastLeading)
796
+ rejectionReasons.push("leading-saturation");
797
+ }
798
+ }
799
+ if (status === "root") {
800
+ roots.push(point);
801
+ }
802
+ else {
803
+ recordAnchor(point, rank, status, dominant, passesNaturalBreak, passesConsensusFloor, pastLeadingSaturation, rejectionReasons);
804
+ continue;
805
+ }
806
+ }
807
+ recordAnchor(point, rank, status, dominant, passesNaturalBreak, passesConsensusFloor, pastLeadingSaturation, rejectionReasons);
808
+ placed.push(point);
809
+ }
810
+ traceAttention(ctx, regions, regionVoter, roots, steps, td, cfg ? { ...cfg, naturalBreak: rootCut, consensusFloor: floor } : undefined, ranked);
811
+ return { roots, ranked };
812
+ }
813
+ export function detectSaturated(ctx, regions, saturated) {
814
+ // Intervals are built from CHUNK regions only. collectRegions emits the
815
+ // tree in POST-ORDER — a parent region arrives AFTER its children and
816
+ // shares its first child's `start` — so the raw array is not monotone in
817
+ // byte position, and a saturated parent would fuse with a later saturated
818
+ // chunk into an interval swallowing a NON-saturated child. Chunk regions
819
+ // (leaf-parents) are disjoint and already in byte order, and saturation
820
+ // masking exists to drop canonicalFailed CHUNK votes (see poolVotes), so
821
+ // chunks are both the sufficient and the safe basis. A region without a
822
+ // `chunk` flag (a bare {start,end} from a direct caller) is treated as a
823
+ // chunk.
824
+ const intervals = [];
825
+ let intStart = -1;
826
+ let intEnd = -1;
827
+ let totalLen = 0;
828
+ for (let ri = 0; ri < regions.length; ri++) {
829
+ const r = regions[ri];
830
+ totalLen = Math.max(totalLen, r.end);
831
+ if (r.chunk === false)
832
+ continue;
833
+ if (saturated[ri]) {
834
+ if (intStart === -1)
835
+ intStart = r.start;
836
+ intEnd = r.end;
837
+ }
838
+ else {
839
+ if (intStart !== -1) {
840
+ intervals.push({ start: intStart, end: intEnd });
841
+ intStart = -1;
842
+ }
843
+ }
844
+ }
845
+ if (intStart !== -1) {
846
+ intervals.push({ start: intStart, end: intEnd });
847
+ }
848
+ const leading = intervals.length > 0 && intervals[0].start === 0
849
+ ? intervals[0]
850
+ : null;
851
+ const hasLeading = leading !== null &&
852
+ leading.end >= ctx.space.maxGroup &&
853
+ leading.end < totalLen;
854
+ const leadingEnd = leading !== null ? leading.end : 0;
855
+ return { leadingEnd, hasLeading, intervals };
856
+ }
857
+ /** Set equality of two climb root lists (the "same conclusion" test the
858
+ * contrastive margin skips rivals by). */
859
+ function sameRoots(a, b) {
860
+ if (a.length !== b.length)
861
+ return false;
862
+ const s = new Set(a);
863
+ for (const x of b)
864
+ if (!s.has(x))
865
+ return false;
866
+ return true;
867
+ }
868
+ export function canonicalChunkId(ctx, regionBytes, N, reachMemo) {
869
+ const len = Math.min(regionBytes.length, ctx.space.maxGroup);
870
+ for (let off = 0; off + len <= regionBytes.length; off++) {
871
+ const ids = leafIdRun(ctx, regionBytes, off, off + len);
872
+ if (ids === null)
873
+ return null;
874
+ const flatId = ctx.store.findBranch(ids);
875
+ if (flatId === null)
876
+ continue;
877
+ if (len < 2)
878
+ return flatId;
879
+ let bestId = flatId;
880
+ let bestReach = edgeAncestors(ctx, flatId, N, reachMemo);
881
+ for (let k2 = 1; k2 < len; k2++) {
882
+ const shortIds = ids.slice(0, len - k2);
883
+ const shortId = ctx.store.findBranch(shortIds);
884
+ if (shortId === null)
885
+ continue;
886
+ const shortReach = edgeAncestors(ctx, shortId, N, reachMemo);
887
+ if (shortReach.saturated ||
888
+ shortReach.contextsReached > bestReach.contextsReached) {
889
+ bestId = shortId;
890
+ bestReach = shortReach;
891
+ }
892
+ }
893
+ return bestId;
894
+ }
895
+ return null;
896
+ }
897
+ export function naturalBreak(votes) {
898
+ if (votes.length <= 1)
899
+ return votes[0] ?? 0;
900
+ let breakAt = 1;
901
+ let steepest = Infinity;
902
+ for (let i = 1; i < votes.length; i++) {
903
+ if (votes[i - 1] <= 0)
904
+ break;
905
+ const ratio = votes[i] / votes[i - 1];
906
+ if (ratio < steepest) {
907
+ steepest = ratio;
908
+ breakAt = i;
909
+ }
910
+ }
911
+ return votes[breakAt - 1];
912
+ }
913
+ const VARIANT_KIND_ORDER = {
914
+ "exact-exact": -1,
915
+ "left-synonym": 0,
916
+ "right-synonym": 1,
917
+ "double-synonym": 2,
918
+ };
919
+ /** Same deterministic ordering the old implementation applied to already-
920
+ * materialized variants (§8): semantic confidence desc, then kind
921
+ * (left-synonym, right-synonym, double-synonym), then sibling ids asc. */
922
+ function compareStructuralVariantSpecs(a, b) {
923
+ return b.semanticConfidence - a.semanticConfidence ||
924
+ VARIANT_KIND_ORDER[a.kind] - VARIANT_KIND_ORDER[b.kind] ||
925
+ (a.leftSiblingId ?? -1) - (b.leftSiblingId ?? -1) ||
926
+ (a.rightSiblingId ?? -1) - (b.rightSiblingId ?? -1);
927
+ }
928
+ /** Every single- and double-synonym combination, as cost-free descriptors —
929
+ * no `read`, `gistOf`, `perceive` or `StructuralPart` allocation. Both
930
+ * sibling lists are already bounded by `haloQueryK`, so the O(haloQueryK²)
931
+ * cross-product here is cheap; only the SELECTED specs go on to pay for
932
+ * sibling reconstruction. */
933
+ function buildStructuralVariantSpecs(sides) {
934
+ const specs = [];
935
+ for (const left of sides.leftSiblings) {
936
+ specs.push({
937
+ kind: "left-synonym",
938
+ semanticConfidence: left.score,
939
+ leftSiblingId: left.id,
940
+ });
941
+ }
942
+ for (const right of sides.rightSiblings) {
943
+ specs.push({
944
+ kind: "right-synonym",
945
+ semanticConfidence: right.score,
946
+ rightSiblingId: right.id,
947
+ });
948
+ }
949
+ for (const left of sides.leftSiblings) {
950
+ for (const right of sides.rightSiblings) {
951
+ specs.push({
952
+ kind: "double-synonym",
953
+ semanticConfidence: Math.min(left.score, right.score),
954
+ leftSiblingId: left.id,
955
+ rightSiblingId: right.id,
956
+ });
957
+ }
958
+ }
959
+ specs.sort(compareStructuralVariantSpecs);
960
+ return specs;
961
+ }
962
+ /** A halo sibling's structural gist, bounded to `maxBytes` of stored content
963
+ * and reused across the whole climb. `positiveMemo` (shared across every
964
+ * probe in the climb, passed in by the caller) remembers only successfully
965
+ * reconstructed complete gists — a sibling rejected here for being too
966
+ * large for THIS pair's phrase-scale bound may still be admissible for a
967
+ * larger-spanning pair later, so a rejection is never memoized globally.
968
+ * `localMemo` is scoped to one `buildStructuralVariants` call, where every
969
+ * variant shares the same bound, so a `null` there is safe to reuse. */
970
+ function loadBoundedSiblingGist(ctx, id, maxBytes, positiveMemo, localMemo) {
971
+ if (localMemo.has(id)) {
972
+ return localMemo.get(id) ?? null;
973
+ }
974
+ const cached = positiveMemo.get(id);
975
+ if (cached !== undefined) {
976
+ localMemo.set(id, cached);
977
+ return cached;
978
+ }
979
+ const length = ctx.store.contentLen(id, maxBytes + 1);
980
+ if (length <= 0 || length > maxBytes) {
981
+ localMemo.set(id, null);
982
+ return null;
983
+ }
984
+ const bytes = read(ctx, id, maxBytes + 1);
985
+ if (bytes.length === 0 || bytes.length > maxBytes) {
986
+ localMemo.set(id, null);
987
+ return null;
988
+ }
989
+ const gist = gistOf(ctx, bytes);
990
+ positiveMemo.set(id, gist);
991
+ localMemo.set(id, gist);
992
+ return gist;
993
+ }
994
+ /** Build, bound and order every mandatory structural variant (§7-8): the
995
+ * exact/exact composition is always kept; up to `ctx.cfg.haloQueryK`
996
+ * synonym variants (single- and double-synonym combined, one shared
997
+ * budget) are appended, ordered by confidence, then kind, then sibling id.
998
+ * Variant selection is entirely lightweight (see {@link
999
+ * buildStructuralVariantSpecs}); a sibling's bytes are read and perceived
1000
+ * only for specs actually retained, and at most once per sibling id per
1001
+ * climb via `siblingGistMemo`. */
1002
+ export function buildStructuralVariants(ctx, ra, rb, sides, siblingGistMemo) {
1003
+ const leftLen = ra.end - ra.start;
1004
+ const rightLen = rb.end - rb.start;
1005
+ const exactLeft = { v: ra.v, len: leftLen };
1006
+ const exactRight = { v: rb.v, len: rightLen };
1007
+ const variants = [
1008
+ {
1009
+ left: exactLeft,
1010
+ right: exactRight,
1011
+ kind: "exact-exact",
1012
+ semanticConfidence: 1,
1013
+ },
1014
+ ];
1015
+ // Same phrase-scale bound the cross-region junction ladder uses
1016
+ // (`maxInterior`): a sibling whose complete stored content exceeds it is
1017
+ // not materialized as a structural-resonance endpoint, keeping sibling
1018
+ // reconstruction phrase-scale even for a large deposit or conversation
1019
+ // root that merely appeared in a halo result.
1020
+ const maxSiblingBytes = (leftLen + rightLen) * ctx.space.maxGroup;
1021
+ const specs = buildStructuralVariantSpecs(sides);
1022
+ const localGistMemo = new Map();
1023
+ let retainedSynonyms = 0;
1024
+ for (const spec of specs) {
1025
+ if (retainedSynonyms >= ctx.cfg.haloQueryK)
1026
+ break;
1027
+ let left = exactLeft;
1028
+ let right = exactRight;
1029
+ if (spec.leftSiblingId !== undefined) {
1030
+ const gist = loadBoundedSiblingGist(ctx, spec.leftSiblingId, maxSiblingBytes, siblingGistMemo, localGistMemo);
1031
+ if (gist === null)
1032
+ continue;
1033
+ left = { v: gist, len: leftLen };
1034
+ }
1035
+ if (spec.rightSiblingId !== undefined) {
1036
+ const gist = loadBoundedSiblingGist(ctx, spec.rightSiblingId, maxSiblingBytes, siblingGistMemo, localGistMemo);
1037
+ if (gist === null)
1038
+ continue;
1039
+ right = { v: gist, len: rightLen };
1040
+ }
1041
+ variants.push({
1042
+ left,
1043
+ right,
1044
+ kind: spec.kind,
1045
+ semanticConfidence: spec.semanticConfidence,
1046
+ leftSiblingId: spec.leftSiblingId,
1047
+ rightSiblingId: spec.rightSiblingId,
1048
+ });
1049
+ retainedSynonyms++;
1050
+ }
1051
+ return { variants, exactLeft, exactRight };
1052
+ }
1053
+ /** Deterministic best-of tie-break for two proposals ranked for the SAME
1054
+ * candidate id — effectiveScore, then annScore, then semanticConfidence,
1055
+ * then variant kind, then sibling ids (§10). */
1056
+ function betterProposal(a, b) {
1057
+ if (a.effectiveScore !== b.effectiveScore) {
1058
+ return a.effectiveScore > b.effectiveScore;
1059
+ }
1060
+ if (a.annScore !== b.annScore)
1061
+ return a.annScore > b.annScore;
1062
+ if (a.semanticConfidence !== b.semanticConfidence) {
1063
+ return a.semanticConfidence > b.semanticConfidence;
1064
+ }
1065
+ if (VARIANT_KIND_ORDER[a.variant] !== VARIANT_KIND_ORDER[b.variant]) {
1066
+ return VARIANT_KIND_ORDER[a.variant] < VARIANT_KIND_ORDER[b.variant];
1067
+ }
1068
+ if ((a.leftSiblingId ?? -1) !== (b.leftSiblingId ?? -1)) {
1069
+ return (a.leftSiblingId ?? -1) < (b.leftSiblingId ?? -1);
1070
+ }
1071
+ return (a.rightSiblingId ?? -1) < (b.rightSiblingId ?? -1);
1072
+ }
1073
+ /** The final approximate tier: compose every retained structural variant,
1074
+ * ANN-query each, merge proposals by candidate id, and validate the winner
1075
+ * through the SAME structural gates every other tier answers to (saturation,
1076
+ * roots, IDF, contrastive margin). Returns null when nothing survives. */
1077
+ export async function structuralResonance(ctx, query, ra, rb, sides, siblingGistMemo, k, N, reachMemo,
1078
+ /** Each side's OWN individual climb roots (from voteRegions), when it cast
1079
+ * one — the self-evidence backstop structural-resonance needs and the
1080
+ * exact tier gets for free from literal byte containment (§11's whole
1081
+ * premise: recover a JOINT context neither side votes for alone). A
1082
+ * candidate whose reach is exactly one side's own conclusion is not new
1083
+ * evidence of a joint whole; it is that side's resonance rediscovering
1084
+ * itself through a synthetic gist still dominated by its own direction. */
1085
+ ownRootsA, ownRootsB, trace) {
1086
+ const { variants } = buildStructuralVariants(ctx, ra, rb, sides, siblingGistMemo);
1087
+ if (trace)
1088
+ trace.variantBudget = ctx.cfg.haloQueryK;
1089
+ const middleBytes = query.subarray(ra.end, rb.start);
1090
+ const middlePart = middleBytes.length === 0
1091
+ ? null
1092
+ : { v: perceive(ctx, middleBytes).v, len: middleBytes.length };
1093
+ const proposals = new Map();
1094
+ for (const variant of variants) {
1095
+ const parts = [variant.left];
1096
+ if (middlePart)
1097
+ parts.push(middlePart);
1098
+ parts.push(variant.right);
1099
+ const synthetic = composeStructuralGist(ctx.space, parts);
1100
+ const hits = await ctx.store.resonate(synthetic, k);
1101
+ if (trace) {
1102
+ trace.variants.push({
1103
+ kind: variant.kind,
1104
+ semanticConfidence: variant.semanticConfidence,
1105
+ leftSiblingId: variant.leftSiblingId,
1106
+ rightSiblingId: variant.rightSiblingId,
1107
+ annHitsReturned: hits.length,
1108
+ });
1109
+ }
1110
+ for (const hit of hits) {
1111
+ const candidate = {
1112
+ id: hit.id,
1113
+ annScore: hit.score,
1114
+ semanticConfidence: variant.semanticConfidence,
1115
+ effectiveScore: hit.score * variant.semanticConfidence,
1116
+ variant: variant.kind,
1117
+ leftSiblingId: variant.leftSiblingId,
1118
+ rightSiblingId: variant.rightSiblingId,
1119
+ };
1120
+ const prev = proposals.get(hit.id);
1121
+ if (prev === undefined || betterProposal(candidate, prev)) {
1122
+ proposals.set(hit.id, candidate);
1123
+ }
1124
+ }
1125
+ }
1126
+ if (trace)
1127
+ trace.mergedProposals = proposals.size;
1128
+ if (proposals.size === 0) {
1129
+ if (trace) {
1130
+ trace.noiseFloor = estimatorNoise(ctx.store.D);
1131
+ trace.outcome = "empty";
1132
+ }
1133
+ return null;
1134
+ }
1135
+ const sorted = [...proposals.values()].sort((a, b) => b.effectiveScore - a.effectiveScore || a.id - b.id);
1136
+ // One shared shape for every `examined` entry (spec §5): only `outcome`
1137
+ // varies across the six exit points below, so build it once instead of
1138
+ // repeating the six-field literal at each site.
1139
+ const recordExamined = (p, outcome) => {
1140
+ if (!trace)
1141
+ return;
1142
+ trace.examined.push({
1143
+ node: p.id,
1144
+ variant: p.variant,
1145
+ leftSiblingId: p.leftSiblingId,
1146
+ rightSiblingId: p.rightSiblingId,
1147
+ annScore: p.annScore,
1148
+ semanticConfidence: p.semanticConfidence,
1149
+ effectiveScore: p.effectiveScore,
1150
+ outcome,
1151
+ });
1152
+ };
1153
+ let selected = null;
1154
+ let selectedReach = null;
1155
+ let selectedIdf = 0;
1156
+ let rival = null;
1157
+ for (const p of sorted) {
1158
+ const reach = edgeAncestors(ctx, p.id, N, reachMemo);
1159
+ if (reach.saturated || reach.roots.length === 0) {
1160
+ recordExamined(p, reach.saturated ? "saturated" : "no-roots");
1161
+ continue;
1162
+ }
1163
+ const idf = Math.log(N / Math.max(1, reach.contextsReached));
1164
+ if (idf <= 0) {
1165
+ recordExamined(p, "nonpositive-idf");
1166
+ continue;
1167
+ }
1168
+ // Self-evidence backstop (see the param doc above): a candidate that is
1169
+ // exactly one side's own already-voted conclusion carries no JOINT
1170
+ // evidence — skip it as if it never survived.
1171
+ if ((ownRootsA && sameRoots(reach.roots, ownRootsA)) ||
1172
+ (ownRootsB && sameRoots(reach.roots, ownRootsB))) {
1173
+ recordExamined(p, "same-as-endpoint");
1174
+ continue;
1175
+ }
1176
+ if (selected === null) {
1177
+ selected = p;
1178
+ selectedReach = reach;
1179
+ selectedIdf = idf;
1180
+ recordExamined(p, "selected");
1181
+ }
1182
+ else if (!sameRoots(reach.roots, selectedReach.roots)) {
1183
+ rival = p;
1184
+ recordExamined(p, "contrastive-rival");
1185
+ break;
1186
+ }
1187
+ else {
1188
+ recordExamined(p, "same-as-selected");
1189
+ }
1190
+ }
1191
+ if (selected === null || selectedReach === null) {
1192
+ if (trace) {
1193
+ trace.noiseFloor = estimatorNoise(ctx.store.D);
1194
+ trace.outcome = "no-valid-proposal";
1195
+ }
1196
+ return null;
1197
+ }
1198
+ const margin = rival
1199
+ ? selected.effectiveScore - rival.effectiveScore
1200
+ : selected.effectiveScore;
1201
+ if (trace) {
1202
+ trace.contrastiveMargin = margin;
1203
+ trace.noiseFloor = estimatorNoise(ctx.store.D);
1204
+ }
1205
+ if (margin <= estimatorNoise(ctx.store.D)) {
1206
+ if (trace)
1207
+ trace.outcome = "margin-rejected";
1208
+ return null;
1209
+ }
1210
+ if (trace)
1211
+ trace.outcome = "accepted";
1212
+ return { proposal: selected, reach: selectedReach, idf: selectedIdf };
1213
+ }
1214
+ async function crossRegionVotes(ctx, query, regions, rvs, k, N, reachMemo, td) {
1215
+ // Candidate regions: every region that ALREADY CAST ITS OWN VOTE in
1216
+ // voteRegions — individually idf > 0, genuinely discriminative on its own,
1217
+ // just not necessarily for the SAME context as its partner. This is the
1218
+ // exact shape of the binding problem: "red" alone votes for `red square`,
1219
+ // "circle" alone for `circle` — each independently informative, disagreeing
1220
+ // on the conclusion — and only their CONJUNCTION resolves to the one
1221
+ // context, `red circle`, that actually holds both.
1222
+ //
1223
+ // A region that never voted (idf == 0 — e.g. a repeated system-prompt
1224
+ // prefix shared by every deposit) carries NO individual signal, and must be
1225
+ // excluded here too: ascending from a non-discriminative fragment's seeds
1226
+ // can still land on some deeper, incidentally-unique DESCENDANT container —
1227
+ // its rarity would come entirely from context OUTSIDE the fragments
1228
+ // actually composed, manufacturing confidence the query gave no reason to
1229
+ // have. Requiring a prior individual vote is the same discipline the noise
1230
+ // drop already applies to single regions, extended to compositions — with
1231
+ // one graded relaxation: a KNOWN region that did NOT vote (saturated, or
1232
+ // idf ≤ 0) may still serve as the WEAK side of a pair whose other side DID
1233
+ // vote. Saturation is an abstention about where the region CLIMBS; its
1234
+ // content-addressed identity is still exact, and the junction asks a
1235
+ // different question — "which whole holds both?" — whose conclusion the
1236
+ // container's own idf gate below still guards. Two non-voting regions
1237
+ // never pair (that is exactly the shared-prefix trap above), so at least
1238
+ // one side is always individually discriminative.
1239
+ //
1240
+ // Only MAXIMAL spans compose: a span contained in another candidate is a
1241
+ // fragment of that candidate's evidence, never independent of it.
1242
+ // Shared across every cross-region probe in this climb: a sibling
1243
+ // successfully reconstructed while probing one pair must not be read and
1244
+ // perceived again while probing another pair in the same climb.
1245
+ const siblingGistMemo = new Map();
1246
+ const votedSpans = new Set();
1247
+ for (const rv of rvs.votes)
1248
+ votedSpans.add(`${rv.start},${rv.end}`);
1249
+ const seen = new Set();
1250
+ const eligible = [];
1251
+ const strong = new Set();
1252
+ for (let ri = 0; ri < regions.length; ri++) {
1253
+ const r = regions[ri];
1254
+ const key = `${r.start},${r.end}`;
1255
+ const isStrong = votedSpans.has(key);
1256
+ if ((!isStrong && !r.known) || seen.has(key))
1257
+ continue;
1258
+ seen.add(key);
1259
+ eligible.push(ri);
1260
+ if (isStrong)
1261
+ strong.add(ri);
1262
+ }
1263
+ const cand = eligible.filter((x) => !eligible.some((y) => y !== x &&
1264
+ regions[y].start <= regions[x].start &&
1265
+ regions[x].end <= regions[y].end &&
1266
+ regions[y].end - regions[y].start > regions[x].end - regions[x].start));
1267
+ const none = { votes: [], superseded: new Set() };
1268
+ if (td) {
1269
+ td.crossRegionSummary = {
1270
+ eligibleRegions: eligible.length,
1271
+ maximalRegions: cand.length,
1272
+ probeLimit: k,
1273
+ probesAttempted: 0, // updated below as probes accrue
1274
+ stopReason: cand.length < 2 ? "insufficient-regions" : undefined,
1275
+ };
1276
+ }
1277
+ if (cand.length < 2)
1278
+ return none;
1279
+ cand.sort((x, y) => regions[x].start - regions[y].start || regions[x].end - regions[y].end);
1280
+ const dec = (b) => new TextDecoder().decode(b).replace(/\s+/g, " ").trim();
1281
+ const cache = walkCache(ctx);
1282
+ // One junctionSeeds per candidate for the WHOLE pairing loop — a candidate
1283
+ // recurs in up to |cand|−1 pairs, and its seeds are a pure function of its
1284
+ // bytes.
1285
+ const seedsMemo = new Map();
1286
+ const seedsOf = (ri) => {
1287
+ let s = seedsMemo.get(ri);
1288
+ if (s === undefined) {
1289
+ const r = regions[ri];
1290
+ s = junctionSeeds(ctx, query.subarray(r.start, r.end));
1291
+ seedsMemo.set(ri, s);
1292
+ }
1293
+ return s;
1294
+ };
1295
+ const overlapsSpan = (e, s) => e.start < s.end && s.start < e.end;
1296
+ const out = [];
1297
+ const superseded = new Set();
1298
+ // A candidate consumed by one junction does not seed another: its evidence
1299
+ // is already composed at full joint strength, and re-pairing it would vote
1300
+ // the same container (or a sub-container of it) twice.
1301
+ const consumed = new Set();
1302
+ let probes = 0;
1303
+ for (let a = 0; a < cand.length && probes < k; a++) {
1304
+ if (consumed.has(cand[a]))
1305
+ continue;
1306
+ const ra = regions[cand[a]];
1307
+ for (let b = a + 1; b < cand.length && probes < k; b++) {
1308
+ if (consumed.has(cand[b]))
1309
+ continue;
1310
+ const rb = regions[cand[b]];
1311
+ if (!strong.has(cand[a]) && !strong.has(cand[b]))
1312
+ continue;
1313
+ if (ra.end >= rb.start)
1314
+ continue; // overlap or adjacent — nothing between
1315
+ // Candidates strictly BETWEEN ra and rb (cand is sorted by start, so
1316
+ // that is exactly cand[a+1 .. b-1]) that already cast their OWN vote —
1317
+ // genuine, individually-corroborated evidence about what fills the gap
1318
+ // — gate the container search below: a joint container is binding
1319
+ // evidence only when it is CONSISTENT with that evidence, i.e. its own
1320
+ // bytes actually contain what the between-region says. This is the
1321
+ // n-ary composition's normal shape (a between-attribute's bytes DO
1322
+ // recur inside the joint container, credited as an "extra" below) as
1323
+ // opposed to a container that silently substitutes something else for
1324
+ // it (e.g. bridging past "Italy" to a container whose interior is
1325
+ // "Japan" — a different, contradicting learnt whole).
1326
+ // Only a KNOWN (content-addressed, exact) between-region qualifies —
1327
+ // an approximate region's resonance climbing "somewhere" is ordinary
1328
+ // noise (any ANN query returns SOME nearest neighbour), not evidence
1329
+ // this specific gap already means something specific.
1330
+ const between = [];
1331
+ for (let m = a + 1; m < b; m++) {
1332
+ if (strong.has(cand[m]) && !consumed.has(cand[m]) &&
1333
+ regions[cand[m]].known)
1334
+ between.push(cand[m]);
1335
+ }
1336
+ // A single KNOWN region covering both: the whole form is already a
1337
+ // stored identity that votes directly; its pieces add nothing.
1338
+ if (regions.some((r) => r.known && r.start <= ra.start && rb.end <= r.end))
1339
+ continue;
1340
+ probes++;
1341
+ if (td?.crossRegionSummary) {
1342
+ td.crossRegionSummary.probesAttempted = probes;
1343
+ }
1344
+ // Trace-only per-probe bookkeeping (spec §2-§7) — built incrementally
1345
+ // as the ladder runs, pushed exactly once at whichever exit fires
1346
+ // below. `pushProbe` is called at every continue/success exit for
1347
+ // THIS pair so the invariant `probes.length === probesAttempted`
1348
+ // holds regardless of which tier settled it.
1349
+ const probe = td
1350
+ ? {
1351
+ leftRegionIndex: cand[a],
1352
+ rightRegionIndex: cand[b],
1353
+ betweenRegionIndices: [...between],
1354
+ exact: { attempted: false, candidatesReturned: 0 },
1355
+ singleSynonym: { attempted: false, candidatesReturned: 0 },
1356
+ doubleSynonym: { attempted: false, candidatesReturned: 0 },
1357
+ outcome: "structural-rejected",
1358
+ }
1359
+ : undefined;
1360
+ let probePushed = false;
1361
+ const pushProbe = (outcome) => {
1362
+ if (!td || !probe || probePushed)
1363
+ return;
1364
+ probe.outcome = outcome;
1365
+ td.crossRegionProbes.push(probe);
1366
+ probePushed = true;
1367
+ };
1368
+ const left = query.subarray(ra.start, ra.end);
1369
+ const right = query.subarray(rb.start, rb.end);
1370
+ // Phrase-scale contract, exactly as the bridge: the glue between the two
1371
+ // forms may be up to W× the content it joins.
1372
+ const maxInterior = (left.length + right.length) * ctx.space.maxGroup;
1373
+ const cap = left.length + right.length + maxInterior;
1374
+ // The graded ladder (spec §1): exact DAG junction, then single-synonym,
1375
+ // then double-synonym, then — only when every DAG tier found nothing —
1376
+ // structural-resonance. `sides` (the two halo sibling lists) is loaded
1377
+ // ONCE and reused by junctionSynonyms AND structural-resonance, so no
1378
+ // ladder rung repeats a halo ANN query an earlier rung already paid for.
1379
+ const sides = await loadJunctionSynonymSides(ctx, left, right);
1380
+ let tier = "exact";
1381
+ let containers = junctionContainersFrom(ctx, left, right, cap, seedsOf(cand[a]), seedsOf(cand[b]), undefined, true);
1382
+ if (probe) {
1383
+ probe.exact = {
1384
+ attempted: true,
1385
+ candidatesReturned: containers.length,
1386
+ };
1387
+ }
1388
+ if (containers.length === 0) {
1389
+ // Tiers 2-4 — synonym containers (junctionSynonyms itself runs
1390
+ // single-synonym first, falling to double-synonym only when
1391
+ // single-synonym found nothing — see junction.ts).
1392
+ const syn = await junctionSynonyms(ctx, left, right, maxInterior, true, sides);
1393
+ if (probe) {
1394
+ const singleAttempted = sides.leftSiblings.length > 0 ||
1395
+ sides.rightSiblings.length > 0;
1396
+ const singleReturned = syn[0]?.tier === "single-synonym"
1397
+ ? syn.length
1398
+ : 0;
1399
+ const doubleAttempted = singleAttempted && singleReturned === 0 &&
1400
+ sides.leftSiblings.length > 0 && sides.rightSiblings.length > 0;
1401
+ const doubleReturned = syn[0]?.tier === "double-synonym"
1402
+ ? syn.length
1403
+ : 0;
1404
+ probe.singleSynonym = {
1405
+ attempted: singleAttempted,
1406
+ candidatesReturned: singleReturned,
1407
+ };
1408
+ probe.doubleSynonym = {
1409
+ attempted: doubleAttempted,
1410
+ candidatesReturned: doubleReturned,
1411
+ };
1412
+ }
1413
+ if (syn.length > 0) {
1414
+ containers = syn;
1415
+ tier = syn[0].tier;
1416
+ }
1417
+ }
1418
+ // Tier 5 — structural-resonance ANN, the FINAL approximate proposal
1419
+ // path. Only reached when every DAG tier found NOTHING, and only when
1420
+ // there is no already-corroborated region between the endpoints (a
1421
+ // between-region with its own vote is evidence the gap already means
1422
+ // something specific — an ANN guess must not override it).
1423
+ let structuralPick = null;
1424
+ if (containers.length === 0) {
1425
+ // Structural-resonance composes each side's OWN gist directly (no
1426
+ // byte-containment truth backs it, unlike the DAG tiers) — so, unlike
1427
+ // the DAG ladder (which tolerates one approximate side because byte
1428
+ // containment cannot lie), the ANN tier requires BOTH sides to be
1429
+ // KNOWN (content-addressed, exact identities): an approximate chunk
1430
+ // fragment's own resonance is noise at any tier, and composing noise
1431
+ // into a synthetic gist only manufactures a plausible-looking but
1432
+ // spurious ANN neighbour, not evidence of a genuine joint whole.
1433
+ // PHRASE-SCALE CONTRACT — the same one the DAG tiers hold their glue
1434
+ // to (see maxInterior above): a junction, exact or approximate, is a
1435
+ // whole the two forms nearly exhaust, not two arbitrary landmarks
1436
+ // anywhere in a long, multi-topic query. Without this, structural-
1437
+ // resonance would pair opposite ends of an unrelated scaffolding-
1438
+ // dominated query and manufacture a plausible-looking ANN neighbour
1439
+ // for a "gap" that never was a phrase.
1440
+ // BOTH sides must be independently DISCRIMINATIVE (individually
1441
+ // voted — `strong`, not merely a content-addressed `known` chunk):
1442
+ // a shared, non-discriminative scaffolding run (a repeated system
1443
+ // preamble) can be `known` without ever being distinctive evidence
1444
+ // of anything, and composing its own gist into a synthetic query
1445
+ // manufactures a plausible-looking but spurious ANN neighbour. The
1446
+ // DAG tiers can tolerate one merely-`known` side because byte
1447
+ // containment cannot lie; structural-resonance has no such
1448
+ // backstop, so both sides earn their place here the same way an
1449
+ // ordinary approximate region earns its individual vote.
1450
+ const gap = rb.start - ra.end;
1451
+ const reasons = [];
1452
+ if (between.length > 0)
1453
+ reasons.push("between-region");
1454
+ if (!strong.has(cand[a]) || !strong.has(cand[b])) {
1455
+ reasons.push("not-both-strong");
1456
+ }
1457
+ if (!ra.known || !rb.known)
1458
+ reasons.push("not-both-known");
1459
+ if (gap > maxInterior)
1460
+ reasons.push("gap-too-large");
1461
+ let resonanceTrace;
1462
+ if (reasons.length > 0) {
1463
+ if (probe) {
1464
+ resonanceTrace = {
1465
+ variantBudget: ctx.cfg.haloQueryK,
1466
+ variants: [],
1467
+ mergedProposals: 0,
1468
+ examined: [],
1469
+ noiseFloor: estimatorNoise(ctx.store.D),
1470
+ outcome: "ineligible",
1471
+ ineligibleReasons: reasons,
1472
+ };
1473
+ probe.resonance = resonanceTrace;
1474
+ }
1475
+ }
1476
+ else {
1477
+ if (probe) {
1478
+ // `outcome`/`noiseFloor` are required fields with no natural
1479
+ // "unset" value; structuralResonance (called just below) always
1480
+ // overwrites both before returning, on every one of its exit
1481
+ // paths — these are never read in their initial form.
1482
+ resonanceTrace = {
1483
+ variantBudget: ctx.cfg.haloQueryK,
1484
+ variants: [],
1485
+ mergedProposals: 0,
1486
+ examined: [],
1487
+ noiseFloor: 0,
1488
+ outcome: "empty",
1489
+ };
1490
+ probe.resonance = resonanceTrace;
1491
+ }
1492
+ const ownRootsA = rvs.votes.find((v) => v.start === ra.start && v.end === ra.end)?.roots;
1493
+ const ownRootsB = rvs.votes.find((v) => v.start === rb.start && v.end === rb.end)?.roots;
1494
+ structuralPick = await structuralResonance(ctx, query, ra, rb, sides, siblingGistMemo, k, N, reachMemo, ownRootsA, ownRootsB, resonanceTrace);
1495
+ }
1496
+ if (structuralPick === null) {
1497
+ pushProbe(reasons.length > 0 ? "resonance-ineligible" : "resonance-rejected");
1498
+ continue;
1499
+ }
1500
+ tier = "structural-resonance";
1501
+ }
1502
+ let best = null;
1503
+ let bestExtras = [];
1504
+ let bestCov = -1;
1505
+ let reach;
1506
+ let idf;
1507
+ let confidence;
1508
+ if (structuralPick !== null) {
1509
+ // A resonance proposal is NOT a Junction — there is no container to
1510
+ // read bytes from, so the self-evidence/contradiction/N-ary
1511
+ // machinery below (byte-verified against a real container) does not
1512
+ // apply; per spec §13, no N-ary extra-region coverage for resonance
1513
+ // proposals.
1514
+ best = { id: structuralPick.proposal.id, interior: new Uint8Array(0) };
1515
+ bestExtras = [];
1516
+ bestCov = rb.end - ra.start;
1517
+ reach = structuralPick.reach;
1518
+ idf = structuralPick.idf;
1519
+ confidence = structuralPick.proposal.effectiveScore;
1520
+ }
1521
+ else {
1522
+ // Aggregate structural-tier trace (spec §4) — one per DAG tier that
1523
+ // returned at least one container (exact, single-synonym or
1524
+ // double-synonym); only aggregate counts and the final outcome are
1525
+ // recorded, never every candidate.
1526
+ const structuralTrace = probe
1527
+ ? {
1528
+ tier: tier,
1529
+ selfEvidenceRejected: 0,
1530
+ contradictionRejected: 0,
1531
+ passedGuards: 0,
1532
+ outcome: "all-rejected",
1533
+ }
1534
+ : undefined;
1535
+ if (probe)
1536
+ probe.structural = structuralTrace;
1537
+ // N-ARY selection: the container covering the MOST remaining candidate
1538
+ // forms wins (then tightest interior, then lowest id). Reads are
1539
+ // cache hits — every container's bytes were already read by the walk.
1540
+ //
1541
+ // SELF-EVIDENCE GUARD: a junction is BINDING evidence only when the
1542
+ // container joins forms the query mentions APART. When the container's
1543
+ // own joined occurrence (left..right including its interior) is a
1544
+ // literal substring of the query, the query already spells that phrase
1545
+ // out contiguously — perception already voted with it, and grid shards
1546
+ // of one phrase pairing "around" a gap chunk would merely rediscover
1547
+ // the phrase they are shards of, then explain away its rivals.
1548
+ for (const c of containers) {
1549
+ const bytes = cachedRead(ctx, cache, c.id, cap);
1550
+ const li = indexOf(bytes, left, 0);
1551
+ const ri = indexOf(bytes, right, 0);
1552
+ if (li >= 0 && ri >= 0) {
1553
+ const joined = bytes.subarray(Math.min(li, ri), Math.max(li + left.length, ri + right.length));
1554
+ if (indexOf(query, joined, 0) >= 0) {
1555
+ if (structuralTrace)
1556
+ structuralTrace.selfEvidenceRejected++;
1557
+ continue; // query says it itself
1558
+ }
1559
+ }
1560
+ // CONTRADICTION GUARD: a between-region already carrying its own
1561
+ // vote must actually recur in this container's bytes — otherwise
1562
+ // the container is a different learnt whole that happens to share
1563
+ // ra/rb, and letting it stand in for the gap would silently
1564
+ // override evidence the query itself already resolved there.
1565
+ if (between.some((bi) => indexOf(bytes, query.subarray(regions[bi].start, regions[bi].end), 0) < 0)) {
1566
+ if (structuralTrace)
1567
+ structuralTrace.contradictionRejected++;
1568
+ continue;
1569
+ }
1570
+ if (structuralTrace)
1571
+ structuralTrace.passedGuards++;
1572
+ let cov = left.length + right.length;
1573
+ const extras = [];
1574
+ for (const ei of cand) {
1575
+ if (ei === cand[a] || ei === cand[b] || consumed.has(ei))
1576
+ continue;
1577
+ const e = regions[ei];
1578
+ if (overlapsSpan(e, ra) || overlapsSpan(e, rb))
1579
+ continue;
1580
+ const eb = query.subarray(e.start, e.end);
1581
+ if (indexOf(bytes, eb, 0) >= 0) {
1582
+ extras.push(ei);
1583
+ cov += eb.length;
1584
+ }
1585
+ }
1586
+ if (cov > bestCov ||
1587
+ (cov === bestCov && best !== null &&
1588
+ (c.interior.length < best.interior.length ||
1589
+ (c.interior.length === best.interior.length && c.id < best.id)))) {
1590
+ best = c;
1591
+ bestExtras = extras;
1592
+ bestCov = cov;
1593
+ }
1594
+ }
1595
+ if (best === null) {
1596
+ // every container was self-evidence / contradiction — outcome
1597
+ // stays "all-rejected".
1598
+ pushProbe("structural-rejected");
1599
+ continue;
1600
+ }
1601
+ const r = edgeAncestors(ctx, best.id, N, reachMemo);
1602
+ if (r.saturated || r.roots.length === 0) {
1603
+ if (structuralTrace) {
1604
+ structuralTrace.outcome = r.saturated ? "saturated" : "no-roots";
1605
+ }
1606
+ pushProbe("structural-rejected");
1607
+ continue;
1608
+ }
1609
+ const df = Math.log(N / Math.max(1, r.contextsReached));
1610
+ if (df <= 0) {
1611
+ if (structuralTrace)
1612
+ structuralTrace.outcome = "nonpositive-idf";
1613
+ pushProbe("structural-rejected");
1614
+ continue;
1615
+ }
1616
+ if (structuralTrace) {
1617
+ structuralTrace.outcome = "accepted";
1618
+ structuralTrace.selectedNode = best.id;
1619
+ }
1620
+ reach = r;
1621
+ idf = df;
1622
+ // Confidence used by voting (spec §13): exact junction = 1;
1623
+ // single/double-synonym = the sibling(s)' score(s), carried on the
1624
+ // SynonymJunction the ladder selected.
1625
+ confidence = "confidence" in best ? best.confidence : 1;
1626
+ }
1627
+ // MUTUAL-EXPLANATION WEIGHT — the same formula for every tier, with
1628
+ // `confidence` collapsed to certainty (1) for exact evidence: under
1629
+ // that collapse this is byte-for-byte the old exact-only formula
1630
+ // (min(1,ratio)·min(1,1/ratio)). For structural-resonance,
1631
+ // `confidence` is already annScore·semanticConfidence — never
1632
+ // multiplied a second time.
1633
+ const lenR = Math.max(1, bestCov);
1634
+ const ratio = Math.sqrt(Math.max(1, ctx.store.contentLen(best.id, lenR * ctx.store.D)) / lenR);
1635
+ const mutual = Math.min(1, confidence * ratio) *
1636
+ Math.min(1, confidence / ratio);
1637
+ const w = (mutual * idf) / reach.roots.length;
1638
+ let spanStart = ra.start;
1639
+ let spanEnd = rb.end;
1640
+ for (const ei of bestExtras) {
1641
+ spanStart = Math.min(spanStart, regions[ei].start);
1642
+ spanEnd = Math.max(spanEnd, regions[ei].end);
1643
+ }
1644
+ consumed.add(cand[a]);
1645
+ consumed.add(cand[b]);
1646
+ for (const ei of bestExtras)
1647
+ consumed.add(ei);
1648
+ // EXPLAINING AWAY — see the block comment above the function. Byte
1649
+ // containment in the joint container is the relatedness test (the
1650
+ // vote's bytes are literally part of the learnt whole), and FULL root
1651
+ // disjointness is the disagreement test: a vote sharing even one root
1652
+ // with the junction corroborates it and keeps its say elsewhere.
1653
+ // Counted BEFORE pushing the junction's own vote below: each ORIGINAL
1654
+ // region this ascent explains away is evidence the junction speaks
1655
+ // for, not evidence lost — `absorbed` (RegionVote's breadth-accounting
1656
+ // field) must credit the junction with all of it, not just the ONE
1657
+ // pooled axiom it collapses to.
1658
+ // Only EXACT DAG evidence may explain away ordinary votes (spec §15).
1659
+ // Single-synonym, double-synonym, and structural-resonance may ADD
1660
+ // supporting evidence but never remove it: their evidence is itself
1661
+ // approximate (a sibling substitution, or an ANN guess), so treating
1662
+ // their byte-containment the way exact containment is treated would
1663
+ // let an approximation override a genuine, independently-voted region.
1664
+ let explainedAway = 0;
1665
+ // Exact set of ORIGINAL region indices this junction explained away —
1666
+ // recorded live as `superseded.add` fires (spec §3's explicit rule:
1667
+ // never inferred from `absorbed` afterward).
1668
+ const explainedAwayIndices = [];
1669
+ if (tier === "exact") {
1670
+ const containerBytes = cachedRead(ctx, cache, best.id, cap);
1671
+ const jointRoots = new Set(reach.roots);
1672
+ for (const rv of rvs.votes) {
1673
+ if (rv.roots.some((r) => jointRoots.has(r)))
1674
+ continue;
1675
+ const bytes = query.subarray(rv.start, rv.end);
1676
+ if (indexOf(containerBytes, bytes, 0) >= 0 && !superseded.has(rv)) {
1677
+ superseded.add(rv);
1678
+ explainedAway++;
1679
+ if (td) {
1680
+ const idx = regions.findIndex((r) => r.start === rv.start && r.end === rv.end);
1681
+ if (idx >= 0)
1682
+ explainedAwayIndices.push(idx);
1683
+ }
1684
+ }
1685
+ }
1686
+ }
1687
+ out.push({
1688
+ start: spanStart,
1689
+ end: spanEnd,
1690
+ canonicalFailed: false, // content-addressed: never saturation-masked
1691
+ roots: reach.roots,
1692
+ w,
1693
+ wFocus: w,
1694
+ absorbed: 1 + explainedAway,
1695
+ });
1696
+ pushProbe("accepted");
1697
+ if (td) {
1698
+ td.crossRegionJunctionVotes.push({
1699
+ container: best.id,
1700
+ span: [spanStart, spanEnd],
1701
+ roots: [...reach.roots],
1702
+ sourceRegionIndices: [cand[a], cand[b], ...bestExtras],
1703
+ explainedAwayRegionIndices: explainedAwayIndices,
1704
+ absorbed: 1 + explainedAway,
1705
+ tier,
1706
+ probe: td.crossRegionProbes.length - 1,
1707
+ confidence,
1708
+ evidenceBytes: bestCov,
1709
+ mutualWeight: mutual,
1710
+ voteWeightPerRoot: w,
1711
+ });
1712
+ }
1713
+ const label = [cand[a], cand[b], ...bestExtras]
1714
+ .sort((x, y) => regions[x].start - regions[y].start)
1715
+ .map((ri) => dec(query.subarray(regions[ri].start, regions[ri].end)))
1716
+ .join(" ▸ ");
1717
+ const tierNote = tier === "exact"
1718
+ ? `junction node ${best.id}` +
1719
+ (best.interior.length === 0
1720
+ ? " (adjacent)"
1721
+ : ` (interior "${dec(best.interior)}")`) +
1722
+ ", by content-addressed ascent"
1723
+ : tier === "structural-resonance"
1724
+ ? `structurally-composed ANN proposal, node ${best.id} — the query ` +
1725
+ `structurally composed the endpoint regions, the real middle-` +
1726
+ `query structure, and the selected halo-sibling endpoint ` +
1727
+ `direction(s) (variant ${structuralPick.proposal.variant}, ` +
1728
+ `annScore ${structuralPick.proposal.annScore.toFixed(3)} × ` +
1729
+ `semanticConfidence ${structuralPick.proposal.semanticConfidence.toFixed(3)} = effectiveScore ${structuralPick.proposal.effectiveScore.toFixed(3)}); it did not concatenate endpoint bytes or rewrite the query`
1730
+ : `${tier} junction node ${best.id}` +
1731
+ (best.interior.length === 0
1732
+ ? " (adjacent)"
1733
+ : ` (interior "${dec(best.interior)}")`) +
1734
+ `, by halo-sibling DAG ascent (confidence ${confidence.toFixed(3)})`;
1735
+ ctx.trace?.step("crossRegion", [{ text: label, role: "pair" }], reach.roots.map((r) => ({
1736
+ text: dec(read(ctx, r)).slice(0, 60),
1737
+ node: r,
1738
+ role: "joint-context",
1739
+ })), `${label} → ${tierNote} → ${reach.roots.length} context(s)` +
1740
+ (superseded.size > 0
1741
+ ? `; ${superseded.size} aliasing vote(s) explained away`
1742
+ : ""));
1743
+ break; // ra is consumed — move to the next unconsumed candidate
1744
+ }
1745
+ }
1746
+ if (td)
1747
+ td.supersededOrdinaryVotes = superseded.size;
1748
+ if (td?.crossRegionSummary) {
1749
+ td.crossRegionSummary.stopReason = probes >= k
1750
+ ? "probe-limit"
1751
+ : "pairs-exhausted";
1752
+ }
1753
+ return { votes: out, superseded };
1754
+ }
1755
+ /** Emit the "climbConsensus" step — the human-readable note this always
1756
+ * produced, now paired (when `ctx.trace` and `cfg` are both present) with
1757
+ * the structured {@link ClimbConsensusData} payload on the SAME step's
1758
+ * `data` field. Every exit of {@link computeAttention} funnels through
1759
+ * here, so instrumentation and the existing rationale text can never drift
1760
+ * apart — see the instrumentation spec's §9 "every exit path". */
1761
+ export function traceAttention(ctx, regions, regionVoter, roots, steps = [], td, cfg, ranked = roots) {
1762
+ if (!ctx.trace)
1763
+ return;
1764
+ const voters = [];
1765
+ for (let i = 0; i < regions.length; i++) {
1766
+ const rv = regionVoter[i];
1767
+ if (rv == null)
1768
+ continue;
1769
+ const item = rNode(ctx, rv.id, "sub-region", rv.score);
1770
+ item.text = `${item.text} (df-w ${rv.w.toFixed(2)})`;
1771
+ voters.push(item);
1772
+ }
1773
+ const t = ctx.trace.enter("climbConsensus", voters);
1774
+ // The pooled-evidence decision, one DerivationStep per anchor — the same
1775
+ // shape {@link GraphSearch}'s own cover steps take (see traceDerivation).
1776
+ if (steps.length > 0)
1777
+ traceDerivation(ctx, steps);
1778
+ const data = (td && cfg)
1779
+ ? {
1780
+ version: 1,
1781
+ cache: { hit: false, detailAvailable: true },
1782
+ config: {
1783
+ annK: cfg.k,
1784
+ crossRegionProbeLimit: cfg.k,
1785
+ mode: cfg.mode,
1786
+ ...(cfg.N !== undefined ? { corpusN: cfg.N } : {}),
1787
+ dimension: ctx.store.D,
1788
+ ...(cfg.N !== undefined ? { hubBound: hubBound(ctx) } : {}),
1789
+ estimatorNoise: estimatorNoise(ctx.store.D),
1790
+ ...(cfg.naturalBreak !== undefined
1791
+ ? { naturalBreak: cfg.naturalBreak }
1792
+ : {}),
1793
+ ...(cfg.consensusFloor !== undefined
1794
+ ? { consensusFloor: cfg.consensusFloor }
1795
+ : {}),
1796
+ },
1797
+ candidates: {
1798
+ perceived: cfg.perceivedCount,
1799
+ recognised: cfg.totalRegions - cfg.perceivedCount,
1800
+ total: cfg.totalRegions,
1801
+ },
1802
+ ...(td.regions.length > 0 ? { regions: td.regions } : {}),
1803
+ ...(cfg.reachMemo ? { reaches: serialiseReaches(cfg.reachMemo) } : {}),
1804
+ ...(td.crossRegionSummary
1805
+ ? {
1806
+ crossRegion: {
1807
+ eligibleRegions: td.crossRegionSummary.eligibleRegions,
1808
+ maximalRegions: td.crossRegionSummary.maximalRegions,
1809
+ probeLimit: td.crossRegionSummary.probeLimit,
1810
+ probesAttempted: td.crossRegionSummary.probesAttempted,
1811
+ junctionVotes: td.crossRegionJunctionVotes,
1812
+ supersededOrdinaryVotes: td.supersededOrdinaryVotes,
1813
+ probes: td.crossRegionProbes,
1814
+ stopReason: td.crossRegionSummary.stopReason ?? "pairs-exhausted",
1815
+ },
1816
+ }
1817
+ : {}),
1818
+ ...(td.saturation ? { saturation: td.saturation } : {}),
1819
+ ...(td.pooling ? { pooling: td.pooling } : {}),
1820
+ ...(td.anchors.length > 0 ? { anchors: td.anchors } : {}),
1821
+ result: { roots: [...roots], ranked: [...ranked] },
1822
+ }
1823
+ : undefined;
1824
+ t.done(roots.map((r) => rNode(ctx, r.anchor, "anchor", r.vote)), roots.length === 0
1825
+ ? `${regions.length} sub-regions climbed the DAG, but none agreed on a context`
1826
+ : roots.length === 1
1827
+ ? `${voters.length} of ${regions.length} sub-regions voted; IDF-weighted consensus picked one context (vote ${roots[0].vote.toFixed(2)})`
1828
+ : `${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(", ")})`, data);
1829
+ }