dsh-cross-memory 0.2.11 → 0.2.13

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/index.js CHANGED
@@ -1521,7 +1521,7 @@ export class MemoriesRuntime {
1521
1521
  // lexical gate refused. When the service is unreachable, `denseScores`
1522
1522
  // returns an empty map and the lexical order stands.
1523
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() });
1524
+ const dense = await denseScores(eligible.map((item) => item.entry), query, { url: DEFAULT_DENSE_URL, model: DEFAULT_DENSE_MODEL, cacheDir: this.denseCacheDir() });
1525
1525
  if (dense.size > 0) {
1526
1526
  const lexical = [...eligible].sort(byStrength).map((item) => item.entry.id);
1527
1527
  const semantic = [...dense.entries()].sort((left, right) => right[1] - left[1]).map(([id]) => id);
@@ -2670,6 +2670,13 @@ export class MemoriesRuntime {
2670
2670
  window,
2671
2671
  projectLabel,
2672
2672
  ...knownTitles.length === 0 ? {} : { knownTitles },
2673
+ ...await readLoops(this.store.memoriesDir).then((ledger) => {
2674
+ const open = ledger.loops
2675
+ .filter((loop) => loop.state === 'open')
2676
+ .slice(-25)
2677
+ .map((loop) => ({ id: loop.id, text: loop.text }));
2678
+ return open.length === 0 ? {} : { openLoops: open };
2679
+ }).catch(() => ({})),
2673
2680
  ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
2674
2681
  ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
2675
2682
  : {},
@@ -2734,7 +2741,7 @@ export class MemoriesRuntime {
2734
2741
  }).catch((error) => {
2735
2742
  this.log.warn('dsh-cross-memory: could not write the evidence note for session %s: %o', key, error);
2736
2743
  });
2737
- await this.recordLoops(key, outcome.loops);
2744
+ await this.recordLoops(key, outcome.loops, outcome.closedLoops);
2738
2745
  this.log.info('dsh-cross-memory: stored %d memories from session %s (%s)%s%s', outcome.drafts.length, key, stored.join(', '), spend, outcome.truncated === true ? ` — the reply hit the ${this.settings.extractMaxOutputTokens}-token cap and was salvaged; raise extractMaxOutputTokens to keep the rest` : '');
2739
2746
  // A pass that always lands on the cap is a pass whose ceiling is the
2740
2747
  // binding constraint. Saying so is the only way anybody can tell that
@@ -3210,10 +3217,10 @@ export class MemoriesRuntime {
3210
3217
  this.noteLimitRefusal(error);
3211
3218
  this.log.warn('dsh-cross-memory: consolidation failed for session %s: %s', parent.session.id, message);
3212
3219
  // 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.
3220
+ // alone ("reading 'id'") names no call site. Record the top stack frames
3221
+ // at warn level so it persists under default `logLevel: 'info'`.
3215
3222
  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);
3223
+ this.log.warn('dsh-cross-memory: consolidation failure stack: %s', error.stack.split('\n').slice(0, 6).join(' | '));
3217
3224
  }
3218
3225
  // The command reports `consolidateSkipReason`; without this the failure
3219
3226
  // surfaced as "Nothing to consolidate: unknown reason".
@@ -3339,7 +3346,7 @@ export class MemoriesRuntime {
3339
3346
  // days. There is no rule that says it is worth an interruption, so the
3340
3347
  // gate decides — and its default is silence. Without a session there is no
3341
3348
  // route to ask through, and silence is the right failure.
3342
- if (this.settings.noticeGate) {
3349
+ if (this.settings.noticeGate && session !== undefined && !this.backgroundPaused()) {
3343
3350
  const staleAfter = 3 * 86_400_000;
3344
3351
  const candidates = loopNow.loops.filter((loop) => loop.state === 'open'
3345
3352
  && loop.dueAt === undefined
@@ -3347,44 +3354,56 @@ export class MemoriesRuntime {
3347
3354
  && (loop.remindCount ?? 0) < 3
3348
3355
  && (loop.remindedAt === undefined || now - loop.remindedAt >= 86_400_000));
3349
3356
  if (candidates.length > 0) {
3350
- const gate = await gateNotices({
3351
- llm: this.llm,
3352
- session,
3353
- candidates: candidates.map((loop) => ({
3354
- id: loop.id,
3355
- title: `还挂着:${loop.text}`,
3356
- detail: `说了 ${Math.round((now - loop.openedAt) / 86_400_000)} 天,没有截止日期,已提醒 ${loop.remindCount ?? 0} 次`,
3357
- })),
3358
- ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3359
- provider: this.settings.extractProvider,
3360
- model: this.settings.extractModel,
3361
- timeoutMs: 20_000,
3362
- signal: this.lifecycle.signal,
3363
- });
3364
- this.log.info('dsh-cross-memory: notice gate: %d candidate(s), %d allowed (%s)', candidates.length, gate.deliver.size, gate.reason);
3365
- let ledger = loopNow;
3366
- for (const candidate of candidates) {
3367
- if (!gate.deliver.has(candidate.id))
3368
- continue;
3369
- const admitted = admitNotice(queue, {
3370
- kind: 'loop',
3371
- createdAt: now,
3372
- dueAt: now,
3373
- title: `还挂着:${candidate.text}`,
3374
- body: candidate.text,
3375
- evidence: [candidate.id],
3376
- dedupeKey: `loop:${candidate.id}`,
3377
- }, policy);
3378
- if (!admitted.ok)
3379
- continue;
3380
- queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
3381
- ledger = withLoop(ledger, candidate.id, { remindedAt: now, remindCount: (candidate.remindCount ?? 0) + 1 });
3357
+ const GATE_COOLDOWN_MS = 6 * 3_600_000;
3358
+ const fingerprint = candidates.map((loop) => `${loop.id}:${loop.remindCount ?? 0}`).sort().join(',');
3359
+ const lastAt = Number(this.state.getMeta('noticeGate:lastAt') ?? '0');
3360
+ const lastFingerprint = this.state.getMeta('noticeGate:lastFingerprint') ?? '';
3361
+ if (lastAt > 0 && now - lastAt < GATE_COOLDOWN_MS && lastFingerprint === fingerprint) {
3362
+ this.log.decision('dsh-cross-memory: notice gate skipped (%d candidate(s) unchanged within 6h cooldown)', candidates.length);
3363
+ }
3364
+ else {
3365
+ this.state.putMeta('noticeGate:lastAt', String(now));
3366
+ this.state.putMeta('noticeGate:lastFingerprint', fingerprint);
3367
+ const gate = await gateNotices({
3368
+ llm: this.llm,
3369
+ session,
3370
+ candidates: candidates.map((loop) => ({
3371
+ id: loop.id,
3372
+ title: `还挂着:${loop.text}`,
3373
+ detail: `说了 ${Math.round((now - loop.openedAt) / 86_400_000)} 天,没有截止日期,已提醒 ${loop.remindCount ?? 0} 次`,
3374
+ })),
3375
+ ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3376
+ ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
3377
+ ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
3378
+ : {},
3379
+ timeoutMs: 20_000,
3380
+ signal: this.lifecycle.signal,
3381
+ });
3382
+ this.log.info('dsh-cross-memory: notice gate: %d candidate(s), %d allowed (%s)', candidates.length, gate.deliver.size, gate.reason);
3383
+ let ledger = loopNow;
3384
+ for (const candidate of candidates) {
3385
+ if (!gate.deliver.has(candidate.id))
3386
+ continue;
3387
+ const admitted = admitNotice(queue, {
3388
+ kind: 'loop',
3389
+ createdAt: now,
3390
+ dueAt: now,
3391
+ title: `还挂着:${candidate.text}`,
3392
+ body: candidate.text,
3393
+ evidence: [candidate.id],
3394
+ dedupeKey: `loop:${candidate.id}`,
3395
+ }, policy);
3396
+ if (!admitted.ok)
3397
+ continue;
3398
+ queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
3399
+ ledger = withLoop(ledger, candidate.id, { remindedAt: now, remindCount: (candidate.remindCount ?? 0) + 1 });
3400
+ }
3401
+ if (ledger !== loopNow)
3402
+ await writeLoops(dir, ledger);
3382
3403
  }
3383
- if (ledger !== loopNow)
3384
- await writeLoops(dir, ledger);
3385
3404
  }
3386
3405
  }
3387
- else if (loopNow.loops.some((loop) => loop.state === 'open' && loop.dueAt === undefined)) {
3406
+ else if (!this.settings.noticeGate && loopNow.loops.some((loop) => loop.state === 'open' && loop.dueAt === undefined)) {
3388
3407
  this.log.decision('dsh-cross-memory: notice gate is off, undated loops stay silent');
3389
3408
  }
3390
3409
  const before = JSON.stringify(queue);
@@ -3416,16 +3435,24 @@ export class MemoriesRuntime {
3416
3435
  * lifecycle and a deadline, it is never recalled by retrieval, and its id must
3417
3436
  * stay stable across rewrites so one promise cannot become three reminders.
3418
3437
  */
3419
- async recordLoops(sessionKey, candidates) {
3420
- if (candidates.length === 0)
3438
+ async recordLoops(sessionKey, candidates, closedIds = []) {
3439
+ if (candidates.length === 0 && closedIds.length === 0)
3421
3440
  return;
3422
3441
  try {
3423
3442
  const dir = this.store.memoriesDir;
3424
3443
  const now = Date.now();
3425
- const current = pruneLoops(await readLoops(dir), now);
3426
- const next = mergeLoops(current, candidates, now, sessionKey);
3444
+ let current = pruneLoops(await readLoops(dir), now);
3445
+ let closed = 0;
3446
+ for (const id of closedIds) {
3447
+ const outcome = closeLoop(current, id);
3448
+ if (outcome.closed !== undefined) {
3449
+ current = outcome.store;
3450
+ closed += 1;
3451
+ }
3452
+ }
3453
+ const next = candidates.length > 0 ? mergeLoops(current, candidates, now, sessionKey) : current;
3427
3454
  await writeLoops(dir, next);
3428
- this.log.info('dsh-cross-memory: open loops now %d (from %d candidate(s))', next.loops.filter((loop) => loop.state === 'open').length, candidates.length);
3455
+ this.log.info('dsh-cross-memory: open loops now %d (from %d candidate(s), %d closed)', next.loops.filter((loop) => loop.state === 'open').length, candidates.length, closed);
3429
3456
  }
3430
3457
  catch (error) {
3431
3458
  this.log.warn('dsh-cross-memory: could not record open loops: %s', error instanceof Error ? error.message : String(error));
@@ -3471,8 +3498,9 @@ export class MemoriesRuntime {
3471
3498
  entries,
3472
3499
  ...await readPersona(dir).then((text) => text === undefined ? {} : { persona: text }),
3473
3500
  previous: previousInsights(files),
3474
- provider: this.settings.extractProvider,
3475
- model: this.settings.extractModel,
3501
+ ...this.settings.extractProvider.length > 0 && this.settings.extractModel.length > 0
3502
+ ? { provider: this.settings.extractProvider, model: this.settings.extractModel }
3503
+ : {},
3476
3504
  timeoutMs: 60_000,
3477
3505
  signal: this.lifecycle.signal,
3478
3506
  });
@@ -3632,6 +3660,7 @@ export class MemoriesRuntime {
3632
3660
  // The profile as it stands, so the pass refines it instead of re-inventing
3633
3661
  // one every six hours. Read before the call: the pass writes it back.
3634
3662
  ...await readPersona(this.store.memoriesDir).then((text) => text === undefined ? {} : { persona: text }),
3663
+ ...await listDrafts(this.store.memoriesDir, this.deployment.dshHome).then((drafts) => drafts.length === 0 ? {} : { existingSkills: drafts.map((d) => ({ name: d.name, description: d.description })) }).catch(() => ({})),
3635
3664
  projectLabel: root === undefined ? NO_PROJECT_LABEL : this.store.target('project', root).label,
3636
3665
  maxUpserts: this.settings.consolidateMaxEntries,
3637
3666
  // The deny list only reaches the pre-0.2.1 seam, whose request still
package/lib/mcp.js ADDED
@@ -0,0 +1,328 @@
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 { 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 denseEnv = env['DSH_MEMORY_DENSE']?.trim().toLowerCase();
108
+ const denseEnabled = denseEnv === undefined ? true : !(denseEnv === '0' || denseEnv === 'false' || denseEnv === 'off');
109
+ const denseUrl = env['DSH_MEMORY_DENSE_URL']?.trim() || DEFAULT_DENSE_URL;
110
+ const denseModel = env['DSH_MEMORY_DENSE_MODEL']?.trim() || DEFAULT_DENSE_MODEL;
111
+ return { memoriesDir, denseEnabled, denseUrl, denseModel };
112
+ }
113
+ /** Resolve a workspace root argument from either `projectRoot` or `projectSlug`. */
114
+ async function resolveProjectRoot(store, projectRootArg, projectSlugArg) {
115
+ if (typeof projectRootArg === 'string' && projectRootArg.trim().length > 0) {
116
+ return resolve(projectRootArg.trim());
117
+ }
118
+ if (typeof projectSlugArg === 'string' && projectSlugArg.trim().length > 0) {
119
+ const slug = projectSlugArg.trim();
120
+ const descriptor = await store.readProjectDescriptor(slug);
121
+ return descriptor?.root ?? join(store.memoriesDir, 'projects', slug);
122
+ }
123
+ return undefined;
124
+ }
125
+ /** Build text tool result envelope. */
126
+ function textResult(text, isError = false) {
127
+ return isError ? { content: [{ type: 'text', text }], isError: true } : { content: [{ type: 'text', text }] };
128
+ }
129
+ /** Re-rank lexical hits with the optional local dense embedding channel. */
130
+ async function maybeDenseRerank(hits, query, options, limit) {
131
+ if (!options.denseEnabled || hits.length <= 1 || query.trim().length === 0)
132
+ return hits.slice(0, limit);
133
+ const pool = hits.slice(0, Math.min(hits.length, 32));
134
+ const scores = await denseScores(pool.map((hit) => hit.entry), query, { url: options.denseUrl, model: options.denseModel, cacheDir: join(options.memoriesDir, 'cache') });
135
+ if (scores.size === 0)
136
+ return hits.slice(0, limit);
137
+ const lexical = pool.map((hit) => hit.entry.id);
138
+ const semantic = [...scores.entries()].sort((a, b) => b[1] - a[1]).map(([id]) => id);
139
+ const fused = rrf([lexical, semantic]);
140
+ return [...pool]
141
+ .sort((a, b) => (fused.get(b.entry.id) ?? 0) - (fused.get(a.entry.id) ?? 0))
142
+ .slice(0, limit);
143
+ }
144
+ /** Execute one MCP tool call. */
145
+ async function executeTool(name, args, store, options) {
146
+ switch (name) {
147
+ case 'memory_persona': {
148
+ const persona = await readPersona(options.memoriesDir);
149
+ if (persona === undefined)
150
+ return textResult('No persona profile stored yet.');
151
+ return textResult(persona);
152
+ }
153
+ case 'memory_projects': {
154
+ const slugs = await store.listProjects();
155
+ if (slugs.length === 0)
156
+ return textResult('No project memory scopes found.');
157
+ const lines = [`${slugs.length} project scopes:`];
158
+ for (const slug of slugs) {
159
+ const desc = await store.readProjectDescriptor(slug);
160
+ const root = desc?.root ?? join(store.memoriesDir, 'projects', slug);
161
+ const entries = await store.list('project', root).catch(() => []);
162
+ lines.push(`- ${slug} (${entries.length} entries)${desc?.root ? ` — ${desc.root}` : ''}`);
163
+ }
164
+ return textResult(lines.join('\n'));
165
+ }
166
+ case 'memory_search': {
167
+ const query = typeof args['query'] === 'string' ? args['query'].trim() : '';
168
+ const scopeArg = typeof args['scope'] === 'string' ? args['scope'] : 'all';
169
+ const rawLimit = typeof args['limit'] === 'number' ? args['limit'] : 8;
170
+ const limit = Math.min(Math.max(Math.trunc(rawLimit), 1), 25);
171
+ const kind = typeof args['kind'] === 'string' ? toMemoryKind(args['kind']) : undefined;
172
+ const tags = Array.isArray(args['tags']) ? args['tags'].filter((t) => typeof t === 'string') : [];
173
+ const projectRoot = await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']);
174
+ const groups = [];
175
+ if ((scopeArg === 'all' || scopeArg === 'project') && projectRoot !== undefined) {
176
+ const entries = await store.list('project', projectRoot).catch(() => []);
177
+ if (entries.length > 0)
178
+ groups.push({ scope: 'project', label: store.target('project', projectRoot).label, entries });
179
+ }
180
+ if (scopeArg === 'all' || scopeArg === 'global') {
181
+ const entries = await store.list('global', undefined).catch(() => []);
182
+ if (entries.length > 0)
183
+ groups.push({ scope: 'global', label: 'global', entries });
184
+ }
185
+ if (groups.length === 0)
186
+ return textResult('No memories available in the requested scope.');
187
+ const filter = {
188
+ ...tags.length > 0 ? { tags } : {},
189
+ ...kind === undefined ? {} : { kinds: [kind] },
190
+ limit: query.length > 0 ? Math.max(limit * 3, 24) : limit,
191
+ };
192
+ const rawHits = query.length === 0
193
+ ? browseMemories(groups, filter)
194
+ : searchMemories(groups, query, filter);
195
+ const hits = query.length === 0
196
+ ? rawHits.slice(0, limit)
197
+ : await maybeDenseRerank(rawHits, query, options, limit);
198
+ if (hits.length === 0) {
199
+ const hints = query.length === 0 ? [] : suggestAliases(groups, query, 12);
200
+ const hintLine = hints.length === 0
201
+ ? ''
202
+ : `\nAliases/tags in store: ${hints.map((h) => h.term).join(', ')}`;
203
+ return textResult(`No memories matched ${JSON.stringify(query)}.${hintLine}`);
204
+ }
205
+ return textResult([`${hits.length} memories:`, ...hits.map((hit, i) => renderHit(hit, i))].join('\n'));
206
+ }
207
+ case 'memory_read': {
208
+ const id = typeof args['id'] === 'string' ? args['id'].trim() : '';
209
+ if (id.length === 0)
210
+ return textResult('memory_read requires a non-empty id.', true);
211
+ const scopeArg = args['scope'] === 'global' || args['scope'] === 'project' ? args['scope'] : undefined;
212
+ const projectRoot = await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']);
213
+ const order = scopeArg !== undefined ? [scopeArg] : projectRoot !== undefined ? ['project', 'global'] : ['global'];
214
+ for (const scope of order) {
215
+ if (scope === 'project' && projectRoot === undefined)
216
+ continue;
217
+ const entry = await store.read(scope, scope === 'project' ? projectRoot : undefined, id);
218
+ if (entry !== undefined)
219
+ return textResult(renderEntry(entry));
220
+ }
221
+ return textResult(`Memory not found: ${id}`, true);
222
+ }
223
+ case 'memory_write': {
224
+ const scope = args['scope'] === 'global' || args['scope'] === 'project' ? args['scope'] : undefined;
225
+ const rawTitle = typeof args['title'] === 'string' ? args['title'].trim() : '';
226
+ const rawBody = typeof args['body'] === 'string' ? args['body'].trim() : '';
227
+ if (scope === undefined)
228
+ return textResult('memory_write requires scope ("global" or "project").', true);
229
+ if (rawTitle.length === 0 || rawBody.length === 0)
230
+ return textResult('memory_write requires non-empty title and body.', true);
231
+ const projectRoot = scope === 'project' ? await resolveProjectRoot(store, args['projectRoot'], args['projectSlug']) : undefined;
232
+ if (scope === 'project' && projectRoot === undefined) {
233
+ return textResult('memory_write with scope="project" requires projectRoot or projectSlug.', true);
234
+ }
235
+ const tags = Array.isArray(args['tags']) ? args['tags'].filter((t) => typeof t === 'string') : [];
236
+ const keys = Array.isArray(args['keys']) ? args['keys'].filter((k) => typeof k === 'string') : undefined;
237
+ const appliesTo = typeof args['appliesTo'] === 'string' && args['appliesTo'].trim().length > 0
238
+ ? redactSecrets(args['appliesTo'].trim())
239
+ : undefined;
240
+ const durability = typeof args['durability'] === 'string' ? toMemoryDurability(args['durability']) : undefined;
241
+ const result = await store.upsert({
242
+ scope,
243
+ title: redactSecrets(rawTitle).slice(0, 120),
244
+ body: redactSecrets(rawBody),
245
+ tags,
246
+ ...typeof args['kind'] === 'string' ? { kind: toMemoryKind(args['kind']) } : {},
247
+ ...keys === undefined ? {} : { keys },
248
+ ...appliesTo === undefined ? {} : { appliesTo },
249
+ ...durability === undefined ? {} : { durability, ...durability === 'snapshot' ? { asOf: Date.now() } : {} },
250
+ ...typeof args['pinned'] === 'boolean' ? { pinned: args['pinned'] } : {},
251
+ ...typeof args['permanent'] === 'boolean' ? { permanent: args['permanent'] } : {},
252
+ }, projectRoot, 'tool');
253
+ if (scope === 'project' && projectRoot !== undefined) {
254
+ await store.writeProjectDescriptor(projectRoot).catch(() => undefined);
255
+ }
256
+ return textResult(`${result.action === 'created' ? 'Remembered' : 'Updated'} ${scope}${projectRoot ? `:${projectSlug(projectRoot)}` : ''} memory "${result.entry.title}" (id=${result.entry.id}).`);
257
+ }
258
+ default:
259
+ return textResult(`Unknown tool: ${name}`, true);
260
+ }
261
+ }
262
+ /** Handle one JSON-RPC 2.0 request. Returns `undefined` for notifications. */
263
+ export async function handleMcpRequest(request, options, store = new MemoryStore(options.memoriesDir)) {
264
+ const id = request.id;
265
+ const isNotification = id === undefined;
266
+ const ok = (result) => ({ jsonrpc: '2.0', id: id ?? null, result });
267
+ const fail = (code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
268
+ switch (request.method) {
269
+ case 'initialize': {
270
+ const requested = typeof request.params?.['protocolVersion'] === 'string'
271
+ ? request.params['protocolVersion']
272
+ : DEFAULT_PROTOCOL_VERSION;
273
+ return ok({
274
+ protocolVersion: requested,
275
+ capabilities: { tools: {} },
276
+ serverInfo: { name: 'dsh-cross-memory', version: '0.2.12' },
277
+ });
278
+ }
279
+ case 'notifications/initialized':
280
+ case 'notifications/cancelled':
281
+ return undefined;
282
+ case 'ping':
283
+ return isNotification ? undefined : ok({});
284
+ case 'tools/list':
285
+ return ok({ tools: MCP_TOOLS });
286
+ case 'tools/call': {
287
+ const toolName = typeof request.params?.['name'] === 'string' ? request.params['name'] : '';
288
+ const toolArgs = (typeof request.params?.['arguments'] === 'object' && request.params['arguments'] !== null)
289
+ ? request.params['arguments']
290
+ : {};
291
+ try {
292
+ const result = await executeTool(toolName, toolArgs, store, options);
293
+ return ok(result);
294
+ }
295
+ catch (error) {
296
+ const message = error instanceof Error ? error.message : String(error);
297
+ return ok(textResult(`Error: ${message}`, true));
298
+ }
299
+ }
300
+ default:
301
+ return isNotification ? undefined : fail(-32601, `Method not found: ${request.method}`);
302
+ }
303
+ }
304
+ /** Run the newline-delimited JSON-RPC 2.0 stdio loop. */
305
+ export function startStdioServer(options = defaultMcpOptions()) {
306
+ const store = new MemoryStore(options.memoriesDir);
307
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
308
+ rl.on('line', (line) => {
309
+ const trimmed = line.trim();
310
+ if (trimmed.length === 0)
311
+ return;
312
+ let parsed;
313
+ try {
314
+ parsed = JSON.parse(trimmed);
315
+ }
316
+ catch {
317
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`);
318
+ return;
319
+ }
320
+ void handleMcpRequest(parsed, options, store).then((response) => {
321
+ if (response !== undefined)
322
+ process.stdout.write(`${JSON.stringify(response)}\n`);
323
+ });
324
+ });
325
+ }
326
+ const isDirectRun = process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
327
+ if (isDirectRun)
328
+ startStdioServer();
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
- await writeFile(temp, `${body.trim()}\n`, 'utf8');
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
  }