@hviana/sema 0.1.9 → 0.2.1

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 (131) 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 +927 -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 +598 -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
  130. package/src/mind/graph-search.ts +128 -46
  131. package/src/mind/mind.ts +37 -0
@@ -0,0 +1,273 @@
1
+ import { Vec } from "../vec.js";
2
+ import { Sema, Space } from "../sema.js";
3
+ import { Alphabet } from "../alphabet.js";
4
+ import { type FoldPyramid, Grid } from "../geometry.js";
5
+ import { BoundedMap, type Store } from "../store.js";
6
+ import { type MindConfig } from "../config.js";
7
+ import { type Canon } from "../canon.js";
8
+ import { GraphSearch, type Leaf, type Site } from "./graph-search.js";
9
+ import type { ComputedSpan, ExtensionHost } from "../extension.js";
10
+ export type { ComputedSpan, ExtensionHost };
11
+ import { type InspectRationale, Rationale } from "./rationale.js";
12
+ export type { InspectRationale, RationaleItem, RationaleStep, } from "./rationale.js";
13
+ export type Input = string | Uint8Array | Grid | Grid[];
14
+ export interface Response {
15
+ v: Vec | null;
16
+ bytes: Uint8Array;
17
+ /** How the answer was grounded (see {@link Provenance}). `"recall-echo"`
18
+ * marks the last-resort fallback that returned the nearest stored form's
19
+ * own bytes verbatim — an echo, NOT a grounded fact. Absent when there is
20
+ * no answer. */
21
+ provenance?: import("./pipeline.js").Provenance;
22
+ }
23
+ /** Serializable state of a conversation — can be saved and restored across
24
+ * sessions. The Mind never interprets the bytes; it only tracks their
25
+ * cumulative lengths so the caller can reconstruct turn boundaries later
26
+ * without inspecting content. */
27
+ export interface ConversationState {
28
+ /** The accumulated context bytes — raw concatenation of every turn's
29
+ * bytes in order. No separator is inserted; the boundary offsets
30
+ * ({@link boundaries}) tell the caller where each turn ends. */
31
+ context: Uint8Array;
32
+ /** Cumulative byte length after each completed turn. Sorted, strictly
33
+ * increasing, each {@code < context.length}. The first turn's length
34
+ * is `boundaries[0]`; the second turn starts at that offset, and so
35
+ * on. Empty for a single-turn or new conversation. */
36
+ boundaries: number[];
37
+ }
38
+ /** An active conversation handle. Opaque — interact through the Mind's
39
+ * conversation methods ({@link Mind.beginConversation},
40
+ * {@link Mind.respondTurn}, {@link Mind.endConversation}). */
41
+ export interface Conversation {
42
+ readonly id: number;
43
+ }
44
+ import type { AttentionRead, MindContext, Recognition } from "./types.js";
45
+ export interface MindOptions {
46
+ seed?: number;
47
+ recallQueryK?: number;
48
+ haloQueryK?: number;
49
+ normalizeEpsilon?: number;
50
+ cosineEpsilon?: number;
51
+ geometry?: Partial<import("../config.js").GeometryConfig>;
52
+ alphabet?: Partial<import("../config.js").AlphabetConfig>;
53
+ storeConfig?: Partial<import("../config.js").StoreConfig>;
54
+ store?: Store;
55
+ /** Additional grounding mechanisms (appended after the built-in defaults). */
56
+ mechanisms?: import("./pipeline-mechanism.js").PipelineMechanism[];
57
+ /** Factories that receive the {@link ExtensionHost} and return mechanisms. */
58
+ mechanismFactories?: ((host: import("../extension.js").ExtensionHost) => import("./pipeline-mechanism.js").PipelineMechanism)[];
59
+ /** Content canonicalizer applied to EVERY response (any modality) for
60
+ * equivalence-class resolution — see src/canon.ts. Text entry points
61
+ * ({@link Mind.respondText}, {@link Mind.respondTurnText}) inject the
62
+ * Unicode text canonicalizer automatically when this is unset; pass
63
+ * `false` to disable canonical resolution everywhere. */
64
+ canon?: Canon | false;
65
+ }
66
+ export declare class Mind implements MindContext {
67
+ readonly space: Space;
68
+ readonly alphabet: Alphabet;
69
+ readonly store: Store;
70
+ readonly cfg: MindConfig;
71
+ /** The lightest-derivation engine over the Sema graph. */
72
+ readonly search: GraphSearch;
73
+ /** The grounding mechanisms iterated by {@link think}. */
74
+ readonly mechanisms: import("./pipeline-mechanism.js").PipelineMechanism[];
75
+ /** The live rationale tracer for the inference currently in flight, or null. */
76
+ trace: Rationale | null;
77
+ /** The content canonicalizer for the response in flight — see
78
+ * {@link MindContext.canon}. Injected per response by the modality entry
79
+ * point; null when the response carries no equivalence. */
80
+ canon: Canon | null;
81
+ /** Per-response canonical-resolution memo — see {@link MindContext.canonMemo}. */
82
+ canonMemo: Map<string, number | null> | null;
83
+ /** The Mind-level canon option: a canonicalizer to use for EVERY response,
84
+ * `false` to disable canonical resolution, or null to let each entry
85
+ * point decide (text entry points inject {@link textCanon}). */
86
+ private _canonOpt;
87
+ /** Memo of the consensus climb — content-keyed. See {@link MindContext.climbMemo}. */
88
+ climbMemo: Map<string, Map<string, AttentionRead>> | null;
89
+ /** Memo of recognise() — content-keyed. See {@link MindContext.recogniseMemo}. */
90
+ recogniseMemo: Map<string, Recognition> | null;
91
+ /** Memo of perceive() — content-keyed. See {@link MindContext.perceiveMemo}. */
92
+ perceiveMemo: Map<string, import("../sema.js").Sema> | null;
93
+ /** Subtree-resolution cache. See {@link MindContext._resolvedSubtrees}. */
94
+ _resolvedSubtrees: WeakMap<import("../sema.js").Sema, {
95
+ id: number;
96
+ len: number;
97
+ }> | null;
98
+ /** The perceived gist of the query currently being answered. Set by `think`
99
+ * before the graph search runs; `chooseNext` consults it as a gate (a null
100
+ * guide means no query is in flight, so structural walkers keep plain
101
+ * first-edge behaviour) and the reverse projection uses it for
102
+ * reverse-recall disambiguation via `chooseAmong`. */
103
+ _edgeGuide: Vec | null;
104
+ /** Per-response memo of {@link chooseNext} picks — ensures every mechanism
105
+ * of a single response follows the SAME continuation for each ambiguous
106
+ * context node. */
107
+ _edgeChoice: Map<number, number>;
108
+ /** Previous deposit's seen node ids for incremental change detection. */
109
+ _prevSeen: Set<number> | null;
110
+ /** Session cache of node-id → perceived gist for candidate scoring — see
111
+ * {@link MindContext._gistCache}. 32 MB ≈ 8K gists at D=1024; hub
112
+ * candidate sets (√N at most) fit comfortably and recur across queries. */
113
+ _gistCache: BoundedMap<number, Vec>;
114
+ _depositTrees: BoundedMap<string, FoldPyramid>;
115
+ _depositLens: Set<number>;
116
+ _internIds: WeakMap<Sema, number>;
117
+ private _nextConvId;
118
+ private _conversations;
119
+ /** Canonical node id of a byte span. Required by GraphSearchHost & MindContext. */
120
+ resolve(bytes: Uint8Array): number | null;
121
+ recogniseSpan(bytes: Uint8Array): {
122
+ sites: ReadonlyArray<Site>;
123
+ leaves: ReadonlyArray<Leaf>;
124
+ splits: ReadonlySet<number>;
125
+ };
126
+ /** Disambiguate among multiple learnt continuations of the same context node.
127
+ * Required by {@link GraphSearchHost} — the graph search calls this through the
128
+ * host interface when a recognised form has more than one outgoing edge.
129
+ * Delegates to the standalone {@link chooseNext} which picks the candidate
130
+ * with the most distributional evidence (highest `prevOf` count — the
131
+ * structural manifestation of its halo). When evidence is equal the
132
+ * first-inserted edge wins. */
133
+ chooseNext(node: number): number | undefined;
134
+ constructor(opts?: MindOptions);
135
+ constructor(cfg: MindConfig, store: Store, _fromStore: true);
136
+ /** Exposed for tests: the consensus climb over query sub-regions. */
137
+ climbAttention(query: Uint8Array, k: number, mode?: import("./types.js").DFMode): Promise<import("./types.js").Attention[]>;
138
+ /** Exposed for tests: climb the structural DAG from a node to its
139
+ * edge-bearing ancestor contexts. */
140
+ edgeAncestors(id: number, contextCount: number): import("./types.js").AncestorReach;
141
+ /** Exposed for tests: find the natural break point in a sorted vote list. */
142
+ naturalBreak(votes: number[]): number;
143
+ /** Perceive input into a content-defined tree. Deterministic — identical
144
+ * bytes always produce an identical tree. Public for ingest-cache. */
145
+ perceive(input: Input, leafAt?: (i: number) => number | null, lookup?: (ids: number[]) => number | null): Sema;
146
+ /** Open one response's transient state — the tracer and the per-response
147
+ * memos. Paired with {@link endResponse}; the ONE place this state is
148
+ * created, so adding a memo cannot forget its reset. */
149
+ private beginResponse;
150
+ /** The canonicalizer a response should carry: the Mind-level option when
151
+ * set (or none when explicitly disabled), else the entry point's own
152
+ * default — text entry points pass {@link textCanon}, binary ones null. */
153
+ private _canonFor;
154
+ /** Close one response's transient state — every per-response field, incl.
155
+ * the edge guide/choices `think` sets mid-flight. */
156
+ private endResponse;
157
+ /** Shared response core — the one path from bytes to voiced answer.
158
+ * `respond` calls this directly; `respondTurn` has its own path
159
+ * with conversation-persistent memos and incremental perception. */
160
+ private _respondImpl;
161
+ respond(input: Input, inspectRationale?: InspectRationale): Promise<Response>;
162
+ /** Text view of {@link respond}. NUL bytes (0x00) are stripped before
163
+ * decoding — they are structural padding in text answers. LOSSY for a
164
+ * binary answer that legitimately contains NULs: use {@link respond} and
165
+ * read `bytes` directly for binary/grid modalities.
166
+ *
167
+ * Injects the TEXT canonicalizer (src/canon.ts) so resolution treats
168
+ * every character variation of the same text — case, width, whitespace —
169
+ * as one form, provided the store's canon index is built
170
+ * ({@link buildCanonIndex}). */
171
+ respondText(input: string, inspectRationale?: InspectRationale): Promise<string>;
172
+ /** Begin a new conversation, optionally restoring from a previously-saved
173
+ * {@link ConversationState}. The returned handle is required for
174
+ * {@link respondTurn} and {@link endConversation}.
175
+ *
176
+ * Conversations are independent — a Mind can manage several concurrently.
177
+ * Each tracks the fold pyramid (accumulated internal processing) and
178
+ * turn-boundary offsets; the geometry never inspects content to guess
179
+ * where one turn ends and the next begins. */
180
+ beginConversation(state?: ConversationState): Conversation;
181
+ /** End a conversation, releasing its internal resources (accumulated
182
+ * context, boundary offsets, and the fold-pyramid cache). Idempotent. */
183
+ endConversation(conv: Conversation): void;
184
+ /** The current serialisable state of an active conversation. Save this
185
+ * to resume the conversation later via {@link beginConversation}. */
186
+ conversationState(conv: Conversation): ConversationState | null;
187
+ /** Append a turn to a conversation's accumulated context WITHOUT
188
+ * responding — raw byte append plus a boundary offset, never a
189
+ * separator; the fold pyramid advances by O(turn).
190
+ *
191
+ * This is the primitive for turns the Mind should hear but not answer:
192
+ * replaying a transcript, feeding the OTHER speaker's line in a
193
+ * prediction harness, or restoring context piecewise. {@link
194
+ * respondTurn} = addTurn + think + its own reply appended the same way. */
195
+ addTurn(conv: Conversation, turn: Input): ConversationState;
196
+ /** Grow a conversation's accumulated context by one turn's bytes — raw
197
+ * append plus a boundary offset, pyramid advanced by O(turn), the grown
198
+ * context's tree seeded into the conversation's perceive memo. The ONE
199
+ * place a context grows ({@link addTurn} and {@link respondTurn} both
200
+ * come through here), so the append semantics cannot drift. */
201
+ private _growContext;
202
+ /** Process one turn of a conversation.
203
+ *
204
+ * `turn` is the raw input for the latest turn — its bytes are appended
205
+ * to the accumulated context directly (raw concatenation). The Mind
206
+ * tracks the byte offset where each turn ends; no separator is ever
207
+ * inserted or inspected.
208
+ *
209
+ * Returns the response AND the updated {@link ConversationState} so the
210
+ * caller can persist it. The conversation handle's internal state is
211
+ * updated in place — the returned state is a snapshot for storage.
212
+ *
213
+ * SINGLE FLIGHT: at most one respondTurn may be in flight per Mind. The
214
+ * conversation's memo caches are swapped into the Mind-level per-response
215
+ * pointers for the duration of the turn, so a concurrently-running
216
+ * respond()/respondTurn() on the SAME Mind would interleave state.
217
+ * Different Minds (or sequential awaits, as in every test) are safe. */
218
+ respondTurn(conv: Conversation, turn: Input, inspectRationale?: InspectRationale): Promise<{
219
+ response: Response;
220
+ state: ConversationState;
221
+ }>;
222
+ /** Text view of {@link respondTurn}. See {@link respondText} for the
223
+ * NUL-stripping caveat. For binary or grid turns use {@link respondTurn}
224
+ * directly — this is a text-only convenience, like {@link respondText}. */
225
+ respondTurnText(conv: Conversation, turn: string, inspectRationale?: InspectRationale): Promise<{
226
+ response: string;
227
+ state: ConversationState;
228
+ }>;
229
+ embedding(input: Input): Promise<Vec | null>;
230
+ /** Kinship note: the vector arm below is a miniature of recall's tier 3
231
+ * (resonate → reach gate → read out the nearest form's bytes) — the
232
+ * read-out direction of the same operation, without recall's grounding
233
+ * ladder. If either side's acceptance rule changes, revisit the other. */
234
+ express(idOrV: number | Vec): Promise<Uint8Array>;
235
+ ingest(input: Input | (Input | [Input, Input])[], second?: Input): Promise<(Sema & {
236
+ id: number;
237
+ }) | undefined>;
238
+ private extensionHost;
239
+ private groundedContinuation;
240
+ /** Re-index structurally-important nodes whose gists were evicted from the
241
+ * pending cache before they reached the content index. See {@link
242
+ * Store.repairContentIndex} for the contract; this method wires the
243
+ * Mind's perception into the store's repair walk.
244
+ *
245
+ * Run this after training or at checkpoints to restore recall reach for
246
+ * nodes that bridge experiences but were never indexed. A pure interior
247
+ * node (no edges, no halo) is deliberately skipped — it is scaffolding,
248
+ * not an experience root or bridge, and regenerating its gist would waste
249
+ * I/O and index space for no recall benefit.
250
+ *
251
+ * @param minParents only repair nodes with ≥ this many structural parents
252
+ * (default 2 — structural bridges)
253
+ * @returns number of nodes added to the content index */
254
+ repairContentIndex(minParents?: number): Promise<number>;
255
+ /** Build (or incrementally refresh) the store's canonical-form index: for
256
+ * every content-bearing node, record the hash of its CANONICAL key so
257
+ * resolution can find stored forms across surface variation (case, width,
258
+ * whitespace — whatever `canon` equates; see src/canon.ts).
259
+ *
260
+ * Incremental and idempotent: the last indexed node id is remembered in
261
+ * store meta (`canon.upto`), so a refresh after further training scans
262
+ * only the new rows. Run once after training, and again after ingests —
263
+ * the same operational shape as {@link repairContentIndex}.
264
+ *
265
+ * @param canon the canonicalizer to index under — MUST be the same one
266
+ * queries will carry (text queries carry {@link textCanon}
267
+ * unless the Mind was constructed with its own)
268
+ * @returns number of index rows added */
269
+ buildCanonIndex(canon?: Canon): Promise<number>;
270
+ save(): Promise<Uint8Array>;
271
+ static load(snapshot: Uint8Array, store: Store): Promise<Mind>;
272
+ static loadFromStore(store: Store): Promise<Mind>;
273
+ }