@hviana/sema 0.4.0 → 0.4.2

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 (154) hide show
  1. package/CONTRIBUTING.md +92 -10
  2. package/LICENSE.md +2 -2
  3. package/package.json +1 -1
  4. package/src/ingest-cache.ts +4 -0
  5. package/src/meter.ts +5 -0
  6. package/src/mind/attention.ts +18 -1
  7. package/src/mind/bridge.ts +292 -54
  8. package/src/mind/junction.ts +21 -7
  9. package/src/mind/match.ts +92 -1
  10. package/src/mind/mechanisms/cast.ts +12 -0
  11. package/src/mind/mechanisms/confluence.ts +30 -1
  12. package/src/mind/mechanisms/cover.ts +36 -4
  13. package/src/mind/mechanisms/recall.ts +21 -44
  14. package/src/mind/mind.ts +39 -2
  15. package/src/mind/pipeline-mechanism.ts +86 -4
  16. package/src/mind/pipeline.ts +1 -1
  17. package/src/mind/reasoning.ts +15 -8
  18. package/src/mind/recognition.ts +40 -0
  19. package/src/mind/resonance.ts +0 -0
  20. package/src/mind/traverse.ts +17 -15
  21. package/src/mind/types.ts +10 -0
  22. package/test/49-natural-units-synonym-bridge.test.mjs +56 -15
  23. package/dist/example/demo.d.ts +0 -1
  24. package/dist/example/demo.js +0 -39
  25. package/dist/example/train_base.d.ts +0 -87
  26. package/dist/example/train_base.js +0 -2252
  27. package/dist/src/alphabet.d.ts +0 -7
  28. package/dist/src/alphabet.js +0 -33
  29. package/dist/src/alu/src/alu.d.ts +0 -185
  30. package/dist/src/alu/src/alu.js +0 -440
  31. package/dist/src/alu/src/expr.d.ts +0 -61
  32. package/dist/src/alu/src/expr.js +0 -318
  33. package/dist/src/alu/src/index.d.ts +0 -11
  34. package/dist/src/alu/src/index.js +0 -19
  35. package/dist/src/alu/src/kernel-arith.d.ts +0 -16
  36. package/dist/src/alu/src/kernel-arith.js +0 -264
  37. package/dist/src/alu/src/kernel-bits.d.ts +0 -19
  38. package/dist/src/alu/src/kernel-bits.js +0 -152
  39. package/dist/src/alu/src/kernel-logic.d.ts +0 -4
  40. package/dist/src/alu/src/kernel-logic.js +0 -60
  41. package/dist/src/alu/src/kernel-nd.d.ts +0 -3
  42. package/dist/src/alu/src/kernel-nd.js +0 -208
  43. package/dist/src/alu/src/kernel-numeric.d.ts +0 -54
  44. package/dist/src/alu/src/kernel-numeric.js +0 -366
  45. package/dist/src/alu/src/operation.d.ts +0 -168
  46. package/dist/src/alu/src/operation.js +0 -189
  47. package/dist/src/alu/src/parser.d.ts +0 -221
  48. package/dist/src/alu/src/parser.js +0 -577
  49. package/dist/src/alu/src/resonance.d.ts +0 -55
  50. package/dist/src/alu/src/resonance.js +0 -126
  51. package/dist/src/alu/src/text.d.ts +0 -31
  52. package/dist/src/alu/src/text.js +0 -73
  53. package/dist/src/alu/src/value.d.ts +0 -109
  54. package/dist/src/alu/src/value.js +0 -300
  55. package/dist/src/alu/test/alu.test.d.ts +0 -1
  56. package/dist/src/alu/test/alu.test.js +0 -764
  57. package/dist/src/bytes.d.ts +0 -14
  58. package/dist/src/bytes.js +0 -59
  59. package/dist/src/canon.d.ts +0 -26
  60. package/dist/src/canon.js +0 -57
  61. package/dist/src/config.d.ts +0 -111
  62. package/dist/src/config.js +0 -91
  63. package/dist/src/derive/src/deduction.d.ts +0 -136
  64. package/dist/src/derive/src/deduction.js +0 -159
  65. package/dist/src/derive/src/index.d.ts +0 -8
  66. package/dist/src/derive/src/index.js +0 -11
  67. package/dist/src/derive/src/priority-queue.d.ts +0 -20
  68. package/dist/src/derive/src/priority-queue.js +0 -73
  69. package/dist/src/derive/src/rewrite.d.ts +0 -56
  70. package/dist/src/derive/src/rewrite.js +0 -100
  71. package/dist/src/derive/src/trie.d.ts +0 -90
  72. package/dist/src/derive/src/trie.js +0 -217
  73. package/dist/src/derive/test/derive.test.d.ts +0 -1
  74. package/dist/src/derive/test/derive.test.js +0 -122
  75. package/dist/src/extension.d.ts +0 -37
  76. package/dist/src/extension.js +0 -7
  77. package/dist/src/geometry.d.ts +0 -175
  78. package/dist/src/geometry.js +0 -823
  79. package/dist/src/index.d.ts +0 -17
  80. package/dist/src/index.js +0 -19
  81. package/dist/src/ingest-cache.d.ts +0 -41
  82. package/dist/src/ingest-cache.js +0 -161
  83. package/dist/src/meter.d.ts +0 -171
  84. package/dist/src/meter.js +0 -269
  85. package/dist/src/mind/articulation.d.ts +0 -6
  86. package/dist/src/mind/articulation.js +0 -99
  87. package/dist/src/mind/attention.d.ts +0 -414
  88. package/dist/src/mind/attention.js +0 -2065
  89. package/dist/src/mind/bridge.d.ts +0 -39
  90. package/dist/src/mind/bridge.js +0 -738
  91. package/dist/src/mind/canonical.d.ts +0 -34
  92. package/dist/src/mind/canonical.js +0 -93
  93. package/dist/src/mind/graph-search.d.ts +0 -294
  94. package/dist/src/mind/graph-search.js +0 -996
  95. package/dist/src/mind/index.d.ts +0 -9
  96. package/dist/src/mind/index.js +0 -5
  97. package/dist/src/mind/junction.d.ts +0 -134
  98. package/dist/src/mind/junction.js +0 -331
  99. package/dist/src/mind/learning.d.ts +0 -75
  100. package/dist/src/mind/learning.js +0 -270
  101. package/dist/src/mind/match.d.ts +0 -166
  102. package/dist/src/mind/match.js +0 -565
  103. package/dist/src/mind/mechanisms/alu.d.ts +0 -4
  104. package/dist/src/mind/mechanisms/alu.js +0 -36
  105. package/dist/src/mind/mechanisms/cast.d.ts +0 -89
  106. package/dist/src/mind/mechanisms/cast.js +0 -773
  107. package/dist/src/mind/mechanisms/confluence.d.ts +0 -24
  108. package/dist/src/mind/mechanisms/confluence.js +0 -225
  109. package/dist/src/mind/mechanisms/cover.d.ts +0 -6
  110. package/dist/src/mind/mechanisms/cover.js +0 -203
  111. package/dist/src/mind/mechanisms/extraction.d.ts +0 -33
  112. package/dist/src/mind/mechanisms/extraction.js +0 -300
  113. package/dist/src/mind/mechanisms/recall.d.ts +0 -16
  114. package/dist/src/mind/mechanisms/recall.js +0 -388
  115. package/dist/src/mind/mind.d.ts +0 -330
  116. package/dist/src/mind/mind.js +0 -594
  117. package/dist/src/mind/pipeline-mechanism.d.ts +0 -172
  118. package/dist/src/mind/pipeline-mechanism.js +0 -382
  119. package/dist/src/mind/pipeline.d.ts +0 -49
  120. package/dist/src/mind/pipeline.js +0 -275
  121. package/dist/src/mind/primitives.d.ts +0 -66
  122. package/dist/src/mind/primitives.js +0 -306
  123. package/dist/src/mind/rationale.d.ts +0 -139
  124. package/dist/src/mind/rationale.js +0 -163
  125. package/dist/src/mind/reasoning.d.ts +0 -40
  126. package/dist/src/mind/reasoning.js +0 -272
  127. package/dist/src/mind/recognition.d.ts +0 -20
  128. package/dist/src/mind/recognition.js +0 -463
  129. package/dist/src/mind/resonance.d.ts +0 -23
  130. package/dist/src/mind/resonance.js +0 -0
  131. package/dist/src/mind/trace.d.ts +0 -15
  132. package/dist/src/mind/trace.js +0 -73
  133. package/dist/src/mind/traverse.d.ts +0 -124
  134. package/dist/src/mind/traverse.js +0 -649
  135. package/dist/src/mind/types.d.ts +0 -323
  136. package/dist/src/mind/types.js +0 -130
  137. package/dist/src/rabitq-ivf/src/database.d.ts +0 -113
  138. package/dist/src/rabitq-ivf/src/database.js +0 -201
  139. package/dist/src/rabitq-ivf/src/index.d.ts +0 -7
  140. package/dist/src/rabitq-ivf/src/index.js +0 -4
  141. package/dist/src/rabitq-ivf/src/ivf.d.ts +0 -200
  142. package/dist/src/rabitq-ivf/src/ivf.js +0 -1165
  143. package/dist/src/rabitq-ivf/src/prng.d.ts +0 -19
  144. package/dist/src/rabitq-ivf/src/prng.js +0 -36
  145. package/dist/src/rabitq-ivf/src/rabitq.d.ts +0 -95
  146. package/dist/src/rabitq-ivf/src/rabitq.js +0 -283
  147. package/dist/src/sema.d.ts +0 -31
  148. package/dist/src/sema.js +0 -63
  149. package/dist/src/store-sqlite.d.ts +0 -184
  150. package/dist/src/store-sqlite.js +0 -942
  151. package/dist/src/store.d.ts +0 -678
  152. package/dist/src/store.js +0 -1703
  153. package/dist/src/vec.d.ts +0 -31
  154. package/dist/src/vec.js +0 -109
@@ -1,649 +0,0 @@
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
- import { cosine } from "../vec.js";
9
- import { gistOf, read } from "./primitives.js";
10
- const structCaches = new WeakMap();
11
- // ── The shared ancestor-reach memo ──────────────────────────────────────
12
- //
13
- // `edgeAncestors` is a pure function of (node, N) over a read-only store —
14
- // asking never writes — so its result is reusable for as long as the store
15
- // is not written to. There used to be TWO memos and they never met: the
16
- // climb built a private one per call (computeAttention), while
17
- // `Precomputed.reachMemo` — documented as "one response-scoped memo serves
18
- // every mechanism that prices commonality" — was reached only by confluence.
19
- // The climb is by far the biggest consumer.
20
- //
21
- // Keyed off `ctx.climbMemo`'s OBJECT IDENTITY, exactly like the struct cache
22
- // above, which buys the right lifetime for free: a plain respond() has a
23
- // fresh climbMemo, so the memo is response-scoped; a conversation turn has
24
- // the conversation's persistent one, so it is conversation-scoped. That
25
- // matters — the stable-prefix fold makes each turn's subtree independent of
26
- // what follows, so 59–70% of a later turn's climb regions are byte-identical
27
- // repeats of an earlier turn's (measured on a 4-turn session), and every one
28
- // of them used to re-climb from cold.
29
- //
30
- // Budgeted, not unbounded (AGENTS §2.12): past the cap the whole map is
31
- // dropped and re-derived, costing a cold climb and never a wrong answer.
32
- const REACH_MEMO_MAX = 100_000;
33
- const reachCaches = new WeakMap();
34
- /** The reach memo this response should use — see the note above.
35
- *
36
- * A TRACED response always gets a fresh, empty one. `AncestorReach`'s
37
- * `visited`/`maxDepth`/`saturation` fields are populated only when a trace
38
- * is attached, so an entry deposited by an untraced earlier turn would
39
- * silently black out the reach detail of a later traced one; and the trace's
40
- * reach payload is serialised by ITERATING this map, which must therefore
41
- * hold what THIS climb consulted, not the whole conversation's history.
42
- * Consistent with AGENTS §2.11: a traced response is a different machine —
43
- * never benchmark with a trace attached. */
44
- export function sharedReachMemo(ctx) {
45
- if (ctx.trace !== null || ctx.climbMemo === null)
46
- return new Map();
47
- let m = reachCaches.get(ctx.climbMemo);
48
- if (m === undefined)
49
- reachCaches.set(ctx.climbMemo, m = new Map());
50
- else if (m.size >= REACH_MEMO_MAX)
51
- m.clear();
52
- return m;
53
- }
54
- function getStructCache(ctx) {
55
- if (ctx.climbMemo === null)
56
- return null;
57
- let c = structCaches.get(ctx.climbMemo);
58
- if (c === undefined) {
59
- structCaches.set(ctx.climbMemo, c = {
60
- hasNext: new Map(),
61
- prevCount: new Map(),
62
- hasParents: new Map(),
63
- });
64
- }
65
- return c;
66
- }
67
- /** Cached {@link Store.hasNext} — pure during one respond(). */
68
- function cachedHasNext(ctx, id, cache) {
69
- if (cache === null)
70
- return ctx.store.hasNext(id);
71
- let v = cache.hasNext.get(id);
72
- if (v === undefined) {
73
- v = ctx.store.hasNext(id);
74
- cache.hasNext.set(id, v);
75
- }
76
- return v;
77
- }
78
- /** Cached {@link Store.prevCount} — pure during one respond(). */
79
- function cachedPrevCount(ctx, id, cache) {
80
- if (cache === null)
81
- return ctx.store.prevCount(id);
82
- let v = cache.prevCount.get(id);
83
- if (v === undefined) {
84
- v = ctx.store.prevCount(id);
85
- cache.prevCount.set(id, v);
86
- }
87
- return v;
88
- }
89
- /** Cached {@link Store.hasParents} — pure during one respond(). */
90
- function cachedHasParents(ctx, id, cache) {
91
- if (cache === null)
92
- return ctx.store.hasParents(id);
93
- let v = cache.hasParents.get(id);
94
- if (v === undefined) {
95
- v = ctx.store.hasParents(id);
96
- cache.hasParents.set(id, v);
97
- }
98
- return v;
99
- }
100
- // ── Graph climbing ───────────────────────────────────────────────────────
101
- /** Climb the structural DAG from a node to its edge-bearing ancestor contexts.
102
- * Ascent stops at hub nodes (parents > √N) — their reach is non-discriminative.
103
- * When the start node has no structural parents, climbs from containment parents
104
- * (sub-span flat branches inheriting their chunks' context).
105
- *
106
- * `memo`, when given, caches whole climbs by start id for the duration of ONE
107
- * query (the store is read-only while a query is in flight, so a climb is a
108
- * pure function of the id). The consensus pipeline climbs the SAME anchors
109
- * repeatedly — regions sharing a chunk, and canonicalChunkId probing each
110
- * chunk's prefixes — so without the memo every repeat re-pays the full
111
- * fan-out reads. */
112
- export function edgeAncestors(ctx, id, contextCount, memo) {
113
- const hit = memo?.get(id);
114
- if (hit !== undefined)
115
- return hit;
116
- // BYTE-ATOM COMMONALITY. A single-byte leaf (implicit negative id) has no
117
- // structural parents BY CONSTRUCTION — atoms are never linked into the kid
118
- // or contain tables — so this climb cannot observe its containment at all.
119
- // The walk below would see only the atom's own direct edges and report
120
- // contextsReached ≈ 1, turning the MOST common content in the store into
121
- // the MOST discriminative voter (observed on a 325K-context store: every
122
- // recognised single-letter site voted full ln N for the one fact whose
123
- // continuation is that letter, and their pooled sum out-voted every
124
- // genuine anchor). An unmeasurable containment must not default to
125
- // "maximally rare": it is bounded below by the uniform expectation over
126
- // the byte alphabet — N contexts, each at least one chunk of up to W of
127
- // the 256 possible atoms, reach ≥ N·W/256 contexts per atom on average
128
- // (see {@link atomReach}). When that floor itself exceeds the hub bound
129
- // √N the atom is a hub at this corpus scale and the climb abstains
130
- // (saturated) — the atom's own edges remain fully traversable (tier-0
131
- // exact recall, chooseNext, project); only its say as a consensus voter
132
- // is withdrawn. On a small store the floor stays ≤ √N and the atom
133
- // climbs exactly as before, so single-letter facts keep working.
134
- if (id < 0 && atomIsHub(ctx, contextCount)) {
135
- const bound0 = boundFor(contextCount);
136
- const reach = {
137
- roots: [],
138
- contextsReached: 0,
139
- saturated: true,
140
- ...(ctx.trace
141
- ? {
142
- saturation: {
143
- reason: "byte-atom-commonality",
144
- node: id,
145
- observed: atomReach(ctx, contextCount),
146
- limit: bound0,
147
- },
148
- visited: 0,
149
- maxDepth: 0,
150
- }
151
- : {}),
152
- };
153
- memo?.set(id, reach);
154
- return reach;
155
- }
156
- const bound = boundFor(contextCount);
157
- const roots = [];
158
- const seen = new Set([id]);
159
- const ctxSeen = new Set();
160
- let saturated = false;
161
- // Provenance of the FIRST decision that saturated this climb — allocated
162
- // only when a trace is requested (see AncestorReach.saturation's doc); the
163
- // climb itself never reads it back.
164
- let satStop;
165
- // EXPAND-UNTIL-DECIDED: a reach is consumed either as a VOTE (which needs
166
- // contextsReached exactly, and only while ≤ √N — beyond that the region is
167
- // non-discriminative) or as an ABSTENTION (saturated — whose roots and
168
- // counts no consumer reads). So the climb may STOP the moment the answer
169
- // is decided:
170
- // • a node whose prev fan-in alone exceeds √N decides it (its
171
- // predecessors are √N+ distinct contexts) — no read needed, prevCount
172
- // is an indexed O(1);
173
- // • distinct contexts crossing √N decides it;
174
- // • a node with more than √N parents decides its own expansion (the
175
- // classic hub guard; the walk aborts rather than continue, which no
176
- // consumer can distinguish — saturated reaches are never voted).
177
- // Below every decision threshold the walk is EXACT — identical roots and
178
- // contexts to the unbounded climb — because prevFirst(√N) IS the full prev
179
- // list and parentsFirst(√N+1) IS the full parent list whenever they do not
180
- // decide. Work is bounded by √N contexts × the climb's local structure,
181
- // never by the corpus.
182
- const structCache = getStructCache(ctx);
183
- // LATERAL-BRANCH ACCOUNT — the cumulative dual of the per-node hub guard.
184
- // Within one deposit the ascent is a CHAIN (each node's first parent);
185
- // every parent BEYOND a node's first is an entry into another containing
186
- // structure (hash-consing: a shared subtree's extra parents are other
187
- // deposits' chunks). The per-node guard already declares a node with more
188
- // than √N parents non-discriminative; a climb whose ACCUMULATED lateral
189
- // entries exceed √N has spread across just as many distinct containing
190
- // structures — the same commonness, distributed along the cone instead of
191
- // concentrated at one node — and is decided: saturated. A deep chain in
192
- // ONE structure accrues no laterals, so legitimate deep scaffolding (a
193
- // fragment far down a long cumulative context) still climbs to its root
194
- // at any depth; what dies is the cross-structure drift that visited tens
195
- // of thousands of edge-free interiors (profiled on a 17.7M-node store:
196
- // ~20K distinct nodes per climb family, >95% unique — not memoisable)
197
- // while the context account never decided.
198
- let lateral = 0;
199
- // CLIMB READ-OUT (pure instrumentation, same contract as satStop): the
200
- // parallel `depths` stack mirrors every push/pop of `stack`, so a node's
201
- // ascent distance is known at its pop. Allocated only when a trace is
202
- // requested; the climb itself never reads any of these back.
203
- const depths = ctx.trace ? [] : null;
204
- let curDepth = 0;
205
- let visitedCount = 0;
206
- let maxDepth = 0;
207
- const visit = (x) => {
208
- if (ctx.meter)
209
- ctx.meter.ancestorVisits++;
210
- if (depths) {
211
- visitedCount++;
212
- if (curDepth > maxDepth)
213
- maxDepth = curDepth;
214
- }
215
- const hasNx = cachedHasNext(ctx, x, structCache);
216
- const pc = cachedPrevCount(ctx, x, structCache);
217
- if (hasNx || pc > 0) {
218
- roots.push(x);
219
- if (hasNx)
220
- ctxSeen.add(x);
221
- if (pc > bound) {
222
- // decided: ≥ pc > √N distinct contexts
223
- if (ctx.trace) {
224
- satStop = {
225
- reason: "predecessor-fan-in",
226
- node: x,
227
- observed: pc,
228
- limit: bound,
229
- };
230
- }
231
- return false;
232
- }
233
- for (const p of ctx.store.prevFirst(x, bound))
234
- ctxSeen.add(p);
235
- if (ctxSeen.size > bound) {
236
- // decided
237
- if (ctx.trace) {
238
- satStop = {
239
- reason: "distinct-context-limit",
240
- node: x,
241
- observed: ctxSeen.size,
242
- limit: bound,
243
- };
244
- }
245
- return false;
246
- }
247
- }
248
- const parents = ctx.store.parentsFirst(x, bound + 1);
249
- if (parents.length > bound) {
250
- // decided: hub
251
- if (ctx.trace) {
252
- satStop = {
253
- reason: "parent-fan-out",
254
- node: x,
255
- observed: parents.length,
256
- limit: bound,
257
- };
258
- }
259
- return false;
260
- }
261
- let fresh = 0;
262
- for (const p of parents) {
263
- if (!seen.has(p)) {
264
- seen.add(p);
265
- stack.push(p);
266
- depths?.push(curDepth + 1);
267
- fresh++;
268
- }
269
- }
270
- if (fresh > 1) {
271
- lateral += fresh - 1;
272
- if (lateral > bound) {
273
- // decided: cone-wide hub
274
- if (ctx.trace) {
275
- satStop = {
276
- reason: "lateral-cone-limit",
277
- node: x,
278
- observed: lateral,
279
- limit: bound,
280
- };
281
- }
282
- return false;
283
- }
284
- }
285
- return true;
286
- };
287
- const stack = [];
288
- const containment = !cachedHasParents(ctx, id, structCache);
289
- if (!containment) {
290
- stack.push(id);
291
- depths?.push(0);
292
- }
293
- // The containment seed is STREAMED in pages of √N: a distinctive window's
294
- // containers (which converge on one or two contexts, however many chunks
295
- // of one deposit repeat it) are walked IN FULL — exact — while a common
296
- // window's corpus-sized container list is abandoned at the first decision
297
- // above, after O(√N) pages at most (each page adds containers whose climbs
298
- // add contexts; √N distinct contexts decide).
299
- let containerOff = 0;
300
- let containersExhausted = !containment;
301
- climb: for (;;) {
302
- if (stack.length === 0) {
303
- if (containersExhausted)
304
- break;
305
- const page = ctx.store.containersSlice(id, containerOff, bound);
306
- containerOff += page.length;
307
- if (page.length < bound)
308
- containersExhausted = true;
309
- for (const c of page) {
310
- if (!seen.has(c)) {
311
- seen.add(c);
312
- stack.push(c);
313
- depths?.push(1);
314
- }
315
- }
316
- if (stack.length === 0) {
317
- if (containerOff === 0) {
318
- stack.push(id); // no containers at all
319
- depths?.push(0);
320
- }
321
- else
322
- break;
323
- }
324
- }
325
- while (stack.length > 0) {
326
- let x = stack.pop();
327
- if (depths)
328
- curDepth = depths.pop();
329
- // TRANSPARENT-CHAIN HOP: a node with no edges in or out and exactly one
330
- // parent contributes nothing here — no root, no context, no lateral
331
- // entry — so the run to its first non-transparent ancestor is skipped
332
- // in ONE store read (Store.chainRun) instead of three probes per node.
333
- // The interior nodes still enter `seen`, exactly as a node-at-a-time
334
- // ascent would have recorded them at push time, so sibling entries into
335
- // the same chain keep identical fresh/lateral accounting; and if the
336
- // terminal was already seen (another chain merged into this one first),
337
- // it is not visited twice — the same dedup the push-time seen-check
338
- // used to provide.
339
- const run = ctx.store.chainRun(x);
340
- if (run.length > 1) {
341
- const top = run[run.length - 1];
342
- const dup = seen.has(top);
343
- for (let i = 1; i < run.length; i++)
344
- seen.add(run[i]);
345
- if (dup)
346
- continue;
347
- x = top;
348
- // The chain's interior hops are part of the terminal's ascent
349
- // distance — count them exactly as a node-at-a-time ascent would.
350
- if (depths)
351
- curDepth += run.length - 1;
352
- }
353
- if (!visit(x)) {
354
- saturated = true;
355
- break climb;
356
- }
357
- }
358
- }
359
- const reach = {
360
- roots,
361
- contextsReached: ctxSeen.size,
362
- saturated,
363
- ...(saturated && satStop ? { saturation: satStop } : {}),
364
- ...(depths ? { visited: visitedCount, maxDepth } : {}),
365
- };
366
- memo?.set(id, reach);
367
- return reach;
368
- }
369
- /** Convenience: forward edges of a node. */
370
- export function nextOf(ctx, id) {
371
- return ctx.store.next(id);
372
- }
373
- /** Convenience: reverse edges of a node. */
374
- export function prevOf(ctx, id) {
375
- return ctx.store.prev(id);
376
- }
377
- /** The uniform-expectation floor on a byte atom's corpus commonality: N
378
- * learnt contexts, each at least one perception chunk of up to W of the 256
379
- * possible byte values, contain a given atom in ≥ N·W/256 contexts on
380
- * average. An atom's TRUE containment is unmeasurable (atoms carry no
381
- * kid/contain links by construction), so this floor is the honest stand-in:
382
- * derived entirely from the corpus scale N, the perception window W, and
383
- * the alphabet size — never tuned. */
384
- export function atomReach(ctx, contextCount) {
385
- return Math.max(1, Math.ceil((contextCount * ctx.space.maxGroup) / 256));
386
- }
387
- /** Whether a byte atom is a hub at this corpus scale — its commonality floor
388
- * {@link atomReach} exceeds the hub bound √N. Below it (small stores) an
389
- * atom votes and is recognised exactly as any stored form; above it the
390
- * alphabet is scaffolding everywhere and abstains. */
391
- export function atomIsHub(ctx, contextCount) {
392
- return atomReach(ctx, contextCount) > boundFor(contextCount);
393
- }
394
- /** Whether a node LEADS SOMEWHERE — it bears a continuation edge or a halo.
395
- * The admission predicate recognition filters sites with (HOW_IT_WORKS
396
- * §15.3): a form that leads nowhere contributes nothing to any derivation.
397
- * Runs once per candidate span on the recognition hot path — `hasNext` is
398
- * cached per response (the same flat-branch ids are probed across prefix
399
- * variants by canonicalChunkId). `hasHalo` is not cached: it's a single
400
- * indexed point probe per candidate, and the candidates that reach this
401
- * check have already been filtered by hasNext above in edgeAncestors. */
402
- export function leadsSomewhere(ctx, id) {
403
- const memo = getStructCache(ctx);
404
- if (cachedHasNext(ctx, id, memo))
405
- return true;
406
- return ctx.store.hasHalo(id);
407
- }
408
- /** The structural IDF read of ONE node: how many distinct learnt contexts
409
- * its containment/edge climb reaches, or Infinity when it reaches none or
410
- * saturates (no usable identity evidence). The number every
411
- * discriminative-vs-scaffolding decision derives from — paired with the
412
- * half-dominance convention (geometry.dominates(reach, N)): content
413
- * reaching a corpus MINORITY of contexts discriminates (an entity, a
414
- * filler); content reaching a majority is frame scaffolding. */
415
- export function reachOf(ctx, id, contextCount, memo) {
416
- const r = edgeAncestors(ctx, id, contextCount, memo);
417
- if (r.saturated || r.roots.length === 0)
418
- return Infinity;
419
- return Math.max(1, r.contextsReached);
420
- }
421
- /** The corpus scale N — the count of DISTINCT learnt contexts, floored at 2
422
- * so its derived readings (ln N in the consensus floor, √N in the hub bound)
423
- * stay meaningful on a near-empty store. The one definition every consumer
424
- * of "how big is this corpus?" reads. */
425
- export function corpusN(ctx) {
426
- return Math.max(2, ctx.store.edgeSourceCount());
427
- }
428
- /** The hub bound √N itself (≥ 2 always, since N is floored at 2) — for
429
- * consumers that pass it to the store's LIMITed reads instead of capping a
430
- * materialised list. {@link hubCap} is the list-side reading of the same
431
- * convention. */
432
- export function hubBound(ctx) {
433
- return boundFor(corpusN(ctx));
434
- }
435
- /** √N for an EXPLICIT context count — the ctx-free reading of {@link
436
- * hubBound}, for the callers inside this module that are handed a count
437
- * rather than a context ({@link edgeAncestors}, {@link atomIsHub}). The
438
- * floor at 2 matches {@link corpusN}'s, so both readings agree for every
439
- * input: the two used to be spelled out inline, once WITH the floor and
440
- * once without, in the same function. */
441
- function boundFor(contextCount) {
442
- return Math.ceil(Math.sqrt(Math.max(2, contextCount)));
443
- }
444
- /** Cap a candidate list at the hub bound √N (insertion order) — the ONE
445
- * fan-out convention every walk and disambiguation uses (see HOW_IT_WORKS
446
- * §8.6). A node connected to more than √N others is a hub whose individual
447
- * connections carry ~no discriminative information; materialising or scoring
448
- * them all would make single decisions scale with the corpus. */
449
- export function hubCap(ctx, ids) {
450
- const bound = hubBound(ctx);
451
- return ids.length > bound ? ids.slice(0, bound) : ids;
452
- }
453
- /** Whether `descendant` lies within `ancestor`'s subtree — a structural DAG
454
- * relation read off the hash-consed `kids` lists, by a bounded explicit-stack
455
- * descent. Used by articulation to keep a voice from revoicing a fragment
456
- * OF that voice. */
457
- export function contains(ctx, ancestor, descendant) {
458
- if (ancestor === descendant)
459
- return true;
460
- const seen = new Set([ancestor]);
461
- const stack = [ancestor];
462
- while (stack.length > 0) {
463
- const rec = ctx.store.get(stack.pop());
464
- if (!rec?.kids)
465
- continue;
466
- for (const k of rec.kids) {
467
- if (k === descendant)
468
- return true;
469
- if (!seen.has(k)) {
470
- seen.add(k);
471
- stack.push(k);
472
- }
473
- }
474
- }
475
- return false;
476
- }
477
- // ── Edge disambiguation (Section 6) ──────────────────────────────────────
478
- /** The best-scoring item by cosine against `query`, among items scoring at
479
- * or above `threshold` — the shared arg-max every Pattern-A "which of these
480
- * resonates best" decision reduces to. `strict` picks the tie-break a
481
- * caller needs: `true` keeps the first-seen leader on a tie (`>`), the
482
- * default lets a later equal score take it (`>=`). */
483
- export function argmaxBy(items, scoreOf, threshold, strict = false) {
484
- let best = null;
485
- for (const item of items) {
486
- const score = scoreOf(item);
487
- const bar = best?.score ?? threshold;
488
- if (strict ? score > bar : score >= bar)
489
- best = { item, score };
490
- }
491
- return best;
492
- }
493
- export function argmaxCosine(query, items, vecOf, threshold, strict = false) {
494
- return argmaxBy(items, (item) => {
495
- const v = vecOf(item);
496
- return v ? cosine(query, v) : -Infinity;
497
- }, threshold, strict);
498
- }
499
- /** The guided-or-first continuation of a node, as answer-shaped bytes source:
500
- * chooseNext under the response guide, falling back to the FIRST-inserted
501
- * edge — the one no-guide convention chooseNext, project() and the search's
502
- * formRules all share. undefined when the node has no continuation. */
503
- export function guidedFirst(ctx, id) {
504
- const pick = guidedNext(ctx, id);
505
- if (pick !== undefined)
506
- return pick;
507
- // No guide in flight (or nothing chosen): the first-inserted edge, read
508
- // with LIMIT 1 — never the full fan-out.
509
- const nx = ctx.store.nextFirst(id, 1);
510
- return nx.length > 0 ? nx[0] : undefined;
511
- }
512
- export function guidedNext(ctx, node) {
513
- if (ctx._edgeGuide === null)
514
- return undefined;
515
- // The pick memo is BYPASSED while a rationale trace is attached — the same
516
- // policy climbMemo and recogniseMemo follow (every mechanism must emit its
517
- // own steps; a memo hit would swallow the repeat's `disambiguate` step).
518
- // Consistency does not need the memo: chooseNext is a pure function of the
519
- // (read-only) store and the guide, so recomputation yields the same pick.
520
- if (!ctx.trace) {
521
- const memo = ctx._edgeChoice.get(node);
522
- if (memo !== undefined)
523
- return memo === -1 ? undefined : memo;
524
- }
525
- const pick = chooseNext(ctx, node, ctx._edgeGuide);
526
- if (!ctx.trace)
527
- ctx._edgeChoice.set(node, pick ?? -1);
528
- return pick;
529
- }
530
- /** Disambiguate among a node's learnt continuations by distributional
531
- * support. NOTE the `guide` contract: its VALUE is deliberately unused —
532
- * only its PRESENCE gates disambiguation (a null guide means no query is in
533
- * flight, so structural walkers keep plain first-edge behaviour). The
534
- * gist-cosine of short answer candidates against a query guide is dominated
535
- * by accidental byte-pattern correlations, not semantic relatedness, so the
536
- * evidence consulted is structural: each candidate's reverse-edge support
537
- * count (see below). Contrast {@link chooseAmong}, the REVERSE-direction
538
- * disambiguator, whose candidates are whole learnt contexts — long enough
539
- * that their perceived gists ARE semantically meaningful — and which
540
- * therefore scores by guide cosine. The two directions consult different
541
- * halves of the evidence on purpose. */
542
- export function chooseNext(ctx, id, guide) {
543
- // CAPPED read: only the first √N continuations are ever candidates (the
544
- // documented hub trade), so only they are read — a hub context's full
545
- // fan-out is corpus-sized and must never be materialised. hubBound ≥ 2,
546
- // so the single-continuation fast path below stays exact.
547
- const nx = ctx.store.nextFirst(id, hubBound(ctx));
548
- if (nx.length === 0)
549
- return undefined;
550
- if (nx.length === 1 || !guide)
551
- return nx[0];
552
- // Cap candidates at √N — the same bound the original chooseAmong used.
553
- // A hub context can accumulate thousands of continuations; the best-fit
554
- // one is among the first √N by insertion order (edges are never deleted,
555
- // so the oldest are the most established). A strongly-supported edge
556
- // inserted beyond the cap is invisible here — the deliberate trade
557
- // against paying O(fan-out) count reads on every disambiguation.
558
- const capped = nx; // already the hub-capped prefix, by the read above
559
- // Distributional-evidence disambiguation, consulting BOTH read-outs of the
560
- // evidence the training poured:
561
- // 1. prevCount — how many DISTINCT contexts predict this candidate (one
562
- // indexed COUNT; never a materialisation — a common continuation's
563
- // reverse fan-in is corpus-sized). Diversity of independent evidence
564
- // is the primary signal: three different formulations agreeing beat
565
- // one formulation repeated.
566
- // 2. haloMass — how many episode signatures were poured into the
567
- // candidate's halo (repetition counts). The tie-break among equally
568
- // diverse candidates: a fact reinforced across many episodes is more
569
- // corroborated than one seen once, and this is the DIRECT measure of
570
- // that — consulting only the structural count would leave poured
571
- // evidence on the table.
572
- // When both are equal, first-inserted wins (backward compatible).
573
- let best = capped[0];
574
- let bestSupport = ctx.store.prevCount(best);
575
- let bestMass = ctx.store.haloMass(best);
576
- for (let i = 1; i < capped.length; i++) {
577
- const support = ctx.store.prevCount(capped[i]);
578
- if (support < bestSupport)
579
- continue;
580
- const mass = ctx.store.haloMass(capped[i]);
581
- if (support > bestSupport || mass > bestMass) {
582
- best = capped[i];
583
- bestSupport = support;
584
- bestMass = mass;
585
- }
586
- }
587
- // NO consensusFloor gate here (tried and reverted — see
588
- // test/40-choosenext-scale-guard.test.mjs): that floor is calibrated for
589
- // POOLED, IDF-weighted CLIMB VOTES (recallByResonance, commitVotes), where
590
- // each corroborating region contributes at most ln N and the floor grows
591
- // with N exactly as that per-region ceiling does (HOW_IT_WORKS.md §8.6).
592
- // `bestSupport` here is a different kind of quantity — a raw prevCount of
593
- // how many training contexts predicted ONE destination, bounded by how
594
- // often that specific fact was retold, never by corpus size N. Gating an
595
- // N-invariant count against an N-growing threshold guarantees failure
596
- // once N is large enough, discarding genuinely, structurally dominant
597
- // edges (observed: a fact corroborated 2-to-1-1-1 refused at N≈325K,
598
- // falling back to a noisy concept-hop). The loop above already IS the
599
- // "genuinely competing" test: a tie leaves first-inserted as the pick
600
- // (test/30's own pinned behaviour); a strict winner is real evidence
601
- // regardless of corpus scale. Matches HOW_IT_WORKS.md §25's own
602
- // chooseNext pseudocode, which has no such floor.
603
- // Trace is built lazily — the filter + map below only execute when a
604
- // trace listener is attached, so the common (no-trace) path pays only
605
- // for the prevCount calls in the loop above, never for extra rItemShort
606
- // byte-reads.
607
- if (ctx.trace) {
608
- const others = capped.filter((c) => c !== best);
609
- ctx.trace.step("disambiguate", [rItemShort(ctx, best, "halo-evidence", bestSupport)], others.map((c) => rItemShort(ctx, c, "candidate", ctx.store.prevCount(c))), `${capped.length} continuations — distributional evidence selects ` +
610
- `the most corroborated (distinct contexts ${bestSupport}, ` +
611
- `poured mass ${bestMass})`);
612
- }
613
- return best;
614
- }
615
- /** The perceived gist of a candidate node, through the session gist cache.
616
- * Re-gisting a candidate is a full river fold of its bytes — the measured
617
- * recall bottleneck (a hub context offers up to √N continuations, EACH
618
- * re-perceived per pick). A node's bytes are immutable and perception is
619
- * pure, so the cached gist is valid for the store's lifetime. Exported for
620
- * every "score node ids against a guide" decision (chooseAmong here, the
621
- * bridge's junction pick) so they share ONE cache and one convention. */
622
- export function candidateGist(ctx, c) {
623
- const hit = ctx._gistCache.get(c);
624
- if (hit !== undefined)
625
- return hit;
626
- const b = read(ctx, c);
627
- if (b.length === 0)
628
- return null;
629
- const g = gistOf(ctx, b);
630
- ctx._gistCache.set(c, g);
631
- return g;
632
- }
633
- export function chooseAmong(ctx, candidates, guide) {
634
- const capped = hubCap(ctx, candidates);
635
- const found = argmaxCosine(guide, capped, (c) => candidateGist(ctx, c), -Infinity, true);
636
- return found
637
- ? { id: found.item, score: found.score }
638
- : { id: candidates[0], score: -Infinity };
639
- }
640
- // ── Trace shim (used by chooseNext before trace module is loaded) ────────
641
- import { decodeText } from "./rationale.js";
642
- function rItemShort(ctx, id, role, score) {
643
- return {
644
- text: decodeText(read(ctx, id)),
645
- node: id,
646
- role,
647
- score,
648
- };
649
- }