dsh-cross-memory 0.2.9 → 0.2.11
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/lib/client.js +5 -0
- package/lib/config.js +9 -0
- package/lib/dense.js +180 -0
- package/lib/index.js +98 -6
- package/lib/sync.js +3 -0
- package/lib/test/bm25.test.js +108 -0
- package/lib/test/caught-up.test.js +84 -0
- package/lib/test/dense.test.js +49 -0
- package/lib/types/config.d.ts +9 -0
- package/lib/types/dense.d.ts +53 -0
- package/lib/types/index.d.ts +6 -0
- package/lib/types/test/bm25.test.d.ts +1 -0
- package/lib/types/test/caught-up.test.d.ts +1 -0
- package/lib/types/test/dense.test.d.ts +1 -0
- package/package.json +1 -1
package/lib/client.js
CHANGED
|
@@ -303,6 +303,11 @@ window.__ModuleLoader__.load({
|
|
|
303
303
|
label: { zh: '全量检索会话数上限', en: 'Session logs opened per recall' },
|
|
304
304
|
hint: { zh: '全量检索最多打开几份 session 日志(按最近修改排序);0 等于关闭。', en: 'How many session logs full-history retrieval may open, newest first. 0 disables it.' },
|
|
305
305
|
},
|
|
306
|
+
{
|
|
307
|
+
field: 'denseEnabled', kind: 'boolean',
|
|
308
|
+
label: { zh: '语义召回通道', en: 'Dense recall channel' },
|
|
309
|
+
hint: { zh: '在词法排序之上加一路本地嵌入(RRF 融合),补「和提问没有共同词但语义相关」的记忆。需要本机运行 ollama(qwen3-embedding:0.6b);服务不可用时自动退回词法,不影响补注。默认关闭。', en: 'Adds a local embedding channel (RRF-fused with BM25) for memories that share no word with the turn but are about it. Needs ollama running locally (qwen3-embedding:0.6b); when the service is unreachable the recall silently stays lexical. Off by default.' },
|
|
310
|
+
},
|
|
306
311
|
{
|
|
307
312
|
field: 'recallMinQueryChars', kind: 'number', min: 0, step: 1,
|
|
308
313
|
label: { zh: '触发补注的最短发问长度', en: 'Shortest turn worth recalling' },
|
package/lib/config.js
CHANGED
|
@@ -218,6 +218,12 @@ export const DEFAULT_RAG_RECALL_BYTES = 12_000;
|
|
|
218
218
|
export const DEFAULT_RAG_RECALL_EXCERPTS = 6;
|
|
219
219
|
export const DEFAULT_RAG_RECALL_SESSIONS = 0;
|
|
220
220
|
export const DEFAULT_RAG_RECALL_CHARS = 2_000;
|
|
221
|
+
/** Dense ranking is opt-in: it needs a local embedding service on every machine that recalls. */
|
|
222
|
+
export const DEFAULT_DENSE_ENABLED = false;
|
|
223
|
+
/** Ollama's default endpoint; the plugin never calls outside the machine unless this is changed. */
|
|
224
|
+
export const DEFAULT_DENSE_URL = 'http://127.0.0.1:11434';
|
|
225
|
+
/** The model the bench measured (1024 dimensions). */
|
|
226
|
+
export const DEFAULT_DENSE_MODEL = 'qwen3-embedding:0.6b';
|
|
221
227
|
/**
|
|
222
228
|
* Default number of distinct strong-field terms a recall needs.
|
|
223
229
|
*
|
|
@@ -428,6 +434,7 @@ export const Config = z.object({
|
|
|
428
434
|
ragRecallExcerpts: z.number().default(DEFAULT_RAG_RECALL_EXCERPTS).description('Most full-history excerpts one recall block may carry.').volatile(),
|
|
429
435
|
ragRecallSessions: z.number().default(DEFAULT_RAG_RECALL_SESSIONS).description('How many session logs the full-history retrieval may open per recall, newest first. 0 opens all of them.').volatile(),
|
|
430
436
|
ragRecallChars: z.number().default(DEFAULT_RAG_RECALL_CHARS).description('Longest one full-history excerpt may be, in characters.').volatile(),
|
|
437
|
+
denseEnabled: z.boolean().default(DEFAULT_DENSE_ENABLED).description('Add an embedding channel to recall ranking (RRF fusion with BM25). Off by default: it needs a local embedding service on every machine that recalls, and the bench gain is mostly in entries the lexical path misses entirely. When the service is unreachable the recall silently stays lexical.').volatile(),
|
|
431
438
|
/** Shortest user turn worth a recall decision. */
|
|
432
439
|
recallMinQueryChars: z.number().default(DEFAULT_RECALL_MIN_QUERY_CHARS).description('Shortest user turn, in characters, that may trigger a recall delta. Short acknowledgements are skipped instead of scanning the store.').volatile(),
|
|
433
440
|
/** Distinct strong-field terms a recall needs before it is credited. */
|
|
@@ -571,6 +578,7 @@ export const MEMORIES_SETTINGS_DEFAULTS = {
|
|
|
571
578
|
ragRecallExcerpts: DEFAULT_RAG_RECALL_EXCERPTS,
|
|
572
579
|
ragRecallSessions: DEFAULT_RAG_RECALL_SESSIONS,
|
|
573
580
|
ragRecallChars: DEFAULT_RAG_RECALL_CHARS,
|
|
581
|
+
denseEnabled: DEFAULT_DENSE_ENABLED,
|
|
574
582
|
recallMinQueryChars: DEFAULT_RECALL_MIN_QUERY_CHARS,
|
|
575
583
|
recallMinTerms: DEFAULT_RECALL_MIN_TERMS,
|
|
576
584
|
injectDelta: DEFAULT_INJECT_DELTA,
|
|
@@ -690,6 +698,7 @@ export function normalizeSettings(input) {
|
|
|
690
698
|
ragRecallExcerpts: positive(value.ragRecallExcerpts, DEFAULT_RAG_RECALL_EXCERPTS, 0),
|
|
691
699
|
ragRecallSessions: nonNegative(value.ragRecallSessions, DEFAULT_RAG_RECALL_SESSIONS),
|
|
692
700
|
ragRecallChars: positive(value.ragRecallChars, DEFAULT_RAG_RECALL_CHARS, 0),
|
|
701
|
+
denseEnabled: value.denseEnabled ?? DEFAULT_DENSE_ENABLED,
|
|
693
702
|
recallMinQueryChars: positive(value.recallMinQueryChars, DEFAULT_RECALL_MIN_QUERY_CHARS, 0),
|
|
694
703
|
recallMinTerms: positive(value.recallMinTerms, DEFAULT_RECALL_MIN_TERMS, 0),
|
|
695
704
|
injectDelta: value.injectDelta ?? DEFAULT_INJECT_DELTA,
|
package/lib/dense.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional dense channel: embeddings for the turns the lexical ranker cannot
|
|
3
|
+
* reach.
|
|
4
|
+
*
|
|
5
|
+
* Why it exists as an option rather than the default. On the clean query batch
|
|
6
|
+
* the RRF hybrid of BM25 and `qwen3-embedding:0.6b` measured: R@1 74.7 against
|
|
7
|
+
* BM25's 76.0, R@5 96.0 against 92.0, and — the point — **1 miss out of 150
|
|
8
|
+
* against BM25's 5**. The gain is almost entirely in the entries that share no
|
|
9
|
+
* word with the query at all, which is exactly the failure mode of a short,
|
|
10
|
+
* context-dependent turn (「附件」 against a memory filed as 「邮件写作风格」).
|
|
11
|
+
*
|
|
12
|
+
* It costs a local embedding service and a first-pass embedding of the store,
|
|
13
|
+
* so it is off unless configured, and every failure here degrades to the lexical
|
|
14
|
+
* result instead of failing the recall.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-cross-memory/dense
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
20
|
+
import { dirname } from 'node:path';
|
|
21
|
+
/** Where the embedding service is reached; the harness never calls outside the machine by default. */
|
|
22
|
+
export const DEFAULT_DENSE_URL = 'http://127.0.0.1:11434';
|
|
23
|
+
/** The model the bench measured. Any embedding model works; the cache is keyed by name. */
|
|
24
|
+
export const DEFAULT_DENSE_MODEL = 'qwen3-embedding:0.6b';
|
|
25
|
+
/** The searchable text of one entry, the same fields the lexical index reads. */
|
|
26
|
+
function documentText(entry) {
|
|
27
|
+
return [entry.title, ...(entry.keys ?? []), ...(entry.tags ?? []), entry.appliesTo ?? '', (entry.body ?? '').slice(0, 2000)]
|
|
28
|
+
.filter((part) => part.length > 0)
|
|
29
|
+
.join('\n');
|
|
30
|
+
}
|
|
31
|
+
const hashOf = (text) => createHash('sha1').update(text).digest('hex').slice(0, 16);
|
|
32
|
+
/** Encode a vector as base64 float32 (JSON-safe). */
|
|
33
|
+
function encode(vector) {
|
|
34
|
+
return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength).toString('base64');
|
|
35
|
+
}
|
|
36
|
+
/** Decode one base64 float32 blob. */
|
|
37
|
+
function decode(blob) {
|
|
38
|
+
const buffer = Buffer.from(blob, 'base64');
|
|
39
|
+
return new Float32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4);
|
|
40
|
+
}
|
|
41
|
+
/** Unit-normalize a vector, so cosine is a dot product. */
|
|
42
|
+
function normalize(vector) {
|
|
43
|
+
let norm = 0;
|
|
44
|
+
for (const value of vector)
|
|
45
|
+
norm += value * value;
|
|
46
|
+
norm = Math.sqrt(norm) || 1;
|
|
47
|
+
const out = new Float32Array(vector.length);
|
|
48
|
+
for (let index = 0; index < vector.length; index += 1)
|
|
49
|
+
out[index] = vector[index] / norm;
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** One embedding call, retried twice: ollama drops the first request after idle. */
|
|
53
|
+
async function callService(url, model, texts) {
|
|
54
|
+
const endpoint = `${url.replace(/\/+$/u, '')}/api/embed`;
|
|
55
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
56
|
+
try {
|
|
57
|
+
const response = await fetch(endpoint, {
|
|
58
|
+
method: 'POST',
|
|
59
|
+
headers: { 'content-type': 'application/json' },
|
|
60
|
+
body: JSON.stringify({ model, input: texts }),
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok)
|
|
63
|
+
throw new Error(`embedding service ${response.status}: ${await response.text()}`);
|
|
64
|
+
const payload = await response.json();
|
|
65
|
+
const vectors = payload.embeddings;
|
|
66
|
+
if (!Array.isArray(vectors) || vectors.length !== texts.length) {
|
|
67
|
+
throw new Error(`embedding service returned ${Array.isArray(vectors) ? vectors.length : 'no'} vectors for ${texts.length} texts`);
|
|
68
|
+
}
|
|
69
|
+
return vectors.map((vector) => normalize(Float32Array.from(vector)));
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (attempt === 2)
|
|
73
|
+
throw error;
|
|
74
|
+
await new Promise((resolve) => setTimeout(resolve, 600));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
throw new Error('unreachable');
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Embed texts, reusing the on-disk cache.
|
|
81
|
+
*
|
|
82
|
+
* Failures propagate: the caller decides whether to fall back. The cache is
|
|
83
|
+
* written only after every batch succeeded, so a partial run never poisons it.
|
|
84
|
+
*
|
|
85
|
+
* @param texts - texts to embed, in order.
|
|
86
|
+
* @param options - service location, model, and cache directory.
|
|
87
|
+
* @returns one unit vector per text.
|
|
88
|
+
*/
|
|
89
|
+
export async function embed(texts, options) {
|
|
90
|
+
const path = `${options.cacheDir}/dense-${options.model.replace(/[^a-z0-9._-]/giu, '_')}.json`;
|
|
91
|
+
let cache = { model: options.model, vectors: {} };
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
94
|
+
if (parsed.model === options.model && typeof parsed.vectors === 'object')
|
|
95
|
+
cache = parsed;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
cache = { model: options.model, vectors: {} };
|
|
99
|
+
}
|
|
100
|
+
const missing = [];
|
|
101
|
+
const seen = new Set();
|
|
102
|
+
for (const text of texts) {
|
|
103
|
+
const key = hashOf(text);
|
|
104
|
+
if (cache.vectors[key] !== undefined || seen.has(key))
|
|
105
|
+
continue;
|
|
106
|
+
seen.add(key);
|
|
107
|
+
missing.push({ key, text });
|
|
108
|
+
}
|
|
109
|
+
const BATCH = 16;
|
|
110
|
+
for (let start = 0; start < missing.length; start += BATCH) {
|
|
111
|
+
const batch = missing.slice(start, start + BATCH);
|
|
112
|
+
for (let index = 0; index < batch.length; index += 1) {
|
|
113
|
+
const vectors = await callService(options.url, options.model, [batch[index].text]);
|
|
114
|
+
cache.vectors[batch[index].key] = encode(vectors[0]);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (missing.length > 0) {
|
|
118
|
+
await mkdir(dirname(path), { recursive: true });
|
|
119
|
+
await writeFile(path, JSON.stringify(cache));
|
|
120
|
+
}
|
|
121
|
+
return texts.map((text) => decode(cache.vectors[hashOf(text)] ?? ''));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Cosine similarity of two unit vectors (a dot product).
|
|
125
|
+
* @param left - one vector.
|
|
126
|
+
* @param right - the other.
|
|
127
|
+
* @returns similarity in `[-1, 1]`.
|
|
128
|
+
*/
|
|
129
|
+
export function cosine(left, right) {
|
|
130
|
+
let sum = 0;
|
|
131
|
+
const length = Math.min(left.length, right.length);
|
|
132
|
+
for (let index = 0; index < length; index += 1)
|
|
133
|
+
sum += left[index] * right[index];
|
|
134
|
+
return sum;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Score every entry against one query by embedding.
|
|
138
|
+
*
|
|
139
|
+
* @param entries - the entries to score.
|
|
140
|
+
* @param query - the turn.
|
|
141
|
+
* @param options - service location, model, and cache directory.
|
|
142
|
+
* @returns id → cosine similarity; empty when the service is unavailable.
|
|
143
|
+
*/
|
|
144
|
+
export async function denseScores(entries, query, options) {
|
|
145
|
+
const scores = new Map();
|
|
146
|
+
if (entries.length === 0 || query.trim().length === 0)
|
|
147
|
+
return scores;
|
|
148
|
+
try {
|
|
149
|
+
const vectors = await embed([...entries.map(documentText), query], options);
|
|
150
|
+
const queryVector = vectors[vectors.length - 1];
|
|
151
|
+
if (queryVector.length === 0)
|
|
152
|
+
return scores;
|
|
153
|
+
for (let index = 0; index < entries.length; index += 1) {
|
|
154
|
+
scores.set(entries[index].id, cosine(vectors[index], queryVector));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// Dense is an optional channel: an unavailable service must never fail a recall.
|
|
159
|
+
return new Map();
|
|
160
|
+
}
|
|
161
|
+
return scores;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Reciprocal rank fusion.
|
|
165
|
+
*
|
|
166
|
+
* The two channels disagree about scale, not about order, so their ranks are
|
|
167
|
+
* fused instead of their scores: each list contributes `1 / (k + rank)`, and
|
|
168
|
+
* the constant keeps a first place worth about twice a tenth.
|
|
169
|
+
*
|
|
170
|
+
* @param lists - ranked id lists, best first.
|
|
171
|
+
* @param k - fusion constant; 60 is the usual value.
|
|
172
|
+
* @returns id → fused score, descending.
|
|
173
|
+
*/
|
|
174
|
+
export function rrf(lists, k = 60) {
|
|
175
|
+
const fused = new Map();
|
|
176
|
+
for (const list of lists) {
|
|
177
|
+
list.forEach((id, rank) => fused.set(id, (fused.get(id) ?? 0) + 1 / (k + rank + 1)));
|
|
178
|
+
}
|
|
179
|
+
return new Map([...fused.entries()].sort((left, right) => right[1] - left[1]));
|
|
180
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { ACCOUNT_QUOTA_EXCEEDED_CODE, createUserMessage, isQuotaExceededError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm';
|
|
25
25
|
import { homedir } from 'node:os';
|
|
26
|
-
import { join, resolve, sep } from 'node:path';
|
|
26
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
27
27
|
import { Config as ConfigSchema, consolidationRouteOf, DEFAULT_ROTATION_MAX_BYTES, readTunables, resolveConfig } from './config.js';
|
|
28
28
|
import { MemoryStore, projectSlug, slugify } from './storage.js';
|
|
29
29
|
import { StateStore, importLegacyState, statePath } from './state.js';
|
|
@@ -40,6 +40,7 @@ import { parseTimeRange } from './time.js';
|
|
|
40
40
|
import { isSubstantiveTurn } from './query.js';
|
|
41
41
|
import { INDEX_OPEN, MEMORY_CLOSE, MEMORY_OPEN, RECALL_OPEN, rankForSummary, renderEntry, renderHit, renderMemoryIndex, renderMemorySummaryResult, renderOpenLoops, renderRecall, renderScopeListing, selectForSummary } from './render.js';
|
|
42
42
|
import { createBm25Index } from './bm25.js';
|
|
43
|
+
import { DEFAULT_DENSE_MODEL, DEFAULT_DENSE_URL, denseScores, rrf } from './dense.js';
|
|
43
44
|
import { findProjectRoot, isWithin } from './workspace.js';
|
|
44
45
|
import { citationRoots, citationWarning, ignoredUnder, missingCitations } from './citations.js';
|
|
45
46
|
import { planRetention, retentionKey } from './retention.js';
|
|
@@ -58,6 +59,16 @@ import { REMOTE_CONTRIBUTION, REMOTE_NAMESPACE, REMOTE_SERVICE, createRemoteServ
|
|
|
58
59
|
export const name = 'memories';
|
|
59
60
|
/** Budget for the extraction a shutdown is allowed to wait for. */
|
|
60
61
|
const EXIT_FLUSH_TIMEOUT_MS = 8_000;
|
|
62
|
+
/**
|
|
63
|
+
* Let the host event loop breathe between two bounded slices of background work.
|
|
64
|
+
*
|
|
65
|
+
* The periodic pass walks every open session and the whole store on the main
|
|
66
|
+
* thread; measured on 29 live sessions, one uninterrupted walk held the loop for
|
|
67
|
+
* 5.6-8.3 s every 30 minutes (the host reported `Host event loop stalled` each
|
|
68
|
+
* time). Yielding between slices keeps the same work but caps one slice at a few
|
|
69
|
+
* milliseconds, so an interactive turn is never parked behind the pass.
|
|
70
|
+
*/
|
|
71
|
+
const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
61
72
|
/**
|
|
62
73
|
* How often a periodic pass that changed nothing still reports at info level.
|
|
63
74
|
*
|
|
@@ -286,6 +297,25 @@ export class MemoriesRuntime {
|
|
|
286
297
|
llm: () => this.llm,
|
|
287
298
|
log: this.log,
|
|
288
299
|
});
|
|
300
|
+
// Dense warm-up: embedding the whole store costs under a minute on a local
|
|
301
|
+
// 0.6b model and must not land inside a user's turn. Fire and forget; the
|
|
302
|
+
// first recall after this is a cache hit (measured 0.04s).
|
|
303
|
+
if (this.settings.denseEnabled)
|
|
304
|
+
void this.warmDense().catch(() => undefined);
|
|
305
|
+
}
|
|
306
|
+
/** Embed the store once in the background so the first recall is not the slow one. */
|
|
307
|
+
async warmDense() {
|
|
308
|
+
const entries = [...await this.store.list('global', undefined)];
|
|
309
|
+
for (const slug of await this.store.listProjects()) {
|
|
310
|
+
const descriptor = await this.store.readProjectDescriptor(slug);
|
|
311
|
+
if (descriptor === undefined)
|
|
312
|
+
continue;
|
|
313
|
+
entries.push(...await this.store.list('project', descriptor.root).catch(() => []));
|
|
314
|
+
}
|
|
315
|
+
if (entries.length === 0)
|
|
316
|
+
return;
|
|
317
|
+
await denseScores(entries, 'warm-up', { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
|
|
318
|
+
this.log.info('dsh-cross-memory: dense channel warmed (%d entries)', entries.length);
|
|
289
319
|
}
|
|
290
320
|
/**
|
|
291
321
|
* The LLM runtime to use right now.
|
|
@@ -1266,6 +1296,10 @@ export class MemoriesRuntime {
|
|
|
1266
1296
|
this.hubCache.set(signature, hub);
|
|
1267
1297
|
return hub;
|
|
1268
1298
|
}
|
|
1299
|
+
/** Where the dense vector cache lives: `<dshHome>/cache/dsh-cross-memory`. */
|
|
1300
|
+
denseCacheDir() {
|
|
1301
|
+
return join(dirname(this.store.memoriesDir), 'cache', 'dsh-cross-memory');
|
|
1302
|
+
}
|
|
1269
1303
|
/**
|
|
1270
1304
|
* The on-demand recall delta for this step, or `undefined` when nothing is
|
|
1271
1305
|
* worth adding.
|
|
@@ -1481,7 +1515,24 @@ export class MemoriesRuntime {
|
|
|
1481
1515
|
}
|
|
1482
1516
|
return undefined;
|
|
1483
1517
|
}
|
|
1484
|
-
|
|
1518
|
+
// Optional dense channel: re-rank what the gate admitted by fusing the
|
|
1519
|
+
// lexical order with an embedding order. Only the ORDER changes — the gate
|
|
1520
|
+
// still decides what may be recalled, so this cannot admit an entry the
|
|
1521
|
+
// lexical gate refused. When the service is unreachable, `denseScores`
|
|
1522
|
+
// returns an empty map and the lexical order stands.
|
|
1523
|
+
if (this.settings.denseEnabled && eligible.length > 1) {
|
|
1524
|
+
const dense = await denseScores(states.flatMap((state) => state.entries), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
|
|
1525
|
+
if (dense.size > 0) {
|
|
1526
|
+
const lexical = [...eligible].sort(byStrength).map((item) => item.entry.id);
|
|
1527
|
+
const semantic = [...dense.entries()].sort((left, right) => right[1] - left[1]).map(([id]) => id);
|
|
1528
|
+
const fused = rrf([lexical, semantic]);
|
|
1529
|
+
eligible.sort((left, right) => (fused.get(right.entry.id) ?? 0) - (fused.get(left.entry.id) ?? 0));
|
|
1530
|
+
this.log.info('dsh-cross-memory: session %s recall re-ranked by the dense channel (%d candidates)', session.id, eligible.length);
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
else {
|
|
1534
|
+
eligible.sort(byStrength);
|
|
1535
|
+
}
|
|
1485
1536
|
// The one-hop neighbours go in after the seeds and carry no lexical
|
|
1486
1537
|
// relevance, so they can only fill slots the lexical path left empty — the
|
|
1487
1538
|
// case this exists for is a turn that names one fragment of something the
|
|
@@ -2163,7 +2214,9 @@ export class MemoriesRuntime {
|
|
|
2163
2214
|
const limit = this.settings.maxSessionsPerPass;
|
|
2164
2215
|
const ordered = [...candidates.values()].sort((left, right) => this.activityOf(right) - this.activityOf(left));
|
|
2165
2216
|
let mined = 0;
|
|
2166
|
-
for (const agent of ordered) {
|
|
2217
|
+
for (const [index, agent] of ordered.entries()) {
|
|
2218
|
+
if (index > 0 && index % 4 === 0)
|
|
2219
|
+
await yieldToEventLoop();
|
|
2167
2220
|
if (this.lifecycle.signal.aborted)
|
|
2168
2221
|
return;
|
|
2169
2222
|
counts.tracked += 1;
|
|
@@ -2517,6 +2570,15 @@ export class MemoriesRuntime {
|
|
|
2517
2570
|
*/
|
|
2518
2571
|
hasNothingNew(session) {
|
|
2519
2572
|
const after = this.state.getSession(session.id)?.lastSeq ?? 0;
|
|
2573
|
+
// Cheap gate before the window walk. A live process keeps every settled
|
|
2574
|
+
// session in `candidates`, and on a caught-up session the walk still pays a
|
|
2575
|
+
// full pass over the surface graph for nothing. The surface nodes are kept
|
|
2576
|
+
// in seq order, so a last node at or below the watermark means no message
|
|
2577
|
+
// can be newer than it — no window can exist, and no string is built.
|
|
2578
|
+
const nodes = session.surface.nodes;
|
|
2579
|
+
const newest = nodes[nodes.length - 1];
|
|
2580
|
+
if (newest !== undefined && newest <= after)
|
|
2581
|
+
return true;
|
|
2520
2582
|
const window = collectWindow(session, after, this.settings.extractWindowMessages, this.settings.extractMaxInputChars);
|
|
2521
2583
|
return window.lastSeq === undefined || window.text.trim().length === 0;
|
|
2522
2584
|
}
|
|
@@ -2541,7 +2603,7 @@ export class MemoriesRuntime {
|
|
|
2541
2603
|
}
|
|
2542
2604
|
/** Bound `beforeExit` handler. */
|
|
2543
2605
|
exitFlush = () => {
|
|
2544
|
-
|
|
2606
|
+
Promise.resolve(this.flushExit()).catch(() => undefined);
|
|
2545
2607
|
};
|
|
2546
2608
|
/**
|
|
2547
2609
|
* Mine one session's transcript tail and store what it yields.
|
|
@@ -3020,7 +3082,18 @@ export class MemoriesRuntime {
|
|
|
3020
3082
|
this.consolidateSkip = `only ${entries.length} memories are eligible for a pass`;
|
|
3021
3083
|
return undefined;
|
|
3022
3084
|
}
|
|
3023
|
-
const
|
|
3085
|
+
const proposedRaw = await this.runConsolidationPass(parent, entries, root);
|
|
3086
|
+
// Two routes feed this plan (the subagent seam and the direct model call),
|
|
3087
|
+
// and a malformed element in any array reaches `item.id` in the classifier
|
|
3088
|
+
// as a TypeError whose message names no field. Drop holes here, once, so a
|
|
3089
|
+
// bad reply costs one skipped row instead of the whole pass.
|
|
3090
|
+
const proposed = proposedRaw === undefined ? undefined : {
|
|
3091
|
+
...proposedRaw,
|
|
3092
|
+
upserts: proposedRaw.upserts.filter((item) => item !== null && item !== undefined),
|
|
3093
|
+
...proposedRaw.conflicts === undefined ? {} : {
|
|
3094
|
+
conflicts: proposedRaw.conflicts.filter((conflict) => conflict !== null && conflict !== undefined),
|
|
3095
|
+
},
|
|
3096
|
+
};
|
|
3024
3097
|
if (proposed === undefined) {
|
|
3025
3098
|
this.state.deleteJob(CONSOLIDATE_JOB);
|
|
3026
3099
|
// `onSkip` records the concrete reason; this is the fallback for a
|
|
@@ -3136,6 +3209,12 @@ export class MemoriesRuntime {
|
|
|
3136
3209
|
});
|
|
3137
3210
|
this.noteLimitRefusal(error);
|
|
3138
3211
|
this.log.warn('dsh-cross-memory: consolidation failed for session %s: %s', parent.session.id, message);
|
|
3212
|
+
// The failure is a plain TypeError from a field access, and its message
|
|
3213
|
+
// alone ("reading 'id'") names no call site. Record the stack once at
|
|
3214
|
+
// decision level so the next occurrence is locatable without a rebuild.
|
|
3215
|
+
if (error instanceof Error && typeof error.stack === 'string' && error.stack.length > 0) {
|
|
3216
|
+
this.log.decision('dsh-cross-memory: consolidation failure stack: %s', error.stack);
|
|
3217
|
+
}
|
|
3139
3218
|
// The command reports `consolidateSkipReason`; without this the failure
|
|
3140
3219
|
// surfaced as "Nothing to consolidate: unknown reason".
|
|
3141
3220
|
this.consolidateSkip = `the pass failed: ${message}`;
|
|
@@ -3666,6 +3745,11 @@ export class MemoriesRuntime {
|
|
|
3666
3745
|
}
|
|
3667
3746
|
scopes += 1;
|
|
3668
3747
|
archived += await this.retain('project', descriptor.root, now);
|
|
3748
|
+
// The sweep walks every known workspace on the main thread; on a store
|
|
3749
|
+
// with 40 scopes that is one long tick. Yield between scopes so the pass
|
|
3750
|
+
// never holds the loop beyond a slice.
|
|
3751
|
+
if (scopes % 4 === 0)
|
|
3752
|
+
await yieldToEventLoop();
|
|
3669
3753
|
}
|
|
3670
3754
|
const rehomed = await this.store.adoptMisnamedProjects().catch(() => []);
|
|
3671
3755
|
for (const move of rehomed) {
|
|
@@ -3896,10 +3980,14 @@ export class MemoriesRuntime {
|
|
|
3896
3980
|
now,
|
|
3897
3981
|
});
|
|
3898
3982
|
let archived = 0;
|
|
3983
|
+
let examined = 0;
|
|
3899
3984
|
for (const decision of expired) {
|
|
3900
3985
|
this.log.decision('dsh-cross-memory: archiving %s/%s, unused for %d days', decision.scope, decision.id, Math.round(decision.ageDays));
|
|
3901
3986
|
if (await this.store.archive(scope, root, decision.id, now, 'retention'))
|
|
3902
3987
|
archived += 1;
|
|
3988
|
+
examined += 1;
|
|
3989
|
+
if (examined % 25 === 0)
|
|
3990
|
+
await yieldToEventLoop();
|
|
3903
3991
|
}
|
|
3904
3992
|
return archived;
|
|
3905
3993
|
}
|
|
@@ -4509,7 +4597,11 @@ export function apply(ctx, config = {}) {
|
|
|
4509
4597
|
runtime.cancelExtraction(agent);
|
|
4510
4598
|
// A short-lived process may exit before the idle timer ever fires; the
|
|
4511
4599
|
// disposal boundary is the last moment an extraction can still run.
|
|
4512
|
-
|
|
4600
|
+
// `flushExit` is declared async, but the registry wraps every listener and
|
|
4601
|
+
// reports anything it throws as "agent/disposed listener threw". Normalise
|
|
4602
|
+
// the return value first: a `.catch` on a non-promise is exactly the failure
|
|
4603
|
+
// the host logged in 2026-11-22..26, and disposal must never be the raiser.
|
|
4604
|
+
Promise.resolve(runtime.flushExit()).catch(() => undefined);
|
|
4513
4605
|
});
|
|
4514
4606
|
// 0.1.7-rc.1 起宿主把 `agent/session-start` 改名为 `agent/created`(公告见 v0.1.7-rc.1
|
|
4515
4607
|
// release notes)。payload 形状不变,仍是 `{ agent, source }`,`source` 取值同为
|
package/lib/sync.js
CHANGED
|
@@ -598,6 +598,9 @@ export class MemorySync {
|
|
|
598
598
|
// cycle cheaply and let the next timer retry once the writes settle; the
|
|
599
599
|
// --autostash shortcut is not used because a concurrent edit to a file the
|
|
600
600
|
// upstream commit also rewrites would resurface as conflict markers.
|
|
601
|
+
// A "commit then retry once" variant was tried on 2026-11-27 and reverted: a
|
|
602
|
+
// local edit that conflicts with the upstream commit turns the retry into a
|
|
603
|
+
// live rebase, which is exactly the state this branch exists to avoid.
|
|
601
604
|
if (!this.rebaseInProgress()) {
|
|
602
605
|
this.options.log.warn('dsh-cross-memory: 记忆库 rebase 没能启动(工作区仍有未提交改动),本轮跳过同步');
|
|
603
606
|
return { ...nothing, pulled: 0, stoppedBy: 'rebase-not-started' };
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the BM25 ranker.
|
|
3
|
+
*
|
|
4
|
+
* BM25 is the ordering layer; the gatekeeper in `search.ts` decides what may be
|
|
5
|
+
* recalled. These pin the properties that make BM25 worth its own ranker: a
|
|
6
|
+
* term that appears everywhere is worth less than a term that names the thing
|
|
7
|
+
* (idf), a title hit outranks a body hit (field multiplicity), and a long
|
|
8
|
+
* document does not win merely by repeating a word (length normalisation).
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/test/bm25.test
|
|
11
|
+
*/
|
|
12
|
+
import assert from 'node:assert/strict';
|
|
13
|
+
import test from 'node:test';
|
|
14
|
+
import { BM25_B, BM25_K1, bm25Rank, createBm25Index } from '../bm25.js';
|
|
15
|
+
import { relevanceOf, searchMemories } from '../search.js';
|
|
16
|
+
/** Build one corpus entry. */
|
|
17
|
+
function entry(id, title, body, extra = {}, kind = 'fact') {
|
|
18
|
+
return {
|
|
19
|
+
id,
|
|
20
|
+
scope: 'global',
|
|
21
|
+
kind,
|
|
22
|
+
title,
|
|
23
|
+
body,
|
|
24
|
+
tags: extra.tags ?? [],
|
|
25
|
+
keys: extra.keys ?? [],
|
|
26
|
+
createdAt: 0,
|
|
27
|
+
updatedAt: 0,
|
|
28
|
+
uses: 0,
|
|
29
|
+
lastUsedAt: 0,
|
|
30
|
+
lastSurfacedAt: 0,
|
|
31
|
+
source: 'auto',
|
|
32
|
+
...extra.appliesTo === undefined ? {} : { appliesTo: extra.appliesTo },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
test('the constants are the sensitivity audit best cell, not a guess', () => {
|
|
36
|
+
assert.equal(BM25_K1, 1.2);
|
|
37
|
+
assert.equal(BM25_B, 0.75);
|
|
38
|
+
});
|
|
39
|
+
test('a title hit outranks an identical body hit', () => {
|
|
40
|
+
const corpus = [
|
|
41
|
+
entry('in-title', '插件日志查看方式', '无关正文。'),
|
|
42
|
+
entry('in-body', '无关标题', '插件日志查看方式写在正文里。'),
|
|
43
|
+
];
|
|
44
|
+
const ranked = bm25Rank(corpus, '插件日志');
|
|
45
|
+
assert.equal(ranked[0]?.id, 'in-title', 'the title is repeated twice in the index');
|
|
46
|
+
assert.ok((createBm25Index(corpus).score('插件日志').get('in-title') ?? 0)
|
|
47
|
+
> (createBm25Index(corpus).score('插件日志').get('in-body') ?? 0));
|
|
48
|
+
});
|
|
49
|
+
test('a term that appears everywhere is worth less than one that names the thing', () => {
|
|
50
|
+
// 「同步」 is on every entry; the file name is on one. A query naming both
|
|
51
|
+
// must prefer the entry that carries the rare term.
|
|
52
|
+
const corpus = Array.from({ length: 20 }, (_unused, index) => entry(`common-${index}`, `同步任务 ${index}`, '同步 同步 同步。'));
|
|
53
|
+
corpus.push(entry('rare', '同步任务:uk_file_invoice_sha_role', '同步。'));
|
|
54
|
+
const ranked = bm25Rank(corpus, '同步 uk_file_invoice_sha_role');
|
|
55
|
+
assert.equal(ranked[0]?.id, 'rare', 'the rare identifier decides the order');
|
|
56
|
+
const index = createBm25Index(corpus);
|
|
57
|
+
const scores = index.score('同步 uk_file_invoice_sha_role');
|
|
58
|
+
assert.ok((scores.get('rare') ?? 0) > (scores.get('common-0') ?? 0));
|
|
59
|
+
});
|
|
60
|
+
test('repeating one common word saturates instead of scaling linearly', () => {
|
|
61
|
+
const shortHit = entry('short', '同步说明', '同步。');
|
|
62
|
+
const longRepeat = entry('long', '同步说明', '同步 '.repeat(80));
|
|
63
|
+
const corpus = [shortHit, longRepeat];
|
|
64
|
+
const scores = createBm25Index(corpus).score('同步');
|
|
65
|
+
const once = scores.get('short') ?? 0;
|
|
66
|
+
const eighty = scores.get('long') ?? 0;
|
|
67
|
+
assert.ok(once > 0 && eighty > 0);
|
|
68
|
+
// 80 repeats are worth about one hit, not eighty: the tf term saturates.
|
|
69
|
+
assert.ok(eighty / once < 10, `repetition scaled too far: ${once.toFixed(2)} -> ${eighty.toFixed(2)}`);
|
|
70
|
+
});
|
|
71
|
+
test('a query with no shared term returns nothing, and an empty query is empty', () => {
|
|
72
|
+
const corpus = [entry('a', '插件日志', '日志正文。')];
|
|
73
|
+
assert.deepEqual(bm25Rank(corpus, '完全不相关的查询'), []);
|
|
74
|
+
assert.deepEqual(bm25Rank(corpus, ''), []);
|
|
75
|
+
assert.deepEqual(bm25Rank(corpus, ' '), []);
|
|
76
|
+
});
|
|
77
|
+
test('the index is cached against the exact array it was built from', () => {
|
|
78
|
+
const corpus = [entry('a', '插件日志', '日志正文。')];
|
|
79
|
+
assert.equal(createBm25Index(corpus), createBm25Index(corpus), 'the same array reuses the index');
|
|
80
|
+
assert.notEqual(createBm25Index([...corpus]), createBm25Index(corpus), 'a copy is a different index');
|
|
81
|
+
});
|
|
82
|
+
test('CJK bigrams rank a Chinese query without a model call', () => {
|
|
83
|
+
const corpus = [
|
|
84
|
+
entry('logs', '插件日志查看方式', '日志写在文件里。'),
|
|
85
|
+
entry('order', '插件注册顺序', '启动时注册。'),
|
|
86
|
+
entry('cost', '成本计量的坑', '另一件事。'),
|
|
87
|
+
];
|
|
88
|
+
const ranked = bm25Rank(corpus, '该插件是否有日志');
|
|
89
|
+
assert.equal(ranked[0]?.id, 'logs');
|
|
90
|
+
assert.ok(!ranked.some((value) => value.id === 'cost'), 'an unrelated entry does not surface');
|
|
91
|
+
});
|
|
92
|
+
test('the ranker changes the order, never the admitted set', () => {
|
|
93
|
+
// The gatekeeper decides what may be recalled; BM25 only decides which of
|
|
94
|
+
// those comes first. If a ranker ever adds or drops an entry, the recall
|
|
95
|
+
// gate has silently changed meaning — so pin the set.
|
|
96
|
+
const corpus = [
|
|
97
|
+
entry('logs', '插件日志查看方式', '日志写在文件里。', { keys: ['logging'] }),
|
|
98
|
+
entry('order', '插件注册顺序', '启动时注册。', { tags: ['插件'] }),
|
|
99
|
+
entry('push', '提交后主动推送', '提交完直接推 origin。', { appliesTo: '准备推送代码之前' }),
|
|
100
|
+
entry('cost', '成本计量的坑', '另一件事。'),
|
|
101
|
+
entry('restart', '重启 dsh web', '用 restart 端点。'),
|
|
102
|
+
];
|
|
103
|
+
const groups = [{ scope: 'global', label: 'global', entries: corpus }];
|
|
104
|
+
const query = '插件的日志和推送';
|
|
105
|
+
const admitted = corpus.filter((value) => relevanceOf(value, query) > 0).map((value) => value.id).sort();
|
|
106
|
+
const ranked = searchMemories(groups, query, { limit: 10 }).map((hit) => hit.entry.id).sort();
|
|
107
|
+
assert.deepEqual(ranked, admitted, 'BM25 must not admit an entry the gatekeeper refused, or hide one it admitted');
|
|
108
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The periodic pass must not walk a caught-up session's surface.
|
|
3
|
+
*
|
|
4
|
+
* `hasNothingNew` runs once per open session every `extractIntervalMinutes`
|
|
5
|
+
* tick. Before the cheap gate it built a full extraction window (a pass over
|
|
6
|
+
* every surface node, one `eventAt` call per seq) just to discover that the
|
|
7
|
+
* watermark was already at the tail; measured with 29 live sessions on the
|
|
8
|
+
* host, that walk held the event loop for 5.6-8.3 s every 30 minutes and the
|
|
9
|
+
* host logged `Host event loop stalled` each time.
|
|
10
|
+
*
|
|
11
|
+
* What the gate must not do is change the answer. This file pins both sides:
|
|
12
|
+
* a last node at or below the watermark is "nothing new" without one `eventAt`
|
|
13
|
+
* call, and anything newer still goes through the window walk.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-cross-memory/test/caught-up.test
|
|
16
|
+
*/
|
|
17
|
+
import assert from 'node:assert/strict';
|
|
18
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
19
|
+
import { tmpdir } from 'node:os';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import test from 'node:test';
|
|
22
|
+
import { MemoriesRuntime } from '../index.js';
|
|
23
|
+
/** A context stand-in. */
|
|
24
|
+
const stubContext = {
|
|
25
|
+
get: () => undefined,
|
|
26
|
+
logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
|
|
27
|
+
};
|
|
28
|
+
/** A runtime over a temp store, disposed after the test. */
|
|
29
|
+
async function fixture(t) {
|
|
30
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-caught-up-'));
|
|
31
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: true });
|
|
32
|
+
t.after(() => {
|
|
33
|
+
runtime.dispose();
|
|
34
|
+
return rm(dir, { recursive: true, force: true });
|
|
35
|
+
});
|
|
36
|
+
return { runtime };
|
|
37
|
+
}
|
|
38
|
+
/** A session whose surface is the given seqs and whose events are all probes. */
|
|
39
|
+
function stubSession(id, nodes, probes) {
|
|
40
|
+
return {
|
|
41
|
+
id,
|
|
42
|
+
header: { version: 0, id, createdAt: 0, cwd: process.cwd(), isSeeded: false },
|
|
43
|
+
surface: { nodes },
|
|
44
|
+
eventAt: (seq) => {
|
|
45
|
+
probes.push(seq);
|
|
46
|
+
return undefined;
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The runtime method under test, at its private face. */
|
|
51
|
+
const gate = (runtime) => runtime;
|
|
52
|
+
test('a session whose last surface node is at the watermark skips the walk', async (t) => {
|
|
53
|
+
const { runtime } = await fixture(t);
|
|
54
|
+
runtime.state.putSession('caught-up', { lastSeq: 7, at: 0 });
|
|
55
|
+
const probes = [];
|
|
56
|
+
const session = stubSession('caught-up', [1, 2, 7], probes);
|
|
57
|
+
assert.equal(gate(runtime).hasNothingNew(session), true);
|
|
58
|
+
assert.deepEqual(probes, [], 'the gate answered without one eventAt call');
|
|
59
|
+
});
|
|
60
|
+
test('the gate opens for any node past the watermark', async (t) => {
|
|
61
|
+
const { runtime } = await fixture(t);
|
|
62
|
+
runtime.state.putSession('behind', { lastSeq: 6, at: 0 });
|
|
63
|
+
const probes = [];
|
|
64
|
+
const session = stubSession('behind', [1, 2, 7], probes);
|
|
65
|
+
// The walk runs (it can see node 7) and still reports "nothing new" because
|
|
66
|
+
// the probe yields no message — which is the behaviour the gate must keep.
|
|
67
|
+
assert.equal(gate(runtime).hasNothingNew(session), true);
|
|
68
|
+
assert.deepEqual(probes, [7], 'the walk started at the first node past the floor');
|
|
69
|
+
});
|
|
70
|
+
test('an empty surface still takes the window path', async (t) => {
|
|
71
|
+
const { runtime } = await fixture(t);
|
|
72
|
+
runtime.state.putSession('empty', { lastSeq: 0, at: 0 });
|
|
73
|
+
const probes = [];
|
|
74
|
+
const session = stubSession('empty', [], probes);
|
|
75
|
+
assert.equal(gate(runtime).hasNothingNew(session), true);
|
|
76
|
+
assert.deepEqual(probes, []);
|
|
77
|
+
});
|
|
78
|
+
test('a session with no recorded watermark is walked, not short-circuited', async (t) => {
|
|
79
|
+
const { runtime } = await fixture(t);
|
|
80
|
+
const probes = [];
|
|
81
|
+
const session = stubSession('fresh', [1, 2], probes);
|
|
82
|
+
assert.equal(gate(runtime).hasNothingNew(session), true);
|
|
83
|
+
assert.deepEqual(probes, [1, 2], 'with no watermark every node is newer');
|
|
84
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the optional dense channel.
|
|
3
|
+
*
|
|
4
|
+
* The ranker is only exercised on the parts that need no service: fusion order
|
|
5
|
+
* and the degrade-to-lexical guarantee. The embedding call itself is covered by
|
|
6
|
+
* the bench (`run-bench.mts`, dense arm), which runs against a real ollama.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-cross-memory/test/dense.test
|
|
9
|
+
*/
|
|
10
|
+
import assert from 'node:assert/strict';
|
|
11
|
+
import test from 'node:test';
|
|
12
|
+
import { cosine, denseScores, rrf } from '../dense.js';
|
|
13
|
+
function entry(id, title, body) {
|
|
14
|
+
return {
|
|
15
|
+
id, scope: 'global', kind: 'fact', title, body,
|
|
16
|
+
tags: [], keys: [], createdAt: 0, updatedAt: 0, uses: 0,
|
|
17
|
+
lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto',
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
test('fusion sums reciprocal ranks and keeps the better-placed entry first', () => {
|
|
21
|
+
const fused = rrf([['a', 'b', 'c'], ['a', 'b']]);
|
|
22
|
+
// `a` leads both lists; `b` follows it in both; `c` appears once.
|
|
23
|
+
assert.ok((fused.get('a') ?? 0) > (fused.get('b') ?? 0), 'a outranks b on total rank');
|
|
24
|
+
assert.ok((fused.get('b') ?? 0) > (fused.get('c') ?? 0), 'c has only one appearance');
|
|
25
|
+
assert.deepEqual([...fused.keys()], ['a', 'b', 'c']);
|
|
26
|
+
});
|
|
27
|
+
test('fusion ignores empty lists and returns nothing for no lists', () => {
|
|
28
|
+
assert.deepEqual([...rrf([[], ['a']]).keys()], ['a']);
|
|
29
|
+
assert.equal(rrf([]).size, 0);
|
|
30
|
+
});
|
|
31
|
+
test('cosine is 1 for identical unit vectors and 0 for orthogonal ones', () => {
|
|
32
|
+
assert.ok(Math.abs(cosine(new Float32Array([1, 0]), new Float32Array([1, 0])) - 1) < 1e-6);
|
|
33
|
+
assert.ok(Math.abs(cosine(new Float32Array([1, 0]), new Float32Array([0, 1]))) < 1e-6);
|
|
34
|
+
});
|
|
35
|
+
test('an unavailable embedding service degrades to an empty result, never a throw', async () => {
|
|
36
|
+
const entries = [entry('a', '插件日志', '日志正文。')];
|
|
37
|
+
const scores = await denseScores(entries, '插件日志', {
|
|
38
|
+
url: 'http://127.0.0.1:1',
|
|
39
|
+
model: 'test-model',
|
|
40
|
+
cacheDir: '/tmp/dsh-cross-memory-dense-test',
|
|
41
|
+
});
|
|
42
|
+
assert.equal(scores.size, 0, 'the lexical caller falls back on an empty map');
|
|
43
|
+
});
|
|
44
|
+
test('an empty query or an empty store scores nothing without calling out', async () => {
|
|
45
|
+
const entries = [entry('a', '插件日志', '日志正文。')];
|
|
46
|
+
const options = { url: 'http://127.0.0.1:1', model: 'test-model', cacheDir: '/tmp/dsh-cross-memory-dense-test' };
|
|
47
|
+
assert.equal((await denseScores(entries, '', options)).size, 0);
|
|
48
|
+
assert.equal((await denseScores([], '插件日志', options)).size, 0);
|
|
49
|
+
});
|
package/lib/types/config.d.ts
CHANGED
|
@@ -214,6 +214,12 @@ export declare const DEFAULT_RAG_RECALL_BYTES = 12000;
|
|
|
214
214
|
export declare const DEFAULT_RAG_RECALL_EXCERPTS = 6;
|
|
215
215
|
export declare const DEFAULT_RAG_RECALL_SESSIONS = 0;
|
|
216
216
|
export declare const DEFAULT_RAG_RECALL_CHARS = 2000;
|
|
217
|
+
/** Dense ranking is opt-in: it needs a local embedding service on every machine that recalls. */
|
|
218
|
+
export declare const DEFAULT_DENSE_ENABLED = false;
|
|
219
|
+
/** Ollama's default endpoint; the plugin never calls outside the machine unless this is changed. */
|
|
220
|
+
export declare const DEFAULT_DENSE_URL = "http://127.0.0.1:11434";
|
|
221
|
+
/** The model the bench measured (1024 dimensions). */
|
|
222
|
+
export declare const DEFAULT_DENSE_MODEL = "qwen3-embedding:0.6b";
|
|
217
223
|
/**
|
|
218
224
|
* Default number of distinct strong-field terms a recall needs.
|
|
219
225
|
*
|
|
@@ -422,6 +428,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
422
428
|
ragRecallExcerpts: z<number, number, "volatile-defined">;
|
|
423
429
|
ragRecallSessions: z<number, number, "volatile-defined">;
|
|
424
430
|
ragRecallChars: z<number, number, "volatile-defined">;
|
|
431
|
+
denseEnabled: z<boolean, boolean, "volatile-defined">;
|
|
425
432
|
/** Shortest user turn worth a recall decision. */
|
|
426
433
|
recallMinQueryChars: z<number, number, "volatile-defined">;
|
|
427
434
|
/** Distinct strong-field terms a recall needs before it is credited. */
|
|
@@ -592,6 +599,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
|
|
|
592
599
|
ragRecallExcerpts: z<number, number, "volatile-defined">;
|
|
593
600
|
ragRecallSessions: z<number, number, "volatile-defined">;
|
|
594
601
|
ragRecallChars: z<number, number, "volatile-defined">;
|
|
602
|
+
denseEnabled: z<boolean, boolean, "volatile-defined">;
|
|
595
603
|
/** Shortest user turn worth a recall decision. */
|
|
596
604
|
recallMinQueryChars: z<number, number, "volatile-defined">;
|
|
597
605
|
/** Distinct strong-field terms a recall needs before it is credited. */
|
|
@@ -738,6 +746,7 @@ export interface MemoriesSettings {
|
|
|
738
746
|
ragRecallExcerpts: number;
|
|
739
747
|
ragRecallSessions: number;
|
|
740
748
|
ragRecallChars: number;
|
|
749
|
+
denseEnabled: boolean;
|
|
741
750
|
recallMinQueryChars: number;
|
|
742
751
|
recallMinTerms: number;
|
|
743
752
|
/** Whether memories written after the summary are announced as a delta. */
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { MemoryEntry } from './types.js';
|
|
2
|
+
/** Where the embedding service is reached; the harness never calls outside the machine by default. */
|
|
3
|
+
export declare const DEFAULT_DENSE_URL = "http://127.0.0.1:11434";
|
|
4
|
+
/** The model the bench measured. Any embedding model works; the cache is keyed by name. */
|
|
5
|
+
export declare const DEFAULT_DENSE_MODEL = "qwen3-embedding:0.6b";
|
|
6
|
+
/** Settings for one dense pass. */
|
|
7
|
+
export interface DenseOptions {
|
|
8
|
+
/** Base URL of the embedding service, e.g. `http://127.0.0.1:11434`. */
|
|
9
|
+
readonly url: string;
|
|
10
|
+
/** Model name. */
|
|
11
|
+
readonly model: string;
|
|
12
|
+
/** Directory holding the JSON vector cache. */
|
|
13
|
+
readonly cacheDir: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Embed texts, reusing the on-disk cache.
|
|
17
|
+
*
|
|
18
|
+
* Failures propagate: the caller decides whether to fall back. The cache is
|
|
19
|
+
* written only after every batch succeeded, so a partial run never poisons it.
|
|
20
|
+
*
|
|
21
|
+
* @param texts - texts to embed, in order.
|
|
22
|
+
* @param options - service location, model, and cache directory.
|
|
23
|
+
* @returns one unit vector per text.
|
|
24
|
+
*/
|
|
25
|
+
export declare function embed(texts: readonly string[], options: DenseOptions): Promise<Float32Array[]>;
|
|
26
|
+
/**
|
|
27
|
+
* Cosine similarity of two unit vectors (a dot product).
|
|
28
|
+
* @param left - one vector.
|
|
29
|
+
* @param right - the other.
|
|
30
|
+
* @returns similarity in `[-1, 1]`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function cosine(left: Float32Array, right: Float32Array): number;
|
|
33
|
+
/**
|
|
34
|
+
* Score every entry against one query by embedding.
|
|
35
|
+
*
|
|
36
|
+
* @param entries - the entries to score.
|
|
37
|
+
* @param query - the turn.
|
|
38
|
+
* @param options - service location, model, and cache directory.
|
|
39
|
+
* @returns id → cosine similarity; empty when the service is unavailable.
|
|
40
|
+
*/
|
|
41
|
+
export declare function denseScores(entries: readonly MemoryEntry[], query: string, options: DenseOptions): Promise<Map<string, number>>;
|
|
42
|
+
/**
|
|
43
|
+
* Reciprocal rank fusion.
|
|
44
|
+
*
|
|
45
|
+
* The two channels disagree about scale, not about order, so their ranks are
|
|
46
|
+
* fused instead of their scores: each list contributes `1 / (k + rank)`, and
|
|
47
|
+
* the constant keeps a first place worth about twice a tenth.
|
|
48
|
+
*
|
|
49
|
+
* @param lists - ranked id lists, best first.
|
|
50
|
+
* @param k - fusion constant; 60 is the usual value.
|
|
51
|
+
* @returns id → fused score, descending.
|
|
52
|
+
*/
|
|
53
|
+
export declare function rrf(lists: readonly (readonly string[])[], k?: number): Map<string, number>;
|
package/lib/types/index.d.ts
CHANGED
|
@@ -142,6 +142,8 @@ export declare class MemoriesRuntime {
|
|
|
142
142
|
*/
|
|
143
143
|
logSinkError: string | undefined;
|
|
144
144
|
constructor(ctx: Context, config: MemoriesConfig, settings?: () => MemoriesSettings);
|
|
145
|
+
/** Embed the store once in the background so the first recall is not the slow one. */
|
|
146
|
+
private warmDense;
|
|
145
147
|
/**
|
|
146
148
|
* The LLM runtime to use right now.
|
|
147
149
|
*
|
|
@@ -500,6 +502,8 @@ export declare class MemoriesRuntime {
|
|
|
500
502
|
* @returns the predicate, or `undefined` when the discount is off.
|
|
501
503
|
*/
|
|
502
504
|
private hubFor;
|
|
505
|
+
/** Where the dense vector cache lives: `<dshHome>/cache/dsh-cross-memory`. */
|
|
506
|
+
private denseCacheDir;
|
|
503
507
|
/**
|
|
504
508
|
* The on-demand recall delta for this step, or `undefined` when nothing is
|
|
505
509
|
* worth adding.
|
|
@@ -1265,6 +1269,7 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
|
|
|
1265
1269
|
ragRecallExcerpts: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1266
1270
|
ragRecallSessions: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1267
1271
|
ragRecallChars: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1272
|
+
denseEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "volatile-defined">;
|
|
1268
1273
|
recallMinQueryChars: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1269
1274
|
recallMinTerms: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1270
1275
|
injectDelta: import("@deepseek-ai/schemastery").default<boolean, boolean, "volatile-defined">;
|
|
@@ -1341,6 +1346,7 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
|
|
|
1341
1346
|
ragRecallExcerpts: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1342
1347
|
ragRecallSessions: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1343
1348
|
ragRecallChars: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1349
|
+
denseEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "volatile-defined">;
|
|
1344
1350
|
recallMinQueryChars: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1345
1351
|
recallMinTerms: import("@deepseek-ai/schemastery").default<number, number, "volatile-defined">;
|
|
1346
1352
|
injectDelta: import("@deepseek-ai/schemastery").default<boolean, boolean, "volatile-defined">;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cross-memory",
|
|
3
3
|
"description": "Cross-session memory for the DeepSeek Harness: project-scoped and global memories with an explicit memory tool, idle-time background extraction, consolidation, and layered summary injection",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.11",
|
|
5
5
|
"private": false,
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"access": "public"
|