@vellumai/assistant 0.10.12-dev.202607250047.75b9ec6 → 0.10.12-dev.202607250140.9979030
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.
- package/package.json +1 -1
- package/src/config/schemas/__tests__/memory-v3.test.ts +1 -0
- package/src/config/schemas/memory-v3.ts +8 -0
- package/src/plugins/defaults/memory/v3/__tests__/orchestrate.test.ts +180 -2
- package/src/plugins/defaults/memory/v3/__tests__/selection-log-store.test.ts +3 -0
- package/src/plugins/defaults/memory/v3/__tests__/shadow-integration.test.ts +1 -0
- package/src/plugins/defaults/memory/v3/__tests__/tuning-profile.test.ts +1 -0
- package/src/plugins/defaults/memory/v3/orchestrate.ts +97 -15
- package/src/plugins/defaults/memory/v3/shadow-plugin.ts +1 -0
- package/src/plugins/defaults/memory/v3/span-query.test.ts +86 -0
- package/src/plugins/defaults/memory/v3/span-query.ts +71 -0
- package/src/plugins/defaults/memory/v3/tuning-profile.ts +3 -0
- package/src/plugins/defaults/memory/v3/types.ts +4 -1
package/package.json
CHANGED
|
@@ -383,6 +383,14 @@ export const MemoryV3ConfigSchema = z
|
|
|
383
383
|
.describe(
|
|
384
384
|
"Per-lane article budget for the reply-query finder pass: needle and dense each re-run over the assistant's previous message as separate queries (never concatenated with the user's message). 0 disables the pass. Deliberately small next to needleK/denseK — the pass adds the assistant-side retrieval signal, not a second full sweep.",
|
|
385
385
|
),
|
|
386
|
+
spanQueryK: z
|
|
387
|
+
.number({ error: "memory.v3.spanQueryK must be a number" })
|
|
388
|
+
.int("memory.v3.spanQueryK must be an integer")
|
|
389
|
+
.nonnegative("memory.v3.spanQueryK must be a non-negative integer")
|
|
390
|
+
.default(0)
|
|
391
|
+
.describe(
|
|
392
|
+
"Per-chunk article budget for the span-query dense pass: the current message's clause spans (merged into at most 8 contiguous chunks) re-run through the dense lane as separate queries, union-additive into the candidate pool. 0 disables the pass; it is also inert when denseK is 0 or the message yields fewer than two chunks. Deliberately small next to denseK — the pass rescues motifs a long message's single query vector averages away, not a second full sweep.",
|
|
393
|
+
),
|
|
386
394
|
selectorEnabled: z
|
|
387
395
|
.boolean({ error: "memory.v3.selectorEnabled must be a boolean" })
|
|
388
396
|
.default(true)
|
|
@@ -71,6 +71,12 @@ mock.module("../../../../../util/logger.js", () => ({
|
|
|
71
71
|
const realDense = { ...(await import("../dense.js")) };
|
|
72
72
|
let denseMockActive = false;
|
|
73
73
|
let denseHits: Array<{ article: Slug; section: number; score?: number }> = [];
|
|
74
|
+
// Per-query hit override for tests that need the full-message and span-chunk
|
|
75
|
+
// dense calls to return DIFFERENT results; falls back to `denseHits`.
|
|
76
|
+
let denseHitsByQuery = new Map<
|
|
77
|
+
string,
|
|
78
|
+
Array<{ article: Slug; section: number; score?: number }>
|
|
79
|
+
>();
|
|
74
80
|
let denseCalls: Array<{ query: string; k: number }> = [];
|
|
75
81
|
mock.module("../dense.js", () => ({
|
|
76
82
|
...realDense,
|
|
@@ -79,7 +85,7 @@ mock.module("../dense.js", () => ({
|
|
|
79
85
|
return realDense.denseLane(...args);
|
|
80
86
|
}
|
|
81
87
|
denseCalls.push({ query: args[1], k: args[2] });
|
|
82
|
-
return args[2] <= 0 ? [] : denseHits;
|
|
88
|
+
return args[2] <= 0 ? [] : (denseHitsByQuery.get(args[1]) ?? denseHits);
|
|
83
89
|
},
|
|
84
90
|
// Orchestrate now calls the SCORED variant; the mock must intercept it too
|
|
85
91
|
// (else the `...realDense` spread resolves the real lane and hits Qdrant).
|
|
@@ -94,7 +100,10 @@ mock.module("../dense.js", () => ({
|
|
|
94
100
|
denseCalls.push({ query: args[1], k: args[2] });
|
|
95
101
|
return args[2] <= 0
|
|
96
102
|
? []
|
|
97
|
-
: denseHits.map((h) => ({
|
|
103
|
+
: (denseHitsByQuery.get(args[1]) ?? denseHits).map((h) => ({
|
|
104
|
+
...h,
|
|
105
|
+
score: h.score ?? 1,
|
|
106
|
+
}));
|
|
98
107
|
},
|
|
99
108
|
}));
|
|
100
109
|
|
|
@@ -330,6 +339,7 @@ beforeEach(() => {
|
|
|
330
339
|
watchdogMockActive = true;
|
|
331
340
|
providerStub = null;
|
|
332
341
|
denseHits = [];
|
|
342
|
+
denseHitsByQuery = new Map();
|
|
333
343
|
denseCalls = [];
|
|
334
344
|
recordedGateEvents = [];
|
|
335
345
|
recordedSelectionEvents = [];
|
|
@@ -1753,3 +1763,171 @@ describe("latency sub-spans", () => {
|
|
|
1753
1763
|
}
|
|
1754
1764
|
});
|
|
1755
1765
|
});
|
|
1766
|
+
|
|
1767
|
+
// ---------------------------------------------------------------------------
|
|
1768
|
+
// Span-query pass: the dense lane re-run over the current message's clause
|
|
1769
|
+
// chunks as separate queries at `spanQueryK`, union-additive into the pool.
|
|
1770
|
+
// ---------------------------------------------------------------------------
|
|
1771
|
+
|
|
1772
|
+
describe("orchestrate — span-query pass", () => {
|
|
1773
|
+
const TWO_CHUNK_MESSAGE =
|
|
1774
|
+
"apple appears in the first sentence here. elderberry shows up in the second sentence.";
|
|
1775
|
+
const CHUNK_1 = "apple appears in the first sentence here.";
|
|
1776
|
+
const CHUNK_2 = "elderberry shows up in the second sentence.";
|
|
1777
|
+
|
|
1778
|
+
test("spanQueryK omitted (default) runs no span dense calls", async () => {
|
|
1779
|
+
const lanes = await buildLanes();
|
|
1780
|
+
|
|
1781
|
+
await orchestrate(
|
|
1782
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1783
|
+
depsOf(lanes, { denseK: 100, selectorEnabled: false }),
|
|
1784
|
+
);
|
|
1785
|
+
|
|
1786
|
+
expect(denseCalls).toEqual([{ query: TWO_CHUNK_MESSAGE, k: 100 }]);
|
|
1787
|
+
});
|
|
1788
|
+
|
|
1789
|
+
test("span pass is inert when denseK=0", async () => {
|
|
1790
|
+
const lanes = await buildLanes();
|
|
1791
|
+
|
|
1792
|
+
await orchestrate(
|
|
1793
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1794
|
+
depsOf(lanes, { denseK: 0, spanQueryK: 7, selectorEnabled: false }),
|
|
1795
|
+
);
|
|
1796
|
+
|
|
1797
|
+
expect(denseCalls).toEqual([]);
|
|
1798
|
+
});
|
|
1799
|
+
|
|
1800
|
+
test("single-chunk message skips the span pass", async () => {
|
|
1801
|
+
const lanes = await buildLanes();
|
|
1802
|
+
|
|
1803
|
+
await orchestrate(
|
|
1804
|
+
makeTurn(1, "apple in one single sentence."),
|
|
1805
|
+
depsOf(lanes, { denseK: 100, spanQueryK: 7, selectorEnabled: false }),
|
|
1806
|
+
);
|
|
1807
|
+
|
|
1808
|
+
expect(denseCalls).toEqual([
|
|
1809
|
+
{ query: "apple in one single sentence.", k: 100 },
|
|
1810
|
+
]);
|
|
1811
|
+
});
|
|
1812
|
+
|
|
1813
|
+
test("multi-chunk message adds span-lane candidates additively", async () => {
|
|
1814
|
+
const lanes = await buildLanes();
|
|
1815
|
+
// Full-message dense (and any chunk without an override) returns topic-b;
|
|
1816
|
+
// chunk 1 re-surfaces topic-a (already a needle hit — attribution must
|
|
1817
|
+
// stay "needle"); chunk 2 surfaces topic-d, which no other lane reaches
|
|
1818
|
+
// ("grape" is not in the message, and the topic-a → topic-d curated edge
|
|
1819
|
+
// must not re-surface an already-seen slug).
|
|
1820
|
+
denseHits = [{ article: "topic-b", section: 0 }];
|
|
1821
|
+
denseHitsByQuery.set(CHUNK_1, [{ article: "topic-a", section: 1 }]);
|
|
1822
|
+
denseHitsByQuery.set(CHUNK_2, [{ article: "topic-d", section: 0 }]);
|
|
1823
|
+
|
|
1824
|
+
const result = await orchestrate(
|
|
1825
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1826
|
+
depsOf(lanes, { denseK: 100, spanQueryK: 7, selectorEnabled: false }),
|
|
1827
|
+
);
|
|
1828
|
+
|
|
1829
|
+
expect(denseCalls).toEqual([
|
|
1830
|
+
{ query: TWO_CHUNK_MESSAGE, k: 100 },
|
|
1831
|
+
{ query: CHUNK_1, k: 7 },
|
|
1832
|
+
{ query: CHUNK_2, k: 7 },
|
|
1833
|
+
]);
|
|
1834
|
+
const laneOf = new Map(
|
|
1835
|
+
result.lanes.finder.map((c) => [c.slug, c.lane] as const),
|
|
1836
|
+
);
|
|
1837
|
+
// "apple"/"elderberry" needle hits keep their lanes; the full-message
|
|
1838
|
+
// dense hit keeps "dense"; only the genuinely span-surfaced page tags
|
|
1839
|
+
// "span".
|
|
1840
|
+
expect(laneOf.get("topic-a")).toBe("needle");
|
|
1841
|
+
expect(laneOf.get("topic-c")).toBe("needle");
|
|
1842
|
+
expect(laneOf.get("topic-b")).toBe("dense");
|
|
1843
|
+
expect(laneOf.get("topic-d")).toBe("span");
|
|
1844
|
+
expect(result.lanes.finder.filter((c) => c.slug === "topic-a").length).toBe(
|
|
1845
|
+
1,
|
|
1846
|
+
);
|
|
1847
|
+
// The span hit's matched section is recorded for injection/spotlight.
|
|
1848
|
+
expect(result.matchedSections.get("topic-d")?.article).toBe("topic-d");
|
|
1849
|
+
expect(result.matchedSections.get("topic-d")?.text).toContain(
|
|
1850
|
+
"lead for topic d",
|
|
1851
|
+
);
|
|
1852
|
+
// Additive: the span-only page joins the passthrough selections alongside
|
|
1853
|
+
// every other lane's candidates.
|
|
1854
|
+
expect(new Set(result.selections.map((s) => s.slug))).toEqual(
|
|
1855
|
+
new Set(["topic-a", "topic-b", "topic-c", "topic-d"]),
|
|
1856
|
+
);
|
|
1857
|
+
});
|
|
1858
|
+
|
|
1859
|
+
test("an article hit by several chunks records its highest-scoring section", async () => {
|
|
1860
|
+
const lanes = await buildLanes();
|
|
1861
|
+
// Both chunks surface topic-d; the EARLIER chunk's hit is the weaker one.
|
|
1862
|
+
// Chunk order must not decide the recorded section — the strong match
|
|
1863
|
+
// (ordinal 1, `## Notes`) wins over the lead (ordinal 0).
|
|
1864
|
+
denseHits = [];
|
|
1865
|
+
denseHitsByQuery.set(CHUNK_1, [
|
|
1866
|
+
{ article: "topic-d", section: 0, score: 0.2 },
|
|
1867
|
+
]);
|
|
1868
|
+
denseHitsByQuery.set(CHUNK_2, [
|
|
1869
|
+
{ article: "topic-d", section: 1, score: 0.9 },
|
|
1870
|
+
]);
|
|
1871
|
+
|
|
1872
|
+
const result = await orchestrate(
|
|
1873
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1874
|
+
depsOf(lanes, { denseK: 100, spanQueryK: 7, selectorEnabled: false }),
|
|
1875
|
+
);
|
|
1876
|
+
|
|
1877
|
+
expect(result.matchedSections.get("topic-d")?.ordinal).toBe(1);
|
|
1878
|
+
expect(result.matchedSections.get("topic-d")?.text).toContain("grape");
|
|
1879
|
+
expect(
|
|
1880
|
+
result.lanes.finder.filter((c) => c.slug === "topic-d"),
|
|
1881
|
+
).toHaveLength(1);
|
|
1882
|
+
});
|
|
1883
|
+
|
|
1884
|
+
test("a strictly stronger span cosine upgrades a dense-recorded section, keeping the lane", async () => {
|
|
1885
|
+
const lanes = await buildLanes();
|
|
1886
|
+
// Full-message dense records topic-b's lead (ordinal 0) at cosine 0.4;
|
|
1887
|
+
// chunk 2 finds `## More` (ordinal 1) at 0.9 — same encoder and
|
|
1888
|
+
// collection, strictly stronger, so the recorded section and finder
|
|
1889
|
+
// descriptor upgrade while the lane attribution stays "dense".
|
|
1890
|
+
denseHits = [{ article: "topic-b", section: 0, score: 0.4 }];
|
|
1891
|
+
denseHitsByQuery.set(CHUNK_2, [
|
|
1892
|
+
{ article: "topic-b", section: 1, score: 0.9 },
|
|
1893
|
+
]);
|
|
1894
|
+
|
|
1895
|
+
const result = await orchestrate(
|
|
1896
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1897
|
+
depsOf(lanes, { denseK: 100, spanQueryK: 7, selectorEnabled: false }),
|
|
1898
|
+
);
|
|
1899
|
+
|
|
1900
|
+
expect(result.matchedSections.get("topic-b")?.ordinal).toBe(1);
|
|
1901
|
+
expect(result.matchedSections.get("topic-b")?.text).toContain(
|
|
1902
|
+
"cherry date",
|
|
1903
|
+
);
|
|
1904
|
+
const entry = result.lanes.finder.find((c) => c.slug === "topic-b");
|
|
1905
|
+
expect(entry?.lane).toBe("dense");
|
|
1906
|
+
expect(entry?.descriptor).toContain("cherry date");
|
|
1907
|
+
});
|
|
1908
|
+
|
|
1909
|
+
test("weaker span hits and needle-recorded sections are not overridden", async () => {
|
|
1910
|
+
const lanes = await buildLanes();
|
|
1911
|
+
// topic-b: span cosine 0.3 < full-message 0.4 — the lead stays recorded.
|
|
1912
|
+
// topic-a: needle recorded the `## Details` match; span scores are not
|
|
1913
|
+
// comparable to BM25, so the span hit must not touch it.
|
|
1914
|
+
denseHits = [{ article: "topic-b", section: 0, score: 0.4 }];
|
|
1915
|
+
denseHitsByQuery.set(CHUNK_1, [
|
|
1916
|
+
{ article: "topic-a", section: 0, score: 0.99 },
|
|
1917
|
+
]);
|
|
1918
|
+
denseHitsByQuery.set(CHUNK_2, [
|
|
1919
|
+
{ article: "topic-b", section: 1, score: 0.3 },
|
|
1920
|
+
]);
|
|
1921
|
+
|
|
1922
|
+
const result = await orchestrate(
|
|
1923
|
+
makeTurn(1, TWO_CHUNK_MESSAGE),
|
|
1924
|
+
depsOf(lanes, { denseK: 100, spanQueryK: 7, selectorEnabled: false }),
|
|
1925
|
+
);
|
|
1926
|
+
|
|
1927
|
+
expect(result.matchedSections.get("topic-b")?.ordinal).toBe(0);
|
|
1928
|
+
expect(result.matchedSections.get("topic-a")?.text).toContain("apple");
|
|
1929
|
+
expect(result.lanes.finder.find((c) => c.slug === "topic-a")?.lane).toBe(
|
|
1930
|
+
"needle",
|
|
1931
|
+
);
|
|
1932
|
+
});
|
|
1933
|
+
});
|
|
@@ -403,6 +403,7 @@ describe("summarizeSelections", () => {
|
|
|
403
403
|
dense: 0,
|
|
404
404
|
edge: 2,
|
|
405
405
|
reply: 0,
|
|
406
|
+
span: 0,
|
|
406
407
|
learned: 0,
|
|
407
408
|
entity: 0,
|
|
408
409
|
});
|
|
@@ -421,6 +422,7 @@ describe("summarizeSelections", () => {
|
|
|
421
422
|
dense: 0,
|
|
422
423
|
edge: 0,
|
|
423
424
|
reply: 0,
|
|
425
|
+
span: 0,
|
|
424
426
|
learned: 0,
|
|
425
427
|
entity: 0,
|
|
426
428
|
},
|
|
@@ -443,6 +445,7 @@ describe("summarizeSelections", () => {
|
|
|
443
445
|
dense: 0,
|
|
444
446
|
edge: 0,
|
|
445
447
|
reply: 0,
|
|
448
|
+
span: 0,
|
|
446
449
|
learned: 0,
|
|
447
450
|
entity: 0,
|
|
448
451
|
},
|
|
@@ -9,7 +9,11 @@
|
|
|
9
9
|
* PREVIOUS message as separate queries at a smaller budget
|
|
10
10
|
* (`replyQueryK` per lane), surfacing the threads the assistant is
|
|
11
11
|
* actively developing that the user's message references without
|
|
12
|
-
* naming —
|
|
12
|
+
* naming —
|
|
13
|
+
* - the span-query pass — the dense lane re-run over the current
|
|
14
|
+
* message's clause chunks as separate queries at a small per-chunk
|
|
15
|
+
* budget (`spanQueryK`), rescuing motifs a long multi-topic message's
|
|
16
|
+
* single query vector averages away — and
|
|
13
17
|
* - link-graph edge expansion (`edgeExpand`) over the top
|
|
14
18
|
* user-message needle+dense article seeds, and
|
|
15
19
|
* - learned-edge expansion (`edgeExpand` over the co-selection NPMI
|
|
@@ -61,6 +65,7 @@ import {
|
|
|
61
65
|
} from "../../../../daemon/turn-latency-sub-spans.js";
|
|
62
66
|
import { recordWatchdogEvent } from "../../../../telemetry/watchdog-events-store.js";
|
|
63
67
|
import { getLogger } from "../logging.js";
|
|
68
|
+
import type { DenseHitScored } from "./dense.js";
|
|
64
69
|
import { denseLaneScored } from "./dense.js";
|
|
65
70
|
import type { EdgeGraph } from "./edge.js";
|
|
66
71
|
import { edgeExpand } from "./edge.js";
|
|
@@ -74,6 +79,7 @@ import type {
|
|
|
74
79
|
} from "./pool-select.js";
|
|
75
80
|
import { selectAllPoolCandidates, selectPool } from "./pool-select.js";
|
|
76
81
|
import type { SectionNeedle } from "./section-needle.js";
|
|
82
|
+
import { spanChunksOf } from "./span-query.js";
|
|
77
83
|
import type {
|
|
78
84
|
FinderLane,
|
|
79
85
|
MemoryRoutingTurn,
|
|
@@ -195,6 +201,12 @@ export interface OrchestrateDeps {
|
|
|
195
201
|
* over `turn.previousAssistantMessage` as separate queries). `0` or
|
|
196
202
|
* omitted disables the pass (canonical value: `memory.v3.replyQueryK`). */
|
|
197
203
|
replyQueryK?: number;
|
|
204
|
+
/** Per-chunk article budget for the span-query pass (dense re-run over the
|
|
205
|
+
* current message's clause chunks as separate queries). `0` or omitted
|
|
206
|
+
* disables the pass; it is also inert when the dense lane is disabled or
|
|
207
|
+
* the message yields fewer than two chunks (canonical value:
|
|
208
|
+
* `memory.v3.spanQueryK`). */
|
|
209
|
+
spanQueryK?: number;
|
|
198
210
|
/** Number of top needle+dense seeds expanded. When omitted, the edge lane's
|
|
199
211
|
* own default applies (canonical value: `memory.v3.edge.seedCount`). */
|
|
200
212
|
edgeSeeds?: number;
|
|
@@ -359,15 +371,23 @@ export async function orchestrate(
|
|
|
359
371
|
// a vector that matches neither) at its own, smaller budget; it runs in the
|
|
360
372
|
// same parallel batch.
|
|
361
373
|
// `denseK = 0` disables dense retrieval for the whole turn, including the
|
|
362
|
-
// reply-query dense
|
|
374
|
+
// reply-query and span-query dense passes.
|
|
363
375
|
const replyK = deps.replyQueryK ?? 0;
|
|
364
376
|
const replyQuery =
|
|
365
377
|
replyK > 0 ? (turn.previousAssistantMessage ?? "").trim() : "";
|
|
366
378
|
const denseEnabled = denseK > 0;
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
379
|
+
// The span-query pass re-runs the dense lane over the current message's
|
|
380
|
+
// clause chunks as SEPARATE queries (a single embedding of a multi-topic
|
|
381
|
+
// message averages its intents into a vector that matches none of them —
|
|
382
|
+
// the within-message form of the averaging the reply pass avoids across
|
|
383
|
+
// speakers). A single-chunk message would just duplicate the full-message
|
|
384
|
+
// dense query, so the pass needs at least two chunks to run.
|
|
385
|
+
const spanK = deps.spanQueryK ?? 0;
|
|
386
|
+
const spanChunks =
|
|
387
|
+
spanK > 0 && denseEnabled ? spanChunksOf(turn.currentMessage) : [];
|
|
388
|
+
const spanQueries = spanChunks.length >= 2 ? spanChunks : [];
|
|
389
|
+
const [needled, densed, replyNeedled, replyDensed, spanDensed] =
|
|
390
|
+
await timeLatencySubSpan("v3_lanes", "Memory search", () =>
|
|
371
391
|
Promise.all([
|
|
372
392
|
Promise.resolve(deps.needle.queryScored(turn.currentMessage, needleK)),
|
|
373
393
|
denseEnabled
|
|
@@ -381,8 +401,13 @@ export async function orchestrate(
|
|
|
381
401
|
replyQuery.length > 0 && denseEnabled
|
|
382
402
|
? denseLaneScored(deps.denseConfig, replyQuery, replyK)
|
|
383
403
|
: Promise.resolve([]),
|
|
404
|
+
Promise.all(
|
|
405
|
+
spanQueries.map((chunk) =>
|
|
406
|
+
denseLaneScored(deps.denseConfig, chunk, spanK),
|
|
407
|
+
),
|
|
408
|
+
),
|
|
384
409
|
]),
|
|
385
|
-
|
|
410
|
+
);
|
|
386
411
|
// Everything from here to the step-3 selection — finder assembly, the
|
|
387
412
|
// entity lane, the injection gate, edge + learned-edge expansion, pool
|
|
388
413
|
// assembly — is synchronous in-memory work, measured as one `v3_expand`
|
|
@@ -437,18 +462,29 @@ export async function orchestrate(
|
|
|
437
462
|
// Step 1b: dense hits — `section` is the matched ORDINAL; resolve it to the
|
|
438
463
|
// concrete `Section` via the section index. Falls back to undefined (blank
|
|
439
464
|
// descriptor) if the ordinal is not in the in-memory index.
|
|
465
|
+
//
|
|
466
|
+
// `denseOwnedSection` tracks the articles whose recorded matched section
|
|
467
|
+
// came from THIS loop (needle records first and wins ties), along with the
|
|
468
|
+
// hit's cosine score — the span pass upgrades those sections when a clause
|
|
469
|
+
// query finds a strictly stronger match under the same metric.
|
|
470
|
+
const denseOwnedSection = new Map<Slug, number>();
|
|
440
471
|
for (const hit of densed) {
|
|
441
472
|
// A deleted page's points can linger in Qdrant; keep only live-index
|
|
442
473
|
// articles. The section index is rebuilt from `getPageIndex` at `initLanes`,
|
|
443
474
|
// so `byArticle` holds exactly the live pages (synthetic capability slugs
|
|
444
475
|
// included) — only truly-deleted pages are dropped here.
|
|
445
|
-
if (!deps.sectionIndex.byArticle.has(hit.article))
|
|
446
|
-
|
|
476
|
+
if (!deps.sectionIndex.byArticle.has(hit.article)) {
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
const section = sectionByOrdinal(
|
|
480
|
+
deps.sectionIndex,
|
|
447
481
|
hit.article,
|
|
448
|
-
|
|
449
|
-
undefined,
|
|
450
|
-
"dense",
|
|
482
|
+
hit.section,
|
|
451
483
|
);
|
|
484
|
+
if (section && !matchedSections.has(hit.article)) {
|
|
485
|
+
denseOwnedSection.set(hit.article, hit.score);
|
|
486
|
+
}
|
|
487
|
+
addFinder(hit.article, section, undefined, "dense");
|
|
452
488
|
}
|
|
453
489
|
|
|
454
490
|
// Step 1b': reply-query hits — candidates the user-message lanes already
|
|
@@ -469,7 +505,53 @@ export async function orchestrate(
|
|
|
469
505
|
);
|
|
470
506
|
}
|
|
471
507
|
|
|
472
|
-
// Step 1b'':
|
|
508
|
+
// Step 1b'': span-query hits — union-additive at the pass's own small
|
|
509
|
+
// budget. Candidates the primary or reply lanes already surfaced keep their
|
|
510
|
+
// attribution (`addFinder`'s first-lane-wins dedupe); only genuinely
|
|
511
|
+
// span-surfaced articles tag `"span"`. Like the reply pass, span hits are
|
|
512
|
+
// excluded from the injection gate (which scores current-message needle +
|
|
513
|
+
// dense only) and from the edge-expansion seeds.
|
|
514
|
+
//
|
|
515
|
+
// An article can be surfaced by SEVERAL chunks; dedupe by best cosine score
|
|
516
|
+
// before `addFinder`, since chunk order would otherwise decide which section
|
|
517
|
+
// gets recorded — letting an earlier chunk's weak match mask the strong
|
|
518
|
+
// buried-clause match the pass exists to recover.
|
|
519
|
+
const bestSpanHits = new Map<Slug, DenseHitScored>();
|
|
520
|
+
for (const hit of spanDensed.flat()) {
|
|
521
|
+
const prev = bestSpanHits.get(hit.article);
|
|
522
|
+
if (!prev || hit.score > prev.score) {
|
|
523
|
+
bestSpanHits.set(hit.article, hit);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
// For an article a primary lane already surfaced, upgrade its matched
|
|
527
|
+
// section/descriptor ONLY when the existing section was recorded by the
|
|
528
|
+
// full-message dense hit and the span's cosine is strictly higher — same
|
|
529
|
+
// encoder, same collection, so the comparison is evidence, not judgment.
|
|
530
|
+
// Needle- and reply-recorded sections stay (BM25 and cosine scores are not
|
|
531
|
+
// comparable, and the reply pass's own convention is first-wins); lane
|
|
532
|
+
// attribution never changes here.
|
|
533
|
+
for (const hit of bestSpanHits.values()) {
|
|
534
|
+
if (!deps.sectionIndex.byArticle.has(hit.article)) {
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const section = sectionByOrdinal(
|
|
538
|
+
deps.sectionIndex,
|
|
539
|
+
hit.article,
|
|
540
|
+
hit.section,
|
|
541
|
+
);
|
|
542
|
+
const denseScore = denseOwnedSection.get(hit.article);
|
|
543
|
+
if (section && denseScore !== undefined && hit.score > denseScore) {
|
|
544
|
+
matchedSections.set(hit.article, section);
|
|
545
|
+
const existing = finder.find((c) => c.slug === hit.article);
|
|
546
|
+
if (existing) {
|
|
547
|
+
existing.descriptor = section.text;
|
|
548
|
+
}
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
addFinder(hit.article, section, undefined, "span");
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// Step 1b''': entity lane — sections whose `## ` heading NAMES a distinctive
|
|
473
555
|
// entity the message mentions. Additive BM25 buries a single named entity
|
|
474
556
|
// under a long, multi-topic message's bulk theme; this keys on the heading
|
|
475
557
|
// vocabulary so the page the user named surfaces regardless of the bulk
|
|
@@ -501,8 +583,8 @@ export async function orchestrate(
|
|
|
501
583
|
}
|
|
502
584
|
}
|
|
503
585
|
|
|
504
|
-
// Step 1b''': opt-in injection gate. With the CURRENT-message finder lanes in
|
|
505
|
-
// hand (needle + dense — NOT reply/entity/edge, which only add recall), decide
|
|
586
|
+
// Step 1b'''': opt-in injection gate. With the CURRENT-message finder lanes in
|
|
587
|
+
// hand (needle + dense — NOT reply/span/entity/edge, which only add recall), decide
|
|
506
588
|
// whether retrieval is confident enough to spend the selectPool LLM call this
|
|
507
589
|
// turn. Default-off via `?.enabled`; pass-open on any throw (a gate bug must
|
|
508
590
|
// never drop a turn's memory). A closed gate either hard-skips selection
|
|
@@ -733,6 +733,7 @@ export async function observeTurn(
|
|
|
733
733
|
activeSlugs: getActiveSlugs(conversationId),
|
|
734
734
|
entityCap: v3.entity.cap,
|
|
735
735
|
replyQueryK: tuning.replyQueryK,
|
|
736
|
+
spanQueryK: tuning.spanQueryK,
|
|
736
737
|
edgeSeeds: tuning.edgeSeedCount,
|
|
737
738
|
edgePerSeed: tuning.edgePerSeed,
|
|
738
739
|
edgeCap: tuning.edgeCap,
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { MAX_SPAN_CHUNKS, spanChunksOf } from "./span-query.js";
|
|
4
|
+
|
|
5
|
+
describe("spanChunksOf", () => {
|
|
6
|
+
test("short message passes through as its clause spans", () => {
|
|
7
|
+
const chunks = spanChunksOf(
|
|
8
|
+
"the first sentence is here. and a second sentence follows!",
|
|
9
|
+
);
|
|
10
|
+
expect(chunks).toEqual([
|
|
11
|
+
"the first sentence is here.",
|
|
12
|
+
"and a second sentence follows!",
|
|
13
|
+
]);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test("newlines split spans like sentence punctuation", () => {
|
|
17
|
+
const chunks = spanChunksOf(
|
|
18
|
+
"a line without terminal punctuation\nanother line of the message",
|
|
19
|
+
);
|
|
20
|
+
expect(chunks).toEqual([
|
|
21
|
+
"a line without terminal punctuation",
|
|
22
|
+
"another line of the message",
|
|
23
|
+
]);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("sub-15-char fragments are dropped", () => {
|
|
27
|
+
const chunks = spanChunksOf("ok. this sentence is long enough to keep.");
|
|
28
|
+
expect(chunks).toEqual(["this sentence is long enough to keep."]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("empty and whitespace-only messages yield no chunks", () => {
|
|
32
|
+
expect(spanChunksOf("")).toEqual([]);
|
|
33
|
+
expect(spanChunksOf(" \n\n ")).toEqual([]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("fullwidth CJK terminators split without trailing whitespace", () => {
|
|
37
|
+
const chunks = spanChunksOf(
|
|
38
|
+
"这是消息里的第一句完整的话。这是紧跟着的第二句完整的话!第三句也一样长够十五个字符?",
|
|
39
|
+
);
|
|
40
|
+
expect(chunks).toEqual([
|
|
41
|
+
"这是消息里的第一句完整的话。",
|
|
42
|
+
"这是紧跟着的第二句完整的话!",
|
|
43
|
+
"第三句也一样长够十五个字符?",
|
|
44
|
+
]);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("non-ASCII spaced terminators split like ASCII ones", () => {
|
|
48
|
+
const chunks = spanChunksOf(
|
|
49
|
+
"पहला वाक्य यहाँ लिखा गया है। दूसरा वाक्य भी यहाँ मौजूद है।",
|
|
50
|
+
);
|
|
51
|
+
expect(chunks).toEqual([
|
|
52
|
+
"पहला वाक्य यहाँ लिखा गया है।",
|
|
53
|
+
"दूसरा वाक्य भी यहाँ मौजूद है।",
|
|
54
|
+
]);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("ASCII periods still do not split decimals or dotted numbers", () => {
|
|
58
|
+
expect(spanChunksOf("the value came out to 3.14159 in the final run.")) //
|
|
59
|
+
.toEqual(["the value came out to 3.14159 in the final run."]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("a message at the cap is returned unchanged", () => {
|
|
63
|
+
const sentences = Array.from(
|
|
64
|
+
{ length: MAX_SPAN_CHUNKS },
|
|
65
|
+
(_, i) => `sentence number ${i} padded for length.`,
|
|
66
|
+
);
|
|
67
|
+
expect(spanChunksOf(sentences.join(" "))).toEqual(sentences);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("over-cap messages merge into ≤cap contiguous chunks covering every span", () => {
|
|
71
|
+
const sentences = Array.from(
|
|
72
|
+
{ length: 30 },
|
|
73
|
+
(_, i) => `sentence number ${i} padded for length.`,
|
|
74
|
+
);
|
|
75
|
+
const chunks = spanChunksOf(sentences.join(" "));
|
|
76
|
+
expect(chunks.length).toBe(MAX_SPAN_CHUNKS);
|
|
77
|
+
// Contiguous coverage: rejoining the chunks reproduces every span in order.
|
|
78
|
+
expect(chunks.join(" ")).toBe(sentences.join(" "));
|
|
79
|
+
// Near-equal partition: no chunk hoards spans (30/8 → sizes 3 or 4).
|
|
80
|
+
for (const chunk of chunks) {
|
|
81
|
+
const n = chunk.match(/sentence number/g)?.length ?? 0;
|
|
82
|
+
expect(n).toBeGreaterThanOrEqual(3);
|
|
83
|
+
expect(n).toBeLessThanOrEqual(4);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory v3 — deterministic clause chunking for the span-query dense pass.
|
|
3
|
+
*
|
|
4
|
+
* A single embedding of a long, multi-topic message averages its distinct
|
|
5
|
+
* retrieval intents into one vector that matches none of them — the
|
|
6
|
+
* within-message form of the cross-speaker averaging the reply-query pass
|
|
7
|
+
* exists to avoid. The span pass re-runs the dense lane over the message's
|
|
8
|
+
* clause spans as separate queries so a motif buried in one clause retrieves
|
|
9
|
+
* at full strength.
|
|
10
|
+
*
|
|
11
|
+
* Chunking is pure text processing: split at newlines and sentence
|
|
12
|
+
* punctuation, drop fragments below {@link MIN_SPAN_WEIGHT}. A message yielding
|
|
13
|
+
* more than {@link MAX_SPAN_CHUNKS} spans is NOT truncated to its head — all
|
|
14
|
+
* spans are partitioned into {@link MAX_SPAN_CHUNKS} contiguous near-equal
|
|
15
|
+
* groups, so the whole message stays covered and long messages are simply
|
|
16
|
+
* queried at paragraph grain instead of clause grain.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Hard cap on span chunks per message — bounds the pass at
|
|
20
|
+
* `MAX_SPAN_CHUNKS × spanQueryK` extra candidates and as many embed calls. */
|
|
21
|
+
export const MAX_SPAN_CHUNKS = 8;
|
|
22
|
+
|
|
23
|
+
/** Spans weighing less than this carry no retrieval signal ("ok.", bare emoji
|
|
24
|
+
* lines) and are dropped before chunking. Weight, not raw length — see
|
|
25
|
+
* {@link spanWeight}. */
|
|
26
|
+
const MIN_SPAN_WEIGHT = 15;
|
|
27
|
+
|
|
28
|
+
/** Dense CJK scripts pack roughly a clause into the character budget English
|
|
29
|
+
* needs for a few words, so a raw char floor tuned for spaced scripts would
|
|
30
|
+
* drop nearly every realistic Chinese/Japanese/Korean sentence. Weigh those
|
|
31
|
+
* chars at 3× so the floor measures comparable information content. */
|
|
32
|
+
const DENSE_SCRIPT = /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Hangul}]/u;
|
|
33
|
+
|
|
34
|
+
function spanWeight(span: string): number {
|
|
35
|
+
let weight = 0;
|
|
36
|
+
for (const ch of span) {
|
|
37
|
+
weight += DENSE_SCRIPT.test(ch) ? 3 : 1;
|
|
38
|
+
}
|
|
39
|
+
return weight;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Split `message` into at most {@link MAX_SPAN_CHUNKS} contiguous clause
|
|
44
|
+
* chunks. Messages with that many spans or fewer return them unchanged;
|
|
45
|
+
* longer messages merge adjacent spans into near-equal groups covering the
|
|
46
|
+
* whole message. Deterministic; returns `[]` for empty/whitespace input.
|
|
47
|
+
*/
|
|
48
|
+
export function spanChunksOf(message: string): string[] {
|
|
49
|
+
// Boundaries: newlines; any Unicode sentence terminator (`\p{STerm}` covers
|
|
50
|
+
// ASCII `.!?` plus CJK `。!?`, Arabic `؟`, Devanagari `।`, …) or ellipsis
|
|
51
|
+
// followed by whitespace; and a zero-width split after fullwidth CJK
|
|
52
|
+
// terminators, which conventionally have NO trailing space. The whitespace
|
|
53
|
+
// requirement on the general arm keeps ASCII `.` from splitting decimals
|
|
54
|
+
// and dotted abbreviations; fullwidth terminators never appear there.
|
|
55
|
+
const spans = message
|
|
56
|
+
.split(/\n+|(?<=[\p{STerm}…])\s+|(?<=[。!?。])/u)
|
|
57
|
+
.map((s) => s.trim())
|
|
58
|
+
.filter((s) => spanWeight(s) >= MIN_SPAN_WEIGHT);
|
|
59
|
+
if (spans.length <= MAX_SPAN_CHUNKS) {
|
|
60
|
+
return spans;
|
|
61
|
+
}
|
|
62
|
+
const chunks: string[] = [];
|
|
63
|
+
for (let i = 0; i < MAX_SPAN_CHUNKS; i++) {
|
|
64
|
+
const lo = Math.floor((i * spans.length) / MAX_SPAN_CHUNKS);
|
|
65
|
+
const hi = Math.floor(((i + 1) * spans.length) / MAX_SPAN_CHUNKS);
|
|
66
|
+
if (hi > lo) {
|
|
67
|
+
chunks.push(spans.slice(lo, hi).join(" "));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return chunks;
|
|
71
|
+
}
|
|
@@ -28,6 +28,7 @@ export interface ResolvedV3Tuning {
|
|
|
28
28
|
needleK: number;
|
|
29
29
|
denseK: number;
|
|
30
30
|
replyQueryK: number;
|
|
31
|
+
spanQueryK: number;
|
|
31
32
|
selectorEnabled: boolean;
|
|
32
33
|
learnedEdgesCap: number;
|
|
33
34
|
edgeSeedCount: number;
|
|
@@ -55,6 +56,7 @@ export const MEMORY_V3_NEW_USER_TUNING: ResolvedV3Tuning = {
|
|
|
55
56
|
needleK: 12,
|
|
56
57
|
denseK: 0,
|
|
57
58
|
replyQueryK: 0,
|
|
59
|
+
spanQueryK: 0,
|
|
58
60
|
selectorEnabled: false,
|
|
59
61
|
learnedEdgesCap: 0,
|
|
60
62
|
edgeSeedCount: 6,
|
|
@@ -82,6 +84,7 @@ export function resolveV3Tuning(
|
|
|
82
84
|
needleK: v3.needleK,
|
|
83
85
|
denseK: v3.denseK,
|
|
84
86
|
replyQueryK: v3.replyQueryK,
|
|
87
|
+
spanQueryK: v3.spanQueryK,
|
|
85
88
|
selectorEnabled: v3.selectorEnabled,
|
|
86
89
|
learnedEdgesCap: v3.learnedEdges.cap,
|
|
87
90
|
edgeSeedCount: v3.edge.seedCount,
|
|
@@ -96,7 +96,9 @@ export interface MemoryRoutingTurn {
|
|
|
96
96
|
* frecency hot set, modification-recency fresh set); `needle` / `dense` /
|
|
97
97
|
* `edge` are the per-turn finder lanes over the user's message; `reply` marks
|
|
98
98
|
* finder candidates first surfaced by the reply-query pass (needle + dense
|
|
99
|
-
* re-run over the assistant's previous message); `
|
|
99
|
+
* re-run over the assistant's previous message); `span` marks candidates first
|
|
100
|
+
* surfaced by the span-query pass (dense re-run over the current message's
|
|
101
|
+
* clause chunks as separate queries); `learned` marks candidates
|
|
100
102
|
* surfaced by the co-selection NPMI association graph; `entity` marks
|
|
101
103
|
* candidates surfaced because the message named an entity that titles a section
|
|
102
104
|
* heading (the heading-anchored entity lane).
|
|
@@ -114,6 +116,7 @@ export const SELECTION_SOURCES = [
|
|
|
114
116
|
"dense",
|
|
115
117
|
"edge",
|
|
116
118
|
"reply",
|
|
119
|
+
"span",
|
|
117
120
|
"learned",
|
|
118
121
|
"entity",
|
|
119
122
|
] as const;
|