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