@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,655 @@
1
+ // match.ts — the ONE elementary operation behind every generalising mechanism:
2
+ // MATCH a learned structure against bytes, then PROJECT along a learned
3
+ // relation, gated by a derived threshold.
4
+ //
5
+ // Every grounding/generalisation mechanism in the mind is a configuration of
6
+ // this single (matcher, direction, gate) operation:
7
+ //
8
+ // mechanism matcher direction gate
9
+ // ─────────────────── ────────────────────────────── ───────────── ────────────────
10
+ // cover follow-edge exact (content-addressed) forward —
11
+ // concept hop halo sibling forward conceptThreshold
12
+ // recall tier 0–1 identity / whole-query gist fwd/reverse identityBar
13
+ // skill extraction locate() ladder (exact→halo→ read-out per-step gates
14
+ // gist) on the exemplar's frames
15
+ // CAST substitution alignGraded() (graded ladder: insert frame shapes
16
+ // literal W-grams → halo sites)
17
+ // CAST comparison analogyStrength() (halo, juxtapose significanceBar
18
+ // direct or mutual-sibling)
19
+ // multi-hop pivot byte containment forward —
20
+ // articulation halo sibling substitute conceptThreshold
21
+ //
22
+ // This module holds the shared vocabulary those configurations are built
23
+ // from — the MATCHERS (locate, alignRuns, alignGraded, analogyStrength) and
24
+ // the PROJECTIONS (follow, conceptHop, reverseContext, project) — so each
25
+ // mechanism file states only its configuration, never its own copy of the
26
+ // machinery. The gates all live in geometry.ts (derived, never tuned).
27
+ import { addInto, cosine, dot, normalize, zeros } from "../vec.js";
28
+ import { conceptThreshold, identityBar, significanceBar } from "../geometry.js";
29
+ import { indexOf } from "../bytes.js";
30
+ import { leafIdRun } from "./canonical.js";
31
+ import { foldTree, gistOf, perceive, read, resolve } from "./primitives.js";
32
+ import { argmaxCosine, chooseAmong, chooseNext, corpusN, edgeAncestors, guidedFirst, hubBound, hubCap, sharedReachMemo, } from "./traverse.js";
33
+ import { recognise, segment } from "./recognition.js";
34
+ // ═══════════════════════════════════════════════════════════════════════════
35
+ // MATCHERS — locating learned structure in/against bytes, by graded strictness
36
+ // ═══════════════════════════════════════════════════════════════════════════
37
+ /** The graded LOCATE ladder: find `needle` in `haystack` starting at
38
+ * `fromPos`, strictest matcher first, relaxing only when the stricter one
39
+ * fails. This is the read-out matcher skill extraction locates exemplar
40
+ * frames with.
41
+ *
42
+ * 1. exact — literal byte match (the fast path).
43
+ * 2. halo — the needle's distributional role matches a recognised query
44
+ * form (gate: conceptThreshold).
45
+ * 3. gist — the needle's perceived gist matches a query segment
46
+ * (gate: identityBar — scale-aware).
47
+ *
48
+ * Returns the absolute byte position, or −1. */
49
+ export function locate(ctx, haystack, needle, fromPos, sites) {
50
+ // 1. Exact match — fast, preserves backward compatibility.
51
+ const exact = indexOf(haystack.subarray(fromPos), needle, 0);
52
+ if (exact >= 0)
53
+ return fromPos + exact;
54
+ // 2. Halo-based: the frame bytes' distributional role matches a query form.
55
+ if (sites && sites.length > 0) {
56
+ const frameId = resolve(ctx, needle);
57
+ if (frameId !== null) {
58
+ const frameHalo = ctx.store.halo(frameId);
59
+ if (frameHalo) {
60
+ const bestSite = bestHaloMate(ctx, frameHalo, sites.filter((s) => s.start >= fromPos), (s) => ctx.store.halo(s.payload));
61
+ if (bestSite !== null)
62
+ return bestSite.item.start;
63
+ }
64
+ }
65
+ }
66
+ // 3. Gist resonance: the frame's perceived gist against query segments.
67
+ const frameGist = gistOf(ctx, needle);
68
+ const segments = segment(ctx, haystack.subarray(fromPos));
69
+ // The gist tier claims the WHOLE needle appears as a segment — an
70
+ // identity claim over `needle.length` bytes, so its bar is the
71
+ // scale-aware {@link identityBar} (one river window of tolerated foreign
72
+ // bytes), not the fixed estimator floor. For quantum-sized frames the
73
+ // two coincide; for long needles the fixed bar accepted segments that
74
+ // differed by whole windows.
75
+ const bestSeg = argmaxCosine(frameGist, segments, (s) => s.v, identityBar(ctx.store.D, ctx.space.maxGroup, needle.length), true);
76
+ if (bestSeg !== null)
77
+ return fromPos + bestSeg.item.start;
78
+ return -1;
79
+ }
80
+ /** The ALIGNED matcher: maximal literal matching runs between `query` and
81
+ * `ct` (a learned context's bytes), by seed-and-extend over
82
+ * `space.maxGroup`-sized n-gram seeds. Where locate() finds ONE position of
83
+ * a short frame, this finds EVERY run two whole structures share — the
84
+ * matcher CAST detects a woven query with. Returns non-overlapping runs
85
+ * sorted by query position. */
86
+ export function alignRuns(ctx, query, ct) {
87
+ if (ctx.meter) {
88
+ ctx.meter.alignments++;
89
+ // The alignment family's honest unit: the seed index is O(|query|) but
90
+ // the run extension is O(|query|·|ct|) in the worst case, and a weave
91
+ // that starts scanning conversation-length contexts shows up HERE long
92
+ // before it shows up in a call count.
93
+ ctx.meter.alignCells += query.length * ct.length;
94
+ }
95
+ // MEASURED AND REFUTED — seeding at the write side's unit floor W−1 instead
96
+ // of W. `canonicalWindows` interns both lengths precisely so a form
97
+ // straddling a group boundary is reachable from either cut, and the runs
98
+ // found here are exactly such remnants: test/29 C1's query shares only `ce `
99
+ // with `Ice is cold` — three bytes, never seeded at W, so that structure
100
+ // enters the weave carrying nothing but the scaffolding run every exemplar
101
+ // shares. But this is a byte MATCHER between two streams, not an index, and
102
+ // at W−1 the corpus is dense with spurious 3-byte agreements: the extra runs
103
+ // reshuffle which point claims which span, and test/29 A2 loses its analog.
104
+ // C1 does not pass either way. The store's unit floor does not transfer to
105
+ // the aligner's seed length.
106
+ const quantum = Math.min(ctx.space.maxGroup, ct.length);
107
+ if (quantum < 1 || query.length < quantum)
108
+ return [];
109
+ const gram = (b, at) => {
110
+ let s = "";
111
+ for (let i = 0; i < quantum; i++)
112
+ s += String.fromCharCode(b[at + i]);
113
+ return s;
114
+ };
115
+ const seeds = new Map();
116
+ for (let i = 0; i + quantum <= query.length; i++) {
117
+ const k2 = gram(query, i);
118
+ const bucket = seeds.get(k2);
119
+ if (bucket === undefined)
120
+ seeds.set(k2, [i]);
121
+ else
122
+ bucket.push(i);
123
+ }
124
+ const found = [];
125
+ for (let j = 0; j + quantum <= ct.length; j++) {
126
+ const bucket = seeds.get(gram(ct, j));
127
+ if (bucket === undefined)
128
+ continue;
129
+ for (const i of bucket) {
130
+ if (i > 0 && j > 0 && query[i - 1] === ct[j - 1])
131
+ continue;
132
+ let len = quantum;
133
+ while (i + len < query.length && j + len < ct.length &&
134
+ query[i + len] === ct[j + len])
135
+ len++;
136
+ found.push({ qs: i, qe: i + len, cs: j, len });
137
+ }
138
+ }
139
+ found.sort((a, b) => b.len - a.len);
140
+ const runs = [];
141
+ for (const r of found) {
142
+ const clash = runs.some((o) => (r.qs < o.qe && o.qs < r.qe) ||
143
+ (r.cs < o.cs + (o.qe - o.qs) && o.cs < r.cs + r.len));
144
+ if (!clash)
145
+ runs.push({ qs: r.qs, qe: r.qe, cs: r.cs });
146
+ }
147
+ return runs.sort((a, b) => a.qs - b.qs);
148
+ }
149
+ /** The GRADED alignment matcher: extends literal W-gram alignment
150
+ * ({@link alignRuns}) with halo-matched recognised sites in query regions
151
+ * that have no literal coverage. Same ladder as {@link locate}: literal
152
+ * first, then distributional role (halo-matched sites, gate:
153
+ * conceptThreshold, enforced by {@link bestHaloMate}). Returns weighted
154
+ * runs sorted by query position.
155
+ *
156
+ * `querySites` are the pre-computed recognition sites for the query
157
+ * (optional — when absent, only literal alignment fires and graded degrades
158
+ * to the original behaviour). Context sites are recognised internally. */
159
+ export function alignGraded(ctx, query, contextBytes, querySites) {
160
+ const lit = alignRuns(ctx, query, contextBytes);
161
+ const out = lit.map((r) => ({ ...r, weight: 1 }));
162
+ if (!querySites || querySites.length === 0)
163
+ return out;
164
+ // Mark query positions ALREADY covered by literal runs — halo fills gaps.
165
+ // If literal coverage is already complete, skip the halo step entirely
166
+ // (recognise is O(|ctx|·W) — wasted when every byte is accounted for).
167
+ const covered = new Uint8Array(query.length);
168
+ let gaps = false;
169
+ for (const r of lit) {
170
+ for (let i = r.qs; i < r.qe; i++)
171
+ covered[i] = 1;
172
+ }
173
+ for (let i = 0; i < query.length; i++) {
174
+ if (!covered[i]) {
175
+ gaps = true;
176
+ break;
177
+ }
178
+ }
179
+ if (!gaps)
180
+ return out;
181
+ // Recognise sites in the exemplar context — structural positions for halo
182
+ // matching. (Circular import with recognition.ts is safe: recognise() is
183
+ // called lazily, never at module load — the same pattern `segment` uses.)
184
+ const ctxSites = recognise(ctx, contextBytes).sites;
185
+ if (ctxSites.length === 0)
186
+ return out;
187
+ // Context sites with halos, hoisted: the same set serves every query site.
188
+ const ctxCands = ctxSites.filter((cs) => ctx.store.hasHalo(cs.payload));
189
+ if (ctxCands.length === 0)
190
+ return out;
191
+ // Candidate halos, also hoisted (lazily, first query site that needs them):
192
+ // bestHaloMate consults every candidate's halo PER QUERY SITE, and sites
193
+ // share the candidate set — without this memo the same few dozen halos were
194
+ // re-fetched thousands of times per response. Distinct payloads can repeat
195
+ // across sites, hence the map by payload id.
196
+ const ctxHalos = new Map();
197
+ const ctxHaloOf = (cs) => {
198
+ let h = ctxHalos.get(cs.payload);
199
+ if (h === undefined) {
200
+ h = ctx.store.halo(cs.payload);
201
+ ctxHalos.set(cs.payload, h);
202
+ }
203
+ return h;
204
+ };
205
+ for (const qs of querySites) {
206
+ // Only sites that overlap UNCOVERED query regions add new evidence.
207
+ let touchesGap = false;
208
+ for (let i = qs.start; i < qs.end; i++) {
209
+ if (!covered[i]) {
210
+ touchesGap = true;
211
+ break;
212
+ }
213
+ }
214
+ if (!touchesGap)
215
+ continue;
216
+ const qHalo = ctx.store.halo(qs.payload);
217
+ if (!qHalo)
218
+ continue;
219
+ // bestHaloMate already gates at conceptThreshold — no second check needed.
220
+ const match = bestHaloMate(ctx, qHalo, ctxCands, ctxHaloOf);
221
+ if (match === null)
222
+ continue;
223
+ out.push({
224
+ qs: qs.start,
225
+ qe: qs.end,
226
+ cs: match.item.start,
227
+ weight: match.score,
228
+ });
229
+ }
230
+ out.sort((a, b) => a.qs - b.qs);
231
+ return out;
232
+ }
233
+ /** The IN-LIST halo matcher: the best halo-mate for `halo` among EXPLICIT
234
+ * candidates, above the concept threshold — the list counterpart of
235
+ * {@link haloSiblings}, which asks the halo INDEX for candidates instead.
236
+ * Behind locate()'s halo step and articulation's voice matching; a third
237
+ * "best halo among these" decision must come here, not inline. */
238
+ export function bestHaloMate(ctx, halo, items, haloOf) {
239
+ return argmaxCosine(halo, items, haloOf, conceptThreshold(ctx.store.D));
240
+ }
241
+ /** The HALO-SIBLING matcher: the nodes that keep the same distributional
242
+ * company as `id`, nearest first — `resonateHalo` filtered to exclude the
243
+ * node itself and everything below `bar` (default: the concept threshold).
244
+ * `halo`, when the caller has already read the node's halo row, is reused
245
+ * instead of refetched (one read per relation). Returns [] for a node with
246
+ * no halo. The one sibling enumeration behind the concept hop, the
247
+ * reasoning stage's synonym expansion, and the analogy matcher below. */
248
+ const haloSiblingMemo = new WeakMap();
249
+ export async function haloSiblings(ctx, id, halo, bar = conceptThreshold(ctx.store.D)) {
250
+ // Per-response memo for the DEFAULT-ARGUMENT reading (the one the concept
251
+ // hop, the bridge's synonym tier, and reasoning's synonym expansion all
252
+ // use): the same node's siblings are asked for repeatedly within one
253
+ // response (bridge pairs share sides), each a full halo-ANN query, and the
254
+ // store is read-only while a response is in flight. Keyed by the response
255
+ // lifecycle object (ctx.climbMemo — fresh per respond, nulled after).
256
+ // Calls with an explicit halo or bar (analogyStrength's gated reading)
257
+ // bypass the memo — their filter differs.
258
+ const memoable = halo === undefined &&
259
+ bar === conceptThreshold(ctx.store.D) && ctx.climbMemo !== null;
260
+ let memo;
261
+ if (memoable) {
262
+ memo = haloSiblingMemo.get(ctx.climbMemo);
263
+ if (memo === undefined) {
264
+ haloSiblingMemo.set(ctx.climbMemo, memo = new Map());
265
+ }
266
+ const hit = memo.get(id);
267
+ if (hit !== undefined)
268
+ return hit;
269
+ }
270
+ const h = halo ?? ctx.store.halo(id);
271
+ const out = h
272
+ ? (await ctx.store.resonateHalo(h, ctx.cfg.haloQueryK))
273
+ .filter((sib) => sib.id !== id && sib.score >= bar)
274
+ : [];
275
+ if (memo !== undefined)
276
+ memo.set(id, out);
277
+ return out;
278
+ }
279
+ /** Bundle the distributional company of every addressable W-window in a
280
+ * byte span. This is the query-time counterpart of the write-side halo
281
+ * pours: no lexical unit or storage row is invented; the span is represented
282
+ * by VSA superposition of the window concepts the store already knows.
283
+ *
284
+ * Components are normalized before bundling so repetition mass remains
285
+ * evidence about each stored node, not an accidental weight on one window
286
+ * inside the composed phrase. Returns null when the corpus provides no
287
+ * distributional evidence for the span. */
288
+ export function spanHalo(ctx, bytes, from = 0, to = bytes.length) {
289
+ const W = ctx.space.maxGroup;
290
+ if (to - from < W)
291
+ return null;
292
+ if (ctx.meter)
293
+ ctx.meter.spanHalos++;
294
+ const out = zeros(ctx.store.D);
295
+ let found = false;
296
+ const added = new Set();
297
+ const episodeRoots = [];
298
+ const N = corpusN(ctx);
299
+ const reachMemo = sharedReachMemo(ctx);
300
+ const addHalo = (id) => {
301
+ if (added.has(id))
302
+ return;
303
+ const halo = ctx.store.halo(id);
304
+ if (halo === null)
305
+ return;
306
+ const norm = Math.sqrt(dot(halo, halo));
307
+ if (norm === 0)
308
+ return;
309
+ added.add(id);
310
+ addInto(out, halo, 1 / norm);
311
+ found = true;
312
+ };
313
+ const windowCount = to - from - W + 1;
314
+ const offsets = [];
315
+ const samples = Math.min(W, windowCount);
316
+ for (let i = 0; i < samples; i++) {
317
+ const relative = samples === 1
318
+ ? 0
319
+ : Math.floor((i * (windowCount - 1)) / (samples - 1));
320
+ const off = from + relative;
321
+ if (offsets[offsets.length - 1] !== off)
322
+ offsets.push(off);
323
+ }
324
+ for (const off of offsets) {
325
+ if (ctx.meter)
326
+ ctx.meter.spanHaloWindows++;
327
+ const ids = leafIdRun(ctx, bytes, off, off + W);
328
+ if (ids === null)
329
+ continue;
330
+ const id = ctx.store.findBranch(ids);
331
+ if (id === null)
332
+ continue;
333
+ addHalo(id);
334
+ // Canonical flat windows are retrieval addresses and normally carry no
335
+ // halo themselves. Their bounded structural ascent reaches the learned
336
+ // episode forms that contain them; bundling those forms' company is the
337
+ // distributional meaning of the window, derived entirely from existing
338
+ // containment and halo state.
339
+ if (!added.has(id)) {
340
+ episodeRoots.push(edgeAncestors(ctx, id, N, reachMemo).roots);
341
+ }
342
+ }
343
+ for (let rank = 0; added.size < ctx.cfg.haloQueryK; rank++) {
344
+ let any = false;
345
+ for (const roots of episodeRoots) {
346
+ if (rank >= roots.length)
347
+ continue;
348
+ any = true;
349
+ addHalo(roots[rank]);
350
+ if (added.size >= ctx.cfg.haloQueryK)
351
+ break;
352
+ }
353
+ if (!any)
354
+ break;
355
+ }
356
+ return found ? normalize(out) : null;
357
+ }
358
+ /** Distributional synonym evidence between arbitrary byte spans. Whole words
359
+ * need not be independently interned: their stored W-window occurrences are
360
+ * lifted to episode halos, bundled, and compared. The caller chooses the
361
+ * derived gate appropriate to its claim (concept identity or analogy). */
362
+ export function spanSynonymStrength(ctx, a, b) {
363
+ const ah = spanHalo(ctx, a);
364
+ const bh = spanHalo(ctx, b);
365
+ if (ah === null || bh === null)
366
+ return 0;
367
+ return cosine(ah, bh);
368
+ }
369
+ export async function analogyStrength(ctx, a, b) {
370
+ const ha = ctx.store.halo(a);
371
+ const hb = ctx.store.halo(b);
372
+ if (ha && hb) {
373
+ const bar = significanceBar(ctx.store.D);
374
+ const direct = cosine(ha, hb);
375
+ if (direct >= bar)
376
+ return { score: direct, halo: true };
377
+ const sibsA = await haloSiblings(ctx, a, ha, bar);
378
+ const sibsB = await haloSiblings(ctx, b, hb, bar);
379
+ let best = 0;
380
+ for (const x of sibsA) {
381
+ if (x.id === b)
382
+ continue;
383
+ const y = sibsB.find((s) => s.id === x.id);
384
+ if (y !== undefined) {
385
+ best = Math.max(best, Math.min(x.score, y.score));
386
+ }
387
+ }
388
+ if (best > 0)
389
+ return { score: best, halo: true };
390
+ }
391
+ return { score: sharedFrameStrength(ctx, a, b), halo: false };
392
+ }
393
+ /** The STRUCTURAL analogy tier: two nodes are analogs when their byte
394
+ * streams share a LEARNT frame — a content-addressed flat form of at least
395
+ * one full river window (W bytes, the perception quantum) that occurs in
396
+ * BOTH. This is what "playing the same role" means structurally: "Ice is
397
+ * cold" and "Steel is hard" share the learnt " is " frame even though they
398
+ * keep disjoint distributional company. Halos measure company by IDENTITY
399
+ * (company signatures — see sema.ts), so unrelated-company analogs must be
400
+ * validated by the frame itself, not by content leaking through halo
401
+ * vectors. Strength is the shared learnt coverage of the SHORTER side —
402
+ * a fraction, comparable to the cosine tiers above. Derived: the window
403
+ * is maxGroup, the same quantum differsByOneWindow and canonicalChunkId
404
+ * measure by; no tuned constants. */
405
+ export function sharedFrameStrength(ctx, a, b) {
406
+ const W = ctx.space.maxGroup;
407
+ const A = read(ctx, a);
408
+ const B = read(ctx, b);
409
+ if (A.length < W || B.length < W)
410
+ return 0;
411
+ // Mark every byte of the shorter side covered by a learnt W-window that
412
+ // also occurs in the longer side.
413
+ const [s, l] = A.length <= B.length ? [A, B] : [B, A];
414
+ const covered = new Uint8Array(s.length);
415
+ for (let off = 0; off + W <= s.length; off++) {
416
+ const win = s.subarray(off, off + W);
417
+ // Learnt: the window resolves as a content-addressed flat form.
418
+ const ids = leafIdRun(ctx, s, off, off + W);
419
+ if (ids === null || ctx.store.findBranch(ids) === null)
420
+ continue;
421
+ if (indexOf(l, win, 0) < 0)
422
+ continue;
423
+ covered.fill(1, off, off + W);
424
+ }
425
+ let n = 0;
426
+ for (let i = 0; i < s.length; i++)
427
+ n += covered[i];
428
+ return n >= W ? n / s.length : 0;
429
+ }
430
+ // ═══════════════════════════════════════════════════════════════════════════
431
+ // PROJECTIONS — what a matched node is projected ALONG (the direction)
432
+ // ═══════════════════════════════════════════════════════════════════════════
433
+ /** FORWARD through a synonym: the continuation an edge-less node borrows from
434
+ * a concept (halo) sibling — resonate the node's halo, take the first
435
+ * sibling above the concept threshold that itself has a direct edge. */
436
+ export async function conceptHop(ctx, id) {
437
+ for (const sib of await haloSiblings(ctx, id)) {
438
+ const hop = guidedFirst(ctx, sib.id);
439
+ if (hop !== undefined)
440
+ return hop;
441
+ }
442
+ return null;
443
+ }
444
+ /** FORWARD projection: follow continuation edges from a node to its fixpoint.
445
+ * The first hop may cross a concept (halo) link — a synonym. The rest
446
+ * follow direct edges. Convergence is intrinsic: the seen set guards
447
+ * against cycles. `guide` disambiguates multi-continuation nodes by
448
+ * resonance. */
449
+ export async function follow(ctx, id, guide) {
450
+ const seen = new Set([id]);
451
+ // First hop: a direct edge, else a concept sibling's edge (the synonym).
452
+ let next = chooseNext(ctx, id, guide);
453
+ if (next === undefined) {
454
+ const hop = await conceptHop(ctx, id);
455
+ if (hop === null)
456
+ return null;
457
+ next = hop;
458
+ }
459
+ // Direct successors to the fixpoint. Only the FIXPOINT's bytes are
460
+ // returned, so the walk tracks node ids and reads bytes exactly once at
461
+ // the end — a K-hop chain used to pay K full reconstructions and discard
462
+ // K−1 of them.
463
+ while (!seen.has(next)) {
464
+ seen.add(next);
465
+ const fwd = chooseNext(ctx, next, guide);
466
+ if (fwd === undefined || seen.has(fwd))
467
+ break;
468
+ next = fwd;
469
+ }
470
+ return read(ctx, next);
471
+ }
472
+ /** REVERSE projection: the context a learnt continuation follows, voiced as
473
+ * bytes. A common continuation ("Yes.") follows MANY contexts; with a
474
+ * `guide` the context whose gist resonates with the query wins (seat
475
+ * symmetry) — without one, the most-corroborated context wins (poured halo
476
+ * MASS, the direct measure of how many episodes established it), falling
477
+ * back to first-learnt on equal mass. Among many predecessors RECIPROCAL
478
+ * ones (mutual edges) are preferred when any exist (RC5). Callers that
479
+ * HAVE a query gist must pass it, or they silently change disambiguation
480
+ * regime.
481
+ *
482
+ * `rev`, when the caller has already materialised prevOf (one read per
483
+ * relation — a hub's reverse fan-in is corpus-sized), is reused instead of
484
+ * refetched. Returns null when there is no predecessor or the picked
485
+ * context reads empty (a zero-length context is no grounding: an empty
486
+ * Uint8Array is truthy, and returning it would flow a hollow "answer"
487
+ * onward). */
488
+ export function reverseContext(ctx, id, guide, rev) {
489
+ // CAPPED default read: only the first √N predecessors are ever candidates
490
+ // (hubCap below / in chooseAmong), so only they are read. hubBound ≥ 2
491
+ // keeps the single-predecessor shortcut exact.
492
+ const candidates = rev ?? ctx.store.prevFirst(id, hubBound(ctx));
493
+ if (candidates.length === 0)
494
+ return null;
495
+ // RECIPROCAL PREFERENCE: among many predecessors, one that `id` also
496
+ // continues TO (cand → id AND id → cand both learnt) is a mutually
497
+ // established pairing — the strongest structural evidence a predecessor
498
+ // can carry (bidirectional training deposits both directions of a genuine
499
+ // pair). A bare predecessor is one episode's adjacency; guide-resonance
500
+ // over bare predecessors favours whichever stored document merely
501
+ // CONTAINS the query's bytes (the linear fold's cosine is byte overlap —
502
+ // the observed "merci → unrelated French document" failure). One capped
503
+ // forward read decides; when no reciprocal exists, behaviour is unchanged
504
+ // — bare predecessors ARE the honest answer for a shared deposited
505
+ // continuation (two questions → one answer; audited by 31-audit C1), and
506
+ // this arm serves every mechanism's reverse projection, so abstaining
507
+ // here starves far more than the one containment failure it would fix.
508
+ let pool = candidates;
509
+ if (candidates.length > 1) {
510
+ const fwd = new Set(ctx.store.nextFirst(id, hubBound(ctx)));
511
+ if (fwd.size > 0) {
512
+ const mutual = candidates.filter((c) => fwd.has(c));
513
+ if (mutual.length > 0)
514
+ pool = mutual;
515
+ }
516
+ }
517
+ const pick = pool.length === 1
518
+ ? pool[0]
519
+ : guide
520
+ ? chooseAmong(ctx, pool, guide).id
521
+ : pickByMass(ctx, pool);
522
+ const g = read(ctx, pick);
523
+ return g.length > 0 ? g : null;
524
+ }
525
+ /** The most-corroborated candidate by poured halo mass (first-seen wins a
526
+ * tie). Capped at √N candidates by insertion order — the same hub bound
527
+ * every fan-out walk uses. */
528
+ function pickByMass(ctx, ids) {
529
+ const capped = hubCap(ctx, ids);
530
+ let best = capped[0];
531
+ let bestMass = ctx.store.haloMass(best);
532
+ for (let i = 1; i < capped.length; i++) {
533
+ const mass = ctx.store.haloMass(capped[i]);
534
+ if (mass > bestMass) {
535
+ best = capped[i];
536
+ bestMass = mass;
537
+ }
538
+ }
539
+ return best;
540
+ }
541
+ /** THE projection: ground a matched node to answer bytes — FORWARD to its
542
+ * continuation fixpoint (which may cross a concept hop), else REVERSE to
543
+ * the context it follows. This is the direction ladder every mechanism's
544
+ * final grounding step reduces to. */
545
+ export async function project(ctx, id, guide) {
546
+ const fc = await follow(ctx, id, guide);
547
+ if (fc)
548
+ return fc;
549
+ return reverseContext(ctx, id, guide);
550
+ }
551
+ // ── The span-shape family ───────────────────────────────────────────────────
552
+ //
553
+ // "Is this answer drawn from this context?" has TWO formally distinct
554
+ // readings, and the pair plus the anchor classifier built on them are SHARED
555
+ // machinery — extraction proposes span-shaped exemplars with them, the
556
+ // shared `Precomputed.spanShapedOf` container computes them, and fusion
557
+ // (reasoning.ts) gates on the strict one. They lived inside
558
+ // mechanisms/extraction.ts, so `pipeline-mechanism.ts` and `reasoning.ts`
559
+ // both had to import back OUT of a specific mechanism — an inversion the
560
+ // mechanism market forbids (AGENTS §2.6: the shared contract may not depend
561
+ // on any one mechanism; §2.5: a shared matcher belongs to this family, never
562
+ // to a mechanism's private helpers). Deleting extraction must not break the
563
+ // shared container, so they live here.
564
+ //
565
+ // • isSpanShaped — the OPEN reading (sparse in-order embedding).
566
+ // • containsSpan — the STRICT reading (contiguous run or resolved node).
567
+ // • skillExemplar — classify one anchor into (context, answer) using them.
568
+ //
569
+ // The two readings are NOT interchangeable; AGENTS §2.5 pins the distinction
570
+ // and each function's own doc states what breaks if it is substituted.
571
+ /** Check whether an anchor is a span-shaped skill exemplar: it represents a
572
+ * fact whose context and answer together form a span-in-context pattern.
573
+ * If the anchor has a nextOf continuation, that is the answer and the anchor
574
+ * itself is the context. Otherwise the anchor's prevOf parents provide
575
+ * candidate contexts, and the longest one whose span is span-shaped wins. */
576
+ export async function skillExemplar(ctx, anchor, guide) {
577
+ if (ctx.store.hasNext(anchor)) {
578
+ const contextBytes = read(ctx, anchor);
579
+ const answerBytes = await follow(ctx, anchor, guide);
580
+ if (answerBytes !== null && isSpanShaped(ctx, contextBytes, answerBytes)) {
581
+ return { contextBytes, answerBytes };
582
+ }
583
+ return null;
584
+ }
585
+ const answerBytes = read(ctx, anchor);
586
+ // Candidate contexts, capped at the hub bound (a common answer's reverse
587
+ // fan-in is corpus-sized).
588
+ const capped = ctx.store.prevFirst(anchor, hubBound(ctx));
589
+ const spanShaped = [];
590
+ for (const p of capped) {
591
+ const ctxB = read(ctx, p);
592
+ if (ctxB.length > 0 && isSpanShaped(ctx, ctxB, answerBytes)) {
593
+ spanShaped.push({ id: p, bytes: ctxB });
594
+ }
595
+ }
596
+ if (spanShaped.length === 0)
597
+ return null;
598
+ // Among span-shaped contexts, the longest wins (the smallest spanning frame
599
+ // heuristic's dual: more frame to locate in the query); the query gist,
600
+ // when given, breaks LENGTH TIES via chooseAmong — the same reverse-regime
601
+ // disambiguator every context pick uses, whose gist cache spares the
602
+ // re-fold this block once paid per tied candidate. Same strict first-seen
603
+ // tie-break as the hand loop it replaces.
604
+ const maxLen = Math.max(...spanShaped.map((s) => s.bytes.length));
605
+ const longest = spanShaped.filter((s) => s.bytes.length === maxLen);
606
+ let contextBytes = longest[0].bytes;
607
+ if (guide && longest.length > 1) {
608
+ const pick = chooseAmong(ctx, longest.map((s) => s.id), guide).id;
609
+ contextBytes = longest.find((s) => s.id === pick).bytes;
610
+ }
611
+ return { contextBytes, answerBytes };
612
+ }
613
+ /** Whether the answer is a SPARSE subsequence of the context (bytes in
614
+ * order, arbitrary gaps) — the OPEN span-shape reading (see the section
615
+ * note above). This is what lets extraction validate a MULTI-PIECE
616
+ * exemplar whose answer is stitched from several context runs — but it is
617
+ * deliberately permissive, so it must never be used as evidence that one
618
+ * span was "drawn from" another (see {@link containsSpan} for that).
619
+ *
620
+ * There is deliberately NO containsSpan pre-check here: strict containment
621
+ * IMPLIES the subsequence embedding (a contiguous run, or a resolved node —
622
+ * whose content-addressed identity means its bytes occur contiguously — is
623
+ * an in-order embedding with zero gaps), so the scan below decides alone,
624
+ * with the same truth value. The old pre-check re-perceived the context
625
+ * (a full river fold) per CANDIDATE in skillExemplar's √N-capped loop —
626
+ * pure cost, no discrimination. */
627
+ export function isSpanShaped(_ctx, context, answer) {
628
+ let ai = 0;
629
+ for (let ci = 0; ci < context.length && ai < answer.length; ci++) {
630
+ if (context[ci] === answer[ai])
631
+ ai++;
632
+ }
633
+ return ai === answer.length;
634
+ }
635
+ /** STRICT containment: the answer's resolved node appears in the context's
636
+ * folded tree, or the answer occurs as one CONTIGUOUS byte run of the
637
+ * context. This is real evidence the answer was drawn from the context.
638
+ * Fusion gates on this — the sparse-subsequence reading of
639
+ * {@link isSpanShaped} is trivially satisfied by short answers over long
640
+ * queries ("cold" is a gap-tolerant subsequence of most sentences holding
641
+ * c…o…l…d in order), and gating fusion on it silently starved multi-topic
642
+ * queries of their further points of attention. */
643
+ export function containsSpan(ctx, context, answer) {
644
+ const ansId = resolve(ctx, answer);
645
+ if (ansId !== null) {
646
+ let found = false;
647
+ foldTree(ctx, perceive(ctx, context), 0, (_n, _s, _e, node) => {
648
+ if (node === ansId)
649
+ found = true;
650
+ });
651
+ if (found)
652
+ return true;
653
+ }
654
+ return indexOf(context, answer, 0) >= 0;
655
+ }
@@ -0,0 +1,4 @@
1
+ import type { Alu } from "../../alu/src/alu.js";
2
+ import type { PipelineMechanism } from "../pipeline-mechanism.js";
3
+ /** Wrap the ALU as a {@link PipelineMechanism}. */
4
+ export declare function aluToMechanism(alu: Alu): PipelineMechanism;