@hviana/sema 0.2.3 → 0.2.4

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 (45) hide show
  1. package/dist/src/mind/attention.d.ts +14 -2
  2. package/dist/src/mind/attention.js +54 -8
  3. package/dist/src/mind/bridge.d.ts +30 -0
  4. package/dist/src/mind/bridge.js +569 -0
  5. package/dist/src/mind/match.d.ts +15 -2
  6. package/dist/src/mind/match.js +3 -8
  7. package/dist/src/mind/mechanisms/cast.d.ts +54 -0
  8. package/dist/src/mind/mechanisms/cast.js +268 -37
  9. package/dist/src/mind/mechanisms/cover.js +16 -31
  10. package/dist/src/mind/mechanisms/recall.js +66 -0
  11. package/dist/src/mind/reasoning.d.ts +11 -0
  12. package/dist/src/mind/reasoning.js +58 -2
  13. package/dist/src/mind/recognition.js +127 -7
  14. package/dist/src/mind/traverse.js +16 -15
  15. package/dist/src/mind/types.d.ts +39 -2
  16. package/dist/src/mind/types.js +38 -7
  17. package/dist/src/store.d.ts +12 -3
  18. package/dist/src/store.js +9 -3
  19. package/package.json +1 -1
  20. package/src/mind/attention.ts +65 -7
  21. package/src/mind/bridge.ts +596 -0
  22. package/src/mind/match.ts +19 -5
  23. package/src/mind/mechanisms/cast.ts +290 -38
  24. package/src/mind/mechanisms/cover.ts +23 -36
  25. package/src/mind/mechanisms/recall.ts +79 -0
  26. package/src/mind/reasoning.ts +71 -2
  27. package/src/mind/recognition.ts +132 -7
  28. package/src/mind/traverse.ts +16 -17
  29. package/src/mind/types.ts +70 -6
  30. package/src/store.ts +19 -5
  31. package/test/36-already-answered-fusion.test.mjs +128 -0
  32. package/test/37-cluster-dispersion-fusion.test.mjs +190 -0
  33. package/test/38-reason-restate-guard.test.mjs +94 -0
  34. package/test/39-cast-restate-guard.test.mjs +102 -0
  35. package/test/40-choosenext-scale-guard.test.mjs +75 -0
  36. package/test/41-seatofnode-direction.test.mjs +85 -0
  37. package/test/42-recognise-trace-idempotence.test.mjs +106 -0
  38. package/test/43-cast-analog-seat.test.mjs +244 -0
  39. package/test/44-recognise-edge-whitespace.test.mjs +63 -0
  40. package/test/45-liftanswer-restated-trim.test.mjs +60 -0
  41. package/test/46-recognise-multibyte-edge.test.mjs +85 -0
  42. package/test/47-cast-comparison-coverage.test.mjs +134 -0
  43. package/test/48-recognise-turn-connective.test.mjs +125 -0
  44. package/test/49-natural-units-synonym-bridge.test.mjs +175 -0
  45. package/test/50-cast-analog-consensus-floor.test.mjs +179 -0
@@ -12,8 +12,9 @@
12
12
  // juxtapose.
13
13
 
14
14
  import type { MindContext } from "../types.js";
15
+ import type { Vec } from "../../vec.js";
15
16
  import { read } from "../primitives.js";
16
- import { argmaxBy, hubBound } from "../traverse.js";
17
+ import { argmaxBy, corpusN, hubBound } from "../traverse.js";
17
18
  import {
18
19
  analogyStrength,
19
20
  follow,
@@ -22,11 +23,17 @@ import {
22
23
  reverseContext,
23
24
  } from "../match.js";
24
25
  import { joinWithBridge } from "../resonance.js";
26
+ import { restatesQuery } from "../reasoning.js";
25
27
  import { CONCEPT, STEP } from "../graph-search.js";
26
28
  import { concat2, indexOf } from "../../bytes.js";
27
- import { dominates } from "../../geometry.js";
28
- import { decodeText, unexplainedLabel } from "../rationale.js";
29
+ import { consensusFloor, dominates } from "../../geometry.js";
30
+ import {
31
+ decodeText,
32
+ unexplainedLabel,
33
+ unexplainedSpans,
34
+ } from "../rationale.js";
29
35
  import { rItem, rNode } from "../trace.js";
36
+ import { dismissedKnownContent } from "../bridge.js";
30
37
 
31
38
  // ── CAST gates ────────────────────────────────────────────────────────────
32
39
  //
@@ -80,6 +87,85 @@ export interface CastResult {
80
87
  unexplained: string;
81
88
  }
82
89
 
90
+ /** The seat that establishes a node's role in an analogical comparison:
91
+ * the REVERSE context (what leads to it) when a predecessor genuinely
92
+ * ESTABLISHES id — introduces or describes it by name — else the FORWARD
93
+ * continuation (what it leads to), else `fallback`.
94
+ *
95
+ * An earlier version gated this purely on `prevCount(id) > 0`: any
96
+ * predecessor at all was treated as proof of a genuine named ENTITY
97
+ * (seat it by what established it), while no predecessor meant a bare
98
+ * learnt CONTEXT (seat it by what it leads to, since voicing it verbatim
99
+ * would answer a question with a question). That test measured the wrong
100
+ * thing — a broad sample of this store's own question-shaped nodes showed
101
+ * the large majority (≈71%) have at least one predecessor, most of them a
102
+ * handful of generic, high-fan-out sentences that recur as an INCIDENTAL
103
+ * neighbour to dozens of otherwise-unrelated destinations (a SmolSent-
104
+ * style sentence-adjacency artifact, never naming or describing what
105
+ * follows). Traced live: "What is the capital of France?" — whose own
106
+ * forward edge unambiguously resolves to "The capital of France is
107
+ * Paris." — has exactly one such incidental predecessor ("Create an
108
+ * example of a types of questions a GPT model can answer.?"), wrongly
109
+ * read as disqualifying proof of "genuine entity."
110
+ *
111
+ * A plain forward-first swap (matching {@link project}'s universal
112
+ * priority) over-corrected: test/29's C2/C3 pin that a genuine entity
113
+ * analog (e.g. "Leonardo da Vinci", established by "The Mona Lisa was
114
+ * painted by Leonardo da Vinci.") must be seated by that establishing
115
+ * sentence, NOT by its own biography fact — voicing the bio leaks exactly
116
+ * what a comparison must keep out, and loses the embedded "Mona Lisa"
117
+ * term C3 relies on for a further hop.
118
+ *
119
+ * The distinguishing signal is content-addressed, not a count: a genuine
120
+ * establishing predecessor's bytes CONTAIN id's own bytes — it names or
121
+ * describes id ("...painted by Leonardo da Vinci." contains "Leonardo da
122
+ * Vinci"). An incidental adjacency predecessor never does — it merely
123
+ * preceded id in some unrelated document without ever mentioning it. No
124
+ * new tuned constant: containment is the same primitive `restatesQuery`
125
+ * and `dominates`-style checks already use throughout this codebase.
126
+ *
127
+ * `allowForward` (default true) gates the FORWARD branch specifically —
128
+ * see the call sites below: the DOMINANT is what the query is actually
129
+ * ASKING, so completing it forward is the whole point; an ANALOG is only
130
+ * being CITED for comparison; the query never asked about IT, so chasing
131
+ * its own further continuation drifts onto whatever coincidentally
132
+ * follows it in the corpus. Traced live: the analog "What is the capital
133
+ * of Japan?\nTokyo is the capital of Japan." is ALREADY a complete,
134
+ * self-answering unit (prevCount 0, so no establishing predecessor
135
+ * either) — its sole forward edge is "And what is the capital of the
136
+ * Moon?", an unrelated quiz question sharing nothing but corpus
137
+ * adjacency. With forward disallowed, an analog like this falls through
138
+ * to `fallback` — its own bytes, exactly the complete fact that made it a
139
+ * genuine analog in the first place. See
140
+ * test/41-seatofnode-direction.test.mjs and
141
+ * test/43-cast-analog-seat.test.mjs. */
142
+ export async function seatOfNode(
143
+ ctx: MindContext,
144
+ id: number,
145
+ guide: Vec | null | undefined,
146
+ fallback: Uint8Array,
147
+ allowForward = true,
148
+ ): Promise<Uint8Array> {
149
+ const rev = ctx.store.prevFirst(id, hubBound(ctx));
150
+ if (rev.length > 0) {
151
+ const own = read(ctx, id);
152
+ const establishing = rev.some((p) => indexOf(read(ctx, p), own, 0) >= 0);
153
+ if (establishing) {
154
+ const back = reverseContext(ctx, id, guide, rev);
155
+ if (back !== null) return back;
156
+ }
157
+ }
158
+ // The "last resort, non-establishing reverse" fallback below is itself a
159
+ // LESS CERTAIN projection (the same tier as forward) — an analog
160
+ // (allowForward: false) must stop at `fallback` (its own bytes) here
161
+ // rather than fall back to a predecessor that already failed the
162
+ // establishing check just above.
163
+ if (!allowForward) return fallback;
164
+ const fwd = await follow(ctx, id, guide);
165
+ if (fwd !== null) return fwd;
166
+ return reverseContext(ctx, id, guide, rev) ?? fallback;
167
+ }
168
+
83
169
  /** CAST's own entry gates, checked once here and reused by
84
170
  /** The main CAST entry point. Given a query and its pre-computed pre.rec.sites,
85
171
  * determine whether the query weaves together multiple independent learnt
@@ -297,7 +383,10 @@ export async function counterfactualTransfer(
297
383
  const tail = proj.ctx.subarray(seat.cs);
298
384
  let answer = await joinWithBridge(ctx, filler, tail);
299
385
  const fwd = await follow(ctx, proj.anchor, qv);
300
- if (fwd !== null && indexOf(answer, fwd, 0) < 0) {
386
+ if (
387
+ fwd !== null && indexOf(answer, fwd, 0) < 0 &&
388
+ !restatesQuery(query, fwd)
389
+ ) {
301
390
  answer = concat2(answer, fwd);
302
391
  }
303
392
  ctx.trace?.step(
@@ -375,36 +464,14 @@ export async function counterfactualTransfer(
375
464
  // seed-dependent failure where the climb ranks an exemplar above a
376
465
  // person node and the person node is excluded from points by run-
377
466
  // overlap trimming.
378
- // The seat that establishes a candidate's role: the REVERSE projection
379
- // (the context it follows), voiced by the query gist — falling back to the
380
- // candidate's own bytes when it follows nothing. DELIBERATE STRENGTHENING
381
- // over the pre-refactor code: reverseContext also returns null when the
382
- // picked context READS EMPTY (a dangling id degrades to zero bytes), so a
383
- // corrupted-store read now falls back here instead of voicing a hollow
384
- // seat into the comparison — the same "empty bytes are no grounding"
385
- // invariant project() has always enforced.
386
- // A node that only ever CONTINUES — an edge SOURCE with no predecessor —
387
- // is a learnt CONTEXT (a stored question-shaped frame), not an entity.
388
- // Voicing it verbatim answers a question with a question (the observed
389
- // cast echo: two stored questions concatenated as an "answer"). The
390
- // context's role is established by what it LEADS TO, so its seat is its
391
- // own continuation — the fact — with the reverse projection and the raw
392
- // bytes as the ordinary fallbacks for genuine entities.
393
- const seatOfNode = async (
394
- id: number,
395
- fallback: Uint8Array,
396
- ): Promise<Uint8Array> => {
397
- if (ctx.store.prevCount(id) === 0 && ctx.store.hasNext(id)) {
398
- const fwd = await follow(ctx, id, qv);
399
- if (fwd !== null) return fwd;
400
- }
401
- return reverseContext(ctx, id, qv) ?? fallback;
402
- };
403
- const seatOf = (p: Point): Promise<Uint8Array> => seatOfNode(p.anchor, p.ctx);
467
+ // The seat that establishes a candidate's role see {@link seatOfNode}.
468
+ const seatOf = (p: Point, allowForward = true): Promise<Uint8Array> =>
469
+ seatOfNode(ctx, p.anchor, qv, p.ctx, allowForward);
404
470
  interface AnalogCandidate {
405
471
  anchor: number;
406
472
  /** The point this candidate came from, or null when it is a nextOf
407
- * descendant — then seatOfNode supplies the seat. */
473
+ * descendant — then its own bytes ARE the seat (already one meaningful
474
+ * hop from `src`; see the comparison gate below). */
408
475
  point: Point | null;
409
476
  /** For a nextOf descendant: the aligned point whose continuation edge
410
477
  * named it. Its runs ARE the query evidence this analog rests on
@@ -447,8 +514,46 @@ export async function counterfactualTransfer(
447
514
  }
448
515
  let bestAnalog: AnalogCandidate | null = null;
449
516
  let bestSim = 0;
517
+ let bestHalo = false;
518
+ // Whether the query itself NAMES a candidate. A directly aligned point
519
+ // is named by construction — its runs ARE query bytes. A hop-reached
520
+ // candidate is named when its own bytes contain the query text of an
521
+ // aligned run of the point whose continuation edge reached it (that
522
+ // alignment IS the query evidence the hop rests on — the same reading
523
+ // cmpAccounted already prices): "William Shakespeare", reached off
524
+ // "Macbeth was written by William Shakespeare.", contains the src's
525
+ // 12-byte aligned run " Shakespeare" — test/29 C2/C3. The run must span
526
+ // at least TWO perception windows (2·W, the same two-quantum floor
527
+ // CAST's own entry gate holds the whole query to): a single shared
528
+ // W-window is exactly the frame tier's own evidence quantum — the level
529
+ // "half the corpus" shares — and stopword scraps (" the ", "he b",
530
+ // 4–5 bytes) never reach two windows, while a genuinely named entity
531
+ // does. NOT the weave's usable()/frame filter: weave depth counts every
532
+ // ranked exemplar, so a query's own named entity recurring across
533
+ // exemplars ("Shakespeare" in Hamlet+Macbeth+…) is wrongly classified as
534
+ // frame — measured live, it silently disqualified C3's genuine analog.
535
+ const namedByQuery = (c: AnalogCandidate): boolean => {
536
+ if (c.point !== null) return true;
537
+ const bytes = read(ctx, c.anchor);
538
+ return c.src.runs.some((r) =>
539
+ r.qe - r.qs >= 2 * quantum &&
540
+ indexOf(bytes, query.subarray(r.qs, r.qe), 0) >= 0
541
+ );
542
+ };
543
+ // Whether any committed root's consensus vote clears the SAME trust bar
544
+ // recallByResonance applies before grounding through a climb root:
545
+ // consensusFloor(N) = ln(N) + 1/2. The climb's FIRST root is
546
+ // deliberately floor-free (attention.ts: "the dominant one always
547
+ // grounds") — fine for ORIENTING mechanisms, not for voicing learnt
548
+ // content the query never asked about. Computed once here; both the
549
+ // hub fallback below and the comparison gate consume it.
550
+ const rootTrusted = roots.some((r) => r.vote >= consensusFloor(corpusN(ctx)));
450
551
  for (const c of analogs) {
451
- const sim = await analogyStrength(ctx, dominant.anchor, c.anchor);
552
+ const { score: sim, halo } = await analogyStrength(
553
+ ctx,
554
+ dominant.anchor,
555
+ c.anchor,
556
+ );
452
557
  ctx.trace?.step(
453
558
  "tryAnalog",
454
559
  [
@@ -456,11 +561,12 @@ export async function counterfactualTransfer(
456
561
  rNode(ctx, c.anchor, "candidate", sim),
457
562
  ],
458
563
  [],
459
- `analogy strength ${sim.toFixed(4)}`,
564
+ `analogy strength ${sim.toFixed(4)}${halo ? " (halo tier)" : ""}`,
460
565
  );
461
566
  if (sim > bestSim) {
462
567
  bestSim = sim;
463
568
  bestAnalog = c;
569
+ bestHalo = halo;
464
570
  }
465
571
  }
466
572
  // When every candidate fails the similarity gates (halo company — now
@@ -489,6 +595,17 @@ export async function counterfactualTransfer(
489
595
  let hubMass = -1;
490
596
  const fanClamp = hubBound(ctx) + 1;
491
597
  for (const c of analogs) {
598
+ // A fallback comparison carries NO similarity evidence at all. Its
599
+ // honesty rests on the grounding decider discounting it against
600
+ // richer candidates (the design note below) — an assumption that
601
+ // holds only when the climb itself settled on this query with real
602
+ // evidence. Under a root the consensus floor does not trust, an
603
+ // unnamed, hop-reached hub is pure corpus adjacency: refusing it is
604
+ // what kept the live wrong echo silent. A hub the query itself
605
+ // NAMED stays eligible either way (test/29 C2/C3's "William
606
+ // Shakespeare"); an unnamed one under a TRUSTED root stays eligible
607
+ // too (test/33 1b's deliberately weak second candidate).
608
+ if (!rootTrusted && !namedByQuery(c)) continue;
492
609
  // Evidence clamped at the hub bound: beyond √N + 1 the exact fan-out
493
610
  // no longer discriminates (every mega-hub ties at the clamp), and
494
611
  // counting it exactly would require the corpus-sized read.
@@ -538,10 +655,111 @@ export async function counterfactualTransfer(
538
655
  // climb's own forest, never tuned; substitution/redirection stay
539
656
  // unaffected — they orient around a displaced seat, not a whole-topic
540
657
  // analogy.
658
+ //
659
+ // roots.length <= 1 is a PROXY for "the query is about one thing" — it is
660
+ // only as good as the climb's own root-commitment, which depends on
661
+ // recognise() having found something to commit a root TO. When the
662
+ // query's newest content genuinely isn't recognised (not boundary noise —
663
+ // real, uncommitted content; see the session's own investigation of the
664
+ // France→Spain live trace), the climb under-commits roots and this proxy
665
+ // is fooled: comparison looks licensed to treat the query as one topic
666
+ // when it is not.
667
+ //
668
+ // The direct check is the SAME accounted spans comparison is about to
669
+ // cite as its evidence: unexplainedSpans (rationale.ts, the same gap
670
+ // computation the trace's own `unexplained` diagnostic uses) names every
671
+ // stretch of the query NEITHER the dominant NOR the analog's evidence
672
+ // touches. A short comparison query ("How is ice like steel?") legitimately
673
+ // accounts for only its two short entity spans — the surrounding "How is
674
+ // ... like ...?" framing is real but SHORT, split into several small gaps,
675
+ // none of them the bulk of the query. The live bug's shape is different in
676
+ // kind, not degree: ONE contiguous, substantial gap — a whole second
677
+ // question the query added that comparison's two spans never touch at all.
678
+ //
679
+ // Two bars, both derived, neither tuned:
680
+ // • the largest gap must not DOMINATE the whole query (the same
681
+ // predicate CAST's own frame gate uses) — rules out a gap that is
682
+ // most of the query outright;
683
+ // • the largest gap must be SMALLER than the dominant's own established
684
+ // context. A gap can't be dismissed as mere connective framing once
685
+ // it is at least as large as the topic being compared FROM — at that
686
+ // scale it isn't glue between two named things, it's substantial
687
+ // enough to be a second topic in its own right. This is what
688
+ // actually separates the live bug (a 47-byte gap against a 30-byte
689
+ // dominant — the ignored content is bigger than the topic itself)
690
+ // from ordinary short comparisons (a 9-byte gap against an 11-byte
691
+ // dominant — the gap is smaller than what's being compared): the two
692
+ // cases land on the same side of "half the query" often enough
693
+ // (both can exceed or clear it) that the query-relative bar alone
694
+ // does not reliably separate them — the topic-relative scale does.
695
+ const cmpAccounted: Array<[number, number]> = bestAnalog !== null
696
+ ? [...runSpans(dominant), ...runSpans(bestAnalog.point ?? bestAnalog.src)]
697
+ : [];
698
+ const cmpGaps = unexplainedSpans(query.length, cmpAccounted);
699
+ const cmpMaxGap = cmpGaps.reduce((n, [s, e]) => Math.max(n, e - s), 0);
700
+ // An analog that is not itself a directly ALIGNED point (point !== null —
701
+ // its own runs are query bytes, the query NAMED it) was only reached
702
+ // through a continuation hop or the structural-hub fallback. Voicing
703
+ // learnt content the query never named is the same act recallByResonance
704
+ // refuses to perform through a climb root whose consensus vote is below
705
+ // consensusFloor(N) = ln(N) + 1/2 (recall.ts's minVote), so comparison
706
+ // holds the climb to that SAME bar before citing a hop-reached analog:
707
+ // some committed root must clear the floor. The climb's FIRST root is
708
+ // deliberately floor-free (attention.ts: "the dominant one always
709
+ // grounds") — fine for ORIENTING mechanisms, not for transferring
710
+ // unnamed content through. The live bug this gates (real trained store,
711
+ // 325k edge sources, floor 13.2): the query's stopword scraps pooled a
712
+ // 1.92 vote that committed an unrelated haiku exemplar as the sole root,
713
+ // and comparison voiced that exemplar's continuation through a
714
+ // hop-reached analog while every other mechanism honestly refused. A
715
+ // directly aligned analog needs no floor — the query's own bytes are its
716
+ // evidence (test/29 C1's "Steel is hard" for "How is ice like steel?").
717
+ // See test/50-cast-analog-consensus-floor.
718
+ // A HALO-tier best analog needs neither: its similarity already cleared
719
+ // significanceBar-gated distributional company (analogyStrength's
720
+ // `halo`) — genuine evidence in its own right, the very case the halo
721
+ // gate exists for (test/33 1b's nickname-corroborated analog). Only a
722
+ // FRAME-tier or fallback analog — whose "similarity" is an unbarred
723
+ // coverage fraction or nothing — needs the query's naming or the climb's
724
+ // trust.
725
+ const analogNamed = bestAnalog !== null && namedByQuery(bestAnalog);
726
+ // NOTE — two further gates were tried here and empirically REFUTED,
727
+ // recorded so they are not re-tried:
728
+ // • dominant self-coverage (dominant's aligned runs must dominate its
729
+ // own ctx): legitimate dominants sit at the same coverage as junk
730
+ // ones ("The Mona Lisa was painted by…" 16/47 vs the live junk
731
+ // haiku ~10/54) — no separation.
732
+ // • denying the shared-frame similarity tier to hop-reached analogs:
733
+ // semantically right in isolation, but it merely promoted the next
734
+ // junk candidate — an ALIGNED scrap-matched point ("The affluence…",
735
+ // frame 0.157) — into bestAnalog on the live store, and the aligned
736
+ // configuration is byte-structurally IDENTICAL to test/29 C1's
737
+ // legitimate one ("Steel is hard", frame 0.364): every derived
738
+ // local separator measured (run length, site overlap, frame
739
+ // query-containment, weave-usable classification) falls on the same
740
+ // side for both. Only corpus-scale consensus separates them, which
741
+ // is exactly what `rootTrusted` prices.
742
+ // FRAME-tier evidence under an UNTRUSTED root is comparison's weakest
743
+ // licence (an unbarred coverage fraction, a climb the consensus floor
744
+ // does not trust). There it is additionally held to the IGNORED-KNOWN
745
+ // principle (dismissedKnownContent, bridge.ts): the two analogs' aligned
746
+ // runs must account for every STORED window of the query. This is the
747
+ // byte-structural separator the refuted-gates note below could not find
748
+ // locally: a legitimate small-corpus comparison ("How is ice like
749
+ // steel?") leaves only UNATTESTED spans ("How ", " like ") unexplained,
750
+ // while a scrap-matched junk pair leaves the query's own trained content
751
+ // ("…songs…times…", "…planet…sun.") dismissed as gaps. Halo-tier and
752
+ // trusted-root comparisons are exempt — their evidence already stands.
753
+ const cmpDismisses = !(bestHalo || rootTrusted) &&
754
+ dismissedKnownContent(ctx, query, cmpAccounted);
541
755
  if (
542
756
  bestAnalog !== null &&
757
+ (bestHalo || analogNamed || rootTrusted) &&
758
+ !cmpDismisses &&
543
759
  dominant.ctx.length <= query.length &&
544
- roots.length <= 1
760
+ roots.length <= 1 &&
761
+ !dominates(cmpMaxGap, query.length) &&
762
+ cmpMaxGap < dominant.ctx.length
545
763
  ) {
546
764
  ctx.trace?.step(
547
765
  "validateAnalogy",
@@ -553,9 +771,21 @@ export async function counterfactualTransfer(
553
771
  "the two structures keep distributional company beyond chance — genuine analogs",
554
772
  );
555
773
  const a = await seatOf(dominant);
774
+ // The analog is only being CITED for comparison — the query never asked
775
+ // about it — so its seat never chases a FORWARD continuation (see
776
+ // seatOfNode's `allowForward`): only reverse (if a predecessor genuinely
777
+ // establishes it) or its own bytes. A DIRECTLY aligned point
778
+ // (bestAnalog.point !== null) still goes through seatOfNode for that
779
+ // reverse check (a bare entity NAME like "Leonardo da Vinci" needs it —
780
+ // test/29's C2/C3). A nextOf DESCENDANT (point === null) was already
781
+ // reached by following ONE meaningful hop off another aligned point (the
782
+ // alignment loop above: "its nextOf is the hub... and the hub's own
783
+ // [...] context will be the seat") — its own bytes ARE that seat
784
+ // directly, with no predecessor to even check (it was found by a
785
+ // forward edge, not matched in the query).
556
786
  const b = bestAnalog.point !== null
557
- ? await seatOf(bestAnalog.point)
558
- : await seatOfNode(bestAnalog.anchor, read(ctx, bestAnalog.anchor));
787
+ ? await seatOf(bestAnalog.point, false)
788
+ : read(ctx, bestAnalog.anchor);
559
789
  const answer = await joinWithBridge(ctx, a, b);
560
790
  record(
561
791
  answer,
@@ -568,10 +798,32 @@ export async function counterfactualTransfer(
568
798
  // when it was an aligned point, else the source point whose
569
799
  // continuation edge reached it (that alignment IS the query evidence
570
800
  // the hop rests on).
801
+ cmpAccounted,
802
+ );
803
+ } else if (
804
+ bestAnalog !== null &&
805
+ dominant.ctx.length <= query.length &&
806
+ roots.length <= 1
807
+ ) {
808
+ ctx.trace?.step(
809
+ "validateAnalogy",
571
810
  [
572
- ...runSpans(dominant),
573
- ...runSpans(bestAnalog.point ?? bestAnalog.src),
811
+ rNode(ctx, dominant.anchor, "analog", bestSim),
812
+ rNode(ctx, bestAnalog.anchor, "analog", bestSim),
574
813
  ],
814
+ [],
815
+ !(bestHalo || analogNamed || rootTrusted)
816
+ ? `the best analog carries no halo-tier company evidence, was never ` +
817
+ `named by the query, and no committed root's consensus vote ` +
818
+ `clears the floor, so comparison refuses to voice it`
819
+ : cmpDismisses
820
+ ? `a frame-tier analog under an untrusted root dismisses stored ` +
821
+ `query content its alignment never accounted for — comparison ` +
822
+ `refuses to ignore what the store knows`
823
+ : `comparison's own accounted evidence leaves a ${cmpMaxGap}-byte gap in ` +
824
+ `a ${query.length}-byte query against a ${dominant.ctx.length}-byte ` +
825
+ `dominant — too large to be mere framing — so it refuses rather ` +
826
+ `than paper over it with an analog the query never asked about`,
575
827
  );
576
828
  }
577
829
  t?.done(
@@ -11,12 +11,11 @@
11
11
 
12
12
  import type { MindContext } from "../types.js";
13
13
  import type { ComputedResult, Site } from "../graph-search.js";
14
- import { bytesEqual, indexOf } from "../../bytes.js";
15
14
  import { read, resolve } from "../primitives.js";
16
15
  import { guidedFirst } from "../traverse.js";
17
16
  import { conceptHop } from "../match.js";
18
17
  import { bridge } from "../resonance.js";
19
- import { liftAnswer } from "../types.js";
18
+ import { liftAnswer, segRestatesQuery } from "../types.js";
20
19
  import { decodeText, unexplainedLabel } from "../rationale.js";
21
20
  import type { RationaleItem } from "../rationale.js";
22
21
  import { rItem, rNode, traceDerivation } from "../trace.js";
@@ -226,44 +225,31 @@ export const coverMechanism: PipelineMechanism = {
226
225
 
227
226
  if (segs === null) return [];
228
227
 
228
+ const W = ctx.space.maxGroup;
229
229
  // A chosen span's SUBSTITUTED bytes (an edge followed from a recognised
230
230
  // site, not the site's own literal text read back) that equal a byte
231
231
  // span the query ALREADY CONTAINS elsewhere restates part of the
232
- // question — never an answer (the same principle recall.ts's tiers
233
- // apply to a whole-query projection: "a projection that is a proper
234
- // byte-subspan of the query restates part of the question"). A
232
+ // question — never an answer (see {@link segRestatesQuery}). A
235
233
  // recognised site that is itself an entire PRIOR TURN of a multi-turn
236
234
  // query is exactly this shape: it carries a genuine learnt
237
235
  // continuation, but that continuation is something the asker already
238
- // said moments later in the SAME query, not a new answer — the cover
239
- // search has no notion of "turn" to gate this itself, so the check
240
- // belongs here, over the derivation it already chose.
241
- const W = ctx.space.maxGroup;
242
- for (const s of segs) {
243
- if (!s.rec) continue;
244
- const literal = s.j - s.i === s.bytes.length &&
245
- bytesEqual(s.bytes, query.subarray(s.i, s.j));
246
- if (literal) continue;
247
- // A span shorter than one river window is exactly the "ice"/"c"
248
- // case: a chain hop's short terminal coincidentally recurring as a
249
- // substring of an unrelated longer word. Below the quantum, byte
250
- // overlap is chance, not evidence — the same floor identityBar and
251
- // reachThreshold hold every other structural-overlap claim to.
252
- if (
253
- s.bytes.length >= W && s.bytes.length < query.length &&
254
- indexOf(query, s.bytes, 0) >= 0
255
- ) {
256
- ctx.trace?.step(
257
- "restatedSpan",
258
- [rItem(s.bytes, "substituted", s.node, [s.i, s.j])],
259
- [],
260
- "the chosen span's substitution already occurs elsewhere in the query — restates it, not an answer",
261
- );
262
- return [];
263
- }
236
+ // said moments later in the SAME query. liftAnswer TRIMS such spans
237
+ // out of both the framing decision and the final concatenation the
238
+ // OTHER spans a derivation chose are independent evidence and must not
239
+ // be discarded along with the stale one.
240
+ const restated = segs.filter((s) =>
241
+ segRestatesQuery(s, query, query.length, W)
242
+ );
243
+ if (restated.length > 0) {
244
+ ctx.trace?.step(
245
+ "restatedSpan",
246
+ restated.map((s) => rItem(s.bytes, "substituted", s.node, [s.i, s.j])),
247
+ [],
248
+ "the chosen span's substitution already occurs elsewhere in the query trimmed from the answer, not an answer itself",
249
+ );
264
250
  }
265
251
 
266
- const composed = liftAnswer(segs, query.length);
252
+ const composed = liftAnswer(segs, query.length, query, W);
267
253
  if (composed === null) return [];
268
254
 
269
255
  ctx.trace?.step(
@@ -276,11 +262,12 @@ export const coverMechanism: PipelineMechanism = {
276
262
  tCover ? [tCover.index] : undefined,
277
263
  );
278
264
 
279
- // accounted = RECOGNISED cover spans only — PASS-carried bytes
280
- // are priced in cost already; the diagnostic label reflects the
281
- // same distinction.
265
+ // accounted = RECOGNISED, non-restating cover spans only — a trimmed
266
+ // restated span contributes nothing to the composed answer, so it must
267
+ // not be priced as if it did (PASS-carried bytes are priced already;
268
+ // the diagnostic label reflects the same distinction).
282
269
  const accounted: Array<[number, number]> = segs
283
- .filter((s) => s.rec)
270
+ .filter((s) => s.rec && !segRestatesQuery(s, query, query.length, W))
284
271
  .map((s) => [s.i, s.j]);
285
272
 
286
273
  return [{
@@ -20,6 +20,7 @@ import { CONCEPT, STEP } from "../graph-search.js";
20
20
  import { unexplainedLabel } from "../rationale.js";
21
21
  import type { PipelineMechanism, Precomputed } from "../pipeline-mechanism.js";
22
22
  import { rItem, rNode } from "../trace.js";
23
+ import { substitutionBridge } from "../bridge.js";
23
24
 
24
25
  /** A recall result. */
25
26
  export interface RecallResult {
@@ -293,6 +294,84 @@ export async function recallByResonance(
293
294
  }
294
295
  }
295
296
  }
297
+ // 3b. Corroborated-substitution bridge — refusal-path only (bridge.ts).
298
+ // Every gist-based tier has failed; before refusing, align the query
299
+ // byte-for-byte against the trained contexts its own stored windows
300
+ // anchor, accepting mismatches only as corpus-attested, concept-bar
301
+ // substitutions. A bridged context grounds exactly like any hit —
302
+ // projected through its learnt edges — under the same restated-fragment
303
+ // guard tiers 0b/2 apply. Costs nothing on any answering path.
304
+ {
305
+ // The resonance hits already ranked above are handed to the bridge as
306
+ // PROPOSED candidates alongside its own anchor climbs: on a corpus this
307
+ // size a W-byte window is far too common for the clamped climb to
308
+ // single out the right trained context, while the whole-query gist
309
+ // already ranked it nearest (observed live: "what is the capital of
310
+ // france" resonating straight to "What is the capital of France?" yet
311
+ // refusing on the reach bar). Approximate scores propose; the bridge's
312
+ // byte-exact alignment and attestation gates decide.
313
+ //
314
+ // The proposal breadth here is widened PAST `k` — first by requesting
315
+ // hubBound(ctx) candidates instead of `k` (recall's own tiers above
316
+ // stay at `k`; this re-resonates only on the refusal path, exactly
317
+ // where the bridge itself already runs), AND by asking the index to
318
+ // search EXHAUSTIVELY. Both matter: the IVF only ever probes
319
+ // ⌈√clusters⌉ of them (store.ts's efFor) REGARDLESS of k — widening k
320
+ // alone just returns more hits from the SAME already-probed clusters,
321
+ // never a hit whose vector lives in an unprobed one. Measured live:
322
+ // "What is the chemical symbol for water?" needs "What is the
323
+ // chemical formula for water?", scoring only 0.58 against the
324
+ // query's gist (a MIDDLE-of-string word swap perturbs the river-fold
325
+ // tree hash far more than a same-length TAIL swap like the "carbon"/
326
+ // "oxygen" neighbours that outrank it at 0.87+) — absent from the
327
+ // resonance list even at k=5000, present and byte-exact-verified the
328
+ // moment it's force-fed to the bridge directly. `exhaustive` is the
329
+ // natural, tuning-free ceiling (probe every cluster) for a call that
330
+ // is ALREADY refusal-path-only and must not miss a candidate hiding
331
+ // behind an unlucky structural distance.
332
+ const wide = k < hubBound(ctx)
333
+ ? await ctx.store.resonate(queryGist, hubBound(ctx), true)
334
+ : whole;
335
+ const bridged = await substitutionBridge(
336
+ ctx,
337
+ query,
338
+ wide.map((h) => h.id),
339
+ );
340
+ if (bridged !== null) {
341
+ const g = await project(ctx, bridged.id, queryGist);
342
+ // A projection contained in a substituted candidate-side span is the
343
+ // substitution RESTATED as if it were knowledge — the exact failure
344
+ // observed live: "Darwin was born in England." bridged to the
345
+ // Einstein fact through " England." → " Germany." and would have
346
+ // voiced "Germany", an answer the substitution itself manufactured.
347
+ // The same principle as the restated-fragment guards above, extended
348
+ // to the bridge's own substitutions.
349
+ const cBytes = ctx.store.bytes(bridged.id);
350
+ const manufactured = g !== null &&
351
+ bridged.subs.some((s) =>
352
+ indexOf(cBytes.subarray(s.cs, s.ce), g!, 0) >= 0
353
+ );
354
+ if (
355
+ g !== null && g.length > 0 && !restates(g) && !manufactured &&
356
+ !(g.length < query.length && indexOf(query, g, 0) >= 0)
357
+ ) {
358
+ return ground(
359
+ g,
360
+ `substitution bridge — a trained context accounts for the query ` +
361
+ `up to ${bridged.subs.length} corroborated substitution(s)`,
362
+ // Accounted NOTHING — the same epistemic humility as the echo
363
+ // tier below: a substitution-bridged grounding is a last resort
364
+ // that must lose to ANY mechanism that actually explained the
365
+ // query (observed: pricing the aligned spans here outweighed
366
+ // extraction's correct answer in the grounding decider), while
367
+ // still beating silence when everything else refused.
368
+ [],
369
+ CONCEPT * bridged.subs.length + STEP,
370
+ );
371
+ }
372
+ }
373
+ }
374
+
296
375
  // The refusal/echo decision. The echo returns a stored form's bytes AS
297
376
  // the answer — a near-identity claim about the query — and identity-grade
298
377
  // decisions are never made on an estimated score ("approximate scores may