@hviana/sema 0.1.0
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/AGENTS.md +470 -0
- package/AUTHORS.md +12 -0
- package/COMMERCIAL-LICENSE.md +19 -0
- package/CONTRIBUTING.md +15 -0
- package/HOW_IT_WORKS.md +4210 -0
- package/LICENSE.md +117 -0
- package/README.md +290 -0
- package/TRADEMARKS.md +19 -0
- package/example/demo.ts +46 -0
- package/example/train_base.ts +2675 -0
- package/index.html +893 -0
- package/package.json +25 -0
- package/src/alphabet.ts +34 -0
- package/src/alu/README.md +332 -0
- package/src/alu/src/alu.ts +541 -0
- package/src/alu/src/expr.ts +339 -0
- package/src/alu/src/index.ts +115 -0
- package/src/alu/src/kernel-arith.ts +377 -0
- package/src/alu/src/kernel-bits.ts +199 -0
- package/src/alu/src/kernel-logic.ts +102 -0
- package/src/alu/src/kernel-nd.ts +235 -0
- package/src/alu/src/kernel-numeric.ts +466 -0
- package/src/alu/src/operation.ts +344 -0
- package/src/alu/src/parser.ts +574 -0
- package/src/alu/src/resonance.ts +161 -0
- package/src/alu/src/text.ts +83 -0
- package/src/alu/src/value.ts +327 -0
- package/src/alu/test/alu.test.ts +1004 -0
- package/src/bytes.ts +62 -0
- package/src/config.ts +227 -0
- package/src/derive/README.md +295 -0
- package/src/derive/src/deduction.ts +263 -0
- package/src/derive/src/index.ts +24 -0
- package/src/derive/src/priority-queue.ts +70 -0
- package/src/derive/src/rewrite.ts +127 -0
- package/src/derive/src/trie.ts +242 -0
- package/src/derive/test/derive.test.ts +137 -0
- package/src/extension.ts +42 -0
- package/src/geometry.ts +511 -0
- package/src/index.ts +38 -0
- package/src/ingest-cache.ts +224 -0
- package/src/mind/articulation.ts +137 -0
- package/src/mind/attention.ts +1061 -0
- package/src/mind/canonical.ts +107 -0
- package/src/mind/graph-search.ts +1100 -0
- package/src/mind/index.ts +18 -0
- package/src/mind/junction.ts +347 -0
- package/src/mind/learning.ts +246 -0
- package/src/mind/match.ts +507 -0
- package/src/mind/mechanisms/alu.ts +33 -0
- package/src/mind/mechanisms/cast.ts +568 -0
- package/src/mind/mechanisms/confluence.ts +268 -0
- package/src/mind/mechanisms/cover.ts +248 -0
- package/src/mind/mechanisms/extraction.ts +422 -0
- package/src/mind/mechanisms/recall.ts +241 -0
- package/src/mind/mind.ts +483 -0
- package/src/mind/pipeline-mechanism.ts +326 -0
- package/src/mind/pipeline.ts +300 -0
- package/src/mind/primitives.ts +201 -0
- package/src/mind/rationale.ts +275 -0
- package/src/mind/reasoning.ts +198 -0
- package/src/mind/recognition.ts +234 -0
- package/src/mind/resonance.ts +0 -0
- package/src/mind/trace.ts +108 -0
- package/src/mind/traverse.ts +556 -0
- package/src/mind/types.ts +281 -0
- package/src/rabitq-hnsw/README.md +303 -0
- package/src/rabitq-hnsw/src/database.ts +492 -0
- package/src/rabitq-hnsw/src/heap.ts +90 -0
- package/src/rabitq-hnsw/src/hnsw.ts +514 -0
- package/src/rabitq-hnsw/src/index.ts +15 -0
- package/src/rabitq-hnsw/src/prng.ts +39 -0
- package/src/rabitq-hnsw/src/rabitq.ts +308 -0
- package/src/rabitq-hnsw/src/store.ts +994 -0
- package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
- package/src/store-sqlite.ts +928 -0
- package/src/store.ts +2148 -0
- package/src/vec.ts +124 -0
- package/test/00-extract.test.mjs +151 -0
- package/test/01-floor.test.mjs +20 -0
- package/test/02-roundtrip.test.mjs +83 -0
- package/test/03-recall.test.mjs +98 -0
- package/test/04-think.test.mjs +627 -0
- package/test/05-concepts.test.mjs +84 -0
- package/test/08-storage.test.mjs +948 -0
- package/test/09-edges.test.mjs +65 -0
- package/test/11-universality.test.mjs +180 -0
- package/test/13-conversation.test.mjs +228 -0
- package/test/14-scaling.test.mjs +503 -0
- package/test/15-decomposition-gap.test.mjs +0 -0
- package/test/16-bridge.test.mjs +250 -0
- package/test/17-intelligence.test.mjs +240 -0
- package/test/18-alu.test.mjs +209 -0
- package/test/19-nd.test.mjs +254 -0
- package/test/20-stability.test.mjs +489 -0
- package/test/21-partial.test.mjs +158 -0
- package/test/22-multihop.test.mjs +130 -0
- package/test/23-rationale.test.mjs +316 -0
- package/test/24-generalization.test.mjs +416 -0
- package/test/25-embedding.test.mjs +75 -0
- package/test/26-cooperative.test.mjs +89 -0
- package/test/27-saturation-drop.test.mjs +637 -0
- package/test/28-unknowable.test.mjs +88 -0
- package/test/29-counterfactual.test.mjs +476 -0
- package/test/30-conflict-resolution.test.mjs +166 -0
- package/test/31-audit.test.mjs +288 -0
- package/test/32-confluence.test.mjs +173 -0
- package/test/33-multi-candidate.test.mjs +222 -0
- package/test/34-cross-region.test.mjs +252 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
// traverse.ts — Traverse primitives + disambiguation (Sections 1 & 6 of the mind).
|
|
2
|
+
//
|
|
3
|
+
// Traverse — node → nodes (edgeAncestors, nextOf, prevOf, contains,
|
|
4
|
+
// guidedNext, chooseNext, chooseAmong, hubCap)
|
|
5
|
+
//
|
|
6
|
+
// The PROJECTIONS built on these walks (follow, conceptHop, reverseContext,
|
|
7
|
+
// project) live in match.ts — the elementary match-and-project operation.
|
|
8
|
+
|
|
9
|
+
import { cosine, Vec } from "../vec.js";
|
|
10
|
+
import type { AncestorReach, MindContext } from "./types.js";
|
|
11
|
+
import { gistOf, read } from "./primitives.js";
|
|
12
|
+
|
|
13
|
+
// ── Per-response structural memo ────────────────────────────────────────
|
|
14
|
+
//
|
|
15
|
+
// Within one respond() the store is read-only, so structural reads are pure
|
|
16
|
+
// functions of the node id. edgeAncestors climbs different start nodes that
|
|
17
|
+
// share ancestry (regions sharing a chunk, canonicalChunkId's prefix probes)
|
|
18
|
+
// — the reachMemo already caches whole-climb results, but a node visited as an
|
|
19
|
+
// INTERMEDIATE in one climb is re-read when it becomes a START in another.
|
|
20
|
+
// Caching per-node structural reads eliminates those duplicates.
|
|
21
|
+
//
|
|
22
|
+
// Each field is cached independently (lazy, separate maps) so that fetching
|
|
23
|
+
// hasNext never pulls prevCount or hasParents — those are only read when the
|
|
24
|
+
// caller genuinely needs them (hasParents is only called for the start node's
|
|
25
|
+
// containment check and voteRegions' canonical-id admission; never for
|
|
26
|
+
// intermediate nodes visited during a climb).
|
|
27
|
+
|
|
28
|
+
interface StructCache {
|
|
29
|
+
hasNext: Map<number, boolean>;
|
|
30
|
+
prevCount: Map<number, number>;
|
|
31
|
+
hasParents: Map<number, boolean>;
|
|
32
|
+
}
|
|
33
|
+
const structCaches = new WeakMap<object, StructCache>();
|
|
34
|
+
|
|
35
|
+
function getStructCache(ctx: MindContext): StructCache | null {
|
|
36
|
+
if (ctx.climbMemo === null) return null;
|
|
37
|
+
let c = structCaches.get(ctx.climbMemo);
|
|
38
|
+
if (c === undefined) {
|
|
39
|
+
structCaches.set(
|
|
40
|
+
ctx.climbMemo,
|
|
41
|
+
c = {
|
|
42
|
+
hasNext: new Map(),
|
|
43
|
+
prevCount: new Map(),
|
|
44
|
+
hasParents: new Map(),
|
|
45
|
+
},
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return c;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Cached {@link Store.hasNext} — pure during one respond(). */
|
|
52
|
+
function cachedHasNext(
|
|
53
|
+
ctx: MindContext,
|
|
54
|
+
id: number,
|
|
55
|
+
cache: StructCache | null,
|
|
56
|
+
): boolean {
|
|
57
|
+
if (cache === null) return ctx.store.hasNext(id);
|
|
58
|
+
let v = cache.hasNext.get(id);
|
|
59
|
+
if (v === undefined) {
|
|
60
|
+
v = ctx.store.hasNext(id);
|
|
61
|
+
cache.hasNext.set(id, v);
|
|
62
|
+
}
|
|
63
|
+
return v;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Cached {@link Store.prevCount} — pure during one respond(). */
|
|
67
|
+
function cachedPrevCount(
|
|
68
|
+
ctx: MindContext,
|
|
69
|
+
id: number,
|
|
70
|
+
cache: StructCache | null,
|
|
71
|
+
): number {
|
|
72
|
+
if (cache === null) return ctx.store.prevCount(id);
|
|
73
|
+
let v = cache.prevCount.get(id);
|
|
74
|
+
if (v === undefined) {
|
|
75
|
+
v = ctx.store.prevCount(id);
|
|
76
|
+
cache.prevCount.set(id, v);
|
|
77
|
+
}
|
|
78
|
+
return v;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Cached {@link Store.hasParents} — pure during one respond(). */
|
|
82
|
+
function cachedHasParents(
|
|
83
|
+
ctx: MindContext,
|
|
84
|
+
id: number,
|
|
85
|
+
cache: StructCache | null,
|
|
86
|
+
): boolean {
|
|
87
|
+
if (cache === null) return ctx.store.hasParents(id);
|
|
88
|
+
let v = cache.hasParents.get(id);
|
|
89
|
+
if (v === undefined) {
|
|
90
|
+
v = ctx.store.hasParents(id);
|
|
91
|
+
cache.hasParents.set(id, v);
|
|
92
|
+
}
|
|
93
|
+
return v;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ── Graph climbing ───────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
/** Climb the structural DAG from a node to its edge-bearing ancestor contexts.
|
|
99
|
+
* Ascent stops at hub nodes (parents > √N) — their reach is non-discriminative.
|
|
100
|
+
* When the start node has no structural parents, climbs from containment parents
|
|
101
|
+
* (sub-span flat branches inheriting their chunks' context).
|
|
102
|
+
*
|
|
103
|
+
* `memo`, when given, caches whole climbs by start id for the duration of ONE
|
|
104
|
+
* query (the store is read-only while a query is in flight, so a climb is a
|
|
105
|
+
* pure function of the id). The consensus pipeline climbs the SAME anchors
|
|
106
|
+
* repeatedly — regions sharing a chunk, and canonicalChunkId probing each
|
|
107
|
+
* chunk's prefixes — so without the memo every repeat re-pays the full
|
|
108
|
+
* fan-out reads. */
|
|
109
|
+
export function edgeAncestors(
|
|
110
|
+
ctx: MindContext,
|
|
111
|
+
id: number,
|
|
112
|
+
contextCount: number,
|
|
113
|
+
memo?: Map<number, AncestorReach>,
|
|
114
|
+
): AncestorReach {
|
|
115
|
+
const hit = memo?.get(id);
|
|
116
|
+
if (hit !== undefined) return hit;
|
|
117
|
+
|
|
118
|
+
const bound = Math.ceil(Math.sqrt(contextCount));
|
|
119
|
+
const roots: number[] = [];
|
|
120
|
+
const seen = new Set<number>([id]);
|
|
121
|
+
const ctxSeen = new Set<number>();
|
|
122
|
+
let saturated = false;
|
|
123
|
+
|
|
124
|
+
// EXPAND-UNTIL-DECIDED: a reach is consumed either as a VOTE (which needs
|
|
125
|
+
// contextsReached exactly, and only while ≤ √N — beyond that the region is
|
|
126
|
+
// non-discriminative) or as an ABSTENTION (saturated — whose roots and
|
|
127
|
+
// counts no consumer reads). So the climb may STOP the moment the answer
|
|
128
|
+
// is decided:
|
|
129
|
+
// • a node whose prev fan-in alone exceeds √N decides it (its
|
|
130
|
+
// predecessors are √N+ distinct contexts) — no read needed, prevCount
|
|
131
|
+
// is an indexed O(1);
|
|
132
|
+
// • distinct contexts crossing √N decides it;
|
|
133
|
+
// • a node with more than √N parents decides its own expansion (the
|
|
134
|
+
// classic hub guard; the walk aborts rather than continue, which no
|
|
135
|
+
// consumer can distinguish — saturated reaches are never voted).
|
|
136
|
+
// Below every decision threshold the walk is EXACT — identical roots and
|
|
137
|
+
// contexts to the unbounded climb — because prevFirst(√N) IS the full prev
|
|
138
|
+
// list and parentsFirst(√N+1) IS the full parent list whenever they do not
|
|
139
|
+
// decide. Work is bounded by √N contexts × the climb's local structure,
|
|
140
|
+
// never by the corpus.
|
|
141
|
+
|
|
142
|
+
const structCache = getStructCache(ctx);
|
|
143
|
+
|
|
144
|
+
// LATERAL-BRANCH ACCOUNT — the cumulative dual of the per-node hub guard.
|
|
145
|
+
// Within one deposit the ascent is a CHAIN (each node's first parent);
|
|
146
|
+
// every parent BEYOND a node's first is an entry into another containing
|
|
147
|
+
// structure (hash-consing: a shared subtree's extra parents are other
|
|
148
|
+
// deposits' chunks). The per-node guard already declares a node with more
|
|
149
|
+
// than √N parents non-discriminative; a climb whose ACCUMULATED lateral
|
|
150
|
+
// entries exceed √N has spread across just as many distinct containing
|
|
151
|
+
// structures — the same commonness, distributed along the cone instead of
|
|
152
|
+
// concentrated at one node — and is decided: saturated. A deep chain in
|
|
153
|
+
// ONE structure accrues no laterals, so legitimate deep scaffolding (a
|
|
154
|
+
// fragment far down a long cumulative context) still climbs to its root
|
|
155
|
+
// at any depth; what dies is the cross-structure drift that visited tens
|
|
156
|
+
// of thousands of edge-free interiors (profiled on a 17.7M-node store:
|
|
157
|
+
// ~20K distinct nodes per climb family, >95% unique — not memoisable)
|
|
158
|
+
// while the context account never decided.
|
|
159
|
+
let lateral = 0;
|
|
160
|
+
|
|
161
|
+
const visit = (x: number): boolean => {
|
|
162
|
+
const hasNx = cachedHasNext(ctx, x, structCache);
|
|
163
|
+
const pc = cachedPrevCount(ctx, x, structCache);
|
|
164
|
+
if (hasNx || pc > 0) {
|
|
165
|
+
roots.push(x);
|
|
166
|
+
if (hasNx) ctxSeen.add(x);
|
|
167
|
+
if (pc > bound) return false; // decided: ≥ pc > √N distinct contexts
|
|
168
|
+
for (const p of ctx.store.prevFirst(x, bound)) ctxSeen.add(p);
|
|
169
|
+
if (ctxSeen.size > bound) return false; // decided
|
|
170
|
+
}
|
|
171
|
+
const parents = ctx.store.parentsFirst(x, bound + 1);
|
|
172
|
+
if (parents.length > bound) return false; // decided: hub
|
|
173
|
+
let fresh = 0;
|
|
174
|
+
for (const p of parents) {
|
|
175
|
+
if (!seen.has(p)) {
|
|
176
|
+
seen.add(p);
|
|
177
|
+
stack.push(p);
|
|
178
|
+
fresh++;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (fresh > 1) {
|
|
182
|
+
lateral += fresh - 1;
|
|
183
|
+
if (lateral > bound) return false; // decided: cone-wide hub
|
|
184
|
+
}
|
|
185
|
+
return true;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const stack: number[] = [];
|
|
189
|
+
const containment = !cachedHasParents(ctx, id, structCache);
|
|
190
|
+
if (!containment) stack.push(id);
|
|
191
|
+
|
|
192
|
+
// The containment seed is STREAMED in pages of √N: a distinctive window's
|
|
193
|
+
// containers (which converge on one or two contexts, however many chunks
|
|
194
|
+
// of one deposit repeat it) are walked IN FULL — exact — while a common
|
|
195
|
+
// window's corpus-sized container list is abandoned at the first decision
|
|
196
|
+
// above, after O(√N) pages at most (each page adds containers whose climbs
|
|
197
|
+
// add contexts; √N distinct contexts decide).
|
|
198
|
+
let containerOff = 0;
|
|
199
|
+
let containersExhausted = !containment;
|
|
200
|
+
climb:
|
|
201
|
+
for (;;) {
|
|
202
|
+
if (stack.length === 0) {
|
|
203
|
+
if (containersExhausted) break;
|
|
204
|
+
const page = ctx.store.containersSlice(id, containerOff, bound);
|
|
205
|
+
containerOff += page.length;
|
|
206
|
+
if (page.length < bound) containersExhausted = true;
|
|
207
|
+
for (const c of page) {
|
|
208
|
+
if (!seen.has(c)) {
|
|
209
|
+
seen.add(c);
|
|
210
|
+
stack.push(c);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (stack.length === 0) {
|
|
214
|
+
if (containerOff === 0) stack.push(id); // no containers at all
|
|
215
|
+
else break;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
while (stack.length > 0) {
|
|
219
|
+
let x = stack.pop()!;
|
|
220
|
+
// TRANSPARENT-CHAIN HOP: a node with no edges in or out and exactly one
|
|
221
|
+
// parent contributes nothing here — no root, no context, no lateral
|
|
222
|
+
// entry — so the run to its first non-transparent ancestor is skipped
|
|
223
|
+
// in ONE store read (Store.chainRun) instead of three probes per node.
|
|
224
|
+
// The interior nodes still enter `seen`, exactly as a node-at-a-time
|
|
225
|
+
// ascent would have recorded them at push time, so sibling entries into
|
|
226
|
+
// the same chain keep identical fresh/lateral accounting; and if the
|
|
227
|
+
// terminal was already seen (another chain merged into this one first),
|
|
228
|
+
// it is not visited twice — the same dedup the push-time seen-check
|
|
229
|
+
// used to provide.
|
|
230
|
+
const run = ctx.store.chainRun(x);
|
|
231
|
+
if (run.length > 1) {
|
|
232
|
+
const top = run[run.length - 1];
|
|
233
|
+
const dup = seen.has(top);
|
|
234
|
+
for (let i = 1; i < run.length; i++) seen.add(run[i]);
|
|
235
|
+
if (dup) continue;
|
|
236
|
+
x = top;
|
|
237
|
+
}
|
|
238
|
+
if (!visit(x)) {
|
|
239
|
+
saturated = true;
|
|
240
|
+
break climb;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const reach = { roots, contextsReached: ctxSeen.size, saturated };
|
|
246
|
+
memo?.set(id, reach);
|
|
247
|
+
return reach;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Convenience: forward edges of a node. */
|
|
251
|
+
export function nextOf(ctx: MindContext, id: number): number[] {
|
|
252
|
+
return ctx.store.next(id);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Convenience: reverse edges of a node. */
|
|
256
|
+
export function prevOf(ctx: MindContext, id: number): number[] {
|
|
257
|
+
return ctx.store.prev(id);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Whether a node LEADS SOMEWHERE — it bears a continuation edge or a halo.
|
|
261
|
+
* The admission predicate recognition filters sites with (HOW_IT_WORKS
|
|
262
|
+
* §15.3): a form that leads nowhere contributes nothing to any derivation.
|
|
263
|
+
* Runs once per candidate span on the recognition hot path — `hasNext` is
|
|
264
|
+
* cached per response (the same flat-branch ids are probed across prefix
|
|
265
|
+
* variants by canonicalChunkId). `hasHalo` is not cached: it's a single
|
|
266
|
+
* indexed point probe per candidate, and the candidates that reach this
|
|
267
|
+
* check have already been filtered by hasNext above in edgeAncestors. */
|
|
268
|
+
export function leadsSomewhere(ctx: MindContext, id: number): boolean {
|
|
269
|
+
const memo = getStructCache(ctx);
|
|
270
|
+
if (cachedHasNext(ctx, id, memo)) return true;
|
|
271
|
+
return ctx.store.hasHalo(id);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The structural IDF read of ONE node: how many distinct learnt contexts
|
|
275
|
+
* its containment/edge climb reaches, or Infinity when it reaches none or
|
|
276
|
+
* saturates (no usable identity evidence). The number every
|
|
277
|
+
* discriminative-vs-scaffolding decision derives from — paired with the
|
|
278
|
+
* half-dominance convention (geometry.dominates(reach, N)): content
|
|
279
|
+
* reaching a corpus MINORITY of contexts discriminates (an entity, a
|
|
280
|
+
* filler); content reaching a majority is frame scaffolding. */
|
|
281
|
+
export function reachOf(
|
|
282
|
+
ctx: MindContext,
|
|
283
|
+
id: number,
|
|
284
|
+
contextCount: number,
|
|
285
|
+
memo?: Map<number, AncestorReach>,
|
|
286
|
+
): number {
|
|
287
|
+
const r = edgeAncestors(ctx, id, contextCount, memo);
|
|
288
|
+
if (r.saturated || r.roots.length === 0) return Infinity;
|
|
289
|
+
return Math.max(1, r.contextsReached);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** The corpus scale N — the count of DISTINCT learnt contexts, floored at 2
|
|
293
|
+
* so its derived readings (ln N in the consensus floor, √N in the hub bound)
|
|
294
|
+
* stay meaningful on a near-empty store. The one definition every consumer
|
|
295
|
+
* of "how big is this corpus?" reads. */
|
|
296
|
+
export function corpusN(ctx: MindContext): number {
|
|
297
|
+
return Math.max(2, ctx.store.edgeSourceCount());
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The hub bound √N itself (≥ 2 always, since N is floored at 2) — for
|
|
301
|
+
* consumers that pass it to the store's LIMITed reads instead of capping a
|
|
302
|
+
* materialised list. {@link hubCap} is the list-side reading of the same
|
|
303
|
+
* convention. */
|
|
304
|
+
export function hubBound(ctx: MindContext): number {
|
|
305
|
+
return Math.ceil(Math.sqrt(corpusN(ctx)));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Cap a candidate list at the hub bound √N (insertion order) — the ONE
|
|
309
|
+
* fan-out convention every walk and disambiguation uses (see HOW_IT_WORKS
|
|
310
|
+
* §8.6). A node connected to more than √N others is a hub whose individual
|
|
311
|
+
* connections carry ~no discriminative information; materialising or scoring
|
|
312
|
+
* them all would make single decisions scale with the corpus. */
|
|
313
|
+
export function hubCap<T>(
|
|
314
|
+
ctx: MindContext,
|
|
315
|
+
ids: readonly T[],
|
|
316
|
+
): readonly T[] {
|
|
317
|
+
const bound = hubBound(ctx);
|
|
318
|
+
return ids.length > bound ? ids.slice(0, bound) : ids;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Whether `descendant` lies within `ancestor`'s subtree — a structural DAG
|
|
322
|
+
* relation read off the hash-consed `kids` lists, by a bounded explicit-stack
|
|
323
|
+
* descent. Used by articulation to keep a voice from revoicing a fragment
|
|
324
|
+
* OF that voice. */
|
|
325
|
+
export function contains(
|
|
326
|
+
ctx: MindContext,
|
|
327
|
+
ancestor: number,
|
|
328
|
+
descendant: number,
|
|
329
|
+
): boolean {
|
|
330
|
+
if (ancestor === descendant) return true;
|
|
331
|
+
const seen = new Set<number>([ancestor]);
|
|
332
|
+
const stack = [ancestor];
|
|
333
|
+
while (stack.length > 0) {
|
|
334
|
+
const rec = ctx.store.get(stack.pop()!);
|
|
335
|
+
if (!rec?.kids) continue;
|
|
336
|
+
for (const k of rec.kids) {
|
|
337
|
+
if (k === descendant) return true;
|
|
338
|
+
if (!seen.has(k)) {
|
|
339
|
+
seen.add(k);
|
|
340
|
+
stack.push(k);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ── Edge disambiguation (Section 6) ──────────────────────────────────────
|
|
348
|
+
|
|
349
|
+
/** The best-scoring item by cosine against `query`, among items scoring at
|
|
350
|
+
* or above `threshold` — the shared arg-max every Pattern-A "which of these
|
|
351
|
+
* resonates best" decision reduces to. `strict` picks the tie-break a
|
|
352
|
+
* caller needs: `true` keeps the first-seen leader on a tie (`>`), the
|
|
353
|
+
* default lets a later equal score take it (`>=`). */
|
|
354
|
+
export function argmaxBy<T>(
|
|
355
|
+
items: Iterable<T>,
|
|
356
|
+
scoreOf: (item: T) => number,
|
|
357
|
+
threshold: number,
|
|
358
|
+
strict: boolean = false,
|
|
359
|
+
): { item: T; score: number } | null {
|
|
360
|
+
let best: { item: T; score: number } | null = null;
|
|
361
|
+
for (const item of items) {
|
|
362
|
+
const score = scoreOf(item);
|
|
363
|
+
const bar = best?.score ?? threshold;
|
|
364
|
+
if (strict ? score > bar : score >= bar) best = { item, score };
|
|
365
|
+
}
|
|
366
|
+
return best;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function argmaxCosine<T>(
|
|
370
|
+
query: Vec,
|
|
371
|
+
items: Iterable<T>,
|
|
372
|
+
vecOf: (item: T) => Vec | null | undefined,
|
|
373
|
+
threshold: number,
|
|
374
|
+
strict: boolean = false,
|
|
375
|
+
): { item: T; score: number } | null {
|
|
376
|
+
return argmaxBy(
|
|
377
|
+
items,
|
|
378
|
+
(item) => {
|
|
379
|
+
const v = vecOf(item);
|
|
380
|
+
return v ? cosine(query, v) : -Infinity;
|
|
381
|
+
},
|
|
382
|
+
threshold,
|
|
383
|
+
strict,
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** The guided-or-first continuation of a node, as answer-shaped bytes source:
|
|
388
|
+
* chooseNext under the response guide, falling back to the FIRST-inserted
|
|
389
|
+
* edge — the one no-guide convention chooseNext, project() and the search's
|
|
390
|
+
* formRules all share. undefined when the node has no continuation. */
|
|
391
|
+
export function guidedFirst(
|
|
392
|
+
ctx: MindContext,
|
|
393
|
+
id: number,
|
|
394
|
+
): number | undefined {
|
|
395
|
+
const pick = guidedNext(ctx, id);
|
|
396
|
+
if (pick !== undefined) return pick;
|
|
397
|
+
// No guide in flight (or nothing chosen): the first-inserted edge, read
|
|
398
|
+
// with LIMIT 1 — never the full fan-out.
|
|
399
|
+
const nx = ctx.store.nextFirst(id, 1);
|
|
400
|
+
return nx.length > 0 ? nx[0] : undefined;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function guidedNext(
|
|
404
|
+
ctx: MindContext,
|
|
405
|
+
node: number,
|
|
406
|
+
): number | undefined {
|
|
407
|
+
if (ctx._edgeGuide === null) return undefined;
|
|
408
|
+
// The pick memo is BYPASSED while a rationale trace is attached — the same
|
|
409
|
+
// policy climbMemo and recogniseMemo follow (every mechanism must emit its
|
|
410
|
+
// own steps; a memo hit would swallow the repeat's `disambiguate` step).
|
|
411
|
+
// Consistency does not need the memo: chooseNext is a pure function of the
|
|
412
|
+
// (read-only) store and the guide, so recomputation yields the same pick.
|
|
413
|
+
if (!ctx.trace) {
|
|
414
|
+
const memo = ctx._edgeChoice.get(node);
|
|
415
|
+
if (memo !== undefined) return memo === -1 ? undefined : memo;
|
|
416
|
+
}
|
|
417
|
+
const pick = chooseNext(ctx, node, ctx._edgeGuide);
|
|
418
|
+
if (!ctx.trace) ctx._edgeChoice.set(node, pick ?? -1);
|
|
419
|
+
return pick;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Disambiguate among a node's learnt continuations by distributional
|
|
423
|
+
* support. NOTE the `guide` contract: its VALUE is deliberately unused —
|
|
424
|
+
* only its PRESENCE gates disambiguation (a null guide means no query is in
|
|
425
|
+
* flight, so structural walkers keep plain first-edge behaviour). The
|
|
426
|
+
* gist-cosine of short answer candidates against a query guide is dominated
|
|
427
|
+
* by accidental byte-pattern correlations, not semantic relatedness, so the
|
|
428
|
+
* evidence consulted is structural: each candidate's reverse-edge support
|
|
429
|
+
* count (see below). Contrast {@link chooseAmong}, the REVERSE-direction
|
|
430
|
+
* disambiguator, whose candidates are whole learnt contexts — long enough
|
|
431
|
+
* that their perceived gists ARE semantically meaningful — and which
|
|
432
|
+
* therefore scores by guide cosine. The two directions consult different
|
|
433
|
+
* halves of the evidence on purpose. */
|
|
434
|
+
export function chooseNext(
|
|
435
|
+
ctx: MindContext,
|
|
436
|
+
id: number,
|
|
437
|
+
guide?: Vec | null,
|
|
438
|
+
): number | undefined {
|
|
439
|
+
// CAPPED read: only the first √N continuations are ever candidates (the
|
|
440
|
+
// documented hub trade), so only they are read — a hub context's full
|
|
441
|
+
// fan-out is corpus-sized and must never be materialised. hubBound ≥ 2,
|
|
442
|
+
// so the single-continuation fast path below stays exact.
|
|
443
|
+
const nx = ctx.store.nextFirst(id, hubBound(ctx));
|
|
444
|
+
if (nx.length === 0) return undefined;
|
|
445
|
+
if (nx.length === 1 || !guide) return nx[0];
|
|
446
|
+
|
|
447
|
+
// Cap candidates at √N — the same bound the original chooseAmong used.
|
|
448
|
+
// A hub context can accumulate thousands of continuations; the best-fit
|
|
449
|
+
// one is among the first √N by insertion order (edges are never deleted,
|
|
450
|
+
// so the oldest are the most established). A strongly-supported edge
|
|
451
|
+
// inserted beyond the cap is invisible here — the deliberate trade
|
|
452
|
+
// against paying O(fan-out) count reads on every disambiguation.
|
|
453
|
+
const capped = nx; // already the hub-capped prefix, by the read above
|
|
454
|
+
|
|
455
|
+
// Distributional-evidence disambiguation, consulting BOTH read-outs of the
|
|
456
|
+
// evidence the training poured:
|
|
457
|
+
// 1. prevCount — how many DISTINCT contexts predict this candidate (one
|
|
458
|
+
// indexed COUNT; never a materialisation — a common continuation's
|
|
459
|
+
// reverse fan-in is corpus-sized). Diversity of independent evidence
|
|
460
|
+
// is the primary signal: three different formulations agreeing beat
|
|
461
|
+
// one formulation repeated.
|
|
462
|
+
// 2. haloMass — how many episode signatures were poured into the
|
|
463
|
+
// candidate's halo (repetition counts). The tie-break among equally
|
|
464
|
+
// diverse candidates: a fact reinforced across many episodes is more
|
|
465
|
+
// corroborated than one seen once, and this is the DIRECT measure of
|
|
466
|
+
// that — consulting only the structural count would leave poured
|
|
467
|
+
// evidence on the table.
|
|
468
|
+
// When both are equal, first-inserted wins (backward compatible).
|
|
469
|
+
let best = capped[0];
|
|
470
|
+
let bestSupport = ctx.store.prevCount(best);
|
|
471
|
+
let bestMass = ctx.store.haloMass(best);
|
|
472
|
+
for (let i = 1; i < capped.length; i++) {
|
|
473
|
+
const support = ctx.store.prevCount(capped[i]);
|
|
474
|
+
if (support < bestSupport) continue;
|
|
475
|
+
const mass = ctx.store.haloMass(capped[i]);
|
|
476
|
+
if (support > bestSupport || mass > bestMass) {
|
|
477
|
+
best = capped[i];
|
|
478
|
+
bestSupport = support;
|
|
479
|
+
bestMass = mass;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// Trace is built lazily — the filter + map below only execute when a
|
|
484
|
+
// trace listener is attached, so the common (no-trace) path pays only
|
|
485
|
+
// for the prevCount calls in the loop above, never for extra rItemShort
|
|
486
|
+
// byte-reads.
|
|
487
|
+
if (ctx.trace) {
|
|
488
|
+
const others = capped.filter((c) => c !== best);
|
|
489
|
+
ctx.trace.step(
|
|
490
|
+
"disambiguate",
|
|
491
|
+
[rItemShort(ctx, best, "halo-evidence", bestSupport)],
|
|
492
|
+
others.map((c) =>
|
|
493
|
+
rItemShort(ctx, c, "candidate", ctx.store.prevCount(c))
|
|
494
|
+
),
|
|
495
|
+
`${capped.length} continuations — distributional evidence selects ` +
|
|
496
|
+
`the most corroborated (distinct contexts ${bestSupport}, ` +
|
|
497
|
+
`poured mass ${bestMass})`,
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
return best;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** The perceived gist of a candidate node, through the session gist cache.
|
|
505
|
+
* Re-gisting a candidate is a full river fold of its bytes — the measured
|
|
506
|
+
* recall bottleneck (a hub context offers up to √N continuations, EACH
|
|
507
|
+
* re-perceived per pick). A node's bytes are immutable and perception is
|
|
508
|
+
* pure, so the cached gist is valid for the store's lifetime. Exported for
|
|
509
|
+
* every "score node ids against a guide" decision (chooseAmong here, the
|
|
510
|
+
* bridge's junction pick) so they share ONE cache and one convention. */
|
|
511
|
+
export function candidateGist(ctx: MindContext, c: number): Vec | null {
|
|
512
|
+
const hit = ctx._gistCache.get(c);
|
|
513
|
+
if (hit !== undefined) return hit;
|
|
514
|
+
const b = read(ctx, c);
|
|
515
|
+
if (b.length === 0) return null;
|
|
516
|
+
const g = gistOf(ctx, b);
|
|
517
|
+
ctx._gistCache.set(c, g);
|
|
518
|
+
return g;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
export function chooseAmong(
|
|
522
|
+
ctx: MindContext,
|
|
523
|
+
candidates: readonly number[],
|
|
524
|
+
guide: Vec,
|
|
525
|
+
): { id: number; score: number } {
|
|
526
|
+
const capped = hubCap(ctx, candidates);
|
|
527
|
+
const found = argmaxCosine(
|
|
528
|
+
guide,
|
|
529
|
+
capped,
|
|
530
|
+
(c) => candidateGist(ctx, c),
|
|
531
|
+
-Infinity,
|
|
532
|
+
true,
|
|
533
|
+
);
|
|
534
|
+
return found
|
|
535
|
+
? { id: found.item, score: found.score }
|
|
536
|
+
: { id: candidates[0], score: -Infinity };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ── Trace shim (used by chooseNext before trace module is loaded) ────────
|
|
540
|
+
|
|
541
|
+
import { decodeText } from "./rationale.js";
|
|
542
|
+
import type { RationaleItem } from "./rationale.js";
|
|
543
|
+
|
|
544
|
+
function rItemShort(
|
|
545
|
+
ctx: MindContext,
|
|
546
|
+
id: number,
|
|
547
|
+
role?: string,
|
|
548
|
+
score?: number,
|
|
549
|
+
): RationaleItem {
|
|
550
|
+
return {
|
|
551
|
+
text: decodeText(read(ctx, id)),
|
|
552
|
+
node: id,
|
|
553
|
+
role,
|
|
554
|
+
score,
|
|
555
|
+
};
|
|
556
|
+
}
|