@hviana/sema 0.4.2 → 0.4.3

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