@hviana/sema 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +470 -0
- package/AUTHORS.md +12 -0
- package/COMMERCIAL-LICENSE.md +19 -0
- package/CONTRIBUTING.md +15 -0
- package/HOW_IT_WORKS.md +4210 -0
- package/LICENSE.md +117 -0
- package/README.md +290 -0
- package/TRADEMARKS.md +19 -0
- package/example/demo.ts +46 -0
- package/example/train_base.ts +2675 -0
- package/index.html +893 -0
- package/package.json +25 -0
- package/src/alphabet.ts +34 -0
- package/src/alu/README.md +332 -0
- package/src/alu/src/alu.ts +541 -0
- package/src/alu/src/expr.ts +339 -0
- package/src/alu/src/index.ts +115 -0
- package/src/alu/src/kernel-arith.ts +377 -0
- package/src/alu/src/kernel-bits.ts +199 -0
- package/src/alu/src/kernel-logic.ts +102 -0
- package/src/alu/src/kernel-nd.ts +235 -0
- package/src/alu/src/kernel-numeric.ts +466 -0
- package/src/alu/src/operation.ts +344 -0
- package/src/alu/src/parser.ts +574 -0
- package/src/alu/src/resonance.ts +161 -0
- package/src/alu/src/text.ts +83 -0
- package/src/alu/src/value.ts +327 -0
- package/src/alu/test/alu.test.ts +1004 -0
- package/src/bytes.ts +62 -0
- package/src/config.ts +227 -0
- package/src/derive/README.md +295 -0
- package/src/derive/src/deduction.ts +263 -0
- package/src/derive/src/index.ts +24 -0
- package/src/derive/src/priority-queue.ts +70 -0
- package/src/derive/src/rewrite.ts +127 -0
- package/src/derive/src/trie.ts +242 -0
- package/src/derive/test/derive.test.ts +137 -0
- package/src/extension.ts +42 -0
- package/src/geometry.ts +511 -0
- package/src/index.ts +38 -0
- package/src/ingest-cache.ts +224 -0
- package/src/mind/articulation.ts +137 -0
- package/src/mind/attention.ts +1061 -0
- package/src/mind/canonical.ts +107 -0
- package/src/mind/graph-search.ts +1100 -0
- package/src/mind/index.ts +18 -0
- package/src/mind/junction.ts +347 -0
- package/src/mind/learning.ts +246 -0
- package/src/mind/match.ts +507 -0
- package/src/mind/mechanisms/alu.ts +33 -0
- package/src/mind/mechanisms/cast.ts +568 -0
- package/src/mind/mechanisms/confluence.ts +268 -0
- package/src/mind/mechanisms/cover.ts +248 -0
- package/src/mind/mechanisms/extraction.ts +422 -0
- package/src/mind/mechanisms/recall.ts +241 -0
- package/src/mind/mind.ts +483 -0
- package/src/mind/pipeline-mechanism.ts +326 -0
- package/src/mind/pipeline.ts +300 -0
- package/src/mind/primitives.ts +201 -0
- package/src/mind/rationale.ts +275 -0
- package/src/mind/reasoning.ts +198 -0
- package/src/mind/recognition.ts +234 -0
- package/src/mind/resonance.ts +0 -0
- package/src/mind/trace.ts +108 -0
- package/src/mind/traverse.ts +556 -0
- package/src/mind/types.ts +281 -0
- package/src/rabitq-hnsw/README.md +303 -0
- package/src/rabitq-hnsw/src/database.ts +492 -0
- package/src/rabitq-hnsw/src/heap.ts +90 -0
- package/src/rabitq-hnsw/src/hnsw.ts +514 -0
- package/src/rabitq-hnsw/src/index.ts +15 -0
- package/src/rabitq-hnsw/src/prng.ts +39 -0
- package/src/rabitq-hnsw/src/rabitq.ts +308 -0
- package/src/rabitq-hnsw/src/store.ts +994 -0
- package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
- package/src/store-sqlite.ts +928 -0
- package/src/store.ts +2148 -0
- package/src/vec.ts +124 -0
- package/test/00-extract.test.mjs +151 -0
- package/test/01-floor.test.mjs +20 -0
- package/test/02-roundtrip.test.mjs +83 -0
- package/test/03-recall.test.mjs +98 -0
- package/test/04-think.test.mjs +627 -0
- package/test/05-concepts.test.mjs +84 -0
- package/test/08-storage.test.mjs +948 -0
- package/test/09-edges.test.mjs +65 -0
- package/test/11-universality.test.mjs +180 -0
- package/test/13-conversation.test.mjs +228 -0
- package/test/14-scaling.test.mjs +503 -0
- package/test/15-decomposition-gap.test.mjs +0 -0
- package/test/16-bridge.test.mjs +250 -0
- package/test/17-intelligence.test.mjs +240 -0
- package/test/18-alu.test.mjs +209 -0
- package/test/19-nd.test.mjs +254 -0
- package/test/20-stability.test.mjs +489 -0
- package/test/21-partial.test.mjs +158 -0
- package/test/22-multihop.test.mjs +130 -0
- package/test/23-rationale.test.mjs +316 -0
- package/test/24-generalization.test.mjs +416 -0
- package/test/25-embedding.test.mjs +75 -0
- package/test/26-cooperative.test.mjs +89 -0
- package/test/27-saturation-drop.test.mjs +637 -0
- package/test/28-unknowable.test.mjs +88 -0
- package/test/29-counterfactual.test.mjs +476 -0
- package/test/30-conflict-resolution.test.mjs +166 -0
- package/test/31-audit.test.mjs +288 -0
- package/test/32-confluence.test.mjs +173 -0
- package/test/33-multi-candidate.test.mjs +222 -0
- package/test/34-cross-region.test.mjs +252 -0
- package/tsconfig.json +16 -0
package/src/mind/mind.ts
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
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
|
+
|
|
12
|
+
import { cosine, makeKeyring, rng, setVecConfig, Vec } from "../vec.js";
|
|
13
|
+
import { bindSeat, fold, Sema, Space } from "../sema.js";
|
|
14
|
+
import { Alphabet } from "../alphabet.js";
|
|
15
|
+
import {
|
|
16
|
+
bytesToTree,
|
|
17
|
+
Grid,
|
|
18
|
+
gridToTree,
|
|
19
|
+
hilbertBytes,
|
|
20
|
+
reachThreshold,
|
|
21
|
+
stackGrids,
|
|
22
|
+
} from "../geometry.js";
|
|
23
|
+
import { BoundedMap, type Store } from "../store.js";
|
|
24
|
+
import { SQliteStore } from "../store-sqlite.js";
|
|
25
|
+
import { type MindConfig, resolveConfig } from "../config.js";
|
|
26
|
+
import {
|
|
27
|
+
type CandidateSpan,
|
|
28
|
+
coverSequence,
|
|
29
|
+
lightestDerivation,
|
|
30
|
+
} from "../derive/src/index.js";
|
|
31
|
+
import { bytesEqual, concat2, concatBytes, indexOf } from "../bytes.js";
|
|
32
|
+
import {
|
|
33
|
+
type ComputedResult,
|
|
34
|
+
type DerivationItem,
|
|
35
|
+
type DerivationStep,
|
|
36
|
+
GraphSearch,
|
|
37
|
+
type Leaf,
|
|
38
|
+
type Seg,
|
|
39
|
+
type Site,
|
|
40
|
+
} from "./graph-search.js";
|
|
41
|
+
import { Alu } from "../alu/src/index.js";
|
|
42
|
+
import type { ComputedSpan, ExtensionHost } from "../extension.js";
|
|
43
|
+
|
|
44
|
+
export type { ComputedSpan, ExtensionHost };
|
|
45
|
+
import {
|
|
46
|
+
decodeText,
|
|
47
|
+
type InspectRationale,
|
|
48
|
+
Rationale,
|
|
49
|
+
type RationaleItem,
|
|
50
|
+
} from "./rationale.js";
|
|
51
|
+
|
|
52
|
+
export type {
|
|
53
|
+
InspectRationale,
|
|
54
|
+
RationaleItem,
|
|
55
|
+
RationaleStep,
|
|
56
|
+
} from "./rationale.js";
|
|
57
|
+
|
|
58
|
+
// Public types re-exported
|
|
59
|
+
export type Input = string | Uint8Array | Grid | Grid[];
|
|
60
|
+
|
|
61
|
+
export interface Response {
|
|
62
|
+
v: Vec | null;
|
|
63
|
+
bytes: Uint8Array;
|
|
64
|
+
/** How the answer was grounded (see {@link Provenance}). `"recall-echo"`
|
|
65
|
+
* marks the last-resort fallback that returned the nearest stored form's
|
|
66
|
+
* own bytes verbatim — an echo, NOT a grounded fact. Absent when there is
|
|
67
|
+
* no answer. */
|
|
68
|
+
provenance?: import("./pipeline.js").Provenance;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Mind module imports
|
|
72
|
+
import type { AttentionRead, MindContext, Recognition } from "./types.js";
|
|
73
|
+
import { changedNodes, liftAnswer, spliceAll } from "./types.js";
|
|
74
|
+
import {
|
|
75
|
+
foldTree,
|
|
76
|
+
gistOf,
|
|
77
|
+
inputBytes,
|
|
78
|
+
perceive as perceiveImpl,
|
|
79
|
+
read,
|
|
80
|
+
resolve as resolveImpl,
|
|
81
|
+
} from "./primitives.js";
|
|
82
|
+
import { chooseNext, edgeAncestors as edgeAncestorsFn } from "./traverse.js";
|
|
83
|
+
import { follow } from "./match.js";
|
|
84
|
+
import { recognise, segment } from "./recognition.js";
|
|
85
|
+
import { meaningOf } from "./resonance.js";
|
|
86
|
+
import {
|
|
87
|
+
climbAttention as climbAttentionFn,
|
|
88
|
+
naturalBreak as naturalBreakFn,
|
|
89
|
+
} from "./attention.js";
|
|
90
|
+
import { aluToMechanism, defaultMechanisms, think } from "./pipeline.js";
|
|
91
|
+
import { articulate } from "./articulation.js";
|
|
92
|
+
import { ingest } from "./learning.js";
|
|
93
|
+
import { rItem } from "./trace.js";
|
|
94
|
+
|
|
95
|
+
// ── MindOptions ───────────────────────────────────────────────────────────
|
|
96
|
+
|
|
97
|
+
export interface MindOptions {
|
|
98
|
+
seed?: number;
|
|
99
|
+
recallQueryK?: number;
|
|
100
|
+
haloQueryK?: number;
|
|
101
|
+
normalizeEpsilon?: number;
|
|
102
|
+
cosineEpsilon?: number;
|
|
103
|
+
geometry?: Partial<import("../config.js").GeometryConfig>;
|
|
104
|
+
alphabet?: Partial<import("../config.js").AlphabetConfig>;
|
|
105
|
+
storeConfig?: Partial<import("../config.js").StoreConfig>;
|
|
106
|
+
store?: Store;
|
|
107
|
+
/** Additional grounding mechanisms (appended after the built-in defaults). */
|
|
108
|
+
mechanisms?: import("./pipeline-mechanism.js").PipelineMechanism[];
|
|
109
|
+
/** Factories that receive the {@link ExtensionHost} and return mechanisms. */
|
|
110
|
+
mechanismFactories?: ((
|
|
111
|
+
host: import("../extension.js").ExtensionHost,
|
|
112
|
+
) => import("./pipeline-mechanism.js").PipelineMechanism)[];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
116
|
+
// THE MIND
|
|
117
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
118
|
+
|
|
119
|
+
export class Mind implements MindContext {
|
|
120
|
+
readonly space: Space;
|
|
121
|
+
readonly alphabet: Alphabet;
|
|
122
|
+
readonly store: Store;
|
|
123
|
+
readonly cfg: MindConfig;
|
|
124
|
+
|
|
125
|
+
/** The lightest-derivation engine over the Sema graph. */
|
|
126
|
+
readonly search: GraphSearch;
|
|
127
|
+
|
|
128
|
+
/** The grounding mechanisms iterated by {@link think}. */
|
|
129
|
+
readonly mechanisms: import("./pipeline-mechanism.js").PipelineMechanism[] =
|
|
130
|
+
[];
|
|
131
|
+
|
|
132
|
+
/** The live rationale tracer for the inference currently in flight, or null. */
|
|
133
|
+
trace: Rationale | null = null;
|
|
134
|
+
|
|
135
|
+
/** Per-response memo of the consensus climb. NOTE: this memo and
|
|
136
|
+
* {@link recogniseMemo} are BYPASSED while a rationale trace is attached
|
|
137
|
+
* (every mechanism must emit its own steps), so a traced respond re-pays
|
|
138
|
+
* up to four consensus climbs plus repeat recognitions — that is where the
|
|
139
|
+
* traced-vs-untraced latency multiple comes from, by design. */
|
|
140
|
+
climbMemo: WeakMap<Uint8Array, Map<string, AttentionRead>> | null = null;
|
|
141
|
+
|
|
142
|
+
/** Per-response memo of recognise() — see {@link MindContext.recogniseMemo}. */
|
|
143
|
+
recogniseMemo: WeakMap<Uint8Array, Recognition> | null = null;
|
|
144
|
+
|
|
145
|
+
/** Per-response memo of perceive() — see {@link MindContext.perceiveMemo}. */
|
|
146
|
+
perceiveMemo: Map<string, import("../sema.js").Sema> | null = null;
|
|
147
|
+
|
|
148
|
+
/** The perceived gist of the query currently being answered. Set by `think`
|
|
149
|
+
* before the graph search runs; `chooseNext` consults it as a gate (a null
|
|
150
|
+
* guide means no query is in flight, so structural walkers keep plain
|
|
151
|
+
* first-edge behaviour) and the reverse projection uses it for
|
|
152
|
+
* reverse-recall disambiguation via `chooseAmong`. */
|
|
153
|
+
_edgeGuide: Vec | null = null;
|
|
154
|
+
/** Per-response memo of {@link chooseNext} picks — ensures every mechanism
|
|
155
|
+
* of a single response follows the SAME continuation for each ambiguous
|
|
156
|
+
* context node. */
|
|
157
|
+
_edgeChoice = new Map<number, number>();
|
|
158
|
+
|
|
159
|
+
/** Previous deposit's seen node ids for incremental change detection. */
|
|
160
|
+
_prevSeen: Set<number> | null = null;
|
|
161
|
+
|
|
162
|
+
/** Session cache of node-id → perceived gist for candidate scoring — see
|
|
163
|
+
* {@link MindContext._gistCache}. 32 MB ≈ 8K gists at D=1024; hub
|
|
164
|
+
* candidate sets (√N at most) fit comfortably and recur across queries. */
|
|
165
|
+
_gistCache = new BoundedMap<number, Vec>(
|
|
166
|
+
32_000_000,
|
|
167
|
+
(v) => v.byteLength,
|
|
168
|
+
);
|
|
169
|
+
// Deposit-path fold-pyramid cache (see MindContext) — ENTRY-count
|
|
170
|
+
// bounded: a pyramid costs ~KB per content byte (one D-float gist per
|
|
171
|
+
// interior node), and only the few live conversation chains need to stay
|
|
172
|
+
// warm, so 8 entries is the honest budget.
|
|
173
|
+
_depositTrees = new BoundedMap<string, import("../geometry.js").FoldPyramid>(
|
|
174
|
+
8,
|
|
175
|
+
);
|
|
176
|
+
_depositLens = new Set<number>();
|
|
177
|
+
_internIds = new WeakMap<import("../sema.js").Sema, number>();
|
|
178
|
+
|
|
179
|
+
// ── GraphSearchHost implementation ─────────────────────────────────────
|
|
180
|
+
|
|
181
|
+
/** Canonical node id of a byte span. Required by GraphSearchHost & MindContext. */
|
|
182
|
+
resolve(bytes: Uint8Array): number | null {
|
|
183
|
+
return resolveImpl(this, bytes);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// recogniseSpan wraps recognise
|
|
187
|
+
recogniseSpan(bytes: Uint8Array): {
|
|
188
|
+
sites: ReadonlyArray<Site>;
|
|
189
|
+
leaves: ReadonlyArray<Leaf>;
|
|
190
|
+
splits: ReadonlySet<number>;
|
|
191
|
+
} {
|
|
192
|
+
const r = recognise(this, bytes);
|
|
193
|
+
return { sites: r.sites, leaves: r.leaves, splits: r.splits };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Disambiguate among multiple learnt continuations of the same context node.
|
|
197
|
+
* Required by {@link GraphSearchHost} — the graph search calls this through the
|
|
198
|
+
* host interface when a recognised form has more than one outgoing edge.
|
|
199
|
+
* Delegates to the standalone {@link chooseNext} which picks the candidate
|
|
200
|
+
* with the most distributional evidence (highest `prevOf` count — the
|
|
201
|
+
* structural manifestation of its halo). When evidence is equal the
|
|
202
|
+
* first-inserted edge wins. */
|
|
203
|
+
chooseNext(node: number): number | undefined {
|
|
204
|
+
return chooseNext(this, node, this._edgeGuide);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ── construction ─────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
constructor(opts?: MindOptions);
|
|
210
|
+
constructor(cfg: MindConfig, store: Store, _fromStore: true);
|
|
211
|
+
constructor(
|
|
212
|
+
optsOrCfg?: MindOptions | MindConfig,
|
|
213
|
+
storeArg?: Store,
|
|
214
|
+
_fromStore?: true,
|
|
215
|
+
) {
|
|
216
|
+
let userMechanisms: import("./pipeline-mechanism.js").PipelineMechanism[] =
|
|
217
|
+
[];
|
|
218
|
+
let userFactories: ((
|
|
219
|
+
host: import("../extension.js").ExtensionHost,
|
|
220
|
+
) => import("./pipeline-mechanism.js").PipelineMechanism)[] = [];
|
|
221
|
+
if (_fromStore !== undefined) {
|
|
222
|
+
this.cfg = resolveConfig(optsOrCfg as Partial<MindConfig>);
|
|
223
|
+
this.store = storeArg!;
|
|
224
|
+
} else {
|
|
225
|
+
const {
|
|
226
|
+
store: optsStore,
|
|
227
|
+
mechanisms: userMechs,
|
|
228
|
+
mechanismFactories: userFacts,
|
|
229
|
+
...rest
|
|
230
|
+
} = (optsOrCfg ?? {}) as MindOptions;
|
|
231
|
+
this.cfg = resolveConfig(rest as Partial<MindConfig>);
|
|
232
|
+
this.store = optsStore ?? new SQliteStore({
|
|
233
|
+
maxGroup: this.cfg.geometry.maxGroup,
|
|
234
|
+
});
|
|
235
|
+
userMechanisms = userMechs ?? [];
|
|
236
|
+
userFactories = userFacts ?? [];
|
|
237
|
+
}
|
|
238
|
+
setVecConfig({
|
|
239
|
+
normalizeEpsilon: this.cfg.normalizeEpsilon,
|
|
240
|
+
cosineEpsilon: this.cfg.cosineEpsilon,
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const seedRand = rng((this.cfg.seed ^ 0x9e3779) >>> 0);
|
|
244
|
+
const seats = makeKeyring(
|
|
245
|
+
this.store.D,
|
|
246
|
+
Math.max(8, this.cfg.geometry.maxGroup),
|
|
247
|
+
seedRand,
|
|
248
|
+
);
|
|
249
|
+
this.space = {
|
|
250
|
+
D: this.store.D,
|
|
251
|
+
seats,
|
|
252
|
+
rand: rng((this.cfg.seed ^ 0x51f15e) >>> 0),
|
|
253
|
+
maxGroup: this.cfg.geometry.maxGroup,
|
|
254
|
+
};
|
|
255
|
+
this.alphabet = new Alphabet(
|
|
256
|
+
this.cfg.seed,
|
|
257
|
+
this.store.D,
|
|
258
|
+
this.cfg.alphabet,
|
|
259
|
+
);
|
|
260
|
+
this.search = new GraphSearch(
|
|
261
|
+
this.store,
|
|
262
|
+
this.space.maxGroup,
|
|
263
|
+
this, // MindContext extends GraphSearchHost
|
|
264
|
+
);
|
|
265
|
+
// Build the mechanism list: default grounding + ALU + user mechanisms.
|
|
266
|
+
for (const m of defaultMechanisms) this.mechanisms.push(m);
|
|
267
|
+
|
|
268
|
+
const host = this.extensionHost();
|
|
269
|
+
if (this.cfg.alu.enabled) {
|
|
270
|
+
const alu = new Alu({
|
|
271
|
+
tol: this.cfg.alu.tol,
|
|
272
|
+
maxIter: this.cfg.alu.maxIter,
|
|
273
|
+
precision: this.cfg.alu.precision,
|
|
274
|
+
}, host);
|
|
275
|
+
this.mechanisms.push(aluToMechanism(alu));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
for (const m of userMechanisms) this.mechanisms.push(m);
|
|
279
|
+
for (const f of userFactories) this.mechanisms.push(f(host));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ── Public API ───────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
/** Exposed for tests: the consensus climb over query sub-regions. */
|
|
285
|
+
climbAttention(
|
|
286
|
+
query: Uint8Array,
|
|
287
|
+
k: number,
|
|
288
|
+
mode: import("./types.js").DFMode = "inverse",
|
|
289
|
+
): Promise<import("./types.js").Attention[]> {
|
|
290
|
+
return climbAttentionFn(this, query, k, mode);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Exposed for tests: climb the structural DAG from a node to its
|
|
294
|
+
* edge-bearing ancestor contexts. */
|
|
295
|
+
edgeAncestors(
|
|
296
|
+
id: number,
|
|
297
|
+
contextCount: number,
|
|
298
|
+
): import("./types.js").AncestorReach {
|
|
299
|
+
return edgeAncestorsFn(this, id, contextCount);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Exposed for tests: find the natural break point in a sorted vote list. */
|
|
303
|
+
naturalBreak(votes: number[]): number {
|
|
304
|
+
return naturalBreakFn(votes);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ── respond ───────────────────────────────────────────────────────────
|
|
308
|
+
|
|
309
|
+
/** Perceive input into a content-defined tree. Deterministic — identical
|
|
310
|
+
* bytes always produce an identical tree. Public for ingest-cache. */
|
|
311
|
+
perceive(
|
|
312
|
+
input: Input,
|
|
313
|
+
leafAt?: (i: number) => number | null,
|
|
314
|
+
lookup?: (ids: number[]) => number | null,
|
|
315
|
+
): Sema {
|
|
316
|
+
return perceiveImpl(this, input, leafAt, lookup);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Open one response's transient state — the tracer and the per-response
|
|
320
|
+
* memos. Paired with {@link endResponse}; the ONE place this state is
|
|
321
|
+
* created, so adding a memo cannot forget its reset. */
|
|
322
|
+
private beginResponse(inspectRationale?: InspectRationale): void {
|
|
323
|
+
this.trace = inspectRationale ? new Rationale(inspectRationale) : null;
|
|
324
|
+
this.climbMemo = new WeakMap();
|
|
325
|
+
this.recogniseMemo = new WeakMap();
|
|
326
|
+
this.perceiveMemo = new Map();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Close one response's transient state — every per-response field, incl.
|
|
330
|
+
* the edge guide/choices `think` sets mid-flight. */
|
|
331
|
+
private endResponse(): void {
|
|
332
|
+
this.trace = null;
|
|
333
|
+
this.climbMemo = null;
|
|
334
|
+
this.recogniseMemo = null;
|
|
335
|
+
this.perceiveMemo = null;
|
|
336
|
+
this._edgeGuide = null;
|
|
337
|
+
this._edgeChoice.clear();
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
async respond(
|
|
341
|
+
input: Input,
|
|
342
|
+
inspectRationale?: InspectRationale,
|
|
343
|
+
): Promise<Response> {
|
|
344
|
+
this.beginResponse(inspectRationale);
|
|
345
|
+
try {
|
|
346
|
+
const inBytes = inputBytes(this, input);
|
|
347
|
+
const top = this.trace?.enter("respond", [
|
|
348
|
+
rItem(inBytes, "query"),
|
|
349
|
+
]);
|
|
350
|
+
|
|
351
|
+
const thought = await think(this, inBytes, this.mechanisms);
|
|
352
|
+
if (thought === null) {
|
|
353
|
+
top?.done([], "nothing to perceive or an empty store — no answer");
|
|
354
|
+
return { v: null, bytes: new Uint8Array(0) };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const voiced = await articulate(this, thought.bytes, inBytes);
|
|
358
|
+
top?.done(
|
|
359
|
+
[rItem(voiced, "answer", resolveImpl(this, voiced) ?? undefined)],
|
|
360
|
+
"the answer, re-voiced in the asker's words",
|
|
361
|
+
);
|
|
362
|
+
return {
|
|
363
|
+
v: gistOf(this, voiced),
|
|
364
|
+
bytes: voiced,
|
|
365
|
+
provenance: thought.provenance,
|
|
366
|
+
};
|
|
367
|
+
} finally {
|
|
368
|
+
this.endResponse();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Text view of {@link respond}. NUL bytes (0x00) are stripped before
|
|
373
|
+
* decoding — they are structural padding in text answers. LOSSY for a
|
|
374
|
+
* binary answer that legitimately contains NULs: use {@link respond} and
|
|
375
|
+
* read `bytes` directly for binary/grid modalities. */
|
|
376
|
+
async respondText(
|
|
377
|
+
input: string,
|
|
378
|
+
inspectRationale?: InspectRationale,
|
|
379
|
+
): Promise<string> {
|
|
380
|
+
const r = await this.respond(input, inspectRationale);
|
|
381
|
+
return decodeText(r.bytes);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async embedding(input: Input): Promise<Vec | null> {
|
|
385
|
+
return (await this.respond(input)).v;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Kinship note: the vector arm below is a miniature of recall's tier 3
|
|
389
|
+
* (resonate → reach gate → read out the nearest form's bytes) — the
|
|
390
|
+
* read-out direction of the same operation, without recall's grounding
|
|
391
|
+
* ladder. If either side's acceptance rule changes, revisit the other. */
|
|
392
|
+
async express(idOrV: number | Vec): Promise<Uint8Array> {
|
|
393
|
+
if (typeof idOrV === "number") return this.store.bytes(idOrV);
|
|
394
|
+
const [hit] = await this.store.resonate(idOrV, 1);
|
|
395
|
+
// The same confidence floor recall uses: a vector whose nearest stored
|
|
396
|
+
// form sits below the reach threshold relates to NOTHING in the store —
|
|
397
|
+
// returning that form's bytes anyway would fabricate an answer from an
|
|
398
|
+
// unrelated neighbour. Silence is the honest read-out.
|
|
399
|
+
if (hit && hit.score >= reachThreshold(this.space.maxGroup)) {
|
|
400
|
+
return this.store.bytes(hit.id);
|
|
401
|
+
}
|
|
402
|
+
return new Uint8Array(0);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// ── Learning ─────────────────────────────────────────────────────────────
|
|
406
|
+
|
|
407
|
+
async ingest(
|
|
408
|
+
input: Input | (Input | [Input, Input])[],
|
|
409
|
+
second?: Input,
|
|
410
|
+
): Promise<(Sema & { id: number }) | undefined> {
|
|
411
|
+
return ingest(this, input, second);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// ── Extension Surface ────────────────────────────────────────────────────
|
|
415
|
+
|
|
416
|
+
private extensionHost(): ExtensionHost {
|
|
417
|
+
const mind = this;
|
|
418
|
+
return {
|
|
419
|
+
meaningOf: (bytes, anchors) => meaningOf(this, bytes, anchors),
|
|
420
|
+
continuation: (bytes) => this.groundedContinuation(bytes),
|
|
421
|
+
segment: (bytes) =>
|
|
422
|
+
segment(this, bytes).map((s) => ({ i: s.start, j: s.end })),
|
|
423
|
+
get reach() {
|
|
424
|
+
return mind.space.maxGroup;
|
|
425
|
+
},
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private async groundedContinuation(
|
|
430
|
+
bytes: Uint8Array,
|
|
431
|
+
): Promise<Uint8Array | null> {
|
|
432
|
+
const id = resolveImpl(this, bytes);
|
|
433
|
+
if (id === null) return null;
|
|
434
|
+
const grounded = await follow(this, id);
|
|
435
|
+
if (grounded !== null && !bytesEqual(grounded, bytes)) return grounded;
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ── Content-index repair ───────────────────────────────────────────────
|
|
440
|
+
|
|
441
|
+
/** Re-index structurally-important nodes whose gists were evicted from the
|
|
442
|
+
* pending cache before they reached the content index. See {@link
|
|
443
|
+
* Store.repairContentIndex} for the contract; this method wires the
|
|
444
|
+
* Mind's perception into the store's repair walk.
|
|
445
|
+
*
|
|
446
|
+
* Run this after training or at checkpoints to restore recall reach for
|
|
447
|
+
* nodes that bridge experiences but were never indexed. A pure interior
|
|
448
|
+
* node (no edges, no halo) is deliberately skipped — it is scaffolding,
|
|
449
|
+
* not an experience root or bridge, and regenerating its gist would waste
|
|
450
|
+
* I/O and index space for no recall benefit.
|
|
451
|
+
*
|
|
452
|
+
* @param minParents only repair nodes with ≥ this many structural parents
|
|
453
|
+
* (default 2 — structural bridges)
|
|
454
|
+
* @returns number of nodes added to the content index */
|
|
455
|
+
async repairContentIndex(minParents = 2): Promise<number> {
|
|
456
|
+
return this.store.repairContentIndex(
|
|
457
|
+
async (id) => {
|
|
458
|
+
const bytes = this.store.bytes(id);
|
|
459
|
+
if (bytes.length === 0) return null;
|
|
460
|
+
return gistOf(this, bytes);
|
|
461
|
+
},
|
|
462
|
+
minParents,
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// ── Persistence ──────────────────────────────────────────────────────────
|
|
467
|
+
|
|
468
|
+
async save(): Promise<Uint8Array> {
|
|
469
|
+
const meta = new TextEncoder().encode(JSON.stringify(this.cfg));
|
|
470
|
+
await this.store.saveSnapshot(meta);
|
|
471
|
+
return meta;
|
|
472
|
+
}
|
|
473
|
+
static async load(snapshot: Uint8Array, store: Store): Promise<Mind> {
|
|
474
|
+
const cfg = JSON.parse(new TextDecoder().decode(snapshot)) as MindConfig;
|
|
475
|
+
return new Mind(cfg, store, true);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
static async loadFromStore(store: Store): Promise<Mind> {
|
|
479
|
+
const meta = await store.loadSnapshot();
|
|
480
|
+
if (!meta) throw new Error("no snapshot in store");
|
|
481
|
+
return Mind.load(meta, store);
|
|
482
|
+
}
|
|
483
|
+
}
|