@hviana/sema 0.4.2 → 0.4.4

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