@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,562 @@
1
+ // mind/mind.ts — perceive, deposit, recall, think, express.
2
+ //
3
+ // Memory is a content-addressed node graph (see store.ts). Learning is
4
+ // DEPOSITION: perceive a stream into a tree and intern every node, so equal —
5
+ // and, by resonance, similar — subtrees collapse to one shared node. A fact is
6
+ // an EDGE between node ids; recall traverses edges; thinking completes the
7
+ // query's OWN tree, node by node, to a fixed point. No whole, no weights.
8
+ //
9
+ // Architecture: 4 primitives × 2 patterns = all inference.
10
+ // Implementation split across src/mind/*.ts — this file assembles the Mind class.
11
+ import { makeKeyring, rng, setVecConfig } from "../vec.js";
12
+ import { Alphabet } from "../alphabet.js";
13
+ import { bytesToTreePyramid, reachThreshold, } from "../geometry.js";
14
+ import { BoundedMap } from "../store.js";
15
+ import { SQliteStore } from "../store-sqlite.js";
16
+ import { resolveConfig } from "../config.js";
17
+ import { canonHash, textCanon } from "../canon.js";
18
+ import { bytesEqual, concat2 } from "../bytes.js";
19
+ import { GraphSearch, } from "./graph-search.js";
20
+ import { Alu } from "../alu/src/index.js";
21
+ import { decodeText, Rationale, } from "./rationale.js";
22
+ import { gistOf, inputBytes, latin1Key, perceive as perceiveImpl, resolve as resolveImpl, } from "./primitives.js";
23
+ import { chooseNext, edgeAncestors as edgeAncestorsFn } from "./traverse.js";
24
+ import { follow } from "./match.js";
25
+ import { recognise, segment } from "./recognition.js";
26
+ import { meaningOf } from "./resonance.js";
27
+ import { climbAttention as climbAttentionFn, naturalBreak as naturalBreakFn, } from "./attention.js";
28
+ import { aluToMechanism, defaultMechanisms, think } from "./pipeline.js";
29
+ import { articulate } from "./articulation.js";
30
+ import { ingest } from "./learning.js";
31
+ import { rItem } from "./trace.js";
32
+ // ═══════════════════════════════════════════════════════════════════════════
33
+ // THE MIND
34
+ // ═══════════════════════════════════════════════════════════════════════════
35
+ export class Mind {
36
+ space;
37
+ alphabet;
38
+ store;
39
+ cfg;
40
+ /** The lightest-derivation engine over the Sema graph. */
41
+ search;
42
+ /** The grounding mechanisms iterated by {@link think}. */
43
+ mechanisms = [];
44
+ /** The live rationale tracer for the inference currently in flight, or null. */
45
+ trace = null;
46
+ /** The content canonicalizer for the response in flight — see
47
+ * {@link MindContext.canon}. Injected per response by the modality entry
48
+ * point; null when the response carries no equivalence. */
49
+ canon = null;
50
+ /** Per-response canonical-resolution memo — see {@link MindContext.canonMemo}. */
51
+ canonMemo = null;
52
+ /** The Mind-level canon option: a canonicalizer to use for EVERY response,
53
+ * `false` to disable canonical resolution, or null to let each entry
54
+ * point decide (text entry points inject {@link textCanon}). */
55
+ _canonOpt = null;
56
+ /** Memo of the consensus climb — content-keyed. See {@link MindContext.climbMemo}. */
57
+ climbMemo = null;
58
+ /** Memo of recognise() — content-keyed. See {@link MindContext.recogniseMemo}. */
59
+ recogniseMemo = null;
60
+ /** Memo of perceive() — content-keyed. See {@link MindContext.perceiveMemo}. */
61
+ perceiveMemo = null;
62
+ /** Subtree-resolution cache. See {@link MindContext._resolvedSubtrees}. */
63
+ _resolvedSubtrees = null;
64
+ /** The perceived gist of the query currently being answered. Set by `think`
65
+ * before the graph search runs; `chooseNext` consults it as a gate (a null
66
+ * guide means no query is in flight, so structural walkers keep plain
67
+ * first-edge behaviour) and the reverse projection uses it for
68
+ * reverse-recall disambiguation via `chooseAmong`. */
69
+ _edgeGuide = null;
70
+ /** Per-response memo of {@link chooseNext} picks — ensures every mechanism
71
+ * of a single response follows the SAME continuation for each ambiguous
72
+ * context node. */
73
+ _edgeChoice = new Map();
74
+ /** Previous deposit's seen node ids for incremental change detection. */
75
+ _prevSeen = null;
76
+ /** Session cache of node-id → perceived gist for candidate scoring — see
77
+ * {@link MindContext._gistCache}. 32 MB ≈ 8K gists at D=1024; hub
78
+ * candidate sets (√N at most) fit comfortably and recur across queries. */
79
+ _gistCache = new BoundedMap(32_000_000, (v) => v.byteLength);
80
+ // Deposit-path fold-pyramid cache (see MindContext) — ENTRY-count
81
+ // bounded: a pyramid costs ~KB per content byte (one D-float gist per
82
+ // interior node), and only the few live conversation chains need to stay
83
+ // warm, so 8 entries is the honest budget.
84
+ _depositTrees = new BoundedMap(8);
85
+ _depositLens = new Set();
86
+ _internIds = new WeakMap();
87
+ // ── Conversation state ──────────────────────────────────────────────────
88
+ _nextConvId = 1;
89
+ _conversations = new Map();
90
+ // ── GraphSearchHost implementation ─────────────────────────────────────
91
+ /** Canonical node id of a byte span. Required by GraphSearchHost & MindContext. */
92
+ resolve(bytes) {
93
+ return resolveImpl(this, bytes);
94
+ }
95
+ // recogniseSpan wraps recognise
96
+ recogniseSpan(bytes) {
97
+ const r = recognise(this, bytes);
98
+ return { sites: r.sites, leaves: r.leaves, splits: r.splits };
99
+ }
100
+ /** Disambiguate among multiple learnt continuations of the same context node.
101
+ * Required by {@link GraphSearchHost} — the graph search calls this through the
102
+ * host interface when a recognised form has more than one outgoing edge.
103
+ * Delegates to the standalone {@link chooseNext} which picks the candidate
104
+ * with the most distributional evidence (highest `prevOf` count — the
105
+ * structural manifestation of its halo). When evidence is equal the
106
+ * first-inserted edge wins. */
107
+ chooseNext(node) {
108
+ return chooseNext(this, node, this._edgeGuide);
109
+ }
110
+ constructor(optsOrCfg, storeArg, _fromStore) {
111
+ let userMechanisms = [];
112
+ let userFactories = [];
113
+ if (_fromStore !== undefined) {
114
+ this.cfg = resolveConfig(optsOrCfg);
115
+ this.store = storeArg;
116
+ }
117
+ else {
118
+ const { store: optsStore, mechanisms: userMechs, mechanismFactories: userFacts, canon: optsCanon, ...rest } = (optsOrCfg ?? {});
119
+ this._canonOpt = optsCanon ?? null;
120
+ this.cfg = resolveConfig(rest);
121
+ this.store = optsStore ?? new SQliteStore({
122
+ maxGroup: this.cfg.geometry.maxGroup,
123
+ });
124
+ userMechanisms = userMechs ?? [];
125
+ userFactories = userFacts ?? [];
126
+ }
127
+ setVecConfig({
128
+ normalizeEpsilon: this.cfg.normalizeEpsilon,
129
+ cosineEpsilon: this.cfg.cosineEpsilon,
130
+ });
131
+ const seedRand = rng((this.cfg.seed ^ 0x9e3779) >>> 0);
132
+ const seats = makeKeyring(this.store.D, Math.max(8, this.cfg.geometry.maxGroup), seedRand);
133
+ this.space = {
134
+ D: this.store.D,
135
+ seats,
136
+ rand: rng((this.cfg.seed ^ 0x51f15e) >>> 0),
137
+ maxGroup: this.cfg.geometry.maxGroup,
138
+ };
139
+ this.alphabet = new Alphabet(this.cfg.seed, this.store.D, this.cfg.alphabet);
140
+ this.search = new GraphSearch(this.store, this.space.maxGroup, this);
141
+ // Build the mechanism list: default grounding + ALU + user mechanisms.
142
+ for (const m of defaultMechanisms)
143
+ this.mechanisms.push(m);
144
+ const host = this.extensionHost();
145
+ if (this.cfg.alu.enabled) {
146
+ const alu = new Alu({
147
+ tol: this.cfg.alu.tol,
148
+ maxIter: this.cfg.alu.maxIter,
149
+ precision: this.cfg.alu.precision,
150
+ }, host);
151
+ this.mechanisms.push(aluToMechanism(alu));
152
+ }
153
+ for (const m of userMechanisms)
154
+ this.mechanisms.push(m);
155
+ for (const f of userFactories)
156
+ this.mechanisms.push(f(host));
157
+ }
158
+ // ── Public API ───────────────────────────────────────────────────────────
159
+ /** Exposed for tests: the consensus climb over query sub-regions. */
160
+ climbAttention(query, k, mode = "inverse") {
161
+ return climbAttentionFn(this, query, k, mode);
162
+ }
163
+ /** Exposed for tests: climb the structural DAG from a node to its
164
+ * edge-bearing ancestor contexts. */
165
+ edgeAncestors(id, contextCount) {
166
+ return edgeAncestorsFn(this, id, contextCount);
167
+ }
168
+ /** Exposed for tests: find the natural break point in a sorted vote list. */
169
+ naturalBreak(votes) {
170
+ return naturalBreakFn(votes);
171
+ }
172
+ // ── respond ───────────────────────────────────────────────────────────
173
+ /** Perceive input into a content-defined tree. Deterministic — identical
174
+ * bytes always produce an identical tree. Public for ingest-cache. */
175
+ perceive(input, leafAt, lookup) {
176
+ return perceiveImpl(this, input, leafAt, lookup);
177
+ }
178
+ /** Open one response's transient state — the tracer and the per-response
179
+ * memos. Paired with {@link endResponse}; the ONE place this state is
180
+ * created, so adding a memo cannot forget its reset. */
181
+ beginResponse(inspectRationale, canon) {
182
+ this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
183
+ this.climbMemo = new Map();
184
+ this.recogniseMemo = new Map();
185
+ this.perceiveMemo = new Map();
186
+ this.canon = canon ?? null;
187
+ this.canonMemo = canon ? new Map() : null;
188
+ }
189
+ /** The canonicalizer a response should carry: the Mind-level option when
190
+ * set (or none when explicitly disabled), else the entry point's own
191
+ * default — text entry points pass {@link textCanon}, binary ones null. */
192
+ _canonFor(entryDefault) {
193
+ if (this._canonOpt === false)
194
+ return null;
195
+ return this._canonOpt ?? entryDefault;
196
+ }
197
+ /** Close one response's transient state — every per-response field, incl.
198
+ * the edge guide/choices `think` sets mid-flight. */
199
+ endResponse() {
200
+ this.trace = null;
201
+ this.climbMemo = null;
202
+ this.recogniseMemo = null;
203
+ this.perceiveMemo = null;
204
+ this.canon = null;
205
+ this.canonMemo = null;
206
+ this._edgeGuide = null;
207
+ this._edgeChoice.clear();
208
+ }
209
+ /** Shared response core — the one path from bytes to voiced answer.
210
+ * `respond` calls this directly; `respondTurn` has its own path
211
+ * with conversation-persistent memos and incremental perception. */
212
+ async _respondImpl(queryBytes, inspectRationale, traceLabel = "respond", canon = null) {
213
+ this.beginResponse(inspectRationale, canon);
214
+ try {
215
+ const top = this.trace?.enter(traceLabel, [
216
+ rItem(queryBytes, "query"),
217
+ ]);
218
+ const thought = await think(this, queryBytes, this.mechanisms);
219
+ if (thought === null) {
220
+ top?.done([], "nothing to perceive or an empty store — no answer");
221
+ return { v: null, bytes: new Uint8Array(0) };
222
+ }
223
+ const voiced = await articulate(this, thought.bytes, queryBytes);
224
+ top?.done([rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined)], "the answer, re-voiced in the asker's words");
225
+ return {
226
+ v: gistOf(this, voiced),
227
+ bytes: voiced,
228
+ provenance: thought.provenance,
229
+ };
230
+ }
231
+ finally {
232
+ this.endResponse();
233
+ }
234
+ }
235
+ async respond(input, inspectRationale) {
236
+ // A STRING input is text by nature: it carries the text equivalence even
237
+ // through the generic entry point. Raw bytes / grids carry only the
238
+ // Mind-level canon option, if any.
239
+ const canon = this._canonFor(typeof input === "string" ? textCanon : null);
240
+ return this._respondImpl(inputBytes(this, input), inspectRationale, "respond", canon);
241
+ }
242
+ /** Text view of {@link respond}. NUL bytes (0x00) are stripped before
243
+ * decoding — they are structural padding in text answers. LOSSY for a
244
+ * binary answer that legitimately contains NULs: use {@link respond} and
245
+ * read `bytes` directly for binary/grid modalities.
246
+ *
247
+ * Injects the TEXT canonicalizer (src/canon.ts) so resolution treats
248
+ * every character variation of the same text — case, width, whitespace —
249
+ * as one form, provided the store's canon index is built
250
+ * ({@link buildCanonIndex}). */
251
+ async respondText(input, inspectRationale) {
252
+ const r = await this.respond(input, inspectRationale);
253
+ return decodeText(r.bytes);
254
+ }
255
+ // ── Conversation API ────────────────────────────────────────────────────
256
+ /** Begin a new conversation, optionally restoring from a previously-saved
257
+ * {@link ConversationState}. The returned handle is required for
258
+ * {@link respondTurn} and {@link endConversation}.
259
+ *
260
+ * Conversations are independent — a Mind can manage several concurrently.
261
+ * Each tracks the fold pyramid (accumulated internal processing) and
262
+ * turn-boundary offsets; the geometry never inspects content to guess
263
+ * where one turn ends and the next begins. */
264
+ beginConversation(state) {
265
+ const id = this._nextConvId++;
266
+ // Build the initial pyramid: from scratch for a new conversation,
267
+ // or from the saved context bytes when restoring.
268
+ const initBytes = state?.context ?? new Uint8Array(0);
269
+ const { pyramid } = bytesToTreePyramid(this.space, this.alphabet, initBytes);
270
+ this._conversations.set(id, {
271
+ pyramid,
272
+ bytes: initBytes,
273
+ boundaries: state?.boundaries ? [...state.boundaries] : [],
274
+ perceiveMemo: new Map(),
275
+ recogniseMemo: new Map(),
276
+ climbMemo: new Map(),
277
+ resolvedSubtrees: new WeakMap(),
278
+ });
279
+ return { id };
280
+ }
281
+ /** End a conversation, releasing its internal resources (accumulated
282
+ * context, boundary offsets, and the fold-pyramid cache). Idempotent. */
283
+ endConversation(conv) {
284
+ this._conversations.delete(conv.id);
285
+ }
286
+ /** The current serialisable state of an active conversation. Save this
287
+ * to resume the conversation later via {@link beginConversation}. */
288
+ conversationState(conv) {
289
+ const data = this._conversations.get(conv.id);
290
+ if (!data)
291
+ return null;
292
+ return {
293
+ context: data.bytes,
294
+ boundaries: [...data.boundaries],
295
+ };
296
+ }
297
+ /** Append a turn to a conversation's accumulated context WITHOUT
298
+ * responding — raw byte append plus a boundary offset, never a
299
+ * separator; the fold pyramid advances by O(turn).
300
+ *
301
+ * This is the primitive for turns the Mind should hear but not answer:
302
+ * replaying a transcript, feeding the OTHER speaker's line in a
303
+ * prediction harness, or restoring context piecewise. {@link
304
+ * respondTurn} = addTurn + think + its own reply appended the same way. */
305
+ addTurn(conv, turn) {
306
+ const data = this._conversations.get(conv.id);
307
+ if (!data)
308
+ throw new Error(`Conversation ${conv.id} not found`);
309
+ const turnBytes = inputBytes(this, turn);
310
+ this._growContext(data, turnBytes);
311
+ return this.conversationState(conv);
312
+ }
313
+ /** Grow a conversation's accumulated context by one turn's bytes — raw
314
+ * append plus a boundary offset, pyramid advanced by O(turn), the grown
315
+ * context's tree seeded into the conversation's perceive memo. The ONE
316
+ * place a context grows ({@link addTurn} and {@link respondTurn} both
317
+ * come through here), so the append semantics cannot drift. */
318
+ _growContext(data, turnBytes) {
319
+ const prevLen = data.pyramid.bytes;
320
+ // An empty turn neither grows the context nor marks a boundary —
321
+ // boundaries are documented strictly increasing, and a zero-length
322
+ // "turn" is no turn. The pyramid's zero-growth shortcut makes the
323
+ // refold below O(1), so the existing tree is returned unchanged.
324
+ const grow = turnBytes.length > 0;
325
+ const grown = !grow
326
+ ? data.bytes
327
+ : prevLen > 0
328
+ ? concat2(data.bytes, turnBytes)
329
+ : turnBytes;
330
+ if (grow && prevLen > 0)
331
+ data.boundaries.push(prevLen);
332
+ const { tree, pyramid } = bytesToTreePyramid(this.space, this.alphabet, grown, data.pyramid);
333
+ data.pyramid = pyramid;
334
+ data.bytes = grown;
335
+ data.perceiveMemo.set(latin1Key(grown), tree);
336
+ return tree;
337
+ }
338
+ /** Process one turn of a conversation.
339
+ *
340
+ * `turn` is the raw input for the latest turn — its bytes are appended
341
+ * to the accumulated context directly (raw concatenation). The Mind
342
+ * tracks the byte offset where each turn ends; no separator is ever
343
+ * inserted or inspected.
344
+ *
345
+ * Returns the response AND the updated {@link ConversationState} so the
346
+ * caller can persist it. The conversation handle's internal state is
347
+ * updated in place — the returned state is a snapshot for storage.
348
+ *
349
+ * SINGLE FLIGHT: at most one respondTurn may be in flight per Mind. The
350
+ * conversation's memo caches are swapped into the Mind-level per-response
351
+ * pointers for the duration of the turn, so a concurrently-running
352
+ * respond()/respondTurn() on the SAME Mind would interleave state.
353
+ * Different Minds (or sequential awaits, as in every test) are safe. */
354
+ async respondTurn(conv, turn, inspectRationale) {
355
+ const data = this._conversations.get(conv.id);
356
+ if (!data)
357
+ throw new Error(`Conversation ${conv.id} not found`);
358
+ const turnBytes = inputBytes(this, turn);
359
+ // Incremental perception — O(turn) instead of O(context).
360
+ const tree = this._growContext(data, turnBytes);
361
+ const newContext = data.bytes;
362
+ // Swap in the conversation's persistent state so the inference
363
+ // pipeline does not re-process the prefix from scratch.
364
+ // perceiveMemo / recogniseMemo / climbMemo — content-keyed;
365
+ // the prefix's results from the previous turn are found by
366
+ // the current turn's sub-span calls.
367
+ // _resolvedSubtrees — Sema-node-keyed; when the pyramid reuses
368
+ // prefix subtrees (identical objects), foldTree returns their
369
+ // ids immediately — O(suffix) instead of O(context).
370
+ this.perceiveMemo = data.perceiveMemo;
371
+ this.recogniseMemo = data.recogniseMemo;
372
+ this.climbMemo = data.climbMemo;
373
+ this._resolvedSubtrees = data.resolvedSubtrees;
374
+ this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
375
+ // A string turn is text by nature — carry the text equivalence, same as
376
+ // respond() (see _canonFor).
377
+ this.canon = this._canonFor(typeof turn === "string" ? textCanon : null);
378
+ this.canonMemo = this.canon ? new Map() : null;
379
+ try {
380
+ const top = this.trace?.enter("respondTurn", [
381
+ rItem(newContext, "query"),
382
+ ]);
383
+ const thought = await think(this, newContext, this.mechanisms);
384
+ if (thought === null) {
385
+ top?.done([], "nothing to perceive or an empty store — no answer");
386
+ return {
387
+ response: { v: null, bytes: new Uint8Array(0) },
388
+ state: this.conversationState(conv),
389
+ };
390
+ }
391
+ const voiced = await articulate(this, thought.bytes, newContext);
392
+ top?.done([rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined)], "the answer, re-voiced in the asker's words");
393
+ // The REPLY joins the accumulated context the same way a turn does
394
+ // ({@link addTurn}): raw byte append plus a boundary offset — never a
395
+ // separator. A conversation's context is the full exchange, exactly
396
+ // the cumulative continuous shape multi-turn training deposits, so a
397
+ // later turn can refer to what was ANSWERED ("which of those two…"),
398
+ // not only to what was asked.
399
+ if (voiced.length > 0)
400
+ this.addTurn(conv, voiced);
401
+ return {
402
+ response: {
403
+ v: gistOf(this, voiced),
404
+ bytes: voiced,
405
+ provenance: thought.provenance,
406
+ },
407
+ state: this.conversationState(conv),
408
+ };
409
+ }
410
+ finally {
411
+ // No save-back: the conversation's memo MAPS were mutated in place —
412
+ // `data.*` still points at them. Re-assigning from the Mind-level
413
+ // pointers here was a no-op in the single-flight case and, under a
414
+ // concurrently-started respond() (which swaps its own fresh maps into
415
+ // those pointers), would inject a FOREIGN response's memos into this
416
+ // conversation. Clear Mind references — non-conversation respond()
417
+ // calls get fresh per-response memos.
418
+ this.trace = null;
419
+ this.perceiveMemo = null;
420
+ this.recogniseMemo = null;
421
+ this.climbMemo = null;
422
+ this.canon = null;
423
+ this.canonMemo = null;
424
+ this._resolvedSubtrees = null;
425
+ this._edgeGuide = null;
426
+ this._edgeChoice.clear();
427
+ }
428
+ }
429
+ /** Text view of {@link respondTurn}. See {@link respondText} for the
430
+ * NUL-stripping caveat. For binary or grid turns use {@link respondTurn}
431
+ * directly — this is a text-only convenience, like {@link respondText}. */
432
+ async respondTurnText(conv, turn, inspectRationale) {
433
+ const { response, state } = await this.respondTurn(conv, turn, inspectRationale);
434
+ return { response: decodeText(response.bytes), state };
435
+ }
436
+ async embedding(input) {
437
+ return (await this.respond(input)).v;
438
+ }
439
+ /** Kinship note: the vector arm below is a miniature of recall's tier 3
440
+ * (resonate → reach gate → read out the nearest form's bytes) — the
441
+ * read-out direction of the same operation, without recall's grounding
442
+ * ladder. If either side's acceptance rule changes, revisit the other. */
443
+ async express(idOrV) {
444
+ if (typeof idOrV === "number")
445
+ return this.store.bytes(idOrV);
446
+ const [hit] = await this.store.resonate(idOrV, 1);
447
+ // The same confidence floor recall uses: a vector whose nearest stored
448
+ // form sits below the reach threshold relates to NOTHING in the store —
449
+ // returning that form's bytes anyway would fabricate an answer from an
450
+ // unrelated neighbour. Silence is the honest read-out.
451
+ if (hit && hit.score >= reachThreshold(this.space.maxGroup)) {
452
+ return this.store.bytes(hit.id);
453
+ }
454
+ return new Uint8Array(0);
455
+ }
456
+ // ── Learning ─────────────────────────────────────────────────────────────
457
+ async ingest(input, second) {
458
+ return ingest(this, input, second);
459
+ }
460
+ // ── Extension Surface ────────────────────────────────────────────────────
461
+ extensionHost() {
462
+ const mind = this;
463
+ return {
464
+ meaningOf: (bytes, anchors) => meaningOf(this, bytes, anchors),
465
+ continuation: (bytes) => this.groundedContinuation(bytes),
466
+ segment: (bytes) => segment(this, bytes).map((s) => ({ i: s.start, j: s.end })),
467
+ get reach() {
468
+ return mind.space.maxGroup;
469
+ },
470
+ };
471
+ }
472
+ async groundedContinuation(bytes) {
473
+ const id = resolveImpl(this, bytes);
474
+ if (id === null)
475
+ return null;
476
+ const grounded = await follow(this, id);
477
+ if (grounded !== null && !bytesEqual(grounded, bytes))
478
+ return grounded;
479
+ return null;
480
+ }
481
+ // ── Content-index repair ───────────────────────────────────────────────
482
+ /** Re-index structurally-important nodes whose gists were evicted from the
483
+ * pending cache before they reached the content index. See {@link
484
+ * Store.repairContentIndex} for the contract; this method wires the
485
+ * Mind's perception into the store's repair walk.
486
+ *
487
+ * Run this after training or at checkpoints to restore recall reach for
488
+ * nodes that bridge experiences but were never indexed. A pure interior
489
+ * node (no edges, no halo) is deliberately skipped — it is scaffolding,
490
+ * not an experience root or bridge, and regenerating its gist would waste
491
+ * I/O and index space for no recall benefit.
492
+ *
493
+ * @param minParents only repair nodes with ≥ this many structural parents
494
+ * (default 2 — structural bridges)
495
+ * @returns number of nodes added to the content index */
496
+ async repairContentIndex(minParents = 2) {
497
+ return this.store.repairContentIndex(async (id) => {
498
+ const bytes = this.store.bytes(id);
499
+ if (bytes.length === 0)
500
+ return null;
501
+ return gistOf(this, bytes);
502
+ }, minParents);
503
+ }
504
+ // ── Canonical-form index ───────────────────────────────────────────────
505
+ /** Build (or incrementally refresh) the store's canonical-form index: for
506
+ * every content-bearing node, record the hash of its CANONICAL key so
507
+ * resolution can find stored forms across surface variation (case, width,
508
+ * whitespace — whatever `canon` equates; see src/canon.ts).
509
+ *
510
+ * Incremental and idempotent: the last indexed node id is remembered in
511
+ * store meta (`canon.upto`), so a refresh after further training scans
512
+ * only the new rows. Run once after training, and again after ingests —
513
+ * the same operational shape as {@link repairContentIndex}.
514
+ *
515
+ * @param canon the canonicalizer to index under — MUST be the same one
516
+ * queries will carry (text queries carry {@link textCanon}
517
+ * unless the Mind was constructed with its own)
518
+ * @returns number of index rows added */
519
+ async buildCanonIndex(canon) {
520
+ const c = canon ?? this._canonFor(textCanon);
521
+ const store = this.store;
522
+ if (c === null || !store.canonAdd || !store.eachContent)
523
+ return 0;
524
+ const from = Number(await store.getMeta("canon.upto") ?? 0);
525
+ let added = 0;
526
+ let maxId = from - 1;
527
+ store.eachContent((id, bytes) => {
528
+ if (id > maxId)
529
+ maxId = id;
530
+ const key = c(bytes);
531
+ if (key.length === 0)
532
+ return;
533
+ // Only index content whose canonical key DIFFERS from its raw bytes —
534
+ // an already-canonical span is found by the exact lookup (and by the
535
+ // fallback's own exact probe of the canonical bytes), so indexing it
536
+ // would only add rows.
537
+ if (bytesEqual(key, bytes))
538
+ return;
539
+ store.canonAdd(canonHash(key), id);
540
+ added++;
541
+ }, from);
542
+ await store.setMeta("canon.upto", String(maxId + 1));
543
+ store.commit();
544
+ return added;
545
+ }
546
+ // ── Persistence ──────────────────────────────────────────────────────────
547
+ async save() {
548
+ const meta = new TextEncoder().encode(JSON.stringify(this.cfg));
549
+ await this.store.saveSnapshot(meta);
550
+ return meta;
551
+ }
552
+ static async load(snapshot, store) {
553
+ const cfg = JSON.parse(new TextDecoder().decode(snapshot));
554
+ return new Mind(cfg, store, true);
555
+ }
556
+ static async loadFromStore(store) {
557
+ const meta = await store.loadSnapshot();
558
+ if (!meta)
559
+ throw new Error("no snapshot in store");
560
+ return Mind.load(meta, store);
561
+ }
562
+ }