@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,447 @@
1
+ // counterfactual.ts — Counterfactual Transfer / CAST (Section 4 of the mind).
2
+ //
3
+ // When a query weaves together byte-string evidence from multiple independently-
4
+ // learnt structures (disjoint run alignments, literal or distributional), CAST
5
+ // attempts to transfer structure between them — substitution, redirection, or
6
+ // analogical comparison — producing a counterfactual answer that goes beyond what
7
+ // the ordinary cover-and-extract pipeline can reach.
8
+ //
9
+ // CAST is a configuration of the elementary match-and-project operation
10
+ // (match.ts): matcher = alignGraded (literal W-gram runs + halo-matched pre.rec.sites),
11
+ // gate = the frame gate below + analogyStrength, projection = insert / project /
12
+ // juxtapose.
13
+ import { read } from "../primitives.js";
14
+ import { argmaxBy, hubBound } from "../traverse.js";
15
+ import { analogyStrength, follow, project, reverseContext, } from "../match.js";
16
+ import { joinWithBridge } from "../resonance.js";
17
+ import { CONCEPT, STEP } from "../graph-search.js";
18
+ import { concat2, indexOf } from "../../bytes.js";
19
+ import { dominates } from "../../geometry.js";
20
+ import { unexplainedLabel } from "../rationale.js";
21
+ import { rItem, rNode } from "../trace.js";
22
+ // ── CAST gates ────────────────────────────────────────────────────────────
23
+ //
24
+ // The frame gate has TWO components, both derived from the weave itself:
25
+ //
26
+ // 1. MIN WEAVE — the same 2 as the precondition `points.length < 2` (CAST
27
+ // needs at least two aligned structures to form a weave). Frame requires
28
+ // evidence BEYOND the minimum pair — a third structure agreeing — so the
29
+ // depth gate is `depth > MIN_WEAVE`. One definition, two uses.
30
+ //
31
+ // 2. HALF-DOMINANCE — `dominates(framed, len)` (the same test
32
+ // collectRegions, liftAnswer, and confluence's filler gate all use): a
33
+ // span more than half scaffolding no longer discriminates its own content.
34
+ // The per-byte test `dominates(depth[i], aligned)` classifies a byte as
35
+ // frame; the per-run test `dominates(framedCount, runLen)` decides
36
+ // whether the run is usable.
37
+ //
38
+ // Both are derived from structural quantities (aligned points, run length),
39
+ // never tuned. The constants below are the weave's own shape, not thresholds.
40
+ //
41
+ // DO NOT replace the frame gates with the structural IDF (reachOf +
42
+ // dominates): it was tried and empirically REFUTED (17-intelligence's
43
+ // reorder probe). CAST's frame is WEAVE-LOCAL — "what the aligned
44
+ // structures share among THEMSELVES" — while the IDF is corpus-global; a
45
+ // phrase common to the aligned exemplars (" describe it", "the importance
46
+ // of") is frame here even when it reaches only a corpus minority, and
47
+ // treating it as content lets the substitution branch fire on reordered
48
+ // single-fact queries. The two commonality notions coincide often, but
49
+ // neither derives the other.
50
+ /** The minimum number of aligned structures to form a weave — the same 2 that
51
+ * gates CAST entry (`points.length < 2`). Frame requires MORE than this
52
+ * minimum: `depth > MIN_WEAVE` means at least three structures agree on a
53
+ * byte, so no byte is frame when only the minimum pair exists. */
54
+ const MIN_WEAVE = 2;
55
+ /** CAST's own entry gates, checked once here and reused by
56
+ /** The main CAST entry point. Given a query and its pre-computed pre.rec.sites,
57
+ * determine whether the query weaves together multiple independent learnt
58
+ * structures (by graded alignment — literal first, then halo-matched pre.rec.sites).
59
+ * If so, attempt substitution, redirection, AND analogical comparison —
60
+ * each schema is tried independently and every one that fires yields its
61
+ * OWN candidate; think's grounding decider (which already compares weights
62
+ * across mechanisms) picks among them, so CAST no longer needs an internal
63
+ * priority order.
64
+ *
65
+ * `climb`, when given, is {@link castFloor}'s own climb result — reused
66
+ * instead of re-running climbAttentionAll (see the note on {@link
67
+ * CastFloor}). Its gates (`query.length`, `edgeSourceCount`,
68
+ * `ranked.length < 2`) MUST stay in sync with castFloor's — one is the
69
+ * other's admissible lower bound, checked before this runs.
70
+ *
71
+ * Returns the array of {@link CastResult}s that fired (possibly empty). */
72
+ export async function counterfactualTransfer(ctx, query, pre) {
73
+ const quantum = ctx.space.maxGroup;
74
+ if (query.length < 2 * quantum || ctx.store.edgeSourceCount() === 0) {
75
+ return [];
76
+ }
77
+ const { roots, ranked } = await pre.attention();
78
+ if (ranked.length < 2)
79
+ return [];
80
+ const weave = await pre.weave();
81
+ const points = weave.points;
82
+ const depth = weave.depth;
83
+ const aligned = points.length;
84
+ if (aligned < 2)
85
+ return [];
86
+ // ── Frame gate (half-dominance, weave-local) ─────────────────────────
87
+ // A byte is FRAME when more than MIN_WEAVE aligned structures cover it
88
+ // AND those structures are a majority of all aligned structures.
89
+ // Per-byte: frame(i) ⇔ depth[i] > MIN_WEAVE ∧ dominates(depth[i], aligned)
90
+ // Per-run: usable(r) ⇔ ¬dominates(framedCount, runLen)
91
+ const isFrame = (i) => depth[i] > MIN_WEAVE && dominates(depth[i], aligned);
92
+ const framedCount = (qs, qe) => {
93
+ let n = 0;
94
+ for (let i = qs; i < qe; i++)
95
+ if (isFrame(i))
96
+ n++;
97
+ return n;
98
+ };
99
+ const usable = (qs, qe) => !dominates(framedCount(qs, qe), qe - qs);
100
+ // The weave's DOMINANT is its principal STRUCTURE — the aligned point
101
+ // explaining the most query bytes — not the climb's top-ranked TOPIC.
102
+ // The two used to coincide (approximate votes from a query's novel spans
103
+ // boosted whichever exemplar shared its frame), but the contrastive
104
+ // margin ranks the query's own exact site first, and CAST's schemas all
105
+ // orient around the frame-bearing structure: the substitution/redirection
106
+ // seat is displaced IN the dominant, and comparison seats the analogs by
107
+ // the contexts that establish their roles. Coverage is weave-local and
108
+ // derived (sum of aligned run lengths); ties keep the ranked order.
109
+ let dominant = points[0];
110
+ let domCover = -1;
111
+ for (const p of points) {
112
+ let cover = 0;
113
+ for (const r of p.runs)
114
+ cover += r.qe - r.qs;
115
+ if (cover > domCover) {
116
+ domCover = cover;
117
+ dominant = p;
118
+ }
119
+ }
120
+ const isRoot = (id) => roots.some((r) => r.anchor === id);
121
+ // The weave must touch a COMMITTED point of attention: the dominant
122
+ // structure itself, or another aligned point the climb committed to.
123
+ if (!points.some((p) => isRoot(p.anchor)))
124
+ return [];
125
+ const woven = points.some((p) => p.runs.some((r) => !pre.rec.sites.some((s) => r.qs >= s.start && r.qe <= s.end)));
126
+ if (!woven)
127
+ return [];
128
+ const t = ctx.trace?.enter("counterfactual", [
129
+ rItem(query, "query"),
130
+ ]);
131
+ // Each schema tried below RECORDS its candidate (when it fires) rather than
132
+ // returning immediately — every schema that succeeds contributes its own
133
+ // candidate, and the grounding decider's own weight comparison (not CAST's
134
+ // former internal priority) picks among them.
135
+ //
136
+ // `accounted` is SCHEMA-SPECIFIC, not the whole weave's alignment: a
137
+ // schema only actually TRANSFERS BETWEEN the two points its own logic
138
+ // names (substitution: the filled subject + the displaced seat;
139
+ // redirection: the displaced seat + the named substitute; comparison:
140
+ // the dominant + its analog) — a THIRD point the weave happened to align
141
+ // but this schema never touched contributes nothing to what THIS answer
142
+ // explains. Pricing every schema against the SAME "every kept point's
143
+ // every run" span would let the cheapest schema win on move-cost alone
144
+ // regardless of which one actually used more of the query; pricing it
145
+ // against only a fragment of even its OWN two points (e.g. one run
146
+ // instead of the point's full aligned evidence) is just as wrong the
147
+ // other way — it starves an otherwise-correct schema of credit for
148
+ // evidence it legitimately relied on. Each call site below passes the
149
+ // full run set of exactly the points ITS OWN transfer used — no more,
150
+ // no less.
151
+ const runSpans = (p) => p.runs.map((r) => [r.qs, r.qe]);
152
+ const results = [];
153
+ const record = (answer, note, used, moves, accounted) => {
154
+ if (answer === null)
155
+ return;
156
+ ctx.trace?.step("castSchema", [rItem(query, "query")], [rItem(answer, "answer")], note);
157
+ results.push({
158
+ bytes: answer,
159
+ used: used ?? new Set(),
160
+ accounted,
161
+ moves,
162
+ unexplained: unexplainedLabel(query, accounted),
163
+ });
164
+ };
165
+ ctx.trace?.step("alignStructures", [rItem(query, "query")], points.map((p) => rNode(ctx, p.anchor, "structure", p.vote)), "the independent learnt structures the query weaves, by graded alignment");
166
+ const lastRun = (p) => p.runs[p.runs.length - 1];
167
+ const qv = pre.guide;
168
+ // ── SUBSTITUTION ──────────────────────────────────────────────────
169
+ const fillerOf = (s) => {
170
+ const r = s.runs[0];
171
+ return r.cs < quantum
172
+ ? s.ctx.subarray(0, r.cs + (r.qe - r.qs))
173
+ : query.subarray(r.qs, r.qe);
174
+ };
175
+ const beforeOf = (p, r) => argmaxBy(points.filter((s) => s !== p && lastRun(s).qe <= r.qs &&
176
+ s.runs[0].cs < quantum &&
177
+ usable(s.runs[0].qs, s.runs[0].qe)), (s) => lastRun(s).qs, -Infinity, true)?.item;
178
+ const displacement = points
179
+ .map((p) => {
180
+ const r = p.runs[0];
181
+ if (r.cs < quantum || !usable(r.qs, r.qe)) {
182
+ return null;
183
+ }
184
+ const before = beforeOf(p, r);
185
+ if (before === undefined)
186
+ return null;
187
+ if (r.cs > fillerOf(before).length + quantum)
188
+ return null;
189
+ return { p, before, depth: p.ctx.length - r.cs };
190
+ })
191
+ .filter((c) => c !== null);
192
+ const picked = argmaxBy(displacement, (c) => c.depth, -Infinity, true);
193
+ const proj = picked?.item.p ?? null;
194
+ const subj = picked?.item.before ?? null;
195
+ if (proj !== null && subj !== null) {
196
+ const seat = proj.runs[0];
197
+ const filler = fillerOf(subj);
198
+ const tail = proj.ctx.subarray(seat.cs);
199
+ let answer = await joinWithBridge(ctx, filler, tail);
200
+ const fwd = await follow(ctx, proj.anchor, qv);
201
+ if (fwd !== null && indexOf(answer, fwd, 0) < 0) {
202
+ answer = concat2(answer, fwd);
203
+ }
204
+ ctx.trace?.step("projectCounterfactual", [
205
+ rItem(filler, "filler", subj.anchor),
206
+ rNode(ctx, proj.anchor, "displaced-structure"),
207
+ ], [rItem(answer, "projection")], "transfer the displaced structure onto the subject filler (seat substitution)");
208
+ record(answer, "counterfactual substitution — the subject fills the analog's seat", new Set([subj.anchor, proj.anchor]),
209
+ // The acts performed: one seat INSERT projection + one edge FOLLOW.
210
+ STEP + STEP,
211
+ // What substitution actually READ: the two points it transfers
212
+ // between — the subject filling the seat, and the displaced
213
+ // structure whose seat it fills — not every OTHER point the weave
214
+ // happened to align (a third, unrelated point in the same weave
215
+ // contributes nothing to what substitution itself explains).
216
+ [...runSpans(subj), ...runSpans(proj)]);
217
+ }
218
+ // ── REDIRECTION ────────────────────────────────────────────────────
219
+ const last = points.reduce((a, b) => lastRun(b).qs > lastRun(a).qs ? b : a);
220
+ // Displacement test, capped at the hub bound: a hub anchor can carry a
221
+ // corpus-sized fan-out, and each continuation costs a full byte
222
+ // reconstruction plus an O(|query|·|bytes|) scan. The first √N edges (the
223
+ // same insertion-order convention chooseNext caps by) decide; past a hub's
224
+ // cap the test reads "none of the established continuations appears".
225
+ const domNext = ctx.store.nextFirst(dominant.anchor, hubBound(ctx));
226
+ const displaced = domNext
227
+ .every((n) => indexOf(query, read(ctx, n), 0) < 0);
228
+ if (last !== dominant &&
229
+ last.runs[0].cs === 0 && displaced &&
230
+ usable(last.runs[0].qs, last.runs[0].qe)) {
231
+ const g = await project(ctx, last.anchor, qv);
232
+ if (g !== null) {
233
+ ctx.trace?.step("projectCounterfactual", [
234
+ rNode(ctx, dominant.anchor, "displaced-structure"),
235
+ rNode(ctx, last.anchor, "substitute"),
236
+ ], [rItem(g, "projection")], "the substitute's own fact replaces the displaced structure's answer");
237
+ record(g, "counterfactual redirection — the named substitute's fact is followed", new Set([dominant.anchor, last.anchor]),
238
+ // One forward projection across the substitute's own fact.
239
+ STEP,
240
+ // What redirection READ: the displaced structure's own recognized
241
+ // seat (still explained — this schema RECOGNIZES it as the slot
242
+ // being overridden, it just doesn't answer from it) plus the named
243
+ // substitute's own aligned run — not every OTHER point the weave
244
+ // happened to align.
245
+ [...runSpans(dominant), ...runSpans(last)]);
246
+ }
247
+ }
248
+ // ── COMPARISON ─────────────────────────────────────────────────────
249
+ // Collect every qualifying non-dominant point as a candidate analog.
250
+ // When a point's own anchor is structurally at the wrong level
251
+ // (e.g. a long exemplar sentence whose halo does not resemble the
252
+ // dominant's), its nextOf targets often point to the right level — the
253
+ // person / concept the exemplar is about. Trying both prevents a
254
+ // seed-dependent failure where the climb ranks an exemplar above a
255
+ // person node and the person node is excluded from points by run-
256
+ // overlap trimming.
257
+ // The seat that establishes a candidate's role: the REVERSE projection
258
+ // (the context it follows), voiced by the query gist — falling back to the
259
+ // candidate's own bytes when it follows nothing. DELIBERATE STRENGTHENING
260
+ // over the pre-refactor code: reverseContext also returns null when the
261
+ // picked context READS EMPTY (a dangling id degrades to zero bytes), so a
262
+ // corrupted-store read now falls back here instead of voicing a hollow
263
+ // seat into the comparison — the same "empty bytes are no grounding"
264
+ // invariant project() has always enforced.
265
+ const seatOfNode = (id, fallback) => reverseContext(ctx, id, qv) ?? fallback;
266
+ const seatOf = (p) => seatOfNode(p.anchor, p.ctx);
267
+ const analogs = [];
268
+ for (const p of points) {
269
+ if (p === dominant)
270
+ continue;
271
+ // Push the point's own anchor only when its context fits within
272
+ // the query (the seat sentence must not dominate the comparison).
273
+ if (p.ctx.length <= query.length &&
274
+ indexOf(dominant.ctx, p.ctx, 0) < 0 &&
275
+ indexOf(p.ctx, dominant.ctx, 0) < 0 &&
276
+ indexOf(query, p.ctx, 0) < 0) {
277
+ analogs.push({ anchor: p.anchor, point: p });
278
+ }
279
+ // Reach through to the point's continuation targets regardless
280
+ // of the point's own context length: when the point is a leaf
281
+ // (exemplar sentence), its nextOf is the hub (person / concept)
282
+ // that makes a genuine cross-domain analog, and the hub's own
283
+ // (shorter) context will be the seat.
284
+ // Capped like every fan-out: a hub anchor's full continuation list is
285
+ // corpus-sized, and each candidate costs a read plus O(|query|·|bytes|)
286
+ // scans — only the first √N (insertion order, the same convention
287
+ // chooseNext caps by) are reachable as analogs.
288
+ for (const nid of ctx.store.nextFirst(p.anchor, hubBound(ctx))) {
289
+ const nctx = read(ctx, nid);
290
+ if (nctx.length > query.length ||
291
+ indexOf(dominant.ctx, nctx, 0) >= 0 ||
292
+ indexOf(nctx, dominant.ctx, 0) >= 0 ||
293
+ indexOf(query, nctx, 0) >= 0)
294
+ continue;
295
+ analogs.push({ anchor: nid, point: null });
296
+ }
297
+ }
298
+ let bestAnalog = null;
299
+ let bestSim = 0;
300
+ for (const c of analogs) {
301
+ const sim = await analogyStrength(ctx, dominant.anchor, c.anchor);
302
+ ctx.trace?.step("tryAnalog", [
303
+ rNode(ctx, dominant.anchor, "dominant"),
304
+ rNode(ctx, c.anchor, "candidate", sim),
305
+ ], [], `analogy strength ${sim.toFixed(4)}`);
306
+ if (sim > bestSim) {
307
+ bestSim = sim;
308
+ bestAnalog = c;
309
+ }
310
+ }
311
+ // When every candidate fails the similarity gates (halo company — now
312
+ // deterministic signatures, see sema.ts — and the shared-frame tier),
313
+ // fall back to a candidate that is a genuine structural hub (edges in
314
+ // BOTH directions). A hub node — a person, concept, or category — is
315
+ // the kind of thing that makes sense to compare across domains. A leaf
316
+ // value (extracted span, terminal answer) has edges in at most one
317
+ // direction and comparing it would preempt the extraction pipeline,
318
+ // which is the right mechanism for those. A fallback comparison carries
319
+ // NO similarity evidence — it stays honest only because the grounding
320
+ // decider weighs it against mechanisms that explain more of the query
321
+ // (extraction accounts its whole located envelope; see extraction.ts).
322
+ //
323
+ // WHICH hub: not the first in `analogs` order — that order flows from the
324
+ // vote ranking, which flows from approximate resonance, which is seed-
325
+ // dependent. Pick by evidence instead: combined edge support (prevCount +
326
+ // fan-out), tie-broken by poured halo MASS (episode corroboration — the
327
+ // direct distributional evidence), then by LOWEST node id. The id order
328
+ // is a property of the corpus, not of the seed — but note ids are SIGNED:
329
+ // byte leaves occupy −256…−1, so "lowest id" is creation order only among
330
+ // multi-byte nodes and byte-value order among leaves. Either way it is
331
+ // deterministic, which is all the final tie-break must be.
332
+ if (bestAnalog === null && analogs.length > 0) {
333
+ let hubSupport = -1;
334
+ let hubMass = -1;
335
+ const fanClamp = hubBound(ctx) + 1;
336
+ for (const c of analogs) {
337
+ // Evidence clamped at the hub bound: beyond √N + 1 the exact fan-out
338
+ // no longer discriminates (every mega-hub ties at the clamp), and
339
+ // counting it exactly would require the corpus-sized read.
340
+ const fanOut = ctx.store.nextFirst(c.anchor, fanClamp).length;
341
+ if (fanOut === 0)
342
+ continue;
343
+ const support = ctx.store.prevCount(c.anchor);
344
+ if (support === 0)
345
+ continue;
346
+ const total = support + fanOut;
347
+ if (total < hubSupport)
348
+ continue;
349
+ const mass = ctx.store.haloMass(c.anchor);
350
+ if (total > hubSupport ||
351
+ mass > hubMass ||
352
+ (mass === hubMass && bestAnalog !== null &&
353
+ c.anchor < bestAnalog.anchor)) {
354
+ hubSupport = total;
355
+ hubMass = mass;
356
+ bestAnalog = c;
357
+ }
358
+ }
359
+ if (bestAnalog !== null) {
360
+ ctx.trace?.step("tryAnalog", [], [rNode(ctx, bestAnalog.anchor, "fallback", hubSupport)], "no candidate passed the similarity gates — using the best-supported structural hub");
361
+ }
362
+ }
363
+ ctx.trace?.step("tryAnalog", [], bestAnalog !== null ? [rNode(ctx, bestAnalog.anchor, "best", bestSim)] : [], bestAnalog !== null
364
+ ? `best analog with strength ${bestSim.toFixed(4)}`
365
+ : `no analog candidate passed (${analogs.length} checked)`);
366
+ // COMPARISON gate — analogical comparison seats the dominant against ONE
367
+ // analog, so it presupposes the query is ABOUT a single thing. When the
368
+ // consensus climb instead committed to MULTIPLE independent points of
369
+ // attention (`roots.length > 1`), the query names independent topics to
370
+ // FUSE — the reasoner's fuseAttention already combines them — not analogs
371
+ // to compare. Firing here would juxtapose two co-scaffolded but unrelated
372
+ // records (each sharing only the corpus preamble), out-accounting the
373
+ // honest thin multi-root grounding with a frame echo. Derived from the
374
+ // climb's own forest, never tuned; substitution/redirection stay
375
+ // unaffected — they orient around a displaced seat, not a whole-topic
376
+ // analogy.
377
+ if (bestAnalog !== null &&
378
+ dominant.ctx.length <= query.length &&
379
+ roots.length <= 1) {
380
+ ctx.trace?.step("validateAnalogy", [
381
+ rNode(ctx, dominant.anchor, "analog", bestSim),
382
+ rNode(ctx, bestAnalog.anchor, "analog", bestSim),
383
+ ], [], "the two structures keep distributional company beyond chance — genuine analogs");
384
+ const a = seatOf(dominant);
385
+ const b = bestAnalog.point !== null
386
+ ? seatOf(bestAnalog.point)
387
+ : seatOfNode(bestAnalog.anchor, read(ctx, bestAnalog.anchor));
388
+ const answer = await joinWithBridge(ctx, a, b);
389
+ record(answer, "analogical comparison — each analog voiced by the context that establishes its role", new Set([dominant.anchor, bestAnalog.anchor]),
390
+ // A halo-mediated act (the analogy gate) plus two seat projections.
391
+ CONCEPT + STEP + STEP,
392
+ // What comparison READ: the dominant's own aligned runs, plus the
393
+ // analog's aligned runs when it was itself an aligned point (a nextOf
394
+ // descendant was never aligned to the query directly, so it
395
+ // contributes no accounted span — its seat is graph-reached, not
396
+ // query-matched).
397
+ [
398
+ ...runSpans(dominant),
399
+ ...(bestAnalog.point !== null ? runSpans(bestAnalog.point) : []),
400
+ ]);
401
+ }
402
+ t?.done(results.map((r) => rItem(r.bytes, "answer")), results.length > 0
403
+ ? `${results.length} counterfactual schema(s) fired — the grounding decider weighs them`
404
+ : "no counterfactual weave — the ordinary pipeline decides");
405
+ return results;
406
+ }
407
+ export const castMechanism = {
408
+ name: "cast",
409
+ provenance: "cast",
410
+ async floor(_ctx, query, pre, worthRunning) {
411
+ const W = _ctx.space.maxGroup;
412
+ // Cheap checks first — no pre-computation needed.
413
+ if (query.length < 2 * W || _ctx.store.edgeSourceCount() === 0)
414
+ return null;
415
+ // CAST's floor, when it exists, is ALWAYS exactly 2*STEP — the climb and
416
+ // the weave only decide whether it exists (2*STEP) or not (null), they
417
+ // never tighten the number itself. So if 2*STEP already can't beat
418
+ // whatever incumbent has already won this response (cover runs first —
419
+ // see defaultMechanisms), no analysis can change the outcome: RETURN THE
420
+ // BOUND uninvested (still admissible) and let the pipeline's own check
421
+ // prune run() with the truthful "cannot beat incumbent" note. This is
422
+ // the SAME admissible-floor economy worthRunning applies to run(),
423
+ // applied to floor()'s own investment — uniformly, whatever mechanism
424
+ // supplied the incumbent (an extension's computed result is not
425
+ // special-cased; any sufficiently cheap incumbent prunes the same way).
426
+ if (!worthRunning(2 * STEP))
427
+ return 2 * STEP;
428
+ // Now first-touch the shared analyses (climb, then the weave built on
429
+ // it). If another mechanism already triggered either, this awaits the
430
+ // cached result; otherwise it's computed once here and reused in run().
431
+ if ((await pre.attention()).ranked.length < 2)
432
+ return null;
433
+ if ((await pre.weave()).points.length < 2)
434
+ return null;
435
+ return 2 * STEP;
436
+ },
437
+ async run(ctx, query, pre) {
438
+ const casts = await counterfactualTransfer(ctx, query, pre);
439
+ return casts.map((c) => ({
440
+ bytes: c.bytes,
441
+ accounted: c.accounted,
442
+ moves: c.moves,
443
+ used: c.used,
444
+ unexplained: c.unexplained,
445
+ }));
446
+ },
447
+ };
@@ -0,0 +1,24 @@
1
+ import type { MindContext } from "../types.js";
2
+ import type { PipelineMechanism, Precomputed } from "../pipeline-mechanism.js";
3
+ /** A join answer plus its elementary evidence for think's grounding decider:
4
+ * `accounted` — the query spans whose votes carried the two constraint
5
+ * streams; `moves` — the ladder cost of the acts performed (two constraint
6
+ * matches and one meet, STEP each). `used` carries the pair's exemplar
7
+ * anchors so the reasoning stage does not re-speak them. */
8
+ export interface JoinResult {
9
+ bytes: Uint8Array;
10
+ used: ReadonlySet<number>;
11
+ accounted: Array<[number, number]>;
12
+ moves: number;
13
+ /** A human-readable label for the query bytes the meet left unexplained —
14
+ * purely diagnostic, never priced. */
15
+ unexplained: string;
16
+ }
17
+ /** The main confluence entry point. Given a query, detect whether it weaves
18
+ * two or more INDEPENDENT constraints (ranked anchors supported by disjoint
19
+ * query spans), intersect the constraints' evidence by content-addressed
20
+ * identity, and return the discriminative content the streams share — the
21
+ * entity that satisfies all constraints at once. Null when the query is
22
+ * not conjunctive or nothing lies in the intersection. */
23
+ export declare function confluenceJoin(ctx: MindContext, query: Uint8Array, pre: Precomputed): Promise<JoinResult | null>;
24
+ export declare const confluenceMechanism: PipelineMechanism;