@hviana/sema 0.1.9 → 0.2.1

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 (131) hide show
  1. package/dist/example/demo.d.ts +1 -0
  2. package/dist/example/demo.js +39 -0
  3. package/dist/example/train_base.d.ts +87 -0
  4. package/dist/example/train_base.js +2252 -0
  5. package/dist/src/alphabet.d.ts +7 -0
  6. package/dist/src/alphabet.js +33 -0
  7. package/dist/src/alu/src/alu.d.ts +185 -0
  8. package/dist/src/alu/src/alu.js +440 -0
  9. package/dist/src/alu/src/expr.d.ts +61 -0
  10. package/dist/src/alu/src/expr.js +318 -0
  11. package/dist/src/alu/src/index.d.ts +11 -0
  12. package/dist/src/alu/src/index.js +19 -0
  13. package/dist/src/alu/src/kernel-arith.d.ts +16 -0
  14. package/dist/src/alu/src/kernel-arith.js +264 -0
  15. package/dist/src/alu/src/kernel-bits.d.ts +19 -0
  16. package/dist/src/alu/src/kernel-bits.js +152 -0
  17. package/dist/src/alu/src/kernel-logic.d.ts +4 -0
  18. package/dist/src/alu/src/kernel-logic.js +60 -0
  19. package/dist/src/alu/src/kernel-nd.d.ts +3 -0
  20. package/dist/src/alu/src/kernel-nd.js +208 -0
  21. package/dist/src/alu/src/kernel-numeric.d.ts +54 -0
  22. package/dist/src/alu/src/kernel-numeric.js +366 -0
  23. package/dist/src/alu/src/operation.d.ts +168 -0
  24. package/dist/src/alu/src/operation.js +189 -0
  25. package/dist/src/alu/src/parser.d.ts +221 -0
  26. package/dist/src/alu/src/parser.js +577 -0
  27. package/dist/src/alu/src/resonance.d.ts +55 -0
  28. package/dist/src/alu/src/resonance.js +126 -0
  29. package/dist/src/alu/src/text.d.ts +31 -0
  30. package/dist/src/alu/src/text.js +73 -0
  31. package/dist/src/alu/src/value.d.ts +109 -0
  32. package/dist/src/alu/src/value.js +300 -0
  33. package/dist/src/alu/test/alu.test.d.ts +1 -0
  34. package/dist/src/alu/test/alu.test.js +764 -0
  35. package/dist/src/bytes.d.ts +14 -0
  36. package/dist/src/bytes.js +59 -0
  37. package/dist/src/canon.d.ts +26 -0
  38. package/dist/src/canon.js +57 -0
  39. package/dist/src/config.d.ts +111 -0
  40. package/dist/src/config.js +91 -0
  41. package/dist/src/derive/src/deduction.d.ts +125 -0
  42. package/dist/src/derive/src/deduction.js +155 -0
  43. package/dist/src/derive/src/index.d.ts +7 -0
  44. package/dist/src/derive/src/index.js +11 -0
  45. package/dist/src/derive/src/priority-queue.d.ts +20 -0
  46. package/dist/src/derive/src/priority-queue.js +73 -0
  47. package/dist/src/derive/src/rewrite.d.ts +56 -0
  48. package/dist/src/derive/src/rewrite.js +100 -0
  49. package/dist/src/derive/src/trie.d.ts +90 -0
  50. package/dist/src/derive/src/trie.js +217 -0
  51. package/dist/src/derive/test/derive.test.d.ts +1 -0
  52. package/dist/src/derive/test/derive.test.js +122 -0
  53. package/dist/src/extension.d.ts +37 -0
  54. package/dist/src/extension.js +7 -0
  55. package/dist/src/geometry.d.ts +148 -0
  56. package/dist/src/geometry.js +511 -0
  57. package/dist/src/index.d.ts +16 -0
  58. package/dist/src/index.js +18 -0
  59. package/dist/src/ingest-cache.d.ts +41 -0
  60. package/dist/src/ingest-cache.js +161 -0
  61. package/dist/src/mind/articulation.d.ts +6 -0
  62. package/dist/src/mind/articulation.js +99 -0
  63. package/dist/src/mind/attention.d.ts +72 -0
  64. package/dist/src/mind/attention.js +898 -0
  65. package/dist/src/mind/canonical.d.ts +29 -0
  66. package/dist/src/mind/canonical.js +88 -0
  67. package/dist/src/mind/graph-search.d.ts +270 -0
  68. package/dist/src/mind/graph-search.js +927 -0
  69. package/dist/src/mind/index.d.ts +5 -0
  70. package/dist/src/mind/index.js +5 -0
  71. package/dist/src/mind/junction.d.ts +95 -0
  72. package/dist/src/mind/junction.js +262 -0
  73. package/dist/src/mind/learning.d.ts +47 -0
  74. package/dist/src/mind/learning.js +233 -0
  75. package/dist/src/mind/match.d.ts +113 -0
  76. package/dist/src/mind/match.js +446 -0
  77. package/dist/src/mind/mechanisms/alu.d.ts +4 -0
  78. package/dist/src/mind/mechanisms/alu.js +29 -0
  79. package/dist/src/mind/mechanisms/cast.d.ts +35 -0
  80. package/dist/src/mind/mechanisms/cast.js +461 -0
  81. package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
  82. package/dist/src/mind/mechanisms/confluence.js +225 -0
  83. package/dist/src/mind/mechanisms/cover.d.ts +6 -0
  84. package/dist/src/mind/mechanisms/cover.js +179 -0
  85. package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
  86. package/dist/src/mind/mechanisms/extraction.js +342 -0
  87. package/dist/src/mind/mechanisms/recall.d.ts +13 -0
  88. package/dist/src/mind/mechanisms/recall.js +235 -0
  89. package/dist/src/mind/mind.d.ts +273 -0
  90. package/dist/src/mind/mind.js +598 -0
  91. package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
  92. package/dist/src/mind/pipeline-mechanism.js +213 -0
  93. package/dist/src/mind/pipeline.d.ts +20 -0
  94. package/dist/src/mind/pipeline.js +185 -0
  95. package/dist/src/mind/primitives.d.ts +63 -0
  96. package/dist/src/mind/primitives.js +251 -0
  97. package/dist/src/mind/rationale.d.ts +134 -0
  98. package/dist/src/mind/rationale.js +162 -0
  99. package/dist/src/mind/reasoning.d.ts +15 -0
  100. package/dist/src/mind/reasoning.js +162 -0
  101. package/dist/src/mind/recognition.d.ts +20 -0
  102. package/dist/src/mind/recognition.js +246 -0
  103. package/dist/src/mind/resonance.d.ts +23 -0
  104. package/dist/src/mind/resonance.js +0 -0
  105. package/dist/src/mind/trace.d.ts +15 -0
  106. package/dist/src/mind/trace.js +73 -0
  107. package/dist/src/mind/traverse.d.ts +113 -0
  108. package/dist/src/mind/traverse.js +488 -0
  109. package/dist/src/mind/types.d.ts +186 -0
  110. package/dist/src/mind/types.js +84 -0
  111. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  112. package/dist/src/rabitq-ivf/src/database.js +201 -0
  113. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  114. package/dist/src/rabitq-ivf/src/index.js +4 -0
  115. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  116. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  117. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  118. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  119. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  120. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  121. package/dist/src/sema.d.ts +31 -0
  122. package/dist/src/sema.js +63 -0
  123. package/dist/src/store-sqlite.d.ts +184 -0
  124. package/dist/src/store-sqlite.js +942 -0
  125. package/dist/src/store.d.ts +654 -0
  126. package/dist/src/store.js +1612 -0
  127. package/dist/src/vec.d.ts +31 -0
  128. package/dist/src/vec.js +109 -0
  129. package/package.json +1 -1
  130. package/src/mind/graph-search.ts +128 -46
  131. package/src/mind/mind.ts +37 -0
@@ -0,0 +1,225 @@
1
+ // confluence.ts — Confluence Join (Section 4 of the mind).
2
+ //
3
+ // THE CLASS THIS SOLVES: conjunctive queries — answers that are stored in NO
4
+ // single fact and exist only as the INTERSECTION of independent evidence
5
+ // streams. "Which material is translucent and featherlight?" No learnt form
6
+ // contains the answer; each constraint reaches its own set of exemplars, and
7
+ // the entity satisfying both lives exactly where those sets MEET. Every
8
+ // other mechanism produces its answer by following ONE evidence path (a
9
+ // chain, a reverse step, a halo hop, one aligned frame); the consensus climb
10
+ // SUMS votes, fusion CONCATENATES topics, CAST COMPARES two seats — none of
11
+ // them intersects, so this class was previously answered wrong (fusion pairs
12
+ // one fact per constraint, from DIFFERENT entities).
13
+ //
14
+ // THE MEET IS NATIVE, NOT A BYTE SCAN. The store is content-addressed: any
15
+ // content two deposits share IS the same node id, interned once at write
16
+ // time (hash-consing) — so "what do these two facts have in common?" is a
17
+ // SET INTERSECTION OF IDENTITIES the write side already computed, asked
18
+ // through the canonical window read (leafIdRun/findBranch — the same
19
+ // write/read contract recognition runs on). Three identity/structure tests
20
+ // make the whole mechanism:
21
+ //
22
+ // • constraint streams — the consensus climb's ranked anchors, each bound
23
+ // to the query spans whose DISCRIMINATIVE windows it holds by identity
24
+ // (a resonance-voted anchor holding none of the query's discriminative
25
+ // content is no constraint at all); two streams are independent when
26
+ // the content they bind is disjoint;
27
+ // • the meet — window ids present in BOTH anchors and ABSENT from the
28
+ // query: shared-with-query windows are the constraint being re-named
29
+ // (or its scaffolding), so subtracting the query's own window ids
30
+ // leaves exactly the content the question asks FOR — the open seat;
31
+ // • the filler/scaffolding separator — the same structural IDF the climb
32
+ // derives (edgeAncestors' contextsReached): shared content reaching a
33
+ // corpus minority of contexts is an entity, content reaching a majority
34
+ // is frame scaffolding. No statistics, no learning — the same global-
35
+ // quantity-from-capped-local-probes reading that makes the climb's IDF
36
+ // work, pointed at a new question.
37
+ //
38
+ // HONESTY: the meet can only ever name content that structurally exists in
39
+ // two independently learnt exemplars — an empty intersection yields null and
40
+ // the ordinary pipeline decides. Confluence cannot fabricate.
41
+ import { read } from "../primitives.js";
42
+ import { corpusN, reachOf } from "../traverse.js";
43
+ import { dominates } from "../../geometry.js";
44
+ import { STEP } from "../graph-search.js";
45
+ import { unexplainedLabel } from "../rationale.js";
46
+ import { rItem, rNode } from "../trace.js";
47
+ /** The main confluence entry point. Given a query, detect whether it weaves
48
+ * two or more INDEPENDENT constraints (ranked anchors supported by disjoint
49
+ * query spans), intersect the constraints' evidence by content-addressed
50
+ * identity, and return the discriminative content the streams share — the
51
+ * entity that satisfies all constraints at once. Null when the query is
52
+ * not conjunctive or nothing lies in the intersection. */
53
+ export async function confluenceJoin(ctx, query, pre) {
54
+ const W = ctx.space.maxGroup;
55
+ if (query.length < 2 * W || ctx.store.edgeSourceCount() === 0)
56
+ return null;
57
+ const { ranked } = await pre.attention();
58
+ if (ranked.length < 2)
59
+ return null;
60
+ const N = corpusN(ctx);
61
+ // Response-scoped shared memos: the anchor-window identities and the
62
+ // structural-IDF reach live on Precomputed, so any other identity-based
63
+ // mechanism in the same response reuses them.
64
+ const reachMemo = pre.reachMemo;
65
+ const windowsOfAnchor = (anchor) => pre.windowsOf(anchor);
66
+ // The query's own window identities, offset → id (the canonical
67
+ // content-addressed read, canonical.windowIds): whatever the meet shares
68
+ // with the query is the CONSTRAINT being re-named (or its scaffolding),
69
+ // never the open seat the question asks for — subtracted by identity,
70
+ // below.
71
+ const queryWin = pre.queryWindows;
72
+ const queryIds = new Set(queryWin.values());
73
+ // A constraint must bind a CONSTITUENT, not a shard. A genuinely shared
74
+ // form weaves a contiguous RUN of shared discriminative windows — its
75
+ // merged cover span is the form's own length, beyond one perception
76
+ // quantum (2W: the same "two quanta of structure" bar the conjunctive
77
+ // precondition `query.length < 2W` and CAST's weave live under). A long
78
+ // stored document holds thousands of W-windows and will hold a FEW of any
79
+ // query's by accident, but accidental sharing is one window (a merged
80
+ // span of W, at most ~W+overlap bytes: "ow ma", "ys a", "ías " —
81
+ // observed), never a run ("​ translucent", " featherlight" — the genuine
82
+ // constraints). Shard-bound streams are no constraints, and their meets
83
+ // are connective debris (". Sure,", "ngul" — observed).
84
+ const bindsAConstituent = (cover) => cover.some(([cs, ce]) => ce - cs >= 2 * W);
85
+ const streams = [];
86
+ const rankedCapped = ranked.length > pre.k ? ranked.slice(0, pre.k) : ranked;
87
+ for (const cand of rankedCapped) {
88
+ if (streams.some((s) => s.anchor === cand.anchor))
89
+ continue;
90
+ const ids = new Set(windowsOfAnchor(cand.anchor).values());
91
+ if (ids.size === 0)
92
+ continue;
93
+ const cover = [];
94
+ const held = [];
95
+ let curC = null;
96
+ let curH = null;
97
+ for (const [off, wid] of queryWin) {
98
+ if (!ids.has(wid))
99
+ continue;
100
+ if (curH !== null && off <= curH[1])
101
+ curH[1] = off + W;
102
+ else
103
+ held.push(curH = [off, off + W]);
104
+ if (dominates(reachOf(ctx, wid, N, reachMemo), N))
105
+ continue; // scaffolding never binds
106
+ if (curC !== null && off <= curC[1])
107
+ curC[1] = off + W;
108
+ else
109
+ cover.push(curC = [off, off + W]);
110
+ }
111
+ if (cover.length > 0 && bindsAConstituent(cover)) {
112
+ streams.push({ anchor: cand.anchor, vote: cand.vote, ids, cover, held });
113
+ }
114
+ }
115
+ if (streams.length < 2)
116
+ return null;
117
+ // Two streams are INDEPENDENT constraints when the query content they
118
+ // hold is disjoint — each answers a different part of what was asked.
119
+ const disjoint = (a, b) => a.cover.every(([as, ae]) => b.cover.every(([bs, be]) => be <= as || bs >= ae));
120
+ let met = null;
121
+ for (let i = 0; i < streams.length; i++) {
122
+ for (let j = i + 1; j < streams.length; j++) {
123
+ const a = streams[i];
124
+ const b = streams[j];
125
+ if (!disjoint(a, b))
126
+ continue;
127
+ const wa = windowsOfAnchor(a.anchor);
128
+ const wb = b.ids;
129
+ // ── The MEET: in both anchors, not in the query ────────────────────
130
+ // Offsets of A whose window id is shared with B and absent from the
131
+ // query — merged into maximal contiguous spans (windows overlap, so
132
+ // consecutive shared offsets weave one span).
133
+ const spans = [];
134
+ let cur = null;
135
+ for (const [off, wid] of wa) {
136
+ const inMeet = wb.has(wid) && !queryIds.has(wid);
137
+ if (inMeet) {
138
+ if (cur !== null && off <= cur[1])
139
+ cur[1] = off + W;
140
+ else
141
+ spans.push(cur = [off, off + W]);
142
+ }
143
+ }
144
+ if (spans.length === 0)
145
+ continue;
146
+ const aBytes = read(ctx, a.anchor);
147
+ for (const [s, e] of spans) {
148
+ // Scaffolding gate: the span's MOST discriminative window decides.
149
+ // Content reaching a corpus MAJORITY of contexts discriminates
150
+ // nothing (the same half-dominance convention every wrapper test
151
+ // uses); the query-subtraction above already removed everything the
152
+ // question names, so what survives here is a genuine open-seat
153
+ // entity.
154
+ let reach = Infinity;
155
+ for (let off = s; off + W <= e; off++) {
156
+ const wid = wa.get(off);
157
+ if (wid !== undefined && wb.has(wid) && !queryIds.has(wid)) {
158
+ reach = Math.min(reach, reachOf(ctx, wid, N, reachMemo));
159
+ }
160
+ }
161
+ if (!isFinite(reach) || dominates(reach, N))
162
+ continue;
163
+ const len = e - s;
164
+ if (met === null || reach < met.reach ||
165
+ (reach === met.reach && len > met.len)) {
166
+ met = { bytes: aBytes.subarray(s, e), reach, len, a, b };
167
+ }
168
+ }
169
+ }
170
+ }
171
+ if (met === null)
172
+ return null;
173
+ const t = ctx.trace?.enter("confluence", [rItem(query, "query")]);
174
+ ctx.trace?.step("intersectEvidence", [
175
+ rNode(ctx, met.a.anchor, "constraint", met.a.vote),
176
+ rNode(ctx, met.b.anchor, "constraint", met.b.vote),
177
+ ], [rItem(met.bytes, "meet")], `the discriminative content BOTH constraints' evidence shares, by content-addressed identity (reach ${met.reach} of ${N} contexts)`);
178
+ t?.done([rItem(met.bytes, "answer")], "conjunctive join — the entity where the independent evidence streams meet");
179
+ // Evidence: the query spans whose content the two streams hold by
180
+ // identity (scaffolding included — held, not just the binding cover);
181
+ // the acts were two constraint matches and one meet.
182
+ const accounted = [
183
+ ...met.a.held,
184
+ ...met.b.held,
185
+ ];
186
+ return {
187
+ bytes: met.bytes,
188
+ used: new Set([met.a.anchor, met.b.anchor]),
189
+ accounted,
190
+ moves: 3 * STEP,
191
+ unexplained: unexplainedLabel(query, accounted),
192
+ };
193
+ }
194
+ // ── Pipeline mechanism ──────────────────────────────────────────────────────
195
+ export const confluenceMechanism = {
196
+ name: "confluence",
197
+ provenance: "join",
198
+ async floor(_ctx, query, pre, worthRunning) {
199
+ const W = _ctx.space.maxGroup;
200
+ if (query.length < 2 * W || _ctx.store.edgeSourceCount() === 0)
201
+ return null;
202
+ // Confluence's floor is always exactly 3*STEP when it exists — same
203
+ // investment discipline as CAST's (see cast.ts): when the bound already
204
+ // cannot beat the incumbent, return it UNINVESTED (never first-touch the
205
+ // climb just to be pruned) and let the pipeline record the truthful
206
+ // "cannot beat incumbent" note.
207
+ if (!worthRunning(3 * STEP))
208
+ return 3 * STEP;
209
+ if ((await pre.attention()).ranked.length < 2)
210
+ return null;
211
+ return 3 * STEP;
212
+ },
213
+ async run(ctx, query, pre) {
214
+ const met = await confluenceJoin(ctx, query, pre);
215
+ if (!met)
216
+ return [];
217
+ return [{
218
+ bytes: met.bytes,
219
+ accounted: met.accounted,
220
+ moves: met.moves,
221
+ used: met.used,
222
+ unexplained: met.unexplained,
223
+ }];
224
+ },
225
+ };
@@ -0,0 +1,6 @@
1
+ import type { MindContext } from "../types.js";
2
+ import type { Site } from "../graph-search.js";
3
+ import type { PipelineMechanism } from "../pipeline-mechanism.js";
4
+ export declare function resolveConcepts(ctx: MindContext, sites: Site[]): Promise<Map<number, number>>;
5
+ export declare function resolveConnectors(ctx: MindContext, sites: ReadonlyArray<Site>): Promise<Map<string, Uint8Array>>;
6
+ export declare const coverMechanism: PipelineMechanism;
@@ -0,0 +1,179 @@
1
+ // mechanisms/cover.ts — Cover (Grounding II): the query's own decomposition
2
+ // composes an answer through ONE lightest-derivation search.
3
+ //
4
+ // Cover consumes recognition directly (its axioms are the query's own
5
+ // decomposition) plus the computed spans any parse()-bearing mechanism
6
+ // contributed: computed spans MASK colliding recognised sites and enter the
7
+ // search at zero cost ("computation always wins", §16.3) — which is also why
8
+ // cover runs FIRST in defaultMechanisms: a computed-backed cover becomes a
9
+ // near-zero-cost incumbent that prunes the other mechanisms through the
10
+ // ordinary admissible-floor check, with no extension special-case anywhere.
11
+ import { read, resolve } from "../primitives.js";
12
+ import { guidedFirst } from "../traverse.js";
13
+ import { conceptHop } from "../match.js";
14
+ import { bridge } from "../resonance.js";
15
+ import { liftAnswer } from "../types.js";
16
+ import { decodeText, unexplainedLabel } from "../rationale.js";
17
+ import { rItem, rNode, traceDerivation } from "../trace.js";
18
+ // ── Concept / connector pre-resolution ──────────────────────────────────────
19
+ export async function resolveConcepts(ctx, sites) {
20
+ const target = new Map();
21
+ const visited = new Set();
22
+ for (const { payload: n } of sites) {
23
+ if (visited.has(n))
24
+ continue;
25
+ visited.add(n);
26
+ if (ctx.store.hasNext(n))
27
+ continue;
28
+ const hop = await conceptHop(ctx, n);
29
+ if (hop !== null)
30
+ target.set(n, hop);
31
+ }
32
+ if (target.size > 0) {
33
+ ctx.trace?.step("resolveConcepts", [...target.keys()].map((n) => rNode(ctx, n, "edgeless-form")), [...target.values()].map((h) => rNode(ctx, h, "concept-sibling")), "borrow a synonym's continuation edge for each edge-less form (a concept/halo hop)");
34
+ }
35
+ return target;
36
+ }
37
+ export async function resolveConnectors(ctx, sites) {
38
+ const links = new Map();
39
+ const ordered = [...sites].sort((a, b) => a.start - b.start);
40
+ const answerOf = (n) => guidedFirst(ctx, n) ?? n;
41
+ const bridgePair = async (l, r) => {
42
+ if (l === r || links.has(l + "," + r))
43
+ return;
44
+ const link = await bridge(ctx, read(ctx, l), read(ctx, r));
45
+ if (link !== null)
46
+ links.set(l + "," + r, link);
47
+ };
48
+ for (let i = 0; i + 1 < ordered.length; i++) {
49
+ if (ordered[i].end !== ordered[i + 1].start)
50
+ continue;
51
+ const lefts = [ordered[i].payload, answerOf(ordered[i].payload)];
52
+ const rights = [ordered[i + 1].payload, answerOf(ordered[i + 1].payload)];
53
+ for (const l of new Set(lefts)) {
54
+ for (const r of new Set(rights)) {
55
+ await bridgePair(l, r);
56
+ await bridgePair(r, l);
57
+ }
58
+ }
59
+ }
60
+ const orderedNodes = [];
61
+ const seenN = new Set();
62
+ for (const s of ordered) {
63
+ const node = guidedFirst(ctx, s.payload) ?? s.payload;
64
+ if (seenN.has(node))
65
+ continue;
66
+ seenN.add(node);
67
+ orderedNodes.push({ node, bytes: read(ctx, node) });
68
+ }
69
+ if (orderedNodes.length >= 3) {
70
+ const first = orderedNodes[0];
71
+ const W = ctx.space.maxGroup;
72
+ let middleBytes = 0; // Σ bytes of the answers BETWEEN first and m-th
73
+ for (let m = 1; m < orderedNodes.length; m++) {
74
+ const key = first.node + "," + orderedNodes[m].node;
75
+ if (links.has(key)) {
76
+ middleBytes += orderedNodes[m].bytes.length;
77
+ continue;
78
+ }
79
+ // The N-ary interior legitimately holds every intermediate answer
80
+ // plus one W-quantum of glue per joint — pass that allowance so the
81
+ // bridge's phrase-scale cap admits the whole learnt run.
82
+ const allowance = middleBytes + (m + 1) * W;
83
+ const interior = await bridge(ctx, first.bytes, orderedNodes[m].bytes, allowance);
84
+ if (interior !== null)
85
+ links.set(key, interior);
86
+ middleBytes += orderedNodes[m].bytes.length;
87
+ }
88
+ }
89
+ if (links.size > 0) {
90
+ ctx.trace?.step("resolveConnectors", ordered.map((s) => rItem(read(ctx, s.payload), "answer", s.payload)), [...links.entries()].map(([pair, bytes]) => ({
91
+ text: `${pair}: "${decodeText(bytes)}"`,
92
+ role: "connector",
93
+ })), "the bytes the graph splices between adjacent answers (asked of the gist space)");
94
+ }
95
+ return links;
96
+ }
97
+ // ── Pipeline mechanism ──────────────────────────────────────────────────────
98
+ export const coverMechanism = {
99
+ name: "cover",
100
+ provenance: "cover",
101
+ async floor(_ctx, _query, _pre, _worthRunning) {
102
+ return 0;
103
+ },
104
+ async run(ctx, query, pre) {
105
+ const { rec, computed } = pre;
106
+ // Masking: computed spans are authoritative. Remove recognised sites
107
+ // that overlap any computed span before building the cover search.
108
+ const sites = computed.length === 0
109
+ ? rec.sites
110
+ : rec.sites.filter((s) => !computed.some((u) => s.start < u.j && u.i < s.end));
111
+ if (computed.length > 0 && sites.length < rec.sites.length) {
112
+ ctx.trace?.step("maskByComputation", rec.sites.map((s) => rItem(query.subarray(s.start, s.end), "form", s.payload, [
113
+ s.start,
114
+ s.end,
115
+ ])), sites.map((s) => rItem(query.subarray(s.start, s.end), "form", s.payload, [
116
+ s.start,
117
+ s.end,
118
+ ])), "a computation always wins: recognised forms overlapping a computed span are dropped");
119
+ }
120
+ if (sites.length === 0 && computed.length === 0)
121
+ return [];
122
+ const connectors = await resolveConnectors(ctx, sites);
123
+ let splits = rec.splits;
124
+ if (computed.length > 0) {
125
+ splits = new Set(rec.splits);
126
+ for (const u of computed) {
127
+ splits.add(u.i);
128
+ splits.add(u.j);
129
+ }
130
+ }
131
+ const concepts = await resolveConcepts(ctx, sites);
132
+ const coverDeps = [
133
+ ctx.trace?.lastIndex("recognise"),
134
+ ctx.trace?.lastIndex("computeExtensions"),
135
+ ctx.trace?.lastIndex("resolveConcepts"),
136
+ ctx.trace?.lastIndex("resolveConnectors"),
137
+ ].filter((x) => x !== undefined);
138
+ // Convert ComputedSpan[] to ComputedResult[] for the graph search.
139
+ const computedResults = computed.map((u) => ({
140
+ i: u.i,
141
+ j: u.j,
142
+ bytes: u.bytes,
143
+ node: resolve(ctx, u.bytes) ?? undefined,
144
+ }));
145
+ const tCover = ctx.trace?.enter("cover", [
146
+ ...sites.map((s) => rItem(query.subarray(s.start, s.end), "form", s.payload, [
147
+ s.start,
148
+ s.end,
149
+ ])),
150
+ ...computedResults.map((u) => rItem(u.bytes, "computed")),
151
+ ], coverDeps.length ? coverDeps : undefined);
152
+ const solved = ctx.search.cover(query.length, sites, concepts, rec.leaves, splits, undefined, connectors, computedResults, ctx.trace ? (steps) => traceDerivation(ctx, steps) : undefined);
153
+ const segs = solved && solved.segs;
154
+ tCover?.done(segs === null
155
+ ? []
156
+ : segs.map((s) => rItem(s.bytes, s.rec ? "chosen" : "bridge", s.node, [s.i, s.j])), segs === null
157
+ ? "no cover of the query composed"
158
+ : "lightest derivation: the chosen spans, left to right");
159
+ if (segs === null)
160
+ return [];
161
+ const composed = liftAnswer(segs, query.length);
162
+ if (composed === null)
163
+ return [];
164
+ ctx.trace?.step("liftAnswer", segs.map((s) => rItem(s.bytes, s.rec ? "chosen" : "scaffolding", s.node, [s.i, s.j])), [rItem(composed, "answer", resolve(ctx, composed) ?? undefined)], "lift the recognised region out of the asker's framing", tCover ? [tCover.index] : undefined);
165
+ // accounted = RECOGNISED cover spans only — PASS-carried bytes
166
+ // are priced in cost already; the diagnostic label reflects the
167
+ // same distinction.
168
+ const accounted = segs
169
+ .filter((s) => s.rec)
170
+ .map((s) => [s.i, s.j]);
171
+ return [{
172
+ bytes: composed,
173
+ accounted,
174
+ moves: 0,
175
+ weight: solved.cost, // A*LD derivation's g-value IS the weight
176
+ unexplained: unexplainedLabel(query, accounted),
177
+ }];
178
+ },
179
+ };
@@ -0,0 +1,67 @@
1
+ import type { Vec } from "../../vec.js";
2
+ import type { MindContext } from "../types.js";
3
+ import type { PipelineMechanism, Precomputed } from "../pipeline-mechanism.js";
4
+ /** Find the first span-shaped skill exemplar among the ranked anchors from
5
+ * climbAttentionAll and read the analogous span from the query. Returns
6
+ * the extracted bytes PLUS the query spans the skill ACCOUNTED FOR — the
7
+ * located frames AND any read span BOUNDED by located frames on both
8
+ * sides, the elementary evidence think's grounding decider weighs. A
9
+ * bounded read is explained: the skill located both its borders in the
10
+ * query and emitted exactly what sits between them. An OPEN-ENDED read
11
+ * (the exemplar's answer reaches the context's end, so the query is read
12
+ * to its own end with no located right border) remains a guess about where
13
+ * the span stops — it stays unaccounted, priced by exclusion like the
14
+ * cover's bridged bytes. (Accounting frames only — the earlier convention
15
+ * — let a CAST juxtaposition that merely echoed the query's exact site
16
+ * outweigh a correct bounded extraction: the same span counted as
17
+ * explained for one mechanism and not the other, and the asymmetry, not
18
+ * the answers' merits, decided the grounding.) Null when no skill
19
+ * applies. */
20
+ export declare function extractBySkill(ctx: MindContext, query: Uint8Array, pre: Precomputed): Promise<{
21
+ bytes: Uint8Array;
22
+ accounted: Array<[number, number]>;
23
+ unexplained: string;
24
+ } | null>;
25
+ /** Decompose an answer into substrings of its surrounding context, in order —
26
+ * the STRONG span-shape reading (see the section note above). Returns null
27
+ * when no greedy longest-run decomposition exists. Adjacent runs that
28
+ * connect contiguously are merged. */
29
+ export declare function answerRunsInContext(_ctx: MindContext, context: Uint8Array, answer: Uint8Array): Array<{
30
+ start: number;
31
+ end: number;
32
+ ansLen: number;
33
+ }> | null;
34
+ /** Check whether an anchor is a span-shaped skill exemplar: it represents a
35
+ * fact whose context and answer together form a span-in-context pattern.
36
+ * If the anchor has a nextOf continuation, that is the answer and the anchor
37
+ * itself is the context. Otherwise the anchor's prevOf parents provide
38
+ * candidate contexts, and the longest one whose span is span-shaped wins. */
39
+ export declare function skillExemplar(ctx: MindContext, anchor: number, guide?: Vec | null): Promise<{
40
+ contextBytes: Uint8Array;
41
+ answerBytes: Uint8Array;
42
+ } | null>;
43
+ /** Whether the answer is a SPARSE subsequence of the context (bytes in
44
+ * order, arbitrary gaps) — the OPEN span-shape reading (see the section
45
+ * note above). This is what lets extraction validate a MULTI-PIECE
46
+ * exemplar whose answer is stitched from several context runs — but it is
47
+ * deliberately permissive, so it must never be used as evidence that one
48
+ * span was "drawn from" another (see {@link containsSpan} for that).
49
+ *
50
+ * There is deliberately NO containsSpan pre-check here: strict containment
51
+ * IMPLIES the subsequence embedding (a contiguous run, or a resolved node —
52
+ * whose content-addressed identity means its bytes occur contiguously — is
53
+ * an in-order embedding with zero gaps), so the scan below decides alone,
54
+ * with the same truth value. The old pre-check re-perceived the context
55
+ * (a full river fold) per CANDIDATE in skillExemplar's √N-capped loop —
56
+ * pure cost, no discrimination. */
57
+ export declare function isSpanShaped(_ctx: MindContext, context: Uint8Array, answer: Uint8Array): boolean;
58
+ /** STRICT containment: the answer's resolved node appears in the context's
59
+ * folded tree, or the answer occurs as one CONTIGUOUS byte run of the
60
+ * context. This is real evidence the answer was drawn from the context.
61
+ * Fusion gates on this — the sparse-subsequence reading of
62
+ * {@link isSpanShaped} is trivially satisfied by short answers over long
63
+ * queries ("cold" is a gap-tolerant subsequence of most sentences holding
64
+ * c…o…l…d in order), and gating fusion on it silently starved multi-topic
65
+ * queries of their further points of attention. */
66
+ export declare function containsSpan(ctx: MindContext, context: Uint8Array, answer: Uint8Array): boolean;
67
+ export declare const extractionMechanism: PipelineMechanism;