@hviana/sema 0.1.9 → 0.2.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 (129) 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 +125 -0
  42. package/dist/src/derive/src/deduction.js +155 -0
  43. package/dist/src/derive/src/index.d.ts +7 -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 +148 -0
  56. package/dist/src/geometry.js +511 -0
  57. package/dist/src/index.d.ts +16 -0
  58. package/dist/src/index.js +18 -0
  59. package/dist/src/ingest-cache.d.ts +41 -0
  60. package/dist/src/ingest-cache.js +161 -0
  61. package/dist/src/mind/articulation.d.ts +6 -0
  62. package/dist/src/mind/articulation.js +99 -0
  63. package/dist/src/mind/attention.d.ts +72 -0
  64. package/dist/src/mind/attention.js +898 -0
  65. package/dist/src/mind/canonical.d.ts +29 -0
  66. package/dist/src/mind/canonical.js +88 -0
  67. package/dist/src/mind/graph-search.d.ts +270 -0
  68. package/dist/src/mind/graph-search.js +847 -0
  69. package/dist/src/mind/index.d.ts +5 -0
  70. package/dist/src/mind/index.js +5 -0
  71. package/dist/src/mind/junction.d.ts +95 -0
  72. package/dist/src/mind/junction.js +262 -0
  73. package/dist/src/mind/learning.d.ts +47 -0
  74. package/dist/src/mind/learning.js +233 -0
  75. package/dist/src/mind/match.d.ts +113 -0
  76. package/dist/src/mind/match.js +446 -0
  77. package/dist/src/mind/mechanisms/alu.d.ts +4 -0
  78. package/dist/src/mind/mechanisms/alu.js +29 -0
  79. package/dist/src/mind/mechanisms/cast.d.ts +35 -0
  80. package/dist/src/mind/mechanisms/cast.js +461 -0
  81. package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
  82. package/dist/src/mind/mechanisms/confluence.js +225 -0
  83. package/dist/src/mind/mechanisms/cover.d.ts +6 -0
  84. package/dist/src/mind/mechanisms/cover.js +179 -0
  85. package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
  86. package/dist/src/mind/mechanisms/extraction.js +342 -0
  87. package/dist/src/mind/mechanisms/recall.d.ts +13 -0
  88. package/dist/src/mind/mechanisms/recall.js +235 -0
  89. package/dist/src/mind/mind.d.ts +273 -0
  90. package/dist/src/mind/mind.js +562 -0
  91. package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
  92. package/dist/src/mind/pipeline-mechanism.js +213 -0
  93. package/dist/src/mind/pipeline.d.ts +20 -0
  94. package/dist/src/mind/pipeline.js +185 -0
  95. package/dist/src/mind/primitives.d.ts +63 -0
  96. package/dist/src/mind/primitives.js +251 -0
  97. package/dist/src/mind/rationale.d.ts +134 -0
  98. package/dist/src/mind/rationale.js +162 -0
  99. package/dist/src/mind/reasoning.d.ts +15 -0
  100. package/dist/src/mind/reasoning.js +162 -0
  101. package/dist/src/mind/recognition.d.ts +20 -0
  102. package/dist/src/mind/recognition.js +246 -0
  103. package/dist/src/mind/resonance.d.ts +23 -0
  104. package/dist/src/mind/resonance.js +0 -0
  105. package/dist/src/mind/trace.d.ts +15 -0
  106. package/dist/src/mind/trace.js +73 -0
  107. package/dist/src/mind/traverse.d.ts +113 -0
  108. package/dist/src/mind/traverse.js +488 -0
  109. package/dist/src/mind/types.d.ts +186 -0
  110. package/dist/src/mind/types.js +84 -0
  111. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  112. package/dist/src/rabitq-ivf/src/database.js +201 -0
  113. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  114. package/dist/src/rabitq-ivf/src/index.js +4 -0
  115. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  116. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  117. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  118. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  119. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  120. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  121. package/dist/src/sema.d.ts +31 -0
  122. package/dist/src/sema.js +63 -0
  123. package/dist/src/store-sqlite.d.ts +184 -0
  124. package/dist/src/store-sqlite.js +942 -0
  125. package/dist/src/store.d.ts +654 -0
  126. package/dist/src/store.js +1612 -0
  127. package/dist/src/vec.d.ts +31 -0
  128. package/dist/src/vec.js +109 -0
  129. package/package.json +1 -1
@@ -0,0 +1,577 @@
1
+ // parser.ts — the ALU's query parser: recognise and evaluate every computation
2
+ // a raw byte query invokes.
3
+ //
4
+ // This is the intelligence layered over the Alu facade, and the ONLY module
5
+ // that reaches outside the kernel — through one narrow port, {@link AluHost}.
6
+ // The host (SEMA's Mind, or nothing) supplies exactly the two things bytes
7
+ // alone cannot answer:
8
+ //
9
+ // • MEANING (resonance) — which operation an opaque span names, and what the
10
+ // resonant opposite of a symbol is. Both are async (they hit the host's
11
+ // gist/halo index) and both are pre-resolved here, before any synchronous
12
+ // computation — the same hoisting discipline the host's search applies to
13
+ // concept hops and connectors.
14
+ // • GEOMETRY (segmentation) — where coherent runs begin and end. The parser
15
+ // never decides for itself whether the bytes between two tokens are "just a
16
+ // separator": it asks the host's geometric segmenter (the same one the
17
+ // perception tree uses), so what counts as spacing is a property of the
18
+ // learnt alphabet space, not a hardcoded character class. `reach` bounds
19
+ // how far an operator may look for its operand — the host's own grouping
20
+ // capacity, so "not … 4" across prose stays silent while "not 4" fires.
21
+ //
22
+ // Everything else — what a numeral is, which symbols are operators, how infix
23
+ // binds, which ops act on expressions — is read off the operation registry via
24
+ // the facade. The parser therefore has NO vocabulary of its own: extend the
25
+ // registry and the parser understands the new notation; teach the host's
26
+ // resonance space and it understands new spellings of the old one.
27
+ //
28
+ // The parser LEXES the query once into a single ascending TOKEN stream —
29
+ // numeric OPERANDS and symbolic OPERATORS from the facade's scanner, and the
30
+ // unclaimed runs between them as TERMS — and every recogniser reads that one
31
+ // stream. Tokens are disjoint and cover every non-spacing byte, so the gap
32
+ // between two consecutive tokens is pure spacing by construction. What it finds (independent of any
33
+ // content-defined chunking, so a number a chunker would split is read whole):
34
+ //
35
+ // 1. INFIX ARITHMETIC RUNS — maximal alternations of numeric operands and
36
+ // symbolic operators ("2+3*4", "3 + 3"), evaluated wholesale through the
37
+ // registry-derived expression grammar, so chaining and precedence are a
38
+ // recursive application of the same kernel.
39
+ // 2. OPERATIONS NAMED BY MEANING — a term (word, glyph, image/audio fragment)
40
+ // that names an operation literally or by resonance, applied to a
41
+ // following operand ("opposite large" → "small"), or, for the numerical
42
+ // layer, to a following EXPRESSION ("derivative of x^2 at 3").
43
+ import { prefetchOpposites, prefetchResonance, } from "./resonance.js";
44
+ import { NO_RESONANCE } from "./operation.js";
45
+ import { int, real, symbol, symbolSpans } from "./value.js";
46
+ import { nonSpaceRuns } from "./text.js";
47
+ import { bytesEqual, latin1 } from "../../bytes.js";
48
+ /** A host that knows nothing beyond structure: no resonance, whitespace-run
49
+ * segmentation, unbounded reach. This is what "the ALU runs fully decoupled"
50
+ * means — the parser still reads literal notation, and only the meaning-based
51
+ * paths stay silent. */
52
+ export const STRUCTURAL_HOST = {
53
+ meaningOf: async () => null,
54
+ continuation: async () => null,
55
+ segment: (bytes) => nonSpaceRuns(bytes),
56
+ reach: Number.POSITIVE_INFINITY,
57
+ };
58
+ export class QueryParser {
59
+ alu;
60
+ host;
61
+ /** The host's generic capabilities, specialised once into the {@link
62
+ * AluResonance} the prefetch bridges consume — the ONE place the ALU gives
63
+ * the host's neutral answers their computational reading: op recognition is
64
+ * meaningOf over the ALU's own concept anchors, and the polymorphic INVERSE
65
+ * of a symbol is the corpus's grounded continuation of it (a learnt
66
+ * opposition relation leads from a form to its opposite; the host never
67
+ * needs to know that is what it grounded). */
68
+ resonance;
69
+ /** Session memo of a term's meaning-based op reading, keyed by its bytes.
70
+ * `meaningOf` is a full river fold of the span — measured at ~a third of
71
+ * a plain-English respond's latency, paid per WORD per query — and it is
72
+ * a pure function of the bytes (perception is pure; the concept anchors
73
+ * are fixed for the Alu's lifetime), so the reading never changes.
74
+ * Bounded: cleared wholesale when full (words recur; a rare clear only
75
+ * re-pays folds, never changes a reading). */
76
+ meaningMemo = new Map();
77
+ static MEANING_MEMO_MAX = 4096;
78
+ constructor(alu, host = STRUCTURAL_HOST) {
79
+ this.alu = alu;
80
+ this.host = host;
81
+ this.resonance = {
82
+ recogniseOp: (bytes) => host.meaningOf(bytes, alu.conceptAnchors()),
83
+ opposite: (bytes) => host.continuation(bytes),
84
+ };
85
+ }
86
+ /** Recognise and evaluate every computation `query` invokes. All async
87
+ * resonance is resolved in here, so the caller receives finished spans it
88
+ * can fold synchronously into its search. Results are deduplicated; a span
89
+ * that fails to compute is simply absent (the "rule does not fire"
90
+ * contract).
91
+ *
92
+ * The pipeline is one composition ladder, iterated to a FIXPOINT:
93
+ *
94
+ * 1. infix arithmetic RUNS are found and evaluated through the
95
+ * registry-derived grammar;
96
+ * 2. every computed span — a run, or a fired operation — is COLLAPSED
97
+ * into a single virtual operand, so the next round consumes it as one
98
+ * finished value: "sum 1*3 4" is add(3, 4), and "sqrt sum 9 16" is
99
+ * sqrt(25) — nesting by iteration, exactly as the grammar nests
100
+ * expressions, with no recursion machinery of its own;
101
+ * 3. rounds repeat while operations still fire (each round consumes at
102
+ * least one term, so the ladder is bounded by the term count).
103
+ *
104
+ * One AUTHORITY law then reconciles the readings: a span strictly
105
+ * contained in a larger computed span is that computation's MATERIAL (the
106
+ * "2-4" inside a solve's "x^2-4", the inner sum under a sqrt), not a rival
107
+ * result — the same rule by which the host's search lets a computed span
108
+ * override colliding learned facts. */
109
+ async parse(query) {
110
+ const tokens = this.lex(query);
111
+ const runs = this.arithmeticRuns(query, tokens).map(([i, j]) => ({
112
+ i,
113
+ j,
114
+ bytes: this.evalRun(query.subarray(i, j)),
115
+ }));
116
+ // BRACKETED runs — "(3 + 4) * (10 - 2)" — extend across grouping
117
+ // notation the flat alternation cannot cross. The expression grammar
118
+ // (expr.ts) already nests and parenthesizes; this only hands it the
119
+ // WHOLE bracketed span instead of the fragments between brackets. A
120
+ // bracketed run that evaluates ABSORBS the flat runs inside it (the
121
+ // authority law: contained spans are its material); one that does not
122
+ // evaluate leaves the flat readings untouched.
123
+ const bracketed = this.bracketedRuns(query, tokens)
124
+ .map(([i, j]) => ({ i, j, bytes: this.evalRun(query.subarray(i, j)) }))
125
+ .filter((r) => r.bytes !== null);
126
+ const absorbed = (r) => bracketed.some((b) => b.i <= r.i && r.j <= b.j);
127
+ const composedRuns = [
128
+ ...runs.filter((r) => !absorbed(r)),
129
+ ...bracketed,
130
+ ].sort((a, b) => a.i - b.i);
131
+ const spans = [
132
+ ...runs.filter((r) => r.bytes !== null),
133
+ ...bracketed,
134
+ ];
135
+ let stream = compose(tokens, composedRuns);
136
+ const readings = new Map();
137
+ for (;;) {
138
+ const fired = await this.operations(query, stream, readings);
139
+ if (fired.length === 0)
140
+ break;
141
+ spans.push(...fired);
142
+ stream = compose(stream, fired);
143
+ }
144
+ return authoritative(dedup(spans));
145
+ }
146
+ /** Apply an ALU operation to operand byte spans, with the host's resonance
147
+ * wired in — the entry point for computation over n-dimensional values.
148
+ *
149
+ * Unlike the in-query arithmetic rule (which hands the facade scalar operand
150
+ * bytes), this recognises each operand's STRUCTURE into a Value first and
151
+ * runs the kernel on the finished Values, with the full resonance snapshot
152
+ * pre-resolved — because an nd computation needs meaning in two places the
153
+ * bare facade cannot reach on its own:
154
+ *
155
+ * • the polymorphic INVERSE inside a broadcast — `inverse [large, 3, tall]`
156
+ * lifts element-wise (operation.ts), and each symbol element's opposite
157
+ * is a resonant lookup, grounded in the host's corpus exactly as a scalar
158
+ * inverse is;
159
+ * • the FUNCTION ARGUMENT of a higher-order op — `reduce(xs, ‹+›)`,
160
+ * `map(xs, ‹negate›)`: the operator value is resolved by
161
+ * {@link "./operation.js".OpContext.resolveOp}, which falls through to
162
+ * resonance when the bytes are not a literal surface form.
163
+ *
164
+ * Both are async, so every SYMBOL span reachable in the operands (recursing
165
+ * through nd nesting, see {@link "./value.js".symbolSpans}) is resolved ONCE
166
+ * up front into a synchronous snapshot, and the synchronous kernel computes
167
+ * against it. Returns null when the op is unknown or the computation
168
+ * declines — the "this rule does not fire" contract.
169
+ *
170
+ * `asSymbol(idx)` keeps an operand opaque (not read as structure or a
171
+ * number) — the numerical-layer convention where operand 0 is an
172
+ * expression's bytes; it defaults to "recognise everything", which is what
173
+ * an nd computation wants. */
174
+ async compute(name, operandBytes, asSymbol = () => false) {
175
+ const operands = [];
176
+ const spans = [];
177
+ for (let i = 0; i < operandBytes.length; i++) {
178
+ const v = asSymbol(i)
179
+ ? symbol(operandBytes[i])
180
+ : this.alu.recogniseValue(operandBytes[i]);
181
+ operands.push(v);
182
+ symbolSpans(v, spans);
183
+ }
184
+ const resonance = await prefetchResonance(this.resonance, spans);
185
+ return this.alu.applyValues(name, operands, resonance);
186
+ }
187
+ // ── the lex: one reading of the query every recogniser shares ────────────
188
+ /** Lex the query ONCE into a single ascending token stream: the facade's
189
+ * scanner claims numeric OPERANDS and symbolic OPERATORS, and every maximal
190
+ * unclaimed run between spacing bytes is a TERM — a word, glyph, or opaque
191
+ * fragment that may name an operation. Terms are deliberately bounded by
192
+ * the spacing floor, not the host's geometric segmentation: perception may
193
+ * cut mid-word (its segments are grouping capacity, not word boundaries),
194
+ * while an operation NAME is a notation-level token. Geometry still
195
+ * governs what happens BETWEEN tokens (gap bridging, operand reach).
196
+ *
197
+ * Tokens are disjoint, ascending, and cover every non-spacing byte — so
198
+ * the gap between consecutive tokens is pure spacing BY CONSTRUCTION, a
199
+ * structural fact the run recogniser leans on. */
200
+ lex(query) {
201
+ const { operands, operators } = this.alu.scan(query);
202
+ const claimed = [
203
+ ...operands.map((o) => ({ i: o.i, j: o.j, kind: "operand" })),
204
+ ...operators.map((o) => ({ i: o.i, j: o.j, kind: "operator" })),
205
+ ].sort((a, b) => a.i - b.i);
206
+ const tokens = [];
207
+ let p = 0;
208
+ for (const c of [...claimed, END]) {
209
+ for (const t of nonSpaceRuns(query, p, Math.min(c.i, query.length))) {
210
+ tokens.push({ ...t, kind: "term" });
211
+ }
212
+ if (c !== END)
213
+ tokens.push(c);
214
+ p = c.j;
215
+ }
216
+ return tokens;
217
+ }
218
+ // ── (1) infix arithmetic ──────────────────────────────────────────────────
219
+ /** The maximal infix-arithmetic runs in the query: an alternation of numeric
220
+ * operands and SYMBOLIC operators (e.g. "2+3*4"), returned as [start, end)
221
+ * ranges that begin and end on an operand.
222
+ *
223
+ * Consecutive tokens may be SEPARATED — "3 + 3" is the same run as "3+3".
224
+ * The gap between two tokens is a bridgeable separator exactly when the
225
+ * host's geometric segmenter reads it as at most one coherent run — the
226
+ * same judgement the perception tree makes about spacing — so no character
227
+ * is privileged as "the" separator. */
228
+ arithmeticRuns(query, tokens) {
229
+ const bridged = (from, to) => from >= to || this.host.segment(query.subarray(from, to)).length <= 1;
230
+ const runs = [];
231
+ let k = 0;
232
+ while (k < tokens.length) {
233
+ if (tokens[k].kind !== "operand") {
234
+ k++;
235
+ continue;
236
+ }
237
+ let end = k;
238
+ while (end + 1 < tokens.length &&
239
+ tokens[end + 1].kind !== "term" && // a term breaks the notation
240
+ tokens[end + 1].kind !== tokens[end].kind && // alternates
241
+ bridged(tokens[end].j, tokens[end + 1].i) // pure-spacing gap coheres
242
+ )
243
+ end++;
244
+ while (end > k && tokens[end].kind === "operator")
245
+ end--; // end on operand
246
+ if (end > k)
247
+ runs.push([tokens[k].i, tokens[end].j]);
248
+ k = end + 1;
249
+ }
250
+ return runs;
251
+ }
252
+ /** The maximal BRACKETED arithmetic runs: like {@link arithmeticRuns} but
253
+ * grouping brackets participate — an all-'(' term opens depth where an
254
+ * operand is expected, a term beginning with ')' closes it where an
255
+ * operator could follow (only its bracket prefix joins the run; anything
256
+ * after — a trailing "?" — ends it). A run is recorded only when it is
257
+ * BALANCED, actually crossed a bracket, and contains an operator — the
258
+ * bracket-free case is {@link arithmeticRuns}' own. Evaluation is the
259
+ * same registry-derived grammar, whose lexer already reads the brackets. */
260
+ bracketedRuns(query, tokens) {
261
+ const OPEN = 0x28, CLOSE = 0x29;
262
+ const bracketPrefix = (t, b) => {
263
+ if (t.kind !== "term")
264
+ return 0;
265
+ let n = 0;
266
+ while (t.i + n < t.j && query[t.i + n] === b)
267
+ n++;
268
+ return n;
269
+ };
270
+ const allOf = (t, b) => bracketPrefix(t, b) === t.j - t.i;
271
+ const bridged = (from, to) => from >= to || this.host.segment(query.subarray(from, to)).length <= 1;
272
+ const runs = [];
273
+ let k = 0;
274
+ while (k < tokens.length) {
275
+ const first = tokens[k];
276
+ if (first.kind !== "operand" && !allOf(first, OPEN)) {
277
+ k++;
278
+ continue;
279
+ }
280
+ let depth = 0;
281
+ let ops = 0;
282
+ let brackets = 0;
283
+ let expectOperand = true;
284
+ let end = -1; // byte end of the last VALID run state (balanced, after operand/close)
285
+ let endTok = k; // token index just past the accepted prefix
286
+ let m = k;
287
+ let prevJ = -1;
288
+ while (m < tokens.length) {
289
+ const t = tokens[m];
290
+ if (prevJ >= 0 && !bridged(prevJ, t.i))
291
+ break;
292
+ if (expectOperand) {
293
+ if (allOf(t, OPEN)) {
294
+ depth += t.j - t.i;
295
+ brackets++;
296
+ }
297
+ else if (t.kind === "operand") {
298
+ expectOperand = false;
299
+ if (depth === 0) {
300
+ end = t.j;
301
+ endTok = m + 1;
302
+ }
303
+ }
304
+ else
305
+ break;
306
+ }
307
+ else {
308
+ const c = bracketPrefix(t, CLOSE);
309
+ if (c > 0 && depth > 0) {
310
+ const take = Math.min(c, depth);
311
+ depth -= take;
312
+ brackets++;
313
+ if (depth === 0) {
314
+ end = t.i + take;
315
+ endTok = m + 1;
316
+ }
317
+ // A term with content beyond its usable bracket prefix ("?")
318
+ // ends the run inside the term.
319
+ if (take < t.j - t.i)
320
+ break;
321
+ }
322
+ else if (t.kind === "operator") {
323
+ expectOperand = true;
324
+ ops++;
325
+ }
326
+ else
327
+ break;
328
+ }
329
+ prevJ = t.j;
330
+ m++;
331
+ }
332
+ if (end >= 0 && ops > 0 && brackets > 0) {
333
+ runs.push([first.i, end]);
334
+ k = endTok;
335
+ }
336
+ else {
337
+ k++;
338
+ }
339
+ }
340
+ return runs;
341
+ }
342
+ /** Evaluate an infix-arithmetic run to its canonical result bytes, through
343
+ * the kernel's recursive expression evaluator, or null if it does not
344
+ * evaluate. A whole result stays an exact int; otherwise the canonical
345
+ * rounded real — deterministic, so the search's chart memoises identical
346
+ * results identically. */
347
+ evalRun(runBytes) {
348
+ const x = this.alu.evalExpression(runBytes, "", 0);
349
+ if (x === null || !Number.isFinite(x))
350
+ return null;
351
+ return this.alu.codec.encode(Number.isInteger(x) ? int(BigInt(x)) : real(x));
352
+ }
353
+ // ── (2) operations named by NAME or MEANING ───────────────────────────────
354
+ /** Recognise and apply the operations the query's TERMS name — the generic,
355
+ * multimodal path. A term may name an operation literally (its bytes are a
356
+ * registered surface form — no resonance cost) or by RESONANCE (its gist
357
+ * lands on an operation's concept, any modality).
358
+ *
359
+ * Recognition PROPOSES, application DISPOSES: a surface form may be shared
360
+ * by several operations ("zero" is both the constant and solve's
361
+ * root-finding), so every literal claimant is kept, in registration order,
362
+ * and the first whose application actually fires wins — disambiguation by
363
+ * what the query supplies, not by a precedence table. Recognition runs
364
+ * CONCURRENTLY — each term's reading is independent — and is memoised in
365
+ * `readings` across fixpoint rounds (a surviving term is the same token
366
+ * object), so each term resonates at most once per parse. Application is
367
+ * then ordered and deterministic: an EXPRESSION op takes the function that
368
+ * follows it ({@link applyToExpression}), any other op takes its arity's
369
+ * worth of operands from the stream ({@link applyToStream}). Both read
370
+ * the same composed stream — an expression's TEXT comes from the raw query
371
+ * bytes by position, so composition never disturbs it, while a composed
372
+ * operand serves as a finished point/bound or argument. */
373
+ async operations(query, tokens, readings) {
374
+ const terms = tokens.filter((t) => t.kind === "term");
375
+ const anchors = this.alu.conceptAnchors();
376
+ await Promise.all(terms.map(async (term) => {
377
+ if (readings.has(term))
378
+ return;
379
+ const span = query.subarray(term.i, term.j);
380
+ const key = latin1(span);
381
+ const literal = this.alu.lookupOperator(key);
382
+ if (literal.length > 0) {
383
+ readings.set(term, literal);
384
+ return;
385
+ }
386
+ const hit = this.meaningMemo.get(key);
387
+ if (hit !== undefined) {
388
+ readings.set(term, hit);
389
+ return;
390
+ }
391
+ const m = await this.host.meaningOf(span, anchors);
392
+ const meant = m ? [m] : [];
393
+ if (this.meaningMemo.size >= QueryParser.MEANING_MEMO_MAX) {
394
+ this.meaningMemo.clear();
395
+ }
396
+ this.meaningMemo.set(key, meant);
397
+ readings.set(term, meant);
398
+ }));
399
+ const out = [];
400
+ for (const term of terms) {
401
+ for (const name of readings.get(term)) {
402
+ const result = this.alu.isExpressionOp(name)
403
+ ? this.applyToExpression(query, name, term, tokens)
404
+ : await this.applyToStream(query, name, term, tokens);
405
+ if (result) {
406
+ out.push(result);
407
+ break; // the first claimant that fires owns the term
408
+ }
409
+ }
410
+ }
411
+ return out;
412
+ }
413
+ /** Apply a NUMERICAL-LAYER op — one whose first operand is an EXPRESSION (a
414
+ * function), declared by the op's own `expression` trait. The registry's
415
+ * arity says how many trailing numeric operands are its points/bounds
416
+ * (arity − 1); the bytes between the operator and those points — with
417
+ * non-math filler stripped by {@link cleanExprText} — are the expression,
418
+ * evaluated by a recursive application of the kernel. */
419
+ applyToExpression(query, name, term, tokens) {
420
+ const operands = tokens.filter((t) => t.kind === "operand" && t.i >= term.j);
421
+ const arity = this.alu.arityOf(name);
422
+ const points = arity - 1;
423
+ const exprEnd = operands.length > points
424
+ ? operands[operands.length - points].i
425
+ : operands[0]?.i ?? query.length;
426
+ const cleaned = this.cleanExprText(latin1(query.subarray(term.j, exprEnd)));
427
+ if (cleaned.length === 0)
428
+ return null;
429
+ const args = [UTF8.encode(cleaned)];
430
+ for (const o of operands.slice(-points)) {
431
+ args.push(o.value ?? query.subarray(o.i, o.j));
432
+ }
433
+ if (args.length !== arity)
434
+ return null; // under-supplied → decline
435
+ const bytes = this.alu.applyBytesTyped(name, args, (idx) => idx === 0);
436
+ if (bytes === null)
437
+ return null;
438
+ return { i: term.i, j: operands[operands.length - 1].j, bytes };
439
+ }
440
+ /** Apply any other op to the OPERAND STREAM after the operator: the numeric
441
+ * operands and symbol terms that follow it, merged nearest-first, each
442
+ * within the host's reach of the token before it — so "sqrt 144",
443
+ * "gcd 12 18", and "opposite large" are one rule, and the NEAREST token is
444
+ * the operand ("opposite large 5" inverts "large", not the 5).
445
+ *
446
+ * Two structural refinements make this read like notation rather than a
447
+ * special case:
448
+ *
449
+ * • WORD-INFIX — an under-supplied operator borrows the numeric operand
450
+ * immediately BEFORE it (within reach), so "7 minus 2" applies
451
+ * subtract(7, 2) exactly as "7 - 2" would: a synonym is notation too.
452
+ * • GROUNDED-ONLY SYMBOLS — when every operand is a symbol, a result that
453
+ * merely echoes an operand means resonance grounded nothing (an inverse
454
+ * with no learnt opposition), and the rule stays silent rather than
455
+ * invent meaning. Numeric identities ("max 3 7" → "7") are real
456
+ * results and pass.
457
+ *
458
+ * A NULLARY op never fires from a bare term: a computation must consume
459
+ * something, or any prose word that happens to name a constant would be
460
+ * rewritten. Symbol operands get their resonance (the opposite each may
461
+ * need) pre-resolved in one prefetch. */
462
+ async applyToStream(query, name, term, tokens) {
463
+ const arity = this.alu.arityOf(name);
464
+ if (arity === 0)
465
+ return null; // a constant consumes nothing → not a rule
466
+ const picked = [];
467
+ let from = term.j;
468
+ for (const tok of tokens) {
469
+ if (tok.i < term.j || tok.kind === "operator")
470
+ continue;
471
+ if (picked.length === arity)
472
+ break;
473
+ if (tok.i - from > this.host.reach)
474
+ break; // next token too far
475
+ picked.push(tok);
476
+ from = tok.j;
477
+ }
478
+ // WORD-INFIX: borrow the numeric operand just before the operator.
479
+ let start = term.i;
480
+ if (picked.length === arity - 1) {
481
+ let before;
482
+ for (const t of tokens) {
483
+ if (t.j > term.i)
484
+ break;
485
+ if (t.kind === "operand")
486
+ before = t;
487
+ }
488
+ if (before && term.i - before.j <= this.host.reach) {
489
+ picked.unshift(before);
490
+ start = before.i;
491
+ }
492
+ }
493
+ if (picked.length !== arity)
494
+ return null; // under-supplied → decline
495
+ const args = picked.map((t) => t.value ?? query.subarray(t.i, t.j));
496
+ const symbols = picked.flatMap((t, k) => t.kind === "term" ? [args[k]] : []);
497
+ const resonance = symbols.length > 0
498
+ ? await prefetchOpposites(this.resonance, symbols)
499
+ : NO_RESONANCE;
500
+ const bytes = this.alu.applyBytes(name, args, resonance);
501
+ if (bytes === null)
502
+ return null;
503
+ if (symbols.length === args.length && args.some((a) => bytesEqual(bytes, a))) {
504
+ return null; // an all-symbol result echoing an operand grounded nothing
505
+ }
506
+ return { i: start, j: picked[picked.length - 1].j, bytes };
507
+ }
508
+ /** Strip non-math filler tokens from a raw expression string — keep numbers,
509
+ * operators, parens, names the GRAMMAR resolves (unary functions,
510
+ * registered constants), and single-RUNE identifiers. The rune rule is the
511
+ * mirror of {@link "./alu.js".Alu.conceptAnchors}' compound rule: a compound
512
+ * name carries distributional meaning (it is either a resolvable operation
513
+ * or filler — "of", "at", "the"), while a bare atom carries none and can
514
+ * only be the expression's free variable. Dropping the filler leaves the
515
+ * evaluator clean notation. */
516
+ cleanExprText(raw) {
517
+ const g = this.alu.grammar;
518
+ const toks = g.tokenize(raw);
519
+ if (!toks)
520
+ return ""; // not a tokenizable expression — stay silent
521
+ const keep = [];
522
+ for (const t of toks) {
523
+ if (t.kind !== "name" ||
524
+ g.isFunction(t.text) || g.isConstant(t.text) || t.text.length === 1) {
525
+ keep.push(t.text);
526
+ }
527
+ }
528
+ return keep.join("");
529
+ }
530
+ }
531
+ const UTF8 = new TextEncoder();
532
+ /** Sentinel closing the lex walk (never emitted). */
533
+ const END = { i: Infinity, j: Infinity, kind: "operator" };
534
+ /** Collapse each EVALUATED arithmetic run into one virtual OPERAND token
535
+ * carrying the run's result — the composed stream named operations consume,
536
+ * so an infix sub-expression is a single finished operand ("sum 1*3 4"
537
+ * applies add(3, 4)) exactly as the grammar nests expressions. A run that
538
+ * did not evaluate keeps its original tokens. One ascending merge walk. */
539
+ function compose(tokens, results) {
540
+ if (results.length === 0)
541
+ return tokens;
542
+ const sorted = [...results].sort((a, b) => a.i - b.i);
543
+ const out = [];
544
+ let k = 0;
545
+ for (const r of sorted) {
546
+ while (k < tokens.length && tokens[k].i < r.i)
547
+ out.push(tokens[k++]);
548
+ const inside = [];
549
+ while (k < tokens.length && tokens[k].j <= r.j)
550
+ inside.push(tokens[k++]);
551
+ if (r.bytes !== null) {
552
+ out.push({ i: r.i, j: r.j, kind: "operand", value: r.bytes });
553
+ }
554
+ else
555
+ out.push(...inside);
556
+ }
557
+ out.push(...tokens.slice(k));
558
+ return out;
559
+ }
560
+ /** The AUTHORITY law: a span strictly contained in a larger computed span is
561
+ * that computation's material — the outer computation consumed it — so only
562
+ * the outermost readings survive. Overlapping-but-not-nested spans are
563
+ * rival readings the host's search may still weigh against each other. */
564
+ function authoritative(spans) {
565
+ return spans.filter((s) => !spans.some((o) => o !== s && o.i <= s.i && s.j <= o.j && o.j - o.i > s.j - s.i));
566
+ }
567
+ /** Keep the first occurrence of each (span, bytes) result. */
568
+ function dedup(spans) {
569
+ const seen = new Set();
570
+ return spans.filter((s) => {
571
+ const key = s.i + "," + s.j + "," + latin1(s.bytes);
572
+ if (seen.has(key))
573
+ return false;
574
+ seen.add(key);
575
+ return true;
576
+ });
577
+ }
@@ -0,0 +1,55 @@
1
+ import type { ResonanceSync } from "./operation.js";
2
+ /** A labelled concept form: the canonical operation name and one of its
3
+ * surface forms, as bytes. The host resonates opaque spans against these to
4
+ * answer "which operation does this span MEAN?" (see parser.ts AluHost). */
5
+ export interface ConceptAnchor {
6
+ name: string;
7
+ form: Uint8Array;
8
+ }
9
+ /** The async resonance capability the host provides. Both methods may return
10
+ * null when resonance finds nothing above the host's own threshold — ALU then
11
+ * declines to guess (operation unrecognised, inverse left unchanged). This
12
+ * keeps synthesis graph-evidenced: ALU never invents meaning resonance did not
13
+ * supply. */
14
+ export interface AluResonance {
15
+ /** The canonical operation a span's MEANING names, found by resonance over the
16
+ * operation concepts — the GENERIC, modality-agnostic recognition path. This
17
+ * is how an operation that is NOT literally spelled (no "∫" for an integral,
18
+ * no "+" for a sum drawn or spoken) is still recognised: the span's gist
19
+ * resonates with the operation's concept. Returns the canonical op name, or
20
+ * null when nothing resonates above threshold. */
21
+ recogniseOp(bytes: Uint8Array): Promise<string | null>;
22
+ /** The resonant opposite of a symbol's bytes (its antonym / inverse in the
23
+ * resonance space, any modality), or null. The host finds it by halo
24
+ * resonance over the negated concept. */
25
+ opposite(bytes: Uint8Array): Promise<Uint8Array | null>;
26
+ }
27
+ /** A AluResonance that knows nothing — the default when the host wires none in,
28
+ * so the kernel runs fully decoupled (operations resolve by literal forms only,
29
+ * and a symbol inverse is left unchanged). */
30
+ export declare const NO_ALU_RESONANCE: AluResonance;
31
+ /** Pre-resolve the resonant opposite of each symbol in `symbols`, awaiting the
32
+ * host's async resonance once per distinct span, and return a SYNCHRONOUS
33
+ * snapshot the op callbacks read during the search. Keyed by the latin1 view
34
+ * of the bytes (a lossless, stable string key — the same device the search's
35
+ * chart uses). This is the async→sync bridge for the polymorphic inverse,
36
+ * mirroring how a concept hop's target is pre-resolved and read synchronously. */
37
+ export declare function prefetchOpposites(resonance: AluResonance, symbols: Iterable<Uint8Array>): Promise<ResonanceSync>;
38
+ /** Pre-resolve BOTH capabilities a computation may need synchronously — the
39
+ * resonant opposite of a symbol (for the polymorphic inverse) AND the operation
40
+ * a symbol's MEANING names (for a higher-order nd op's function argument) — over
41
+ * one set of candidate spans, and return a single {@link ResonanceSync}. Each
42
+ * distinct span is awaited once per capability. This is the unified async→sync
43
+ * bridge the host uses for an nd computation, where the same spans may serve as
44
+ * inverse operands and as a reduce/map/filter operator. Either lookup yields
45
+ * null for a span that resonates with nothing, so callbacks decline rather than
46
+ * guess. */
47
+ export declare function prefetchResonance(resonance: AluResonance, spans: Iterable<Uint8Array>): Promise<ResonanceSync>;
48
+ /** Pre-resolve, for each candidate span, the operation its MEANING names —
49
+ * awaiting the host's async gist resonance once per distinct span — and return
50
+ * a synchronous map keyed by the span's latin1 bytes → canonical op name. This
51
+ * is the async→sync bridge for the GENERIC operation-recognition path: a span
52
+ * the literal scan could not classify (no operator symbol) but whose gist
53
+ * resonates with an operation's concept. Spans that resonate with nothing are
54
+ * omitted, so the caller treats a miss as "not an operation". */
55
+ export declare function prefetchRecognisedOps(resonance: AluResonance, spans: Iterable<Uint8Array>): Promise<Map<string, string>>;