@hviana/sema 0.1.0

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