@vellumai/assistant 0.10.12-dev.202607250047.75b9ec6 → 0.10.12-dev.202607250309.e24b258
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/__tests__/request-secret-standalone-channel-gate.test.ts +2 -2
- package/src/config/feature-flag-registry.json +0 -24
- package/src/config/schemas/__tests__/memory-v3.test.ts +1 -0
- package/src/config/schemas/memory-v3.ts +11 -4
- 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__/shadow-plugin.test.ts +10 -35
- package/src/plugins/defaults/memory/v3/__tests__/tuning-profile.test.ts +1 -0
- package/src/plugins/defaults/memory/v3/gate.ts +4 -4
- package/src/plugins/defaults/memory/v3/orchestrate.ts +100 -18
- package/src/plugins/defaults/memory/v3/shadow-plugin.ts +5 -10
- 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/src/runtime/routes/credential-request-routes.ts +0 -1
- package/src/plugins/defaults/memory/v3/__tests__/gate-flag.test.ts +0 -69
- package/src/plugins/defaults/memory/v3/gate-flag.ts +0 -20
package/package.json
CHANGED
|
@@ -177,11 +177,11 @@ describe("requestSecretStandalone channel gate", () => {
|
|
|
177
177
|
});
|
|
178
178
|
|
|
179
179
|
test("falls back to a plain unsupported_channel when minting is refused", async () => {
|
|
180
|
-
// GIVEN the gateway refuses to mint (
|
|
180
|
+
// GIVEN the gateway refuses to mint (no public URL)
|
|
181
181
|
registeredConversation = {
|
|
182
182
|
channelCapabilities: { supportsDynamicUi: false },
|
|
183
183
|
};
|
|
184
|
-
gatewayMintResult = { ok: false, error: "
|
|
184
|
+
gatewayMintResult = { ok: false, error: "no_public_base_url" };
|
|
185
185
|
|
|
186
186
|
// WHEN a standalone prompt is scoped to that conversation
|
|
187
187
|
const result = await requestSecretStandalone({
|
|
@@ -293,14 +293,6 @@
|
|
|
293
293
|
"description": "Expose the developer-only Memory Router Playground tab in macOS Settings and the /assistant/memory-router-playground web page for dry-running v4 router config overrides against the live page index. Dev-only; default off.",
|
|
294
294
|
"defaultEnabled": false
|
|
295
295
|
},
|
|
296
|
-
{
|
|
297
|
-
"id": "memory-v3-injection-gate",
|
|
298
|
-
"scope": "assistant",
|
|
299
|
-
"key": "memory-v3-injection-gate",
|
|
300
|
-
"label": "Memory v3 injection gate",
|
|
301
|
-
"description": "Per-turn injection gate for memory v3: after the BM25F needle + dense cosine finder lanes run, skip the selectPool LLM call (inject nothing) when finder-lane scores fall below the configured thresholds (memory.v3.gate). Default on (flipped remotely July 2026); this registry value is the fallback when no platform snapshot is available.",
|
|
302
|
-
"defaultEnabled": true
|
|
303
|
-
},
|
|
304
296
|
{
|
|
305
297
|
"id": "self-intro-greeting",
|
|
306
298
|
"scope": "both",
|
|
@@ -349,22 +341,6 @@
|
|
|
349
341
|
"description": "Surface the Security settings page where users enroll and manage TOTP two-factor authentication for their Vellum (WorkOS) account. Applies to email/password sign-in only.",
|
|
350
342
|
"defaultEnabled": false
|
|
351
343
|
},
|
|
352
|
-
{
|
|
353
|
-
"id": "credentials-settings",
|
|
354
|
-
"scope": "assistant",
|
|
355
|
-
"key": "credentials-settings",
|
|
356
|
-
"label": "Credentials settings page",
|
|
357
|
-
"description": "Show the Credentials page in web settings for listing, adding, and deleting stored credentials.",
|
|
358
|
-
"defaultEnabled": false
|
|
359
|
-
},
|
|
360
|
-
{
|
|
361
|
-
"id": "credential-requests",
|
|
362
|
-
"scope": "assistant",
|
|
363
|
-
"key": "credential-requests",
|
|
364
|
-
"label": "One-time credential request links",
|
|
365
|
-
"description": "Enable one-time credential-request links: the generate-link action in settings, the public credential entry page, and assistant-initiated links on channels without secure input.",
|
|
366
|
-
"defaultEnabled": false
|
|
367
|
-
},
|
|
368
344
|
{
|
|
369
345
|
"id": "chat-credential-reveal",
|
|
370
346
|
"scope": "assistant",
|
|
@@ -252,8 +252,7 @@ export const MemoryV3EntitySchema = z
|
|
|
252
252
|
/**
|
|
253
253
|
* Per-turn injection-gate tuning: thresholds the retrieval signals must clear
|
|
254
254
|
* for the gate to open and run the selector. The gate runs only when the
|
|
255
|
-
* `
|
|
256
|
-
* `enabled` kill-switch below are both on.
|
|
255
|
+
* `enabled` kill-switch below is on.
|
|
257
256
|
*/
|
|
258
257
|
export const MemoryV3GateSchema = z
|
|
259
258
|
.object({
|
|
@@ -261,7 +260,7 @@ export const MemoryV3GateSchema = z
|
|
|
261
260
|
.boolean({ error: "memory.v3.gate.enabled must be a boolean" })
|
|
262
261
|
.default(true)
|
|
263
262
|
.describe(
|
|
264
|
-
"Whether the injection gate may run at all. false forces the full selection process every turn
|
|
263
|
+
"Whether the injection gate may run at all. false forces the full selection process every turn; true (default) lets the gate run when the thresholds are met.",
|
|
265
264
|
),
|
|
266
265
|
denseThreshold: z
|
|
267
266
|
.number({ error: "memory.v3.gate.denseThreshold must be a number" })
|
|
@@ -327,7 +326,7 @@ export const MemoryV3GateSchema = z
|
|
|
327
326
|
),
|
|
328
327
|
})
|
|
329
328
|
.describe(
|
|
330
|
-
"Memory v3 per-turn injection gate tuning (thresholds; the gate runs when
|
|
329
|
+
"Memory v3 per-turn injection gate tuning (thresholds; the gate runs when `enabled` is on).",
|
|
331
330
|
);
|
|
332
331
|
|
|
333
332
|
// NOTE: a retired `workingSet` sub-config (maxPages/evictWindow for the old
|
|
@@ -383,6 +382,14 @@ export const MemoryV3ConfigSchema = z
|
|
|
383
382
|
.describe(
|
|
384
383
|
"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
384
|
),
|
|
385
|
+
spanQueryK: z
|
|
386
|
+
.number({ error: "memory.v3.spanQueryK must be a number" })
|
|
387
|
+
.int("memory.v3.spanQueryK must be an integer")
|
|
388
|
+
.nonnegative("memory.v3.spanQueryK must be a non-negative integer")
|
|
389
|
+
.default(0)
|
|
390
|
+
.describe(
|
|
391
|
+
"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.",
|
|
392
|
+
),
|
|
386
393
|
selectorEnabled: z
|
|
387
394
|
.boolean({ error: "memory.v3.selectorEnabled must be a boolean" })
|
|
388
395
|
.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
|
},
|
|
@@ -102,9 +102,6 @@ let extraRealConceptPages = 0;
|
|
|
102
102
|
// Mutable mocked config knob (orchestrate-only) for asserting per-turn tuning
|
|
103
103
|
// re-resolution from a live config edit.
|
|
104
104
|
let selectorEnabledCfg = false;
|
|
105
|
-
// Drives the `memory-v3-injection-gate` feature flag through the shared
|
|
106
|
-
// assistant-feature-flags mock below (default off).
|
|
107
|
-
let gateFlagEnabled = false;
|
|
108
105
|
// Mutable `memory.v3.gate.enabled` config kill-switch carried by the mocked
|
|
109
106
|
// config (default on, mirroring the schema default).
|
|
110
107
|
let gateEnabledCfg = true;
|
|
@@ -112,8 +109,7 @@ let messages: Array<{ role: string; content: string }> = [];
|
|
|
112
109
|
|
|
113
110
|
// Schema defaults for `memory.v3.gate` (the tuning the mocked config carries
|
|
114
111
|
// and the gate-config threading test asserts against). Includes the default-on
|
|
115
|
-
// `enabled` kill-switch
|
|
116
|
-
// flag AND config value.
|
|
112
|
+
// `enabled` kill-switch that `observeTurn` threads through to orchestrate.
|
|
117
113
|
const GATE_DEFAULTS = MemoryV3GateSchema.parse({});
|
|
118
114
|
|
|
119
115
|
// A synthetic skill capability slug the page index carries. Its rendered
|
|
@@ -217,11 +213,7 @@ const FAKE_SECTION_INDEX: SectionIndex = {
|
|
|
217
213
|
|
|
218
214
|
mock.module("../../../../../config/assistant-feature-flags.js", () => ({
|
|
219
215
|
isAssistantFeatureFlagEnabled: (key: string) =>
|
|
220
|
-
key === "memory-v3-live"
|
|
221
|
-
? liveEnabled
|
|
222
|
-
: key === "memory-v3-injection-gate"
|
|
223
|
-
? gateFlagEnabled
|
|
224
|
-
: false,
|
|
216
|
+
key === "memory-v3-live" ? liveEnabled : false,
|
|
225
217
|
}));
|
|
226
218
|
|
|
227
219
|
// `observeTurn` and the injector resolve their tuning through the real
|
|
@@ -251,9 +243,8 @@ function seedMemoryConfig(): void {
|
|
|
251
243
|
},
|
|
252
244
|
edge: { hubDegree: 30, seedCount: 6, perSeed: 1, cap: 6 },
|
|
253
245
|
entity: { enabled: true, idfFloor: 4, cap: 8 },
|
|
254
|
-
// Gate tuning (schema defaults) with the mutable `enabled` kill-switch
|
|
255
|
-
//
|
|
256
|
-
// flag AND config value before passing to orchestrate.
|
|
246
|
+
// Gate tuning (schema defaults) with the mutable `enabled` kill-switch,
|
|
247
|
+
// threaded through to orchestrate as-is.
|
|
257
248
|
gate: { ...GATE_DEFAULTS, enabled: gateEnabledCfg },
|
|
258
249
|
},
|
|
259
250
|
qdrant: { vectorSize: 8, onDisk: false },
|
|
@@ -523,7 +514,6 @@ beforeEach(() => {
|
|
|
523
514
|
learnedEdgesCap = 0;
|
|
524
515
|
extraRealConceptPages = 0;
|
|
525
516
|
selectorEnabledCfg = false;
|
|
526
|
-
gateFlagEnabled = false;
|
|
527
517
|
gateEnabledCfg = true;
|
|
528
518
|
messages = [
|
|
529
519
|
{
|
|
@@ -775,41 +765,26 @@ describe("memory-v3 engine", () => {
|
|
|
775
765
|
expect(secondDeps.selectorEnabled).toBe(true);
|
|
776
766
|
});
|
|
777
767
|
|
|
778
|
-
test("
|
|
779
|
-
gateFlagEnabled = true;
|
|
768
|
+
test("gate enabled (default) → threads the gate tuning plus enabled:true into orchestrate", async () => {
|
|
780
769
|
await observeTurn("conv-1", 0);
|
|
781
770
|
|
|
782
771
|
const deps = (
|
|
783
772
|
orchestrateSpy.mock.calls as unknown as unknown[][]
|
|
784
773
|
)[0]![1] as { gateConfig?: unknown };
|
|
785
|
-
// The
|
|
786
|
-
//
|
|
774
|
+
// The live gate config is the `memory.v3.gate` tuning, including the
|
|
775
|
+
// default-on `enabled` kill-switch.
|
|
787
776
|
expect(deps.gateConfig).toEqual({ ...GATE_DEFAULTS, enabled: true });
|
|
788
777
|
});
|
|
789
778
|
|
|
790
|
-
test("
|
|
791
|
-
// gateFlagEnabled defaults to false in beforeEach.
|
|
792
|
-
await observeTurn("conv-1", 0);
|
|
793
|
-
|
|
794
|
-
const deps = (
|
|
795
|
-
orchestrateSpy.mock.calls as unknown as unknown[][]
|
|
796
|
-
)[0]![1] as { gateConfig?: { enabled?: boolean } };
|
|
797
|
-
// Flag off → the gate is wired in but inert, and the tuning fields are the
|
|
798
|
-
// schema defaults the config carries.
|
|
799
|
-
expect(deps.gateConfig?.enabled).toBe(false);
|
|
800
|
-
expect(deps.gateConfig).toEqual({ ...GATE_DEFAULTS, enabled: false });
|
|
801
|
-
});
|
|
802
|
-
|
|
803
|
-
test("flag on + gate.enabled:false config kill-switch → gate threads inert", async () => {
|
|
804
|
-
gateFlagEnabled = true;
|
|
779
|
+
test("gate.enabled:false config kill-switch → gate threads inert", async () => {
|
|
805
780
|
gateEnabledCfg = false;
|
|
806
781
|
await observeTurn("conv-1", 0);
|
|
807
782
|
|
|
808
783
|
const deps = (
|
|
809
784
|
orchestrateSpy.mock.calls as unknown as unknown[][]
|
|
810
785
|
)[0]![1] as { gateConfig?: unknown };
|
|
811
|
-
// The
|
|
812
|
-
//
|
|
786
|
+
// The kill-switch makes the effective `enabled` false, so selection
|
|
787
|
+
// always runs.
|
|
813
788
|
expect(deps.gateConfig).toEqual({ ...GATE_DEFAULTS, enabled: false });
|
|
814
789
|
});
|
|
815
790
|
|
|
@@ -17,9 +17,9 @@
|
|
|
17
17
|
// regardless of how the thresholds are tuned.
|
|
18
18
|
//
|
|
19
19
|
// This module is intentionally PURE — no async, no I/O, no logging, and no
|
|
20
|
-
// imports beyond the two scored-hit types. `config.enabled` is the
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// imports beyond the two scored-hit types. `config.enabled` is the
|
|
21
|
+
// `memory.v3.gate.enabled` kill-switch supplied by the caller, which also
|
|
22
|
+
// feeds in the finder-lane hits.
|
|
23
23
|
|
|
24
24
|
import type { DenseHitScored } from "./dense.js";
|
|
25
25
|
import type { SectionNeedleScoredHit } from "./section-needle.js";
|
|
@@ -37,7 +37,7 @@ export type V3GateReason =
|
|
|
37
37
|
| "disabled";
|
|
38
38
|
|
|
39
39
|
export interface V3GateConfig {
|
|
40
|
-
enabled: boolean; //
|
|
40
|
+
enabled: boolean; // the `memory.v3.gate.enabled` kill-switch, threaded through by observeTurn
|
|
41
41
|
denseThreshold: number;
|
|
42
42
|
sparseThreshold: number;
|
|
43
43
|
sparseOnlyThreshold: number;
|
|
@@ -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;
|
|
@@ -220,9 +232,9 @@ export interface OrchestrateDeps {
|
|
|
220
232
|
/** Whether to run the selector LLM. False passes all pooled candidates
|
|
221
233
|
* straight through as selections, preserving pool-order slug dedup. */
|
|
222
234
|
selectorEnabled?: boolean;
|
|
223
|
-
/** Per-turn injection gate config (`memory.v3.gate` tuning
|
|
224
|
-
*
|
|
225
|
-
*
|
|
235
|
+
/** Per-turn injection gate config (the `memory.v3.gate` tuning, threaded
|
|
236
|
+
* through by observeTurn). Omitted/disabled → the gate never runs and every
|
|
237
|
+
* turn proceeds to selectPool as before. */
|
|
226
238
|
gateConfig?: V3GateConfig;
|
|
227
239
|
/** Real concept-page count at lane build — the same corpus-size signal
|
|
228
240
|
* `resolveV3Tuning` switches the lean/full profile on. Reported with each
|
|
@@ -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
|
|
@@ -53,7 +53,6 @@ import type { EntityIndex } from "./entity-lane.js";
|
|
|
53
53
|
import { buildEntityIndex } from "./entity-lane.js";
|
|
54
54
|
import { getActiveSlugs } from "./ever-injected-store.js";
|
|
55
55
|
import { computeFreshSet } from "./fresh-set.js";
|
|
56
|
-
import { isMemoryV3InjectionGateEnabled } from "./gate-flag.js";
|
|
57
56
|
import { computeHotSet } from "./hot-set.js";
|
|
58
57
|
import { bumpLanesVersion, readLanesVersion } from "./lanes-version-store.js";
|
|
59
58
|
import { computeLearnedEdgeGraph } from "./learned-edges.js";
|
|
@@ -702,10 +701,6 @@ export async function observeTurn(
|
|
|
702
701
|
() => getLanes(cfg),
|
|
703
702
|
);
|
|
704
703
|
const v3 = cfg.memory.v3;
|
|
705
|
-
// Resolve the effective gate enable once for the turn: the feature flag
|
|
706
|
-
// AND the `memory.v3.gate.enabled` config kill-switch. Tuning lives in
|
|
707
|
-
// `memory.v3.gate`.
|
|
708
|
-
const gateEnabled = isMemoryV3InjectionGateEnabled(cfg);
|
|
709
704
|
// Re-resolve the corpus-adaptive tuning each turn from the CURRENT config
|
|
710
705
|
// (with the lane-build corpus-size signal) so a live config.json edit to a
|
|
711
706
|
// per-turn knob (selectorEnabled, denseK, replyQueryK, edge.*) takes effect
|
|
@@ -733,6 +728,7 @@ export async function observeTurn(
|
|
|
733
728
|
activeSlugs: getActiveSlugs(conversationId),
|
|
734
729
|
entityCap: v3.entity.cap,
|
|
735
730
|
replyQueryK: tuning.replyQueryK,
|
|
731
|
+
spanQueryK: tuning.spanQueryK,
|
|
736
732
|
edgeSeeds: tuning.edgeSeedCount,
|
|
737
733
|
edgePerSeed: tuning.edgePerSeed,
|
|
738
734
|
edgeCap: tuning.edgeCap,
|
|
@@ -744,11 +740,10 @@ export async function observeTurn(
|
|
|
744
740
|
v3.selectorPromptPath,
|
|
745
741
|
getWorkspaceDir(),
|
|
746
742
|
),
|
|
747
|
-
// Per-turn injection gate: the `memory.v3.gate` tuning
|
|
748
|
-
//
|
|
749
|
-
//
|
|
750
|
-
|
|
751
|
-
gateConfig: { ...v3.gate, enabled: gateEnabled },
|
|
743
|
+
// Per-turn injection gate: the `memory.v3.gate` tuning, `enabled`
|
|
744
|
+
// kill-switch included. Read-only downstream, so the config object is
|
|
745
|
+
// passed as-is.
|
|
746
|
+
gateConfig: v3.gate,
|
|
752
747
|
});
|
|
753
748
|
|
|
754
749
|
// A zero-selection turn over a non-trivial pool is unusual enough to be
|
|
@@ -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;
|
|
@@ -25,7 +25,6 @@ type GatewayMintResult =
|
|
|
25
25
|
| { ok: false; error: string };
|
|
26
26
|
|
|
27
27
|
const MINT_ERROR_MESSAGES: Record<string, string> = {
|
|
28
|
-
flag_disabled: "One-time credential links are not enabled",
|
|
29
28
|
no_public_base_url:
|
|
30
29
|
"No public ingress URL is configured — set ingress.publicBaseUrl first",
|
|
31
30
|
rate_limited: "Too many credential links created — try again in a minute",
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for `gate-flag.ts` — the on/off predicate gating the memory-v3
|
|
3
|
-
* per-turn injection gate. The assistant flag resolver is mocked so the test
|
|
4
|
-
* asserts the composition: the predicate forwards `MEMORY_V3_INJECTION_GATE_FLAG`
|
|
5
|
-
* and the config to `isAssistantFeatureFlagEnabled` and ANDs its boolean with
|
|
6
|
-
* the `memory.v3.gate.enabled` config kill-switch.
|
|
7
|
-
*/
|
|
8
|
-
import { beforeEach, describe, expect, mock, test } from "bun:test";
|
|
9
|
-
|
|
10
|
-
import type { AssistantConfig } from "../../../../../config/schema.js";
|
|
11
|
-
|
|
12
|
-
// The resolver is mocked BEFORE importing the module under test so the import
|
|
13
|
-
// observes the spy at load time. The specifier is resolved relative to THIS
|
|
14
|
-
// test file (one level deeper than gate-flag.ts's own import path).
|
|
15
|
-
const isAssistantFeatureFlagEnabled = mock(
|
|
16
|
-
(_flag: string, _config: AssistantConfig): boolean => false,
|
|
17
|
-
);
|
|
18
|
-
|
|
19
|
-
mock.module("../../../../../config/assistant-feature-flags.js", () => ({
|
|
20
|
-
isAssistantFeatureFlagEnabled,
|
|
21
|
-
}));
|
|
22
|
-
|
|
23
|
-
const { isMemoryV3InjectionGateEnabled, MEMORY_V3_INJECTION_GATE_FLAG } =
|
|
24
|
-
await import("../gate-flag.js");
|
|
25
|
-
|
|
26
|
-
// The predicate reads only `memory.v3.gate.enabled` from the config.
|
|
27
|
-
const cfgWithGateEnabled = (enabled: boolean): AssistantConfig =>
|
|
28
|
-
({ memory: { v3: { gate: { enabled } } } }) as AssistantConfig;
|
|
29
|
-
|
|
30
|
-
describe("gate-flag", () => {
|
|
31
|
-
beforeEach(() => {
|
|
32
|
-
isAssistantFeatureFlagEnabled.mockReset();
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
test("constant is the kebab-case flag id", () => {
|
|
36
|
-
expect(MEMORY_V3_INJECTION_GATE_FLAG).toBe("memory-v3-injection-gate");
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
test("flag on + config enabled → true, resolver called with the flag id + config", () => {
|
|
40
|
-
isAssistantFeatureFlagEnabled.mockReturnValue(true);
|
|
41
|
-
|
|
42
|
-
const cfg = cfgWithGateEnabled(true);
|
|
43
|
-
expect(isMemoryV3InjectionGateEnabled(cfg)).toBe(true);
|
|
44
|
-
expect(isAssistantFeatureFlagEnabled).toHaveBeenCalledTimes(1);
|
|
45
|
-
expect(isAssistantFeatureFlagEnabled).toHaveBeenCalledWith(
|
|
46
|
-
MEMORY_V3_INJECTION_GATE_FLAG,
|
|
47
|
-
cfg,
|
|
48
|
-
);
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
test("returns false when the resolver returns false", () => {
|
|
52
|
-
isAssistantFeatureFlagEnabled.mockReturnValue(false);
|
|
53
|
-
|
|
54
|
-
const cfg = cfgWithGateEnabled(true);
|
|
55
|
-
expect(isMemoryV3InjectionGateEnabled(cfg)).toBe(false);
|
|
56
|
-
expect(isAssistantFeatureFlagEnabled).toHaveBeenCalledWith(
|
|
57
|
-
MEMORY_V3_INJECTION_GATE_FLAG,
|
|
58
|
-
cfg,
|
|
59
|
-
);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
test("config kill-switch: flag on + gate.enabled false → false", () => {
|
|
63
|
-
isAssistantFeatureFlagEnabled.mockReturnValue(true);
|
|
64
|
-
|
|
65
|
-
expect(isMemoryV3InjectionGateEnabled(cfgWithGateEnabled(false))).toBe(
|
|
66
|
-
false,
|
|
67
|
-
);
|
|
68
|
-
});
|
|
69
|
-
});
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { isAssistantFeatureFlagEnabled } from "../../../../config/assistant-feature-flags.js";
|
|
2
|
-
import type { AssistantConfig } from "../../../../config/schema.js";
|
|
3
|
-
|
|
4
|
-
/** Feature-flag id (kebab-case) gating the memory-v3 per-turn injection gate. */
|
|
5
|
-
export const MEMORY_V3_INJECTION_GATE_FLAG =
|
|
6
|
-
"memory-v3-injection-gate" as const;
|
|
7
|
-
|
|
8
|
-
/** Whether the memory-v3 injection gate is enabled for this config: the
|
|
9
|
-
* feature flag (resolved via the standard assistant flag resolver — gateway
|
|
10
|
-
* override → registry default → false) AND the `memory.v3.gate.enabled`
|
|
11
|
-
* config kill-switch. `enabled: false` forces the full selection process
|
|
12
|
-
* every turn even with the flag on. Thresholds live in `memory.v3.gate`. */
|
|
13
|
-
export function isMemoryV3InjectionGateEnabled(
|
|
14
|
-
config: AssistantConfig,
|
|
15
|
-
): boolean {
|
|
16
|
-
return (
|
|
17
|
-
isAssistantFeatureFlagEnabled(MEMORY_V3_INJECTION_GATE_FLAG, config) &&
|
|
18
|
-
config.memory.v3.gate.enabled
|
|
19
|
-
);
|
|
20
|
-
}
|