@hviana/sema 0.1.0 → 0.1.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 +2216 -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 +212 -0
  26. package/dist/src/alu/src/parser.js +469 -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/config.d.ts +114 -0
  38. package/dist/src/config.js +96 -0
  39. package/dist/src/derive/src/deduction.d.ts +125 -0
  40. package/dist/src/derive/src/deduction.js +155 -0
  41. package/dist/src/derive/src/index.d.ts +7 -0
  42. package/dist/src/derive/src/index.js +11 -0
  43. package/dist/src/derive/src/priority-queue.d.ts +20 -0
  44. package/dist/src/derive/src/priority-queue.js +73 -0
  45. package/dist/src/derive/src/rewrite.d.ts +56 -0
  46. package/dist/src/derive/src/rewrite.js +100 -0
  47. package/dist/src/derive/src/trie.d.ts +90 -0
  48. package/dist/src/derive/src/trie.js +217 -0
  49. package/dist/src/derive/test/derive.test.d.ts +1 -0
  50. package/dist/src/derive/test/derive.test.js +122 -0
  51. package/dist/src/extension.d.ts +37 -0
  52. package/dist/src/extension.js +7 -0
  53. package/dist/src/geometry.d.ts +137 -0
  54. package/dist/src/geometry.js +430 -0
  55. package/dist/src/index.d.ts +15 -0
  56. package/dist/src/index.js +21 -0
  57. package/dist/src/ingest-cache.d.ts +41 -0
  58. package/dist/src/ingest-cache.js +161 -0
  59. package/dist/src/mind/articulation.d.ts +6 -0
  60. package/dist/src/mind/articulation.js +99 -0
  61. package/dist/src/mind/attention.d.ts +72 -0
  62. package/dist/src/mind/attention.js +894 -0
  63. package/dist/src/mind/canonical.d.ts +29 -0
  64. package/dist/src/mind/canonical.js +88 -0
  65. package/dist/src/mind/graph-search.d.ts +270 -0
  66. package/dist/src/mind/graph-search.js +847 -0
  67. package/dist/src/mind/index.d.ts +5 -0
  68. package/dist/src/mind/index.js +5 -0
  69. package/dist/src/mind/junction.d.ts +95 -0
  70. package/dist/src/mind/junction.js +262 -0
  71. package/dist/src/mind/learning.d.ts +47 -0
  72. package/dist/src/mind/learning.js +201 -0
  73. package/dist/src/mind/match.d.ts +111 -0
  74. package/dist/src/mind/match.js +422 -0
  75. package/dist/src/mind/mechanisms/alu.d.ts +4 -0
  76. package/dist/src/mind/mechanisms/alu.js +29 -0
  77. package/dist/src/mind/mechanisms/cast.d.ts +35 -0
  78. package/dist/src/mind/mechanisms/cast.js +447 -0
  79. package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
  80. package/dist/src/mind/mechanisms/confluence.js +213 -0
  81. package/dist/src/mind/mechanisms/cover.d.ts +6 -0
  82. package/dist/src/mind/mechanisms/cover.js +179 -0
  83. package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
  84. package/dist/src/mind/mechanisms/extraction.js +342 -0
  85. package/dist/src/mind/mechanisms/recall.d.ts +13 -0
  86. package/dist/src/mind/mechanisms/recall.js +151 -0
  87. package/dist/src/mind/mind.d.ts +147 -0
  88. package/dist/src/mind/mind.js +300 -0
  89. package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
  90. package/dist/src/mind/pipeline-mechanism.js +213 -0
  91. package/dist/src/mind/pipeline.d.ts +20 -0
  92. package/dist/src/mind/pipeline.js +185 -0
  93. package/dist/src/mind/primitives.d.ts +43 -0
  94. package/dist/src/mind/primitives.js +162 -0
  95. package/dist/src/mind/rationale.d.ts +134 -0
  96. package/dist/src/mind/rationale.js +162 -0
  97. package/dist/src/mind/reasoning.d.ts +15 -0
  98. package/dist/src/mind/reasoning.js +162 -0
  99. package/dist/src/mind/recognition.d.ts +20 -0
  100. package/dist/src/mind/recognition.js +223 -0
  101. package/dist/src/mind/resonance.d.ts +23 -0
  102. package/dist/src/mind/resonance.js +0 -0
  103. package/dist/src/mind/trace.d.ts +15 -0
  104. package/dist/src/mind/trace.js +73 -0
  105. package/dist/src/mind/traverse.d.ts +100 -0
  106. package/dist/src/mind/traverse.js +447 -0
  107. package/dist/src/mind/types.d.ts +174 -0
  108. package/dist/src/mind/types.js +84 -0
  109. package/dist/src/rabitq-hnsw/src/database.d.ts +200 -0
  110. package/dist/src/rabitq-hnsw/src/database.js +388 -0
  111. package/dist/src/rabitq-hnsw/src/heap.d.ts +22 -0
  112. package/dist/src/rabitq-hnsw/src/heap.js +89 -0
  113. package/dist/src/rabitq-hnsw/src/hnsw.d.ts +125 -0
  114. package/dist/src/rabitq-hnsw/src/hnsw.js +474 -0
  115. package/dist/src/rabitq-hnsw/src/index.d.ts +10 -0
  116. package/dist/src/rabitq-hnsw/src/index.js +6 -0
  117. package/dist/src/rabitq-hnsw/src/prng.d.ts +19 -0
  118. package/dist/src/rabitq-hnsw/src/prng.js +36 -0
  119. package/dist/src/rabitq-hnsw/src/rabitq.d.ts +95 -0
  120. package/dist/src/rabitq-hnsw/src/rabitq.js +283 -0
  121. package/dist/src/rabitq-hnsw/src/store.d.ts +162 -0
  122. package/dist/src/rabitq-hnsw/src/store.js +825 -0
  123. package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +1 -0
  124. package/dist/src/rabitq-hnsw/test/hnsw.test.js +948 -0
  125. package/dist/src/store-sqlite.d.ts +149 -0
  126. package/dist/src/store-sqlite.js +702 -0
  127. package/dist/src/store.d.ts +638 -0
  128. package/dist/src/store.js +1618 -0
  129. package/dist/src/vec.d.ts +31 -0
  130. package/dist/src/vec.js +109 -0
  131. package/package.json +1 -1
@@ -0,0 +1,847 @@
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
+ // LIMIT 2 decides all three facts this rule needs — emptiness, plurality
491
+ // (whether to consult the disambiguator), and the first-inserted
492
+ // fallback — without materialising a hub context's corpus-sized fan-out.
493
+ const nx = this.store.nextFirst(it.node, 2);
494
+ if (nx.length) {
495
+ // A direct edge — step along the chain toward its fixpoint. A recomposed
496
+ // form (parts already rewritten and fused into a learned whole) follows
497
+ // its continuation at MICRO, so reaching the grounded answer of the
498
+ // recomposition beats leaving the parts split; the flag rides the chain so
499
+ // every step of the recomposition's completion stays cheap.
500
+ //
501
+ // WHICH edge: a context node often carries SEVERAL learnt continuations
502
+ // (the same sentence trained against 100+ target languages, a question
503
+ // answered differently across sessions). `nx[0]` is an accident of
504
+ // training order; when the host provides a `chooseNext` disambiguator
505
+ // (see Mind.chooseNext) it picks the continuation with the most
506
+ // distributional evidence (prevOf count — the structural manifestation
507
+ // of its halo), falling back to first-inserted when evidence is equal.
508
+ yield {
509
+ premises: [it],
510
+ conclusion: {
511
+ kind: "form",
512
+ i: it.i,
513
+ j: it.j,
514
+ node: (nx.length > 1 ? this.host.chooseNext?.(it.node) : undefined) ??
515
+ nx[0],
516
+ via: true,
517
+ rcmp: it.rcmp,
518
+ },
519
+ // A recomposed form's continuation is FREE: the two (or more) parts were
520
+ // already paid for as their own rewrites, and the single consolidated
521
+ // span saves one cover-bridge versus leaving them split — so charging 0
522
+ // here makes the grounded whole (e.g. "DE"→F) strictly beat the split
523
+ // ("D","E") by exactly that saved bridge, deterministically.
524
+ cost: it.rcmp ? 0 : STEP,
525
+ };
526
+ }
527
+ else if (it.via) {
528
+ // The chain reached a node with no WHOLE-node continuation. Before
529
+ // emitting it as terminal, CONTINUE THE EXPLORATION into its own structure:
530
+ // a composite answer like "p1 p2" leads nowhere as a whole, yet recognising
531
+ // it surfaces p1, p2 — each of which continues (→ R1, R2) and recomposes
532
+ // into a deeper learnt form (→ FINAL). {@link recompleteNode} re-covers the
533
+ // node's bytes through the SAME recognition + edge/fuse machinery the top
534
+ // query uses (a continued graph exploration, not a re-perception), and
535
+ // returns the deeper completion's bytes when it genuinely leads somewhere
536
+ // new. Emit that; else emit the node itself as the terminal answer.
537
+ const deeper = this.recompleteNode(it.node);
538
+ yield {
539
+ premises: [it],
540
+ conclusion: {
541
+ kind: "out",
542
+ i: it.i,
543
+ j: it.j,
544
+ bytes: deeper ?? nodeBytes(it.node),
545
+ cover: true,
546
+ rec: true,
547
+ node: it.node,
548
+ },
549
+ cost: 0,
550
+ };
551
+ }
552
+ else {
553
+ // Recognised but edge-less: borrow a concept (halo) sibling's edge. No
554
+ // edge and no concept means the form leads nowhere — it yields no rule, so
555
+ // a query of only such forms produces no derivation, and think is silent.
556
+ const target = conceptTarget.get(it.node);
557
+ if (target !== undefined) {
558
+ yield {
559
+ premises: [it],
560
+ conclusion: {
561
+ kind: "form",
562
+ i: it.i,
563
+ j: it.j,
564
+ node: target,
565
+ via: true,
566
+ },
567
+ cost: CONCEPT,
568
+ };
569
+ }
570
+ }
571
+ }
572
+ /** Complete a node that an edge produced but that bears no further whole-edge,
573
+ * by COVERING ITS OWN BYTES — the very same operation the top query runs.
574
+ * Completion is not a special pass: a produced composite ("p1 p2") is just
575
+ * another span to cover, and covering it re-applies recognition, edge-follow,
576
+ * fusion and recomposition to discover that its parts continue (p1→R1, p2→R2)
577
+ * and recompose into a deeper learnt form (→ FINAL). This is why a single
578
+ * edge-target needs no bespoke logic — it routes back through {@link solve}.
579
+ *
580
+ * Re-recognition (not the node's tree children) is what surfaces the learnt
581
+ * parts: content-defined chunking may cut "p1 p2" as "p1 p"|"2", so only
582
+ * recognising the bytes recovers p1 and p2 as the forms the graph knows.
583
+ *
584
+ * The recovered answer is accepted only when it MOVED and names a LEARNT node
585
+ * ({@link resolve}) — the graph itself gates against re-expanding a contained
586
+ * form ("ice is cold" ⊅→ "ice is cold is cold").
587
+ *
588
+ * Termination is INTRINSIC, not a depth limit: a node already on the
589
+ * completion stack ({@link recompleteOpen}) is not re-entered — a self-
590
+ * referential recomposition is a cycle that can yield nothing new, so it
591
+ * stops there, exactly as {@link completeForward} stops on a revisited edge.
592
+ * Distinct node ids are finite and each finished completion is memoised, so a
593
+ * legitimate chain runs as deep as the graph licenses and no further. */
594
+ recompleteNode(node) {
595
+ if (!this.host.recogniseSpan)
596
+ return null;
597
+ const memo = this.recompleteMemo;
598
+ if (memo.has(node))
599
+ return memo.get(node) ?? null;
600
+ // Cycle guard: a node being completed must not recurse back into itself.
601
+ if (this.recompleteOpen.has(node))
602
+ return null;
603
+ // A leaf or single-child node has no parts to recompose; skip before the
604
+ // costly recognition so a plain terminal answer pays nothing.
605
+ const nrec = this.store.get(node);
606
+ if (!nrec || nrec.kids === null || nrec.kids.length < 2) {
607
+ memo.set(node, null);
608
+ return null;
609
+ }
610
+ const bytes = this.store.bytesPrefix(node, ALL);
611
+ this.recompleteOpen.add(node);
612
+ try {
613
+ // Completion is cover: re-cover the produced bytes through the SAME solve
614
+ // routine, recognising them afresh. No concepts/connectors (those need the
615
+ // caller's async pre-resolution) — the recursion explores edges and fusion,
616
+ // which is what a deeper rewrite chain is made of.
617
+ const solved = this.solve(bytes.length, this.host.recogniseSpan(bytes), new Map());
618
+ const answer = solved && concatBytes(solved.segs.map((s) => s.bytes));
619
+ const out = (answer !== null && !bytesEqual(answer, bytes) &&
620
+ this.host.resolve(answer) !== null)
621
+ ? answer
622
+ : null;
623
+ memo.set(node, out);
624
+ return out;
625
+ }
626
+ finally {
627
+ this.recompleteOpen.delete(node);
628
+ }
629
+ }
630
+ /** Per-cover memo of each produced node's completion (so the many terminal
631
+ * outs of a long query re-cover each distinct node at most once); reset at the
632
+ * top of {@link cover}. */
633
+ recompleteMemo = new Map();
634
+ /** The nodes currently being re-completed — the recursion stack. A node in
635
+ * this set is not re-entered, so a cyclic recomposition terminates naturally
636
+ * (the same cycle guard {@link completeForward} uses), with no depth cap. */
637
+ recompleteOpen = new Set();
638
+ /** out(i,j,bytes,…): index it for the binary rules, then offer splicing a
639
+ * learnt connector (the in-search bridge), splitting (at a sub-leaf form
640
+ * boundary), bridging (cover(i) ∧ this → cover(j)), and fusing with an
641
+ * adjacent finalised out. */
642
+ *outRules(it, ctx) {
643
+ const { splits, coversDone, outsByStart, outsByEnd, coverableByStart } = ctx;
644
+ const outsByNode = ctx.outsByNode;
645
+ const byRight = ctx.linksByRight ?? new Map();
646
+ pushInto(outsByStart, it.i, it);
647
+ pushInto(outsByEnd, it.j, it);
648
+ if (it.rec && it.node !== undefined)
649
+ pushInto(outsByNode, it.node, it);
650
+ if (it.cover)
651
+ pushInto(coverableByStart, it.i, it);
652
+ // ── connector rule (the BRIDGE, in-search) ──────────────────────────
653
+ // A connector keyed `L,R` carries everything a learnt whole holds BETWEEN
654
+ // answer L and answer R — for an N-ary whole, that includes the interior
655
+ // answers (see {@link Mind.resolveGroupConnectors}). Splicing it joins L and
656
+ // R into one recognised span L+connector+R, priced inside the search. The
657
+ // rule fires for ADJACENT parts (R begins where L ends) AND across a gap that
658
+ // is ITSELF wholly recognised (an interior answer absorbed into the whole,
659
+ // Points 2 & 5) — but NEVER across the asker's own unrecognised separator (a
660
+ // space, comma), so "ice fire" stays "cold hot", never "cold or hot".
661
+ //
662
+ // Cost stays bounded by iterating only the FEW resolved connector targets of
663
+ // this out's node (links are selective and, for the N-ary case, keyed first→
664
+ // later — O(parts), not O(parts²)), and matching them against finalised outs
665
+ // by node id, rather than scanning every position pair.
666
+ const byLeft = ctx.linksByLeft;
667
+ if (byLeft && it.rec && it.node !== undefined) {
668
+ // L = this out, R = a later out whose node is a resolved target.
669
+ for (const [rNode, link] of byLeft.get(it.node) ?? []) {
670
+ for (const r of outsByNode.get(rNode) ?? []) {
671
+ const rule = this.trySplice(it, r, link, outsByEnd);
672
+ if (rule)
673
+ yield rule;
674
+ }
675
+ }
676
+ // R = this out, L = an earlier out whose node has a resolved target here.
677
+ for (const [lNode, link] of byRight.get(it.node) ?? []) {
678
+ for (const l of outsByNode.get(lNode) ?? []) {
679
+ const rule = this.trySplice(l, it, link, outsByEnd);
680
+ if (rule)
681
+ yield rule;
682
+ }
683
+ }
684
+ }
685
+ // Split an unrecognised out at a sub-leaf form boundary — demand-driven,
686
+ // only when a split point sits inside this out's range. Each half carries
687
+ // its own resolved node id so it can still anchor a fusion.
688
+ if (it.cover && !it.rec && it.j - it.i > 1) {
689
+ for (const k of splits) {
690
+ if (k > it.i && k < it.j) {
691
+ const lb = it.bytes.subarray(0, k - it.i);
692
+ const rb = it.bytes.subarray(k - it.i);
693
+ yield {
694
+ premises: [it],
695
+ conclusion: {
696
+ kind: "out",
697
+ i: it.i,
698
+ j: k,
699
+ bytes: lb,
700
+ cover: true,
701
+ rec: false,
702
+ node: ctx.findLeafU(lb),
703
+ },
704
+ cost: 0,
705
+ };
706
+ yield {
707
+ premises: [it],
708
+ conclusion: {
709
+ kind: "out",
710
+ i: k,
711
+ j: it.j,
712
+ bytes: rb,
713
+ cover: true,
714
+ rec: false,
715
+ node: ctx.findLeafU(rb),
716
+ },
717
+ cost: 0,
718
+ };
719
+ }
720
+ }
721
+ }
722
+ // The BRIDGE, fired from the out side: cover(i) ∧ this → cover(j). Same
723
+ // rule as coverRules, the other order of arrival — an out finalised after
724
+ // its start was already covered. Either way the connective (this out, when
725
+ // unrecognised) is carried into the cover chain so the asker's own link
726
+ // survives between the rewritten parts.
727
+ if (it.cover && coversDone.has(it.i)) {
728
+ yield this.bridgeRule({ kind: "cover", p: it.i }, it);
729
+ }
730
+ for (const r of outsByStart.get(it.j) ?? [])
731
+ yield* this.fuse(it, r, ctx);
732
+ for (const l of outsByEnd.get(it.i) ?? [])
733
+ yield* this.fuse(l, it, ctx);
734
+ }
735
+ /** Whether the query span [from, to) is wholly covered by RECOGNISED outs —
736
+ * the test that lets a connector jump across INTERIOR answers (an N-ary whole)
737
+ * but never across the asker's own unrecognised framing (a space or comma the
738
+ * asker wrote between parts). Empty span (from === to, the adjacent case) is
739
+ * trivially recognised. Otherwise step right-to-left: from `to`, find a
740
+ * recognised out ending there and continue from its start, until reaching
741
+ * `from`. Greedy-longest is sufficient here — the spans in play are the few
742
+ * recognised answers of one query, not a general interval cover. */
743
+ gapRecognised(from, to, outsByEnd) {
744
+ let pos = to;
745
+ while (pos > from) {
746
+ let stepped = -1;
747
+ for (const o of outsByEnd.get(pos) ?? []) {
748
+ if (o.rec && o.i >= from && o.i < pos) {
749
+ stepped = Math.min(stepped === -1 ? o.i : stepped, o.i);
750
+ }
751
+ }
752
+ if (stepped < 0)
753
+ return false; // a position not spanned by a recognised out
754
+ pos = stepped;
755
+ }
756
+ return true;
757
+ }
758
+ /** Fuse two adjacent finalised outs — the search's own discovery of forms
759
+ * that cross leaf boundaries. The concatenation may be a known leaf
760
+ * (findLeaf, when short enough), or — when both sides resolved — their pair a
761
+ * known branch (findBranch); a completion fused with its neighbour may spell
762
+ * a deeper learned form, recovered canonically by {@link resolve} (gated on a
763
+ * completion being present, so it only runs along chains). The fused span
764
+ * lives on as an intermediate out while it could still grow into a form, and
765
+ * enters the graph as a form the moment it names a node. */
766
+ *fuse(l, r, ctx) {
767
+ const bytes = concat2(l.bytes, r.bytes);
768
+ let node = bytes.length <= ctx.W ? ctx.findLeafU(bytes) : undefined;
769
+ // Whether this pair ACTUALLY forms a 2-child branch — the hard evidence
770
+ // that the fused bytes are a learned form worth keeping alive. Derived
771
+ // from the same findBranchU probe that sets `node`; when false, the pair
772
+ // is structurally unrecognised and an intermediate span that carries no
773
+ // node cannot contribute to any further fusion (findBranch needs two
774
+ // nodes, resolve needs a completion, and findLeaf already had its chance).
775
+ let pairFormsBranch = false;
776
+ if (node === undefined && l.node !== undefined && r.node !== undefined) {
777
+ node = ctx.findBranchU([l.node, r.node]);
778
+ pairFormsBranch = node !== undefined;
779
+ }
780
+ if (node === undefined && (l.rec || r.rec)) {
781
+ // Canonical recovery of a deeper learned form fused from a completion and
782
+ // its neighbour.
783
+ const id = this.host.resolve(bytes);
784
+ if (id !== null)
785
+ node = id;
786
+ }
787
+ // A completed rewrite (rec) must not be absorbed into an unrelated INTERIOR
788
+ // chunk of a one-shot phrase: that lets the chunk's continuation swallow the
789
+ // inter-part gap and corrupt the answer ("cold"+" " → "cold " ⊂ "cold or
790
+ // hot"; "Y"+" " → "Y " ⊂ "X then Y then Z"). A node learnt as a meaningful
791
+ // unit bears a halo (it took part in an episode); a bare phrase-interior
792
+ // chunk does not. So when a completion fuses into a node, require that node
793
+ // to be halo-bearing — a real fused form (a learnt fact context like "4+3")
794
+ // carries a halo and still passes.
795
+ if (node !== undefined && (l.rec || r.rec) && !this.store.hasHalo(node)) {
796
+ node = undefined;
797
+ }
798
+ // A node-less fused span is kept alive ONLY while it can still grow INTO a
799
+ // learned form: it's still ≤ W bytes (so a wider fuse might yet name it via
800
+ // findLeaf), or the pair ACTUALLY forms a branch (so the fused bytes are
801
+ // a real learned form, even if the halo gate cleared its node above). It is
802
+ // NOT kept merely because both sides carry a node — that "potential" gate
803
+ // let every pair of adjacent recognised forms produce an intermediate span
804
+ // regardless of whether they name a branch together, generating O(N²) chart
805
+ // items for N abutted forms where only O(N) pairs actually form branches.
806
+ // The earlier O(2ⁿ) gate (kept alive whenever a side was a completion) is
807
+ // already superseded by this one — a completion that genuinely deepens names
808
+ // a node via findBranch or resolve and is yielded as a form regardless.
809
+ const couldGrow = bytes.length <= ctx.W || pairFormsBranch;
810
+ if (node === undefined && !couldGrow)
811
+ return;
812
+ yield {
813
+ premises: [l, r],
814
+ conclusion: {
815
+ kind: "out",
816
+ i: l.i,
817
+ j: r.j,
818
+ bytes,
819
+ cover: false,
820
+ rec: false,
821
+ node,
822
+ },
823
+ cost: 0,
824
+ };
825
+ if (node !== undefined) {
826
+ // A RECOMPOSITION: two already-rewritten parts (both rec completions)
827
+ // fused into a node that itself CONTINUES. Tag the form so its onward
828
+ // step is charged at MICRO (see formRules) — the graph learned this whole,
829
+ // so following it to its grounded answer must win over leaving the parts
830
+ // split. An ordinary cross-leaf fuse (not from rewrites) is not tagged and
831
+ // keeps the normal STEP cost.
832
+ const recomposed = l.rec && r.rec && this.store.hasNext(node);
833
+ yield {
834
+ premises: [l, r],
835
+ conclusion: {
836
+ kind: "form",
837
+ i: l.i,
838
+ j: r.j,
839
+ node,
840
+ via: false,
841
+ rcmp: recomposed,
842
+ },
843
+ cost: 0,
844
+ };
845
+ }
846
+ }
847
+ }