@hviana/sema 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/AGENTS.md +470 -0
  2. package/AUTHORS.md +12 -0
  3. package/COMMERCIAL-LICENSE.md +19 -0
  4. package/CONTRIBUTING.md +15 -0
  5. package/HOW_IT_WORKS.md +4210 -0
  6. package/LICENSE.md +117 -0
  7. package/README.md +290 -0
  8. package/TRADEMARKS.md +19 -0
  9. package/example/demo.ts +46 -0
  10. package/example/train_base.ts +2675 -0
  11. package/index.html +893 -0
  12. package/package.json +25 -0
  13. package/src/alphabet.ts +34 -0
  14. package/src/alu/README.md +332 -0
  15. package/src/alu/src/alu.ts +541 -0
  16. package/src/alu/src/expr.ts +339 -0
  17. package/src/alu/src/index.ts +115 -0
  18. package/src/alu/src/kernel-arith.ts +377 -0
  19. package/src/alu/src/kernel-bits.ts +199 -0
  20. package/src/alu/src/kernel-logic.ts +102 -0
  21. package/src/alu/src/kernel-nd.ts +235 -0
  22. package/src/alu/src/kernel-numeric.ts +466 -0
  23. package/src/alu/src/operation.ts +344 -0
  24. package/src/alu/src/parser.ts +574 -0
  25. package/src/alu/src/resonance.ts +161 -0
  26. package/src/alu/src/text.ts +83 -0
  27. package/src/alu/src/value.ts +327 -0
  28. package/src/alu/test/alu.test.ts +1004 -0
  29. package/src/bytes.ts +62 -0
  30. package/src/config.ts +227 -0
  31. package/src/derive/README.md +295 -0
  32. package/src/derive/src/deduction.ts +263 -0
  33. package/src/derive/src/index.ts +24 -0
  34. package/src/derive/src/priority-queue.ts +70 -0
  35. package/src/derive/src/rewrite.ts +127 -0
  36. package/src/derive/src/trie.ts +242 -0
  37. package/src/derive/test/derive.test.ts +137 -0
  38. package/src/extension.ts +42 -0
  39. package/src/geometry.ts +511 -0
  40. package/src/index.ts +38 -0
  41. package/src/ingest-cache.ts +224 -0
  42. package/src/mind/articulation.ts +137 -0
  43. package/src/mind/attention.ts +1061 -0
  44. package/src/mind/canonical.ts +107 -0
  45. package/src/mind/graph-search.ts +1100 -0
  46. package/src/mind/index.ts +18 -0
  47. package/src/mind/junction.ts +347 -0
  48. package/src/mind/learning.ts +246 -0
  49. package/src/mind/match.ts +507 -0
  50. package/src/mind/mechanisms/alu.ts +33 -0
  51. package/src/mind/mechanisms/cast.ts +568 -0
  52. package/src/mind/mechanisms/confluence.ts +268 -0
  53. package/src/mind/mechanisms/cover.ts +248 -0
  54. package/src/mind/mechanisms/extraction.ts +422 -0
  55. package/src/mind/mechanisms/recall.ts +241 -0
  56. package/src/mind/mind.ts +483 -0
  57. package/src/mind/pipeline-mechanism.ts +326 -0
  58. package/src/mind/pipeline.ts +300 -0
  59. package/src/mind/primitives.ts +201 -0
  60. package/src/mind/rationale.ts +275 -0
  61. package/src/mind/reasoning.ts +198 -0
  62. package/src/mind/recognition.ts +234 -0
  63. package/src/mind/resonance.ts +0 -0
  64. package/src/mind/trace.ts +108 -0
  65. package/src/mind/traverse.ts +556 -0
  66. package/src/mind/types.ts +281 -0
  67. package/src/rabitq-hnsw/README.md +303 -0
  68. package/src/rabitq-hnsw/src/database.ts +492 -0
  69. package/src/rabitq-hnsw/src/heap.ts +90 -0
  70. package/src/rabitq-hnsw/src/hnsw.ts +514 -0
  71. package/src/rabitq-hnsw/src/index.ts +15 -0
  72. package/src/rabitq-hnsw/src/prng.ts +39 -0
  73. package/src/rabitq-hnsw/src/rabitq.ts +308 -0
  74. package/src/rabitq-hnsw/src/store.ts +994 -0
  75. package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
  76. package/src/store-sqlite.ts +928 -0
  77. package/src/store.ts +2148 -0
  78. package/src/vec.ts +124 -0
  79. package/test/00-extract.test.mjs +151 -0
  80. package/test/01-floor.test.mjs +20 -0
  81. package/test/02-roundtrip.test.mjs +83 -0
  82. package/test/03-recall.test.mjs +98 -0
  83. package/test/04-think.test.mjs +627 -0
  84. package/test/05-concepts.test.mjs +84 -0
  85. package/test/08-storage.test.mjs +948 -0
  86. package/test/09-edges.test.mjs +65 -0
  87. package/test/11-universality.test.mjs +180 -0
  88. package/test/13-conversation.test.mjs +228 -0
  89. package/test/14-scaling.test.mjs +503 -0
  90. package/test/15-decomposition-gap.test.mjs +0 -0
  91. package/test/16-bridge.test.mjs +250 -0
  92. package/test/17-intelligence.test.mjs +240 -0
  93. package/test/18-alu.test.mjs +209 -0
  94. package/test/19-nd.test.mjs +254 -0
  95. package/test/20-stability.test.mjs +489 -0
  96. package/test/21-partial.test.mjs +158 -0
  97. package/test/22-multihop.test.mjs +130 -0
  98. package/test/23-rationale.test.mjs +316 -0
  99. package/test/24-generalization.test.mjs +416 -0
  100. package/test/25-embedding.test.mjs +75 -0
  101. package/test/26-cooperative.test.mjs +89 -0
  102. package/test/27-saturation-drop.test.mjs +637 -0
  103. package/test/28-unknowable.test.mjs +88 -0
  104. package/test/29-counterfactual.test.mjs +476 -0
  105. package/test/30-conflict-resolution.test.mjs +166 -0
  106. package/test/31-audit.test.mjs +288 -0
  107. package/test/32-confluence.test.mjs +173 -0
  108. package/test/33-multi-candidate.test.mjs +222 -0
  109. package/test/34-cross-region.test.mjs +252 -0
  110. package/tsconfig.json +16 -0
@@ -0,0 +1,507 @@
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
+
28
+ import { cosine, Vec } from "../vec.js";
29
+ import type { Hit } from "../store.js";
30
+ import { conceptThreshold, identityBar, significanceBar } from "../geometry.js";
31
+ import { indexOf } from "../bytes.js";
32
+ import type { MindContext } from "./types.js";
33
+ import { leafIdRun } from "./canonical.js";
34
+ import { gistOf, read, resolve } from "./primitives.js";
35
+ import {
36
+ argmaxCosine,
37
+ chooseAmong,
38
+ chooseNext,
39
+ guidedFirst,
40
+ hubBound,
41
+ hubCap,
42
+ } from "./traverse.js";
43
+ import { recognise, segment } from "./recognition.js";
44
+ import type { Site } from "./graph-search.js";
45
+
46
+ // ═══════════════════════════════════════════════════════════════════════════
47
+ // MATCHERS — locating learned structure in/against bytes, by graded strictness
48
+ // ═══════════════════════════════════════════════════════════════════════════
49
+
50
+ /** The graded LOCATE ladder: find `needle` in `haystack` starting at
51
+ * `fromPos`, strictest matcher first, relaxing only when the stricter one
52
+ * fails. This is the read-out matcher skill extraction locates exemplar
53
+ * frames with.
54
+ *
55
+ * 1. exact — literal byte match (the fast path).
56
+ * 2. halo — the needle's distributional role matches a recognised query
57
+ * form (gate: conceptThreshold).
58
+ * 3. gist — the needle's perceived gist matches a query segment
59
+ * (gate: identityBar — scale-aware).
60
+ *
61
+ * Returns the absolute byte position, or −1. */
62
+ export function locate(
63
+ ctx: MindContext,
64
+ haystack: Uint8Array,
65
+ needle: Uint8Array,
66
+ fromPos: number,
67
+ sites?: ReadonlyArray<Site>,
68
+ ): number {
69
+ // 1. Exact match — fast, preserves backward compatibility.
70
+ const exact = indexOf(haystack.subarray(fromPos), needle, 0);
71
+ if (exact >= 0) return fromPos + exact;
72
+
73
+ // 2. Halo-based: the frame bytes' distributional role matches a query form.
74
+ if (sites && sites.length > 0) {
75
+ const frameId = resolve(ctx, needle);
76
+ if (frameId !== null) {
77
+ const frameHalo = ctx.store.halo(frameId);
78
+ if (frameHalo) {
79
+ const bestSite = bestHaloMate(
80
+ ctx,
81
+ frameHalo,
82
+ sites.filter((s) => s.start >= fromPos),
83
+ (s) => ctx.store.halo(s.payload),
84
+ );
85
+ if (bestSite !== null) return bestSite.item.start;
86
+ }
87
+ }
88
+ }
89
+
90
+ // 3. Gist resonance: the frame's perceived gist against query segments.
91
+ const frameGist = gistOf(ctx, needle);
92
+ const segments = segment(ctx, haystack.subarray(fromPos));
93
+ // The gist tier claims the WHOLE needle appears as a segment — an
94
+ // identity claim over `needle.length` bytes, so its bar is the
95
+ // scale-aware {@link identityBar} (one river window of tolerated foreign
96
+ // bytes), not the fixed estimator floor. For quantum-sized frames the
97
+ // two coincide; for long needles the fixed bar accepted segments that
98
+ // differed by whole windows.
99
+ const bestSeg = argmaxCosine(
100
+ frameGist,
101
+ segments,
102
+ (s) => s.v,
103
+ identityBar(ctx.store.D, ctx.space.maxGroup, needle.length),
104
+ true,
105
+ );
106
+ if (bestSeg !== null) return fromPos + bestSeg.item.start;
107
+
108
+ return -1;
109
+ }
110
+
111
+ /** The ALIGNED matcher: maximal literal matching runs between `query` and
112
+ * `ct` (a learned context's bytes), by seed-and-extend over
113
+ * `space.maxGroup`-sized n-gram seeds. Where locate() finds ONE position of
114
+ * a short frame, this finds EVERY run two whole structures share — the
115
+ * matcher CAST detects a woven query with. Returns non-overlapping runs
116
+ * sorted by query position. */
117
+ export function alignRuns(
118
+ ctx: MindContext,
119
+ query: Uint8Array,
120
+ ct: Uint8Array,
121
+ ): Array<{ qs: number; qe: number; cs: number }> {
122
+ const quantum = Math.min(ctx.space.maxGroup, ct.length);
123
+ if (quantum < 1 || query.length < quantum) return [];
124
+ const gram = (b: Uint8Array, at: number): string => {
125
+ let s = "";
126
+ for (let i = 0; i < quantum; i++) s += String.fromCharCode(b[at + i]);
127
+ return s;
128
+ };
129
+ const seeds = new Map<string, number[]>();
130
+ for (let i = 0; i + quantum <= query.length; i++) {
131
+ const k2 = gram(query, i);
132
+ const bucket = seeds.get(k2);
133
+ if (bucket === undefined) seeds.set(k2, [i]);
134
+ else bucket.push(i);
135
+ }
136
+ const found: Array<{ qs: number; qe: number; cs: number; len: number }> = [];
137
+ for (let j = 0; j + quantum <= ct.length; j++) {
138
+ const bucket = seeds.get(gram(ct, j));
139
+ if (bucket === undefined) continue;
140
+ for (const i of bucket) {
141
+ if (i > 0 && j > 0 && query[i - 1] === ct[j - 1]) continue;
142
+ let len = quantum;
143
+ while (
144
+ i + len < query.length && j + len < ct.length &&
145
+ query[i + len] === ct[j + len]
146
+ ) len++;
147
+ found.push({ qs: i, qe: i + len, cs: j, len });
148
+ }
149
+ }
150
+ found.sort((a, b) => b.len - a.len);
151
+ const runs: Array<{ qs: number; qe: number; cs: number }> = [];
152
+ for (const r of found) {
153
+ const clash = runs.some((o) =>
154
+ (r.qs < o.qe && o.qs < r.qe) ||
155
+ (r.cs < o.cs + (o.qe - o.qs) && o.cs < r.cs + r.len)
156
+ );
157
+ if (!clash) runs.push({ qs: r.qs, qe: r.qe, cs: r.cs });
158
+ }
159
+ return runs.sort((a, b) => a.qs - b.qs);
160
+ }
161
+
162
+ /** A run from {@link alignGraded} — the ALIGNED matcher extended with the
163
+ * same graded-evidence ladder as {@link locate}. Literal runs carry
164
+ * `weight = 1` (exact match is full evidence); halo-matched site runs carry
165
+ * `weight = cosine` (measured evidence — the halo similarity itself).
166
+ * `cs` is the structural byte position in the context regardless of run
167
+ * kind, so the substitution/redirection schemas work unchanged on conceptual
168
+ * alignment. */
169
+ export interface GradedRun {
170
+ qs: number;
171
+ qe: number;
172
+ cs: number;
173
+ weight: number;
174
+ }
175
+
176
+ /** The GRADED alignment matcher: extends literal W-gram alignment
177
+ * ({@link alignRuns}) with halo-matched recognised sites in query regions
178
+ * that have no literal coverage. Same ladder as {@link locate}: literal
179
+ * first, then distributional role (halo-matched sites, gate:
180
+ * conceptThreshold, enforced by {@link bestHaloMate}). Returns weighted
181
+ * runs sorted by query position.
182
+ *
183
+ * `querySites` are the pre-computed recognition sites for the query
184
+ * (optional — when absent, only literal alignment fires and graded degrades
185
+ * to the original behaviour). Context sites are recognised internally. */
186
+ export function alignGraded(
187
+ ctx: MindContext,
188
+ query: Uint8Array,
189
+ contextBytes: Uint8Array,
190
+ querySites?: ReadonlyArray<Site>,
191
+ ): GradedRun[] {
192
+ const lit = alignRuns(ctx, query, contextBytes);
193
+ const out: GradedRun[] = lit.map((r) => ({ ...r, weight: 1 }));
194
+
195
+ if (!querySites || querySites.length === 0) return out;
196
+
197
+ // Mark query positions ALREADY covered by literal runs — halo fills gaps.
198
+ // If literal coverage is already complete, skip the halo step entirely
199
+ // (recognise is O(|ctx|·W) — wasted when every byte is accounted for).
200
+ const covered = new Uint8Array(query.length);
201
+ let gaps = false;
202
+ for (const r of lit) {
203
+ for (let i = r.qs; i < r.qe; i++) covered[i] = 1;
204
+ }
205
+ for (let i = 0; i < query.length; i++) {
206
+ if (!covered[i]) {
207
+ gaps = true;
208
+ break;
209
+ }
210
+ }
211
+ if (!gaps) return out;
212
+
213
+ // Recognise sites in the exemplar context — structural positions for halo
214
+ // matching. (Circular import with recognition.ts is safe: recognise() is
215
+ // called lazily, never at module load — the same pattern `segment` uses.)
216
+ const ctxSites = recognise(ctx, contextBytes).sites;
217
+ if (ctxSites.length === 0) return out;
218
+
219
+ // Context sites with halos, hoisted: the same set serves every query site.
220
+ const ctxCands = ctxSites.filter((cs) => ctx.store.hasHalo(cs.payload));
221
+ if (ctxCands.length === 0) return out;
222
+
223
+ // Candidate halos, also hoisted (lazily, first query site that needs them):
224
+ // bestHaloMate consults every candidate's halo PER QUERY SITE, and sites
225
+ // share the candidate set — without this memo the same few dozen halos were
226
+ // re-fetched thousands of times per response. Distinct payloads can repeat
227
+ // across sites, hence the map by payload id.
228
+ const ctxHalos = new Map<number, Vec | null>();
229
+ const ctxHaloOf = (cs: Site): Vec | null => {
230
+ let h = ctxHalos.get(cs.payload);
231
+ if (h === undefined) {
232
+ h = ctx.store.halo(cs.payload);
233
+ ctxHalos.set(cs.payload, h);
234
+ }
235
+ return h;
236
+ };
237
+
238
+ for (const qs of querySites) {
239
+ // Only sites that overlap UNCOVERED query regions add new evidence.
240
+ let touchesGap = false;
241
+ for (let i = qs.start; i < qs.end; i++) {
242
+ if (!covered[i]) {
243
+ touchesGap = true;
244
+ break;
245
+ }
246
+ }
247
+ if (!touchesGap) continue;
248
+
249
+ const qHalo = ctx.store.halo(qs.payload);
250
+ if (!qHalo) continue;
251
+
252
+ // bestHaloMate already gates at conceptThreshold — no second check needed.
253
+ const match = bestHaloMate(ctx, qHalo, ctxCands, ctxHaloOf);
254
+ if (match === null) continue;
255
+
256
+ out.push({
257
+ qs: qs.start,
258
+ qe: qs.end,
259
+ cs: match.item.start,
260
+ weight: match.score,
261
+ });
262
+ }
263
+
264
+ out.sort((a, b) => a.qs - b.qs);
265
+ return out;
266
+ }
267
+
268
+ /** The IN-LIST halo matcher: the best halo-mate for `halo` among EXPLICIT
269
+ * candidates, above the concept threshold — the list counterpart of
270
+ * {@link haloSiblings}, which asks the halo INDEX for candidates instead.
271
+ * Behind locate()'s halo step and articulation's voice matching; a third
272
+ * "best halo among these" decision must come here, not inline. */
273
+ export function bestHaloMate<T>(
274
+ ctx: MindContext,
275
+ halo: Vec,
276
+ items: Iterable<T>,
277
+ haloOf: (item: T) => Vec | null | undefined,
278
+ ): { item: T; score: number } | null {
279
+ return argmaxCosine(halo, items, haloOf, conceptThreshold(ctx.store.D));
280
+ }
281
+
282
+ /** The HALO-SIBLING matcher: the nodes that keep the same distributional
283
+ * company as `id`, nearest first — `resonateHalo` filtered to exclude the
284
+ * node itself and everything below `bar` (default: the concept threshold).
285
+ * `halo`, when the caller has already read the node's halo row, is reused
286
+ * instead of refetched (one read per relation). Returns [] for a node with
287
+ * no halo. The one sibling enumeration behind the concept hop, the
288
+ * reasoning stage's synonym expansion, and the analogy matcher below. */
289
+ const haloSiblingMemo = new WeakMap<object, Map<number, Hit[]>>();
290
+ export async function haloSiblings(
291
+ ctx: MindContext,
292
+ id: number,
293
+ halo?: Vec | null,
294
+ bar: number = conceptThreshold(ctx.store.D),
295
+ ): Promise<Hit[]> {
296
+ // Per-response memo for the DEFAULT-ARGUMENT reading (the one the concept
297
+ // hop, the bridge's synonym tier, and reasoning's synonym expansion all
298
+ // use): the same node's siblings are asked for repeatedly within one
299
+ // response (bridge pairs share sides), each a full halo-ANN query, and the
300
+ // store is read-only while a response is in flight. Keyed by the response
301
+ // lifecycle object (ctx.climbMemo — fresh per respond, nulled after).
302
+ // Calls with an explicit halo or bar (analogyStrength's gated reading)
303
+ // bypass the memo — their filter differs.
304
+ const memoable = halo === undefined &&
305
+ bar === conceptThreshold(ctx.store.D) && ctx.climbMemo !== null;
306
+ let memo: Map<number, Hit[]> | undefined;
307
+ if (memoable) {
308
+ memo = haloSiblingMemo.get(ctx.climbMemo!);
309
+ if (memo === undefined) {
310
+ haloSiblingMemo.set(ctx.climbMemo!, memo = new Map());
311
+ }
312
+ const hit = memo.get(id);
313
+ if (hit !== undefined) return hit;
314
+ }
315
+ const h = halo ?? ctx.store.halo(id);
316
+ const out = h
317
+ ? (await ctx.store.resonateHalo(h, ctx.cfg.haloQueryK))
318
+ .filter((sib) => sib.id !== id && sib.score >= bar)
319
+ : [];
320
+ if (memo !== undefined) memo.set(id, out);
321
+ return out;
322
+ }
323
+
324
+ /** The DISTRIBUTIONAL matcher between two nodes: mutual-nearest-neighbour
325
+ * strength, not a pick. Returns the direct halo cosine, or failing that the
326
+ * highest mutual-halo-sibling min-score (second-order analogy), or failing
327
+ * that the SHARED-FRAME strength (below) — the gate CAST's comparison
328
+ * schema validates genuine analogs with (bar: significanceBar). */
329
+ export async function analogyStrength(
330
+ ctx: MindContext,
331
+ a: number,
332
+ b: number,
333
+ ): Promise<number> {
334
+ const ha = ctx.store.halo(a);
335
+ const hb = ctx.store.halo(b);
336
+ if (ha && hb) {
337
+ const bar = significanceBar(ctx.store.D);
338
+ const direct = cosine(ha, hb);
339
+ if (direct >= bar) return direct;
340
+ const sibsA = await haloSiblings(ctx, a, ha, bar);
341
+ const sibsB = await haloSiblings(ctx, b, hb, bar);
342
+ let best = 0;
343
+ for (const x of sibsA) {
344
+ if (x.id === b) continue;
345
+ const y = sibsB.find((s) => s.id === x.id);
346
+ if (y !== undefined) {
347
+ best = Math.max(best, Math.min(x.score, y.score));
348
+ }
349
+ }
350
+ if (best > 0) return best;
351
+ }
352
+ return sharedFrameStrength(ctx, a, b);
353
+ }
354
+
355
+ /** The STRUCTURAL analogy tier: two nodes are analogs when their byte
356
+ * streams share a LEARNT frame — a content-addressed flat form of at least
357
+ * one full river window (W bytes, the perception quantum) that occurs in
358
+ * BOTH. This is what "playing the same role" means structurally: "Ice is
359
+ * cold" and "Steel is hard" share the learnt " is " frame even though they
360
+ * keep disjoint distributional company. Halos measure company by IDENTITY
361
+ * (company signatures — see sema.ts), so unrelated-company analogs must be
362
+ * validated by the frame itself, not by content leaking through halo
363
+ * vectors. Strength is the shared learnt coverage of the SHORTER side —
364
+ * a fraction, comparable to the cosine tiers above. Derived: the window
365
+ * is maxGroup, the same quantum differsByOneWindow and canonicalChunkId
366
+ * measure by; no tuned constants. */
367
+ export function sharedFrameStrength(
368
+ ctx: MindContext,
369
+ a: number,
370
+ b: number,
371
+ ): number {
372
+ const W = ctx.space.maxGroup;
373
+ const A = read(ctx, a);
374
+ const B = read(ctx, b);
375
+ if (A.length < W || B.length < W) return 0;
376
+ // Mark every byte of the shorter side covered by a learnt W-window that
377
+ // also occurs in the longer side.
378
+ const [s, l] = A.length <= B.length ? [A, B] : [B, A];
379
+ const covered = new Uint8Array(s.length);
380
+ for (let off = 0; off + W <= s.length; off++) {
381
+ const win = s.subarray(off, off + W);
382
+ // Learnt: the window resolves as a content-addressed flat form.
383
+ const ids = leafIdRun(ctx, s, off, off + W);
384
+ if (ids === null || ctx.store.findBranch(ids) === null) continue;
385
+ if (indexOf(l, win, 0) < 0) continue;
386
+ covered.fill(1, off, off + W);
387
+ }
388
+ let n = 0;
389
+ for (let i = 0; i < s.length; i++) n += covered[i];
390
+ return n >= W ? n / s.length : 0;
391
+ }
392
+
393
+ // ═══════════════════════════════════════════════════════════════════════════
394
+ // PROJECTIONS — what a matched node is projected ALONG (the direction)
395
+ // ═══════════════════════════════════════════════════════════════════════════
396
+
397
+ /** FORWARD through a synonym: the continuation an edge-less node borrows from
398
+ * a concept (halo) sibling — resonate the node's halo, take the first
399
+ * sibling above the concept threshold that itself has a direct edge. */
400
+ export async function conceptHop(
401
+ ctx: MindContext,
402
+ id: number,
403
+ ): Promise<number | null> {
404
+ for (const sib of await haloSiblings(ctx, id)) {
405
+ const hop = guidedFirst(ctx, sib.id);
406
+ if (hop !== undefined) return hop;
407
+ }
408
+ return null;
409
+ }
410
+
411
+ /** FORWARD projection: follow continuation edges from a node to its fixpoint.
412
+ * The first hop may cross a concept (halo) link — a synonym. The rest
413
+ * follow direct edges. Convergence is intrinsic: the seen set guards
414
+ * against cycles. `guide` disambiguates multi-continuation nodes by
415
+ * resonance. */
416
+ export async function follow(
417
+ ctx: MindContext,
418
+ id: number,
419
+ guide?: Vec | null,
420
+ ): Promise<Uint8Array | null> {
421
+ const seen = new Set<number>([id]);
422
+
423
+ // First hop: a direct edge, else a concept sibling's edge (the synonym).
424
+ let next = chooseNext(ctx, id, guide);
425
+ if (next === undefined) {
426
+ const hop = await conceptHop(ctx, id);
427
+ if (hop === null) return null;
428
+ next = hop;
429
+ }
430
+
431
+ // Direct successors to the fixpoint. Only the FIXPOINT's bytes are
432
+ // returned, so the walk tracks node ids and reads bytes exactly once at
433
+ // the end — a K-hop chain used to pay K full reconstructions and discard
434
+ // K−1 of them.
435
+ while (!seen.has(next)) {
436
+ seen.add(next);
437
+ const fwd = chooseNext(ctx, next, guide);
438
+ if (fwd === undefined || seen.has(fwd)) break;
439
+ next = fwd;
440
+ }
441
+ return read(ctx, next);
442
+ }
443
+
444
+ /** REVERSE projection: the context a learnt continuation follows, voiced as
445
+ * bytes. A common continuation ("Yes.") follows MANY contexts; with a
446
+ * `guide` the context whose gist resonates with the query wins (seat
447
+ * symmetry) — without one, the most-corroborated context wins (poured halo
448
+ * MASS, the direct measure of how many episodes established it), falling
449
+ * back to first-learnt on equal mass. Callers that HAVE a query gist must
450
+ * pass it, or they silently change disambiguation regime.
451
+ *
452
+ * `rev`, when the caller has already materialised prevOf (one read per
453
+ * relation — a hub's reverse fan-in is corpus-sized), is reused instead of
454
+ * refetched. Returns null when there is no predecessor or the picked
455
+ * context reads empty (a zero-length context is no grounding: an empty
456
+ * Uint8Array is truthy, and returning it would flow a hollow "answer"
457
+ * onward). */
458
+ export function reverseContext(
459
+ ctx: MindContext,
460
+ id: number,
461
+ guide?: Vec | null,
462
+ rev?: readonly number[],
463
+ ): Uint8Array | null {
464
+ // CAPPED default read: only the first √N predecessors are ever candidates
465
+ // (hubCap below / in chooseAmong), so only they are read. hubBound ≥ 2
466
+ // keeps the single-predecessor shortcut exact.
467
+ const candidates = rev ?? ctx.store.prevFirst(id, hubBound(ctx));
468
+ if (candidates.length === 0) return null;
469
+ const pick = candidates.length === 1
470
+ ? candidates[0]
471
+ : guide
472
+ ? chooseAmong(ctx, candidates, guide).id
473
+ : pickByMass(ctx, candidates);
474
+ const g = read(ctx, pick);
475
+ return g.length > 0 ? g : null;
476
+ }
477
+
478
+ /** The most-corroborated candidate by poured halo mass (first-seen wins a
479
+ * tie). Capped at √N candidates by insertion order — the same hub bound
480
+ * every fan-out walk uses. */
481
+ function pickByMass(ctx: MindContext, ids: readonly number[]): number {
482
+ const capped = hubCap(ctx, ids);
483
+ let best = capped[0];
484
+ let bestMass = ctx.store.haloMass(best);
485
+ for (let i = 1; i < capped.length; i++) {
486
+ const mass = ctx.store.haloMass(capped[i]);
487
+ if (mass > bestMass) {
488
+ best = capped[i];
489
+ bestMass = mass;
490
+ }
491
+ }
492
+ return best;
493
+ }
494
+
495
+ /** THE projection: ground a matched node to answer bytes — FORWARD to its
496
+ * continuation fixpoint (which may cross a concept hop), else REVERSE to
497
+ * the context it follows. This is the direction ladder every mechanism's
498
+ * final grounding step reduces to. */
499
+ export async function project(
500
+ ctx: MindContext,
501
+ id: number,
502
+ guide?: Vec | null,
503
+ ): Promise<Uint8Array | null> {
504
+ const fc = await follow(ctx, id, guide);
505
+ if (fc) return fc;
506
+ return reverseContext(ctx, id, guide);
507
+ }
@@ -0,0 +1,33 @@
1
+ // mechanisms/alu.ts — the ALU wrapped as an ordinary PipelineMechanism.
2
+ //
3
+ // The ALU is a self-contained sublibrary (src/alu) that knows nothing about
4
+ // the pipeline; this adapter is the whole coupling. Its `parse` populates
5
+ // `pre.computed` before the grounding loop; the cover mechanism handles
6
+ // masking (see mechanisms/cover.ts). The ALU's own trace steps
7
+ // (`evalComputation`) are emitted inside its `parse()`. A user extension
8
+ // joins the same way — see MindOptions.mechanismFactories.
9
+
10
+ import type { Alu } from "../../alu/src/alu.js";
11
+ import { STEP } from "../graph-search.js";
12
+ import { unexplainedLabel } from "../rationale.js";
13
+ import type { PipelineMechanism } from "../pipeline-mechanism.js";
14
+
15
+ /** Wrap the ALU as a {@link PipelineMechanism}. */
16
+ export function aluToMechanism(alu: Alu): PipelineMechanism {
17
+ return {
18
+ name: "alu",
19
+ provenance: "cover",
20
+ parse: (query) => alu.parse(query),
21
+ async floor(_ctx, _query, pre, _worthRunning) {
22
+ return pre.computed.length > 0 ? 0 : null;
23
+ },
24
+ async run(_ctx, query, pre) {
25
+ return pre.computed.map((u) => ({
26
+ bytes: u.bytes,
27
+ accounted: [[u.i, u.j]],
28
+ moves: STEP,
29
+ unexplained: unexplainedLabel(query, [[u.i, u.j]]),
30
+ }));
31
+ },
32
+ };
33
+ }