@hviana/sema 0.1.5 → 0.1.6

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