@hviana/sema 0.8.1 → 0.8.2

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 (57) hide show
  1. package/dist/src/config.d.ts +17 -0
  2. package/dist/src/config.js +18 -0
  3. package/dist/src/meter.d.ts +25 -0
  4. package/dist/src/meter.js +44 -0
  5. package/dist/src/mind/corpus.d.ts +40 -0
  6. package/dist/src/mind/corpus.js +149 -0
  7. package/dist/src/mind/graph-search.d.ts +7 -0
  8. package/dist/src/mind/graph-search.js +235 -24
  9. package/dist/src/mind/index.d.ts +3 -1
  10. package/dist/src/mind/index.js +1 -0
  11. package/dist/src/mind/match.d.ts +8 -3
  12. package/dist/src/mind/match.js +142 -58
  13. package/dist/src/mind/mechanisms/cast.js +18 -2
  14. package/dist/src/mind/mechanisms/cover.js +6 -0
  15. package/dist/src/mind/mind.d.ts +55 -0
  16. package/dist/src/mind/mind.js +72 -2
  17. package/dist/src/mind/pipeline.js +25 -6
  18. package/dist/src/mind/reasoning.d.ts +5 -1
  19. package/dist/src/mind/reasoning.js +54 -1
  20. package/dist/src/mind/traverse.js +9 -1
  21. package/dist/src/mind/types.d.ts +22 -0
  22. package/docs/failures/tempting-but-wrong.md +31 -2
  23. package/jsr.json +1 -1
  24. package/package.json +1 -1
  25. package/src/config.ts +35 -0
  26. package/src/meter.ts +47 -0
  27. package/src/mind/corpus.ts +202 -0
  28. package/src/mind/graph-search.ts +252 -23
  29. package/src/mind/index.ts +8 -1
  30. package/src/mind/match.ts +143 -54
  31. package/src/mind/mechanisms/cast.ts +17 -1
  32. package/src/mind/mechanisms/cover.ts +5 -0
  33. package/src/mind/mind.ts +123 -0
  34. package/src/mind/pipeline.ts +30 -6
  35. package/src/mind/reasoning.ts +55 -0
  36. package/src/mind/traverse.ts +9 -1
  37. package/src/mind/types.ts +26 -0
  38. package/test/100-complete-grounding-trace.test.mjs +109 -0
  39. package/test/101-alignment-gap-bound.test.mjs +106 -0
  40. package/test/102-production-composes-at-scale.test.mjs +110 -0
  41. package/test/103-alignment-gap-budget.test.mjs +89 -0
  42. package/test/104-composition-is-reported.test.mjs +90 -0
  43. package/test/105-derive-through-reports-its-refusal.test.mjs +113 -0
  44. package/test/106-the-join-fires.test.mjs +94 -0
  45. package/test/107-the-join-is-counted.test.mjs +81 -0
  46. package/test/108-the-join-chains.test.mjs +78 -0
  47. package/test/109-the-pivot-is-counted.test.mjs +60 -0
  48. package/test/110-the-reasoner-stops-when-the-question-is-answered.test.mjs +91 -0
  49. package/test/111-the-cover-assembly-is-counted.test.mjs +74 -0
  50. package/test/112-the-exploration-does-not-grow-with-the-hub.test.mjs +89 -0
  51. package/test/113-the-rationale-payload-is-bounded.test.mjs +84 -0
  52. package/test/114-alignment-budget-is-per-sweep.test.mjs +93 -0
  53. package/test/116-the-extension-is-gated-by-the-pipelines-own-remainder.test.mjs +100 -0
  54. package/test/117-corpus-search.test.mjs +171 -0
  55. package/test/14-scaling.test.mjs +10 -7
  56. package/test/76-reference-binding.test.mjs +6 -1
  57. package/test/89-completion-recursion.test.mjs +30 -5
@@ -0,0 +1,202 @@
1
+ // corpus.ts — read the trained memory back out of the DAG, AS DATA.
2
+ //
3
+ // A trained experience pair IS one continuation edge: `src` is the context that
4
+ // was deposited, `dst` is what the mind learnt follows it. Reading them back
5
+ // uses the store's own structure and its own indexes — no auxiliary index is
6
+ // built, nothing is written, and NOTHING HERE KNOWS ABOUT TEXT: this layer takes
7
+ // bytes and returns bytes. The text case is one helper on the Mind
8
+ // (`searchCorpusText`), which encodes, calls this, and decodes.
9
+ //
10
+ // WHERE EACH STAGE COMES FROM (ported from the demo's `explore.ts`, which
11
+ // hand-rolled its own resolution):
12
+ //
13
+ // 1. PERCEIVE, CONTENT-ADDRESS and ADMIT the query — `recognise()`, the SAME
14
+ // machinery an answer goes through. It returns the sites: the query spans
15
+ // that content-addressed to a stored node that can lead somewhere. The
16
+ // demo's own recursive `findLeaf`/`findBranch` walk was a second
17
+ // implementation of exactly this, and it is NOT ported.
18
+ // 2. CLIMB the structural `kid` table from each resolved site to the
19
+ // edge-bearing contexts above it (`edgeAncestors`, traverse.ts), weighting
20
+ // each context by how much query content reached it.
21
+ // 3. READ the continuation off the edge table (`nextFirst`).
22
+ //
23
+ // COST is set by how much of the QUERY resolves, never by the size of the
24
+ // store: the sites are what recognition already found, the climb is bounded by
25
+ // the declared `corpusClimbs`/`corpusContextsPerClimb`, and every store call is
26
+ // a point probe or a capped read. All work is accounted by the store's own
27
+ // meter hooks when a response's meter is open — there is no second instrument.
28
+ //
29
+ // WHAT THIS IS NOT. Exact content addressing, not fuzzy keyword search: a query
30
+ // shares results with a stored note when it shares actual chunk-aligned content
31
+ // with it. An arbitrary mid-word fragment resolves to nothing, and the honest
32
+ // answer there is "nothing matched" — which is why `sampleCorpus` exists, and
33
+ // why the miss is reported as a STATE rather than as prose (the text helper
34
+ // turns it into words).
35
+
36
+ import { recognise } from "./recognition.js";
37
+ import { edgeAncestors } from "./traverse.js";
38
+ import type { MindContext } from "./types.js";
39
+
40
+ /** One stored experience pair, as bytes. */
41
+ export interface CorpusPair {
42
+ context: Uint8Array;
43
+ continuation: Uint8Array;
44
+ contextId: number;
45
+ continuationId: number;
46
+ /** Bytes of the query this pair was matched on — 0 when browsing. */
47
+ matchedBytes: number;
48
+ /** True when the stored bytes ran past the declared preview capacity. */
49
+ contextTruncated: boolean;
50
+ continuationTruncated: boolean;
51
+ }
52
+
53
+ /** Why a search produced no pairs. A STATE, so a caller's own layer can say it
54
+ * in its own words — the byte layer does not speak. */
55
+ export type CorpusMiss = "matched" | "nothing-resolved" | "no-continuations";
56
+
57
+ export interface CorpusResult {
58
+ pairs: CorpusPair[];
59
+ /** Query subtrees that content-addressed to a real stored node. */
60
+ resolved: number;
61
+ /** Distinct edge-bearing contexts the climb reached. */
62
+ reached: number;
63
+ /** Distinct contexts that carry a learnt continuation, store-wide. */
64
+ totalContexts: number;
65
+ /** True when these are browse samples rather than search results. */
66
+ browsed: boolean;
67
+ miss: CorpusMiss;
68
+ }
69
+
70
+ /** A context node as a pair, or null when it carries no continuation. */
71
+ function pairOf(
72
+ ctx: MindContext,
73
+ id: number,
74
+ matchedBytes: number,
75
+ ): CorpusPair | null {
76
+ const outs = ctx.store.nextFirst(id, 1);
77
+ if (outs.length === 0) return null;
78
+ const cap = ctx.cfg.corpusPreviewBytes;
79
+ const context = ctx.store.bytesPrefix(id, cap + 1);
80
+ const continuation = ctx.store.bytesPrefix(outs[0], cap + 1);
81
+ const contextTruncated = context.length > cap;
82
+ const continuationTruncated = continuation.length > cap;
83
+ return {
84
+ context: contextTruncated ? context.subarray(0, cap) : context,
85
+ continuation: continuationTruncated
86
+ ? continuation.subarray(0, cap)
87
+ : continuation,
88
+ contextId: id,
89
+ continuationId: outs[0],
90
+ matchedBytes,
91
+ contextTruncated,
92
+ continuationTruncated,
93
+ };
94
+ }
95
+
96
+ /** Which stored notes does this query reach? BYTES in, BYTES out.
97
+ *
98
+ * Exact content addressing through the machinery that already exists: the
99
+ * query's recognised sites are the resolved subtrees, the climb goes up from
100
+ * the biggest first, and a pair is a context that carries a continuation. */
101
+ export function searchCorpus(
102
+ ctx: MindContext,
103
+ queryBytes: Uint8Array,
104
+ limit?: number,
105
+ ): CorpusResult {
106
+ const store = ctx.store;
107
+ const want = Math.max(
108
+ 1,
109
+ Math.min(limit ?? ctx.cfg.corpusContextsPerClimb, ctx.cfg.corpusLimitMax),
110
+ );
111
+ // A resolved subtree must account for at least one window (W): a single
112
+ // character resolves against almost any store and means nothing. W is the
113
+ // mind's own line between chance and evidence — derived, never declared.
114
+ const floor = ctx.space.maxGroup;
115
+ const resolved = recognise(ctx, queryBytes).sites
116
+ .map((s) => ({ id: s.payload, len: store.contentLen(s.payload, 512) }))
117
+ .filter((r) => r.len >= floor);
118
+ // Biggest first, lowest id breaking ties: a clause is evidence, a character is
119
+ // noise, and equal evidence must not be decided by iteration order.
120
+ const byLength = resolved
121
+ .sort((a, b) => b.len - a.len || a.id - b.id)
122
+ .slice(0, ctx.cfg.corpusClimbs);
123
+
124
+ // Weight each context by how much query content reached it.
125
+ const weight = new Map<number, number>();
126
+ for (const { id, len } of byLength) {
127
+ for (
128
+ const root of edgeAncestors(ctx, id, ctx.cfg.corpusContextsPerClimb).roots
129
+ ) {
130
+ weight.set(root, (weight.get(root) ?? 0) + len);
131
+ }
132
+ }
133
+
134
+ const pairs: CorpusPair[] = [];
135
+ const ranked = [...weight.entries()].sort(
136
+ (a, b) => b[1] - a[1] || a[0] - b[0],
137
+ );
138
+ for (const [id, w] of ranked) {
139
+ if (pairs.length >= want) break;
140
+ const pair = pairOf(ctx, id, w);
141
+ if (pair) pairs.push(pair);
142
+ }
143
+ return {
144
+ pairs,
145
+ resolved: byLength.length,
146
+ reached: weight.size,
147
+ totalContexts: store.edgeSourceCount(),
148
+ browsed: false,
149
+ miss: pairs.length > 0
150
+ ? "matched"
151
+ : weight.size === 0
152
+ ? "nothing-resolved"
153
+ : "no-continuations",
154
+ };
155
+ }
156
+
157
+ /** Browse real pairs, striding the id space so the sample is spread rather than
158
+ * one local cluster. DETERMINISTIC: `from` is the caller's own offset, so
159
+ * browsing twice with different offsets shows different notes without a random
160
+ * draw (the demo drew `Math.random()`, which the engine cannot do — same seed,
161
+ * same order, same query must mean the same answer). */
162
+ export function sampleCorpus(
163
+ ctx: MindContext,
164
+ limit?: number,
165
+ from = 0,
166
+ ): CorpusResult {
167
+ const store = ctx.store;
168
+ const want = Math.max(
169
+ 1,
170
+ Math.min(limit ?? ctx.cfg.corpusContextsPerClimb, ctx.cfg.corpusLimitMax),
171
+ );
172
+ const total = store.nodeCount();
173
+ const probes = ctx.cfg.corpusSampleProbes;
174
+ const floorBytes = ctx.cfg.corpusSampleFloorBytes;
175
+ const pairs: CorpusPair[] = [];
176
+ // EACH CONTEXT AT MOST ONCE. Striding the id space revisits ids when the
177
+ // store is small relative to the probe budget (measured: a 160-node store
178
+ // returned the SAME pair six times for `limit: 6`), and a browse that repeats
179
+ // itself is not a browse. The demo had the same hole; it is invisible only on
180
+ // a store far larger than the probe budget.
181
+ const seen = new Set<number>();
182
+ for (let i = 0; i < probes && pairs.length < want && total > 0; i++) {
183
+ const slot = (i / probes + from) % 1;
184
+ const id = Math.floor(slot * total);
185
+ if (seen.has(id)) continue;
186
+ if (!store.has(id) || !store.hasNext(id)) continue;
187
+ if (store.contentLen(id, floorBytes) < floorBytes) continue;
188
+ const pair = pairOf(ctx, id, 0);
189
+ if (pair) {
190
+ seen.add(id);
191
+ pairs.push(pair);
192
+ }
193
+ }
194
+ return {
195
+ pairs,
196
+ resolved: 0,
197
+ reached: pairs.length,
198
+ totalContexts: store.edgeSourceCount(),
199
+ browsed: true,
200
+ miss: pairs.length > 0 ? "matched" : "no-continuations",
201
+ };
202
+ }
@@ -375,6 +375,14 @@ export class GraphSearch {
375
375
  private readonly host: GraphSearchHost,
376
376
  ) {}
377
377
 
378
+ /** The nodes the QUERY canonically names — the same identity the store's keys
379
+ * were written through. A byte-exact test is not enough: the query writes
380
+ * `Eiffel Tower country` and the deposited node is `eiffel tower country`, so
381
+ * a join that filters the query's own subject by RAW bytes re-admits it —
382
+ * measured: that is the trap's wrong answer (`The capital of Eiffel Tower
383
+ * country is Berlin.`). Cached by query identity, because the search is
384
+ * reused across responses. */
385
+
378
386
  /* * The hub bound √N (bounded-reads.md) — the ONE
379
387
  * fan-out cap, stated here rather than imported from `traverse.ts` because
380
388
  * this module is deliberately host-based (it holds a bare Store, never a
@@ -703,7 +711,13 @@ export class GraphSearch {
703
711
  return this.coverRules(it, coversDone, coverableByStart);
704
712
  }
705
713
  if (it.kind === "form") {
706
- return this.formRules(it, conceptTarget, substitutions, nodeBytes);
714
+ return this.formRules(
715
+ it,
716
+ conceptTarget,
717
+ substitutions,
718
+ nodeBytes,
719
+ queryLen,
720
+ );
707
721
  }
708
722
  return this.outRules(it, {
709
723
  W,
@@ -808,6 +822,7 @@ export class GraphSearch {
808
822
  conceptTarget: ReadonlyMap<number, number>,
809
823
  substitutions: ReadonlyMap<number, Uint8Array> | undefined,
810
824
  nodeBytes: (n: number) => Uint8Array,
825
+ queryLen: number,
811
826
  ): Iterable<Rule<GItem>> {
812
827
  // Articulation: emit voice bytes at the recognised span; the hop/concept/
813
828
  // emit chain is suppressed — the form contributes only its substitute.
@@ -843,7 +858,45 @@ export class GraphSearch {
843
858
  // guard then dead-ends it) with no way to reach the forward edge.
844
859
  // Forking offers every continuation as its own rule so the one that
845
860
  // genuinely advances (not a duplicate) is still reachable.
861
+ // A CHAIN HOP OFFERS ONLY WHAT THE QUESTION CAN PAY FOR.
862
+ //
863
+ // `hubBound` = √N is the READ cap — every read here stays inside it — but
864
+ // it is not an exploration bound: measured, a hub of degree 1083 sits
865
+ // BELOW √N = 1559, so a hop offered all 1083 continuations, the chart grew
866
+ // to 3113 outs for a two-word question, and since every out with an
867
+ // uncovered tail probes its tail's prefixes (measured: 16 885 canonical
868
+ // probes = 87% of that query's work, and its 270 MB peak / 256 MB OOM),
869
+ // the cost came from OFFERING rather than from reading.
870
+ //
871
+ // The bound is derived, not tuned: a derivation of L hops consumes ~L
872
+ // units of the question, so a hop cannot be paid for by offering more
873
+ // continuations than the question has units —
874
+ // `ceil(queryLen / W)`, floored at 2 for plurality. It is QUERY-sized
875
+ // (invariant 5: no per-query read grows with N) and it leaves `hubBound`
876
+ // and every read untouched.
877
+ // THE OFFER IS THE CORPUS'S OWN STRUCTURE, and the search pays for
878
+ // exploring it. There is no offer cap here any more: the traversal cap I
879
+ // had put on this hop was a short-circuit — it bounded what a hop could
880
+ // OFFER instead of charging for it — and it was not needed.
881
+ //
882
+ // MEASURED in the regime where it used to bite (`hubBound = ceil(√N)`
883
+ // GREATER than the hub's degree — reached in a fixture by choosing the
884
+ // degree below √N, so the trained store is not needed): with the cap the
885
+ // offer was 8/9/9 continuations at degrees 35/70/120; without it, 52/84/120
886
+ // — and the WORK is LINEAR in the degree, not quadratic: pushes 262/296/332,
887
+ // perceptions 530/592/757, while the PEAK is identical with and without the
888
+ // cap (218/415/689 MB against 215/410/662) because it is set by the store,
889
+ // not by the fan-out. What made this hop expensive was never the fan-out
890
+ // breadth: it was the per-offer work, two duplicate/oversized computations
891
+ // since removed (the per-offset canonical scan, and the tail scan now
892
+ // restricted to the fold's boundaries).
893
+ //
894
+ // The residual, stated: the trained store's hub (degree 1 083) is an
895
+ // EXTRAPOLATION from this linear shape, not a measurement.
846
896
  const nx = this.store.nextFirst(it.node, this.hubBound());
897
+ // Count what is OFFERED, not what was read: the evidence-preferred
898
+ // continuation is yielded too, even when it lies outside the cap.
899
+ if (this.host.meter) this.host.meter.chainOffers += nx.length + 1;
847
900
  if (nx.length) {
848
901
  // The SAME evidence-weighted disambiguation the first hop uses
849
902
  // (below) identifies the most-corroborated continuation. Yielding
@@ -852,10 +905,14 @@ export class GraphSearch {
852
905
  // arrivals at an EQUAL cost (`cost < current`, strictly) — so
853
906
  // among same-depth sibling forks that tie in cost, the
854
907
  // evidence-backed edge wins deterministically, never by
855
- // exploration-order luck. `preferred`, when set, is necessarily
856
- // an element of `nx` (chooseNext reads the identical hub-bounded
857
- // set — see traverse.ts), so a plain skip-in-place suffices; no
858
- // second array need be allocated to reorder it to the front.
908
+ // exploration-order luck. `preferred` is NOT necessarily an element
909
+ // of `nx` any more: `nx` is the capped read above, while `chooseNext`
910
+ // reads its own hub-bounded set (see traverse.ts) — so the evidence
911
+ // pick may lie outside the cap, and it is still yielded FIRST on
912
+ // purpose. The cap bounds what the hop EXPLORES; it must never make
913
+ // the evidence-ranked continuation unreachable, or the derivation the
914
+ // corpus corroborates would lose to exploration order. Nothing is
915
+ // reallocated: `nx` is walked with a skip-in-place for the duplicate.
859
916
  const preferred = nx.length > 1
860
917
  ? this.host.chooseNext?.(it.node)
861
918
  : undefined;
@@ -1080,10 +1137,48 @@ export class GraphSearch {
1080
1137
  // a deeper rewrite chain is made of.
1081
1138
  const rec = this.host.recogniseSpan(bytes);
1082
1139
  const kids = new Set(nrec.kids);
1140
+ // THE NODE'S OWN KIDS ARE SITES BY STRUCTURE — recognition cannot be the
1141
+ // only source. A produced composite is decomposed by ITS OWN SHAPE, and
1142
+ // at hub scale the recognition of a produced span returns the WHOLE while
1143
+ // deliberately suppressing its atoms (the off-boundary suppression), so
1144
+ // the kid filter below would admit nothing at all and the chain would end
1145
+ // at the intermediate composite. Measured on the chain
1146
+ // `seed → "p q" → (p→r, q→s) → "r s" → "m n"`: below the flip it reaches
1147
+ // "m n" with fuse+recompose, above it stops at "p q" — the trace shows
1148
+ // `recognise("p q") ⇒ form "p q"` alone, no parts.
1149
+ //
1150
+ // Laying the node's kids out over its own bytes restores exactly the
1151
+ // decomposition the node's tree already states; a kid recognition ALREADY
1152
+ // offers is skipped, so below the flip the seed set is byte-identical to
1153
+ // what it was. The filter's guarantee is untouched: nothing beyond the
1154
+ // node's own kids may enter.
1155
+ const recognised = rec.sites.filter((s) => kids.has(s.payload));
1156
+ // DEDUPED BY SPAN, not by payload. A node whose kids repeat (`"abab"`
1157
+ // folds as ["ab","ab"]) has TWO occurrences of the same node at different
1158
+ // offsets; a payload-keyed set suppressed the structural site for BOTH, so
1159
+ // the second occurrence had no site at all. The set now holds the spans
1160
+ // recognition already covers, and a structural site is added exactly when
1161
+ // nothing covers that PLACE — O(1) lookups, no extra reads.
1162
+ const seenSpans = new Set(recognised.map((s) => `${s.start}:${s.end}`));
1163
+ const structural: Site[] = [];
1164
+ {
1165
+ let off = 0;
1166
+ for (const k of nrec.kids) {
1167
+ const len = this.store.bytesPrefix(k, ALL).length;
1168
+ if (!seenSpans.has(`${off}:${off + len}`) && len > 0) {
1169
+ structural.push({
1170
+ start: off,
1171
+ end: Math.min(off + len, bytes.length),
1172
+ payload: k,
1173
+ });
1174
+ }
1175
+ off += len;
1176
+ }
1177
+ }
1083
1178
  const solved = this.solve(
1084
1179
  bytes.length,
1085
1180
  {
1086
- sites: rec.sites.filter((s) => kids.has(s.payload)),
1181
+ sites: [...recognised, ...structural],
1087
1182
  leaves: rec.leaves,
1088
1183
  splits: rec.splits,
1089
1184
  starts: rec.starts,
@@ -1163,6 +1258,14 @@ export class GraphSearch {
1163
1258
  if (!this.host.recogniseSpan) return;
1164
1259
  const tail = queryBytes.subarray(fact.j, queryLen);
1165
1260
  if (tail.length === 0) return;
1261
+ // Report ONLY the invocations that could have joined: the search asks this
1262
+ // rule for every finalized out with a node, which includes the one-byte
1263
+ // outs the cover bridges with — measured, 68 refusals for a single
1264
+ // 3-relation query, all of them letters. A form shorter than one window is
1265
+ // not a fact a join could travel through, so it is not a refusal worth
1266
+ // reporting; W is the same line the rest of the mind draws between a chance
1267
+ // overlap and a form.
1268
+ const reportable = fact.bytes.length >= this.maxGroup;
1166
1269
  // The entity candidates are the forms the fact's own bytes CONTAIN — the
1167
1270
  // same recogniser the query went through, so the evidence standard is the
1168
1271
  // query's. A byte atom is never a subject; the fact's own node is the span
@@ -1171,12 +1274,66 @@ export class GraphSearch {
1171
1274
  // LENDS it when it can (Mind does, with the response-scoped struct cache),
1172
1275
  // and a bare host falls back to the raw-store probe, so the search stays
1173
1276
  // host-based.
1174
- const leading = this.host.recogniseSpan(fact.bytes).sites.filter((s) =>
1175
- s.payload >= 0 && s.payload !== fact.node &&
1176
- (this.host.leadsSomewhere !== undefined
1177
- ? this.host.leadsSomewhere(s.payload)
1178
- : this.store.hasNext(s.payload) || this.store.hasHalo(s.payload))
1277
+ const factRec = this.host.recogniseSpan(fact.bytes);
1278
+ const leads = (id: number): boolean =>
1279
+ this.host.leadsSomewhere !== undefined
1280
+ ? this.host.leadsSomewhere(id)
1281
+ : this.store.hasNext(id) || this.store.hasHalo(id);
1282
+ // THE QUERY'S OWN SUBJECT, CANONICALLY. The filter used raw bytes and the
1283
+ // store's nodes are canonical, so `Eiffel Tower country` in the query did
1284
+ // not match the deposited `eiffel tower country` — measured, that is the
1285
+ // trap's wrong answer.
1286
+ //
1287
+ // TAKEN FROM THE RECOGNITION THE RESPONSE ALREADY COMPUTED — the host's
1288
+ // `recogniseSpan`, the same surface the rest of this search uses — not from
1289
+ // a second offset scan. `canonicalQueryNodes` re-derived, per byte offset,
1290
+ // what `recognise` had already resolved once per query (its memo is keyed by
1291
+ // content), and that scan was the largest single cost the DIANOT join added:
1292
+ // measured against the pre-change tree, the same fixture and the same test
1293
+ // were 21 s slower with the scan than without it. A recognised site IS a
1294
+ // canonical node of the query that can lead somewhere, which is exactly the
1295
+ // set this filter wants, and it costs nothing to read.
1296
+ const queryNodes = new Set<number>(
1297
+ (this.host.recogniseSpan?.(queryBytes)?.sites ?? []).map((s) =>
1298
+ s.payload
1299
+ ),
1179
1300
  );
1301
+ // TWO SOURCES, ONE ADMISSION. The recognition of a STORED WHOLE returns the
1302
+ // whole and stops — measured: for `The director of Eva is Gustaf Molander.`
1303
+ // it yields exactly ONE site, the fact's own node — so the entity a join
1304
+ // exists for is never proposed. The canonical fold is the second source,
1305
+ // and the scan runs only for a FORM (≥ W: a one-byte out is not something to
1306
+ // join through, and running it per letter measured 20-26 s in test/99).
1307
+ const W = this.maxGroup;
1308
+ const proposed = new Map<number, Uint8Array>();
1309
+ // The SOURCE of each proposal travels with it: a refusal that names only the
1310
+ // bytes leaves the next reader guessing which path proposed them — three
1311
+ // attempts at the chained join were spent fixing paths that never produced
1312
+ // the offending candidate.
1313
+ const source = new Map<number, string>();
1314
+ for (const s of factRec.sites) {
1315
+ if (s.payload >= 0 && leads(s.payload)) {
1316
+ proposed.set(s.payload, this.store.bytesPrefix(s.payload, ALL));
1317
+ source.set(s.payload, "recognised site");
1318
+ }
1319
+ }
1320
+ if (this.host.canonResolve !== undefined && fact.bytes.length >= W) {
1321
+ const canon = this.host.canonResolve.bind(this.host);
1322
+ for (let start = 0; start < fact.bytes.length; start++) {
1323
+ for (let end = fact.bytes.length; end - start >= W; end--) {
1324
+ const id = canon(fact.bytes.subarray(start, end));
1325
+ if (id === null) continue;
1326
+ if (leads(id)) {
1327
+ proposed.set(id, this.store.bytesPrefix(id, ALL));
1328
+ source.set(id, "canonical fold");
1329
+ }
1330
+ break; // the longest form at this offset wins
1331
+ }
1332
+ }
1333
+ }
1334
+ const leading = [...proposed]
1335
+ .filter(([payload]) => payload !== fact.node && !queryNodes.has(payload))
1336
+ .map(([payload, bytes]) => ({ payload, bytes }));
1180
1337
  // …then prefer the entity the query did NOT name, and the MAXIMAL one. The
1181
1338
  // join exists to reach the subject the query never wrote, so:
1182
1339
  // • a candidate the query already contains is the query's OWN subject, and
@@ -1187,32 +1344,104 @@ export class GraphSearch {
1187
1344
  // introduces ("Timur" must not win over "Timur Bekmambetov").
1188
1345
  // Byte work over bytes already read, and the pruning REMOVES the
1189
1346
  // resolve()/nextFirst() probes these candidates would have paid.
1347
+ if (leading.length === 0) {
1348
+ if (this.host.meter) this.host.meter.joinNoEntity++;
1349
+ if (reportable) {
1350
+ // Report WHAT the recognition returned, not just that nothing led: the
1351
+ // count and the first few site texts are the difference between "the
1352
+ // fact was not recognised" and "it was recognised but nothing led".
1353
+ const seen = factRec.sites.slice(0, 3).map((s) =>
1354
+ this.store.bytesPrefix(s.payload, ALL)
1355
+ );
1356
+ this.host.reportSearch?.(
1357
+ "deriveThroughMiss",
1358
+ [fact.bytes, tail, ...seen],
1359
+ `no entity inside the fact leads anywhere — ${factRec.sites.length} site(s) recognised inside it`,
1360
+ );
1361
+ }
1362
+ }
1190
1363
  const candidates = leading
1191
- .map((s) => ({
1192
- payload: s.payload,
1193
- bytes: this.store.bytesPrefix(s.payload, ALL),
1194
- }))
1195
- .filter((c) => indexOf(queryBytes, c.bytes, 0) < 0)
1196
1364
  .filter((c, _i, all) =>
1197
1365
  !all.some((o) =>
1198
1366
  o.bytes.length > c.bytes.length && indexOf(o.bytes, c.bytes, 0) >= 0
1199
1367
  )
1200
1368
  );
1201
1369
  for (const c of candidates) {
1202
- const key = this.host.resolve(concat2(c.bytes, tail));
1203
- if (key === null) continue;
1204
- const nx = this.store.nextFirst(key, 1);
1205
- if (nx.length === 0) continue;
1370
+ // THE SHORTEST TAIL PREFIX WHOSE KEY ALSO LEADS SOMEWHERE.
1371
+ //
1372
+ // The conclusion covers only that prefix, so the rest of the tail stays
1373
+ // for the step after — which is what CHAINING is (a whole-tail key
1374
+ // consumed the whole remainder and made every join terminal: measured,
1375
+ // `joinFired=0` on a three-relation query).
1376
+ //
1377
+ // A KEY THAT RESOLVES IS NOT ENOUGH. Measured with a dry run of these
1378
+ // very primitives: for the candidate `Sweden` the first tail prefix that
1379
+ // resolves is `" "` — the key `Sweden ` (a trailing space) — and it leads
1380
+ // NOWHERE (`nextFirst` = 0), so accepting it refused the join while the
1381
+ // key that names the fact (`sweden capital`) sat one prefix further. The
1382
+ // loop therefore asks BOTH questions before accepting, and keeps looking
1383
+ // otherwise.
1384
+ //
1385
+ // EXACT FIRST, THEN CANONICAL: the corpus holds both identities.
1386
+ let key: number | null = null;
1387
+ let used = 0;
1388
+ // The continuation the accepted key leads to, carried out of the loop:
1389
+ // the loop already HAD to read it to accept the key (a key that leads
1390
+ // nowhere is not the relation), so re-reading it after the loop was a
1391
+ // duplicate read and a branch that could never be taken.
1392
+ let next: number | null = null;
1393
+ let keyBytes = c.bytes;
1394
+ // THE PREFIX ENDS ARE THE TAIL'S OWN FOLD BOUNDARIES, not every byte
1395
+ // length. The key is `entity + prefix`, and the prefix that names a
1396
+ // stored relation ends where the fold cuts: measured over four join-firing
1397
+ // queries, 5 of 5 accepted keys ended on a boundary (or the tail's end)
1398
+ // while the byte-by-byte scan spent 153 probes where 14 boundaries would
1399
+ // do. Same criterion — resolves AND leads — same shortest-first order, so
1400
+ // the answer is the same one the enumeration found; only the candidates
1401
+ // come from the structure instead of from the byte count. A host with no
1402
+ // boundary rule falls back to the enumeration.
1403
+ const cuts = this.host.contentCuts?.(tail);
1404
+ const ends = cuts && cuts.length > 0
1405
+ ? [...cuts.filter((c) => c > 0 && c < tail.length), tail.length]
1406
+ : Array.from({ length: tail.length }, (_, i) => i + 1);
1407
+ for (const len of ends) {
1408
+ keyBytes = concat2(c.bytes, tail.subarray(0, len));
1409
+ const k = this.host.resolve(keyBytes) ??
1410
+ this.host.canonResolve?.(keyBytes) ??
1411
+ null;
1412
+ if (k === null) continue;
1413
+ const nx = this.store.nextFirst(k, 1);
1414
+ if (nx.length === 0) continue;
1415
+ key = k;
1416
+ used = len;
1417
+ next = nx[0];
1418
+ break;
1419
+ }
1420
+ if (key === null) {
1421
+ if (this.host.meter) this.host.meter.joinNoKey++;
1422
+ if (reportable) {
1423
+ this.host.reportSearch?.(
1424
+ "deriveThroughMiss",
1425
+ [c.bytes, tail, keyBytes],
1426
+ `no learnt key names this entity and tail together ` +
1427
+ `(candidate #${c.payload}, from the ${
1428
+ source.get(c.payload) ?? "unknown"
1429
+ } source)`,
1430
+ );
1431
+ }
1432
+ continue;
1433
+ }
1434
+ if (this.host.meter) this.host.meter.joinFired++;
1206
1435
  yield {
1207
1436
  premises: [fact],
1208
1437
  conclusion: {
1209
1438
  kind: "out",
1210
1439
  i: fact.i,
1211
- j: queryLen,
1212
- bytes: this.store.bytesPrefix(nx[0], ALL),
1440
+ j: fact.j + used,
1441
+ bytes: this.store.bytesPrefix(next!, ALL),
1213
1442
  cover: true,
1214
1443
  rec: true,
1215
- node: nx[0],
1444
+ node: next!,
1216
1445
  throughFact: true,
1217
1446
  },
1218
1447
  cost: STEP,
package/src/mind/index.ts CHANGED
@@ -4,7 +4,12 @@
4
4
  // exported from mind/mind.ts directly.
5
5
 
6
6
  export { Mind } from "./mind.js";
7
- export type { Input, Response } from "./mind.js";
7
+ export type {
8
+ CorpusTextPair,
9
+ CorpusTextResult,
10
+ Input,
11
+ Response,
12
+ } from "./mind.js";
8
13
  export type { ComputedSpan, ExtensionHost } from "./mind.js";
9
14
  export type {
10
15
  MechanismResult,
@@ -38,3 +43,5 @@ export type {
38
43
  NarrowDecisionData,
39
44
  Provenance,
40
45
  } from "./pipeline.js";
46
+ export { sampleCorpus, searchCorpus } from "./corpus.js";
47
+ export type { CorpusMiss, CorpusPair, CorpusResult } from "./corpus.js";