@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,268 @@
1
+ // confluence.ts — Confluence Join (Section 4 of the mind).
2
+ //
3
+ // THE CLASS THIS SOLVES: conjunctive queries — answers that are stored in NO
4
+ // single fact and exist only as the INTERSECTION of independent evidence
5
+ // streams. "Which material is translucent and featherlight?" No learnt form
6
+ // contains the answer; each constraint reaches its own set of exemplars, and
7
+ // the entity satisfying both lives exactly where those sets MEET. Every
8
+ // other mechanism produces its answer by following ONE evidence path (a
9
+ // chain, a reverse step, a halo hop, one aligned frame); the consensus climb
10
+ // SUMS votes, fusion CONCATENATES topics, CAST COMPARES two seats — none of
11
+ // them intersects, so this class was previously answered wrong (fusion pairs
12
+ // one fact per constraint, from DIFFERENT entities).
13
+ //
14
+ // THE MEET IS NATIVE, NOT A BYTE SCAN. The store is content-addressed: any
15
+ // content two deposits share IS the same node id, interned once at write
16
+ // time (hash-consing) — so "what do these two facts have in common?" is a
17
+ // SET INTERSECTION OF IDENTITIES the write side already computed, asked
18
+ // through the canonical window read (leafIdRun/findBranch — the same
19
+ // write/read contract recognition runs on). Three identity/structure tests
20
+ // make the whole mechanism:
21
+ //
22
+ // • constraint streams — the consensus climb's ranked anchors, each bound
23
+ // to the query spans whose DISCRIMINATIVE windows it holds by identity
24
+ // (a resonance-voted anchor holding none of the query's discriminative
25
+ // content is no constraint at all); two streams are independent when
26
+ // the content they bind is disjoint;
27
+ // • the meet — window ids present in BOTH anchors and ABSENT from the
28
+ // query: shared-with-query windows are the constraint being re-named
29
+ // (or its scaffolding), so subtracting the query's own window ids
30
+ // leaves exactly the content the question asks FOR — the open seat;
31
+ // • the filler/scaffolding separator — the same structural IDF the climb
32
+ // derives (edgeAncestors' contextsReached): shared content reaching a
33
+ // corpus minority of contexts is an entity, content reaching a majority
34
+ // is frame scaffolding. No statistics, no learning — the same global-
35
+ // quantity-from-capped-local-probes reading that makes the climb's IDF
36
+ // work, pointed at a new question.
37
+ //
38
+ // HONESTY: the meet can only ever name content that structurally exists in
39
+ // two independently learnt exemplars — an empty intersection yields null and
40
+ // the ordinary pipeline decides. Confluence cannot fabricate.
41
+
42
+ import type { MindContext } from "../types.js";
43
+ import { read } from "../primitives.js";
44
+ import { corpusN, reachOf } from "../traverse.js";
45
+ import { dominates } from "../../geometry.js";
46
+ import { STEP } from "../graph-search.js";
47
+ import { unexplainedLabel } from "../rationale.js";
48
+ import type { PipelineMechanism, Precomputed } from "../pipeline-mechanism.js";
49
+ import { rItem, rNode } from "../trace.js";
50
+
51
+ /** A join answer plus its elementary evidence for think's grounding decider:
52
+ * `accounted` — the query spans whose votes carried the two constraint
53
+ * streams; `moves` — the ladder cost of the acts performed (two constraint
54
+ * matches and one meet, STEP each). `used` carries the pair's exemplar
55
+ * anchors so the reasoning stage does not re-speak them. */
56
+ export interface JoinResult {
57
+ bytes: Uint8Array;
58
+ used: ReadonlySet<number>;
59
+ accounted: Array<[number, number]>;
60
+ moves: number;
61
+ /** A human-readable label for the query bytes the meet left unexplained —
62
+ * purely diagnostic, never priced. */
63
+ unexplained: string;
64
+ }
65
+
66
+ /** The main confluence entry point. Given a query, detect whether it weaves
67
+ * two or more INDEPENDENT constraints (ranked anchors supported by disjoint
68
+ * query spans), intersect the constraints' evidence by content-addressed
69
+ * identity, and return the discriminative content the streams share — the
70
+ * entity that satisfies all constraints at once. Null when the query is
71
+ * not conjunctive or nothing lies in the intersection. */
72
+ export async function confluenceJoin(
73
+ ctx: MindContext,
74
+ query: Uint8Array,
75
+ pre: Precomputed,
76
+ ): Promise<JoinResult | null> {
77
+ const W = ctx.space.maxGroup;
78
+ if (query.length < 2 * W || ctx.store.edgeSourceCount() === 0) return null;
79
+ const { ranked } = await pre.attention();
80
+ if (ranked.length < 2) return null;
81
+
82
+ const N = corpusN(ctx);
83
+ // Response-scoped shared memos: the anchor-window identities and the
84
+ // structural-IDF reach live on Precomputed, so any other identity-based
85
+ // mechanism in the same response reuses them.
86
+ const reachMemo = pre.reachMemo;
87
+ const windowsOfAnchor = (anchor: number) => pre.windowsOf(anchor);
88
+
89
+ // The query's own window identities, offset → id (the canonical
90
+ // content-addressed read, canonical.windowIds): whatever the meet shares
91
+ // with the query is the CONSTRAINT being re-named (or its scaffolding),
92
+ // never the open seat the question asks for — subtracted by identity,
93
+ // below.
94
+ const queryWin = pre.queryWindows;
95
+ const queryIds = new Set(queryWin.values());
96
+
97
+ // ── Constraint streams: which query content does each anchor CONTAIN ──
98
+ // An anchor is a constraint of the query spans whose windows it holds BY
99
+ // IDENTITY — and only DISCRIMINATIVE windows bind (scaffolding like
100
+ // " is " is contained everywhere and constrains nothing; the same
101
+ // half-dominance reading of the structural IDF as the meet's gate).
102
+ // This is exact where a vote span is approximate: a resonance-voted
103
+ // anchor that contains none of the query's discriminative windows is no
104
+ // constraint at all.
105
+ interface Stream {
106
+ anchor: number;
107
+ vote: number;
108
+ ids: Set<number>;
109
+ /** Merged [start, end) query spans whose DISCRIMINATIVE windows this
110
+ * anchor holds — what the constraint BINDS (disjointness reads this). */
111
+ cover: Array<[number, number]>;
112
+ /** Merged [start, end) query spans this anchor holds AT ALL, scaffolding
113
+ * included — what the evidence EXPLAINS (the decider's accounted reads
114
+ * this: a contained " is " does not bind a constraint, but it is
115
+ * genuinely matched content, the same way the cover search counts a
116
+ * recognised common form). */
117
+ held: Array<[number, number]>;
118
+ }
119
+ const streams: Stream[] = [];
120
+ const rankedCapped = ranked.length > pre.k ? ranked.slice(0, pre.k) : ranked;
121
+ for (const cand of rankedCapped) {
122
+ if (streams.some((s) => s.anchor === cand.anchor)) continue;
123
+ const ids = new Set(windowsOfAnchor(cand.anchor).values());
124
+ if (ids.size === 0) continue;
125
+ const cover: Array<[number, number]> = [];
126
+ const held: Array<[number, number]> = [];
127
+ let curC: [number, number] | null = null;
128
+ let curH: [number, number] | null = null;
129
+ for (const [off, wid] of queryWin) {
130
+ if (!ids.has(wid)) continue;
131
+ if (curH !== null && off <= curH[1]) curH[1] = off + W;
132
+ else held.push(curH = [off, off + W]);
133
+ if (dominates(reachOf(ctx, wid, N, reachMemo), N)) continue; // scaffolding never binds
134
+ if (curC !== null && off <= curC[1]) curC[1] = off + W;
135
+ else cover.push(curC = [off, off + W]);
136
+ }
137
+ if (cover.length > 0) {
138
+ streams.push({ anchor: cand.anchor, vote: cand.vote, ids, cover, held });
139
+ }
140
+ }
141
+ if (streams.length < 2) return null;
142
+
143
+ // Two streams are INDEPENDENT constraints when the query content they
144
+ // hold is disjoint — each answers a different part of what was asked.
145
+ const disjoint = (a: Stream, b: Stream): boolean =>
146
+ a.cover.every(([as, ae]) =>
147
+ b.cover.every(([bs, be]) => be <= as || bs >= ae)
148
+ );
149
+
150
+ interface Meet {
151
+ bytes: Uint8Array;
152
+ reach: number;
153
+ len: number;
154
+ a: Stream;
155
+ b: Stream;
156
+ }
157
+ let met: Meet | null = null;
158
+
159
+ for (let i = 0; i < streams.length; i++) {
160
+ for (let j = i + 1; j < streams.length; j++) {
161
+ const a = streams[i];
162
+ const b = streams[j];
163
+ if (!disjoint(a, b)) continue;
164
+ const wa = windowsOfAnchor(a.anchor);
165
+ const wb = b.ids;
166
+
167
+ // ── The MEET: in both anchors, not in the query ────────────────────
168
+ // Offsets of A whose window id is shared with B and absent from the
169
+ // query — merged into maximal contiguous spans (windows overlap, so
170
+ // consecutive shared offsets weave one span).
171
+ const spans: Array<[number, number]> = [];
172
+ let cur: [number, number] | null = null;
173
+ for (const [off, wid] of wa) {
174
+ const inMeet = wb.has(wid) && !queryIds.has(wid);
175
+ if (inMeet) {
176
+ if (cur !== null && off <= cur[1]) cur[1] = off + W;
177
+ else spans.push(cur = [off, off + W]);
178
+ }
179
+ }
180
+ if (spans.length === 0) continue;
181
+
182
+ const aBytes = read(ctx, a.anchor);
183
+ for (const [s, e] of spans) {
184
+ // Scaffolding gate: the span's MOST discriminative window decides.
185
+ // Content reaching a corpus MAJORITY of contexts discriminates
186
+ // nothing (the same half-dominance convention every wrapper test
187
+ // uses); the query-subtraction above already removed everything the
188
+ // question names, so what survives here is a genuine open-seat
189
+ // entity.
190
+ let reach = Infinity;
191
+ for (let off = s; off + W <= e; off++) {
192
+ const wid = wa.get(off);
193
+ if (wid !== undefined && wb.has(wid) && !queryIds.has(wid)) {
194
+ reach = Math.min(reach, reachOf(ctx, wid, N, reachMemo));
195
+ }
196
+ }
197
+ if (!isFinite(reach) || dominates(reach, N)) continue;
198
+ const len = e - s;
199
+ if (
200
+ met === null || reach < met.reach ||
201
+ (reach === met.reach && len > met.len)
202
+ ) {
203
+ met = { bytes: aBytes.subarray(s, e), reach, len, a, b };
204
+ }
205
+ }
206
+ }
207
+ }
208
+ if (met === null) return null;
209
+
210
+ const t = ctx.trace?.enter("confluence", [rItem(query, "query")]);
211
+ ctx.trace?.step(
212
+ "intersectEvidence",
213
+ [
214
+ rNode(ctx, met.a.anchor, "constraint", met.a.vote),
215
+ rNode(ctx, met.b.anchor, "constraint", met.b.vote),
216
+ ],
217
+ [rItem(met.bytes, "meet")],
218
+ `the discriminative content BOTH constraints' evidence shares, by content-addressed identity (reach ${met.reach} of ${N} contexts)`,
219
+ );
220
+ t?.done(
221
+ [rItem(met.bytes, "answer")],
222
+ "conjunctive join — the entity where the independent evidence streams meet",
223
+ );
224
+ // Evidence: the query spans whose content the two streams hold by
225
+ // identity (scaffolding included — held, not just the binding cover);
226
+ // the acts were two constraint matches and one meet.
227
+ const accounted: Array<[number, number]> = [
228
+ ...met.a.held,
229
+ ...met.b.held,
230
+ ];
231
+ return {
232
+ bytes: met.bytes,
233
+ used: new Set([met.a.anchor, met.b.anchor]),
234
+ accounted,
235
+ moves: 3 * STEP,
236
+ unexplained: unexplainedLabel(query, accounted),
237
+ };
238
+ }
239
+
240
+ // ── Pipeline mechanism ──────────────────────────────────────────────────────
241
+
242
+ export const confluenceMechanism: PipelineMechanism = {
243
+ name: "confluence",
244
+ provenance: "join",
245
+ async floor(_ctx, query, pre, worthRunning) {
246
+ const W = _ctx.space.maxGroup;
247
+ if (query.length < 2 * W || _ctx.store.edgeSourceCount() === 0) return null;
248
+ // Confluence's floor is always exactly 3*STEP when it exists — same
249
+ // investment discipline as CAST's (see cast.ts): when the bound already
250
+ // cannot beat the incumbent, return it UNINVESTED (never first-touch the
251
+ // climb just to be pruned) and let the pipeline record the truthful
252
+ // "cannot beat incumbent" note.
253
+ if (!worthRunning(3 * STEP)) return 3 * STEP;
254
+ if ((await pre.attention()).ranked.length < 2) return null;
255
+ return 3 * STEP;
256
+ },
257
+ async run(ctx, query, pre) {
258
+ const met = await confluenceJoin(ctx, query, pre);
259
+ if (!met) return [];
260
+ return [{
261
+ bytes: met.bytes,
262
+ accounted: met.accounted,
263
+ moves: met.moves,
264
+ used: met.used,
265
+ unexplained: met.unexplained,
266
+ }];
267
+ },
268
+ };
@@ -0,0 +1,248 @@
1
+ // mechanisms/cover.ts — Cover (Grounding II): the query's own decomposition
2
+ // composes an answer through ONE lightest-derivation search.
3
+ //
4
+ // Cover consumes recognition directly (its axioms are the query's own
5
+ // decomposition) plus the computed spans any parse()-bearing mechanism
6
+ // contributed: computed spans MASK colliding recognised sites and enter the
7
+ // search at zero cost ("computation always wins", §16.3) — which is also why
8
+ // cover runs FIRST in defaultMechanisms: a computed-backed cover becomes a
9
+ // near-zero-cost incumbent that prunes the other mechanisms through the
10
+ // ordinary admissible-floor check, with no extension special-case anywhere.
11
+
12
+ import type { MindContext } from "../types.js";
13
+ import type { ComputedResult, Site } from "../graph-search.js";
14
+ import { read, resolve } from "../primitives.js";
15
+ import { guidedFirst } from "../traverse.js";
16
+ import { conceptHop } from "../match.js";
17
+ import { bridge } from "../resonance.js";
18
+ import { liftAnswer } from "../types.js";
19
+ import { decodeText, unexplainedLabel } from "../rationale.js";
20
+ import type { RationaleItem } from "../rationale.js";
21
+ import { rItem, rNode, traceDerivation } from "../trace.js";
22
+ import type { PipelineMechanism } from "../pipeline-mechanism.js";
23
+
24
+ // ── Concept / connector pre-resolution ──────────────────────────────────────
25
+
26
+ export async function resolveConcepts(
27
+ ctx: MindContext,
28
+ sites: Site[],
29
+ ): Promise<Map<number, number>> {
30
+ const target = new Map<number, number>();
31
+ const visited = new Set<number>();
32
+ for (const { payload: n } of sites) {
33
+ if (visited.has(n)) continue;
34
+ visited.add(n);
35
+ if (ctx.store.hasNext(n)) continue;
36
+ const hop = await conceptHop(ctx, n);
37
+ if (hop !== null) target.set(n, hop);
38
+ }
39
+ if (target.size > 0) {
40
+ ctx.trace?.step(
41
+ "resolveConcepts",
42
+ [...target.keys()].map((n) => rNode(ctx, n, "edgeless-form")),
43
+ [...target.values()].map((h) => rNode(ctx, h, "concept-sibling")),
44
+ "borrow a synonym's continuation edge for each edge-less form (a concept/halo hop)",
45
+ );
46
+ }
47
+ return target;
48
+ }
49
+
50
+ export async function resolveConnectors(
51
+ ctx: MindContext,
52
+ sites: ReadonlyArray<Site>,
53
+ ): Promise<Map<string, Uint8Array>> {
54
+ const links = new Map<string, Uint8Array>();
55
+ const ordered = [...sites].sort((a, b) => a.start - b.start);
56
+ const answerOf = (n: number) => guidedFirst(ctx, n) ?? n;
57
+ const bridgePair = async (l: number, r: number) => {
58
+ if (l === r || links.has(l + "," + r)) return;
59
+ const link = await bridge(ctx, read(ctx, l), read(ctx, r));
60
+ if (link !== null) links.set(l + "," + r, link);
61
+ };
62
+ for (let i = 0; i + 1 < ordered.length; i++) {
63
+ if (ordered[i].end !== ordered[i + 1].start) continue;
64
+ const lefts = [ordered[i].payload, answerOf(ordered[i].payload)];
65
+ const rights = [ordered[i + 1].payload, answerOf(ordered[i + 1].payload)];
66
+ for (const l of new Set(lefts)) {
67
+ for (const r of new Set(rights)) {
68
+ await bridgePair(l, r);
69
+ await bridgePair(r, l);
70
+ }
71
+ }
72
+ }
73
+ const orderedNodes: Array<{ node: number; bytes: Uint8Array }> = [];
74
+ const seenN = new Set<number>();
75
+ for (const s of ordered) {
76
+ const node = guidedFirst(ctx, s.payload) ?? s.payload;
77
+ if (seenN.has(node)) continue;
78
+ seenN.add(node);
79
+ orderedNodes.push({ node, bytes: read(ctx, node) });
80
+ }
81
+ if (orderedNodes.length >= 3) {
82
+ const first = orderedNodes[0];
83
+ const W = ctx.space.maxGroup;
84
+ let middleBytes = 0; // Σ bytes of the answers BETWEEN first and m-th
85
+ for (let m = 1; m < orderedNodes.length; m++) {
86
+ const key = first.node + "," + orderedNodes[m].node;
87
+ if (links.has(key)) {
88
+ middleBytes += orderedNodes[m].bytes.length;
89
+ continue;
90
+ }
91
+ // The N-ary interior legitimately holds every intermediate answer
92
+ // plus one W-quantum of glue per joint — pass that allowance so the
93
+ // bridge's phrase-scale cap admits the whole learnt run.
94
+ const allowance = middleBytes + (m + 1) * W;
95
+ const interior = await bridge(
96
+ ctx,
97
+ first.bytes,
98
+ orderedNodes[m].bytes,
99
+ allowance,
100
+ );
101
+ if (interior !== null) links.set(key, interior);
102
+ middleBytes += orderedNodes[m].bytes.length;
103
+ }
104
+ }
105
+ if (links.size > 0) {
106
+ ctx.trace?.step(
107
+ "resolveConnectors",
108
+ ordered.map((s) => rItem(read(ctx, s.payload), "answer", s.payload)),
109
+ [...links.entries()].map(([pair, bytes]) => ({
110
+ text: `${pair}: "${decodeText(bytes)}"`,
111
+ role: "connector",
112
+ } as RationaleItem)),
113
+ "the bytes the graph splices between adjacent answers (asked of the gist space)",
114
+ );
115
+ }
116
+ return links;
117
+ }
118
+
119
+ // ── Pipeline mechanism ──────────────────────────────────────────────────────
120
+
121
+ export const coverMechanism: PipelineMechanism = {
122
+ name: "cover",
123
+ provenance: "cover",
124
+ async floor(_ctx, _query, _pre, _worthRunning) {
125
+ return 0;
126
+ },
127
+ async run(ctx, query, pre) {
128
+ const { rec, computed } = pre;
129
+
130
+ // Masking: computed spans are authoritative. Remove recognised sites
131
+ // that overlap any computed span before building the cover search.
132
+ const sites = computed.length === 0
133
+ ? rec.sites
134
+ : rec.sites.filter((s) =>
135
+ !computed.some((u) => s.start < u.j && u.i < s.end)
136
+ );
137
+
138
+ if (computed.length > 0 && sites.length < rec.sites.length) {
139
+ ctx.trace?.step(
140
+ "maskByComputation",
141
+ rec.sites.map((s) =>
142
+ rItem(query.subarray(s.start, s.end), "form", s.payload, [
143
+ s.start,
144
+ s.end,
145
+ ])
146
+ ),
147
+ sites.map((s) =>
148
+ rItem(query.subarray(s.start, s.end), "form", s.payload, [
149
+ s.start,
150
+ s.end,
151
+ ])
152
+ ),
153
+ "a computation always wins: recognised forms overlapping a computed span are dropped",
154
+ );
155
+ }
156
+
157
+ if (sites.length === 0 && computed.length === 0) return [];
158
+
159
+ const connectors = await resolveConnectors(ctx, sites);
160
+ let splits = rec.splits;
161
+ if (computed.length > 0) {
162
+ splits = new Set(rec.splits);
163
+ for (const u of computed) {
164
+ splits.add(u.i);
165
+ splits.add(u.j);
166
+ }
167
+ }
168
+ const concepts = await resolveConcepts(ctx, sites);
169
+
170
+ const coverDeps = [
171
+ ctx.trace?.lastIndex("recognise"),
172
+ ctx.trace?.lastIndex("computeExtensions"),
173
+ ctx.trace?.lastIndex("resolveConcepts"),
174
+ ctx.trace?.lastIndex("resolveConnectors"),
175
+ ].filter((x): x is number => x !== undefined);
176
+
177
+ // Convert ComputedSpan[] to ComputedResult[] for the graph search.
178
+ const computedResults: ComputedResult[] = computed.map((u) => ({
179
+ i: u.i,
180
+ j: u.j,
181
+ bytes: u.bytes,
182
+ node: resolve(ctx, u.bytes) ?? undefined,
183
+ }));
184
+
185
+ const tCover = ctx.trace?.enter("cover", [
186
+ ...sites.map((s) =>
187
+ rItem(query.subarray(s.start, s.end), "form", s.payload, [
188
+ s.start,
189
+ s.end,
190
+ ])
191
+ ),
192
+ ...computedResults.map((u) => rItem(u.bytes, "computed")),
193
+ ], coverDeps.length ? coverDeps : undefined);
194
+
195
+ const solved = ctx.search.cover(
196
+ query.length,
197
+ sites,
198
+ concepts,
199
+ rec.leaves,
200
+ splits,
201
+ undefined,
202
+ connectors,
203
+ computedResults,
204
+ ctx.trace ? (steps) => traceDerivation(ctx, steps) : undefined,
205
+ );
206
+ const segs = solved && solved.segs;
207
+ tCover?.done(
208
+ segs === null
209
+ ? []
210
+ : segs.map((s) =>
211
+ rItem(s.bytes, s.rec ? "chosen" : "bridge", s.node, [s.i, s.j])
212
+ ),
213
+ segs === null
214
+ ? "no cover of the query composed"
215
+ : "lightest derivation: the chosen spans, left to right",
216
+ );
217
+
218
+ if (segs === null) return [];
219
+
220
+ const composed = liftAnswer(segs, query.length);
221
+ if (composed === null) return [];
222
+
223
+ ctx.trace?.step(
224
+ "liftAnswer",
225
+ segs.map((s) =>
226
+ rItem(s.bytes, s.rec ? "chosen" : "scaffolding", s.node, [s.i, s.j])
227
+ ),
228
+ [rItem(composed, "answer", resolve(ctx, composed) ?? undefined)],
229
+ "lift the recognised region out of the asker's framing",
230
+ tCover ? [tCover.index] : undefined,
231
+ );
232
+
233
+ // accounted = RECOGNISED cover spans only — PASS-carried bytes
234
+ // are priced in cost already; the diagnostic label reflects the
235
+ // same distinction.
236
+ const accounted: Array<[number, number]> = segs
237
+ .filter((s) => s.rec)
238
+ .map((s) => [s.i, s.j]);
239
+
240
+ return [{
241
+ bytes: composed,
242
+ accounted,
243
+ moves: 0,
244
+ weight: solved!.cost, // A*LD derivation's g-value IS the weight
245
+ unexplained: unexplainedLabel(query, accounted),
246
+ }];
247
+ },
248
+ };