@hviana/sema 0.1.4 → 0.1.5

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 (122) hide show
  1. package/dist/example/demo.js +25 -25
  2. package/dist/example/train_base.d.ts +21 -19
  3. package/dist/example/train_base.js +1952 -1684
  4. package/dist/src/alphabet.d.ts +3 -3
  5. package/dist/src/alphabet.js +27 -24
  6. package/dist/src/alu/src/alu.d.ts +194 -169
  7. package/dist/src/alu/src/alu.js +414 -374
  8. package/dist/src/alu/src/expr.d.ts +43 -36
  9. package/dist/src/alu/src/expr.js +278 -252
  10. package/dist/src/alu/src/index.d.ts +98 -9
  11. package/dist/src/alu/src/index.js +63 -9
  12. package/dist/src/alu/src/kernel-arith.d.ts +5 -1
  13. package/dist/src/alu/src/kernel-arith.js +285 -195
  14. package/dist/src/alu/src/kernel-bits.d.ts +5 -1
  15. package/dist/src/alu/src/kernel-bits.js +115 -81
  16. package/dist/src/alu/src/kernel-logic.js +63 -33
  17. package/dist/src/alu/src/kernel-nd.js +195 -155
  18. package/dist/src/alu/src/kernel-numeric.d.ts +80 -16
  19. package/dist/src/alu/src/kernel-numeric.js +331 -259
  20. package/dist/src/alu/src/operation.d.ts +132 -112
  21. package/dist/src/alu/src/operation.js +163 -149
  22. package/dist/src/alu/src/parser.d.ts +175 -168
  23. package/dist/src/alu/src/parser.js +421 -382
  24. package/dist/src/alu/src/resonance.d.ts +25 -16
  25. package/dist/src/alu/src/resonance.js +56 -49
  26. package/dist/src/alu/src/text.d.ts +7 -3
  27. package/dist/src/alu/src/text.js +37 -31
  28. package/dist/src/alu/src/value.d.ts +14 -14
  29. package/dist/src/alu/src/value.js +160 -150
  30. package/dist/src/alu/test/alu.test.js +656 -543
  31. package/dist/src/bytes.d.ts +5 -1
  32. package/dist/src/bytes.js +40 -33
  33. package/dist/src/config.d.ts +102 -102
  34. package/dist/src/config.js +83 -83
  35. package/dist/src/derive/src/deduction.d.ts +62 -60
  36. package/dist/src/derive/src/deduction.js +109 -103
  37. package/dist/src/derive/src/index.d.ts +7 -1
  38. package/dist/src/derive/src/priority-queue.d.ts +8 -8
  39. package/dist/src/derive/src/priority-queue.js +61 -57
  40. package/dist/src/derive/src/rewrite.d.ts +18 -15
  41. package/dist/src/derive/src/rewrite.js +67 -59
  42. package/dist/src/derive/src/trie.d.ts +56 -56
  43. package/dist/src/derive/src/trie.js +179 -175
  44. package/dist/src/derive/test/derive.test.js +100 -96
  45. package/dist/src/extension.d.ts +16 -13
  46. package/dist/src/geometry.d.ts +42 -17
  47. package/dist/src/geometry.js +266 -235
  48. package/dist/src/index.d.ts +17 -2
  49. package/dist/src/index.js +7 -1
  50. package/dist/src/ingest-cache.d.ts +30 -25
  51. package/dist/src/ingest-cache.js +127 -108
  52. package/dist/src/mind/articulation.d.ts +5 -1
  53. package/dist/src/mind/articulation.js +112 -77
  54. package/dist/src/mind/attention.d.ts +108 -40
  55. package/dist/src/mind/attention.js +871 -749
  56. package/dist/src/mind/canonical.d.ts +19 -4
  57. package/dist/src/mind/canonical.js +31 -27
  58. package/dist/src/mind/graph-search.d.ts +225 -201
  59. package/dist/src/mind/graph-search.js +821 -742
  60. package/dist/src/mind/index.d.ts +10 -2
  61. package/dist/src/mind/junction.d.ts +58 -31
  62. package/dist/src/mind/junction.js +237 -172
  63. package/dist/src/mind/learning.d.ts +52 -16
  64. package/dist/src/mind/learning.js +165 -143
  65. package/dist/src/mind/match.d.ts +69 -20
  66. package/dist/src/mind/match.js +318 -259
  67. package/dist/src/mind/mechanisms/alu.js +16 -16
  68. package/dist/src/mind/mechanisms/cast.d.ts +13 -9
  69. package/dist/src/mind/mechanisms/cast.js +456 -363
  70. package/dist/src/mind/mechanisms/confluence.d.ts +12 -8
  71. package/dist/src/mind/mechanisms/confluence.js +183 -152
  72. package/dist/src/mind/mechanisms/cover.d.ts +8 -2
  73. package/dist/src/mind/mechanisms/cover.js +210 -148
  74. package/dist/src/mind/mechanisms/extraction.d.ts +34 -8
  75. package/dist/src/mind/mechanisms/extraction.js +288 -234
  76. package/dist/src/mind/mechanisms/recall.d.ts +10 -6
  77. package/dist/src/mind/mechanisms/recall.js +185 -126
  78. package/dist/src/mind/mind.d.ts +154 -129
  79. package/dist/src/mind/mind.js +288 -258
  80. package/dist/src/mind/pipeline-mechanism.d.ts +124 -112
  81. package/dist/src/mind/pipeline-mechanism.js +172 -161
  82. package/dist/src/mind/pipeline.d.ts +14 -4
  83. package/dist/src/mind/pipeline.js +189 -125
  84. package/dist/src/mind/primitives.d.ts +32 -8
  85. package/dist/src/mind/primitives.js +117 -99
  86. package/dist/src/mind/rationale.d.ts +98 -86
  87. package/dist/src/mind/rationale.js +121 -113
  88. package/dist/src/mind/reasoning.d.ts +13 -2
  89. package/dist/src/mind/reasoning.js +166 -129
  90. package/dist/src/mind/recognition.d.ts +4 -1
  91. package/dist/src/mind/recognition.js +208 -183
  92. package/dist/src/mind/resonance.d.ts +22 -5
  93. package/dist/src/mind/resonance.js +0 -0
  94. package/dist/src/mind/trace.d.ts +25 -6
  95. package/dist/src/mind/trace.js +58 -50
  96. package/dist/src/mind/traverse.d.ts +58 -16
  97. package/dist/src/mind/traverse.js +357 -304
  98. package/dist/src/mind/types.d.ts +127 -120
  99. package/dist/src/mind/types.js +69 -60
  100. package/dist/src/rabitq-hnsw/src/database.d.ts +179 -177
  101. package/dist/src/rabitq-hnsw/src/database.js +359 -342
  102. package/dist/src/rabitq-hnsw/src/heap.d.ts +12 -12
  103. package/dist/src/rabitq-hnsw/src/heap.js +80 -75
  104. package/dist/src/rabitq-hnsw/src/hnsw.d.ts +103 -103
  105. package/dist/src/rabitq-hnsw/src/hnsw.js +454 -428
  106. package/dist/src/rabitq-hnsw/src/index.d.ts +6 -1
  107. package/dist/src/rabitq-hnsw/src/prng.d.ts +10 -10
  108. package/dist/src/rabitq-hnsw/src/prng.js +27 -25
  109. package/dist/src/rabitq-hnsw/src/rabitq.d.ts +69 -69
  110. package/dist/src/rabitq-hnsw/src/rabitq.js +262 -246
  111. package/dist/src/rabitq-hnsw/src/store.d.ts +132 -132
  112. package/dist/src/rabitq-hnsw/src/store.js +843 -752
  113. package/dist/src/rabitq-hnsw/test/hnsw.test.js +1054 -805
  114. package/dist/src/sema.d.ts +13 -9
  115. package/dist/src/sema.js +40 -26
  116. package/dist/src/store-sqlite.d.ts +166 -144
  117. package/dist/src/store-sqlite.js +660 -578
  118. package/dist/src/store.d.ts +630 -593
  119. package/dist/src/store.js +1581 -1440
  120. package/dist/src/vec.d.ts +9 -5
  121. package/dist/src/vec.js +73 -61
  122. package/package.json +2 -2
@@ -10,20 +10,28 @@
10
10
  // Implementation split across src/mind/*.ts — this file assembles the Mind class.
11
11
  import { makeKeyring, rng, setVecConfig } from "../vec.js";
12
12
  import { Alphabet } from "../alphabet.js";
13
- import { reachThreshold, } from "../geometry.js";
13
+ import { reachThreshold } from "../geometry.js";
14
14
  import { BoundedMap } from "../store.js";
15
15
  import { SQliteStore } from "../store-sqlite.js";
16
16
  import { resolveConfig } from "../config.js";
17
17
  import { bytesEqual } from "../bytes.js";
18
- import { GraphSearch, } from "./graph-search.js";
18
+ import { GraphSearch } from "./graph-search.js";
19
19
  import { Alu } from "../alu/src/index.js";
20
- import { decodeText, Rationale, } from "./rationale.js";
21
- import { gistOf, inputBytes, perceive as perceiveImpl, resolve as resolveImpl, } from "./primitives.js";
20
+ import { decodeText, Rationale } from "./rationale.js";
21
+ import {
22
+ gistOf,
23
+ inputBytes,
24
+ perceive as perceiveImpl,
25
+ resolve as resolveImpl,
26
+ } from "./primitives.js";
22
27
  import { chooseNext, edgeAncestors as edgeAncestorsFn } from "./traverse.js";
23
28
  import { follow } from "./match.js";
24
29
  import { recognise, segment } from "./recognition.js";
25
30
  import { meaningOf } from "./resonance.js";
26
- import { climbAttention as climbAttentionFn, naturalBreak as naturalBreakFn, } from "./attention.js";
31
+ import {
32
+ climbAttention as climbAttentionFn,
33
+ naturalBreak as naturalBreakFn,
34
+ } from "./attention.js";
27
35
  import { aluToMechanism, defaultMechanisms, think } from "./pipeline.js";
28
36
  import { articulate } from "./articulation.js";
29
37
  import { ingest } from "./learning.js";
@@ -32,269 +40,291 @@ import { rItem } from "./trace.js";
32
40
  // THE MIND
33
41
  // ═══════════════════════════════════════════════════════════════════════════
34
42
  export class Mind {
35
- space;
36
- alphabet;
37
- store;
38
- cfg;
39
- /** The lightest-derivation engine over the Sema graph. */
40
- search;
41
- /** The grounding mechanisms iterated by {@link think}. */
42
- mechanisms = [];
43
- /** The live rationale tracer for the inference currently in flight, or null. */
44
- trace = null;
45
- /** Per-response memo of the consensus climb. NOTE: this memo and
46
- * {@link recogniseMemo} are BYPASSED while a rationale trace is attached
47
- * (every mechanism must emit its own steps), so a traced respond re-pays
48
- * up to four consensus climbs plus repeat recognitions — that is where the
49
- * traced-vs-untraced latency multiple comes from, by design. */
50
- climbMemo = null;
51
- /** Per-response memo of recognise() — see {@link MindContext.recogniseMemo}. */
52
- recogniseMemo = null;
53
- /** Per-response memo of perceive() — see {@link MindContext.perceiveMemo}. */
54
- perceiveMemo = null;
55
- /** The perceived gist of the query currently being answered. Set by `think`
56
- * before the graph search runs; `chooseNext` consults it as a gate (a null
57
- * guide means no query is in flight, so structural walkers keep plain
58
- * first-edge behaviour) and the reverse projection uses it for
59
- * reverse-recall disambiguation via `chooseAmong`. */
60
- _edgeGuide = null;
61
- /** Per-response memo of {@link chooseNext} picks — ensures every mechanism
62
- * of a single response follows the SAME continuation for each ambiguous
63
- * context node. */
64
- _edgeChoice = new Map();
65
- /** Previous deposit's seen node ids for incremental change detection. */
66
- _prevSeen = null;
67
- /** Session cache of node-id → perceived gist for candidate scoring — see
68
- * {@link MindContext._gistCache}. 32 MB ≈ 8K gists at D=1024; hub
69
- * candidate sets (√N at most) fit comfortably and recur across queries. */
70
- _gistCache = new BoundedMap(32_000_000, (v) => v.byteLength);
71
- // Deposit-path fold-pyramid cache (see MindContext) — ENTRY-count
72
- // bounded: a pyramid costs ~KB per content byte (one D-float gist per
73
- // interior node), and only the few live conversation chains need to stay
74
- // warm, so 8 entries is the honest budget.
75
- _depositTrees = new BoundedMap(8);
76
- _depositLens = new Set();
77
- _internIds = new WeakMap();
78
- // ── GraphSearchHost implementation ─────────────────────────────────────
79
- /** Canonical node id of a byte span. Required by GraphSearchHost & MindContext. */
80
- resolve(bytes) {
81
- return resolveImpl(this, bytes);
43
+ space;
44
+ alphabet;
45
+ store;
46
+ cfg;
47
+ /** The lightest-derivation engine over the Sema graph. */
48
+ search;
49
+ /** The grounding mechanisms iterated by {@link think}. */
50
+ mechanisms = [];
51
+ /** The live rationale tracer for the inference currently in flight, or null. */
52
+ trace = null;
53
+ /** Per-response memo of the consensus climb. NOTE: this memo and
54
+ * {@link recogniseMemo} are BYPASSED while a rationale trace is attached
55
+ * (every mechanism must emit its own steps), so a traced respond re-pays
56
+ * up to four consensus climbs plus repeat recognitions — that is where the
57
+ * traced-vs-untraced latency multiple comes from, by design. */
58
+ climbMemo = null;
59
+ /** Per-response memo of recognise() — see {@link MindContext.recogniseMemo}. */
60
+ recogniseMemo = null;
61
+ /** Per-response memo of perceive() — see {@link MindContext.perceiveMemo}. */
62
+ perceiveMemo = null;
63
+ /** The perceived gist of the query currently being answered. Set by `think`
64
+ * before the graph search runs; `chooseNext` consults it as a gate (a null
65
+ * guide means no query is in flight, so structural walkers keep plain
66
+ * first-edge behaviour) and the reverse projection uses it for
67
+ * reverse-recall disambiguation via `chooseAmong`. */
68
+ _edgeGuide = null;
69
+ /** Per-response memo of {@link chooseNext} picks — ensures every mechanism
70
+ * of a single response follows the SAME continuation for each ambiguous
71
+ * context node. */
72
+ _edgeChoice = new Map();
73
+ /** Previous deposit's seen node ids for incremental change detection. */
74
+ _prevSeen = null;
75
+ /** Session cache of node-id → perceived gist for candidate scoring — see
76
+ * {@link MindContext._gistCache}. 32 MB ≈ 8K gists at D=1024; hub
77
+ * candidate sets (√N at most) fit comfortably and recur across queries. */
78
+ _gistCache = new BoundedMap(32_000_000, (v) => v.byteLength);
79
+ // Deposit-path fold-pyramid cache (see MindContext) — ENTRY-count
80
+ // bounded: a pyramid costs ~KB per content byte (one D-float gist per
81
+ // interior node), and only the few live conversation chains need to stay
82
+ // warm, so 8 entries is the honest budget.
83
+ _depositTrees = new BoundedMap(8);
84
+ _depositLens = new Set();
85
+ _internIds = new WeakMap();
86
+ // ── GraphSearchHost implementation ─────────────────────────────────────
87
+ /** Canonical node id of a byte span. Required by GraphSearchHost & MindContext. */
88
+ resolve(bytes) {
89
+ return resolveImpl(this, bytes);
90
+ }
91
+ // recogniseSpan wraps recognise
92
+ recogniseSpan(bytes) {
93
+ const r = recognise(this, bytes);
94
+ return { sites: r.sites, leaves: r.leaves, splits: r.splits };
95
+ }
96
+ /** Disambiguate among multiple learnt continuations of the same context node.
97
+ * Required by {@link GraphSearchHost} — the graph search calls this through the
98
+ * host interface when a recognised form has more than one outgoing edge.
99
+ * Delegates to the standalone {@link chooseNext} which picks the candidate
100
+ * with the most distributional evidence (highest `prevOf` count — the
101
+ * structural manifestation of its halo). When evidence is equal the
102
+ * first-inserted edge wins. */
103
+ chooseNext(node) {
104
+ return chooseNext(this, node, this._edgeGuide);
105
+ }
106
+ constructor(optsOrCfg, storeArg, _fromStore) {
107
+ let userMechanisms = [];
108
+ let userFactories = [];
109
+ if (_fromStore !== undefined) {
110
+ this.cfg = resolveConfig(optsOrCfg);
111
+ this.store = storeArg;
112
+ } else {
113
+ const {
114
+ store: optsStore,
115
+ mechanisms: userMechs,
116
+ mechanismFactories: userFacts,
117
+ ...rest
118
+ } = optsOrCfg ?? {};
119
+ this.cfg = resolveConfig(rest);
120
+ this.store = optsStore ?? new SQliteStore({
121
+ maxGroup: this.cfg.geometry.maxGroup,
122
+ });
123
+ userMechanisms = userMechs ?? [];
124
+ userFactories = userFacts ?? [];
82
125
  }
83
- // recogniseSpan wraps recognise
84
- recogniseSpan(bytes) {
85
- const r = recognise(this, bytes);
86
- return { sites: r.sites, leaves: r.leaves, splits: r.splits };
126
+ setVecConfig({
127
+ normalizeEpsilon: this.cfg.normalizeEpsilon,
128
+ cosineEpsilon: this.cfg.cosineEpsilon,
129
+ });
130
+ const seedRand = rng((this.cfg.seed ^ 0x9e3779) >>> 0);
131
+ const seats = makeKeyring(
132
+ this.store.D,
133
+ Math.max(8, this.cfg.geometry.maxGroup),
134
+ seedRand,
135
+ );
136
+ this.space = {
137
+ D: this.store.D,
138
+ seats,
139
+ rand: rng((this.cfg.seed ^ 0x51f15e) >>> 0),
140
+ maxGroup: this.cfg.geometry.maxGroup,
141
+ };
142
+ this.alphabet = new Alphabet(
143
+ this.cfg.seed,
144
+ this.store.D,
145
+ this.cfg.alphabet,
146
+ );
147
+ this.search = new GraphSearch(this.store, this.space.maxGroup, this);
148
+ // Build the mechanism list: default grounding + ALU + user mechanisms.
149
+ for (const m of defaultMechanisms) {
150
+ this.mechanisms.push(m);
87
151
  }
88
- /** Disambiguate among multiple learnt continuations of the same context node.
89
- * Required by {@link GraphSearchHost} — the graph search calls this through the
90
- * host interface when a recognised form has more than one outgoing edge.
91
- * Delegates to the standalone {@link chooseNext} which picks the candidate
92
- * with the most distributional evidence (highest `prevOf` count — the
93
- * structural manifestation of its halo). When evidence is equal the
94
- * first-inserted edge wins. */
95
- chooseNext(node) {
96
- return chooseNext(this, node, this._edgeGuide);
152
+ const host = this.extensionHost();
153
+ if (this.cfg.alu.enabled) {
154
+ const alu = new Alu({
155
+ tol: this.cfg.alu.tol,
156
+ maxIter: this.cfg.alu.maxIter,
157
+ precision: this.cfg.alu.precision,
158
+ }, host);
159
+ this.mechanisms.push(aluToMechanism(alu));
97
160
  }
98
- constructor(optsOrCfg, storeArg, _fromStore) {
99
- let userMechanisms = [];
100
- let userFactories = [];
101
- if (_fromStore !== undefined) {
102
- this.cfg = resolveConfig(optsOrCfg);
103
- this.store = storeArg;
104
- }
105
- else {
106
- const { store: optsStore, mechanisms: userMechs, mechanismFactories: userFacts, ...rest } = (optsOrCfg ?? {});
107
- this.cfg = resolveConfig(rest);
108
- this.store = optsStore ?? new SQliteStore({
109
- maxGroup: this.cfg.geometry.maxGroup,
110
- });
111
- userMechanisms = userMechs ?? [];
112
- userFactories = userFacts ?? [];
113
- }
114
- setVecConfig({
115
- normalizeEpsilon: this.cfg.normalizeEpsilon,
116
- cosineEpsilon: this.cfg.cosineEpsilon,
117
- });
118
- const seedRand = rng((this.cfg.seed ^ 0x9e3779) >>> 0);
119
- const seats = makeKeyring(this.store.D, Math.max(8, this.cfg.geometry.maxGroup), seedRand);
120
- this.space = {
121
- D: this.store.D,
122
- seats,
123
- rand: rng((this.cfg.seed ^ 0x51f15e) >>> 0),
124
- maxGroup: this.cfg.geometry.maxGroup,
125
- };
126
- this.alphabet = new Alphabet(this.cfg.seed, this.store.D, this.cfg.alphabet);
127
- this.search = new GraphSearch(this.store, this.space.maxGroup, this);
128
- // Build the mechanism list: default grounding + ALU + user mechanisms.
129
- for (const m of defaultMechanisms)
130
- this.mechanisms.push(m);
131
- const host = this.extensionHost();
132
- if (this.cfg.alu.enabled) {
133
- const alu = new Alu({
134
- tol: this.cfg.alu.tol,
135
- maxIter: this.cfg.alu.maxIter,
136
- precision: this.cfg.alu.precision,
137
- }, host);
138
- this.mechanisms.push(aluToMechanism(alu));
139
- }
140
- for (const m of userMechanisms)
141
- this.mechanisms.push(m);
142
- for (const f of userFactories)
143
- this.mechanisms.push(f(host));
161
+ for (const m of userMechanisms) {
162
+ this.mechanisms.push(m);
144
163
  }
145
- // ── Public API ───────────────────────────────────────────────────────────
146
- /** Exposed for tests: the consensus climb over query sub-regions. */
147
- climbAttention(query, k, mode = "inverse") {
148
- return climbAttentionFn(this, query, k, mode);
164
+ for (const f of userFactories) {
165
+ this.mechanisms.push(f(host));
149
166
  }
150
- /** Exposed for tests: climb the structural DAG from a node to its
151
- * edge-bearing ancestor contexts. */
152
- edgeAncestors(id, contextCount) {
153
- return edgeAncestorsFn(this, id, contextCount);
167
+ }
168
+ // ── Public API ───────────────────────────────────────────────────────────
169
+ /** Exposed for tests: the consensus climb over query sub-regions. */
170
+ climbAttention(query, k, mode = "inverse") {
171
+ return climbAttentionFn(this, query, k, mode);
172
+ }
173
+ /** Exposed for tests: climb the structural DAG from a node to its
174
+ * edge-bearing ancestor contexts. */
175
+ edgeAncestors(id, contextCount) {
176
+ return edgeAncestorsFn(this, id, contextCount);
177
+ }
178
+ /** Exposed for tests: find the natural break point in a sorted vote list. */
179
+ naturalBreak(votes) {
180
+ return naturalBreakFn(votes);
181
+ }
182
+ // ── respond ───────────────────────────────────────────────────────────
183
+ /** Perceive input into a content-defined tree. Deterministic — identical
184
+ * bytes always produce an identical tree. Public for ingest-cache. */
185
+ perceive(input, leafAt, lookup) {
186
+ return perceiveImpl(this, input, leafAt, lookup);
187
+ }
188
+ /** Open one response's transient state — the tracer and the per-response
189
+ * memos. Paired with {@link endResponse}; the ONE place this state is
190
+ * created, so adding a memo cannot forget its reset. */
191
+ beginResponse(inspectRationale) {
192
+ this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
193
+ this.climbMemo = new WeakMap();
194
+ this.recogniseMemo = new WeakMap();
195
+ this.perceiveMemo = new Map();
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._edgeGuide = null;
205
+ this._edgeChoice.clear();
206
+ }
207
+ async respond(input, inspectRationale) {
208
+ this.beginResponse(inspectRationale);
209
+ try {
210
+ const inBytes = inputBytes(this, input);
211
+ const top = this.trace?.enter("respond", [
212
+ rItem(inBytes, "query"),
213
+ ]);
214
+ const thought = await think(this, inBytes, this.mechanisms);
215
+ if (thought === null) {
216
+ top?.done([], "nothing to perceive or an empty store — no answer");
217
+ return { v: null, bytes: new Uint8Array(0) };
218
+ }
219
+ const voiced = await articulate(this, thought.bytes, inBytes);
220
+ top?.done([
221
+ rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined),
222
+ ], "the answer, re-voiced in the asker's words");
223
+ return {
224
+ v: gistOf(this, voiced),
225
+ bytes: voiced,
226
+ provenance: thought.provenance,
227
+ };
228
+ } finally {
229
+ this.endResponse();
154
230
  }
155
- /** Exposed for tests: find the natural break point in a sorted vote list. */
156
- naturalBreak(votes) {
157
- return naturalBreakFn(votes);
231
+ }
232
+ /** Text view of {@link respond}. NUL bytes (0x00) are stripped before
233
+ * decoding — they are structural padding in text answers. LOSSY for a
234
+ * binary answer that legitimately contains NULs: use {@link respond} and
235
+ * read `bytes` directly for binary/grid modalities. */
236
+ async respondText(input, inspectRationale) {
237
+ const r = await this.respond(input, inspectRationale);
238
+ return decodeText(r.bytes);
239
+ }
240
+ async embedding(input) {
241
+ return (await this.respond(input)).v;
242
+ }
243
+ /** Kinship note: the vector arm below is a miniature of recall's tier 3
244
+ * (resonate → reach gate → read out the nearest form's bytes) — the
245
+ * read-out direction of the same operation, without recall's grounding
246
+ * ladder. If either side's acceptance rule changes, revisit the other. */
247
+ async express(idOrV) {
248
+ if (typeof idOrV === "number") {
249
+ return this.store.bytes(idOrV);
158
250
  }
159
- // ── respond ───────────────────────────────────────────────────────────
160
- /** Perceive input into a content-defined tree. Deterministic identical
161
- * bytes always produce an identical tree. Public for ingest-cache. */
162
- perceive(input, leafAt, lookup) {
163
- return perceiveImpl(this, input, leafAt, lookup);
251
+ const [hit] = await this.store.resonate(idOrV, 1);
252
+ // The same confidence floor recall uses: a vector whose nearest stored
253
+ // form sits below the reach threshold relates to NOTHING in the store —
254
+ // returning that form's bytes anyway would fabricate an answer from an
255
+ // unrelated neighbour. Silence is the honest read-out.
256
+ if (hit && hit.score >= reachThreshold(this.space.maxGroup)) {
257
+ return this.store.bytes(hit.id);
164
258
  }
165
- /** Open one response's transient state — the tracer and the per-response
166
- * memos. Paired with {@link endResponse}; the ONE place this state is
167
- * created, so adding a memo cannot forget its reset. */
168
- beginResponse(inspectRationale) {
169
- this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
170
- this.climbMemo = new WeakMap();
171
- this.recogniseMemo = new WeakMap();
172
- this.perceiveMemo = new Map();
259
+ return new Uint8Array(0);
260
+ }
261
+ // ── Learning ─────────────────────────────────────────────────────────────
262
+ async ingest(input, second) {
263
+ return ingest(this, input, second);
264
+ }
265
+ // ── Extension Surface ────────────────────────────────────────────────────
266
+ extensionHost() {
267
+ const mind = this;
268
+ return {
269
+ meaningOf: (bytes, anchors) => meaningOf(this, bytes, anchors),
270
+ continuation: (bytes) => this.groundedContinuation(bytes),
271
+ segment: (bytes) =>
272
+ segment(this, bytes).map((s) => ({ i: s.start, j: s.end })),
273
+ get reach() {
274
+ return mind.space.maxGroup;
275
+ },
276
+ };
277
+ }
278
+ async groundedContinuation(bytes) {
279
+ const id = resolveImpl(this, bytes);
280
+ if (id === null) {
281
+ return null;
173
282
  }
174
- /** Close one response's transient state — every per-response field, incl.
175
- * the edge guide/choices `think` sets mid-flight. */
176
- endResponse() {
177
- this.trace = null;
178
- this.climbMemo = null;
179
- this.recogniseMemo = null;
180
- this.perceiveMemo = null;
181
- this._edgeGuide = null;
182
- this._edgeChoice.clear();
283
+ const grounded = await follow(this, id);
284
+ if (grounded !== null && !bytesEqual(grounded, bytes)) {
285
+ return grounded;
183
286
  }
184
- async respond(input, inspectRationale) {
185
- this.beginResponse(inspectRationale);
186
- try {
187
- const inBytes = inputBytes(this, input);
188
- const top = this.trace?.enter("respond", [
189
- rItem(inBytes, "query"),
190
- ]);
191
- const thought = await think(this, inBytes, this.mechanisms);
192
- if (thought === null) {
193
- top?.done([], "nothing to perceive or an empty store no answer");
194
- return { v: null, bytes: new Uint8Array(0) };
195
- }
196
- const voiced = await articulate(this, thought.bytes, inBytes);
197
- top?.done([rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined)], "the answer, re-voiced in the asker's words");
198
- return {
199
- v: gistOf(this, voiced),
200
- bytes: voiced,
201
- provenance: thought.provenance,
202
- };
203
- }
204
- finally {
205
- this.endResponse();
206
- }
207
- }
208
- /** Text view of {@link respond}. NUL bytes (0x00) are stripped before
209
- * decoding — they are structural padding in text answers. LOSSY for a
210
- * binary answer that legitimately contains NULs: use {@link respond} and
211
- * read `bytes` directly for binary/grid modalities. */
212
- async respondText(input, inspectRationale) {
213
- const r = await this.respond(input, inspectRationale);
214
- return decodeText(r.bytes);
215
- }
216
- async embedding(input) {
217
- return (await this.respond(input)).v;
218
- }
219
- /** Kinship note: the vector arm below is a miniature of recall's tier 3
220
- * (resonate → reach gate → read out the nearest form's bytes) — the
221
- * read-out direction of the same operation, without recall's grounding
222
- * ladder. If either side's acceptance rule changes, revisit the other. */
223
- async express(idOrV) {
224
- if (typeof idOrV === "number")
225
- return this.store.bytes(idOrV);
226
- const [hit] = await this.store.resonate(idOrV, 1);
227
- // The same confidence floor recall uses: a vector whose nearest stored
228
- // form sits below the reach threshold relates to NOTHING in the store —
229
- // returning that form's bytes anyway would fabricate an answer from an
230
- // unrelated neighbour. Silence is the honest read-out.
231
- if (hit && hit.score >= reachThreshold(this.space.maxGroup)) {
232
- return this.store.bytes(hit.id);
233
- }
234
- return new Uint8Array(0);
235
- }
236
- // ── Learning ─────────────────────────────────────────────────────────────
237
- async ingest(input, second) {
238
- return ingest(this, input, second);
239
- }
240
- // ── Extension Surface ────────────────────────────────────────────────────
241
- extensionHost() {
242
- const mind = this;
243
- return {
244
- meaningOf: (bytes, anchors) => meaningOf(this, bytes, anchors),
245
- continuation: (bytes) => this.groundedContinuation(bytes),
246
- segment: (bytes) => segment(this, bytes).map((s) => ({ i: s.start, j: s.end })),
247
- get reach() {
248
- return mind.space.maxGroup;
249
- },
250
- };
251
- }
252
- async groundedContinuation(bytes) {
253
- const id = resolveImpl(this, bytes);
254
- if (id === null)
255
- return null;
256
- const grounded = await follow(this, id);
257
- if (grounded !== null && !bytesEqual(grounded, bytes))
258
- return grounded;
287
+ return null;
288
+ }
289
+ // ── Content-index repair ───────────────────────────────────────────────
290
+ /** Re-index structurally-important nodes whose gists were evicted from the
291
+ * pending cache before they reached the content index. See {@link
292
+ * Store.repairContentIndex} for the contract; this method wires the
293
+ * Mind's perception into the store's repair walk.
294
+ *
295
+ * Run this after training or at checkpoints to restore recall reach for
296
+ * nodes that bridge experiences but were never indexed. A pure interior
297
+ * node (no edges, no halo) is deliberately skipped — it is scaffolding,
298
+ * not an experience root or bridge, and regenerating its gist would waste
299
+ * I/O and index space for no recall benefit.
300
+ *
301
+ * @param minParents only repair nodes with ≥ this many structural parents
302
+ * (default 2 — structural bridges)
303
+ * @returns number of nodes added to the content index */
304
+ async repairContentIndex(minParents = 2) {
305
+ return this.store.repairContentIndex(async (id) => {
306
+ const bytes = this.store.bytes(id);
307
+ if (bytes.length === 0) {
259
308
  return null;
309
+ }
310
+ return gistOf(this, bytes);
311
+ }, minParents);
312
+ }
313
+ // ── Persistence ──────────────────────────────────────────────────────────
314
+ async save() {
315
+ const meta = new TextEncoder().encode(JSON.stringify(this.cfg));
316
+ await this.store.saveSnapshot(meta);
317
+ return meta;
318
+ }
319
+ static async load(snapshot, store) {
320
+ const cfg = JSON.parse(new TextDecoder().decode(snapshot));
321
+ return new Mind(cfg, store, true);
322
+ }
323
+ static async loadFromStore(store) {
324
+ const meta = await store.loadSnapshot();
325
+ if (!meta) {
326
+ throw new Error("no snapshot in store");
260
327
  }
261
- // ── Content-index repair ───────────────────────────────────────────────
262
- /** Re-index structurally-important nodes whose gists were evicted from the
263
- * pending cache before they reached the content index. See {@link
264
- * Store.repairContentIndex} for the contract; this method wires the
265
- * Mind's perception into the store's repair walk.
266
- *
267
- * Run this after training or at checkpoints to restore recall reach for
268
- * nodes that bridge experiences but were never indexed. A pure interior
269
- * node (no edges, no halo) is deliberately skipped — it is scaffolding,
270
- * not an experience root or bridge, and regenerating its gist would waste
271
- * I/O and index space for no recall benefit.
272
- *
273
- * @param minParents only repair nodes with ≥ this many structural parents
274
- * (default 2 — structural bridges)
275
- * @returns number of nodes added to the content index */
276
- async repairContentIndex(minParents = 2) {
277
- return this.store.repairContentIndex(async (id) => {
278
- const bytes = this.store.bytes(id);
279
- if (bytes.length === 0)
280
- return null;
281
- return gistOf(this, bytes);
282
- }, minParents);
283
- }
284
- // ── Persistence ──────────────────────────────────────────────────────────
285
- async save() {
286
- const meta = new TextEncoder().encode(JSON.stringify(this.cfg));
287
- await this.store.saveSnapshot(meta);
288
- return meta;
289
- }
290
- static async load(snapshot, store) {
291
- const cfg = JSON.parse(new TextDecoder().decode(snapshot));
292
- return new Mind(cfg, store, true);
293
- }
294
- static async loadFromStore(store) {
295
- const meta = await store.loadSnapshot();
296
- if (!meta)
297
- throw new Error("no snapshot in store");
298
- return Mind.load(meta, store);
299
- }
328
+ return Mind.load(meta, store);
329
+ }
300
330
  }