@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,339 @@
1
+ // expr.ts — evaluate a symbolic EXPRESSION at a binding of its free variable.
2
+ //
3
+ // A numerical operation (a derivative, an integral, a limit — or any refinement
4
+ // the kernel can express) does not act on a number; it acts on a FUNCTION, and a
5
+ // function is an expression with a free variable. To refine such an operation,
6
+ // the engine must sample that expression at many points — and evaluating the
7
+ // expression is a RECURSIVE application of the very same ALU (its "+", "·",
8
+ // "sin", … are the registered ops). This module is that recursion.
9
+ //
10
+ // The grammar is NOT hardcoded: it is READ OFF the operation registry. An
11
+ // infix operator is any op registered with an `infix` trait (its precedence and
12
+ // associativity declared next to the op, kernel-arith.ts); a prefix operator is
13
+ // the arity-1 claimant of a shared symbol ("-" is negate before an operand,
14
+ // subtract between two); a function is any arity-1 op named by one of its
15
+ // surface forms; a CONSTANT is any arity-0 op (pi, e — registered like every
16
+ // other operation, kernel-numeric.ts). So extending the notation is extending
17
+ // the registry — no parser edits, no operator tables, no magic characters
18
+ // beyond the irreducible numeral floor.
19
+ //
20
+ // The free variable can be given explicitly or AUTO-DETECTED: when none is
21
+ // named, the single identifier that resolves to no registered op is taken as
22
+ // the variable. This keeps "x^2", "t*t", or a one-symbol form in any alphabet
23
+ // working without the caller having to spell out the variable.
24
+
25
+ import type { InfixSyntax, OperationRegistry } from "./operation.js";
26
+
27
+ /** Apply a scalar kernel op by canonical name to numeric arguments, returning a
28
+ * number. The expression evaluator routes every step through this, so the
29
+ * arithmetic inside an integrand is the kernel's own. */
30
+ export type ApplyScalar = (name: string, args: number[]) => number;
31
+
32
+ /** Whether a name is a registered unary function the evaluator may call. */
33
+ export type IsUnaryFn = (name: string) => boolean;
34
+
35
+ export interface Token {
36
+ kind: "num" | "name" | "op" | "lparen" | "rparen";
37
+ text: string;
38
+ value?: number;
39
+ }
40
+
41
+ const isDigit = (c: string) => c >= "0" && c <= "9";
42
+ // A "letter" for identifier purposes is any non-ASCII rune or an ASCII letter —
43
+ // so a variable or function name may be written in any script (multimodal /
44
+ // multilingual), not just A–Z. Operator glyphs (registered symbolic forms)
45
+ // are claimed BEFORE identifiers, so "·" and "≤" never read as names.
46
+ const isLetter = (c: string) =>
47
+ (c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.charCodeAt(0) > 127;
48
+ const isSpace = (c: string) =>
49
+ c === " " || c === "\t" || c === "\n" || c === "\r";
50
+
51
+ /** Tokenize an expression string: numerals (the irreducible floor), operator
52
+ * tokens (matched longest-first against `operators` — the registry's own
53
+ * symbolic surface forms), identifiers, and parentheses. When no operator
54
+ * vocabulary is given, each symbolic character stands alone (enough for name
55
+ * extraction). Returns null when a character fits none of these — the span is
56
+ * not a clean expression. */
57
+ export function tokenize(
58
+ s: string,
59
+ operators?: readonly string[],
60
+ ): Token[] | null {
61
+ const toks: Token[] = [];
62
+ let i = 0;
63
+ while (i < s.length) {
64
+ const c = s[i];
65
+ if (isSpace(c)) {
66
+ i++;
67
+ continue;
68
+ }
69
+ if (isDigit(c) || (c === "." && i + 1 < s.length && isDigit(s[i + 1]))) {
70
+ let j = i;
71
+ let seenDot = false;
72
+ while (j < s.length) {
73
+ if (isDigit(s[j])) j++;
74
+ else if (s[j] === "." && !seenDot) {
75
+ seenDot = true;
76
+ j++;
77
+ } else break;
78
+ }
79
+ // optional exponent
80
+ if (j < s.length && (s[j] === "e" || s[j] === "E")) {
81
+ let k = j + 1;
82
+ if (k < s.length && (s[k] === "+" || s[k] === "-")) k++;
83
+ if (k < s.length && isDigit(s[k])) {
84
+ while (k < s.length && isDigit(s[k])) k++;
85
+ j = k;
86
+ }
87
+ }
88
+ const text = s.slice(i, j);
89
+ const num = Number(text);
90
+ if (!Number.isFinite(num)) return null;
91
+ toks.push({ kind: "num", text, value: num });
92
+ i = j;
93
+ continue;
94
+ }
95
+ if (c === "(") {
96
+ toks.push({ kind: "lparen", text: c });
97
+ i++;
98
+ continue;
99
+ }
100
+ if (c === ")") {
101
+ toks.push({ kind: "rparen", text: c });
102
+ i++;
103
+ continue;
104
+ }
105
+ // A registered symbolic operator form, longest first — claimed before the
106
+ // identifier path so an operator GLYPH (·, ×, ≤, …) is an operator, not a
107
+ // name.
108
+ const op = operators?.find((f) => s.startsWith(f, i));
109
+ if (op !== undefined) {
110
+ toks.push({ kind: "op", text: op });
111
+ i += op.length;
112
+ continue;
113
+ }
114
+ if (isLetter(c)) {
115
+ let j = i;
116
+ while (j < s.length && (isLetter(s[j]) || isDigit(s[j]))) j++;
117
+ toks.push({ kind: "name", text: s.slice(i, j) });
118
+ i = j;
119
+ continue;
120
+ }
121
+ // Fallback for a symbolic character outside any vocabulary: its own token,
122
+ // so name extraction (freeVariables) still splits "a*b" without a grammar.
123
+ if (operators === undefined) {
124
+ toks.push({ kind: "op", text: c });
125
+ i++;
126
+ continue;
127
+ }
128
+ return null; // an unexpected character → not a clean expression
129
+ }
130
+ return toks;
131
+ }
132
+
133
+ /** The identifiers in `s` that are NOT known unary functions and NOT registered
134
+ * constants — the free-variable candidates. Used to auto-detect the variable
135
+ * when the caller did not name one. */
136
+ export function freeVariables(
137
+ s: string,
138
+ isUnaryFn: IsUnaryFn,
139
+ isConstant: (name: string) => boolean = () => false,
140
+ ): string[] {
141
+ const toks = tokenize(s);
142
+ if (!toks) return [];
143
+ const out: string[] = [];
144
+ const seen = new Set<string>();
145
+ for (let k = 0; k < toks.length; k++) {
146
+ const t = toks[k];
147
+ if (t.kind !== "name") continue;
148
+ // A name immediately followed by "(" is a function call, not a variable.
149
+ const isCall = k + 1 < toks.length && toks[k + 1].kind === "lparen";
150
+ if (isCall || isUnaryFn(t.text) || isConstant(t.text)) continue;
151
+ if (!seen.has(t.text)) {
152
+ seen.add(t.text);
153
+ out.push(t.text);
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** The expression grammar, read off an operation registry once and reused for
160
+ * every evaluation. It resolves each token through the registry's own form
161
+ * index — infix binding from the `infix` trait, a prefix operator as the
162
+ * arity-1 claimant of a shared symbol, functions as arity-1 ops, constants as
163
+ * arity-0 ops — so the grammar and the kernel can never drift apart. */
164
+ export class ExprGrammar {
165
+ /** Symbolic operator tokens, longest first (so "<=" wins over "<"). */
166
+ private readonly operatorTokens: string[];
167
+ /** token → the infix op it names and its declared binding. */
168
+ private readonly infixTable = new Map<
169
+ string,
170
+ { name: string; syntax: InfixSyntax }
171
+ >();
172
+ /** token → the arity-1 (prefix) op it names. */
173
+ private readonly prefixTable = new Map<string, string>();
174
+ /** The tightest infix tier — a prefix operator binds its operand up through
175
+ * it, so "-x^2" reads -(x^2) without a hardcoded rule. */
176
+ private readonly maxPrecedence: number;
177
+
178
+ constructor(
179
+ private readonly registry: OperationRegistry,
180
+ private readonly applyScalar: ApplyScalar,
181
+ ) {
182
+ const tokens = new Set<string>();
183
+ let maxPrec = 0;
184
+ for (const { form, name } of registry.formEntries()) {
185
+ const op = registry.get(name)!;
186
+ const symbolic = form.length > 0 && !/[A-Za-z0-9]/.test(form);
187
+ if (!symbolic) continue;
188
+ tokens.add(form);
189
+ if (op.infix && !this.infixTable.has(form)) {
190
+ this.infixTable.set(form, { name, syntax: op.infix });
191
+ maxPrec = Math.max(maxPrec, op.infix.precedence);
192
+ }
193
+ if (op.arity === 1 && !this.prefixTable.has(form)) {
194
+ this.prefixTable.set(form, name);
195
+ }
196
+ }
197
+ this.operatorTokens = [...tokens].sort((a, b) => b.length - a.length);
198
+ this.maxPrecedence = maxPrec;
199
+ }
200
+
201
+ /** Resolve an identifier to a registered op of the given arity: a surface
202
+ * form claimant of that arity first, else the canonical name itself. */
203
+ private resolveName(name: string, arity: number): string | null {
204
+ for (const n of this.registry.lookupForm(name)) {
205
+ if (this.registry.get(n)!.arity === arity) return n;
206
+ }
207
+ const own = this.registry.get(name);
208
+ return own && own.arity === arity ? name : null;
209
+ }
210
+
211
+ /** Whether an identifier names a unary function. */
212
+ isFunction(name: string): boolean {
213
+ return this.resolveName(name, 1) !== null;
214
+ }
215
+
216
+ /** Whether an identifier names a nullary constant (an arity-0 op). */
217
+ isConstant(name: string): boolean {
218
+ return this.resolveName(name, 0) !== null;
219
+ }
220
+
221
+ /** Tokenize with this grammar's operator vocabulary. */
222
+ tokenize(s: string): Token[] | null {
223
+ return tokenize(s, this.operatorTokens);
224
+ }
225
+
226
+ /** The free-variable candidates of `s` under this grammar. */
227
+ freeVariables(s: string): string[] {
228
+ return freeVariables(
229
+ s,
230
+ (n) => this.isFunction(n),
231
+ (n) => this.isConstant(n),
232
+ );
233
+ }
234
+
235
+ /** Evaluate expression `s` with `variable` bound to `at`. Returns a number,
236
+ * or null if `s` is not a well-formed expression. Every binary/function/
237
+ * constant step is applied through the kernel, so the arithmetic is the
238
+ * kernel's own. When `variable` is empty, the single free variable is
239
+ * auto-detected; if there is more than one and none was named, evaluation
240
+ * declines (null) — a genuinely multivariate expression needs an explicit
241
+ * binding. */
242
+ eval(s: string, variable: string, at: number): number | null {
243
+ const toks = this.tokenize(s);
244
+ if (!toks || toks.length === 0) return null;
245
+
246
+ let v = variable;
247
+ if (v === "") {
248
+ const fv = this.freeVariables(s);
249
+ if (fv.length === 1) v = fv[0];
250
+ else if (fv.length > 1) return null; // multivariate, no binding named
251
+ // fv.length === 0: a constant expression is fine.
252
+ }
253
+
254
+ let pos = 0;
255
+ const peek = () => toks[pos];
256
+ const next = () => toks[pos++];
257
+ const FAIL = Symbol("expr-fail");
258
+ const fail = (): never => {
259
+ throw FAIL;
260
+ };
261
+ const grammar = this;
262
+
263
+ // Precedence climbing over the registry-declared infix tiers.
264
+ function parseExpr(minPrec: number): number {
265
+ let lhs = parseOperand();
266
+ for (;;) {
267
+ const t = peek();
268
+ if (!t || t.kind !== "op") break;
269
+ const infix = grammar.infixTable.get(t.text);
270
+ if (!infix || infix.syntax.precedence < minPrec) break;
271
+ next();
272
+ const nextMin = infix.syntax.rightAssoc
273
+ ? infix.syntax.precedence
274
+ : infix.syntax.precedence + 1;
275
+ const rhs = parseExpr(nextMin);
276
+ lhs = grammar.applyScalar(infix.name, [lhs, rhs]);
277
+ }
278
+ return lhs;
279
+ }
280
+
281
+ // An operand: a prefix operator (the arity-1 claimant of its symbol,
282
+ // binding up through the tightest infix tier), or an atom.
283
+ function parseOperand(): number {
284
+ const t = peek();
285
+ if (t && t.kind === "op") {
286
+ const prefix = grammar.prefixTable.get(t.text);
287
+ if (prefix === undefined) return fail();
288
+ next();
289
+ return grammar.applyScalar(prefix, [parseExpr(grammar.maxPrecedence)]);
290
+ }
291
+ return parseAtom();
292
+ }
293
+
294
+ function parseAtom(): number {
295
+ const t = peek();
296
+ if (!t) fail();
297
+ if (t.kind === "num") {
298
+ next();
299
+ return t.value!;
300
+ }
301
+ if (t.kind === "lparen") {
302
+ next();
303
+ const inner = parseExpr(0);
304
+ if (!peek() || peek().kind !== "rparen") fail();
305
+ next();
306
+ return inner;
307
+ }
308
+ if (t.kind === "name") {
309
+ next();
310
+ // A function call: name "(" expr ")".
311
+ if (peek() && peek().kind === "lparen") {
312
+ const fn = grammar.resolveName(t.text, 1);
313
+ if (fn === null) return fail();
314
+ next(); // (
315
+ const arg = parseExpr(0);
316
+ if (!peek() || peek().kind !== "rparen") fail();
317
+ next(); // )
318
+ return grammar.applyScalar(fn, [arg]);
319
+ }
320
+ // Otherwise an identifier: the free variable, or a nullary constant
321
+ // resolved through the registry like any other operation.
322
+ if (t.text === v) return at;
323
+ const konst = grammar.resolveName(t.text, 0);
324
+ if (konst !== null) return grammar.applyScalar(konst, []);
325
+ return fail();
326
+ }
327
+ return fail();
328
+ }
329
+
330
+ try {
331
+ const result = parseExpr(0);
332
+ if (pos !== toks.length) return null; // trailing tokens → malformed
333
+ return Number.isFinite(result) ? result : null;
334
+ } catch (err) {
335
+ if (err === FAIL) return null;
336
+ return null; // a kernel apply threw (e.g. ÷0 produced ∞) → decline
337
+ }
338
+ }
339
+ }
@@ -0,0 +1,115 @@
1
+ // alu — the ALU sub-library: a tiny irreducible kernel from which arithmetic,
2
+ // logic, and numerical computation are all DERIVED.
3
+ //
4
+ // Self-contained in the spirit of derive/ and rabitq-hnsw/: it imports only the
5
+ // pure byte helpers (../../bytes.js) and nothing else from SEMA. The host
6
+ // reaches meaning (operator synonymy, the symbolic inverse) through the injected
7
+ // AluResonance, pre-resolved into a synchronous snapshot before the search runs.
8
+ // See ./../README.md for the kernel and its derivation DAG.
9
+
10
+ export {
11
+ asBit,
12
+ asInt,
13
+ asReal,
14
+ bit,
15
+ coerce,
16
+ decimalCodec,
17
+ type Domain,
18
+ formatReal,
19
+ int,
20
+ isNd,
21
+ isNumeric,
22
+ joinDomain,
23
+ nd,
24
+ parseValue,
25
+ real,
26
+ symbol,
27
+ symbolSpans,
28
+ tagOf,
29
+ type Value,
30
+ type ValueCodec,
31
+ } from "./value.js";
32
+
33
+ export {
34
+ type Arity,
35
+ type EvalExpr,
36
+ type InfixSyntax,
37
+ NO_RESONANCE,
38
+ type OpContext,
39
+ type Operation,
40
+ OperationRegistry,
41
+ type OpFn,
42
+ type OpRuntime,
43
+ type OpTraits,
44
+ type ResonanceSync,
45
+ } from "./operation.js";
46
+
47
+ export {
48
+ type AluResonance,
49
+ type ConceptAnchor,
50
+ NO_ALU_RESONANCE,
51
+ prefetchOpposites,
52
+ prefetchRecognisedOps,
53
+ prefetchResonance,
54
+ } from "./resonance.js";
55
+
56
+ export {
57
+ type ApplyScalar,
58
+ ExprGrammar,
59
+ freeVariables,
60
+ type IsUnaryFn,
61
+ type Token,
62
+ tokenize,
63
+ } from "./expr.js";
64
+
65
+ export {
66
+ type AluHost,
67
+ type ComputedSpan,
68
+ QueryParser,
69
+ type Span,
70
+ STRUCTURAL_HOST,
71
+ } from "./parser.js";
72
+
73
+ export { registerNd } from "./kernel-nd.js";
74
+ export { registerLogic } from "./kernel-logic.js";
75
+ export {
76
+ addBits,
77
+ compareBits,
78
+ mulBits,
79
+ negateBits,
80
+ registerBits,
81
+ signBits,
82
+ } from "./kernel-bits.js";
83
+ export {
84
+ dot,
85
+ linsolve,
86
+ matMul,
87
+ matVec,
88
+ polyEval,
89
+ registerArith,
90
+ } from "./kernel-arith.js";
91
+ export {
92
+ converge,
93
+ cosSeries,
94
+ diff,
95
+ expSeries,
96
+ integrate,
97
+ interpolate,
98
+ logNewton,
99
+ odeSolve,
100
+ optimize,
101
+ powerEig,
102
+ registerNumeric,
103
+ regress,
104
+ sinSeries,
105
+ solve,
106
+ sqrtNewton,
107
+ topSingular,
108
+ } from "./kernel-numeric.js";
109
+
110
+ export {
111
+ Alu,
112
+ type AluOptions,
113
+ type OperandSpan,
114
+ type OperatorSpan,
115
+ } from "./alu.js";