@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,927 @@
1
+ // graph-search.ts — the weighted deduction system that thinking runs on.
2
+ //
3
+ // Thinking is ONE thing: a lightest derivation over the Sema graph (derive's
4
+ // adapted A*LD engine). This file is that one thing, factored out of the mind: it
5
+ // states the items, axioms, goal, and weighted rules, and returns the chosen
6
+ // spans of the lightest cover. Every behaviour — covering the query, following
7
+ // edges to a fixpoint, jumping a concept (halo) link, fusing fragments into a
8
+ // deeper learned form, splicing a learnt connector between two rewrites, and
9
+ // re-voicing an answer in the asker's words — is a rule here, not a separate
10
+ // algorithm.
11
+ //
12
+ // It reaches Sema only through the {@link Store} interface and one injected
13
+ // callback, {@link GraphSearch.resolve} (canonical node id of a byte span). The
14
+ // async hints the synchronous search cannot gather for itself — concept targets
15
+ // and connectors — are pre-resolved by the caller (see src/mind/pipeline.ts) and handed in.
16
+ // So this engine stays decoupled: it knows the graph's shape, never how the
17
+ // graph was learnt.
18
+ import { lightestDerivation, } from "../derive/src/index.js";
19
+ import { bytesEqual, concat2, concatBytes, latin1 } from "../bytes.js";
20
+ import { ALL } from "./types.js";
21
+ // The cost ladder is a strict ORDERING, not tuned magic:
22
+ // • Coverage dominates everything: leaving one query byte unrecognised (PASS)
23
+ // outweighs any chain of graph steps a covering derivation could take, so
24
+ // the search always prefers to recognise.
25
+ // • A direct edge (STEP) is the cheapest move; fusing adjacent fragments is
26
+ // free (cost 0) — it only re-NAMES a span, it does not advance the cover.
27
+ // • A concept jump (CONCEPT) is dearer than a direct edge, so a literal
28
+ // continuation is preferred to a synonym's.
29
+ // Any constants with this ordering give the same lightest derivations.
30
+ //
31
+ // EXPORTED because the ladder is the ONE cost currency of the whole mind:
32
+ // think's grounding decider (pipeline.ts) weighs every mechanism's candidate
33
+ // answer in these same units, so a mechanism-level choice and a byte-level
34
+ // choice are the same kind of decision — a lightest derivation.
35
+ export const STEP = 1;
36
+ export const CONCEPT = 10;
37
+ export const PASS = 1000;
38
+ /** The cheapest local cost in the ladder: a recognised completion bridging into
39
+ * the cover. Far below STEP, so connecting two recognised spans never disturbs
40
+ * the ordering — and, being the minimum per-position cost, it is the per-byte
41
+ * unit of the admissible search heuristic (see {@link GraphSearch.buildSearch}). */
42
+ export const MICRO = 1e-3;
43
+ /** Append `v` to the list at `mp[k]`, creating the list on first use. */
44
+ function pushInto(mp, k, v) {
45
+ const a = mp.get(k);
46
+ if (a)
47
+ a.push(v);
48
+ else
49
+ mp.set(k, [v]);
50
+ }
51
+ /** Read the chosen spans back off a derivation: the goal is a chain of bridge
52
+ * steps, each whose second premise is the `out` it crossed. Walk the chain to
53
+ * the axiom and reverse into left-to-right order. */
54
+ function readCover(derivation) {
55
+ const segs = [];
56
+ let node = derivation;
57
+ while (node && node.rule) {
58
+ const out = node.premises[1].item;
59
+ if (out.kind === "out") {
60
+ segs.push({
61
+ i: out.i,
62
+ j: out.j,
63
+ bytes: out.bytes,
64
+ rec: out.rec,
65
+ node: out.node,
66
+ });
67
+ }
68
+ node = node.premises[0];
69
+ }
70
+ segs.reverse();
71
+ return segs;
72
+ }
73
+ /** Flatten a {@link GItem} into the {@link DerivationItem} a rationale shows. */
74
+ function derivationItem(it) {
75
+ if (it.kind === "cover")
76
+ return { kind: "cover", span: [it.p, it.p] };
77
+ if (it.kind === "form") {
78
+ return { kind: "form", span: [it.i, it.j], node: it.node };
79
+ }
80
+ return { kind: "out", span: [it.i, it.j], bytes: it.bytes, node: it.node };
81
+ }
82
+ /** Name the reasoning act a rule performed, from the shape of what it consumed
83
+ * and produced — the one mapping from rule geometry to a human move. Mirrors
84
+ * the rule set in {@link GraphSearch.coverRules}/{@link formRules}/{@link
85
+ * outRules}/{@link fuse}; kept here beside {@link readCover} so the two readers
86
+ * of a derivation sit together. */
87
+ function classifyMove(premises, conclusion, articulating) {
88
+ if (premises.length === 1) {
89
+ const [p] = premises;
90
+ if (p.kind === "form" && conclusion.kind === "form") {
91
+ // form→form is an edge step; CONCEPT cost marks the synonym hop, but the
92
+ // cost is on the rule, not the item — the caller passes it to refine this.
93
+ return "follow-edge";
94
+ }
95
+ if (p.kind === "form" && conclusion.kind === "out") {
96
+ // form→out: grounding to a terminal answer, or — under a substitution map —
97
+ // the form emitting the asker's own wording (articulation's `voice`).
98
+ if (!conclusion.rec)
99
+ return "step";
100
+ return articulating ? "voice" : "ground";
101
+ }
102
+ if (p.kind === "out" && conclusion.kind === "out")
103
+ return "split";
104
+ return "step";
105
+ }
106
+ if (premises.length === 2) {
107
+ const [a, b] = premises;
108
+ if (a.kind === "cover" || b.kind === "cover")
109
+ return "bridge";
110
+ if (conclusion.kind === "form")
111
+ return "recompose";
112
+ if (conclusion.kind === "out") {
113
+ // A connector splice concatenates THREE pieces (l + link + r); a plain
114
+ // fuse concatenates two (concat2). Distinguish by BYTE width: a splice's
115
+ // conclusion is wider than its two premises summed (the link sits between
116
+ // them), whereas a fuse's conclusion is exactly their sum. Position can't
117
+ // tell them apart — in "icefire" the two rewrites are positionally
118
+ // adjacent yet a connector is still spliced into the bytes.
119
+ if (a.kind === "out" && b.kind === "out") {
120
+ const summed = (a.bytes?.length ?? 0) + (b.bytes?.length ?? 0);
121
+ return (conclusion.bytes?.length ?? 0) > summed
122
+ ? "splice-connector"
123
+ : "fuse";
124
+ }
125
+ return "fuse";
126
+ }
127
+ }
128
+ return "step";
129
+ }
130
+ /** Walk a finished derivation into its rule applications, in post-order
131
+ * (premises before the conclusion they feed), deduplicating shared
132
+ * sub-derivations so a node reached by two rules is reported once. This is the
133
+ * whole proof tree — every STEP, CONCEPT, fuse and bridge the lightest cover
134
+ * was built from — the finest granularity a rationale can reach. */
135
+ function readDerivation(root, articulating = false) {
136
+ const steps = [];
137
+ // The `order` assigned to each already-emitted derivation node, so a later
138
+ // step that consumes it as a premise can name it as a producer — the proof
139
+ // tree's data-flow edge, preserved exactly. Only RULE-bearing nodes (the
140
+ // emitted steps) get an entry; an axiom premise (a seed leaf/form/computed
141
+ // result) has no producer and contributes no edge. `order` therefore stays
142
+ // contiguous with `steps`, so producers index directly into the emitted list.
143
+ const orderOf = new Map();
144
+ let order = 0;
145
+ const walk = (d) => {
146
+ if (orderOf.has(d))
147
+ return; // a shared sub-derivation, already emitted
148
+ for (const p of d.premises)
149
+ walk(p);
150
+ if (!d.rule)
151
+ return; // an axiom: a seed, reported as its consumer's premise
152
+ const move = classifyMove(d.rule.premises, d.rule.conclusion, articulating);
153
+ // Refine an edge step to a concept hop by its cost (CONCEPT > STEP).
154
+ const refined = move === "follow-edge" && d.rule.cost >= CONCEPT ? "concept-hop" : move;
155
+ const producers = [];
156
+ for (const p of d.premises) {
157
+ const o = orderOf.get(p); // defined iff p was itself an emitted rule step
158
+ if (o !== undefined)
159
+ producers.push(o);
160
+ }
161
+ const myOrder = order++;
162
+ orderOf.set(d, myOrder);
163
+ steps.push({
164
+ order: myOrder,
165
+ move: refined,
166
+ premises: d.premises.map((p) => derivationItem(p.item)),
167
+ conclusion: derivationItem(d.item),
168
+ cost: d.rule.cost,
169
+ producers,
170
+ });
171
+ };
172
+ walk(root);
173
+ return steps;
174
+ }
175
+ /** The lightest-derivation search over the Sema graph. One instance binds the
176
+ * store, `maxGroup` (the fusible span ceiling), and the canonical
177
+ * {@link resolve} callback; {@link cover} then solves one query. */
178
+ export class GraphSearch {
179
+ store;
180
+ maxGroup;
181
+ host;
182
+ constructor(store, maxGroup,
183
+ /** The host whose capabilities the search consults: resolve (canonical node
184
+ * id of a byte span), recogniseSpan (content-addressed graph lookup for
185
+ * recursive completion), and chooseNext (distributional-evidence edge
186
+ * disambiguation when a recognised form has multiple continuations). */
187
+ host) {
188
+ this.store = store;
189
+ this.maxGroup = maxGroup;
190
+ this.host = host;
191
+ }
192
+ /** Explore the Sema graph for the lightest cover of the query and return its
193
+ * chosen spans left-to-right — WITH the derivation's total weight (the g
194
+ * value of the goal item, in the exported cost ladder), which think's
195
+ * grounding decider compares against the other mechanisms' candidates —
196
+ * or null if the query cannot be covered.
197
+ *
198
+ * The search runs on the query's tree leaves, not flat bytes — leaf-level
199
+ * cover axioms, recognised forms as graph entry points — and discovers
200
+ * cross-leaf forms by fusing adjacent fragments on demand (the only
201
+ * byte-processing it does, and only where a derivation needs it). When
202
+ * `substitutions` is given, recognised forms emit substitute bytes directly
203
+ * (cost 0) — articulation splicing the asker's wording in.
204
+ *
205
+ * Any learnt connector between two rewrites is spliced IN by the in-search
206
+ * connector rule (see {@link outRules}), so the returned spans already carry
207
+ * it — there is no post-pass. */
208
+ cover(queryLen, sites, conceptTarget, leaves, splits, substitutions, connectors, computedResults,
209
+ /** When given, receives the lightest derivation's rule applications — the
210
+ * full adapted A*LD proof tree as classified {@link DerivationStep}s — for the TOP
211
+ * cover only (a recursive recompletion solves its own sub-cover and is not
212
+ * reported here, to keep the trace one layer per think). Off by default,
213
+ * so the search pays nothing when no one inspects. */
214
+ onDerivation) {
215
+ // Top-level entry: reset the per-call recursion state, then run the one
216
+ // {@link solve} routine that both the query and any produced composite go
217
+ // through (completion is cover, recursively — see {@link recompleteNode}).
218
+ this.recompleteOpen.clear();
219
+ this.recompleteMemo = new Map();
220
+ return this.solve(queryLen, {
221
+ sites,
222
+ leaves,
223
+ splits,
224
+ }, conceptTarget, substitutions, connectors, computedResults, onDerivation);
225
+ }
226
+ /** Build the deduction system for one span and return its lightest cover's
227
+ * chosen spans — the SINGLE routine the query and every produced composite
228
+ * run through. `recognition` carries the span's recognised forms; the query
229
+ * brings its own (with pre-resolved concepts/connectors), a recursive
230
+ * completion re-recognises the produced bytes (edge/fuse only).
231
+ *
232
+ * No depth limit governs nesting — convergence is INTRINSIC, exactly as in the
233
+ * adapted A*LD chart and {@link completeForward}: a completion only recurses into a
234
+ * node it has not already entered ({@link recompleteNode}'s cycle guard), and
235
+ * the node ids are finite, so the recursion must terminate on its own. A
236
+ * decomposition may therefore run as deep as the graph licenses — three
237
+ * decomposes, two recomposes, any mix — and stops only when it reaches a node
238
+ * that leads nowhere new, never at an arbitrary count. */
239
+ solve(spanLen, recognition, conceptTarget, substitutions, connectors, computedResults, onDerivation) {
240
+ const system = this.buildSearch(spanLen, recognition.sites, conceptTarget, recognition.leaves, recognition.splits, substitutions, connectors, computedResults);
241
+ const derivation = lightestDerivation(system);
242
+ // When covering under a substitution map (articulation), a form→out rule is
243
+ // the form EMITTING the asker's voice, not grounding to its own answer — so
244
+ // tell the reader to name those moves `voice` rather than `ground`.
245
+ if (derivation && onDerivation) {
246
+ onDerivation(readDerivation(derivation, substitutions !== undefined));
247
+ }
248
+ return derivation
249
+ ? { segs: readCover(derivation), cost: derivation.cost }
250
+ : null;
251
+ }
252
+ /** The weighted deduction system the graph exploration solves (the four
253
+ * reductions of adapted A*LD live in {@link lightestDerivation}; this only states the
254
+ * items, axioms, goal, and rules — see {@link GItem} for the item kinds).
255
+ *
256
+ * Forms that span across leaves are discovered BY the rules, which fuse
257
+ * adjacent fragments toward a known leaf (findLeaf) or branch (findBranch);
258
+ * a completion fused with its neighbour may spell a deeper learned form the
259
+ * flat probes can't name, recovered canonically by {@link resolve}. */
260
+ buildSearch(queryLen, sites, conceptTarget, leaves, splits, substitutions, connectors, computedResults) {
261
+ const W = this.maxGroup; // fusible span ceiling (shortest composite bound)
262
+ const nodeBytes = (n) => this.store.bytesPrefix(n, ALL);
263
+ // Content-addressed probes over the store's hash-cons maps — the same keys
264
+ // training filled. No byte-by-byte trie walk.
265
+ const findLeafU = (b) => this.store.findLeaf(b) ?? undefined;
266
+ const findBranchU = (k) => this.store.findBranch(k) ?? undefined;
267
+ // Finalised `out` items, indexed for the binary (bridge, fuse) rules.
268
+ const coversDone = new Set();
269
+ const outsByStart = new Map();
270
+ const outsByEnd = new Map();
271
+ const outsByNode = new Map();
272
+ const coverableByStart = new Map();
273
+ // Index the connectors by their left and right answer-node, so the connector
274
+ // rule iterates only this out's FEW resolved partners (selective, and for the
275
+ // N-ary case O(parts) keys) instead of scanning every position pair — what
276
+ // keeps the in-search bridge bounded when many parts are recognised at once.
277
+ const linksByLeft = new Map();
278
+ const linksByRight = new Map();
279
+ if (connectors) {
280
+ for (const [key, bytes] of connectors) {
281
+ const comma = key.indexOf(",");
282
+ const l = Number(key.slice(0, comma));
283
+ const r = Number(key.slice(comma + 1));
284
+ pushInto(linksByLeft, l, [r, bytes]);
285
+ pushInto(linksByRight, r, [l, bytes]);
286
+ }
287
+ }
288
+ return {
289
+ key(it) {
290
+ if (it.kind === "cover")
291
+ return "c" + it.p;
292
+ if (it.kind === "form") {
293
+ return `f${it.i}.${it.j}.${it.node}.${it.via ? 1 : 0}.${it.rcmp ? 1 : 0}`;
294
+ }
295
+ return `o${it.i}.${it.j}.${it.cover ? 1 : 0}.${it.rec ? 1 : 0}.${it.node ?? -1}.${latin1(it.bytes)}`;
296
+ },
297
+ *axioms() {
298
+ yield { item: { kind: "cover", p: 0 }, cost: 0 };
299
+ // One out per tree leaf — content-defined chunks, far fewer than bytes.
300
+ // Each carries the node id it resolves to (when known) so it can compose
301
+ // toward a known branch by findBranch.
302
+ for (const lf of leaves) {
303
+ yield {
304
+ item: {
305
+ kind: "out",
306
+ i: lf.start,
307
+ j: lf.end,
308
+ bytes: lf.bytes,
309
+ cover: true,
310
+ rec: false,
311
+ node: lf.node ?? undefined,
312
+ },
313
+ cost: 0,
314
+ };
315
+ }
316
+ for (const s of sites) {
317
+ yield {
318
+ item: {
319
+ kind: "form",
320
+ i: s.start,
321
+ j: s.end,
322
+ node: s.payload,
323
+ via: false,
324
+ },
325
+ cost: 0,
326
+ };
327
+ }
328
+ // Computed (extension) results — see {@link ComputedResult}. Each enters as a
329
+ // RECOGNISED covering completion, exactly like a learned terminal answer:
330
+ // its bytes are the computed result, it bridges the cover at MICRO (rec),
331
+ // and it carries the result's canonical node (when the store holds it) so
332
+ // it can fuse as an operand of an outer form. The STEP base cost marks a
333
+ // computation as a unit of work — a derived fact, on par with following a
334
+ // learned edge (STEP), so it decisively beats leaving the span
335
+ // unrecognised (PASS) but never masquerades as a free perceived leaf.
336
+ // Because this cost EQUALS a learned edge's, the search would tie a
337
+ // computation against a colliding recall; the computation-always-wins policy lives
338
+ // in the caller (src/mind/pipeline.ts think), which masks any recognised site a result
339
+ // overlaps so the computation is the cover's sole completion there — the
340
+ // search stays a neutral cost engine with no computation-vs-recall precedence baked
341
+ // in. When `computedResults` is empty (every non-arithmetic query) this loop
342
+ // emits nothing, so the search is byte-identical to one with no extension at all.
343
+ for (const u of computedResults ?? []) {
344
+ yield {
345
+ item: {
346
+ kind: "out",
347
+ i: u.i,
348
+ j: u.j,
349
+ bytes: u.bytes,
350
+ cover: true,
351
+ rec: true,
352
+ node: u.node,
353
+ },
354
+ cost: STEP,
355
+ };
356
+ }
357
+ },
358
+ isGoal: (it) => it.kind === "cover" && it.p === queryLen,
359
+ // Admissible, consistent lower bound on the cost remaining to the goal
360
+ // cover(queryLen) — this is what makes the adapted A*LD search OUTPUT-SENSITIVE
361
+ // (work proportional to the answer, not to how densely the corpus enriched
362
+ // the query's sub-forms). Without it the engine runs as uninformed
363
+ // Dijkstra and pops every zero-cost fuse before the goal; with it the
364
+ // agenda is ordered g + h, so the frontier is driven FORWARD toward full
365
+ // coverage instead of wallowing in low-position fragment fusions.
366
+ //
367
+ // The bound: whatever an item is, reaching the goal still requires the
368
+ // cover frontier to advance to queryLen, and the CHEAPEST any single
369
+ // covered position can be is the recognised-completion bridge (ε = MICRO,
370
+ // the minimum local cost in the ladder — every other move costs ≥ STEP).
371
+ // So the remaining query past the item's right edge is a guaranteed
372
+ // ≥ ε-per-byte cost. cover(p) still owes [p,queryLen); a form/out at
373
+ // [i,j) can contribute coverage no further than j, so it still owes
374
+ // [j,queryLen). Using ε (≤ every real per-byte cost, incl. PASS) keeps it
375
+ // a true lower bound; counting only the suffix past the right edge keeps it
376
+ // consistent (each forward rule pays ≥ ε per byte it advances the edge).
377
+ heuristic: (it) => {
378
+ const right = it.kind === "cover" ? it.p : it.j;
379
+ return (queryLen - right) * MICRO;
380
+ },
381
+ rules: (it) => {
382
+ if (it.kind === "cover") {
383
+ return this.coverRules(it, coversDone, coverableByStart);
384
+ }
385
+ if (it.kind === "form") {
386
+ return this.formRules(it, conceptTarget, substitutions, nodeBytes);
387
+ }
388
+ return this.outRules(it, {
389
+ W,
390
+ splits,
391
+ coversDone,
392
+ outsByStart,
393
+ outsByEnd,
394
+ outsByNode,
395
+ coverableByStart,
396
+ findLeafU,
397
+ findBranchU,
398
+ linksByLeft,
399
+ linksByRight,
400
+ });
401
+ },
402
+ };
403
+ }
404
+ /** cover(p): the BRIDGE rule — extend the cover across any coverable out that
405
+ * begins at p, stepping the frontier from p to that out's end.
406
+ *
407
+ * This is what links the rewritten parts of a multi-form answer. An out is
408
+ * either a recognised completion (`rec`, free) or a literal span the query
409
+ * carried between known forms — the connective: a space, comma, period,
410
+ * newline, or any run of bytes that was never recognised. Bridging a literal
411
+ * costs PASS per byte (so the search still prefers to recognise), but it is
412
+ * the cheapest — indeed only — way to cross a gap that has no learned form,
413
+ * and it KEEPS that connective in the cover chain, so the asker's own linking
414
+ * material reappears when it still coheres ("ice, fire" → "cold, hot", not
415
+ * "coldhot"). A recognised completion bridges for a tiny ε (1e-3, far below
416
+ * STEP), so a single connected span beats two separate ones on coherence
417
+ * without disturbing the cost ladder's ordering.
418
+ *
419
+ * Marks p finalised so the symmetric out-side bridge ({@link outRules}) can
420
+ * fire for outs that arrive after their start position is covered. */
421
+ *coverRules(it, coversDone, coverableByStart) {
422
+ coversDone.add(it.p);
423
+ for (const o of coverableByStart.get(it.p) ?? []) {
424
+ yield this.bridgeRule(it, o);
425
+ }
426
+ }
427
+ /** The BRIDGE rule, built once for its two arrival orders (cover-first in
428
+ * {@link coverRules}, out-first in {@link outRules}): ε for a recognised
429
+ * completion; PASS per byte for a literal connective — kept in the cover
430
+ * so the asker's own connector survives where it fits. ONE definition of
431
+ * the cost expression, so the ladder's application cannot drift between
432
+ * the two sides. */
433
+ bridgeRule(cover, o) {
434
+ return {
435
+ premises: [cover, o],
436
+ conclusion: { kind: "cover", p: o.j },
437
+ cost: o.rec ? MICRO : PASS * (o.j - o.i),
438
+ };
439
+ }
440
+ /** The connector-SPLICE rule for an oriented (l, r) pair, or null when the
441
+ * pair does not qualify — the ONE body behind {@link outRules}' two
442
+ * mirror loops (this-as-left over resolved right partners, this-as-right
443
+ * over resolved left partners). Fires only when both sides are
444
+ * recognised, r starts at or after l ends, and the gap between them is
445
+ * empty or wholly recognised — never across the asker's own literal
446
+ * separator. */
447
+ trySplice(l, r, link, outsByEnd) {
448
+ if (!l.rec || !r.rec || r.i < l.j)
449
+ return null;
450
+ if (!this.gapRecognised(l.j, r.i, outsByEnd))
451
+ return null;
452
+ return {
453
+ premises: [l, r],
454
+ conclusion: {
455
+ kind: "out",
456
+ i: l.i,
457
+ j: r.j,
458
+ bytes: concatBytes([l.bytes, link, r.bytes]),
459
+ cover: true,
460
+ rec: true,
461
+ node: r.node,
462
+ },
463
+ cost: 0,
464
+ };
465
+ }
466
+ /** form(i,j,node,via): follow the graph out of `node`, or (in articulation)
467
+ * emit its substitute voice directly. */
468
+ *formRules(it, conceptTarget, substitutions, nodeBytes) {
469
+ // Articulation: emit voice bytes at the recognised span; the hop/concept/
470
+ // emit chain is suppressed — the form contributes only its substitute.
471
+ if (substitutions) {
472
+ const voice = substitutions.get(it.node);
473
+ if (voice !== undefined) {
474
+ yield {
475
+ premises: [it],
476
+ conclusion: {
477
+ kind: "out",
478
+ i: it.i,
479
+ j: it.j,
480
+ bytes: voice,
481
+ cover: true,
482
+ rec: true,
483
+ node: it.node,
484
+ },
485
+ cost: 0,
486
+ };
487
+ }
488
+ return;
489
+ }
490
+ if (it.via) {
491
+ // A CHAIN hop (this form was itself reached by following an edge):
492
+ // read up to the hub bound — the SAME √(max(2,N)) convention {@link
493
+ // hubBound} in traverse.ts derives, replicated here because
494
+ // GraphSearch holds only a bare Store, not a MindContext — and fork
495
+ // across EVERY continuation. A bidirectional pair (SmolSent trains
496
+ // both directions) puts the back-edge to where we came from ahead of
497
+ // the forward edge in insertion order; a single first-inserted pick
498
+ // would walk the search straight into a cycle (the A*LD duplicate-key
499
+ // guard then dead-ends it) with no way to reach the forward edge.
500
+ // Forking offers every continuation as its own rule so the one that
501
+ // genuinely advances (not a duplicate) is still reachable.
502
+ const bound = Math.ceil(Math.sqrt(Math.max(2, this.store.edgeSourceCount())));
503
+ const nx = this.store.nextFirst(it.node, bound);
504
+ if (nx.length) {
505
+ // The SAME evidence-weighted disambiguation the first hop uses
506
+ // (below) identifies the most-corroborated continuation. Yielding
507
+ // it FIRST matters: {@link lightestDerivation}'s chart keeps the
508
+ // FIRST rule to reach a given cost for an item and discards later
509
+ // arrivals at an EQUAL cost (`cost < current`, strictly) — so
510
+ // among same-depth sibling forks that tie in cost, the
511
+ // evidence-backed edge wins deterministically, never by
512
+ // exploration-order luck. `preferred`, when set, is necessarily
513
+ // an element of `nx` (chooseNext reads the identical hub-bounded
514
+ // set — see traverse.ts), so a plain skip-in-place suffices; no
515
+ // second array need be allocated to reorder it to the front.
516
+ const preferred = nx.length > 1
517
+ ? this.host.chooseNext?.(it.node)
518
+ : undefined;
519
+ const fork = (node) => ({
520
+ premises: [it],
521
+ conclusion: { kind: "form", i: it.i, j: it.j, node, via: true },
522
+ // A real edge always costs STEP, whether it is the first hop or
523
+ // the fifth — so a chain's total cost is proportional to its
524
+ // length and the lightest derivation is always the SHORTEST
525
+ // successful one. (Charging every hop after the first for
526
+ // FREE, as an earlier design did, made every stopping point at
527
+ // any depth tie at the same cost — indistinguishable to the
528
+ // search, decided by whichever arrived first.)
529
+ cost: STEP,
530
+ });
531
+ if (preferred !== undefined)
532
+ yield fork(preferred);
533
+ for (const c of nx) {
534
+ if (c !== preferred)
535
+ yield fork(c);
536
+ }
537
+ // Also offer stopping HERE, at CONCEPT above whatever the chain
538
+ // has already cost — the same "a synonym jump is dearer than a
539
+ // direct edge" ordering the ladder already uses elsewhere,
540
+ // repurposed as "giving up early is dearer than one more real
541
+ // hop". A premature stop at depth D costs D·STEP + CONCEPT, so a
542
+ // SHORTER premature stop always beats a longer one, and a genuine
543
+ // fixpoint (below, costing +0) always beats any premature stop at
544
+ // the same depth — the search only settles here when continuing
545
+ // genuinely dead-ends (every fork above revisits an already-
546
+ // explored key) or grows costlier than giving up.
547
+ //
548
+ // The stop-here bytes are the node's OWN, as-is — NOT recompleteNode's
549
+ // recursive re-cover. recompleteNode re-runs the full recognition
550
+ // + edge/fuse search over the node's bytes, an O(node's own
551
+ // substructure) cost independent of chain depth; offering it at
552
+ // EVERY premature stop makes a query's total cost scale with how
553
+ // many nodes the corpus happens to interconnect here (corpus
554
+ // density), not with the answer's own hop count — the exact
555
+ // output-sensitivity the rest of this search is built to keep.
556
+ // Reserved below for the ONE place it is load-bearing: the true
557
+ // fixpoint, checked once, at the chain's actual end.
558
+ yield {
559
+ premises: [it],
560
+ conclusion: {
561
+ kind: "out",
562
+ i: it.i,
563
+ j: it.j,
564
+ bytes: nodeBytes(it.node),
565
+ cover: true,
566
+ rec: true,
567
+ node: it.node,
568
+ },
569
+ cost: CONCEPT,
570
+ };
571
+ return;
572
+ }
573
+ // The chain reached a node with no WHOLE-node continuation anywhere
574
+ // — a genuine fixpoint, not a premature stop. Before emitting it as
575
+ // terminal, CONTINUE THE EXPLORATION into its own structure: a
576
+ // composite answer like "p1 p2" leads nowhere as a whole, yet
577
+ // recognising it surfaces p1, p2 — each of which continues (→ R1,
578
+ // R2) and recomposes into a deeper learnt form (→ FINAL). {@link
579
+ // recompleteNode} re-covers the node's bytes through the SAME
580
+ // recognition + edge/fuse machinery the top query uses (a continued
581
+ // graph exploration, not a re-perception), and returns the deeper
582
+ // completion's bytes when it genuinely leads somewhere new. Emit
583
+ // that; else emit the node itself as the terminal answer. This is
584
+ // the ONE place the recursive re-cover runs — once, at the chain's
585
+ // actual end, never per intermediate stop — so its cost tracks the
586
+ // ANSWER's own structure, not how densely the corpus interconnects
587
+ // the nodes passed through on the way there.
588
+ const deeper = this.recompleteNode(it.node);
589
+ yield {
590
+ premises: [it],
591
+ conclusion: {
592
+ kind: "out",
593
+ i: it.i,
594
+ j: it.j,
595
+ bytes: deeper ?? nodeBytes(it.node),
596
+ cover: true,
597
+ rec: true,
598
+ node: it.node,
599
+ },
600
+ cost: 0,
601
+ };
602
+ }
603
+ else {
604
+ // The FIRST hop out of a recognised site — unchanged from the
605
+ // original design. LIMIT 2 only senses PLURALITY (does this node
606
+ // have more than one learnt continuation?); the actual bounded read
607
+ // and evidence-weighted pick both live inside {@link
608
+ // Mind.chooseNext} (see traverse.ts), which floors its own hub bound
609
+ // at √(max(2,N)) regardless of what we read here.
610
+ const nx = this.store.nextFirst(it.node, 2);
611
+ if (nx.length) {
612
+ yield {
613
+ premises: [it],
614
+ conclusion: {
615
+ kind: "form",
616
+ i: it.i,
617
+ j: it.j,
618
+ node: (nx.length > 1 ? this.host.chooseNext?.(it.node) : undefined) ??
619
+ nx[0],
620
+ via: true,
621
+ rcmp: it.rcmp,
622
+ },
623
+ // A recomposed form's continuation is FREE: the two (or more) parts
624
+ // were already paid for as their own rewrites, and the single
625
+ // consolidated span saves one cover-bridge versus leaving them
626
+ // split — so charging 0 here makes the grounded whole (e.g.
627
+ // "DE"→F) strictly beat the split ("D","E") by exactly that saved
628
+ // bridge, deterministically.
629
+ cost: it.rcmp ? 0 : STEP,
630
+ };
631
+ return;
632
+ }
633
+ // Recognised but edge-less: borrow a concept (halo) sibling's edge. No
634
+ // edge and no concept means the form leads nowhere — it yields no rule, so
635
+ // a query of only such forms produces no derivation, and think is silent.
636
+ const target = conceptTarget.get(it.node);
637
+ if (target !== undefined) {
638
+ yield {
639
+ premises: [it],
640
+ conclusion: {
641
+ kind: "form",
642
+ i: it.i,
643
+ j: it.j,
644
+ node: target,
645
+ via: true,
646
+ },
647
+ cost: CONCEPT,
648
+ };
649
+ }
650
+ }
651
+ }
652
+ /** Complete a node that an edge produced but that bears no further whole-edge,
653
+ * by COVERING ITS OWN BYTES — the very same operation the top query runs.
654
+ * Completion is not a special pass: a produced composite ("p1 p2") is just
655
+ * another span to cover, and covering it re-applies recognition, edge-follow,
656
+ * fusion and recomposition to discover that its parts continue (p1→R1, p2→R2)
657
+ * and recompose into a deeper learnt form (→ FINAL). This is why a single
658
+ * edge-target needs no bespoke logic — it routes back through {@link solve}.
659
+ *
660
+ * Re-recognition (not the node's tree children) is what surfaces the learnt
661
+ * parts: content-defined chunking may cut "p1 p2" as "p1 p"|"2", so only
662
+ * recognising the bytes recovers p1 and p2 as the forms the graph knows.
663
+ *
664
+ * The recovered answer is accepted only when it MOVED and names a LEARNT node
665
+ * ({@link resolve}) — the graph itself gates against re-expanding a contained
666
+ * form ("ice is cold" ⊅→ "ice is cold is cold").
667
+ *
668
+ * Termination is INTRINSIC, not a depth limit: a node already on the
669
+ * completion stack ({@link recompleteOpen}) is not re-entered — a self-
670
+ * referential recomposition is a cycle that can yield nothing new, so it
671
+ * stops there, exactly as {@link completeForward} stops on a revisited edge.
672
+ * Distinct node ids are finite and each finished completion is memoised, so a
673
+ * legitimate chain runs as deep as the graph licenses and no further. */
674
+ recompleteNode(node) {
675
+ if (!this.host.recogniseSpan)
676
+ return null;
677
+ const memo = this.recompleteMemo;
678
+ if (memo.has(node))
679
+ return memo.get(node) ?? null;
680
+ // Cycle guard: a node being completed must not recurse back into itself.
681
+ if (this.recompleteOpen.has(node))
682
+ return null;
683
+ // A leaf or single-child node has no parts to recompose; skip before the
684
+ // costly recognition so a plain terminal answer pays nothing.
685
+ const nrec = this.store.get(node);
686
+ if (!nrec || nrec.kids === null || nrec.kids.length < 2) {
687
+ memo.set(node, null);
688
+ return null;
689
+ }
690
+ const bytes = this.store.bytesPrefix(node, ALL);
691
+ this.recompleteOpen.add(node);
692
+ try {
693
+ // Completion is cover: re-cover the produced bytes through the SAME solve
694
+ // routine, recognising them afresh. No concepts/connectors (those need the
695
+ // caller's async pre-resolution) — the recursion explores edges and fusion,
696
+ // which is what a deeper rewrite chain is made of.
697
+ const solved = this.solve(bytes.length, this.host.recogniseSpan(bytes), new Map());
698
+ const answer = solved && concatBytes(solved.segs.map((s) => s.bytes));
699
+ const out = (answer !== null && !bytesEqual(answer, bytes) &&
700
+ this.host.resolve(answer) !== null)
701
+ ? answer
702
+ : null;
703
+ memo.set(node, out);
704
+ return out;
705
+ }
706
+ finally {
707
+ this.recompleteOpen.delete(node);
708
+ }
709
+ }
710
+ /** Per-cover memo of each produced node's completion (so the many terminal
711
+ * outs of a long query re-cover each distinct node at most once); reset at the
712
+ * top of {@link cover}. */
713
+ recompleteMemo = new Map();
714
+ /** The nodes currently being re-completed — the recursion stack. A node in
715
+ * this set is not re-entered, so a cyclic recomposition terminates naturally
716
+ * (the same cycle guard {@link completeForward} uses), with no depth cap. */
717
+ recompleteOpen = new Set();
718
+ /** out(i,j,bytes,…): index it for the binary rules, then offer splicing a
719
+ * learnt connector (the in-search bridge), splitting (at a sub-leaf form
720
+ * boundary), bridging (cover(i) ∧ this → cover(j)), and fusing with an
721
+ * adjacent finalised out. */
722
+ *outRules(it, ctx) {
723
+ const { splits, coversDone, outsByStart, outsByEnd, coverableByStart } = ctx;
724
+ const outsByNode = ctx.outsByNode;
725
+ const byRight = ctx.linksByRight ?? new Map();
726
+ pushInto(outsByStart, it.i, it);
727
+ pushInto(outsByEnd, it.j, it);
728
+ if (it.rec && it.node !== undefined)
729
+ pushInto(outsByNode, it.node, it);
730
+ if (it.cover)
731
+ pushInto(coverableByStart, it.i, it);
732
+ // ── connector rule (the BRIDGE, in-search) ──────────────────────────
733
+ // A connector keyed `L,R` carries everything a learnt whole holds BETWEEN
734
+ // answer L and answer R — for an N-ary whole, that includes the interior
735
+ // answers (see {@link Mind.resolveGroupConnectors}). Splicing it joins L and
736
+ // R into one recognised span L+connector+R, priced inside the search. The
737
+ // rule fires for ADJACENT parts (R begins where L ends) AND across a gap that
738
+ // is ITSELF wholly recognised (an interior answer absorbed into the whole,
739
+ // Points 2 & 5) — but NEVER across the asker's own unrecognised separator (a
740
+ // space, comma), so "ice fire" stays "cold hot", never "cold or hot".
741
+ //
742
+ // Cost stays bounded by iterating only the FEW resolved connector targets of
743
+ // this out's node (links are selective and, for the N-ary case, keyed first→
744
+ // later — O(parts), not O(parts²)), and matching them against finalised outs
745
+ // by node id, rather than scanning every position pair.
746
+ const byLeft = ctx.linksByLeft;
747
+ if (byLeft && it.rec && it.node !== undefined) {
748
+ // L = this out, R = a later out whose node is a resolved target.
749
+ for (const [rNode, link] of byLeft.get(it.node) ?? []) {
750
+ for (const r of outsByNode.get(rNode) ?? []) {
751
+ const rule = this.trySplice(it, r, link, outsByEnd);
752
+ if (rule)
753
+ yield rule;
754
+ }
755
+ }
756
+ // R = this out, L = an earlier out whose node has a resolved target here.
757
+ for (const [lNode, link] of byRight.get(it.node) ?? []) {
758
+ for (const l of outsByNode.get(lNode) ?? []) {
759
+ const rule = this.trySplice(l, it, link, outsByEnd);
760
+ if (rule)
761
+ yield rule;
762
+ }
763
+ }
764
+ }
765
+ // Split an unrecognised out at a sub-leaf form boundary — demand-driven,
766
+ // only when a split point sits inside this out's range. Each half carries
767
+ // its own resolved node id so it can still anchor a fusion.
768
+ if (it.cover && !it.rec && it.j - it.i > 1) {
769
+ for (const k of splits) {
770
+ if (k > it.i && k < it.j) {
771
+ const lb = it.bytes.subarray(0, k - it.i);
772
+ const rb = it.bytes.subarray(k - it.i);
773
+ yield {
774
+ premises: [it],
775
+ conclusion: {
776
+ kind: "out",
777
+ i: it.i,
778
+ j: k,
779
+ bytes: lb,
780
+ cover: true,
781
+ rec: false,
782
+ node: ctx.findLeafU(lb),
783
+ },
784
+ cost: 0,
785
+ };
786
+ yield {
787
+ premises: [it],
788
+ conclusion: {
789
+ kind: "out",
790
+ i: k,
791
+ j: it.j,
792
+ bytes: rb,
793
+ cover: true,
794
+ rec: false,
795
+ node: ctx.findLeafU(rb),
796
+ },
797
+ cost: 0,
798
+ };
799
+ }
800
+ }
801
+ }
802
+ // The BRIDGE, fired from the out side: cover(i) ∧ this → cover(j). Same
803
+ // rule as coverRules, the other order of arrival — an out finalised after
804
+ // its start was already covered. Either way the connective (this out, when
805
+ // unrecognised) is carried into the cover chain so the asker's own link
806
+ // survives between the rewritten parts.
807
+ if (it.cover && coversDone.has(it.i)) {
808
+ yield this.bridgeRule({ kind: "cover", p: it.i }, it);
809
+ }
810
+ for (const r of outsByStart.get(it.j) ?? [])
811
+ yield* this.fuse(it, r, ctx);
812
+ for (const l of outsByEnd.get(it.i) ?? [])
813
+ yield* this.fuse(l, it, ctx);
814
+ }
815
+ /** Whether the query span [from, to) is wholly covered by RECOGNISED outs —
816
+ * the test that lets a connector jump across INTERIOR answers (an N-ary whole)
817
+ * but never across the asker's own unrecognised framing (a space or comma the
818
+ * asker wrote between parts). Empty span (from === to, the adjacent case) is
819
+ * trivially recognised. Otherwise step right-to-left: from `to`, find a
820
+ * recognised out ending there and continue from its start, until reaching
821
+ * `from`. Greedy-longest is sufficient here — the spans in play are the few
822
+ * recognised answers of one query, not a general interval cover. */
823
+ gapRecognised(from, to, outsByEnd) {
824
+ let pos = to;
825
+ while (pos > from) {
826
+ let stepped = -1;
827
+ for (const o of outsByEnd.get(pos) ?? []) {
828
+ if (o.rec && o.i >= from && o.i < pos) {
829
+ stepped = Math.min(stepped === -1 ? o.i : stepped, o.i);
830
+ }
831
+ }
832
+ if (stepped < 0)
833
+ return false; // a position not spanned by a recognised out
834
+ pos = stepped;
835
+ }
836
+ return true;
837
+ }
838
+ /** Fuse two adjacent finalised outs — the search's own discovery of forms
839
+ * that cross leaf boundaries. The concatenation may be a known leaf
840
+ * (findLeaf, when short enough), or — when both sides resolved — their pair a
841
+ * known branch (findBranch); a completion fused with its neighbour may spell
842
+ * a deeper learned form, recovered canonically by {@link resolve} (gated on a
843
+ * completion being present, so it only runs along chains). The fused span
844
+ * lives on as an intermediate out while it could still grow into a form, and
845
+ * enters the graph as a form the moment it names a node. */
846
+ *fuse(l, r, ctx) {
847
+ const bytes = concat2(l.bytes, r.bytes);
848
+ let node = bytes.length <= ctx.W ? ctx.findLeafU(bytes) : undefined;
849
+ // Whether this pair ACTUALLY forms a 2-child branch — the hard evidence
850
+ // that the fused bytes are a learned form worth keeping alive. Derived
851
+ // from the same findBranchU probe that sets `node`; when false, the pair
852
+ // is structurally unrecognised and an intermediate span that carries no
853
+ // node cannot contribute to any further fusion (findBranch needs two
854
+ // nodes, resolve needs a completion, and findLeaf already had its chance).
855
+ let pairFormsBranch = false;
856
+ if (node === undefined && l.node !== undefined && r.node !== undefined) {
857
+ node = ctx.findBranchU([l.node, r.node]);
858
+ pairFormsBranch = node !== undefined;
859
+ }
860
+ if (node === undefined && (l.rec || r.rec)) {
861
+ // Canonical recovery of a deeper learned form fused from a completion and
862
+ // its neighbour.
863
+ const id = this.host.resolve(bytes);
864
+ if (id !== null)
865
+ node = id;
866
+ }
867
+ // A completed rewrite (rec) must not be absorbed into an unrelated INTERIOR
868
+ // chunk of a one-shot phrase: that lets the chunk's continuation swallow the
869
+ // inter-part gap and corrupt the answer ("cold"+" " → "cold " ⊂ "cold or
870
+ // hot"; "Y"+" " → "Y " ⊂ "X then Y then Z"). A node learnt as a meaningful
871
+ // unit bears a halo (it took part in an episode); a bare phrase-interior
872
+ // chunk does not. So when a completion fuses into a node, require that node
873
+ // to be halo-bearing — a real fused form (a learnt fact context like "4+3")
874
+ // carries a halo and still passes.
875
+ if (node !== undefined && (l.rec || r.rec) && !this.store.hasHalo(node)) {
876
+ node = undefined;
877
+ }
878
+ // A node-less fused span is kept alive ONLY while it can still grow INTO a
879
+ // learned form: it's still ≤ W bytes (so a wider fuse might yet name it via
880
+ // findLeaf), or the pair ACTUALLY forms a branch (so the fused bytes are
881
+ // a real learned form, even if the halo gate cleared its node above). It is
882
+ // NOT kept merely because both sides carry a node — that "potential" gate
883
+ // let every pair of adjacent recognised forms produce an intermediate span
884
+ // regardless of whether they name a branch together, generating O(N²) chart
885
+ // items for N abutted forms where only O(N) pairs actually form branches.
886
+ // The earlier O(2ⁿ) gate (kept alive whenever a side was a completion) is
887
+ // already superseded by this one — a completion that genuinely deepens names
888
+ // a node via findBranch or resolve and is yielded as a form regardless.
889
+ const couldGrow = bytes.length <= ctx.W || pairFormsBranch;
890
+ if (node === undefined && !couldGrow)
891
+ return;
892
+ yield {
893
+ premises: [l, r],
894
+ conclusion: {
895
+ kind: "out",
896
+ i: l.i,
897
+ j: r.j,
898
+ bytes,
899
+ cover: false,
900
+ rec: false,
901
+ node,
902
+ },
903
+ cost: 0,
904
+ };
905
+ if (node !== undefined) {
906
+ // A RECOMPOSITION: two already-rewritten parts (both rec completions)
907
+ // fused into a node that itself CONTINUES. Tag the form so its onward
908
+ // step is charged at MICRO (see formRules) — the graph learned this whole,
909
+ // so following it to its grounded answer must win over leaving the parts
910
+ // split. An ordinary cross-leaf fuse (not from rewrites) is not tagged and
911
+ // keeps the normal STEP cost.
912
+ const recomposed = l.rec && r.rec && this.store.hasNext(node);
913
+ yield {
914
+ premises: [l, r],
915
+ conclusion: {
916
+ kind: "form",
917
+ i: l.i,
918
+ j: r.j,
919
+ node,
920
+ via: false,
921
+ rcmp: recomposed,
922
+ },
923
+ cost: 0,
924
+ };
925
+ }
926
+ }
927
+ }