@hviana/sema 0.5.2 → 0.5.4

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 (157) hide show
  1. package/AGENTS.md +115 -53
  2. package/HOW_IT_WORKS.md +291 -184
  3. package/jsr.json +6 -0
  4. package/package.json +1 -1
  5. package/src/mind/bridge.ts +10 -104
  6. package/src/mind/match.ts +497 -7
  7. package/src/mind/{prefix-completion.ts → mechanisms/prefix-completion.ts} +66 -92
  8. package/src/mind/mechanisms/recall.ts +38 -129
  9. package/src/mind/mechanisms/reference.ts +343 -0
  10. package/src/mind/mind.ts +12 -8
  11. package/src/mind/pipeline-mechanism.ts +120 -3
  12. package/src/mind/pipeline.ts +16 -2
  13. package/src/mind/traverse.ts +92 -1
  14. package/src/store.ts +13 -4
  15. package/test/33-multi-candidate.test.mjs +21 -11
  16. package/test/70-prefix-completion.test.mjs +1 -1
  17. package/test/72-prefix-candidate-supply.test.mjs +7 -9
  18. package/test/74-prefix-trap-not-sprung-early.test.mjs +1 -1
  19. package/test/76-reference-binding.test.mjs +543 -0
  20. package/dist/example/demo.d.ts +0 -1
  21. package/dist/example/demo.js +0 -39
  22. package/dist/example/train_base.d.ts +0 -93
  23. package/dist/example/train_base.js +0 -2269
  24. package/dist/src/alphabet.d.ts +0 -7
  25. package/dist/src/alphabet.js +0 -33
  26. package/dist/src/alu/src/alu.d.ts +0 -185
  27. package/dist/src/alu/src/alu.js +0 -440
  28. package/dist/src/alu/src/expr.d.ts +0 -61
  29. package/dist/src/alu/src/expr.js +0 -318
  30. package/dist/src/alu/src/index.d.ts +0 -11
  31. package/dist/src/alu/src/index.js +0 -19
  32. package/dist/src/alu/src/kernel-arith.d.ts +0 -16
  33. package/dist/src/alu/src/kernel-arith.js +0 -264
  34. package/dist/src/alu/src/kernel-bits.d.ts +0 -19
  35. package/dist/src/alu/src/kernel-bits.js +0 -152
  36. package/dist/src/alu/src/kernel-logic.d.ts +0 -4
  37. package/dist/src/alu/src/kernel-logic.js +0 -60
  38. package/dist/src/alu/src/kernel-nd.d.ts +0 -3
  39. package/dist/src/alu/src/kernel-nd.js +0 -208
  40. package/dist/src/alu/src/kernel-numeric.d.ts +0 -54
  41. package/dist/src/alu/src/kernel-numeric.js +0 -366
  42. package/dist/src/alu/src/operation.d.ts +0 -168
  43. package/dist/src/alu/src/operation.js +0 -189
  44. package/dist/src/alu/src/parser.d.ts +0 -221
  45. package/dist/src/alu/src/parser.js +0 -577
  46. package/dist/src/alu/src/resonance.d.ts +0 -55
  47. package/dist/src/alu/src/resonance.js +0 -126
  48. package/dist/src/alu/src/text.d.ts +0 -31
  49. package/dist/src/alu/src/text.js +0 -73
  50. package/dist/src/alu/src/value.d.ts +0 -109
  51. package/dist/src/alu/src/value.js +0 -300
  52. package/dist/src/alu/test/alu.test.d.ts +0 -1
  53. package/dist/src/alu/test/alu.test.js +0 -764
  54. package/dist/src/bytes.d.ts +0 -14
  55. package/dist/src/bytes.js +0 -59
  56. package/dist/src/canon.d.ts +0 -45
  57. package/dist/src/canon.js +0 -85
  58. package/dist/src/config.d.ts +0 -111
  59. package/dist/src/config.js +0 -91
  60. package/dist/src/derive/src/deduction.d.ts +0 -136
  61. package/dist/src/derive/src/deduction.js +0 -159
  62. package/dist/src/derive/src/index.d.ts +0 -8
  63. package/dist/src/derive/src/index.js +0 -11
  64. package/dist/src/derive/src/priority-queue.d.ts +0 -20
  65. package/dist/src/derive/src/priority-queue.js +0 -73
  66. package/dist/src/derive/src/rewrite.d.ts +0 -56
  67. package/dist/src/derive/src/rewrite.js +0 -100
  68. package/dist/src/derive/src/trie.d.ts +0 -90
  69. package/dist/src/derive/src/trie.js +0 -217
  70. package/dist/src/derive/test/derive.test.d.ts +0 -1
  71. package/dist/src/derive/test/derive.test.js +0 -122
  72. package/dist/src/extension.d.ts +0 -37
  73. package/dist/src/extension.js +0 -7
  74. package/dist/src/geometry.d.ts +0 -233
  75. package/dist/src/geometry.js +0 -1089
  76. package/dist/src/index.d.ts +0 -17
  77. package/dist/src/index.js +0 -19
  78. package/dist/src/ingest-cache.d.ts +0 -41
  79. package/dist/src/ingest-cache.js +0 -165
  80. package/dist/src/meter.d.ts +0 -176
  81. package/dist/src/meter.js +0 -274
  82. package/dist/src/mind/articulation.d.ts +0 -6
  83. package/dist/src/mind/articulation.js +0 -99
  84. package/dist/src/mind/attention.d.ts +0 -430
  85. package/dist/src/mind/attention.js +0 -2418
  86. package/dist/src/mind/bridge.d.ts +0 -39
  87. package/dist/src/mind/bridge.js +0 -998
  88. package/dist/src/mind/canonical.d.ts +0 -34
  89. package/dist/src/mind/canonical.js +0 -93
  90. package/dist/src/mind/frame-filler.d.ts +0 -15
  91. package/dist/src/mind/frame-filler.js +0 -535
  92. package/dist/src/mind/graph-search.d.ts +0 -294
  93. package/dist/src/mind/graph-search.js +0 -996
  94. package/dist/src/mind/index.d.ts +0 -9
  95. package/dist/src/mind/index.js +0 -5
  96. package/dist/src/mind/junction.d.ts +0 -137
  97. package/dist/src/mind/junction.js +0 -358
  98. package/dist/src/mind/learning.d.ts +0 -75
  99. package/dist/src/mind/learning.js +0 -265
  100. package/dist/src/mind/match.d.ts +0 -192
  101. package/dist/src/mind/match.js +0 -666
  102. package/dist/src/mind/mechanisms/alu.d.ts +0 -4
  103. package/dist/src/mind/mechanisms/alu.js +0 -36
  104. package/dist/src/mind/mechanisms/cast.d.ts +0 -89
  105. package/dist/src/mind/mechanisms/cast.js +0 -1186
  106. package/dist/src/mind/mechanisms/confluence.d.ts +0 -24
  107. package/dist/src/mind/mechanisms/confluence.js +0 -271
  108. package/dist/src/mind/mechanisms/cover.d.ts +0 -6
  109. package/dist/src/mind/mechanisms/cover.js +0 -232
  110. package/dist/src/mind/mechanisms/extraction.d.ts +0 -33
  111. package/dist/src/mind/mechanisms/extraction.js +0 -327
  112. package/dist/src/mind/mechanisms/recall.d.ts +0 -16
  113. package/dist/src/mind/mechanisms/recall.js +0 -558
  114. package/dist/src/mind/mind.d.ts +0 -386
  115. package/dist/src/mind/mind.js +0 -754
  116. package/dist/src/mind/pipeline-mechanism.d.ts +0 -183
  117. package/dist/src/mind/pipeline-mechanism.js +0 -521
  118. package/dist/src/mind/pipeline.d.ts +0 -49
  119. package/dist/src/mind/pipeline.js +0 -331
  120. package/dist/src/mind/prefix-completion.d.ts +0 -59
  121. package/dist/src/mind/prefix-completion.js +0 -270
  122. package/dist/src/mind/primitives.d.ts +0 -85
  123. package/dist/src/mind/primitives.js +0 -333
  124. package/dist/src/mind/rationale.d.ts +0 -139
  125. package/dist/src/mind/rationale.js +0 -163
  126. package/dist/src/mind/reasoning.d.ts +0 -42
  127. package/dist/src/mind/reasoning.js +0 -305
  128. package/dist/src/mind/recognition.d.ts +0 -20
  129. package/dist/src/mind/recognition.js +0 -696
  130. package/dist/src/mind/resonance.d.ts +0 -35
  131. package/dist/src/mind/resonance.js +0 -365
  132. package/dist/src/mind/trace.d.ts +0 -15
  133. package/dist/src/mind/trace.js +0 -73
  134. package/dist/src/mind/traverse.d.ts +0 -158
  135. package/dist/src/mind/traverse.js +0 -716
  136. package/dist/src/mind/types.d.ts +0 -418
  137. package/dist/src/mind/types.js +0 -179
  138. package/dist/src/rabitq-ivf/src/database.d.ts +0 -113
  139. package/dist/src/rabitq-ivf/src/database.js +0 -201
  140. package/dist/src/rabitq-ivf/src/index.d.ts +0 -7
  141. package/dist/src/rabitq-ivf/src/index.js +0 -4
  142. package/dist/src/rabitq-ivf/src/ivf.d.ts +0 -200
  143. package/dist/src/rabitq-ivf/src/ivf.js +0 -1165
  144. package/dist/src/rabitq-ivf/src/prng.d.ts +0 -19
  145. package/dist/src/rabitq-ivf/src/prng.js +0 -36
  146. package/dist/src/rabitq-ivf/src/rabitq.d.ts +0 -95
  147. package/dist/src/rabitq-ivf/src/rabitq.js +0 -313
  148. package/dist/src/sema.d.ts +0 -41
  149. package/dist/src/sema.js +0 -77
  150. package/dist/src/store-sqlite.d.ts +0 -184
  151. package/dist/src/store-sqlite.js +0 -942
  152. package/dist/src/store.d.ts +0 -762
  153. package/dist/src/store.js +0 -1823
  154. package/dist/src/vec.d.ts +0 -31
  155. package/dist/src/vec.js +0 -109
  156. package/src/mind/frame-filler.ts +0 -604
  157. package/test/69-frame-filler.test.mjs +0 -115
@@ -1,754 +0,0 @@
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 { contentFoldIncremental, 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, textEdgeTrim } 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, perceive as perceiveImpl, perceiveKey, 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` spares foldTree the store
210
- * probes for every prefix subtree — and, for walks that pass no visitor,
211
- * the descent as well. respondTurn used to inline its own copy of this
212
- * and of {@link endResponse}; the two drifted (a memo added to one was
213
- * silently absent from the other), so there is exactly one pair now. */
214
- beginResponse(inspectRationale, canon, conv) {
215
- this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
216
- this.climbMemo = conv ? conv.climbMemo : new Map();
217
- this.recogniseMemo = conv ? conv.recogniseMemo : new Map();
218
- this.perceiveMemo = conv ? conv.perceiveMemo : new Map();
219
- this._resolvedSubtrees = conv ? conv.resolvedSubtrees : null;
220
- // Inference is a pure function of cumulative bytes. Conversation
221
- // boundaries remain persistence/API metadata and must not select a
222
- // different mechanism path than respond() on the identical byte stream.
223
- // answeredSpans and currentTurnStart ARE restored from the conversation,
224
- // however — they are pure functions of the cumulative byte stream (the
225
- // assistant's own prior replies, and where the current user turn starts,
226
- // are deterministic given the full transcript). Without them confluence,
227
- // cover, the weave, and the consensus climb treat prior assistant turns
228
- // as fresh query content — re-deriving them as constraints, voting
229
- // anchors, and alignment points.
230
- this.answeredSpans = conv ? conv.answeredSpans : [];
231
- this.currentTurnStart = conv && conv.boundaries.length > 0
232
- ? conv.boundaries[conv.boundaries.length - 1]
233
- : 0;
234
- this.canon = canon ?? null;
235
- this.canonMemo = canon ? new Map() : null;
236
- this._beginMeter();
237
- }
238
- /** Open (or leave closed) the response's work accumulator. Separate from
239
- * {@link beginResponse} because {@link respondTurn} keeps its own
240
- * conversation-scoped lifecycle and must not create fresh per-response
241
- * memos — but it DOES meter, through this same pair. */
242
- _beginMeter() {
243
- if (!this._profile)
244
- return;
245
- this.meter = new Meter();
246
- this.store.meter = this.meter;
247
- }
248
- /** Close the accumulator and publish its report. Detaching from the store
249
- * matters: a Mind that shares a store with another Mind must not keep
250
- * charging that store's reads to a finished response. */
251
- _endMeter(queryBytes) {
252
- if (this.meter === null)
253
- return;
254
- this.lastCost = this.meter.report(queryBytes);
255
- this.store.meter = null;
256
- this.meter = null;
257
- }
258
- /** The canonicalizer a response should carry: the Mind-level option when
259
- * set (or none when explicitly disabled), else the entry point's own
260
- * default — text entry points pass {@link textCanon}, binary ones null. */
261
- _canonFor(entryDefault) {
262
- if (this._canonOpt === false)
263
- return null;
264
- return this._canonOpt ?? entryDefault;
265
- }
266
- /** Close one response's transient state — every per-response field, incl.
267
- * the edge guide/choices `think` sets mid-flight, and the meter's report.
268
- *
269
- * A conversation's memo MAPS were mutated in place, so `data.*` still
270
- * points at them and there is nothing to save back. Clearing the Mind's
271
- * references is what matters: a concurrently-started `respond()` swaps its
272
- * own fresh maps into these pointers, and copying back from them here
273
- * would inject a foreign response's memos into the conversation. */
274
- endResponse(queryBytes) {
275
- this._endMeter(queryBytes);
276
- this.trace = null;
277
- this.climbMemo = null;
278
- this.recogniseMemo = null;
279
- this.perceiveMemo = null;
280
- this._resolvedSubtrees = null;
281
- this.answeredSpans = [];
282
- this.currentTurnStart = 0;
283
- this.canon = null;
284
- this.canonMemo = null;
285
- this._edgeGuide = null;
286
- this._edgeChoice.clear();
287
- }
288
- /** Shared response core — the one path from bytes to voiced answer.
289
- * `respond` calls this directly; `respondTurn` has its own path
290
- * with conversation-persistent memos and incremental perception. */
291
- async _respondImpl(queryBytes, inspectRationale, traceLabel = "respond", canon = null) {
292
- this.beginResponse(inspectRationale, canon);
293
- try {
294
- return await this._groundAndVoice(queryBytes, traceLabel);
295
- }
296
- finally {
297
- this.endResponse(queryBytes.length);
298
- }
299
- }
300
- /** The ONE path from query bytes to a voiced answer: ground (think), then
301
- * re-voice in the asker's words (articulate). Both entry points run
302
- * exactly this — they differ only in the LIFECYCLE around it (fresh
303
- * per-response memos vs. a conversation's persistent ones) and in what
304
- * they do with the answer afterwards. It must be called between
305
- * {@link beginResponse} and {@link endResponse}. */
306
- async _groundAndVoice(queryBytes, traceLabel) {
307
- const top = this.trace?.enter(traceLabel, [rItem(queryBytes, "query")]);
308
- const meter = this.meter;
309
- const thought = meter
310
- ? await meter.time("think", () => think(this, queryBytes, this.mechanisms))
311
- : await think(this, queryBytes, this.mechanisms);
312
- if (thought === null) {
313
- top?.done([], "nothing to perceive or an empty store — no answer");
314
- return { v: null, bytes: new Uint8Array(0) };
315
- }
316
- const voiced = meter
317
- ? await meter.time("articulate", () => articulate(this, thought.bytes, queryBytes))
318
- : await articulate(this, thought.bytes, queryBytes);
319
- top?.done([rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined)], "the answer, re-voiced in the asker's words");
320
- return {
321
- v: gistOf(this, voiced),
322
- bytes: voiced,
323
- provenance: thought.provenance,
324
- };
325
- }
326
- /** Answer ONE self-contained input.
327
- *
328
- * A MULTI-TURN context is not that, and this is the wrong entry point for
329
- * it. `respond` folds the bytes it is handed with no boundary set, because
330
- * nothing in a flat byte string says where one turn ended — only the caller
331
- * who assembled it knows, which is the whole reason `boundaries` is a
332
- * parameter of {@link perceiveImpl} and never inferred from content. A
333
- * conversation deposited through {@link ingest} folds its contexts over
334
- * those turn boundaries, so a hand-concatenated transcript passed here
335
- * folds differently from the way it was learnt and reaches the trained
336
- * context node only by luck (measured on a 7-turn conversation: 5/7 here
337
- * against 7/7 through {@link respondTurn}, same bytes). Use
338
- * {@link beginConversation} + {@link respondTurn}, or {@link addTurn} to
339
- * replay turns the Mind should hear but not answer. */
340
- async respond(input, inspectRationale) {
341
- // A STRING input is text by nature: it carries the text equivalence even
342
- // through the generic entry point. Raw bytes / grids carry only the
343
- // Mind-level canon option, if any.
344
- const canon = this._canonFor(typeof input === "string" ? textCanon : null);
345
- // EDGE WHITESPACE IS NOT PART OF THE QUESTION — trim it once, here, so
346
- // every mechanism downstream sees the same question regardless of how the
347
- // caller spaced it. See canon.ts's textEdgeTrim for why the outer edges of a
348
- // whole input are exactly where canon.ts's no-trimming hazard cannot arise.
349
- // Gated on the SAME modality test as the canonicalizer above: for bytes and
350
- // grids 0x20 is content, and nothing is trimmed.
351
- //
352
- // Measured on the 15.7M-node store: without this, one leading space took
353
- // `Who wrote Romeo and Juliet?` and `What is the chemical symbol for
354
- // water?` from answered to silent, because a shift re-seats every fold
355
- // boundary — the whole of analyze_training.ts's K2 phase-robustness gap.
356
- // The caller's EXACT bytes are tried first and the trim is a RETRY, not a
357
- // pre-filter. Trimming up front is asymmetric — it normalises the query but
358
- // not the stored forms — so it breaks byte-exact identity for a form trained
359
- // WITH edge whitespace: test/04 deposits [" ice ", "cold"] and asks
360
- // " ice ", which must keep answering. Retrying preserves that (the raw
361
- // query resolves on the first pass) while still reaching the padded case
362
- // (the raw query grounds nothing, the trimmed one does).
363
- //
364
- // COST: nothing on any answering path. The retry needs BOTH silence AND
365
- // edge whitespace on the query, the same "only on the already-failed path"
366
- // discipline test/44 and the bridge's own trim retry use. The conversation
367
- // entry point (respondTurn) is deliberately NOT trimmed — it tracks
368
- // turn-boundary offsets into its accumulated context, and shifting the bytes
369
- // under those offsets would desync them.
370
- const bytes = inputBytes(this, input);
371
- const first = await this._respondImpl(bytes, inspectRationale, "respond", canon);
372
- if (first.bytes.length > 0 || typeof input !== "string")
373
- return first;
374
- const trimmed = textEdgeTrim(bytes);
375
- if (trimmed.length === bytes.length || trimmed.length === 0)
376
- return first;
377
- return this._respondImpl(trimmed, inspectRationale, "respond", canon);
378
- }
379
- /** Text view of {@link respond}. NUL bytes (0x00) are stripped before
380
- * decoding — they are structural padding in text answers. LOSSY for a
381
- * binary answer that legitimately contains NULs: use {@link respond} and
382
- * read `bytes` directly for binary/grid modalities.
383
- *
384
- * Injects the TEXT canonicalizer (src/canon.ts) so resolution treats
385
- * every character variation of the same text — case, width, whitespace —
386
- * as one form, provided the store's canon index is built
387
- * ({@link buildCanonIndex}). */
388
- async respondText(input, inspectRationale) {
389
- const r = await this.respond(input, inspectRationale);
390
- return decodeText(r.bytes);
391
- }
392
- // ── Conversation API ────────────────────────────────────────────────────
393
- /** Begin a new conversation, optionally restoring from a previously-saved
394
- * {@link ConversationState}. The returned handle is required for
395
- * {@link respondTurn} and {@link endConversation}.
396
- *
397
- * Conversations are independent — a Mind can manage several concurrently.
398
- * Each tracks the fold pyramid (accumulated internal processing) and
399
- * turn-boundary offsets; the geometry never inspects content to guess
400
- * where one turn ends and the next begins. */
401
- beginConversation(state) {
402
- const id = this._nextConvId++;
403
- const initBytes = state?.context ?? new Uint8Array(0);
404
- // NORMALISE CALLER-SUPPLIED BOUNDARIES. `boundaries` is documented
405
- // strictly increasing and every boundary this class produces is (they are
406
- // appended as the context grows), but a restored {@link ConversationState}
407
- // comes from OUTSIDE — hand-built, migrated, or round-tripped through a
408
- // store that did not preserve order. The folds consume boundaries with a
409
- // sequential `b > prev` filter, so an out-of-order entry is silently
410
- // DROPPED rather than rejected, and the conversation would then fold over
411
- // a different cut set than the one the caller believes it restored.
412
- // `bytesToTree` used to sort on the way in and absorbed this; the
413
- // incremental fold this now calls does not, so the normalisation belongs
414
- // here, at the one public door untrusted boundaries come through.
415
- const initBoundaries = state?.boundaries
416
- ? [...new Set(state.boundaries)]
417
- .filter((b) => b > 0 && b < initBytes.length)
418
- .sort((a, b) => a - b)
419
- : [];
420
- const initAnswered = state?.answeredSpans
421
- ? state.answeredSpans.map(([start, end]) => [start, end])
422
- : initBoundaries.flatMap((start, i, cuts) => i % 2 === 0 && i + 1 < cuts.length
423
- ? [[start, cuts[i + 1]]]
424
- : []);
425
- // The same incremental fold `_growContext` uses, so a RESTORED
426
- // conversation starts with segment state its next turn can reuse — a
427
- // resumed conversation is otherwise identical to a live one and must not
428
- // pay a full re-fold on every turn for the rest of its life.
429
- const restored = contentFoldIncremental(this.space, this.alphabet, initBytes);
430
- this._conversations.set(id, {
431
- tree: restored.tree,
432
- content: restored.fold,
433
- bytes: initBytes,
434
- boundaries: initBoundaries,
435
- answeredSpans: initAnswered,
436
- perceiveMemo: new Map(),
437
- recogniseMemo: new Map(),
438
- climbMemo: new Map(),
439
- resolvedSubtrees: new WeakMap(),
440
- });
441
- return { id };
442
- }
443
- /** End a conversation, releasing its internal resources (accumulated
444
- * context, boundary offsets, and the fold-pyramid cache). Idempotent. */
445
- endConversation(conv) {
446
- this._conversations.delete(conv.id);
447
- }
448
- /** The current serialisable state of an active conversation. Save this
449
- * to resume the conversation later via {@link beginConversation}. */
450
- conversationState(conv) {
451
- const data = this._conversations.get(conv.id);
452
- if (!data)
453
- return null;
454
- return {
455
- context: data.bytes,
456
- boundaries: [...data.boundaries],
457
- answeredSpans: data.answeredSpans.map(([start, end]) => [start, end]),
458
- };
459
- }
460
- /** Append a turn to a conversation's accumulated context WITHOUT
461
- * responding — raw byte append plus a boundary offset, never a
462
- * separator; the fold pyramid advances by O(turn).
463
- *
464
- * This is the primitive for turns the Mind should hear but not answer:
465
- * replaying a transcript, feeding the OTHER speaker's line in a
466
- * prediction harness, or restoring context piecewise. {@link
467
- * respondTurn} = addTurn + think + its own reply appended the same way.
468
- *
469
- * ── ON SEPARATORS: THERE IS NO SEPARATOR QUESTION ────────────────────
470
- *
471
- * "Never a separator" above says what this method DOES — it appends the
472
- * bytes you give it and records an OFFSET — not that separator bytes are
473
- * forbidden, unsupported, or something the engine must be taught about.
474
- * Sema is agnostic to them, and reviewers keep mistaking that agnosticism
475
- * for a constraint. To be explicit, because the mistake is easy:
476
- *
477
- * 1. A turn boundary is an OFFSET, held here, in `boundaries`. It is
478
- * never a character the geometry scans for. Nothing downstream asks
479
- * "what byte separates two turns?" because nothing downstream finds
480
- * boundaries by looking at content at all.
481
- * 2. A separator in a CORPUS is ordinary content. If a trainer joins
482
- * turns with "\n" (example/train_base.ts does), those newlines are
483
- * simply bytes inside the stream, folded like every other byte. They
484
- * are a property of that corpus, not of this API and not of the fold.
485
- * 3. This API can therefore reproduce ANY corpus exactly, with no
486
- * convention to agree on: replaying a "\n"-joined corpus means passing
487
- * `"\n" + turnText` as the turn. The separator rides along IN the
488
- * turn bytes, where it belongs. There is nothing to configure and no
489
- * mode to select.
490
- * 4. Inference is not exact-match anyway. Recognition works over
491
- * sub-spans, canonical equivalence and resonance, so a query that
492
- * differs from the trained bytes by punctuation or whitespace still
493
- * reaches the trained forms; it degrades, it does not fail closed.
494
- *
495
- * What follows from 1–4: differing separator bytes between a corpus and a
496
- * query is an ordinary CONTENT difference — the same kind as any other
497
- * wording difference — and it is measured the same way. It is NOT an
498
- * incompatibility between the trainer and this API, and it does NOT
499
- * require choosing a project-wide separator convention. A review that
500
- * concludes otherwise (this one did, before being corrected) has mistaken
501
- * its own harness feeding untrained bytes for an architectural defect. */
502
- addTurn(conv, turn) {
503
- const data = this._conversations.get(conv.id);
504
- if (!data)
505
- throw new Error(`Conversation ${conv.id} not found`);
506
- const turnBytes = inputBytes(this, turn);
507
- this._growContext(data, turnBytes);
508
- return this.conversationState(conv);
509
- }
510
- /** Grow a conversation's accumulated context by one turn's bytes — raw
511
- * append plus a boundary offset, pyramid advanced by O(turn), the grown
512
- * context's tree seeded into the conversation's perceive memo. The ONE
513
- * place a context grows ({@link addTurn} and {@link respondTurn} both
514
- * come through here), so the append semantics cannot drift. */
515
- _growContext(data, turnBytes) {
516
- const prevLen = data.bytes.length;
517
- // An empty turn neither grows the context nor marks a boundary —
518
- // boundaries are documented strictly increasing, and a zero-length
519
- // "turn" is no turn. Nothing changed, so the existing tree stands.
520
- const grow = turnBytes.length > 0;
521
- if (!grow)
522
- return data.tree;
523
- const grown = prevLen > 0 ? concat2(data.bytes, turnBytes) : turnBytes;
524
- if (prevLen > 0)
525
- data.boundaries.push(prevLen);
526
- // THE PLAIN FOLD, INCREMENTALLY. No boundary set is imposed here: the
527
- // tree is exactly the tree `perceive(grown)` builds for these bytes, which
528
- // is exactly the tree the DEPOSIT path folded when it learnt them. That
529
- // agreement is the whole point — it is what lets a cumulative context
530
- // resolve to its trained node, and when it was absent the alignment family
531
- // went quadratic (measured: 5.2M cells on a 476-byte context, against 0
532
- // when the two sides agree).
533
- //
534
- // The optimisation is unaffected by dropping the boundaries, because it
535
- // never came from them: content cuts are stable under append, so the
536
- // incremental fold reuses every segment left of the new turn as the SAME
537
- // object (see contentFoldIncremental). That object identity is what
538
- // `resolvedSubtrees` — a WeakMap keyed by node identity — needs in order
539
- // to hit at all. Measured against the stable-prefix fold it replaces:
540
- // ~40 rebuilt nodes per turn either way, flat as the context grows
541
- // sevenfold, and ~92% of nodes reused by identity in both.
542
- //
543
- // `data.boundaries` is still tracked, and is still exact — it is API
544
- // metadata (ConversationState, answeredSpans, currentTurnStart), not a
545
- // fold instruction.
546
- const folded = contentFoldIncremental(this.space, this.alphabet, grown, data.content);
547
- const tree = folded.tree;
548
- data.content = folded.fold;
549
- data.tree = tree;
550
- data.bytes = grown;
551
- // Seeded under the PLAIN content key, and that is now the only key there
552
- // is: with no boundary set imposed, this tree IS what `perceive(grown)`
553
- // computes, so the memo entry is an ordinary cache hit rather than the
554
- // deliberate alias it had to be while the two folds differed. The entry
555
- // saves the pipeline re-folding the context it was just handed.
556
- data.perceiveMemo.set(perceiveKey(grown), tree);
557
- return tree;
558
- }
559
- /** Process one turn of a conversation.
560
- *
561
- * `turn` is the raw input for the latest turn — its bytes are appended
562
- * to the accumulated context directly (raw concatenation). The Mind
563
- * tracks the byte offset where each turn ends; no separator is ever
564
- * inserted or inspected.
565
- *
566
- * Returns the response AND the updated {@link ConversationState} so the
567
- * caller can persist it. The conversation handle's internal state is
568
- * updated in place — the returned state is a snapshot for storage.
569
- *
570
- * SINGLE FLIGHT: at most one respondTurn may be in flight per Mind. The
571
- * conversation's memo caches are swapped into the Mind-level per-response
572
- * pointers for the duration of the turn, so a concurrently-running
573
- * respond()/respondTurn() on the SAME Mind would interleave state.
574
- * Different Minds (or sequential awaits, as in every test) are safe. */
575
- async respondTurn(conv, turn, inspectRationale) {
576
- const data = this._conversations.get(conv.id);
577
- if (!data)
578
- throw new Error(`Conversation ${conv.id} not found`);
579
- const turnBytes = inputBytes(this, turn);
580
- // Incremental perception — O(turn) instead of O(context).
581
- this._growContext(data, turnBytes);
582
- const newContext = data.bytes;
583
- // The conversation's persistent memos and subtree cache are swapped in
584
- // by beginResponse (see there) — the SAME lifecycle respond() uses, so a
585
- // memo added in one place can never be missing from the other. A string
586
- // turn is text by nature and carries the text equivalence, same as
587
- // respond() (see _canonFor).
588
- //
589
- // No recognise-memo pre-seeding here: that used to be necessary because
590
- // the flat/positional fold lost visibility into an earlier turn's own
591
- // structure once later bytes shifted its position (foldTree no longer
592
- // visited the turn's root node). The STABLE-PREFIX fold (see {@link
593
- // ConversationData}) makes every turn's subtree independent of what
594
- // follows it by construction, so recognise() finds it correctly on its
595
- // own, first-touch, exactly once per turn.
596
- this.beginResponse(inspectRationale, this._canonFor(typeof turn === "string" ? textCanon : null), data);
597
- try {
598
- const response = await this._groundAndVoice(newContext, "respondTurn");
599
- // The REPLY joins the accumulated context the same way a turn does
600
- // ({@link addTurn}): raw byte append plus a boundary offset — never a
601
- // separator. A conversation's context is the full exchange, exactly
602
- // the cumulative continuous shape multi-turn training deposits, so a
603
- // later turn can refer to what was ANSWERED ("which of those two…"),
604
- // not only to what was asked.
605
- if (response.bytes.length > 0) {
606
- const start = data.bytes.length;
607
- this.addTurn(conv, response.bytes);
608
- data.answeredSpans.push([start, data.bytes.length]);
609
- }
610
- return { response, state: this.conversationState(conv) };
611
- }
612
- finally {
613
- this.endResponse(newContext.length);
614
- }
615
- }
616
- /** Text view of {@link respondTurn}. See {@link respondText} for the
617
- * NUL-stripping caveat. For binary or grid turns use {@link respondTurn}
618
- * directly — this is a text-only convenience, like {@link respondText}. */
619
- async respondTurnText(conv, turn, inspectRationale) {
620
- const { response, state } = await this.respondTurn(conv, turn, inspectRationale);
621
- return { response: decodeText(response.bytes), state };
622
- }
623
- async embedding(input) {
624
- return (await this.respond(input)).v;
625
- }
626
- /** Kinship note: the vector arm below is a miniature of recall's tier 3
627
- * (resonate → reach gate → read out the nearest form's bytes) — the
628
- * read-out direction of the same operation, without recall's grounding
629
- * ladder. If either side's acceptance rule changes, revisit the other. */
630
- async express(idOrV) {
631
- if (typeof idOrV === "number")
632
- return this.store.bytes(idOrV);
633
- const [hit] = await this.store.resonate(idOrV, 1);
634
- // The same confidence floor recall uses: a vector whose nearest stored
635
- // form sits below the reach threshold relates to NOTHING in the store —
636
- // returning that form's bytes anyway would fabricate an answer from an
637
- // unrelated neighbour. Silence is the honest read-out.
638
- if (hit && hit.score >= reachThreshold(this.space.maxGroup)) {
639
- return this.store.bytes(hit.id);
640
- }
641
- return new Uint8Array(0);
642
- }
643
- // ── Learning ─────────────────────────────────────────────────────────────
644
- /** See {@link import("./learning.js").ingest} — `onDeposit`, when given,
645
- * reports each ingested item's deposited root node ids
646
- * ({@link DepositReport}); purely observational. */
647
- async ingest(input, second, onDeposit) {
648
- invalidateStructuralCaches(this);
649
- invalidateJunctionCache(this);
650
- return ingest(this, input, second, onDeposit);
651
- }
652
- // ── Extension Surface ────────────────────────────────────────────────────
653
- extensionHost() {
654
- const mind = this;
655
- return {
656
- meaningOf: (bytes, anchors) => meaningOf(this, bytes, anchors),
657
- continuation: (bytes) => this.groundedContinuation(bytes),
658
- segment: (bytes) => segment(this, bytes).map((s) => ({ i: s.start, j: s.end })),
659
- get reach() {
660
- return mind.space.maxGroup;
661
- },
662
- };
663
- }
664
- async groundedContinuation(bytes) {
665
- const id = resolveImpl(this, bytes);
666
- if (id === null)
667
- return null;
668
- const grounded = await follow(this, id);
669
- if (grounded !== null && !bytesEqual(grounded, bytes))
670
- return grounded;
671
- return null;
672
- }
673
- // ── Content-index repair ───────────────────────────────────────────────
674
- /** Re-index structurally-important nodes whose gists were evicted from the
675
- * pending cache before they reached the content index. See {@link
676
- * Store.repairContentIndex} for the contract; this method wires the
677
- * Mind's perception into the store's repair walk.
678
- *
679
- * Run this after training or at checkpoints to restore recall reach for
680
- * nodes that bridge experiences but were never indexed. A pure interior
681
- * node (no edges, no halo) is deliberately skipped — it is scaffolding,
682
- * not an experience root or bridge, and regenerating its gist would waste
683
- * I/O and index space for no recall benefit.
684
- *
685
- * @param minParents only repair nodes with ≥ this many structural parents
686
- * (default 2 — structural bridges)
687
- * @returns number of nodes added to the content index */
688
- async repairContentIndex(minParents = 2) {
689
- return this.store.repairContentIndex(async (id) => {
690
- const bytes = this.store.bytes(id);
691
- if (bytes.length === 0)
692
- return null;
693
- return gistOf(this, bytes);
694
- }, minParents);
695
- }
696
- // ── Canonical-form index ───────────────────────────────────────────────
697
- /** Build (or incrementally refresh) the store's canonical-form index: for
698
- * every content-bearing node, record the hash of its CANONICAL key so
699
- * resolution can find stored forms across surface variation (case, width,
700
- * whitespace — whatever `canon` equates; see src/canon.ts).
701
- *
702
- * Incremental and idempotent: the last indexed node id is remembered in
703
- * store meta (`canon.upto`), so a refresh after further training scans
704
- * only the new rows. Run once after training, and again after ingests —
705
- * the same operational shape as {@link repairContentIndex}.
706
- *
707
- * @param canon the canonicalizer to index under — MUST be the same one
708
- * queries will carry (text queries carry {@link textCanon}
709
- * unless the Mind was constructed with its own)
710
- * @returns number of index rows added */
711
- async buildCanonIndex(canon) {
712
- const c = canon ?? this._canonFor(textCanon);
713
- const store = this.store;
714
- if (c === null || !store.canonAdd || !store.eachContent)
715
- return 0;
716
- const from = Number(await store.getMeta("canon.upto") ?? 0);
717
- let added = 0;
718
- let maxId = from - 1;
719
- store.eachContent((id, bytes) => {
720
- if (id > maxId)
721
- maxId = id;
722
- const key = c(bytes);
723
- if (key.length === 0)
724
- return;
725
- // Only index content whose canonical key DIFFERS from its raw bytes —
726
- // an already-canonical span is found by the exact lookup (and by the
727
- // fallback's own exact probe of the canonical bytes), so indexing it
728
- // would only add rows.
729
- if (bytesEqual(key, bytes))
730
- return;
731
- store.canonAdd(canonHash(key), id);
732
- added++;
733
- }, from);
734
- await store.setMeta("canon.upto", String(maxId + 1));
735
- store.commit();
736
- return added;
737
- }
738
- // ── Persistence ──────────────────────────────────────────────────────────
739
- async save() {
740
- const meta = new TextEncoder().encode(JSON.stringify(this.cfg));
741
- await this.store.saveSnapshot(meta);
742
- return meta;
743
- }
744
- static async load(snapshot, store) {
745
- const cfg = JSON.parse(new TextDecoder().decode(snapshot));
746
- return new Mind(cfg, store, true);
747
- }
748
- static async loadFromStore(store) {
749
- const meta = await store.loadSnapshot();
750
- if (!meta)
751
- throw new Error("no snapshot in store");
752
- return Mind.load(meta, store);
753
- }
754
- }