@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,511 @@
1
+ // geometry.ts — every modality is a stream; geometry is only a reading order.
2
+ //
3
+ // 1. Each byte is a leaf — an atom carrying its own vector straight from
4
+ // the alphabet.
5
+ // 2. The river folds leaves upward in fixed-size groups (maxGroup). Items
6
+ // that cross the stable-prefix boundary are split so the prefix folds
7
+ // identically regardless of what follows — pure structural stability.
8
+ // 3. The same rule recurses level after level until one root remains.
9
+
10
+ import { normalize, Vec } from "./vec.js";
11
+ import { Sema, sema, Space } from "./sema.js";
12
+ import { Alphabet } from "./alphabet.js";
13
+
14
+ // ---- geometric constants ----
15
+ //
16
+ // Every threshold below is a derived function of the fold's own geometry —
17
+ // dimension D, maxGroup, etc. — never a tuned magic number. They live here
18
+ // (not in a config file) because they follow from the structure itself.
19
+ //
20
+ // MEASUREMENT CAVEAT: these thresholds are compared against RaBitQ-ESTIMATED
21
+ // cosines (1-bit stored codes scored against a 4-bit-quantized query; the
22
+ // index never reranks with exact vectors). The derivations assume an exact
23
+ // cosine; the estimator adds a small, rotation-uniformised error the bars do
24
+ // not model. This is benign for the inequality thresholds (they gate broad
25
+ // regions), but it means NO decision may treat an estimated score as exact —
26
+ // identity in particular is decided by content-addressed resolve(), never by
27
+ // `score >= 1` (see recallByResonance tier 0).
28
+
29
+ /** The store's geometric identity bar: cosine ≥ 1 − 1/√D is the similarity at
30
+ * which `intern` already treats two gists as the SAME node. Recall reuses it
31
+ * to accept a near-identical query, and the climb to accept a containing form —
32
+ * one derived constant, never a tuned threshold. NOTE: this fixed bar is
33
+ * the ESTIMATOR floor of an identity claim; a whole-span claim over a span
34
+ * longer than the perception quantum must use the scale-aware
35
+ * {@link identityBar}, which converts the tolerated fraction into bytes. */
36
+ export function mergeThreshold(D: number): number {
37
+ return 1 - 1 / Math.sqrt(D);
38
+ }
39
+
40
+ /** The scale-aware IDENTITY bar for a whole-span resonance claim over a span
41
+ * of `len` bytes. Under the linear fold a cosine reads "fraction of aligned
42
+ * shared bytes", so a FIXED cosine bar admits a byte budget that grows with
43
+ * the span: 1 − 1/√D over a 4·√D-byte span tolerates four whole river
44
+ * windows of foreign content while still claiming "near-identical". An
45
+ * identity claim may tolerate at most ONE river window W — the perception
46
+ * quantum, the same single-window budget near-dedup's differsByOneWindow
47
+ * grants — so the bar is 1 − W/len, floored at mergeThreshold(D), below
48
+ * which the RaBitQ estimator cannot certify identity anyway. This is the
49
+ * angle+magnitude form of the identity test: the ANGLE carries the shared
50
+ * fraction, the span's MAGNITUDE (√len, the linear fold's own norm) converts
51
+ * the tolerated fraction into tolerated bytes. Derived from W, D and the
52
+ * span; never tuned. */
53
+ export function identityBar(D: number, maxGroup: number, len: number): number {
54
+ return Math.max(mergeThreshold(D), 1 - maxGroup / Math.max(1, len));
55
+ }
56
+
57
+ /** The reach bar: half a river quantum, derived from the fold's own geometry.
58
+ * A branch folds up to `maxGroup` children, so two forms that differ in ONE
59
+ * whole child — the smallest distinction perception can mean — sit at cosine
60
+ * ≈ 1 − 1/maxGroup. Half that quantum, 1 − 1/(2·maxGroup), is closer than any
61
+ * single-child difference can be: a positional echo of the same content.
62
+ *
63
+ * Recall uses this as its confidence floor: a query whose nearest resonant
64
+ * form sits below this bar is structurally unrelated to everything in the store
65
+ * — further than any single-child variant — and the system returns null rather
66
+ * than fabricate an answer from an unrelated form. Derived, never tuned. */
67
+ export function reachThreshold(maxGroup: number): number {
68
+ return 1 - 1 / (2 * maxGroup);
69
+ }
70
+
71
+ /** The estimator's own noise floor: 1/√D — ONE standard deviation of the
72
+ * cosine between two independent random vectors in D dimensions (the same σ
73
+ * {@link significanceBar} takes three of). It is the smallest difference in
74
+ * cosine that is distinguishable from the rotation-uniformised RaBitQ
75
+ * estimation error (see the MEASUREMENT CAVEAT above): a contrastive margin
76
+ * below it is quantisation noise, not evidence. The consensus climb gates a
77
+ * region's vote on its discriminative margin clearing this floor — the
78
+ * minimal "above noise" bar, one σ, not the stricter 3σ relatedness bar.
79
+ * Derived, never tuned. */
80
+ export function estimatorNoise(D: number): number {
81
+ return 1 / Math.sqrt(D);
82
+ }
83
+
84
+ /** The statistical-significance bar for whole-query resonance: 3/√D.
85
+ * In D dimensions the expected cosine of two independent random vectors is 0
86
+ * with standard deviation 1/√D. A cosine ≥ 3/√D is three standard deviations
87
+ * above chance — the query is statistically related to the store, not merely
88
+ * sharing random byte noise. Below this bar the consensus climb (which trusts
89
+ * sub-region resonance) is skipped: there is no evidence the query belongs to
90
+ * the same distribution as the stored content. Derived, never tuned. */
91
+ export function significanceBar(D: number): number {
92
+ return 3 / Math.sqrt(D);
93
+ }
94
+
95
+ /** The concept (halo) threshold: the cosine above which two nodes share a
96
+ * distributional concept. A halo is a superposition of episode signatures in
97
+ * D-dimensional space, so the expected cosine between two unrelated halos is 0
98
+ * with standard deviation 1/√D. The structural midpoint 0.5 separates "more
99
+ * similar than not" from noise; the +0.5/√D term adds one half-sigma margin
100
+ * that vanishes as D → ∞, accounting for the wider noise band at lower D
101
+ * without inventing a tuned constant. At D=1024 this gives 0.516, within
102
+ * 3% of 0.5 — existing behavior is preserved while threshold and D move
103
+ * together. Derived, never tuned. */
104
+ export function conceptThreshold(D: number): number {
105
+ return 0.5 + 0.5 / Math.sqrt(D);
106
+ }
107
+
108
+ /** The HALF-DOMINANCE predicate: whether a part covering `partLen` of a
109
+ * whole of `wholeLen` covers STRICTLY more than half of it. A span that
110
+ * dominates its whole can no longer discriminate the whole's own content —
111
+ * the one test behind liftAnswer's keep-the-frame rule, collectRegions'
112
+ * wrapper exclusion, and CAST's frame-depth majority (each cites this).
113
+ * CAST's frame-FRACTION gate is the deliberately CLOSED variant (≥ ½ is
114
+ * already unusable there) and stays inline where it is documented.
115
+ * Derived from the structural midpoint, never tuned. */
116
+ export function dominates(partLen: number, wholeLen: number): boolean {
117
+ return partLen * 2 > wholeLen;
118
+ }
119
+
120
+ /** The consensus-vote significance floor: ln(N) + 1/2, where N is the number
121
+ * of learnt contexts (edge sources). A single region's IDF-weighted vote for
122
+ * an anchor reached through c contexts is at most ln(N/c) ≤ ln(N); the +1/2
123
+ * demands the pooled vote exceed what ONE maximally-specific region could
124
+ * contribute by half a unit — i.e. genuine corroboration beyond a lone
125
+ * region's echo at this corpus scale. The ONE floor both consumers gate on:
126
+ * recallByResonance trusting a climb anchor, and commitVotes admitting a
127
+ * further point of attention. Defined once here so the two can never
128
+ * drift apart. Derived from N, never tuned. */
129
+ export function consensusFloor(N: number): number {
130
+ return Math.log(N) + 1 / 2;
131
+ }
132
+
133
+ /** The coverage bar for the reach (interior) index, when vector-similarity
134
+ * gating is used. Returns the concept threshold — the structural midpoint
135
+ * (~0.5 at D=1024) where two forms are "more similar than not."
136
+ *
137
+ * Currently UNUSED in the hot training path: interior nodes are indexed
138
+ * unconditionally (hash-cons dedup bounds the index naturally).
139
+ * Post-hoc structural compaction ({@link Store.compactContentIndex})
140
+ * replaces runtime coverage gating with a batch pass that removes
141
+ * structurally-isolated entries. Derived, never tuned. */
142
+ export function coverageBar(_maxGroup: number, D: number): number {
143
+ return conceptThreshold(D);
144
+ }
145
+
146
+ // ---- types ----
147
+
148
+ interface Folded {
149
+ tree: Sema;
150
+ /** Byte length of the subtree — carried incrementally so the stable-prefix
151
+ * boundary scan never re-walks subtrees (the old per-level walk was
152
+ * O(n log n) over the whole input). */
153
+ len: number;
154
+ }
155
+
156
+ export interface Grid {
157
+ width: number;
158
+ height: number;
159
+ channels: number;
160
+ data: Uint8Array;
161
+ dims?: number[];
162
+ }
163
+
164
+ // ---- folding ----
165
+ //
166
+ // The river fold is a hierarchical prefix network: each level contracts
167
+ // groups of `maxGroup` adjacent items into one via permute-then-add
168
+ // (positional seat binding), recursing until one root remains.
169
+ //
170
+ // FLAT per-level fold — one inline loop per level (foldSlice): no per-group
171
+ // function calls, no Array.slice per group, the permute and add FUSED
172
+ // (`gist[d] += v[seat[d]]`, no scratch buffer), and subtree byte lengths
173
+ // carried incrementally on Folded (the old boundary scan re-walked subtrees
174
+ // every level — O(n log n)). The per-level SUPERPOSITION is byte-identical
175
+ // to the original recursive foldGroup: the same FP additions in the same
176
+ // order.
177
+ //
178
+ // LINEAR fold — intermediate gists are NOT normalized; only the final root is
179
+ // (riverFold's single normalize). This is a deliberate change of similarity
180
+ // semantics from the original per-group normalize, not a cached optimization:
181
+ // the fold is now a pure linear operator — a superposition of positionally-
182
+ // bound leaf vectors — so an interior node carries its span's natural
183
+ // magnitude and a resonance score reads as byte-proportional overlap rather
184
+ // than a scale-free cosine. The mechanisms that depend on that reading
185
+ // compensate for it EXPLICITLY, never silently: the contrastive margin on
186
+ // approximate votes (voteRegions), company signatures decoupling halo company
187
+ // from gist content (sema.ts), and the shared-frame analogy tier (match.ts).
188
+
189
+ /** Fold `items[start .. start+count)` in groups of `mg` into `out`.
190
+ *
191
+ * With `force`, the trailing incomplete group (2..mg-1 items) is folded as
192
+ * well — only a lone singleton passes through — guaranteeing progress when
193
+ * the caller detected a stall. */
194
+ function foldSlice(
195
+ space: Space,
196
+ items: Folded[],
197
+ start: number,
198
+ count: number,
199
+ out: Folded[],
200
+ force: boolean,
201
+ ): void {
202
+ const mg = space.maxGroup;
203
+ const D = space.D;
204
+ const complete = count - (count % mg);
205
+
206
+ const foldAt = (at: number, size: number): void => {
207
+ const gist = new Float32Array(D);
208
+ const kids = new Array<Sema>(size);
209
+ let len = 0;
210
+ for (let k = 0; k < size; k++) {
211
+ const f = items[at + k];
212
+ const seat = space.seats[k].fwd;
213
+ const v = f.tree.v;
214
+ // Fused permute-and-accumulate — same FP ops, same order as the old
215
+ // permuteInto + addInto pair, with no scratch buffer.
216
+ for (let d = 0; d < D; d++) gist[d] += v[seat[d]];
217
+ kids[k] = f.tree;
218
+ len += f.len;
219
+ }
220
+ out.push({ tree: sema(gist, null, kids), len });
221
+ };
222
+
223
+ for (let i = 0; i < complete; i += mg) foldAt(start + i, mg);
224
+
225
+ const leftover = count - complete;
226
+ if (leftover === 0) return;
227
+ if (force && leftover >= 2) foldAt(start + complete, leftover);
228
+ else for (let i = complete; i < count; i++) out.push(items[start + i]);
229
+ }
230
+
231
+ function riverFold(space: Space, row: Folded[], stableBytes: number): Folded {
232
+ if (row.length === 0) {
233
+ const z = new Float32Array(space.D);
234
+ return { tree: sema(z, new Uint8Array(0), null), len: 0 };
235
+ }
236
+ let level = row;
237
+ while (level.length > 1) {
238
+ // Find the item index where accumulated bytes reaches stableBytes.
239
+ let boundary = level.length;
240
+ if (stableBytes > 0) {
241
+ let acc = 0;
242
+ for (let i = 0; i < level.length; i++) {
243
+ acc += level[i].len;
244
+ if (acc >= stableBytes) {
245
+ boundary = i + 1;
246
+ break;
247
+ }
248
+ }
249
+ }
250
+
251
+ const next: Folded[] = [];
252
+ if (boundary < level.length) {
253
+ // Prefix folds independently of the suffix — structural stability.
254
+ foldSlice(space, level, 0, boundary, next, false);
255
+ foldSlice(space, level, boundary, level.length - boundary, next, false);
256
+ } else {
257
+ foldSlice(space, level, 0, level.length, next, false);
258
+ }
259
+ if (next.length === level.length) {
260
+ // Stuck — every group was incomplete. Force-fold to break the stall.
261
+ const forced: Folded[] = [];
262
+ foldSlice(space, next, 0, next.length, forced, true);
263
+ level = forced;
264
+ } else {
265
+ level = next;
266
+ }
267
+ }
268
+ // LINEAR fold — this root normalize is the ONLY normalize of the entire
269
+ // fold; every intermediate gist stays unnormalized (see the folding
270
+ // header). Skipped for a single-leaf input: that root IS the shared
271
+ // alphabet vector (already unit), and normalizing in place would mutate the
272
+ // alphabet itself.
273
+ if (row.length > 1) normalize(level[0].tree.v);
274
+ return level[0];
275
+ }
276
+
277
+ // ---- public API ----
278
+
279
+ function bytesToLeaves(
280
+ alphabet: Alphabet,
281
+ bytes: Uint8Array,
282
+ ): Folded[] {
283
+ return Array.from(bytes, (b, i) => {
284
+ const v = alphabet.vecs[b];
285
+ return { tree: sema(v, bytes.slice(i, i + 1), null), len: 1 };
286
+ });
287
+ }
288
+
289
+ /** Find the longest prefix of `bytes` whose leaf-id signature matches a
290
+ * known branch via `lookup`. Returns the byte-length of that prefix, or 0. */
291
+ export function knownPrefixLength(
292
+ bytes: Uint8Array,
293
+ leafAt: (i: number) => number | null,
294
+ lookup: (leafIds: number[]) => number | null,
295
+ ): number {
296
+ const leafIds: number[] = [];
297
+ for (let i = 0; i < bytes.length; i++) {
298
+ const lid = leafAt(i);
299
+ if (lid === null) break;
300
+ leafIds.push(lid);
301
+ }
302
+ // Match the longest PROPER prefix — a full-length match means the entire
303
+ // input already exists as a stored form (e.g. the flat leaf-id branch
304
+ // stored alongside the structural root). That would hide the true split
305
+ // point and prevent the river from producing the same tree it folded
306
+ // during training, so the structural recognition cannot find the right
307
+ // forms. A proper prefix guarantees at least two regions.
308
+ for (let len = bytes.length - 1; len >= 2; len--) {
309
+ if (lookup(leafIds.slice(0, len)) !== null) return len;
310
+ }
311
+ return 0;
312
+ }
313
+
314
+ /** Bytes → Sema tree. `leafAt` and `lookup` are store capabilities for
315
+ * detecting previously-stored prefixes so the river can split at the
316
+ * correct boundary. Pass them through from `perceive`; the geometry
317
+ * computes the stable prefix internally. */
318
+ export function bytesToTree(
319
+ space: Space,
320
+ alphabet: Alphabet,
321
+ bytes: Uint8Array,
322
+ leafAt?: (i: number) => number | null,
323
+ lookup?: (leafIds: number[]) => number | null,
324
+ ): Sema {
325
+ if (bytes.length === 0) {
326
+ return sema(alphabet.vecs[0], new Uint8Array(0), null);
327
+ }
328
+ const sb = (leafAt && lookup) ? knownPrefixLength(bytes, leafAt, lookup) : 0;
329
+ return riverFold(
330
+ space,
331
+ bytesToLeaves(alphabet, bytes),
332
+ sb > 0 ? sb : bytes.length,
333
+ ).tree;
334
+ }
335
+
336
+ // ---- pyramid fold (incremental plain perception) ----
337
+
338
+ /** The PLAIN fold's full level pyramid — every level's item list, bottom
339
+ * (leaves) to top (root). Left-grouped folding is RADIX-ALIGNED: the item
340
+ * at level L, index i, covers exactly bytes [i·mg^L, (i+1)·mg^L) whenever
341
+ * it is a FULL block, and a full block folds bit-identically in ANY byte
342
+ * string that contains it at that offset. So a string extended by a
343
+ * suffix (a conversation's accumulated context) reuses every full block of
344
+ * its prefix's pyramid and refolds only the right edge of each level —
345
+ * O(suffix + depth·mg) per extension instead of O(whole), with the
346
+ * produced tree BIT-IDENTICAL to a from-scratch plain fold (same nodes,
347
+ * same FP ops; reused subtrees are shared objects, and Sema nodes are
348
+ * never mutated). Purely an implementation cache: structure and numerics
349
+ * never depend on whether a pyramid was available. */
350
+ export interface FoldPyramid {
351
+ levels: Array<Array<{ tree: Sema; len: number }>>;
352
+ bytes: number;
353
+ }
354
+
355
+ /** Plain bytes→tree (identical to capability-less {@link bytesToTree}) that
356
+ * also RETURNS its pyramid, reusing `prev` — the pyramid of a PROPER
357
+ * prefix of `bytes` (caller guarantees content match and
358
+ * prev.bytes < bytes.length). */
359
+ export function bytesToTreePyramid(
360
+ space: Space,
361
+ alphabet: Alphabet,
362
+ bytes: Uint8Array,
363
+ prev?: FoldPyramid,
364
+ ): { tree: Sema; pyramid: FoldPyramid } {
365
+ if (bytes.length === 0) {
366
+ return {
367
+ tree: sema(alphabet.vecs[0], new Uint8Array(0), null),
368
+ pyramid: { levels: [], bytes: 0 },
369
+ };
370
+ }
371
+ const mg = space.maxGroup;
372
+ const reusable = (L: number): ReadonlyArray<Folded> | null => {
373
+ // prev's TOPMOST level holds its normalized ROOT — reusable blocks must
374
+ // be raw interiors, so the top level is always excluded.
375
+ if (!prev || L > prev.levels.length - 2) return null;
376
+ return prev.levels[L];
377
+ };
378
+ // Level 0: reuse the prefix's leaf items wholesale (all are full blocks).
379
+ const lv0 = reusable(0);
380
+ const row: Folded[] = lv0
381
+ ? [...lv0, ...bytesToLeaves(alphabet, bytes.subarray(prev!.bytes))]
382
+ : bytesToLeaves(alphabet, bytes);
383
+ const levels: Folded[][] = [row];
384
+ let level = row;
385
+ let L = 0;
386
+ while (level.length > 1) {
387
+ let next: Folded[] = [];
388
+ // Reuse the leading FULL blocks of prev's level L+1 (len == mg^(L+1),
389
+ // wholly inside the prefix); the rule below folds the rest from this
390
+ // level's items exactly as the from-scratch fold would.
391
+ const blockLen = mg ** (L + 1);
392
+ let reused = 0;
393
+ const cand = reusable(L + 1);
394
+ if (cand) {
395
+ const maxFull = Math.floor(prev!.bytes / blockLen);
396
+ while (
397
+ reused < maxFull && reused < cand.length &&
398
+ cand[reused].len === blockLen
399
+ ) reused++;
400
+ for (let i = 0; i < reused; i++) next.push(cand[i]);
401
+ }
402
+ foldSlice(
403
+ space,
404
+ level,
405
+ reused * mg,
406
+ level.length - reused * mg,
407
+ next,
408
+ false,
409
+ );
410
+ if (next.length === level.length) {
411
+ // Stuck — same force-fold as riverFold (reuse cannot cause it: any
412
+ // reused block replaces a whole folded group, so reused > 0 implies
413
+ // progress).
414
+ const forced: Folded[] = [];
415
+ foldSlice(space, next, 0, next.length, forced, true);
416
+ next = forced;
417
+ }
418
+ levels.push(next);
419
+ level = next;
420
+ L++;
421
+ }
422
+ if (row.length > 1) normalize(level[0].tree.v);
423
+ return {
424
+ tree: level[0].tree,
425
+ pyramid: { levels, bytes: bytes.length },
426
+ };
427
+ }
428
+
429
+ // ---- n-D Hilbert curve ----
430
+
431
+ function gridDims(grid: Grid): number[] {
432
+ if (grid.dims && grid.dims.length > 0) return grid.dims.slice();
433
+ const dims = [grid.height, grid.width];
434
+ if (grid.channels > 1) dims.push(grid.channels);
435
+ return dims;
436
+ }
437
+
438
+ function hilbertPoint(index: number, n: number, bits: number): number[] {
439
+ const x = new Array<number>(n).fill(0);
440
+ for (let b = 0; b < bits; b++) {
441
+ for (let d = 0; d < n; d++) {
442
+ const bit = (index >>> (b * n + (n - 1 - d))) & 1;
443
+ x[d] |= bit << b;
444
+ }
445
+ }
446
+ const N = 1 << bits;
447
+ let t = x[n - 1] >> 1;
448
+ for (let i = n - 1; i > 0; i--) x[i] ^= x[i - 1];
449
+ x[0] ^= t;
450
+ for (let q = 2; q !== N; q <<= 1) {
451
+ const p = q - 1;
452
+ for (let i = n - 1; i >= 0; i--) {
453
+ if (x[i] & q) x[0] ^= p;
454
+ else {
455
+ t = (x[0] ^ x[i]) & p;
456
+ x[0] ^= t;
457
+ x[i] ^= t;
458
+ }
459
+ }
460
+ }
461
+ return x;
462
+ }
463
+
464
+ export function hilbertBytes(grid: Grid): Uint8Array {
465
+ const dims = gridDims(grid);
466
+ const n = dims.length;
467
+ if (n === 0 || grid.data.length === 0) return new Uint8Array(0);
468
+ if (n === 1) return grid.data.slice(0, dims[0]);
469
+ const maxAxis = Math.max(...dims);
470
+ const bits = Math.max(1, Math.ceil(Math.log2(maxAxis)));
471
+ const side = 1 << bits;
472
+ const total = Math.pow(side, n);
473
+ const stride = new Array<number>(n);
474
+ stride[n - 1] = 1;
475
+ for (let d = n - 2; d >= 0; d--) stride[d] = stride[d + 1] * dims[d + 1];
476
+ const out: number[] = [];
477
+ for (let h = 0; h < total; h++) {
478
+ const pt = hilbertPoint(h, n, bits);
479
+ let inside = true, flat = 0;
480
+ for (let d = 0; d < n; d++) {
481
+ if (pt[d] >= dims[d]) {
482
+ inside = false;
483
+ break;
484
+ }
485
+ flat += pt[d] * stride[d];
486
+ }
487
+ if (inside) out.push(grid.data[flat]);
488
+ }
489
+ return Uint8Array.from(out);
490
+ }
491
+
492
+ export function gridToTree(space: Space, alphabet: Alphabet, grid: Grid): Sema {
493
+ return bytesToTree(space, alphabet, hilbertBytes(grid));
494
+ }
495
+
496
+ export function stackGrids(frames: Grid[]): Grid {
497
+ if (frames.length === 0) {
498
+ return { width: 0, height: 0, channels: 0, data: new Uint8Array(0) };
499
+ }
500
+ const frameDims = gridDims(frames[0]);
501
+ const per = frames[0].data.length;
502
+ const data = new Uint8Array(per * frames.length);
503
+ for (let i = 0; i < frames.length; i++) data.set(frames[i].data, i * per);
504
+ return {
505
+ width: 0,
506
+ height: 0,
507
+ channels: 0,
508
+ dims: [frames.length, ...frameDims],
509
+ data,
510
+ };
511
+ }
package/src/index.ts ADDED
@@ -0,0 +1,38 @@
1
+ // sema — an elementary, recursive, weight-free multimodal mind.
2
+ // One structure, one verb, one memory. See AGENTS.md for the full algorithm.
3
+
4
+ export * from "./bytes.js";
5
+ export * from "./vec.js";
6
+ export * from "./sema.js";
7
+ export * from "./alphabet.js";
8
+ export * from "./geometry.js";
9
+ export * from "./store.js";
10
+ export * from "./mind/rationale.js";
11
+ export * from "./mind/index.js";
12
+ export * from "./store-sqlite.js";
13
+ export * from "./config.js";
14
+ export * from "./extension.js";
15
+ export * from "./ingest-cache.js";
16
+ // rabitq-hnsw is re-exported selectively: its `Store`, `NodeRec`, and
17
+ // `StoreConfig` are internal names that collide with sema's own top-level
18
+ // `store.js` / `config.js` exports, and sema code that needs the rabitq ones
19
+ // imports them from the subpath directly. Re-export the public vector-DB
20
+ // surface under the sema root, omitting the three colliding names.
21
+ export {
22
+ Heap,
23
+ HnswIndex,
24
+ Prng,
25
+ RaBitQuantizer,
26
+ VectorDatabase,
27
+ } from "./rabitq-hnsw/src/index.js";
28
+ export type {
29
+ DatabaseOptions,
30
+ ExternalId,
31
+ HnswParams,
32
+ KnnHit,
33
+ QueryContext,
34
+ QueryResult,
35
+ RaBitQOptions,
36
+ StorageStats,
37
+ } from "./rabitq-hnsw/src/index.js";
38
+ export * from "./derive/src/index.js";