@hviana/sema 0.1.5 → 0.1.7

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 (170) hide show
  1. package/AGENTS.md +6 -5
  2. package/CITATION.cff +49 -0
  3. package/HOW_IT_WORKS.md +11 -12
  4. package/README.md +7 -5
  5. package/dist/example/demo.js +25 -25
  6. package/dist/example/train_base.d.ts +19 -21
  7. package/dist/example/train_base.js +1700 -1952
  8. package/dist/src/alphabet.d.ts +3 -3
  9. package/dist/src/alphabet.js +24 -27
  10. package/dist/src/alu/src/alu.d.ts +169 -194
  11. package/dist/src/alu/src/alu.js +374 -414
  12. package/dist/src/alu/src/expr.d.ts +36 -43
  13. package/dist/src/alu/src/expr.js +252 -278
  14. package/dist/src/alu/src/index.d.ts +9 -98
  15. package/dist/src/alu/src/index.js +10 -64
  16. package/dist/src/alu/src/kernel-arith.d.ts +1 -5
  17. package/dist/src/alu/src/kernel-arith.js +195 -285
  18. package/dist/src/alu/src/kernel-bits.d.ts +1 -5
  19. package/dist/src/alu/src/kernel-bits.js +81 -115
  20. package/dist/src/alu/src/kernel-logic.js +33 -63
  21. package/dist/src/alu/src/kernel-nd.js +155 -195
  22. package/dist/src/alu/src/kernel-numeric.d.ts +16 -80
  23. package/dist/src/alu/src/kernel-numeric.js +259 -331
  24. package/dist/src/alu/src/operation.d.ts +112 -132
  25. package/dist/src/alu/src/operation.js +149 -163
  26. package/dist/src/alu/src/parser.d.ts +168 -175
  27. package/dist/src/alu/src/parser.js +382 -421
  28. package/dist/src/alu/src/resonance.d.ts +16 -25
  29. package/dist/src/alu/src/resonance.js +49 -56
  30. package/dist/src/alu/src/text.d.ts +3 -7
  31. package/dist/src/alu/src/text.js +31 -37
  32. package/dist/src/alu/src/value.d.ts +14 -14
  33. package/dist/src/alu/src/value.js +150 -160
  34. package/dist/src/alu/test/alu.test.js +543 -656
  35. package/dist/src/bytes.d.ts +1 -5
  36. package/dist/src/bytes.js +33 -40
  37. package/dist/src/config.d.ts +99 -102
  38. package/dist/src/config.js +78 -83
  39. package/dist/src/derive/src/deduction.d.ts +60 -62
  40. package/dist/src/derive/src/deduction.js +103 -109
  41. package/dist/src/derive/src/index.d.ts +1 -7
  42. package/dist/src/derive/src/priority-queue.d.ts +8 -8
  43. package/dist/src/derive/src/priority-queue.js +57 -61
  44. package/dist/src/derive/src/rewrite.d.ts +15 -18
  45. package/dist/src/derive/src/rewrite.js +59 -67
  46. package/dist/src/derive/src/trie.d.ts +56 -56
  47. package/dist/src/derive/src/trie.js +175 -179
  48. package/dist/src/derive/test/derive.test.js +96 -100
  49. package/dist/src/extension.d.ts +13 -16
  50. package/dist/src/geometry.d.ts +29 -43
  51. package/dist/src/geometry.js +324 -268
  52. package/dist/src/index.d.ts +2 -17
  53. package/dist/src/index.js +2 -12
  54. package/dist/src/ingest-cache.d.ts +25 -30
  55. package/dist/src/ingest-cache.js +108 -127
  56. package/dist/src/mind/articulation.d.ts +1 -5
  57. package/dist/src/mind/articulation.js +77 -112
  58. package/dist/src/mind/attention.d.ts +40 -108
  59. package/dist/src/mind/attention.js +754 -872
  60. package/dist/src/mind/canonical.d.ts +4 -19
  61. package/dist/src/mind/canonical.js +27 -31
  62. package/dist/src/mind/graph-search.d.ts +201 -225
  63. package/dist/src/mind/graph-search.js +742 -821
  64. package/dist/src/mind/index.d.ts +2 -10
  65. package/dist/src/mind/junction.d.ts +31 -58
  66. package/dist/src/mind/junction.js +172 -237
  67. package/dist/src/mind/learning.d.ts +16 -52
  68. package/dist/src/mind/learning.js +143 -165
  69. package/dist/src/mind/match.d.ts +20 -69
  70. package/dist/src/mind/match.js +259 -318
  71. package/dist/src/mind/mechanisms/alu.js +16 -16
  72. package/dist/src/mind/mechanisms/cast.d.ts +9 -13
  73. package/dist/src/mind/mechanisms/cast.js +363 -456
  74. package/dist/src/mind/mechanisms/confluence.d.ts +8 -12
  75. package/dist/src/mind/mechanisms/confluence.js +152 -183
  76. package/dist/src/mind/mechanisms/cover.d.ts +2 -8
  77. package/dist/src/mind/mechanisms/cover.js +148 -210
  78. package/dist/src/mind/mechanisms/extraction.d.ts +8 -34
  79. package/dist/src/mind/mechanisms/extraction.js +234 -288
  80. package/dist/src/mind/mechanisms/recall.d.ts +6 -10
  81. package/dist/src/mind/mechanisms/recall.js +141 -185
  82. package/dist/src/mind/mind.d.ts +194 -155
  83. package/dist/src/mind/mind.js +392 -289
  84. package/dist/src/mind/pipeline-mechanism.d.ts +112 -124
  85. package/dist/src/mind/pipeline-mechanism.js +161 -172
  86. package/dist/src/mind/pipeline.d.ts +4 -14
  87. package/dist/src/mind/pipeline.js +125 -189
  88. package/dist/src/mind/primitives.d.ts +20 -33
  89. package/dist/src/mind/primitives.js +124 -120
  90. package/dist/src/mind/rationale.d.ts +86 -98
  91. package/dist/src/mind/rationale.js +113 -121
  92. package/dist/src/mind/reasoning.d.ts +2 -13
  93. package/dist/src/mind/reasoning.js +129 -166
  94. package/dist/src/mind/recognition.d.ts +1 -4
  95. package/dist/src/mind/recognition.js +198 -210
  96. package/dist/src/mind/resonance.d.ts +5 -22
  97. package/dist/src/mind/resonance.js +0 -0
  98. package/dist/src/mind/trace.d.ts +6 -25
  99. package/dist/src/mind/trace.js +50 -58
  100. package/dist/src/mind/traverse.d.ts +29 -58
  101. package/dist/src/mind/traverse.js +344 -356
  102. package/dist/src/mind/types.d.ts +122 -127
  103. package/dist/src/mind/types.js +60 -69
  104. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  105. package/dist/src/rabitq-ivf/src/database.js +201 -0
  106. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  107. package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/index.js +1 -3
  108. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  109. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  110. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  111. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  112. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  113. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  114. package/dist/src/sema.d.ts +9 -13
  115. package/dist/src/sema.js +26 -40
  116. package/dist/src/store-sqlite.d.ts +171 -166
  117. package/dist/src/store-sqlite.js +768 -662
  118. package/dist/src/store.d.ts +597 -630
  119. package/dist/src/store.js +1434 -1581
  120. package/dist/src/vec.d.ts +5 -9
  121. package/dist/src/vec.js +61 -73
  122. package/example/train_base.ts +33 -15
  123. package/index.html +65 -0
  124. package/package.json +1 -1
  125. package/src/alu/README.md +1 -1
  126. package/src/alu/src/index.ts +1 -1
  127. package/src/config.ts +19 -27
  128. package/src/geometry.ts +93 -1
  129. package/src/index.ts +6 -11
  130. package/src/mind/attention.ts +11 -6
  131. package/src/mind/mechanisms/recall.ts +29 -13
  132. package/src/mind/mind.ts +250 -19
  133. package/src/mind/primitives.ts +43 -6
  134. package/src/mind/recognition.ts +26 -8
  135. package/src/mind/traverse.ts +47 -0
  136. package/src/mind/types.ts +20 -21
  137. package/src/rabitq-ivf/README.md +56 -0
  138. package/src/rabitq-ivf/src/database.ts +276 -0
  139. package/src/{rabitq-hnsw → rabitq-ivf}/src/index.ts +2 -5
  140. package/src/rabitq-ivf/src/ivf.ts +1330 -0
  141. package/src/{rabitq-hnsw → rabitq-ivf}/src/prng.ts +1 -1
  142. package/src/store-sqlite.ts +204 -9
  143. package/src/store.ts +27 -34
  144. package/test/08-storage.test.mjs +3 -3
  145. package/test/13-conversation.test.mjs +190 -20
  146. package/test/14-scaling.test.mjs +2 -2
  147. package/test/35-ivf.test.mjs +263 -0
  148. package/test/36-bloom.test.mjs +123 -0
  149. package/dist/src/rabitq-hnsw/src/database.d.ts +0 -202
  150. package/dist/src/rabitq-hnsw/src/database.js +0 -405
  151. package/dist/src/rabitq-hnsw/src/heap.d.ts +0 -22
  152. package/dist/src/rabitq-hnsw/src/heap.js +0 -94
  153. package/dist/src/rabitq-hnsw/src/hnsw.d.ts +0 -125
  154. package/dist/src/rabitq-hnsw/src/hnsw.js +0 -500
  155. package/dist/src/rabitq-hnsw/src/index.d.ts +0 -15
  156. package/dist/src/rabitq-hnsw/src/prng.d.ts +0 -19
  157. package/dist/src/rabitq-hnsw/src/prng.js +0 -38
  158. package/dist/src/rabitq-hnsw/src/rabitq.d.ts +0 -95
  159. package/dist/src/rabitq-hnsw/src/rabitq.js +0 -299
  160. package/dist/src/rabitq-hnsw/src/store.d.ts +0 -162
  161. package/dist/src/rabitq-hnsw/src/store.js +0 -916
  162. package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +0 -1
  163. package/dist/src/rabitq-hnsw/test/hnsw.test.js +0 -1197
  164. package/src/rabitq-hnsw/README.md +0 -303
  165. package/src/rabitq-hnsw/src/database.ts +0 -492
  166. package/src/rabitq-hnsw/src/heap.ts +0 -90
  167. package/src/rabitq-hnsw/src/hnsw.ts +0 -514
  168. package/src/rabitq-hnsw/src/store.ts +0 -994
  169. package/src/rabitq-hnsw/test/hnsw.test.ts +0 -1213
  170. /package/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.ts +0 -0
@@ -31,174 +31,130 @@ import { rItem, rNode, traceFail } from "../trace.js";
31
31
  * the answers' merits, decided the grounding.) Null when no skill
32
32
  * applies. */
33
33
  export async function extractBySkill(ctx, query, pre) {
34
- const t = ctx.trace?.enter("extractBySkill", [
35
- rItem(query, "query"),
36
- ]);
37
- const fail = traceFail(t);
38
- // Use climbAttentionAll to get the FULL ranked list, not just the
39
- // roots that cleared commitVotes' significance floor. The floor
40
- // gates further points of attention for fusion, but extraction only
41
- // needs ONE anchor that IS a span-shaped skill exemplar — and on
42
- // some seeds the top-voted anchor is not one (e.g. a concept-merge
43
- // nickname outvotes the painting exemplars on shared substrings,
44
- // while the exemplars' votes fall below the floor). Iterating the
45
- // ranked list instead of just the roots lets extraction reach the
46
- // first painting-exemplar anchor regardless of its floor status.
47
- //
48
- const { ranked } = await pre.attention();
49
- if (ranked.length === 0) {
50
- return fail("no consensus anchor — no skill to apply");
51
- }
52
- let exemplar = null;
53
- let chosenAnchor = null;
54
- let skipped = 0;
55
- for (const cand of ranked) {
56
- const ex = await pre.spanShapedOf(cand.anchor);
57
- if (ex) {
58
- exemplar = ex;
59
- chosenAnchor = cand.anchor;
60
- break;
34
+ const t = ctx.trace?.enter("extractBySkill", [
35
+ rItem(query, "query"),
36
+ ]);
37
+ const fail = traceFail(t);
38
+ // Use climbAttentionAll to get the FULL ranked list, not just the
39
+ // roots that cleared commitVotes' significance floor. The floor
40
+ // gates further points of attention for fusion, but extraction only
41
+ // needs ONE anchor that IS a span-shaped skill exemplar — and on
42
+ // some seeds the top-voted anchor is not one (e.g. a concept-merge
43
+ // nickname outvotes the painting exemplars on shared substrings,
44
+ // while the exemplars' votes fall below the floor). Iterating the
45
+ // ranked list instead of just the roots lets extraction reach the
46
+ // first painting-exemplar anchor regardless of its floor status.
47
+ //
48
+ const { ranked } = await pre.attention();
49
+ if (ranked.length === 0) {
50
+ return fail("no consensus anchor — no skill to apply");
61
51
  }
62
- skipped++;
63
- }
64
- if (exemplar === null) {
65
- ctx.trace?.step(
66
- "trySkillAnchors",
67
- [],
68
- [],
69
- `none of ${ranked.length} ranked anchor(s) is a span-shaped skill exemplar`,
70
- );
71
- return fail("no consensus root is a span-shaped skill exemplar");
72
- }
73
- if (skipped > 0) {
74
- ctx.trace?.step(
75
- "trySkillAnchors",
76
- [
77
- rItem(query.subarray(0, 0), `skipped ${skipped}`),
78
- rNode(ctx, chosenAnchor, "chosen"),
79
- ],
80
- [],
81
- `skipped ${skipped} anchor(s) that are not skill exemplars`,
82
- );
83
- }
84
- const { contextBytes, answerBytes } = exemplar;
85
- const ansCtxRuns = answerRunsInContext(ctx, contextBytes, answerBytes);
86
- if (ansCtxRuns === null || ansCtxRuns.length === 0) {
87
- return fail("answer is not a subsequence of the context");
88
- }
89
- if (ansCtxRuns.length > 1) {
90
- ctx.trace?.step(
91
- "decomposeAnswer",
92
- [rItem(answerBytes, "multi-piece-answer")],
93
- ansCtxRuns.map((r) =>
94
- rItem(contextBytes.subarray(r.start, r.end), "piece", undefined, [
95
- r.start,
96
- r.end,
97
- ])
98
- ),
99
- `answer splits into ${ansCtxRuns.length} piece(s) within the exemplar context`,
100
- );
101
- }
102
- const pieces = [];
103
- const accounted = [];
104
- for (let ri = 0; ri < ansCtxRuns.length; ri++) {
105
- const run = ansCtxRuns[ri];
106
- const isLast = ri === ansCtxRuns.length - 1;
107
- const framePreLen = Math.min(run.start, ctx.space.maxGroup);
108
- const framePre = run.start > 0
109
- ? contextBytes.subarray(run.start - framePreLen, run.start)
110
- : null;
111
- const frames = [];
112
- let start = 0;
113
- if (framePre) {
114
- const prePos = locate(ctx, query, framePre, 0, pre.rec.sites);
115
- if (prePos < 0) {
116
- continue;
117
- }
118
- start = prePos + framePre.length;
119
- frames.push([prePos, start]); // the located frame IS matched evidence
120
- }
121
- let end;
122
- if (isLast) {
123
- if (run.end < contextBytes.length) {
124
- const framePostLen = Math.min(
125
- contextBytes.length - run.end,
126
- ctx.space.maxGroup,
127
- );
128
- const framePost = contextBytes.subarray(
129
- run.end,
130
- run.end + framePostLen,
131
- );
132
- const postPos = locate(
133
- ctx,
134
- query.subarray(start),
135
- framePost,
136
- 0,
137
- pre.rec.sites,
138
- );
139
- if (postPos < 0) {
140
- continue;
52
+ let exemplar = null;
53
+ let chosenAnchor = null;
54
+ let skipped = 0;
55
+ for (const cand of ranked) {
56
+ const ex = await pre.spanShapedOf(cand.anchor);
57
+ if (ex) {
58
+ exemplar = ex;
59
+ chosenAnchor = cand.anchor;
60
+ break;
141
61
  }
142
- end = start + postPos;
143
- frames.push([end, end + framePost.length]); // matched post-frame
144
- } else {
145
- end = query.length;
146
- }
147
- } else {
148
- const nextRun = ansCtxRuns[ri + 1];
149
- const nextPreLen = Math.min(nextRun.start, ctx.space.maxGroup);
150
- const nextPre = contextBytes.subarray(
151
- nextRun.start - nextPreLen,
152
- nextRun.start,
153
- );
154
- const nextPos = locate(
155
- ctx,
156
- query.subarray(start),
157
- nextPre,
158
- 0,
159
- pre.rec.sites,
160
- );
161
- if (nextPos < 0) {
162
- end = start + run.ansLen;
163
- } else {
164
- end = start + nextPos;
165
- frames.push([end, end + nextPre.length]); // matched next-frame
166
- }
62
+ skipped++;
63
+ }
64
+ if (exemplar === null) {
65
+ ctx.trace?.step("trySkillAnchors", [], [], `none of ${ranked.length} ranked anchor(s) is a span-shaped skill exemplar`);
66
+ return fail("no consensus root is a span-shaped skill exemplar");
67
+ }
68
+ if (skipped > 0) {
69
+ ctx.trace?.step("trySkillAnchors", [
70
+ rItem(query.subarray(0, 0), `skipped ${skipped}`),
71
+ rNode(ctx, chosenAnchor, "chosen"),
72
+ ], [], `skipped ${skipped} anchor(s) that are not skill exemplars`);
167
73
  }
168
- if (start >= end) {
169
- continue;
74
+ const { contextBytes, answerBytes } = exemplar;
75
+ const ansCtxRuns = answerRunsInContext(ctx, contextBytes, answerBytes);
76
+ if (ansCtxRuns === null || ansCtxRuns.length === 0) {
77
+ return fail("answer is not a subsequence of the context");
170
78
  }
171
- pieces.push(query.subarray(start, end));
172
- accounted.push(...frames);
173
- // Bounded on both sides ⇒ the read span itself is explained (see doc).
174
- // frames carries the pre-border (when the answer is not at the context's
175
- // start) and the located right border (post-frame or next piece's
176
- // pre-frame); only when BOTH borders were located is the read bounded.
177
- const preBounded = run.start === 0 || frames.some(([, e]) => e === start);
178
- const postBounded = frames.some(([b]) => b === end);
179
- if (preBounded && postBounded) {
180
- accounted.push([start, end]);
79
+ if (ansCtxRuns.length > 1) {
80
+ ctx.trace?.step("decomposeAnswer", [rItem(answerBytes, "multi-piece-answer")], ansCtxRuns.map((r) => rItem(contextBytes.subarray(r.start, r.end), "piece", undefined, [
81
+ r.start,
82
+ r.end,
83
+ ])), `answer splits into ${ansCtxRuns.length} piece(s) within the exemplar context`);
181
84
  }
182
- }
183
- if (pieces.length === 0) {
184
- return fail("no answer piece's frame located in the query");
185
- }
186
- const out = pieces.length === 1 ? pieces[0] : concatBytes(pieces);
187
- t?.done(
188
- [rItem(out, "extracted")],
189
- pieces.length === 1
190
- ? `apply a learnt extraction skill — read the analogous span of the query` +
191
- ` framed like "${decodeText(answerBytes)}" sits in its exemplar`
192
- : `apply a learnt MULTI-PIECE skill — read ${pieces.length} analogous` +
193
- ` pieces of the query and synthesize them like "${
194
- decodeText(answerBytes)
195
- }"`,
196
- );
197
- return {
198
- bytes: out,
199
- accounted,
200
- unexplained: unexplainedLabel(query, accounted),
201
- };
85
+ const pieces = [];
86
+ const accounted = [];
87
+ for (let ri = 0; ri < ansCtxRuns.length; ri++) {
88
+ const run = ansCtxRuns[ri];
89
+ const isLast = ri === ansCtxRuns.length - 1;
90
+ const framePreLen = Math.min(run.start, ctx.space.maxGroup);
91
+ const framePre = run.start > 0
92
+ ? contextBytes.subarray(run.start - framePreLen, run.start)
93
+ : null;
94
+ const frames = [];
95
+ let start = 0;
96
+ if (framePre) {
97
+ const prePos = locate(ctx, query, framePre, 0, pre.rec.sites);
98
+ if (prePos < 0)
99
+ continue;
100
+ start = prePos + framePre.length;
101
+ frames.push([prePos, start]); // the located frame IS matched evidence
102
+ }
103
+ let end;
104
+ if (isLast) {
105
+ if (run.end < contextBytes.length) {
106
+ const framePostLen = Math.min(contextBytes.length - run.end, ctx.space.maxGroup);
107
+ const framePost = contextBytes.subarray(run.end, run.end + framePostLen);
108
+ const postPos = locate(ctx, query.subarray(start), framePost, 0, pre.rec.sites);
109
+ if (postPos < 0)
110
+ continue;
111
+ end = start + postPos;
112
+ frames.push([end, end + framePost.length]); // matched post-frame
113
+ }
114
+ else {
115
+ end = query.length;
116
+ }
117
+ }
118
+ else {
119
+ const nextRun = ansCtxRuns[ri + 1];
120
+ const nextPreLen = Math.min(nextRun.start, ctx.space.maxGroup);
121
+ const nextPre = contextBytes.subarray(nextRun.start - nextPreLen, nextRun.start);
122
+ const nextPos = locate(ctx, query.subarray(start), nextPre, 0, pre.rec.sites);
123
+ if (nextPos < 0) {
124
+ end = start + run.ansLen;
125
+ }
126
+ else {
127
+ end = start + nextPos;
128
+ frames.push([end, end + nextPre.length]); // matched next-frame
129
+ }
130
+ }
131
+ if (start >= end)
132
+ continue;
133
+ pieces.push(query.subarray(start, end));
134
+ accounted.push(...frames);
135
+ // Bounded on both sides ⇒ the read span itself is explained (see doc).
136
+ // frames carries the pre-border (when the answer is not at the context's
137
+ // start) and the located right border (post-frame or next piece's
138
+ // pre-frame); only when BOTH borders were located is the read bounded.
139
+ const preBounded = run.start === 0 || frames.some(([, e]) => e === start);
140
+ const postBounded = frames.some(([b]) => b === end);
141
+ if (preBounded && postBounded)
142
+ accounted.push([start, end]);
143
+ }
144
+ if (pieces.length === 0) {
145
+ return fail("no answer piece's frame located in the query");
146
+ }
147
+ const out = pieces.length === 1 ? pieces[0] : concatBytes(pieces);
148
+ t?.done([rItem(out, "extracted")], pieces.length === 1
149
+ ? `apply a learnt extraction skill — read the analogous span of the query` +
150
+ ` framed like "${decodeText(answerBytes)}" sits in its exemplar`
151
+ : `apply a learnt MULTI-PIECE skill — read ${pieces.length} analogous` +
152
+ ` pieces of the query and synthesize them like "${decodeText(answerBytes)}"`);
153
+ return {
154
+ bytes: out,
155
+ accounted,
156
+ unexplained: unexplainedLabel(query, accounted),
157
+ };
202
158
  }
203
159
  // ── The two span-shape readings: OPEN acceptance vs. STRONG decomposition ──
204
160
  //
@@ -225,55 +181,52 @@ export async function extractBySkill(ctx, query, pre) {
225
181
  * when no greedy longest-run decomposition exists. Adjacent runs that
226
182
  * connect contiguously are merged. */
227
183
  export function answerRunsInContext(_ctx, context, answer) {
228
- const pos = indexOf(context, answer, 0);
229
- if (pos >= 0) {
230
- return [{ start: pos, end: pos + answer.length, ansLen: answer.length }];
231
- }
232
- const runs = [];
233
- let ai = 0;
234
- let ci = 0;
235
- while (ai < answer.length) {
236
- // Longest match of the remaining answer at any position of the remaining
237
- // context: one direct extend per context position — O(|ctx|·match) per
238
- // run, replacing the previous longest-first indexOf countdown whose
239
- // repeated scans were cubic on long sparse-subsequence answers.
240
- let bestLen = 0;
241
- let bestPos = -1;
242
- for (let p = ci; p < context.length; p++) {
243
- let l = 0;
244
- const maxL = Math.min(context.length - p, answer.length - ai);
245
- if (maxL <= bestLen) {
246
- break; // no later position can beat the best
247
- }
248
- while (l < maxL && context[p + l] === answer[ai + l]) {
249
- l++;
250
- }
251
- if (l > bestLen) {
252
- bestLen = l;
253
- bestPos = p;
254
- if (ai + l === answer.length) {
255
- break; // the whole remainder matched
256
- }
257
- }
184
+ const pos = indexOf(context, answer, 0);
185
+ if (pos >= 0) {
186
+ return [{ start: pos, end: pos + answer.length, ansLen: answer.length }];
258
187
  }
259
- if (bestLen === 0) {
260
- return null;
188
+ const runs = [];
189
+ let ai = 0;
190
+ let ci = 0;
191
+ while (ai < answer.length) {
192
+ // Longest match of the remaining answer at any position of the remaining
193
+ // context: one direct extend per context position — O(|ctx|·match) per
194
+ // run, replacing the previous longest-first indexOf countdown whose
195
+ // repeated scans were cubic on long sparse-subsequence answers.
196
+ let bestLen = 0;
197
+ let bestPos = -1;
198
+ for (let p = ci; p < context.length; p++) {
199
+ let l = 0;
200
+ const maxL = Math.min(context.length - p, answer.length - ai);
201
+ if (maxL <= bestLen)
202
+ break; // no later position can beat the best
203
+ while (l < maxL && context[p + l] === answer[ai + l])
204
+ l++;
205
+ if (l > bestLen) {
206
+ bestLen = l;
207
+ bestPos = p;
208
+ if (ai + l === answer.length)
209
+ break; // the whole remainder matched
210
+ }
211
+ }
212
+ if (bestLen === 0)
213
+ return null;
214
+ runs.push({ start: bestPos, end: bestPos + bestLen, ansLen: bestLen });
215
+ ai += bestLen;
216
+ ci = bestPos + bestLen;
261
217
  }
262
- runs.push({ start: bestPos, end: bestPos + bestLen, ansLen: bestLen });
263
- ai += bestLen;
264
- ci = bestPos + bestLen;
265
- }
266
- const merged = [];
267
- for (const r of runs) {
268
- const last = merged[merged.length - 1];
269
- if (last && r.start === last.end) {
270
- last.end = r.end;
271
- last.ansLen += r.ansLen;
272
- } else {
273
- merged.push({ ...r });
218
+ const merged = [];
219
+ for (const r of runs) {
220
+ const last = merged[merged.length - 1];
221
+ if (last && r.start === last.end) {
222
+ last.end = r.end;
223
+ last.ansLen += r.ansLen;
224
+ }
225
+ else {
226
+ merged.push({ ...r });
227
+ }
274
228
  }
275
- }
276
- return merged.length > 0 ? merged : null;
229
+ return merged.length > 0 ? merged : null;
277
230
  }
278
231
  /** Check whether an anchor is a span-shaped skill exemplar: it represents a
279
232
  * fact whose context and answer together form a span-in-context pattern.
@@ -281,42 +234,41 @@ export function answerRunsInContext(_ctx, context, answer) {
281
234
  * itself is the context. Otherwise the anchor's prevOf parents provide
282
235
  * candidate contexts, and the longest one whose span is span-shaped wins. */
283
236
  export async function skillExemplar(ctx, anchor, guide) {
284
- if (ctx.store.hasNext(anchor)) {
285
- const contextBytes = read(ctx, anchor);
286
- const answerBytes = await follow(ctx, anchor, guide);
287
- if (answerBytes !== null && isSpanShaped(ctx, contextBytes, answerBytes)) {
288
- return { contextBytes, answerBytes };
237
+ if (ctx.store.hasNext(anchor)) {
238
+ const contextBytes = read(ctx, anchor);
239
+ const answerBytes = await follow(ctx, anchor, guide);
240
+ if (answerBytes !== null && isSpanShaped(ctx, contextBytes, answerBytes)) {
241
+ return { contextBytes, answerBytes };
242
+ }
243
+ return null;
289
244
  }
290
- return null;
291
- }
292
- const answerBytes = read(ctx, anchor);
293
- // Candidate contexts, capped at the hub bound (a common answer's reverse
294
- // fan-in is corpus-sized).
295
- const capped = ctx.store.prevFirst(anchor, hubBound(ctx));
296
- const spanShaped = [];
297
- for (const p of capped) {
298
- const ctxB = read(ctx, p);
299
- if (ctxB.length > 0 && isSpanShaped(ctx, ctxB, answerBytes)) {
300
- spanShaped.push({ id: p, bytes: ctxB });
245
+ const answerBytes = read(ctx, anchor);
246
+ // Candidate contexts, capped at the hub bound (a common answer's reverse
247
+ // fan-in is corpus-sized).
248
+ const capped = ctx.store.prevFirst(anchor, hubBound(ctx));
249
+ const spanShaped = [];
250
+ for (const p of capped) {
251
+ const ctxB = read(ctx, p);
252
+ if (ctxB.length > 0 && isSpanShaped(ctx, ctxB, answerBytes)) {
253
+ spanShaped.push({ id: p, bytes: ctxB });
254
+ }
301
255
  }
302
- }
303
- if (spanShaped.length === 0) {
304
- return null;
305
- }
306
- // Among span-shaped contexts, the longest wins (the smallest spanning frame
307
- // heuristic's dual: more frame to locate in the query); the query gist,
308
- // when given, breaks LENGTH TIES via chooseAmong the same reverse-regime
309
- // disambiguator every context pick uses, whose gist cache spares the
310
- // re-fold this block once paid per tied candidate. Same strict first-seen
311
- // tie-break as the hand loop it replaces.
312
- const maxLen = Math.max(...spanShaped.map((s) => s.bytes.length));
313
- const longest = spanShaped.filter((s) => s.bytes.length === maxLen);
314
- let contextBytes = longest[0].bytes;
315
- if (guide && longest.length > 1) {
316
- const pick = chooseAmong(ctx, longest.map((s) => s.id), guide).id;
317
- contextBytes = longest.find((s) => s.id === pick).bytes;
318
- }
319
- return { contextBytes, answerBytes };
256
+ if (spanShaped.length === 0)
257
+ return null;
258
+ // Among span-shaped contexts, the longest wins (the smallest spanning frame
259
+ // heuristic's dual: more frame to locate in the query); the query gist,
260
+ // when given, breaks LENGTH TIES via chooseAmong — the same reverse-regime
261
+ // disambiguator every context pick uses, whose gist cache spares the
262
+ // re-fold this block once paid per tied candidate. Same strict first-seen
263
+ // tie-break as the hand loop it replaces.
264
+ const maxLen = Math.max(...spanShaped.map((s) => s.bytes.length));
265
+ const longest = spanShaped.filter((s) => s.bytes.length === maxLen);
266
+ let contextBytes = longest[0].bytes;
267
+ if (guide && longest.length > 1) {
268
+ const pick = chooseAmong(ctx, longest.map((s) => s.id), guide).id;
269
+ contextBytes = longest.find((s) => s.id === pick).bytes;
270
+ }
271
+ return { contextBytes, answerBytes };
320
272
  }
321
273
  /** Whether the answer is a SPARSE subsequence of the context (bytes in
322
274
  * order, arbitrary gaps) — the OPEN span-shape reading (see the section
@@ -333,13 +285,12 @@ export async function skillExemplar(ctx, anchor, guide) {
333
285
  * (a full river fold) per CANDIDATE in skillExemplar's √N-capped loop —
334
286
  * pure cost, no discrimination. */
335
287
  export function isSpanShaped(_ctx, context, answer) {
336
- let ai = 0;
337
- for (let ci = 0; ci < context.length && ai < answer.length; ci++) {
338
- if (context[ci] === answer[ai]) {
339
- ai++;
288
+ let ai = 0;
289
+ for (let ci = 0; ci < context.length && ai < answer.length; ci++) {
290
+ if (context[ci] === answer[ai])
291
+ ai++;
340
292
  }
341
- }
342
- return ai === answer.length;
293
+ return ai === answer.length;
343
294
  }
344
295
  /** STRICT containment: the answer's resolved node appears in the context's
345
296
  * folded tree, or the answer occurs as one CONTIGUOUS byte run of the
@@ -350,47 +301,42 @@ export function isSpanShaped(_ctx, context, answer) {
350
301
  * c…o…l…d in order), and gating fusion on it silently starved multi-topic
351
302
  * queries of their further points of attention. */
352
303
  export function containsSpan(ctx, context, answer) {
353
- const ansId = resolve(ctx, answer);
354
- if (ansId !== null) {
355
- let found = false;
356
- foldTree(ctx, perceive(ctx, context), 0, (_n, _s, _e, node) => {
357
- if (node === ansId) {
358
- found = true;
359
- }
360
- });
361
- if (found) {
362
- return true;
304
+ const ansId = resolve(ctx, answer);
305
+ if (ansId !== null) {
306
+ let found = false;
307
+ foldTree(ctx, perceive(ctx, context), 0, (_n, _s, _e, node) => {
308
+ if (node === ansId)
309
+ found = true;
310
+ });
311
+ if (found)
312
+ return true;
363
313
  }
364
- }
365
- return indexOf(context, answer, 0) >= 0;
314
+ return indexOf(context, answer, 0) >= 0;
366
315
  }
367
316
  // ── Pipeline mechanism ──────────────────────────────────────────────────────
368
317
  export const extractionMechanism = {
369
- name: "extraction",
370
- provenance: "extract",
371
- async floor(_ctx, _query, pre, worthRunning) {
372
- // Extraction's floor is always exactly CONCEPT+STEP when it exists —
373
- // same investment discipline as CAST's (see cast.ts): when the bound
374
- // already cannot beat the incumbent, return it UNINVESTED (never
375
- // first-touch the climb just to be pruned).
376
- if (!worthRunning(CONCEPT + STEP)) {
377
- return CONCEPT + STEP;
378
- }
379
- if ((await pre.attention()).ranked.length === 0) {
380
- return null;
381
- }
382
- return CONCEPT + STEP;
383
- },
384
- async run(ctx, query, pre) {
385
- const ex = await extractBySkill(ctx, query, pre);
386
- if (!ex) {
387
- return [];
388
- }
389
- return [{
390
- bytes: ex.bytes,
391
- accounted: ex.accounted,
392
- moves: CONCEPT + STEP * ex.accounted.length,
393
- unexplained: ex.unexplained,
394
- }];
395
- },
318
+ name: "extraction",
319
+ provenance: "extract",
320
+ async floor(_ctx, _query, pre, worthRunning) {
321
+ // Extraction's floor is always exactly CONCEPT+STEP when it exists —
322
+ // same investment discipline as CAST's (see cast.ts): when the bound
323
+ // already cannot beat the incumbent, return it UNINVESTED (never
324
+ // first-touch the climb just to be pruned).
325
+ if (!worthRunning(CONCEPT + STEP))
326
+ return CONCEPT + STEP;
327
+ if ((await pre.attention()).ranked.length === 0)
328
+ return null;
329
+ return CONCEPT + STEP;
330
+ },
331
+ async run(ctx, query, pre) {
332
+ const ex = await extractBySkill(ctx, query, pre);
333
+ if (!ex)
334
+ return [];
335
+ return [{
336
+ bytes: ex.bytes,
337
+ accounted: ex.accounted,
338
+ moves: CONCEPT + STEP * ex.accounted.length,
339
+ unexplained: ex.unexplained,
340
+ }];
341
+ },
396
342
  };
@@ -2,16 +2,12 @@ import type { MindContext } from "../types.js";
2
2
  import type { PipelineMechanism, Precomputed } from "../pipeline-mechanism.js";
3
3
  /** A recall result. */
4
4
  export interface RecallResult {
5
- bytes: Uint8Array;
6
- echoed: boolean;
7
- accounted: Array<[number, number]>;
8
- moves: number;
9
- unexplained: string;
5
+ bytes: Uint8Array;
6
+ echoed: boolean;
7
+ accounted: Array<[number, number]>;
8
+ moves: number;
9
+ unexplained: string;
10
10
  }
11
11
  /** Recall the answer by resonating the whole query against the content index. */
12
- export declare function recallByResonance(
13
- ctx: MindContext,
14
- query: Uint8Array,
15
- pre: Precomputed,
16
- ): Promise<RecallResult | null>;
12
+ export declare function recallByResonance(ctx: MindContext, query: Uint8Array, pre: Precomputed): Promise<RecallResult | null>;
17
13
  export declare const recallMechanism: PipelineMechanism;