@hviana/sema 0.1.7 → 0.1.9
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/example/train_base.ts +29 -4
- package/package.json +1 -1
- package/src/alu/src/parser.ts +105 -4
- package/src/canon.ts +65 -0
- package/src/geometry.ts +26 -30
- package/src/index.ts +1 -0
- package/src/mind/learning.ts +39 -1
- package/src/mind/match.ts +29 -6
- package/src/mind/mechanisms/cast.ts +33 -13
- package/src/mind/mechanisms/confluence.ts +15 -1
- package/src/mind/mechanisms/recall.ts +116 -41
- package/src/mind/mind.ts +172 -29
- package/src/mind/primitives.ts +66 -1
- package/src/mind/recognition.ts +10 -0
- package/src/mind/types.ts +10 -0
- package/src/store-sqlite.ts +68 -0
- package/src/store.ts +27 -0
- package/test/13-conversation.test.mjs +77 -27
- package/test/35-prefix-edge.test.mjs +86 -0
- package/dist/example/demo.d.ts +0 -1
- package/dist/example/demo.js +0 -39
- package/dist/example/train_base.d.ts +0 -87
- package/dist/example/train_base.js +0 -2232
- package/dist/src/alphabet.d.ts +0 -7
- package/dist/src/alphabet.js +0 -33
- package/dist/src/alu/src/alu.d.ts +0 -185
- package/dist/src/alu/src/alu.js +0 -440
- package/dist/src/alu/src/expr.d.ts +0 -61
- package/dist/src/alu/src/expr.js +0 -318
- package/dist/src/alu/src/index.d.ts +0 -11
- package/dist/src/alu/src/index.js +0 -19
- package/dist/src/alu/src/kernel-arith.d.ts +0 -16
- package/dist/src/alu/src/kernel-arith.js +0 -264
- package/dist/src/alu/src/kernel-bits.d.ts +0 -19
- package/dist/src/alu/src/kernel-bits.js +0 -152
- package/dist/src/alu/src/kernel-logic.d.ts +0 -4
- package/dist/src/alu/src/kernel-logic.js +0 -60
- package/dist/src/alu/src/kernel-nd.d.ts +0 -3
- package/dist/src/alu/src/kernel-nd.js +0 -208
- package/dist/src/alu/src/kernel-numeric.d.ts +0 -54
- package/dist/src/alu/src/kernel-numeric.js +0 -366
- package/dist/src/alu/src/operation.d.ts +0 -168
- package/dist/src/alu/src/operation.js +0 -189
- package/dist/src/alu/src/parser.d.ts +0 -212
- package/dist/src/alu/src/parser.js +0 -469
- package/dist/src/alu/src/resonance.d.ts +0 -55
- package/dist/src/alu/src/resonance.js +0 -126
- package/dist/src/alu/src/text.d.ts +0 -31
- package/dist/src/alu/src/text.js +0 -73
- package/dist/src/alu/src/value.d.ts +0 -109
- package/dist/src/alu/src/value.js +0 -300
- package/dist/src/alu/test/alu.test.d.ts +0 -1
- package/dist/src/alu/test/alu.test.js +0 -764
- package/dist/src/bytes.d.ts +0 -14
- package/dist/src/bytes.js +0 -59
- package/dist/src/config.d.ts +0 -111
- package/dist/src/config.js +0 -91
- package/dist/src/derive/src/deduction.d.ts +0 -125
- package/dist/src/derive/src/deduction.js +0 -155
- package/dist/src/derive/src/index.d.ts +0 -7
- package/dist/src/derive/src/index.js +0 -11
- package/dist/src/derive/src/priority-queue.d.ts +0 -20
- package/dist/src/derive/src/priority-queue.js +0 -73
- package/dist/src/derive/src/rewrite.d.ts +0 -56
- package/dist/src/derive/src/rewrite.js +0 -100
- package/dist/src/derive/src/trie.d.ts +0 -90
- package/dist/src/derive/src/trie.js +0 -217
- package/dist/src/derive/test/derive.test.d.ts +0 -1
- package/dist/src/derive/test/derive.test.js +0 -122
- package/dist/src/extension.d.ts +0 -37
- package/dist/src/extension.js +0 -7
- package/dist/src/geometry.d.ts +0 -148
- package/dist/src/geometry.js +0 -517
- package/dist/src/index.d.ts +0 -15
- package/dist/src/index.js +0 -17
- package/dist/src/ingest-cache.d.ts +0 -41
- package/dist/src/ingest-cache.js +0 -161
- package/dist/src/mind/articulation.d.ts +0 -6
- package/dist/src/mind/articulation.js +0 -99
- package/dist/src/mind/attention.d.ts +0 -72
- package/dist/src/mind/attention.js +0 -898
- package/dist/src/mind/canonical.d.ts +0 -29
- package/dist/src/mind/canonical.js +0 -88
- package/dist/src/mind/graph-search.d.ts +0 -270
- package/dist/src/mind/graph-search.js +0 -847
- package/dist/src/mind/index.d.ts +0 -5
- package/dist/src/mind/index.js +0 -5
- package/dist/src/mind/junction.d.ts +0 -95
- package/dist/src/mind/junction.js +0 -262
- package/dist/src/mind/learning.d.ts +0 -47
- package/dist/src/mind/learning.js +0 -201
- package/dist/src/mind/match.d.ts +0 -111
- package/dist/src/mind/match.js +0 -422
- package/dist/src/mind/mechanisms/alu.d.ts +0 -4
- package/dist/src/mind/mechanisms/alu.js +0 -29
- package/dist/src/mind/mechanisms/cast.d.ts +0 -35
- package/dist/src/mind/mechanisms/cast.js +0 -447
- package/dist/src/mind/mechanisms/confluence.d.ts +0 -24
- package/dist/src/mind/mechanisms/confluence.js +0 -213
- package/dist/src/mind/mechanisms/cover.d.ts +0 -6
- package/dist/src/mind/mechanisms/cover.js +0 -179
- package/dist/src/mind/mechanisms/extraction.d.ts +0 -67
- package/dist/src/mind/mechanisms/extraction.js +0 -342
- package/dist/src/mind/mechanisms/recall.d.ts +0 -13
- package/dist/src/mind/mechanisms/recall.js +0 -166
- package/dist/src/mind/mind.d.ts +0 -211
- package/dist/src/mind/mind.js +0 -433
- package/dist/src/mind/pipeline-mechanism.d.ts +0 -142
- package/dist/src/mind/pipeline-mechanism.js +0 -213
- package/dist/src/mind/pipeline.d.ts +0 -20
- package/dist/src/mind/pipeline.js +0 -185
- package/dist/src/mind/primitives.d.ts +0 -54
- package/dist/src/mind/primitives.js +0 -184
- package/dist/src/mind/rationale.d.ts +0 -134
- package/dist/src/mind/rationale.js +0 -162
- package/dist/src/mind/reasoning.d.ts +0 -15
- package/dist/src/mind/reasoning.js +0 -162
- package/dist/src/mind/recognition.d.ts +0 -20
- package/dist/src/mind/recognition.js +0 -236
- package/dist/src/mind/resonance.d.ts +0 -23
- package/dist/src/mind/resonance.js +0 -0
- package/dist/src/mind/trace.d.ts +0 -15
- package/dist/src/mind/trace.js +0 -73
- package/dist/src/mind/traverse.d.ts +0 -113
- package/dist/src/mind/traverse.js +0 -488
- package/dist/src/mind/types.d.ts +0 -176
- package/dist/src/mind/types.js +0 -84
- package/dist/src/rabitq-ivf/src/database.d.ts +0 -113
- package/dist/src/rabitq-ivf/src/database.js +0 -201
- package/dist/src/rabitq-ivf/src/index.d.ts +0 -7
- package/dist/src/rabitq-ivf/src/index.js +0 -4
- package/dist/src/rabitq-ivf/src/ivf.d.ts +0 -200
- package/dist/src/rabitq-ivf/src/ivf.js +0 -1165
- package/dist/src/rabitq-ivf/src/prng.d.ts +0 -19
- package/dist/src/rabitq-ivf/src/prng.js +0 -36
- package/dist/src/rabitq-ivf/src/rabitq.d.ts +0 -95
- package/dist/src/rabitq-ivf/src/rabitq.js +0 -283
- package/dist/src/sema.d.ts +0 -31
- package/dist/src/sema.js +0 -63
- package/dist/src/store-sqlite.d.ts +0 -176
- package/dist/src/store-sqlite.js +0 -890
- package/dist/src/store.d.ts +0 -642
- package/dist/src/store.js +0 -1612
- package/dist/src/vec.d.ts +0 -31
- package/dist/src/vec.js +0 -109
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
// primitives.ts — Address + Read primitives (Section 1 of the mind).
|
|
2
|
-
//
|
|
3
|
-
// Address — bytes → node (perceive, foldTree, resolve)
|
|
4
|
-
// Read — node → bytes (read)
|
|
5
|
-
import { bytesToTree, bytesToTreePyramid, gridToTree, hilbertBytes, stackGrids, } from "../geometry.js";
|
|
6
|
-
import { ALL } from "./types.js";
|
|
7
|
-
// ── Address: bytes → node ──────────────────────────────────────────────
|
|
8
|
-
/** The content key of a byte span — one latin1 char per byte, an exact,
|
|
9
|
-
* collision-free encoding. Spans on the perception path are query-scale
|
|
10
|
-
* (windows, regions, candidate spans), so key construction is far cheaper
|
|
11
|
-
* than the river fold it deduplicates. */
|
|
12
|
-
export function latin1Key(bytes) {
|
|
13
|
-
// Batched String.fromCharCode — avoids the O(n²) cost of repeated += on
|
|
14
|
-
// potentially-large query spans, and stays well under the ~65536 arg limit.
|
|
15
|
-
const n = bytes.length;
|
|
16
|
-
let s = "";
|
|
17
|
-
for (let i = 0; i < n; i += 4096) {
|
|
18
|
-
s += String.fromCharCode(...bytes.subarray(i, Math.min(i + 4096, n)));
|
|
19
|
-
}
|
|
20
|
-
return s;
|
|
21
|
-
}
|
|
22
|
-
/** Perceive input into a content-defined tree (the river fold).
|
|
23
|
-
* Deterministic — identical bytes always produce an identical tree.
|
|
24
|
-
*
|
|
25
|
-
* `boundaries` is an optional sorted list of proper byte offsets where the
|
|
26
|
-
* fold must split so that each prefix segment folds identically to how it
|
|
27
|
-
* folded when it was learned (§10.3 stable-prefix contract). Only the
|
|
28
|
-
* CALLER — who assembled the multi-turn context — knows where those
|
|
29
|
-
* boundaries are; the geometry never guesses them from the bytes. */
|
|
30
|
-
export function perceive(ctx, input, leafAt, lookup, boundaries) {
|
|
31
|
-
if (typeof input === "string" || input instanceof Uint8Array) {
|
|
32
|
-
const bytes = typeof input === "string"
|
|
33
|
-
? new TextEncoder().encode(input)
|
|
34
|
-
: input;
|
|
35
|
-
if (leafAt === undefined && lookup === undefined) {
|
|
36
|
-
// Per-response memo (see MindContext.perceiveMemo): only the plain
|
|
37
|
-
// inference shape — raw bytes, no store capabilities — is memoised,
|
|
38
|
-
// keyed by CONTENT so byte-identical spans in fresh arrays still hit.
|
|
39
|
-
// The tree is shared by reference; Sema nodes are never mutated.
|
|
40
|
-
const memo = ctx.perceiveMemo;
|
|
41
|
-
if (memo) {
|
|
42
|
-
const key = latin1Key(bytes);
|
|
43
|
-
const hit = memo.get(key);
|
|
44
|
-
if (hit !== undefined)
|
|
45
|
-
return hit;
|
|
46
|
-
const tree = bytesToTree(ctx.space, ctx.alphabet, bytes, undefined, undefined, boundaries);
|
|
47
|
-
memo.set(key, tree);
|
|
48
|
-
return tree;
|
|
49
|
-
}
|
|
50
|
-
return bytesToTree(ctx.space, ctx.alphabet, bytes, undefined, undefined, boundaries);
|
|
51
|
-
}
|
|
52
|
-
return bytesToTree(ctx.space, ctx.alphabet, bytes, leafAt, lookup);
|
|
53
|
-
}
|
|
54
|
-
if (Array.isArray(input)) {
|
|
55
|
-
return gridToTree(ctx.space, ctx.alphabet, stackGrids(input));
|
|
56
|
-
}
|
|
57
|
-
return gridToTree(ctx.space, ctx.alphabet, input);
|
|
58
|
-
}
|
|
59
|
-
/** The DEPOSIT-shaped perceive: the PLAIN fold (bit-identical to inference
|
|
60
|
-
* perception — that structural train/inference agreement is load-bearing
|
|
61
|
-
* for exact recall), computed INCREMENTALLY via the fold's level pyramid
|
|
62
|
-
* ({@link bytesToTreePyramid}). An accumulated context (a conversation)
|
|
63
|
-
* grows by suffixes: the previous context's pyramid is cached by CONTENT
|
|
64
|
-
* (ctx._depositTrees), and this deposit refolds only the right edge of
|
|
65
|
-
* each level — O(turn) instead of O(context) per turn. Purely a cache:
|
|
66
|
-
* the produced tree never depends on cache state. */
|
|
67
|
-
export function perceiveDeposit(ctx, bytes) {
|
|
68
|
-
let prev;
|
|
69
|
-
// Longest cached PROPER prefix first.
|
|
70
|
-
const lens = [...ctx._depositLens]
|
|
71
|
-
.filter((L) => L >= 2 && L < bytes.length)
|
|
72
|
-
.sort((a, b) => b - a);
|
|
73
|
-
for (const L of lens) {
|
|
74
|
-
const hit = ctx._depositTrees.get(latin1Key(bytes.subarray(0, L)));
|
|
75
|
-
if (hit !== undefined) {
|
|
76
|
-
prev = hit;
|
|
77
|
-
break;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
const { tree, pyramid } = bytesToTreePyramid(ctx.space, ctx.alphabet, bytes, prev);
|
|
81
|
-
if (bytes.length >= 2) {
|
|
82
|
-
// The lengths set drifts as the map evicts; past the probe budget the
|
|
83
|
-
// drift itself becomes the cost (each stale length is an O(len) key
|
|
84
|
-
// build), so both reset together — losing only warm-up on live chains.
|
|
85
|
-
if (ctx._depositLens.size > 64) {
|
|
86
|
-
ctx._depositLens.clear();
|
|
87
|
-
ctx._depositTrees.clear();
|
|
88
|
-
}
|
|
89
|
-
ctx._depositTrees.set(latin1Key(bytes), pyramid);
|
|
90
|
-
ctx._depositLens.add(bytes.length);
|
|
91
|
-
}
|
|
92
|
-
return tree;
|
|
93
|
-
}
|
|
94
|
-
/** The raw bytes of an input — modality-neutral conversion. */
|
|
95
|
-
export function inputBytes(ctx, input) {
|
|
96
|
-
if (typeof input === "string")
|
|
97
|
-
return new TextEncoder().encode(input);
|
|
98
|
-
if (input instanceof Uint8Array)
|
|
99
|
-
return input;
|
|
100
|
-
if (Array.isArray(input))
|
|
101
|
-
return hilbertBytes(stackGrids(input));
|
|
102
|
-
return hilbertBytes(input);
|
|
103
|
-
}
|
|
104
|
-
/** Convenience: the gist vector of a byte span. */
|
|
105
|
-
export function gistOf(ctx, bytes) {
|
|
106
|
-
return perceive(ctx, bytes).v;
|
|
107
|
-
}
|
|
108
|
-
/** Fold a perceived tree bottom-up against the store's content-addressed maps:
|
|
109
|
-
* every leaf is named by findLeaf, every branch by findBranch over its kids'
|
|
110
|
-
* ids (null the moment any child is unknown). `visit`, when given, sees each
|
|
111
|
-
* node with its byte span and resolved id. Returns the node's byte end and
|
|
112
|
-
* resolved id. */
|
|
113
|
-
export function foldTree(ctx, n, start, visit) {
|
|
114
|
-
// Fast path: subtree already resolved (from a previous conversation turn
|
|
115
|
-
// or an earlier recognition pass). The pyramid reuses prefix subtrees as
|
|
116
|
-
// identical Sema objects, so this cache turns foldTree into O(suffix)
|
|
117
|
-
// instead of O(context) for multi-turn recognition.
|
|
118
|
-
const cached = ctx._resolvedSubtrees?.get(n);
|
|
119
|
-
if (cached !== undefined) {
|
|
120
|
-
const end = start + cached.len;
|
|
121
|
-
visit?.(n, start, end, cached.id);
|
|
122
|
-
return { end, node: cached.id };
|
|
123
|
-
}
|
|
124
|
-
if (n.kids === null) {
|
|
125
|
-
const b = n.leaf ?? new Uint8Array(0);
|
|
126
|
-
const end = start + b.length;
|
|
127
|
-
const node = ctx.store.findLeaf(b);
|
|
128
|
-
visit?.(n, start, end, node);
|
|
129
|
-
if (node !== null && ctx._resolvedSubtrees) {
|
|
130
|
-
ctx._resolvedSubtrees.set(n, { id: node, len: b.length });
|
|
131
|
-
}
|
|
132
|
-
return { end, node };
|
|
133
|
-
}
|
|
134
|
-
let pos = start;
|
|
135
|
-
let known = true;
|
|
136
|
-
const kids = [];
|
|
137
|
-
for (const k of n.kids) {
|
|
138
|
-
const r = foldTree(ctx, k, pos, visit);
|
|
139
|
-
if (r.node === null)
|
|
140
|
-
known = false;
|
|
141
|
-
else if (known)
|
|
142
|
-
kids.push(r.node);
|
|
143
|
-
pos = r.end;
|
|
144
|
-
}
|
|
145
|
-
const node = known ? ctx.store.findBranch(kids) : null;
|
|
146
|
-
visit?.(n, start, pos, node);
|
|
147
|
-
if (node !== null && ctx._resolvedSubtrees) {
|
|
148
|
-
ctx._resolvedSubtrees.set(n, { id: node, len: pos - start });
|
|
149
|
-
}
|
|
150
|
-
return { end: pos, node };
|
|
151
|
-
}
|
|
152
|
-
/** The canonical node id of a byte span: perceive it in isolation — the way
|
|
153
|
-
* training did — and recover its root bottom-up. Returns null if any part is
|
|
154
|
-
* unknown. */
|
|
155
|
-
export function resolve(ctx, bytes) {
|
|
156
|
-
if (bytes.length === 0)
|
|
157
|
-
return null;
|
|
158
|
-
return foldTree(ctx, perceive(ctx, bytes), 0).node;
|
|
159
|
-
}
|
|
160
|
-
/** Walk a perceived tree in POST-ORDER with byte offsets — children before
|
|
161
|
-
* their parent, `visit(node, start, end)` for every node including leaves.
|
|
162
|
-
* Returns the byte end. The one shared traversal the offset-carrying tree
|
|
163
|
-
* readers (recognition via foldTree's richer variant, attention's region
|
|
164
|
-
* collection, resonance's branch counting) build on, so each does not
|
|
165
|
-
* re-derive the offset bookkeeping. (recognition.segment keeps its own
|
|
166
|
-
* walk: its flush semantics need PRE-order decisions at leaf-parents, which
|
|
167
|
-
* a post-order visitor cannot express.) */
|
|
168
|
-
export function walkTree(n, start, visit) {
|
|
169
|
-
if (n.kids === null) {
|
|
170
|
-
const end = start + (n.leaf?.length ?? 0);
|
|
171
|
-
visit(n, start, end);
|
|
172
|
-
return end;
|
|
173
|
-
}
|
|
174
|
-
let pos = start;
|
|
175
|
-
for (const k of n.kids)
|
|
176
|
-
pos = walkTree(k, pos, visit);
|
|
177
|
-
visit(n, start, pos);
|
|
178
|
-
return pos;
|
|
179
|
-
}
|
|
180
|
-
// ── Read: node → bytes ──────────────────────────────────────────────────
|
|
181
|
-
/** Reconstruct a node's byte content from the DAG, up to `maxLen` bytes. */
|
|
182
|
-
export function read(ctx, id, maxLen = ALL) {
|
|
183
|
-
return ctx.store.bytesPrefix(id, maxLen);
|
|
184
|
-
}
|
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import type { Vec } from "../vec.js";
|
|
2
|
-
/** One element of a step's input or output vector.
|
|
3
|
-
*
|
|
4
|
-
* Modality-neutral and deliberately partial: an element might be a byte span of
|
|
5
|
-
* the query, a resolved graph node, a resonance hit with its score, a spliced
|
|
6
|
-
* connector — so every descriptive field is optional and a mechanism fills only
|
|
7
|
-
* the ones that carry meaning for what it did. `text` is always present (the
|
|
8
|
-
* human-readable rendering); the rest is provenance a debugger can lean on. */
|
|
9
|
-
export interface RationaleItem {
|
|
10
|
-
/** Human-readable rendering — decoded text for a byte span, else a label like
|
|
11
|
-
* "‹none›" or an operator name. Always set, so a step always reads. */
|
|
12
|
-
text: string;
|
|
13
|
-
/** The graph node this element is, or resolved to, when known — the handle to
|
|
14
|
-
* point back at the exact stored fact in the content-addressed DAG. */
|
|
15
|
-
node?: number;
|
|
16
|
-
/** The `[start, end)` span this element occupies in its step's frame of
|
|
17
|
-
* reference (usually the query or the answer being composed). */
|
|
18
|
-
span?: [number, number];
|
|
19
|
-
/** The resonance / cosine score that selected this element, when it was chosen
|
|
20
|
-
* by similarity rather than by exact structure. */
|
|
21
|
-
score?: number;
|
|
22
|
-
/** A short role tag — "query", "leaf", "form", "hit", "connector", "answer",
|
|
23
|
-
* … — naming what KIND of element this is within the step. */
|
|
24
|
-
role?: string;
|
|
25
|
-
/** The gist vector, only when the element fundamentally IS a vector and a
|
|
26
|
-
* caller asked to carry it (off by default — a D-float array per item would
|
|
27
|
-
* bury the reasoning it is meant to explain). */
|
|
28
|
-
v?: Vec;
|
|
29
|
-
}
|
|
30
|
-
/** A single completed act of inference — one mechanism, run once.
|
|
31
|
-
*
|
|
32
|
-
* Steps are emitted in COMPLETION order (a sub-mechanism finishes, and is
|
|
33
|
-
* reported, before the mechanism that called it), while `index` is assigned in
|
|
34
|
-
* ENTRY order (a parent reserves its index before its children run). So a
|
|
35
|
-
* parent's `index` is always lower than its children's, and the two orderings
|
|
36
|
-
* together give a valid topological reading of the dependency graph. */
|
|
37
|
-
export interface RationaleStep {
|
|
38
|
-
/** This step's index, assigned when the mechanism was ENTERED — a strict,
|
|
39
|
-
* incremental ordering over the whole inference. */
|
|
40
|
-
index: number;
|
|
41
|
-
/** The mechanism and its enclosing mechanisms, outermost → innermost, e.g.
|
|
42
|
-
* `["respond", "think", "recognise"]`. The last entry is this step; the
|
|
43
|
-
* prefix is the nest of sub-mechanisms it ran inside. */
|
|
44
|
-
mechanism: string[];
|
|
45
|
-
/** The enclosing mechanism's step index, or -1 at the root — the NESTING edge
|
|
46
|
-
* of the dependency graph (which step this one is a part of). */
|
|
47
|
-
parent: number;
|
|
48
|
-
/** The earlier steps whose OUTPUTS became this step's inputs — the DATA-FLOW
|
|
49
|
-
* edges of the dependency graph. Defaults to the previous sibling (the step
|
|
50
|
-
* run just before this one inside the same mechanism), or the parent when
|
|
51
|
-
* this is the first sub-step; a mechanism that fuses several earlier results
|
|
52
|
-
* names them all explicitly. */
|
|
53
|
-
dependsOn: number[];
|
|
54
|
-
/** The vector of elements handed to the mechanism (one or more). */
|
|
55
|
-
inputs: RationaleItem[];
|
|
56
|
-
/** The vector of elements the mechanism produced (one or more) — longer than
|
|
57
|
-
* `inputs` when it decomposed, shorter when it combined. */
|
|
58
|
-
outputs: RationaleItem[];
|
|
59
|
-
/** A one-line, human account of what the mechanism did and why — the sentence
|
|
60
|
-
* that turns the data into an explanation. */
|
|
61
|
-
note?: string;
|
|
62
|
-
}
|
|
63
|
-
/** The callback {@link Mind.respond} / {@link Mind.respondText} accept. It is
|
|
64
|
-
* invoked once per completed step, AS the inference unfolds — never batched at
|
|
65
|
-
* the end — so a caller can stream the reasoning live or accumulate it. */
|
|
66
|
-
export type InspectRationale = (step: RationaleStep) => void;
|
|
67
|
-
/** Decode bytes to text for display, dropping the NUL padding the encoder uses
|
|
68
|
-
* (the same cleanup {@link Mind.respondText} does for its result). */
|
|
69
|
-
export declare function decodeText(bytes: Uint8Array): string;
|
|
70
|
-
/** The `[start, end)` gaps of `[0, queryLen)` NOT covered by `accounted` —
|
|
71
|
-
* the same union-of-spans reading think's grounding decider prices at PASS
|
|
72
|
-
* per byte, exposed here so a mechanism can turn it into a human label. */
|
|
73
|
-
export declare function unexplainedSpans(queryLen: number, accounted: ReadonlyArray<[number, number]>): Array<[number, number]>;
|
|
74
|
-
/** A human-readable label for the query bytes a mechanism's `accounted`
|
|
75
|
-
* spans leave unexplained — purely diagnostic (Task 2's negative evidence):
|
|
76
|
-
* it never changes a candidate's weight, only what the rationale trace
|
|
77
|
-
* says the mechanism left on the table. `""` when nothing is unexplained. */
|
|
78
|
-
export declare function unexplainedLabel(query: Uint8Array, accounted: ReadonlyArray<[number, number]>): string;
|
|
79
|
-
/** An open mechanism — the handle {@link Rationale.enter} returns. Hold it for
|
|
80
|
-
* the duration of the mechanism and call {@link Scope.done} with the outputs
|
|
81
|
-
* when it finishes; that emits the step and pops the nesting. */
|
|
82
|
-
export interface Scope {
|
|
83
|
-
/** The step index reserved for this mechanism at entry — pass it as an
|
|
84
|
-
* explicit dependency of a later step that consumes this one's output. */
|
|
85
|
-
readonly index: number;
|
|
86
|
-
/** Close the mechanism: emit its step with these outputs and pop it off the
|
|
87
|
-
* nesting stack. Idempotent — a second call is ignored, so a `finally` that
|
|
88
|
-
* closes after an early return is safe. */
|
|
89
|
-
done(outputs: RationaleItem[], note?: string): void;
|
|
90
|
-
}
|
|
91
|
-
/** The live tracer: a stack of open mechanisms over one {@link Mind.respond}.
|
|
92
|
-
*
|
|
93
|
-
* Sema's inference is single-threaded and strictly sequential — every async
|
|
94
|
-
* step is awaited before the next begins, and `respond` holds no two thoughts
|
|
95
|
-
* at once — so a plain stack exactly tracks the current nesting: {@link enter}
|
|
96
|
-
* pushes, {@link Scope.done} pops, and {@link step} (a mechanism with no
|
|
97
|
-
* sub-steps) is the two fused. The tracer never branches the control flow; it
|
|
98
|
-
* only records it. */
|
|
99
|
-
export declare class Rationale {
|
|
100
|
-
private readonly sink;
|
|
101
|
-
private next;
|
|
102
|
-
/** Open mechanisms, outermost first. Each frame remembers the last child it
|
|
103
|
-
* has spawned so the next sibling can default its data-flow edge to it. */
|
|
104
|
-
private readonly stack;
|
|
105
|
-
/** The most recent step index emitted under each mechanism name — the handle
|
|
106
|
-
* a later step uses to name an EARLIER mechanism as its data-flow producer
|
|
107
|
-
* (e.g. cover depends on the latest recognise / computeExtensions). One tracer is
|
|
108
|
-
* built per response and inference is sequential, so "most recent" is exactly
|
|
109
|
-
* "the one that produced the inputs I am about to consume". */
|
|
110
|
-
private readonly lastByName;
|
|
111
|
-
constructor(sink: InspectRationale);
|
|
112
|
-
/** The index of the most recent step with this mechanism name, or undefined if
|
|
113
|
-
* none has run. Used to wire an explicit producer edge into {@link
|
|
114
|
-
* Scope.done} / {@link step}'s `deps`. */
|
|
115
|
-
lastIndex(name: string): number | undefined;
|
|
116
|
-
/** The mechanism names currently open, outermost → innermost. */
|
|
117
|
-
private path;
|
|
118
|
-
/** The default data-flow edge for a step entering now: the previous sibling
|
|
119
|
-
* inside the current mechanism, else the enclosing mechanism, else nothing
|
|
120
|
-
* (the root). An explicit `deps` overrides this. */
|
|
121
|
-
private defaultDeps;
|
|
122
|
-
/** Reserve this step's index and register it as the current mechanism's most
|
|
123
|
-
* recent child (so the NEXT sibling chains to it) and as the most recent step
|
|
124
|
-
* of its own NAME (so a later mechanism can name it as a producer). */
|
|
125
|
-
private reserve;
|
|
126
|
-
private emit;
|
|
127
|
-
/** Enter a mechanism that has sub-steps. Captures its inputs and the nesting
|
|
128
|
-
* now; the matching {@link Scope.done} supplies the outputs when it finishes.
|
|
129
|
-
* `deps` overrides the default data-flow edge (previous sibling / parent). */
|
|
130
|
-
enter(name: string, inputs: RationaleItem[], deps?: number[]): Scope;
|
|
131
|
-
/** Record a mechanism that has no sub-steps — its inputs and outputs are both
|
|
132
|
-
* known at the call site. Returns its index, for a later step to depend on. */
|
|
133
|
-
step(name: string, inputs: RationaleItem[], outputs: RationaleItem[], note?: string, deps?: number[]): number;
|
|
134
|
-
}
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
// rationale.ts — the inference, told as it happens.
|
|
2
|
-
//
|
|
3
|
-
// Sema's edge over a weight matrix is that every answer is a DERIVATION over
|
|
4
|
-
// explicit facts, not a sample from an opaque distribution. This module turns
|
|
5
|
-
// that derivation into a stream a human (or a debugger) can read: as {@link
|
|
6
|
-
// Mind.respond} thinks, each inference MECHANISM it runs emits a {@link
|
|
7
|
-
// RationaleStep} the moment it completes — what it was handed, what it produced,
|
|
8
|
-
// where it sits in the nesting of mechanisms, and which earlier steps fed it.
|
|
9
|
-
//
|
|
10
|
-
// Nothing here drives the inference; it only WITNESSES it. When no
|
|
11
|
-
// `inspectRationale` callback is supplied the tracer is never constructed and
|
|
12
|
-
// the cost is exactly zero — every emit site in src/mind/mind.ts is guarded by `?.`, and
|
|
13
|
-
// optional-chaining short-circuits its arguments, so the items are not even
|
|
14
|
-
// built (see {@link Mind.respond}).
|
|
15
|
-
//
|
|
16
|
-
// The shape of a step mirrors how Sema reasons. A mechanism is rarely a 1→1
|
|
17
|
-
// map: {@link Mind.recognise} DECOMPOSES one query into many recognised forms;
|
|
18
|
-
// the cover COMBINES many forms back into one answer; resonance fans one gist
|
|
19
|
-
// out into a ranked list of hits. So a step's `inputs` and `outputs` are each a
|
|
20
|
-
// VECTOR — an ordered list of {@link RationaleItem}s, one per element — and the
|
|
21
|
-
// fan-out / fan-in is visible in their lengths.
|
|
22
|
-
/** Decode bytes to text for display, dropping the NUL padding the encoder uses
|
|
23
|
-
* (the same cleanup {@link Mind.respondText} does for its result). */
|
|
24
|
-
export function decodeText(bytes) {
|
|
25
|
-
return new TextDecoder().decode(bytes.filter((b) => b !== 0x00));
|
|
26
|
-
}
|
|
27
|
-
/** The `[start, end)` gaps of `[0, queryLen)` NOT covered by `accounted` —
|
|
28
|
-
* the same union-of-spans reading think's grounding decider prices at PASS
|
|
29
|
-
* per byte, exposed here so a mechanism can turn it into a human label. */
|
|
30
|
-
export function unexplainedSpans(queryLen, accounted) {
|
|
31
|
-
const sorted = accounted
|
|
32
|
-
.map(([s, e]) => [Math.max(0, s), Math.min(queryLen, e)])
|
|
33
|
-
.filter(([s, e]) => e > s)
|
|
34
|
-
.sort((a, b) => a[0] - b[0]);
|
|
35
|
-
const gaps = [];
|
|
36
|
-
let reach = 0;
|
|
37
|
-
for (const [s, e] of sorted) {
|
|
38
|
-
if (s > reach)
|
|
39
|
-
gaps.push([reach, s]);
|
|
40
|
-
if (e > reach)
|
|
41
|
-
reach = e;
|
|
42
|
-
}
|
|
43
|
-
if (reach < queryLen)
|
|
44
|
-
gaps.push([reach, queryLen]);
|
|
45
|
-
return gaps;
|
|
46
|
-
}
|
|
47
|
-
/** A human-readable label for the query bytes a mechanism's `accounted`
|
|
48
|
-
* spans leave unexplained — purely diagnostic (Task 2's negative evidence):
|
|
49
|
-
* it never changes a candidate's weight, only what the rationale trace
|
|
50
|
-
* says the mechanism left on the table. `""` when nothing is unexplained. */
|
|
51
|
-
export function unexplainedLabel(query, accounted) {
|
|
52
|
-
const gaps = unexplainedSpans(query.length, accounted);
|
|
53
|
-
if (gaps.length === 0)
|
|
54
|
-
return "";
|
|
55
|
-
return gaps.map(([s, e]) => decodeText(query.subarray(s, e))).join(" … ");
|
|
56
|
-
}
|
|
57
|
-
/** The live tracer: a stack of open mechanisms over one {@link Mind.respond}.
|
|
58
|
-
*
|
|
59
|
-
* Sema's inference is single-threaded and strictly sequential — every async
|
|
60
|
-
* step is awaited before the next begins, and `respond` holds no two thoughts
|
|
61
|
-
* at once — so a plain stack exactly tracks the current nesting: {@link enter}
|
|
62
|
-
* pushes, {@link Scope.done} pops, and {@link step} (a mechanism with no
|
|
63
|
-
* sub-steps) is the two fused. The tracer never branches the control flow; it
|
|
64
|
-
* only records it. */
|
|
65
|
-
export class Rationale {
|
|
66
|
-
sink;
|
|
67
|
-
next = 0;
|
|
68
|
-
/** Open mechanisms, outermost first. Each frame remembers the last child it
|
|
69
|
-
* has spawned so the next sibling can default its data-flow edge to it. */
|
|
70
|
-
stack = [];
|
|
71
|
-
/** The most recent step index emitted under each mechanism name — the handle
|
|
72
|
-
* a later step uses to name an EARLIER mechanism as its data-flow producer
|
|
73
|
-
* (e.g. cover depends on the latest recognise / computeExtensions). One tracer is
|
|
74
|
-
* built per response and inference is sequential, so "most recent" is exactly
|
|
75
|
-
* "the one that produced the inputs I am about to consume". */
|
|
76
|
-
lastByName = new Map();
|
|
77
|
-
constructor(sink) {
|
|
78
|
-
this.sink = sink;
|
|
79
|
-
}
|
|
80
|
-
/** The index of the most recent step with this mechanism name, or undefined if
|
|
81
|
-
* none has run. Used to wire an explicit producer edge into {@link
|
|
82
|
-
* Scope.done} / {@link step}'s `deps`. */
|
|
83
|
-
lastIndex(name) {
|
|
84
|
-
return this.lastByName.get(name);
|
|
85
|
-
}
|
|
86
|
-
/** The mechanism names currently open, outermost → innermost. */
|
|
87
|
-
path(leaf) {
|
|
88
|
-
const p = this.stack.map((f) => f.name);
|
|
89
|
-
p.push(leaf);
|
|
90
|
-
return p;
|
|
91
|
-
}
|
|
92
|
-
/** The default data-flow edge for a step entering now: the previous sibling
|
|
93
|
-
* inside the current mechanism, else the enclosing mechanism, else nothing
|
|
94
|
-
* (the root). An explicit `deps` overrides this. */
|
|
95
|
-
defaultDeps() {
|
|
96
|
-
const top = this.stack[this.stack.length - 1];
|
|
97
|
-
if (!top)
|
|
98
|
-
return [];
|
|
99
|
-
return [top.lastChild ?? top.index];
|
|
100
|
-
}
|
|
101
|
-
/** Reserve this step's index and register it as the current mechanism's most
|
|
102
|
-
* recent child (so the NEXT sibling chains to it) and as the most recent step
|
|
103
|
-
* of its own NAME (so a later mechanism can name it as a producer). */
|
|
104
|
-
reserve(name) {
|
|
105
|
-
const index = this.next++;
|
|
106
|
-
const top = this.stack[this.stack.length - 1];
|
|
107
|
-
if (top)
|
|
108
|
-
top.lastChild = index;
|
|
109
|
-
this.lastByName.set(name, index);
|
|
110
|
-
return index;
|
|
111
|
-
}
|
|
112
|
-
emit(index, mechanism, inputs, outputs, deps, note) {
|
|
113
|
-
this.sink({
|
|
114
|
-
index,
|
|
115
|
-
mechanism,
|
|
116
|
-
parent: this.stack.length > 0
|
|
117
|
-
? this.stack[this.stack.length - 1].index
|
|
118
|
-
: -1,
|
|
119
|
-
dependsOn: deps ?? this.defaultDeps(),
|
|
120
|
-
inputs,
|
|
121
|
-
outputs,
|
|
122
|
-
note,
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
/** Enter a mechanism that has sub-steps. Captures its inputs and the nesting
|
|
126
|
-
* now; the matching {@link Scope.done} supplies the outputs when it finishes.
|
|
127
|
-
* `deps` overrides the default data-flow edge (previous sibling / parent). */
|
|
128
|
-
enter(name, inputs, deps) {
|
|
129
|
-
const mechanism = this.path(name);
|
|
130
|
-
const resolvedDeps = deps ?? this.defaultDeps();
|
|
131
|
-
const index = this.reserve(name);
|
|
132
|
-
this.stack.push({ index, name, lastChild: null });
|
|
133
|
-
let closed = false;
|
|
134
|
-
const emit = this.emit.bind(this);
|
|
135
|
-
const pop = () => {
|
|
136
|
-
// Pop down to and including this frame — tolerant of a sub-mechanism that
|
|
137
|
-
// forgot to close, so one missed `done` cannot desync the whole stack.
|
|
138
|
-
const at = this.stack.findIndex((f) => f.index === index);
|
|
139
|
-
if (at >= 0)
|
|
140
|
-
this.stack.length = at;
|
|
141
|
-
};
|
|
142
|
-
return {
|
|
143
|
-
index,
|
|
144
|
-
done: (outputs, note) => {
|
|
145
|
-
if (closed)
|
|
146
|
-
return;
|
|
147
|
-
closed = true;
|
|
148
|
-
pop();
|
|
149
|
-
emit(index, mechanism, inputs, outputs, resolvedDeps, note);
|
|
150
|
-
},
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
/** Record a mechanism that has no sub-steps — its inputs and outputs are both
|
|
154
|
-
* known at the call site. Returns its index, for a later step to depend on. */
|
|
155
|
-
step(name, inputs, outputs, note, deps) {
|
|
156
|
-
const mechanism = this.path(name);
|
|
157
|
-
const resolvedDeps = deps ?? this.defaultDeps();
|
|
158
|
-
const index = this.reserve(name);
|
|
159
|
-
this.emit(index, mechanism, inputs, outputs, resolvedDeps, note);
|
|
160
|
-
return index;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { MindContext } from "./types.js";
|
|
2
|
-
import type { Precomputed } from "./pipeline-mechanism.js";
|
|
3
|
-
/** Extend a grounded answer forward across facts (multi-hop reasoning).
|
|
4
|
-
* Pivots on the longest unconsumed learnt context each answer contains,
|
|
5
|
-
* then follows the pivot's continuation to the next fact. Repeats up
|
|
6
|
-
* to `cfg.recallQueryK` hops. `preConsumed` carries node ids already
|
|
7
|
-
* spoken for by the grounding stage (cover/extract/CAST). `pre` is the
|
|
8
|
-
* response's shared pre-computation — the post-grounding stages read the
|
|
9
|
-
* same container the mechanisms did. */
|
|
10
|
-
export declare function reason(ctx: MindContext, query: Uint8Array, answer: Uint8Array, preConsumed: ReadonlySet<number>, pre: Precomputed): Promise<Uint8Array>;
|
|
11
|
-
/** Fuse independent points of attention into one answer (multi-topic).
|
|
12
|
-
* When the consensus climb finds more than one dominant point, each
|
|
13
|
-
* independent point grounds its own answer; they are bridged together
|
|
14
|
-
* by any learnt connector the graph holds between them. */
|
|
15
|
-
export declare function fuseAttention(ctx: MindContext, query: Uint8Array, primary: Uint8Array, pre: Precomputed): Promise<Uint8Array>;
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
// reasoning.ts — multi-hop reasoning + multi-topic fusion (Section 4 of the mind).
|
|
2
|
-
//
|
|
3
|
-
// reason — extend an answer forward across facts (multi-hop)
|
|
4
|
-
// fuseAttention — fuse independent points of attention (multi-topic)
|
|
5
|
-
import { rItem, rNode } from "./trace.js";
|
|
6
|
-
import { bytesEqual, indexOf } from "../bytes.js";
|
|
7
|
-
import { resolve } from "./primitives.js";
|
|
8
|
-
import { corpusN } from "./traverse.js";
|
|
9
|
-
import { follow, haloSiblings, project } from "./match.js";
|
|
10
|
-
import { joinWithBridge, pivotInto } from "./resonance.js";
|
|
11
|
-
/** Extend a grounded answer forward across facts (multi-hop reasoning).
|
|
12
|
-
* Pivots on the longest unconsumed learnt context each answer contains,
|
|
13
|
-
* then follows the pivot's continuation to the next fact. Repeats up
|
|
14
|
-
* to `cfg.recallQueryK` hops. `preConsumed` carries node ids already
|
|
15
|
-
* spoken for by the grounding stage (cover/extract/CAST). `pre` is the
|
|
16
|
-
* response's shared pre-computation — the post-grounding stages read the
|
|
17
|
-
* same container the mechanisms did. */
|
|
18
|
-
export async function reason(ctx, query, answer, preConsumed, pre) {
|
|
19
|
-
// Echo guard: a query that is ITSELF a learnt continuation (some context's
|
|
20
|
-
// answer) is being asked back at the system — hopping forward from it would
|
|
21
|
-
// chain through the very fact that produced it and echo the conversation
|
|
22
|
-
// back. The grounded answer alone is the honest read-out. Deliberately a
|
|
23
|
-
// broad structural gate; pinned by test/31-audit.
|
|
24
|
-
const qId = pre.queryResolved;
|
|
25
|
-
if (qId !== null && ctx.store.prevCount(qId) > 0)
|
|
26
|
-
return answer;
|
|
27
|
-
const consumed = new Set();
|
|
28
|
-
// Consume a node and its neighbours for pivot-cycle prevention — CAPPED at
|
|
29
|
-
// the hub bound, via the store's LIMITed edge reads: a common continuation's
|
|
30
|
-
// reverse fan-in (and a hub context's forward fan-out) is corpus-sized, and
|
|
31
|
-
// no per-hop operation may grow with the corpus. The cap follows the one
|
|
32
|
-
// convention every fan-out decision uses (first √N in the relation's own
|
|
33
|
-
// read order); a pivot suppressed only by a beyond-cap neighbour may now
|
|
34
|
-
// fire — the same visibility trade chooseNext documents.
|
|
35
|
-
const hubBound = Math.ceil(Math.sqrt(corpusN(ctx)));
|
|
36
|
-
const consumeNode = (id) => {
|
|
37
|
-
if (id === null)
|
|
38
|
-
return;
|
|
39
|
-
consumed.add(id);
|
|
40
|
-
for (const p of ctx.store.prevFirst(id, hubBound))
|
|
41
|
-
consumed.add(p);
|
|
42
|
-
};
|
|
43
|
-
const consumeAll = (id) => {
|
|
44
|
-
if (id === null)
|
|
45
|
-
return;
|
|
46
|
-
consumeNode(id);
|
|
47
|
-
for (const n of ctx.store.nextFirst(id, hubBound))
|
|
48
|
-
consumed.add(n);
|
|
49
|
-
};
|
|
50
|
-
// Pre-consume whatever the grounding stage already spoke for. The halo
|
|
51
|
-
// sweep is one ANN query per node — cap it at haloQueryK sweeps (cover
|
|
52
|
-
// grounding can pre-consume one node per recognised site, O(query length));
|
|
53
|
-
// nodes past the cap are still consumed directly, they just skip the
|
|
54
|
-
// synonym expansion.
|
|
55
|
-
let haloSweeps = 0;
|
|
56
|
-
for (const id of preConsumed) {
|
|
57
|
-
consumeNode(id);
|
|
58
|
-
if (haloSweeps >= ctx.cfg.haloQueryK)
|
|
59
|
-
continue;
|
|
60
|
-
const h = ctx.store.halo(id);
|
|
61
|
-
if (!h)
|
|
62
|
-
continue;
|
|
63
|
-
haloSweeps++;
|
|
64
|
-
for (const sib of await haloSiblings(ctx, id, h))
|
|
65
|
-
consumeNode(sib.id);
|
|
66
|
-
}
|
|
67
|
-
let cur = answer;
|
|
68
|
-
const qv = pre.guide; // the response-wide guide IS the query's gist
|
|
69
|
-
let t;
|
|
70
|
-
const startedFrom = answer;
|
|
71
|
-
for (let hop = 0; hop < ctx.cfg.recallQueryK; hop++) {
|
|
72
|
-
const curId = resolve(ctx, cur);
|
|
73
|
-
consumeNode(curId);
|
|
74
|
-
// Forward-absorb: follow only UNCONSUMED continuations. The gate below
|
|
75
|
-
// checks an unconsumed edge EXISTS, but follow()'s chooseNext knows
|
|
76
|
-
// nothing of `consumed` and may still walk to a consumed fixpoint —
|
|
77
|
-
// absorbing it would repeat content the grounding stage already spoke
|
|
78
|
-
// for, so a consumed fixpoint falls through to the pivot step instead.
|
|
79
|
-
if (curId !== null &&
|
|
80
|
-
ctx.store.nextFirst(curId, hubBound).some((n) => !consumed.has(n))) {
|
|
81
|
-
const fwd = await follow(ctx, curId, qv);
|
|
82
|
-
const fwdId = fwd !== null ? resolve(ctx, fwd) : null;
|
|
83
|
-
if (fwd !== null && !bytesEqual(fwd, cur) &&
|
|
84
|
-
(fwdId === null || !consumed.has(fwdId))) {
|
|
85
|
-
consumeAll(curId);
|
|
86
|
-
t ??= ctx.trace?.enter("reason", [
|
|
87
|
-
rItem(startedFrom, "grounded"),
|
|
88
|
-
]);
|
|
89
|
-
ctx.trace?.step("absorbForward", [rItem(cur, "answer", curId)], [rItem(fwd, "answer", resolve(ctx, fwd) ?? undefined)], "the answer is itself a learnt fact — follow its continuation to the fixpoint");
|
|
90
|
-
cur = fwd;
|
|
91
|
-
continue;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
// Pivot: find the longest unconsumed learnt context the answer contains.
|
|
95
|
-
consumeAll(curId);
|
|
96
|
-
const pivot = await pivotInto(ctx, cur, consumed);
|
|
97
|
-
if (pivot === null)
|
|
98
|
-
break;
|
|
99
|
-
const fc = await follow(ctx, pivot, qv);
|
|
100
|
-
consumeAll(pivot);
|
|
101
|
-
if (fc === null || bytesEqual(fc, cur))
|
|
102
|
-
break;
|
|
103
|
-
t ??= ctx.trace?.enter("reason", [rItem(startedFrom, "grounded")]);
|
|
104
|
-
ctx.trace?.step("pivotStep", [rItem(cur, "answer"), rNode(ctx, pivot, "pivot")], [rItem(fc, "answer", resolve(ctx, fc) ?? undefined)], "pivot on the shared span this answer contains, then step forward across that fact");
|
|
105
|
-
cur = fc;
|
|
106
|
-
}
|
|
107
|
-
t?.done([rItem(cur, "answer", resolve(ctx, cur) ?? undefined)], "the multi-hop chain's fixpoint");
|
|
108
|
-
return cur;
|
|
109
|
-
}
|
|
110
|
-
/** Fuse independent points of attention into one answer (multi-topic).
|
|
111
|
-
* When the consensus climb finds more than one dominant point, each
|
|
112
|
-
* independent point grounds its own answer; they are bridged together
|
|
113
|
-
* by any learnt connector the graph holds between them. */
|
|
114
|
-
export async function fuseAttention(ctx, query, primary, pre) {
|
|
115
|
-
// When the answer is structurally drawn from the query itself
|
|
116
|
-
// (extraction), it already spans all the query's pieces — fusion
|
|
117
|
-
// would only add noise from unrelated stored contexts. The gate is
|
|
118
|
-
// STRICT containment (resolved node in the query's tree, or a contiguous
|
|
119
|
-
// byte run): the old sparse-subsequence test was trivially satisfied by
|
|
120
|
-
// short answers over long queries, silently starving multi-topic queries
|
|
121
|
-
// of fusion.
|
|
122
|
-
if (containsSpan(ctx, query, primary))
|
|
123
|
-
return primary;
|
|
124
|
-
// The committed points of attention ARE the shared climb's roots (same
|
|
125
|
-
// query, same k, same DF mode) — read them from Precomputed instead of
|
|
126
|
-
// re-climbing, so even a traced response pays for the climb once.
|
|
127
|
-
const forest = (await pre.attention()).roots;
|
|
128
|
-
if (forest.length <= 1)
|
|
129
|
-
return primary;
|
|
130
|
-
const pieces = [
|
|
131
|
-
{ start: forest[0].start, bytes: primary },
|
|
132
|
-
];
|
|
133
|
-
const qv = pre.guide; // once, not per root
|
|
134
|
-
const t = ctx.trace?.enter("fuseAttention", [
|
|
135
|
-
rItem(primary, "primary"),
|
|
136
|
-
...forest.slice(1).map((r) => rNode(ctx, r.anchor, "point", r.vote)),
|
|
137
|
-
]);
|
|
138
|
-
for (const root of forest.slice(1)) {
|
|
139
|
-
const g = await project(ctx, root.anchor, qv);
|
|
140
|
-
if (g === null || g.length === 0)
|
|
141
|
-
continue;
|
|
142
|
-
if (pieces.some((p) => indexOf(p.bytes, g, 0) >= 0))
|
|
143
|
-
continue;
|
|
144
|
-
pieces.push({ start: root.start, bytes: g });
|
|
145
|
-
}
|
|
146
|
-
if (pieces.length === 1) {
|
|
147
|
-
t?.done([rItem(primary, "answer")], "no further independent point grounded");
|
|
148
|
-
return primary;
|
|
149
|
-
}
|
|
150
|
-
pieces.sort((a, b) => a.start - b.start);
|
|
151
|
-
let out = pieces[0].bytes;
|
|
152
|
-
for (let i = 1; i < pieces.length; i++) {
|
|
153
|
-
// An approximate-resonance miss (or a genuinely unlearnt junction) joins
|
|
154
|
-
// the pieces bare — joinWithBridge surfaces it as a bridgeMiss step.
|
|
155
|
-
out = await joinWithBridge(ctx, out, pieces[i].bytes);
|
|
156
|
-
}
|
|
157
|
-
t?.done([rItem(out, "answer", resolve(ctx, out) ?? undefined)], `fused ${pieces.length} independent points of attention into one answer`);
|
|
158
|
-
return out;
|
|
159
|
-
}
|
|
160
|
-
// (resonance.js is already a static dependency above — `bridge` — so the old
|
|
161
|
-
// dynamic import of pivotInto guarded against a cycle that does not exist.)
|
|
162
|
-
import { containsSpan } from "./mechanisms/extraction.js";
|