dsh-cross-memory 0.2.12 → 0.2.14
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 +55 -16
- package/docs/DETAIL.md +13 -10
- package/docs/DETAIL.zh.md +13 -10
- package/lib/backfill.js +32 -1
- package/lib/client.js +3 -3
- package/lib/consolidate.js +41 -39
- package/lib/dense.js +47 -15
- package/lib/extract.js +39 -11
- package/lib/gate.js +35 -19
- package/lib/index.js +221 -131
- package/lib/mcp.js +330 -0
- package/lib/notify.js +10 -5
- package/lib/persona.js +99 -1
- package/lib/raw-recall.js +18 -7
- package/lib/reflection.js +10 -1
- package/lib/state.js +19 -7
- package/lib/storage.js +11 -1
- package/lib/sync.js +36 -14
- package/lib/test/archive.test.js +19 -0
- package/lib/test/consolidate.test.js +48 -10
- package/lib/test/extract.test.js +30 -1
- package/lib/test/loops.test.js +3 -2
- package/lib/test/mcp.test.js +103 -0
- package/lib/test/notices.test.js +67 -0
- package/lib/test/persona.test.js +40 -1
- package/lib/test/recall.test.js +54 -1
- package/lib/test/reflection.test.js +60 -1
- package/lib/test/subagent-contract.test.js +18 -12
- package/lib/test/sync.test.js +4 -0
- package/lib/tool.js +4 -3
- package/lib/types/backfill.d.ts +5 -0
- package/lib/types/consolidate.d.ts +34 -51
- package/lib/types/dense.d.ts +7 -2
- package/lib/types/extract.d.ts +14 -0
- package/lib/types/gate.d.ts +4 -0
- package/lib/types/index.d.ts +10 -0
- package/lib/types/mcp.d.ts +184 -0
- package/lib/types/notify.d.ts +3 -2
- package/lib/types/persona.d.ts +17 -0
- package/lib/types/raw-recall.d.ts +1 -0
- package/lib/types/sync.d.ts +7 -5
- package/lib/types/test/mcp.test.d.ts +1 -0
- package/package.json +14 -7
package/lib/mcp.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Lightweight stdio MCP server for `dsh-cross-memory`.
|
|
4
|
+
*
|
|
5
|
+
* Exposes the local `$DSH_HOME/memories` store (and `persona/human.md`) to any
|
|
6
|
+
* MCP-capable client — Antigravity, Claude Code, Cursor, Codex, VS Code — with
|
|
7
|
+
* zero extra runtime dependencies. Reads and writes the exact same Markdown
|
|
8
|
+
* files that DSH maintains, using BM25 lexical search plus optional local
|
|
9
|
+
* embedding RRF re-ranking (`qwen3-embedding:0.6b` via Ollama, silent lexical
|
|
10
|
+
* fallback when unreachable).
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-cross-memory/mcp
|
|
13
|
+
*/
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { dirname, join, resolve } from 'node:path';
|
|
16
|
+
import { createInterface } from 'node:readline';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { DEFAULT_DENSE_MODEL, DEFAULT_DENSE_URL, denseScores, rrf } from './dense.js';
|
|
19
|
+
import { redactSecrets } from './extract.js';
|
|
20
|
+
import { readPersona } from './persona.js';
|
|
21
|
+
import { renderEntry, renderHit } from './render.js';
|
|
22
|
+
import { browseMemories, searchMemories, suggestAliases } from './search.js';
|
|
23
|
+
import { MemoryStore, projectSlug } from './storage.js';
|
|
24
|
+
import { toMemoryDurability, toMemoryKind } from './types.js';
|
|
25
|
+
/** Protocol version advertised when the client does not specify one. */
|
|
26
|
+
const DEFAULT_PROTOCOL_VERSION = '2024-11-05';
|
|
27
|
+
/** Tool definitions exposed to MCP clients (compact on purpose). */
|
|
28
|
+
export const MCP_TOOLS = [
|
|
29
|
+
{
|
|
30
|
+
name: 'memory_persona',
|
|
31
|
+
description: 'Read the user profile (persona/human.md): who the user is, their working conventions, standards, environment, and communication preferences. Call this early in a new session when user preferences matter.',
|
|
32
|
+
inputSchema: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
properties: {},
|
|
35
|
+
additionalProperties: false,
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
name: 'memory_search',
|
|
40
|
+
description: 'Search durable cross-session memories (global and/or one project workspace) using BM25 + optional local embedding hybrid ranking. Omit query to browse recent entries.',
|
|
41
|
+
inputSchema: {
|
|
42
|
+
type: 'object',
|
|
43
|
+
properties: {
|
|
44
|
+
query: { type: 'string', description: 'Search query (Chinese or English). Empty lists most recent entries.' },
|
|
45
|
+
scope: { type: 'string', enum: ['global', 'project', 'all'], description: 'Target scope; defaults to all (project + global when projectRoot/projectSlug is given, otherwise global).' },
|
|
46
|
+
projectRoot: { type: 'string', description: 'Absolute path of the current workspace root (used to resolve project scope).' },
|
|
47
|
+
projectSlug: { type: 'string', description: 'Explicit project directory slug under memories/projects/ (alternative to projectRoot).' },
|
|
48
|
+
kind: { type: 'string', enum: ['fact', 'preference', 'knowledge', 'failure', 'procedure'], description: 'Filter by memory kind.' },
|
|
49
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Optional lowercase tag filters.' },
|
|
50
|
+
limit: { type: 'integer', minimum: 1, maximum: 25, description: 'Maximum hits to return (default 8, max 25).' },
|
|
51
|
+
},
|
|
52
|
+
additionalProperties: false,
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'memory_read',
|
|
57
|
+
description: 'Read the full body and metadata of one memory entry by id.',
|
|
58
|
+
inputSchema: {
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: {
|
|
61
|
+
id: { type: 'string', description: 'Entry id returned by memory_search.' },
|
|
62
|
+
scope: { type: 'string', enum: ['global', 'project'], description: 'Scope to read from (defaults to project then global).' },
|
|
63
|
+
projectRoot: { type: 'string', description: 'Workspace root for project scope.' },
|
|
64
|
+
projectSlug: { type: 'string', description: 'Explicit project slug for project scope.' },
|
|
65
|
+
},
|
|
66
|
+
required: ['id'],
|
|
67
|
+
additionalProperties: false,
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: 'memory_write',
|
|
72
|
+
description: 'Write or update a durable memory entry. Title is the identity (same title updates in place). Credentials and passwords are automatically redacted before persistence.',
|
|
73
|
+
inputSchema: {
|
|
74
|
+
type: 'object',
|
|
75
|
+
properties: {
|
|
76
|
+
scope: { type: 'string', enum: ['global', 'project'], description: 'global for cross-project facts/preferences, project for one workspace.' },
|
|
77
|
+
title: { type: 'string', description: 'Short imperative heading (max 120 chars).' },
|
|
78
|
+
body: { type: 'string', description: 'Self-contained fact, 1-4 sentences.' },
|
|
79
|
+
kind: { type: 'string', enum: ['fact', 'preference', 'knowledge', 'failure', 'procedure'] },
|
|
80
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
81
|
+
keys: { type: 'array', items: { type: 'string' }, description: 'Aliases and bilingual search keywords.' },
|
|
82
|
+
appliesTo: { type: 'string', description: 'Short phrase saying when this memory matters.' },
|
|
83
|
+
durability: { type: 'string', enum: ['durable', 'snapshot'] },
|
|
84
|
+
pinned: { type: 'boolean' },
|
|
85
|
+
permanent: { type: 'boolean' },
|
|
86
|
+
projectRoot: { type: 'string', description: 'Workspace root (required when scope=project unless projectSlug is given).' },
|
|
87
|
+
projectSlug: { type: 'string', description: 'Explicit project slug (alternative to projectRoot).' },
|
|
88
|
+
},
|
|
89
|
+
required: ['scope', 'title', 'body'],
|
|
90
|
+
additionalProperties: false,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
name: 'memory_projects',
|
|
95
|
+
description: 'List known project memory scopes with their slugs, recorded workspace roots, and entry counts.',
|
|
96
|
+
inputSchema: {
|
|
97
|
+
type: 'object',
|
|
98
|
+
properties: {},
|
|
99
|
+
additionalProperties: false,
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
/** Resolve default options from environment variables. */
|
|
104
|
+
export function defaultMcpOptions(env = process.env) {
|
|
105
|
+
const dshHome = env['DSH_HOME']?.trim() || join(homedir(), '.dsh');
|
|
106
|
+
const memoriesDir = resolve(env['DSH_MEMORIES_DIR']?.trim() || join(dshHome, 'memories'));
|
|
107
|
+
const cacheDir = resolve(env['DSH_MEMORY_CACHE_DIR']?.trim() || join(dshHome, 'cache', 'dsh-cross-memory'));
|
|
108
|
+
const denseEnv = env['DSH_MEMORY_DENSE']?.trim().toLowerCase();
|
|
109
|
+
const denseEnabled = denseEnv === undefined ? true : !(denseEnv === '0' || denseEnv === 'false' || denseEnv === 'off');
|
|
110
|
+
const denseUrl = env['DSH_MEMORY_DENSE_URL']?.trim() || DEFAULT_DENSE_URL;
|
|
111
|
+
const denseModel = env['DSH_MEMORY_DENSE_MODEL']?.trim() || DEFAULT_DENSE_MODEL;
|
|
112
|
+
return { memoriesDir, cacheDir, denseEnabled, denseUrl, denseModel };
|
|
113
|
+
}
|
|
114
|
+
/** Resolve a workspace root argument from either `projectRoot` or `projectSlug`. */
|
|
115
|
+
async function resolveProjectRoot(store, projectRootArg, projectSlugArg) {
|
|
116
|
+
if (typeof projectRootArg === 'string' && projectRootArg.trim().length > 0) {
|
|
117
|
+
return resolve(projectRootArg.trim());
|
|
118
|
+
}
|
|
119
|
+
if (typeof projectSlugArg === 'string' && projectSlugArg.trim().length > 0) {
|
|
120
|
+
const slug = projectSlugArg.trim();
|
|
121
|
+
const descriptor = await store.readProjectDescriptor(slug);
|
|
122
|
+
return descriptor?.root;
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/** Build text tool result envelope. */
|
|
127
|
+
function textResult(text, isError = false) {
|
|
128
|
+
return isError ? { content: [{ type: 'text', text }], isError: true } : { content: [{ type: 'text', text }] };
|
|
129
|
+
}
|
|
130
|
+
/** Re-rank lexical hits with the optional local dense embedding channel. */
|
|
131
|
+
async function maybeDenseRerank(hits, query, options, limit) {
|
|
132
|
+
if (!options.denseEnabled || hits.length <= 1 || query.trim().length === 0)
|
|
133
|
+
return hits.slice(0, limit);
|
|
134
|
+
const pool = hits.slice(0, Math.min(hits.length, 32));
|
|
135
|
+
const cacheDir = options.cacheDir ?? join(dirname(options.memoriesDir), 'cache', 'dsh-cross-memory');
|
|
136
|
+
const scores = await denseScores(pool.map((hit) => hit.entry), query, { url: options.denseUrl, model: options.denseModel, cacheDir });
|
|
137
|
+
if (scores.size === 0)
|
|
138
|
+
return hits.slice(0, limit);
|
|
139
|
+
const lexical = pool.map((hit) => hit.entry.id);
|
|
140
|
+
const semantic = [...scores.entries()].sort((a, b) => b[1] - a[1]).map(([id]) => id);
|
|
141
|
+
const fused = rrf([lexical, semantic]);
|
|
142
|
+
return [...pool]
|
|
143
|
+
.sort((a, b) => (fused.get(b.entry.id) ?? 0) - (fused.get(a.entry.id) ?? 0))
|
|
144
|
+
.slice(0, limit);
|
|
145
|
+
}
|
|
146
|
+
/** Execute one MCP tool call. */
|
|
147
|
+
async function executeTool(name, args, store, options) {
|
|
148
|
+
switch (name) {
|
|
149
|
+
case 'memory_persona': {
|
|
150
|
+
const persona = await readPersona(options.memoriesDir);
|
|
151
|
+
if (persona === undefined)
|
|
152
|
+
return textResult('No persona profile stored yet.');
|
|
153
|
+
return textResult(persona);
|
|
154
|
+
}
|
|
155
|
+
case 'memory_projects': {
|
|
156
|
+
const slugs = await store.listProjects();
|
|
157
|
+
if (slugs.length === 0)
|
|
158
|
+
return textResult('No project memory scopes found.');
|
|
159
|
+
const lines = [`${slugs.length} project scopes:`];
|
|
160
|
+
for (const slug of slugs) {
|
|
161
|
+
const desc = await store.readProjectDescriptor(slug);
|
|
162
|
+
const root = desc?.root ?? join(store.memoriesDir, 'projects', slug);
|
|
163
|
+
const entries = await store.list('project', root).catch(() => []);
|
|
164
|
+
lines.push(`- ${slug} (${entries.length} entries)${desc?.root ? ` — ${desc.root}` : ''}`);
|
|
165
|
+
}
|
|
166
|
+
return textResult(lines.join('\n'));
|
|
167
|
+
}
|
|
168
|
+
case 'memory_search': {
|
|
169
|
+
const query = typeof args['query'] === 'string' ? args['query'].trim() : '';
|
|
170
|
+
const scopeArg = typeof args['scope'] === 'string' ? args['scope'] : 'all';
|
|
171
|
+
const rawLimit = typeof args['limit'] === 'number' ? args['limit'] : 8;
|
|
172
|
+
const limit = Math.min(Math.max(Math.trunc(rawLimit), 1), 25);
|
|
173
|
+
const kind = typeof args['kind'] === 'string' ? toMemoryKind(args['kind']) : undefined;
|
|
174
|
+
const tags = Array.isArray(args['tags']) ? args['tags'].filter((t) => typeof t === 'string') : [];
|
|
175
|
+
const projectRoot = await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']);
|
|
176
|
+
const groups = [];
|
|
177
|
+
if ((scopeArg === 'all' || scopeArg === 'project') && projectRoot !== undefined) {
|
|
178
|
+
const entries = await store.list('project', projectRoot).catch(() => []);
|
|
179
|
+
if (entries.length > 0)
|
|
180
|
+
groups.push({ scope: 'project', label: store.target('project', projectRoot).label, entries });
|
|
181
|
+
}
|
|
182
|
+
if (scopeArg === 'all' || scopeArg === 'global') {
|
|
183
|
+
const entries = await store.list('global', undefined).catch(() => []);
|
|
184
|
+
if (entries.length > 0)
|
|
185
|
+
groups.push({ scope: 'global', label: 'global', entries });
|
|
186
|
+
}
|
|
187
|
+
if (groups.length === 0)
|
|
188
|
+
return textResult('No memories available in the requested scope.');
|
|
189
|
+
const filter = {
|
|
190
|
+
...tags.length > 0 ? { tags } : {},
|
|
191
|
+
...kind === undefined ? {} : { kinds: [kind] },
|
|
192
|
+
limit: query.length > 0 ? Math.max(limit * 3, 24) : limit,
|
|
193
|
+
};
|
|
194
|
+
const rawHits = query.length === 0
|
|
195
|
+
? browseMemories(groups, filter)
|
|
196
|
+
: searchMemories(groups, query, filter);
|
|
197
|
+
const hits = query.length === 0
|
|
198
|
+
? rawHits.slice(0, limit)
|
|
199
|
+
: await maybeDenseRerank(rawHits, query, options, limit);
|
|
200
|
+
if (hits.length === 0) {
|
|
201
|
+
const hints = query.length === 0 ? [] : suggestAliases(groups, query, 12);
|
|
202
|
+
const hintLine = hints.length === 0
|
|
203
|
+
? ''
|
|
204
|
+
: `\nAliases/tags in store: ${hints.map((h) => h.term).join(', ')}`;
|
|
205
|
+
return textResult(`No memories matched ${JSON.stringify(query)}.${hintLine}`);
|
|
206
|
+
}
|
|
207
|
+
return textResult([`${hits.length} memories:`, ...hits.map((hit, i) => renderHit(hit, i))].join('\n'));
|
|
208
|
+
}
|
|
209
|
+
case 'memory_read': {
|
|
210
|
+
const id = typeof args['id'] === 'string' ? args['id'].trim() : '';
|
|
211
|
+
if (id.length === 0)
|
|
212
|
+
return textResult('memory_read requires a non-empty id.', true);
|
|
213
|
+
const scopeArg = args['scope'] === 'global' || args['scope'] === 'project' ? args['scope'] : undefined;
|
|
214
|
+
const projectRoot = await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']);
|
|
215
|
+
const order = scopeArg !== undefined ? [scopeArg] : projectRoot !== undefined ? ['project', 'global'] : ['global'];
|
|
216
|
+
for (const scope of order) {
|
|
217
|
+
if (scope === 'project' && projectRoot === undefined)
|
|
218
|
+
continue;
|
|
219
|
+
const entry = await store.read(scope, scope === 'project' ? projectRoot : undefined, id);
|
|
220
|
+
if (entry !== undefined)
|
|
221
|
+
return textResult(renderEntry(entry));
|
|
222
|
+
}
|
|
223
|
+
return textResult(`Memory not found: ${id}`, true);
|
|
224
|
+
}
|
|
225
|
+
case 'memory_write': {
|
|
226
|
+
const scope = args['scope'] === 'global' || args['scope'] === 'project' ? args['scope'] : undefined;
|
|
227
|
+
const rawTitle = typeof args['title'] === 'string' ? args['title'].trim() : '';
|
|
228
|
+
const rawBody = typeof args['body'] === 'string' ? args['body'].trim() : '';
|
|
229
|
+
if (scope === undefined)
|
|
230
|
+
return textResult('memory_write requires scope ("global" or "project").', true);
|
|
231
|
+
if (rawTitle.length === 0 || rawBody.length === 0)
|
|
232
|
+
return textResult('memory_write requires non-empty title and body.', true);
|
|
233
|
+
const projectRoot = scope === 'project' ? await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']) : undefined;
|
|
234
|
+
if (scope === 'project' && projectRoot === undefined) {
|
|
235
|
+
return textResult('memory_write with scope="project" requires projectRoot or projectSlug.', true);
|
|
236
|
+
}
|
|
237
|
+
const tags = Array.isArray(args['tags']) ? args['tags'].filter((t) => typeof t === 'string') : [];
|
|
238
|
+
const keys = Array.isArray(args['keys']) ? args['keys'].filter((k) => typeof k === 'string') : undefined;
|
|
239
|
+
const appliesTo = typeof args['appliesTo'] === 'string' && args['appliesTo'].trim().length > 0
|
|
240
|
+
? redactSecrets(args['appliesTo'].trim())
|
|
241
|
+
: undefined;
|
|
242
|
+
const durability = typeof args['durability'] === 'string' ? toMemoryDurability(args['durability']) : undefined;
|
|
243
|
+
const result = await store.upsert({
|
|
244
|
+
scope,
|
|
245
|
+
title: redactSecrets(rawTitle).slice(0, 120),
|
|
246
|
+
body: redactSecrets(rawBody),
|
|
247
|
+
tags,
|
|
248
|
+
...typeof args['kind'] === 'string' ? { kind: toMemoryKind(args['kind']) } : {},
|
|
249
|
+
...keys === undefined ? {} : { keys },
|
|
250
|
+
...appliesTo === undefined ? {} : { appliesTo },
|
|
251
|
+
...durability === undefined ? {} : { durability, ...durability === 'snapshot' ? { asOf: Date.now() } : {} },
|
|
252
|
+
...typeof args['pinned'] === 'boolean' ? { pinned: args['pinned'] } : {},
|
|
253
|
+
...typeof args['permanent'] === 'boolean' ? { permanent: args['permanent'] } : {},
|
|
254
|
+
}, projectRoot, 'tool');
|
|
255
|
+
if (scope === 'project' && projectRoot !== undefined) {
|
|
256
|
+
await store.writeProjectDescriptor(projectRoot).catch(() => undefined);
|
|
257
|
+
}
|
|
258
|
+
return textResult(`${result.action === 'created' ? 'Remembered' : 'Updated'} ${scope}${projectRoot ? `:${projectSlug(projectRoot)}` : ''} memory "${result.entry.title}" (id=${result.entry.id}).`);
|
|
259
|
+
}
|
|
260
|
+
default:
|
|
261
|
+
return textResult(`Unknown tool: ${name}`, true);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Handle one JSON-RPC 2.0 request. Returns `undefined` for notifications. */
|
|
265
|
+
export async function handleMcpRequest(request, options, store = new MemoryStore(options.memoriesDir)) {
|
|
266
|
+
const id = request.id;
|
|
267
|
+
const isNotification = id === undefined;
|
|
268
|
+
const ok = (result) => ({ jsonrpc: '2.0', id: id ?? null, result });
|
|
269
|
+
const fail = (code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
|
|
270
|
+
switch (request.method) {
|
|
271
|
+
case 'initialize': {
|
|
272
|
+
const requested = typeof request.params?.['protocolVersion'] === 'string'
|
|
273
|
+
? request.params['protocolVersion']
|
|
274
|
+
: DEFAULT_PROTOCOL_VERSION;
|
|
275
|
+
return ok({
|
|
276
|
+
protocolVersion: requested,
|
|
277
|
+
capabilities: { tools: {} },
|
|
278
|
+
serverInfo: { name: 'dsh-cross-memory', version: '0.2.14' },
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
case 'notifications/initialized':
|
|
282
|
+
case 'notifications/cancelled':
|
|
283
|
+
return undefined;
|
|
284
|
+
case 'ping':
|
|
285
|
+
return isNotification ? undefined : ok({});
|
|
286
|
+
case 'tools/list':
|
|
287
|
+
return ok({ tools: MCP_TOOLS });
|
|
288
|
+
case 'tools/call': {
|
|
289
|
+
const toolName = typeof request.params?.['name'] === 'string' ? request.params['name'] : '';
|
|
290
|
+
const toolArgs = (typeof request.params?.['arguments'] === 'object' && request.params['arguments'] !== null)
|
|
291
|
+
? request.params['arguments']
|
|
292
|
+
: {};
|
|
293
|
+
try {
|
|
294
|
+
const result = await executeTool(toolName, toolArgs, store, options);
|
|
295
|
+
return ok(result);
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
299
|
+
return ok(textResult(`Error: ${message}`, true));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
default:
|
|
303
|
+
return isNotification ? undefined : fail(-32601, `Method not found: ${request.method}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** Run the newline-delimited JSON-RPC 2.0 stdio loop. */
|
|
307
|
+
export function startStdioServer(options = defaultMcpOptions()) {
|
|
308
|
+
const store = new MemoryStore(options.memoriesDir);
|
|
309
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
310
|
+
rl.on('line', (line) => {
|
|
311
|
+
const trimmed = line.trim();
|
|
312
|
+
if (trimmed.length === 0)
|
|
313
|
+
return;
|
|
314
|
+
let parsed;
|
|
315
|
+
try {
|
|
316
|
+
parsed = JSON.parse(trimmed);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
void handleMcpRequest(parsed, options, store).then((response) => {
|
|
323
|
+
if (response !== undefined)
|
|
324
|
+
process.stdout.write(`${JSON.stringify(response)}\n`);
|
|
325
|
+
});
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
const isDirectRun = process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
|
|
329
|
+
if (isDirectRun)
|
|
330
|
+
startStdioServer();
|
package/lib/notify.js
CHANGED
|
@@ -9,9 +9,12 @@
|
|
|
9
9
|
*
|
|
10
10
|
* @module dsh-cross-memory/notify
|
|
11
11
|
*/
|
|
12
|
-
import {
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { promisify } from 'node:util';
|
|
14
|
+
const execFileAsync = promisify(execFile);
|
|
13
15
|
/**
|
|
14
|
-
* Post a macOS notification
|
|
16
|
+
* Post a macOS notification asynchronously so the Host event loop is never
|
|
17
|
+
* blocked waiting on AppleScript.
|
|
15
18
|
*
|
|
16
19
|
* Deliberately the quiet kind: no sound, no focus steal. The point is that a
|
|
17
20
|
* notice is not lost, not that it interrupts. Never throws — a notification
|
|
@@ -21,11 +24,13 @@ import { spawnSync } from 'node:child_process';
|
|
|
21
24
|
* @param message - notification body.
|
|
22
25
|
* @returns whether `osascript` accepted it.
|
|
23
26
|
*/
|
|
24
|
-
export function systemNotification(title, message) {
|
|
27
|
+
export async function systemNotification(title, message) {
|
|
28
|
+
if (process.platform !== 'darwin')
|
|
29
|
+
return false;
|
|
25
30
|
const script = `display notification "${message.replace(/["\\]/gu, '')}" with title "${title.replace(/["\\]/gu, '')}"`;
|
|
26
31
|
try {
|
|
27
|
-
|
|
28
|
-
return
|
|
32
|
+
await execFileAsync('osascript', ['-e', script], { timeout: 3_000 });
|
|
33
|
+
return true;
|
|
29
34
|
}
|
|
30
35
|
catch {
|
|
31
36
|
return false;
|
package/lib/persona.js
CHANGED
|
@@ -55,11 +55,108 @@ export async function readPersona(memoriesDir) {
|
|
|
55
55
|
const body = legacy?.trim();
|
|
56
56
|
return body !== undefined && body.length > 0 ? body : undefined;
|
|
57
57
|
}
|
|
58
|
+
/** A Latin/digit/underscore word run. */
|
|
59
|
+
const PERSONA_LATIN = /^[0-9a-z_]+$/u;
|
|
60
|
+
/** Split a persona bullet into normalized tokens (Latin words + CJK chars/bigrams). */
|
|
61
|
+
function personaTokens(line) {
|
|
62
|
+
const body = line.replace(/^\s*[-*]\s+/u, '').toLowerCase();
|
|
63
|
+
const tokens = new Set();
|
|
64
|
+
for (const raw of body.split(/[^\p{L}\p{N}_]+/u)) {
|
|
65
|
+
if (raw.length === 0)
|
|
66
|
+
continue;
|
|
67
|
+
if (PERSONA_LATIN.test(raw)) {
|
|
68
|
+
tokens.add(raw);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const chars = [...raw];
|
|
72
|
+
for (const char of chars)
|
|
73
|
+
tokens.add(char);
|
|
74
|
+
for (let i = 0; i + 1 < chars.length; i += 1)
|
|
75
|
+
tokens.add(`${chars[i]}${chars[i + 1]}`);
|
|
76
|
+
}
|
|
77
|
+
return tokens;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Whether two persona bullets express the same rule (rephrased or tightened).
|
|
81
|
+
*
|
|
82
|
+
* A consolidation pass often tightens a bullet's wording on one machine while
|
|
83
|
+
* another machine still holds the older phrasing. Exact-string matching treats
|
|
84
|
+
* both as distinct rules and doubles every section on sync. Token overlap +
|
|
85
|
+
* containment catches rewrites without merging genuinely different rules.
|
|
86
|
+
*/
|
|
87
|
+
export function isNearDuplicateBullet(left, right) {
|
|
88
|
+
const a = left.trim();
|
|
89
|
+
const b = right.trim();
|
|
90
|
+
if (a === b)
|
|
91
|
+
return true;
|
|
92
|
+
const ta = personaTokens(a);
|
|
93
|
+
const tb = personaTokens(b);
|
|
94
|
+
const smaller = Math.min(ta.size, tb.size);
|
|
95
|
+
// Short bullets (e.g. "- 左机的规则" vs "- 右机的规则") share most of their
|
|
96
|
+
// tokens through a common suffix; only full-sentence rules are candidates for
|
|
97
|
+
// fuzzy deduplication.
|
|
98
|
+
if (smaller < 12)
|
|
99
|
+
return false;
|
|
100
|
+
let shared = 0;
|
|
101
|
+
for (const token of ta)
|
|
102
|
+
if (tb.has(token))
|
|
103
|
+
shared += 1;
|
|
104
|
+
if (shared < 10)
|
|
105
|
+
return false;
|
|
106
|
+
const jaccard = shared / (ta.size + tb.size - shared);
|
|
107
|
+
if (jaccard >= 0.48)
|
|
108
|
+
return true;
|
|
109
|
+
const containment = shared / smaller;
|
|
110
|
+
return containment >= 0.72;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Deduplicate exact and near-duplicate bullets inside each section of a persona
|
|
114
|
+
* markdown document, keeping the earlier bullet when two bullets state the same
|
|
115
|
+
* rule. Also collapses repeated blank lines.
|
|
116
|
+
*/
|
|
117
|
+
export function dedupePersona(body) {
|
|
118
|
+
const out = [];
|
|
119
|
+
let sectionBullets = [];
|
|
120
|
+
let prevBlank = false;
|
|
121
|
+
for (const rawLine of body.split('\n')) {
|
|
122
|
+
const line = rawLine.trimEnd();
|
|
123
|
+
if (line.startsWith('#')) {
|
|
124
|
+
sectionBullets = [];
|
|
125
|
+
if (out.length > 0 && !prevBlank)
|
|
126
|
+
out.push('');
|
|
127
|
+
out.push(line);
|
|
128
|
+
prevBlank = false;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (/^\s*[-*]\s+/u.test(line)) {
|
|
132
|
+
if (sectionBullets.some((existing) => isNearDuplicateBullet(existing, line)))
|
|
133
|
+
continue;
|
|
134
|
+
sectionBullets.push(line);
|
|
135
|
+
out.push(line);
|
|
136
|
+
prevBlank = false;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (line.trim() === '') {
|
|
140
|
+
if (out.length === 0 || prevBlank)
|
|
141
|
+
continue;
|
|
142
|
+
out.push('');
|
|
143
|
+
prevBlank = true;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
out.push(line);
|
|
147
|
+
prevBlank = false;
|
|
148
|
+
}
|
|
149
|
+
while (out.length > 0 && out[out.length - 1] === '')
|
|
150
|
+
out.pop();
|
|
151
|
+
return out.join('\n');
|
|
152
|
+
}
|
|
58
153
|
/**
|
|
59
154
|
* Replace the profile atomically.
|
|
60
155
|
*
|
|
61
156
|
* A half-written profile is worse than a stale one — it would be injected into
|
|
62
157
|
* every conversation — so the write goes through a temp file and a rename.
|
|
158
|
+
* Deduplicates near-identical bullets within each section before persisting so
|
|
159
|
+
* neither consolidation nor multi-machine sync can double the profile.
|
|
63
160
|
*
|
|
64
161
|
* @param memoriesDir - the memory store root.
|
|
65
162
|
* @param body - the new markdown profile.
|
|
@@ -69,7 +166,8 @@ export async function writePersona(memoriesDir, body) {
|
|
|
69
166
|
const target = personaPath(memoriesDir);
|
|
70
167
|
await mkdir(dirname(target), { recursive: true });
|
|
71
168
|
const temp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
72
|
-
|
|
169
|
+
const cleaned = dedupePersona(body.trim());
|
|
170
|
+
await writeFile(temp, `${cleaned}\n`, 'utf8');
|
|
73
171
|
await rename(temp, target);
|
|
74
172
|
return target;
|
|
75
173
|
}
|
package/lib/raw-recall.js
CHANGED
|
@@ -167,8 +167,20 @@ export function windowAroundQuote(messages, quote, maxChars = 600) {
|
|
|
167
167
|
/** Cache of parsed transcripts, keyed by sessions dir + session id. */
|
|
168
168
|
const transcriptCache = new Map();
|
|
169
169
|
const CACHE_TTL_MS = 10 * 60_000;
|
|
170
|
+
const MAX_TRANSCRIPT_CACHE = 128;
|
|
170
171
|
const INDEX_TTL_MS = 60_000;
|
|
171
172
|
const indexCache = new Map();
|
|
173
|
+
function setTranscriptCache(key, entry) {
|
|
174
|
+
if (transcriptCache.has(key))
|
|
175
|
+
transcriptCache.delete(key);
|
|
176
|
+
transcriptCache.set(key, entry);
|
|
177
|
+
while (transcriptCache.size > MAX_TRANSCRIPT_CACHE) {
|
|
178
|
+
const oldest = transcriptCache.keys().next().value;
|
|
179
|
+
if (oldest === undefined)
|
|
180
|
+
break;
|
|
181
|
+
transcriptCache.delete(oldest);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
172
184
|
/** Normalize a log directory name and a session id to the same form. */
|
|
173
185
|
function normalizeSession(id) {
|
|
174
186
|
return id.replace(/^session-/u, '');
|
|
@@ -206,15 +218,15 @@ export async function readTranscript(sessionsDir, sessionId, now = Date.now()) {
|
|
|
206
218
|
try {
|
|
207
219
|
const log = (await logIndex(sessionsDir, now)).get(normalizeSession(sessionId));
|
|
208
220
|
if (log === undefined) {
|
|
209
|
-
|
|
221
|
+
setTranscriptCache(key, { at: now, messages: undefined });
|
|
210
222
|
return undefined;
|
|
211
223
|
}
|
|
212
224
|
const parsed = await readSessionLog(log.file, log.modifiedAt);
|
|
213
|
-
|
|
225
|
+
setTranscriptCache(key, { at: now, messages: parsed?.messages });
|
|
214
226
|
return parsed?.messages;
|
|
215
227
|
}
|
|
216
228
|
catch {
|
|
217
|
-
|
|
229
|
+
setTranscriptCache(key, { at: now, messages: undefined });
|
|
218
230
|
return undefined;
|
|
219
231
|
}
|
|
220
232
|
}
|
|
@@ -279,7 +291,7 @@ export async function collectRagExcerpts(sessionsDir, query, limits = {}) {
|
|
|
279
291
|
if (messages === undefined)
|
|
280
292
|
continue;
|
|
281
293
|
for (const chunk of turnChunks(messages))
|
|
282
|
-
turns.push({ sessionId, chunk });
|
|
294
|
+
turns.push({ sessionId, chunk: { ...chunk, sessionId } });
|
|
283
295
|
}
|
|
284
296
|
// Document frequency across every turn in this history, so the scorer can tell
|
|
285
297
|
// a word that appears everywhere from a word that names the thing.
|
|
@@ -290,8 +302,7 @@ export async function collectRagExcerpts(sessionsDir, query, limits = {}) {
|
|
|
290
302
|
}
|
|
291
303
|
const candidates = [];
|
|
292
304
|
for (const item of selectTurnExcerpts(turns.map((turn) => turn.chunk), query, df, { maxExcerpts, maxChars, maxBytes })) {
|
|
293
|
-
|
|
294
|
-
candidates.push({ excerpt: { ...item.excerpt, sessionId: turn?.sessionId ?? '' }, score: item.score });
|
|
305
|
+
candidates.push({ excerpt: item.excerpt, score: item.score });
|
|
295
306
|
}
|
|
296
307
|
// Merge across sessions by score: one conversation that happens to hold several
|
|
297
308
|
// matching turns must not crowd out the conversation that holds the answer.
|
|
@@ -378,7 +389,7 @@ function selectTurnExcerpts(turns, query, df, limits = {}) {
|
|
|
378
389
|
return scored.map((item) => {
|
|
379
390
|
const window = bestWindow(item.turn.text.trim(), queryTokens, maxChars);
|
|
380
391
|
const text = redactSecrets(window.text.trim()).replace(/\s+/gu, ' ').slice(0, maxChars);
|
|
381
|
-
return { excerpt: { sessionId: '', seq: item.turn.seq, role: 'assistant', text }, score: item.score };
|
|
392
|
+
return { excerpt: { sessionId: item.turn.sessionId ?? '', seq: item.turn.seq, role: 'assistant', text }, score: item.score };
|
|
382
393
|
}).filter((item) => item.excerpt.text.length >= 24);
|
|
383
394
|
}
|
|
384
395
|
export async function collectExcerpts(sessionsDir, sources, query, limits = {}) {
|
package/lib/reflection.js
CHANGED
|
@@ -201,16 +201,22 @@ export async function runReflection(request) {
|
|
|
201
201
|
model: route.model,
|
|
202
202
|
messages: [createUserMessage({ content: [{ type: 'text', text: input }], source: { kind: MEMORY_SOURCE_KIND } })],
|
|
203
203
|
system: REFLECTION_SYSTEM,
|
|
204
|
-
maxTokens:
|
|
204
|
+
maxTokens: 4_096,
|
|
205
205
|
purpose: 'compaction',
|
|
206
206
|
sessionId: request.session.id,
|
|
207
207
|
signal: AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]),
|
|
208
208
|
};
|
|
209
209
|
let text = '';
|
|
210
|
+
let finishKind = 'stop';
|
|
210
211
|
try {
|
|
211
212
|
const assembler = new BlockAssembler();
|
|
212
213
|
for await (const chunk of request.llm.stream(options))
|
|
213
214
|
assembler.push(chunk);
|
|
215
|
+
const finish = assembler.finish;
|
|
216
|
+
finishKind = finish.kind;
|
|
217
|
+
if (finish.kind === 'error' || finish.kind === 'aborted') {
|
|
218
|
+
return { insights: [], reason: `reflection call ${finish.kind}: ${finish.failure.message}`, skipped: 'failed' };
|
|
219
|
+
}
|
|
214
220
|
text = assembler.blocks()
|
|
215
221
|
.filter((block) => block.type === 'text')
|
|
216
222
|
.map((block) => block.text)
|
|
@@ -219,6 +225,9 @@ export async function runReflection(request) {
|
|
|
219
225
|
catch (error) {
|
|
220
226
|
return { insights: [], reason: `reflection call failed: ${error instanceof Error ? error.message : String(error)}`, skipped: 'failed' };
|
|
221
227
|
}
|
|
228
|
+
if (finishKind === 'max-tokens' && text.trim().length === 0) {
|
|
229
|
+
return { insights: [], reason: 'reflection reply hit maxTokens before emitting text', skipped: 'failed' };
|
|
230
|
+
}
|
|
222
231
|
const known = new Set(request.entries.map((entry) => entry.id));
|
|
223
232
|
const insights = parseReflection(text, known);
|
|
224
233
|
// A zero result has two very different causes — the model wrote no observations,
|
package/lib/state.js
CHANGED
|
@@ -500,8 +500,10 @@ export class StateStore {
|
|
|
500
500
|
* @param now - clock to record.
|
|
501
501
|
*/
|
|
502
502
|
markConsolidated(refs, now = Date.now()) {
|
|
503
|
-
|
|
504
|
-
|
|
503
|
+
if (refs.length === 0)
|
|
504
|
+
return;
|
|
505
|
+
if (this.db === undefined) {
|
|
506
|
+
for (const ref of refs) {
|
|
505
507
|
const key = `${ref.scope}\u0000${ref.id}`;
|
|
506
508
|
const previous = this.usage.get(key);
|
|
507
509
|
this.usage.set(key, {
|
|
@@ -510,12 +512,22 @@ export class StateStore {
|
|
|
510
512
|
surfacedAt: previous?.surfacedAt ?? 0,
|
|
511
513
|
consolidatedAt: now,
|
|
512
514
|
});
|
|
513
|
-
continue;
|
|
514
515
|
}
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const stmt = this.db.prepare(`
|
|
519
|
+
INSERT INTO usage (scope, id, uses, last_used_at, consolidated_at) VALUES (?, ?, 0, 0, ?)
|
|
520
|
+
ON CONFLICT(scope, id) DO UPDATE SET consolidated_at = excluded.consolidated_at
|
|
521
|
+
`);
|
|
522
|
+
this.db.exec('BEGIN');
|
|
523
|
+
try {
|
|
524
|
+
for (const ref of refs)
|
|
525
|
+
stmt.run(ref.scope, ref.id, now);
|
|
526
|
+
this.db.exec('COMMIT');
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
this.db.exec('ROLLBACK');
|
|
530
|
+
throw error;
|
|
519
531
|
}
|
|
520
532
|
}
|
|
521
533
|
/** Every usage row with all four timestamps, for the retention pass. */
|
package/lib/storage.js
CHANGED
|
@@ -1096,7 +1096,17 @@ export class MemoryStore {
|
|
|
1096
1096
|
supersedes = explicit;
|
|
1097
1097
|
else if (similar !== undefined) {
|
|
1098
1098
|
const previous = await this.read(draft.scope, projectRoot, similar);
|
|
1099
|
-
|
|
1099
|
+
if (previous !== undefined) {
|
|
1100
|
+
if (carriesForward(previous, draft)) {
|
|
1101
|
+
supersedes = similar;
|
|
1102
|
+
}
|
|
1103
|
+
else if (source === 'auto') {
|
|
1104
|
+
// A background extraction that re-derives an existing memory under a
|
|
1105
|
+
// re-worded title with LESS detail/tags must not create a second file:
|
|
1106
|
+
// keep the richer existing entry intact and skip the redundant copy.
|
|
1107
|
+
return { entry: previous, action: 'updated' };
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1100
1110
|
}
|
|
1101
1111
|
// Evidence binding is tied to the exact body it supported. A draft that
|
|
1102
1112
|
// carries a verified quote (automatic extraction) sets it; a rewrite that
|