@hviana/sema 0.4.2 → 0.4.4

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