dsh-cross-memory 0.2.8 → 0.2.10
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/README.md +12 -2
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/lib/bm25.js +100 -0
- package/lib/cards.js +188 -0
- package/lib/client.js +200 -1
- package/lib/config.js +16 -4
- package/lib/dense.js +180 -0
- package/lib/index.js +174 -44
- package/lib/render.js +71 -18
- package/lib/search.js +33 -53
- package/lib/test/bm25.test.js +108 -0
- package/lib/test/dense.test.js +49 -0
- package/lib/test/injection.test.js +18 -2
- package/lib/test/proposal-card.test.js +353 -0
- package/lib/tokenize.js +68 -0
- package/lib/types/bm25.d.ts +66 -0
- package/lib/types/cards.d.ts +186 -0
- package/lib/types/config.d.ts +16 -4
- package/lib/types/dense.d.ts +53 -0
- package/lib/types/index.d.ts +30 -8
- package/lib/types/render.d.ts +1 -0
- package/lib/types/search.d.ts +1 -21
- package/lib/types/test/bm25.test.d.ts +1 -0
- package/lib/types/test/dense.test.d.ts +1 -0
- package/lib/types/test/proposal-card.test.d.ts +1 -0
- package/lib/types/tokenize.d.ts +39 -0
- package/package.json +8 -4
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';
|
|
@@ -39,6 +39,8 @@ import { listReflections, previousInsights, reflectionDue, runReflection, writeR
|
|
|
39
39
|
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
|
+
import { createBm25Index } from './bm25.js';
|
|
43
|
+
import { DEFAULT_DENSE_MODEL, DEFAULT_DENSE_URL, denseScores, rrf } from './dense.js';
|
|
42
44
|
import { findProjectRoot, isWithin } from './workspace.js';
|
|
43
45
|
import { citationRoots, citationWarning, ignoredUnder, missingCitations } from './citations.js';
|
|
44
46
|
import { planRetention, retentionKey } from './retention.js';
|
|
@@ -51,6 +53,7 @@ import { CONSOLIDATE_PRESET_ID, adjudicateDisputes, applyPlan, applyVerdicts, cl
|
|
|
51
53
|
import { discardDraft, listDrafts, promote, writeDraft } from './skills.js';
|
|
52
54
|
import { MEMORY_KINDS, MEMORY_SOURCE_KIND } from './types.js';
|
|
53
55
|
import { registerMemoryTool } from './tool.js';
|
|
56
|
+
import { PROPOSAL_ACTION, PROPOSAL_SKILL, registerProposalCard } from './cards.js';
|
|
54
57
|
import { REMOTE_CONTRIBUTION, REMOTE_NAMESPACE, REMOTE_SERVICE, createRemoteService } from './remote.js';
|
|
55
58
|
/** Plugin name; also the source tag of every injected message. */
|
|
56
59
|
export const name = 'memories';
|
|
@@ -284,6 +287,25 @@ export class MemoriesRuntime {
|
|
|
284
287
|
llm: () => this.llm,
|
|
285
288
|
log: this.log,
|
|
286
289
|
});
|
|
290
|
+
// Dense warm-up: embedding the whole store costs under a minute on a local
|
|
291
|
+
// 0.6b model and must not land inside a user's turn. Fire and forget; the
|
|
292
|
+
// first recall after this is a cache hit (measured 0.04s).
|
|
293
|
+
if (this.settings.denseEnabled)
|
|
294
|
+
void this.warmDense().catch(() => undefined);
|
|
295
|
+
}
|
|
296
|
+
/** Embed the store once in the background so the first recall is not the slow one. */
|
|
297
|
+
async warmDense() {
|
|
298
|
+
const entries = [...await this.store.list('global', undefined)];
|
|
299
|
+
for (const slug of await this.store.listProjects()) {
|
|
300
|
+
const descriptor = await this.store.readProjectDescriptor(slug);
|
|
301
|
+
if (descriptor === undefined)
|
|
302
|
+
continue;
|
|
303
|
+
entries.push(...await this.store.list('project', descriptor.root).catch(() => []));
|
|
304
|
+
}
|
|
305
|
+
if (entries.length === 0)
|
|
306
|
+
return;
|
|
307
|
+
await denseScores(entries, 'warm-up', { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
|
|
308
|
+
this.log.info('dsh-cross-memory: dense channel warmed (%d entries)', entries.length);
|
|
287
309
|
}
|
|
288
310
|
/**
|
|
289
311
|
* The LLM runtime to use right now.
|
|
@@ -679,14 +701,55 @@ export class MemoriesRuntime {
|
|
|
679
701
|
const projectHasEntries = states.some((state) => state.scope === 'project' && state.entries.length > 0);
|
|
680
702
|
const globalCap = projectHasEntries ? this.settings.globalSummaryEntries : this.settings.maxSummaryEntries;
|
|
681
703
|
const capOf = (state) => state.scope === 'global' ? globalCap : this.settings.maxSummaryEntries;
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
704
|
+
// Project memories render before global ones.
|
|
705
|
+
//
|
|
706
|
+
// The renderer walks the scopes in order and the byte budget keeps the head,
|
|
707
|
+
// so this is the decision about which memories a session actually reads.
|
|
708
|
+
// Measured on 20 real sessions with a live store: the first six rendered
|
|
709
|
+
// slots held 113 entries the session's own topic matched when project led,
|
|
710
|
+
// against 14 with global first — global's generic entries were occupying
|
|
711
|
+
// every slot the budget reliably reaches. Global keeps its own smaller cap
|
|
712
|
+
// and its own byte budget, so it is not crowded out, just no longer first.
|
|
713
|
+
const ordered = [
|
|
714
|
+
...states.filter((state) => state.scope === 'project'),
|
|
715
|
+
...states.filter((state) => state.scope === 'global'),
|
|
716
|
+
];
|
|
717
|
+
// Rank the scopes together, then let each scope pick from that order.
|
|
718
|
+
//
|
|
719
|
+
// Ranking per scope is what the renderer used to do, and it loses the
|
|
720
|
+
// cross-scope comparison: a global entry that shares a word with the opening
|
|
721
|
+
// turn outranks a project entry the turn is about, because each scope's top
|
|
722
|
+
// is taken without reference to the other. The merged ranking's first
|
|
723
|
+
// twelve entries measured 96% topic-relevant on 20 real sessions, against
|
|
724
|
+
// 67% for the per-scope rendering of the same store.
|
|
725
|
+
const stateOf = new Map();
|
|
726
|
+
for (const state of ordered)
|
|
727
|
+
for (const entry of state.entries)
|
|
728
|
+
stateOf.set(entry.id, state);
|
|
729
|
+
const merged = rankForSummary(ordered.flatMap((state) => state.entries), Date.now(), query);
|
|
730
|
+
const rankedByState = new Map();
|
|
731
|
+
for (const entry of merged) {
|
|
732
|
+
const state = stateOf.get(entry.id);
|
|
733
|
+
if (state === undefined)
|
|
734
|
+
continue;
|
|
735
|
+
const list = rankedByState.get(state);
|
|
736
|
+
if (list === undefined)
|
|
737
|
+
rankedByState.set(state, [entry]);
|
|
738
|
+
else
|
|
739
|
+
list.push(entry);
|
|
740
|
+
}
|
|
741
|
+
const selected = ordered.map((state) => {
|
|
742
|
+
const ranked = rankedByState.get(state);
|
|
743
|
+
return selectForSummary(state.entries, capOf(state), {
|
|
744
|
+
freshSlots: this.settings.summaryFreshSlots,
|
|
745
|
+
// The opening turn is the only topic signal available this early, and it
|
|
746
|
+
// is what keeps a globally scoped memory that shares nothing with this
|
|
747
|
+
// conversation from outranking one that does.
|
|
748
|
+
...query === undefined || query.length === 0 ? {} : { query },
|
|
749
|
+
...ranked === undefined ? {} : { ranked },
|
|
750
|
+
});
|
|
751
|
+
});
|
|
752
|
+
const scopes = ordered.map((state, index) => ({
|
|
690
753
|
label: state.label,
|
|
691
754
|
heading: state.heading,
|
|
692
755
|
entries: selected[index] ?? [],
|
|
@@ -841,7 +904,8 @@ export class MemoriesRuntime {
|
|
|
841
904
|
* Apply every waiting decision.
|
|
842
905
|
*
|
|
843
906
|
* @param _parent - the agent asking; the stored rows carry their own scope.
|
|
844
|
-
* @returns
|
|
907
|
+
* @returns the command's report plus the counts the action-card decision
|
|
908
|
+
* records, or `undefined` when nothing is staged.
|
|
845
909
|
*/
|
|
846
910
|
async applyPendingPlan(_parent) {
|
|
847
911
|
const pending = await readPendingPlan(this.store.memoriesDir);
|
|
@@ -853,14 +917,31 @@ export class MemoriesRuntime {
|
|
|
853
917
|
const result = await applyPlan(pending.plan, this.consolidationTarget(), root, { entries });
|
|
854
918
|
await clearPendingPlan(this.store.memoriesDir);
|
|
855
919
|
this.log.info('dsh-cross-memory: applied %d waiting consolidation decision(s): %d written, %d retired', pending.disputes.length, result.written, result.retired);
|
|
856
|
-
return
|
|
920
|
+
return {
|
|
921
|
+
text: `Applied ${pending.disputes.length} decision${pending.disputes.length === 1 ? '' : 's'}: ${result.written} written, ${result.retired} retired.`,
|
|
922
|
+
written: result.written,
|
|
923
|
+
retired: result.retired,
|
|
924
|
+
};
|
|
857
925
|
}
|
|
858
926
|
catch (error) {
|
|
859
927
|
const message = error instanceof Error ? error.message : String(error);
|
|
860
928
|
this.log.warn('dsh-cross-memory: applying the waiting decisions failed: %s', message);
|
|
861
|
-
return `Applying them failed and the store was rolled back: ${message}
|
|
929
|
+
return { text: `Applying them failed and the store was rolled back: ${message}`, written: 0, retired: 0 };
|
|
862
930
|
}
|
|
863
931
|
}
|
|
932
|
+
/**
|
|
933
|
+
* Discard every waiting decision, leaving the store untouched.
|
|
934
|
+
*
|
|
935
|
+
* @returns how many decisions were dropped, or `undefined` when nothing was staged.
|
|
936
|
+
*/
|
|
937
|
+
async rejectPendingPlan() {
|
|
938
|
+
const pending = await readPendingPlan(this.store.memoriesDir);
|
|
939
|
+
if (pending === undefined)
|
|
940
|
+
return undefined;
|
|
941
|
+
await clearPendingPlan(this.store.memoriesDir);
|
|
942
|
+
this.log.info('dsh-cross-memory: discarded %d waiting consolidation decision(s)', pending.disputes.length);
|
|
943
|
+
return pending.disputes.length;
|
|
944
|
+
}
|
|
864
945
|
/**
|
|
865
946
|
* A warning when this workspace's memory directory is shared with another
|
|
866
947
|
* repository of the same name.
|
|
@@ -917,6 +998,11 @@ export class MemoriesRuntime {
|
|
|
917
998
|
// retire" and nobody could see that 17 decisions were waiting.
|
|
918
999
|
const needDecision = pending.disputes.length > 0 ? `, ${pending.disputes.length} need you` : '';
|
|
919
1000
|
lines.push(`Pending consolidation proposal for ${pending.label}: ${pending.plan.upserts.length} to write, ${pending.plan.retire.length} to retire${needDecision} — review with /memories plan, then /memories apply or /memories reject.`);
|
|
1001
|
+
// The card is the in-answer path to the same question, but only the model
|
|
1002
|
+
// decides to offer it: the skill has to be loaded in the turn and the
|
|
1003
|
+
// block has to be the last thing in the answer. Naming the exact fields
|
|
1004
|
+
// here is what keeps count/stagedAt honest instead of invented.
|
|
1005
|
+
lines.push(`When the user asks about memory changes or pending decisions (记忆变更 / 待确认 / 待裁决), load the ${PROPOSAL_SKILL} skill first, then end the final answer with one \`action-card\` block for this proposal: action "${PROPOSAL_ACTION}", label ${JSON.stringify(pending.label)}, count ${pending.disputes.length}, stagedAt ${pending.at}.`);
|
|
920
1006
|
}
|
|
921
1007
|
// `dshHome` filters out drafts whose promoted copy is byte-identical: the
|
|
922
1008
|
// banner used to report already-promoted skills as pending forever.
|
|
@@ -1200,6 +1286,10 @@ export class MemoriesRuntime {
|
|
|
1200
1286
|
this.hubCache.set(signature, hub);
|
|
1201
1287
|
return hub;
|
|
1202
1288
|
}
|
|
1289
|
+
/** Where the dense vector cache lives: `<dshHome>/cache/dsh-cross-memory`. */
|
|
1290
|
+
denseCacheDir() {
|
|
1291
|
+
return join(dirname(this.store.memoriesDir), 'cache', 'dsh-cross-memory');
|
|
1292
|
+
}
|
|
1203
1293
|
/**
|
|
1204
1294
|
* The on-demand recall delta for this step, or `undefined` when nothing is
|
|
1205
1295
|
* worth adding.
|
|
@@ -1262,10 +1352,14 @@ export class MemoriesRuntime {
|
|
|
1262
1352
|
//
|
|
1263
1353
|
// The seeds for the one-hop expansion are taken after this sort for the same
|
|
1264
1354
|
// reason: they used to be whichever three candidates the store listed first.
|
|
1265
|
-
const byStrength = (left, right) => right.
|
|
1355
|
+
const byStrength = (left, right) => right.bm25 - left.bm25
|
|
1356
|
+
|| right.relevance - left.relevance
|
|
1266
1357
|
|| right.score - left.score
|
|
1267
1358
|
|| right.entry.updatedAt - left.entry.updatedAt
|
|
1268
1359
|
|| left.entry.title.localeCompare(right.entry.title);
|
|
1360
|
+
// One BM25 index over every entry the turn can see, so a global and a
|
|
1361
|
+
// project entry are ranked on the same document frequencies.
|
|
1362
|
+
const bm25Scores = createBm25Index(states.flatMap((state) => state.entries)).score(query);
|
|
1269
1363
|
const eligible = [];
|
|
1270
1364
|
let near;
|
|
1271
1365
|
for (const state of states) {
|
|
@@ -1291,7 +1385,7 @@ export class MemoriesRuntime {
|
|
|
1291
1385
|
}
|
|
1292
1386
|
continue;
|
|
1293
1387
|
}
|
|
1294
|
-
eligible.push({ entry, ...why });
|
|
1388
|
+
eligible.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
|
|
1295
1389
|
}
|
|
1296
1390
|
}
|
|
1297
1391
|
if (eligible.length === 0) {
|
|
@@ -1334,7 +1428,7 @@ export class MemoriesRuntime {
|
|
|
1334
1428
|
...hub === undefined ? {} : { hub },
|
|
1335
1429
|
});
|
|
1336
1430
|
if (why.about)
|
|
1337
|
-
byAlias.push({ entry, ...why });
|
|
1431
|
+
byAlias.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
|
|
1338
1432
|
}
|
|
1339
1433
|
}
|
|
1340
1434
|
if (byAlias.length > 0) {
|
|
@@ -1411,7 +1505,24 @@ export class MemoriesRuntime {
|
|
|
1411
1505
|
}
|
|
1412
1506
|
return undefined;
|
|
1413
1507
|
}
|
|
1414
|
-
|
|
1508
|
+
// Optional dense channel: re-rank what the gate admitted by fusing the
|
|
1509
|
+
// lexical order with an embedding order. Only the ORDER changes — the gate
|
|
1510
|
+
// still decides what may be recalled, so this cannot admit an entry the
|
|
1511
|
+
// lexical gate refused. When the service is unreachable, `denseScores`
|
|
1512
|
+
// returns an empty map and the lexical order stands.
|
|
1513
|
+
if (this.settings.denseEnabled && eligible.length > 1) {
|
|
1514
|
+
const dense = await denseScores(states.flatMap((state) => state.entries), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
|
|
1515
|
+
if (dense.size > 0) {
|
|
1516
|
+
const lexical = [...eligible].sort(byStrength).map((item) => item.entry.id);
|
|
1517
|
+
const semantic = [...dense.entries()].sort((left, right) => right[1] - left[1]).map(([id]) => id);
|
|
1518
|
+
const fused = rrf([lexical, semantic]);
|
|
1519
|
+
eligible.sort((left, right) => (fused.get(right.entry.id) ?? 0) - (fused.get(left.entry.id) ?? 0));
|
|
1520
|
+
this.log.info('dsh-cross-memory: session %s recall re-ranked by the dense channel (%d candidates)', session.id, eligible.length);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
else {
|
|
1524
|
+
eligible.sort(byStrength);
|
|
1525
|
+
}
|
|
1415
1526
|
// The one-hop neighbours go in after the seeds and carry no lexical
|
|
1416
1527
|
// relevance, so they can only fill slots the lexical path left empty — the
|
|
1417
1528
|
// case this exists for is a turn that names one fragment of something the
|
|
@@ -1426,6 +1537,7 @@ export class MemoriesRuntime {
|
|
|
1426
1537
|
relevance: 0,
|
|
1427
1538
|
score: hit.score,
|
|
1428
1539
|
best: '',
|
|
1540
|
+
bm25: 0,
|
|
1429
1541
|
evidence: { strongTerms: 0, phrase: false },
|
|
1430
1542
|
});
|
|
1431
1543
|
}
|
|
@@ -3096,12 +3208,17 @@ export class MemoriesRuntime {
|
|
|
3096
3208
|
/**
|
|
3097
3209
|
* Speak without being asked, when there is something to say.
|
|
3098
3210
|
*
|
|
3099
|
-
* Two deterministic triggers
|
|
3100
|
-
*
|
|
3101
|
-
*
|
|
3102
|
-
*
|
|
3103
|
-
*
|
|
3104
|
-
*
|
|
3211
|
+
* Two deterministic triggers: a daily line about what the plugin maintained,
|
|
3212
|
+
* and a promise whose deadline has passed. Both are judgements a rule can
|
|
3213
|
+
* make, which is why they are the ones allowed to interrupt. Everything
|
|
3214
|
+
* smarter (reflections) enters here later through the same queue, and the
|
|
3215
|
+
* same rules apply: evidence or silence, and never the same subject twice.
|
|
3216
|
+
*
|
|
3217
|
+
* A staged consolidation proposal no longer comes through this pump: its
|
|
3218
|
+
* backlog branch could not reach the user in this deployment (macOS
|
|
3219
|
+
* `osascript` is unavailable, so every delivery logged `no channel for notice
|
|
3220
|
+
* backlog`), and the answer card plus the injected draft note are the
|
|
3221
|
+
* confirmation path now.
|
|
3105
3222
|
*
|
|
3106
3223
|
* Called from the once-per-conversation hook and from the maintenance sweep. A
|
|
3107
3224
|
* failure is logged and swallowed: speaking is never allowed to break a turn.
|
|
@@ -3146,25 +3263,7 @@ export class MemoriesRuntime {
|
|
|
3146
3263
|
queue = { ...queue, lastDigestAt: now };
|
|
3147
3264
|
}
|
|
3148
3265
|
}
|
|
3149
|
-
// 2.
|
|
3150
|
-
const pending = await readPendingPlan(dir).catch(() => undefined);
|
|
3151
|
-
if (pending !== undefined && now - pending.at >= 12 * 3_600_000) {
|
|
3152
|
-
const age = Math.round((now - pending.at) / 3_600_000);
|
|
3153
|
-
const admitted = admitNotice(queue, {
|
|
3154
|
-
kind: 'backlog',
|
|
3155
|
-
createdAt: now,
|
|
3156
|
-
dueAt: now,
|
|
3157
|
-
title: `有 ${pending.disputes.length} 条记忆变更等你确认(已等 ${age} 小时,超时会丢弃)`,
|
|
3158
|
-
body: pending.disputes.map((row) => `- [${row.action}] ${row.title}:${row.reason}`).join('\n'),
|
|
3159
|
-
evidence: pending.disputes.map((row) => row.id),
|
|
3160
|
-
dedupeKey: `backlog:${pending.disputes.length}`,
|
|
3161
|
-
}, policy);
|
|
3162
|
-
if (admitted.ok)
|
|
3163
|
-
queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
|
|
3164
|
-
else
|
|
3165
|
-
this.log.decision('dsh-cross-memory: notice suppressed (%s)', admitted.reason);
|
|
3166
|
-
}
|
|
3167
|
-
// 3. Open loops whose deadline has passed. This is the trigger that makes
|
|
3266
|
+
// 2. Open loops whose deadline has passed. This is the trigger that makes
|
|
3168
3267
|
// the assistant pro-active rather than reactive: it needs no question to
|
|
3169
3268
|
// answer, only a promise the user made and has not closed.
|
|
3170
3269
|
const loopNow = pruneLoops(await readLoops(dir), now);
|
|
@@ -4272,6 +4371,35 @@ export function apply(ctx, config = {}) {
|
|
|
4272
4371
|
});
|
|
4273
4372
|
runtime = new MemoriesRuntime(ctx, config, read);
|
|
4274
4373
|
ctx.effect(() => () => runtime.dispose(), 'dsh-cross-memory.lifecycle');
|
|
4374
|
+
// A staged consolidation proposal can also wait as an answer-embedded action
|
|
4375
|
+
// card: the model offers it from its skill, and the buttons apply or discard
|
|
4376
|
+
// the whole batch. Both services are optional, and an older action-card
|
|
4377
|
+
// service has no `skillProvider`; in either case the command and the settings
|
|
4378
|
+
// panel stay the only confirmation paths, which is the degradation this
|
|
4379
|
+
// plugin has always supported.
|
|
4380
|
+
ctx.inject(['actionCards', 'skills'], (child) => {
|
|
4381
|
+
const { actionCards, skills } = child;
|
|
4382
|
+
if (actionCards === undefined || skills === undefined)
|
|
4383
|
+
return;
|
|
4384
|
+
if (typeof actionCards.skillProvider !== 'function') {
|
|
4385
|
+
log.info('dsh-cross-memory: the action-card service predates answer cards; the confirmation card is skipped');
|
|
4386
|
+
return;
|
|
4387
|
+
}
|
|
4388
|
+
const seam = {
|
|
4389
|
+
pending: async () => {
|
|
4390
|
+
const pending = await readPendingPlan(runtime.store.memoriesDir).catch(() => undefined);
|
|
4391
|
+
return pending === undefined
|
|
4392
|
+
? undefined
|
|
4393
|
+
: { label: pending.label, count: pending.disputes.length, stagedAt: pending.at };
|
|
4394
|
+
},
|
|
4395
|
+
apply: async (agent) => {
|
|
4396
|
+
const result = await runtime.applyPendingPlan(agent);
|
|
4397
|
+
return result === undefined ? undefined : { written: result.written, retired: result.retired };
|
|
4398
|
+
},
|
|
4399
|
+
reject: () => runtime.rejectPendingPlan(),
|
|
4400
|
+
};
|
|
4401
|
+
child.effect(() => registerProposalCard(actionCards, skills, seam), 'dsh-cross-memory.proposalCard');
|
|
4402
|
+
});
|
|
4275
4403
|
// The consolidation child needs a composition of its own. Since 0.2.1-rc.2 a
|
|
4276
4404
|
// subagent takes its tool set from the preset it names, and a child that
|
|
4277
4405
|
// names none inherits the parent's composition — the parent's tools, which is
|
|
@@ -4656,11 +4784,13 @@ async function handleCommand(runtime, invocation) {
|
|
|
4656
4784
|
}
|
|
4657
4785
|
case 'apply': {
|
|
4658
4786
|
const summary = await runtime.applyPendingPlan(invocation.agent);
|
|
4659
|
-
return { kind: 'success', text: summary ?? 'No consolidation proposal is waiting.' };
|
|
4787
|
+
return { kind: 'success', text: summary?.text ?? 'No consolidation proposal is waiting.' };
|
|
4660
4788
|
}
|
|
4661
4789
|
case 'reject': {
|
|
4662
|
-
const dropped = await
|
|
4663
|
-
return
|
|
4790
|
+
const dropped = await runtime.rejectPendingPlan();
|
|
4791
|
+
return dropped === undefined
|
|
4792
|
+
? { kind: 'success', text: 'No consolidation proposal is waiting.' }
|
|
4793
|
+
: { kind: 'success', text: `Discarded ${dropped} waiting decision${dropped === 1 ? '' : 's'}. The store is unchanged.` };
|
|
4664
4794
|
}
|
|
4665
4795
|
case 'mine': {
|
|
4666
4796
|
const count = await runtime.mineNow(invocation.agent);
|