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/sync.js
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
*
|
|
29
29
|
* @module dsh-cross-memory/sync
|
|
30
30
|
*/
|
|
31
|
+
import { dedupePersona, isNearDuplicateBullet } from './persona.js';
|
|
31
32
|
import { execFile } from 'node:child_process';
|
|
32
33
|
import { existsSync } from 'node:fs';
|
|
33
34
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
@@ -46,6 +47,7 @@ export const STORE_GITIGNORE = [
|
|
|
46
47
|
'**/index.json',
|
|
47
48
|
'# a project descriptor records THIS machine\'s checkout path',
|
|
48
49
|
'**/project.json',
|
|
50
|
+
'cache/',
|
|
49
51
|
'pending/',
|
|
50
52
|
'*.log',
|
|
51
53
|
'.DS_Store',
|
|
@@ -97,20 +99,28 @@ export function isPersonaPath(path) {
|
|
|
97
99
|
return /(^|\/)persona\/[^/]+\.md$/u.test(path);
|
|
98
100
|
}
|
|
99
101
|
/**
|
|
100
|
-
* Merge two versions of a persona file as a bullet union.
|
|
102
|
+
* Merge two versions of a persona file as a deduplicated bullet union.
|
|
101
103
|
*
|
|
102
104
|
* A persona file is headings plus bullet lists; both machines append their own
|
|
103
|
-
* observations, so a
|
|
104
|
-
* Bullets are matched on
|
|
105
|
-
*
|
|
106
|
-
*
|
|
105
|
+
* observations, so a section-aware union keeps every rule either machine
|
|
106
|
+
* recorded. Bullets are matched not only on exact text but also on near-duplicate
|
|
107
|
+
* token overlap within the same section — otherwise a consolidation pass that
|
|
108
|
+
* tightens wording on one machine causes the next sync to append the older
|
|
109
|
+
* phrasing beside it and double every section. Non-bullet lines come from `ours`.
|
|
107
110
|
*/
|
|
108
111
|
export function mergePersona(ours, theirs) {
|
|
109
|
-
const result = ours.split('\n');
|
|
110
|
-
const
|
|
112
|
+
const result = dedupePersona(ours).split('\n');
|
|
113
|
+
const sectionBullets = new Map();
|
|
114
|
+
let oursSection = '';
|
|
111
115
|
for (const line of result) {
|
|
112
|
-
if (line.startsWith('
|
|
113
|
-
|
|
116
|
+
if (line.startsWith('#')) {
|
|
117
|
+
oursSection = line.trim();
|
|
118
|
+
}
|
|
119
|
+
else if (line.startsWith('- ')) {
|
|
120
|
+
const list = sectionBullets.get(oursSection) ?? [];
|
|
121
|
+
list.push(line.trim());
|
|
122
|
+
sectionBullets.set(oursSection, list);
|
|
123
|
+
}
|
|
114
124
|
}
|
|
115
125
|
// Bucket the bullets that only the other side has, by their section heading.
|
|
116
126
|
const pending = new Map();
|
|
@@ -120,16 +130,18 @@ export function mergePersona(ours, theirs) {
|
|
|
120
130
|
section = line.trim();
|
|
121
131
|
else if (line.startsWith('- ')) {
|
|
122
132
|
const key = line.trim();
|
|
123
|
-
|
|
133
|
+
const existing = sectionBullets.get(section) ?? [];
|
|
134
|
+
if (existing.some((item) => isNearDuplicateBullet(item, key)))
|
|
124
135
|
continue;
|
|
125
|
-
|
|
136
|
+
existing.push(key);
|
|
137
|
+
sectionBullets.set(section, existing);
|
|
126
138
|
const bucket = pending.get(section) ?? [];
|
|
127
139
|
bucket.push(line);
|
|
128
140
|
pending.set(section, bucket);
|
|
129
141
|
}
|
|
130
142
|
}
|
|
131
143
|
if (pending.size === 0)
|
|
132
|
-
return
|
|
144
|
+
return result.join('\n');
|
|
133
145
|
// Insert each bucket after the last line that belongs to its section.
|
|
134
146
|
const sectionRanges = [];
|
|
135
147
|
let current;
|
|
@@ -159,7 +171,7 @@ export function mergePersona(ours, theirs) {
|
|
|
159
171
|
result.push('', heading);
|
|
160
172
|
result.push(...bucket);
|
|
161
173
|
}
|
|
162
|
-
return result.join('\n');
|
|
174
|
+
return dedupePersona(result.join('\n'));
|
|
163
175
|
}
|
|
164
176
|
/**
|
|
165
177
|
* Resolve one conflicting session note by keeping the later `at:` stamp.
|
|
@@ -407,6 +419,7 @@ export class MemorySync {
|
|
|
407
419
|
debounce;
|
|
408
420
|
pushing = false;
|
|
409
421
|
inflight;
|
|
422
|
+
dirtyWhileInflight = false;
|
|
410
423
|
lastOutcome;
|
|
411
424
|
constructor(options) {
|
|
412
425
|
this.options = options;
|
|
@@ -503,6 +516,8 @@ export class MemorySync {
|
|
|
503
516
|
* commit and the network happen later, on the debounce timer.
|
|
504
517
|
*/
|
|
505
518
|
queueCommit() {
|
|
519
|
+
if (this.inflight !== undefined)
|
|
520
|
+
this.dirtyWhileInflight = true;
|
|
506
521
|
if (this.debounce !== undefined)
|
|
507
522
|
return;
|
|
508
523
|
this.debounce = setTimeout(() => {
|
|
@@ -525,9 +540,14 @@ export class MemorySync {
|
|
|
525
540
|
async run(reason) {
|
|
526
541
|
if (this.inflight !== undefined)
|
|
527
542
|
return await this.inflight;
|
|
543
|
+
this.dirtyWhileInflight = false;
|
|
528
544
|
this.inflight = this.flush(reason).finally(() => { this.inflight = undefined; });
|
|
529
545
|
const outcome = await this.inflight;
|
|
530
546
|
this.lastOutcome = outcome;
|
|
547
|
+
if (this.dirtyWhileInflight && this.debounce === undefined) {
|
|
548
|
+
this.dirtyWhileInflight = false;
|
|
549
|
+
this.queueCommit();
|
|
550
|
+
}
|
|
531
551
|
return outcome;
|
|
532
552
|
}
|
|
533
553
|
/** The body of one run; see {@link run}. */
|
|
@@ -548,7 +568,9 @@ export class MemorySync {
|
|
|
548
568
|
resolvedByTime = pull.resolvedByTime;
|
|
549
569
|
mergedByStructure = pull.mergedByStructure;
|
|
550
570
|
stoppedBy = pull.stoppedBy;
|
|
551
|
-
|
|
571
|
+
if (stoppedBy !== 'rebase-not-started') {
|
|
572
|
+
pushed = await this.push();
|
|
573
|
+
}
|
|
552
574
|
}
|
|
553
575
|
if (committed > 0 || pulled > 0 || conflicts > 0 || pushed || stoppedBy !== undefined) {
|
|
554
576
|
this.options.log.info('dsh-cross-memory: 记忆库同步(%s):提交 %d、拉取 %d、推送 %s、冲突 %d(AI %d / 时间 %d / 结构 %d)%s', reason, committed, pulled, pushed ? '是' : '否', conflicts, resolvedByResolver, resolvedByTime, mergedByStructure, stoppedBy === undefined ? '' : ',止于 ' + stoppedBy);
|
package/lib/test/archive.test.js
CHANGED
|
@@ -180,3 +180,22 @@ test('a near-duplicate rewrite that keeps everything still supersedes', async (t
|
|
|
180
180
|
assert.ok(!live.some((entry) => entry.id === older.entry.id), 'the predecessor is retired');
|
|
181
181
|
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), [older.entry.id]);
|
|
182
182
|
});
|
|
183
|
+
test('an auto-extracted near-duplicate that drops material skips creating a second copy', async (t) => {
|
|
184
|
+
const { store, dir } = await tempStore();
|
|
185
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
186
|
+
store.similarityLimit = () => 0.7;
|
|
187
|
+
const older = await store.upsert({
|
|
188
|
+
scope: 'global', title: 'Push rule public repositories private',
|
|
189
|
+
body: 'public repositories push directly; private repositories ask first.',
|
|
190
|
+
tags: ['git', 'push'],
|
|
191
|
+
}, undefined, 'tool', 1);
|
|
192
|
+
const dup = await store.upsert({
|
|
193
|
+
scope: 'global', title: 'Push rule public repositories',
|
|
194
|
+
body: 'public repositories push directly; private repositories ask first.',
|
|
195
|
+
tags: ['git'],
|
|
196
|
+
}, undefined, 'auto', 2);
|
|
197
|
+
assert.equal(dup.action, 'updated');
|
|
198
|
+
assert.equal(dup.entry.id, older.entry.id);
|
|
199
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
200
|
+
assert.equal(live.length, 1, 'no redundant second file is written for weaker auto duplicates');
|
|
201
|
+
});
|
|
@@ -123,19 +123,22 @@ test('the consolidation child is denied every write and network tool', async ()
|
|
|
123
123
|
assert.deepEqual([...CONSOLIDATE_DENY_TOOLS].length, request.toolFilter.deny.length);
|
|
124
124
|
});
|
|
125
125
|
test('the 0.2.1-rc.2 seam runs the child under a tool-free preset', async () => {
|
|
126
|
-
// The kernel
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
const seen = {};
|
|
126
|
+
// The kernel takes the child's tool set from the preset it names, and
|
|
127
|
+
// expects a flat `SubagentActivationSpec` (`parent`, `agentPreset`, etc. at top level).
|
|
128
|
+
const seen = { disposed: 0 };
|
|
130
129
|
const reply = '{"memories":[{"id":null,"scope":"global","title":"t","body":"b"}],"retire":[],"notes":"n"}';
|
|
131
130
|
const modern = {
|
|
132
131
|
startActivation: async (spec) => {
|
|
133
132
|
seen.spec = spec;
|
|
134
|
-
return {
|
|
133
|
+
return {
|
|
134
|
+
result: Promise.resolve({ output: [{ type: 'text', text: reply }], structured: undefined, stopReason: { kind: 'completed' } }),
|
|
135
|
+
dispose: async () => { seen.disposed += 1; },
|
|
136
|
+
};
|
|
135
137
|
},
|
|
136
138
|
};
|
|
139
|
+
const parent = { id: 'parent-1' };
|
|
137
140
|
const plan = await runConsolidation(modern, {
|
|
138
|
-
parent
|
|
141
|
+
parent,
|
|
139
142
|
entries: [entry({ id: 'a', title: 'A', body: 'a' })],
|
|
140
143
|
projectLabel: 'project:x',
|
|
141
144
|
maxUpserts: 10,
|
|
@@ -147,10 +150,13 @@ test('the 0.2.1-rc.2 seam runs the child under a tool-free preset', async () =>
|
|
|
147
150
|
assert.ok(plan !== undefined);
|
|
148
151
|
const spec = seen.spec;
|
|
149
152
|
assert.equal(spec.provider, 'spawn');
|
|
150
|
-
assert.equal(spec.
|
|
151
|
-
assert.equal(spec.
|
|
152
|
-
assert.
|
|
153
|
-
assert.
|
|
153
|
+
assert.equal(spec.parent, parent);
|
|
154
|
+
assert.equal(spec.agentPreset, 'memories-consolidator');
|
|
155
|
+
assert.equal(spec.maxDepth, 1, 'the child runs, but cannot delegate further');
|
|
156
|
+
assert.ok(spec.outputSchema !== undefined, 'the child must answer through the JSON schema');
|
|
157
|
+
assert.equal(spec.toolFilter, undefined, 'the new spec carries no tool filter');
|
|
158
|
+
assert.equal(spec.request, undefined, 'the new spec is flat, with no nested request object');
|
|
159
|
+
assert.equal(seen.disposed, 1, 'activation must be disposed once run.result settles');
|
|
154
160
|
});
|
|
155
161
|
test('the modern seam is refused without a preset, because the child would inherit the parent tools', async () => {
|
|
156
162
|
// A child that names no preset inherits the parent's composition, so the
|
|
@@ -207,6 +213,9 @@ test('renderConsolidationInput groups by scope and lists ids', () => {
|
|
|
207
213
|
assert.match(text, /## project/u);
|
|
208
214
|
assert.match(text, /id: g1/u);
|
|
209
215
|
assert.match(text, /id: p1/u);
|
|
216
|
+
const withSkills = renderConsolidationInput([entry({ id: 'g1', title: 'Global one', body: 'g', scope: 'global' })], 'project:demo', undefined, [{ name: 'homebrew-upgrade-repair', description: 'Homebrew 升级修复流程' }]);
|
|
217
|
+
assert.match(withSkills, /## Existing skill drafts/u);
|
|
218
|
+
assert.match(withSkills, /homebrew-upgrade-repair: Homebrew 升级修复流程/u);
|
|
210
219
|
});
|
|
211
220
|
test('parsePlan keeps only ids that exist and drops self-contradictory retirements', () => {
|
|
212
221
|
const known = new Set(['keep-me', 'retire-me']);
|
|
@@ -528,3 +537,32 @@ test('a child that answers without a plan names why the pass stopped', async ()
|
|
|
528
537
|
assert.match(reasons[0] ?? '', /carried no plan/u);
|
|
529
538
|
assert.match(reasons[0] ?? '', /stopReason: error/u, 'the child ending goes into the report');
|
|
530
539
|
});
|
|
540
|
+
test('startActivation disposes the activation even when run.result rejects', async () => {
|
|
541
|
+
let disposed = 0;
|
|
542
|
+
const seam = {
|
|
543
|
+
startActivation: async () => ({
|
|
544
|
+
result: Promise.reject(new Error('child crashed')),
|
|
545
|
+
dispose: async () => { disposed += 1; },
|
|
546
|
+
}),
|
|
547
|
+
};
|
|
548
|
+
await assert.rejects(() => runConsolidation(seam, modernRequest()), /child crashed/u);
|
|
549
|
+
assert.equal(disposed, 1);
|
|
550
|
+
});
|
|
551
|
+
test('runConsolidationDirect reports stream error finish via onSkip', async () => {
|
|
552
|
+
const reasons = [];
|
|
553
|
+
const failingLlm = {
|
|
554
|
+
stream: () => (async function* () {
|
|
555
|
+
yield { type: 'finish', reason: { kind: 'error', failure: { message: 'boom', code: 'ERR' } } };
|
|
556
|
+
})(),
|
|
557
|
+
};
|
|
558
|
+
const plan = await runConsolidationDirect(failingLlm, {
|
|
559
|
+
...modernRequest({
|
|
560
|
+
parent: { session: { id: 's1' } },
|
|
561
|
+
onSkip: (reason) => reasons.push(reason),
|
|
562
|
+
}),
|
|
563
|
+
route: { provider: 'p', model: 'm' },
|
|
564
|
+
});
|
|
565
|
+
assert.equal(plan, undefined);
|
|
566
|
+
assert.equal(reasons.length, 1);
|
|
567
|
+
assert.match(reasons[0] ?? '', /error: boom/u);
|
|
568
|
+
});
|
package/lib/test/extract.test.js
CHANGED
|
@@ -15,7 +15,7 @@ import { tmpdir } from 'node:os';
|
|
|
15
15
|
import { join } from 'node:path';
|
|
16
16
|
import test from 'node:test';
|
|
17
17
|
import { MemoriesRuntime } from '../index.js';
|
|
18
|
-
import { EXTRACT_JSON_SCHEMA, bindEvidence, collectExtractionWindow, collectWindow, mustCoverCandidates, parseExtraction, redactSecrets, renderMustCover, resolveRelativeTimes, runExtraction, selectKnownTitles } from '../extract.js';
|
|
18
|
+
import { EXTRACT_JSON_SCHEMA, bindEvidence, collectExtractionWindow, collectWindow, mustCoverCandidates, parseExtraction, redactSecrets, renderMustCover, resolveLlmRoute, resolveRelativeTimes, runExtraction, selectKnownTitles } from '../extract.js';
|
|
19
19
|
import { normalizeSettings } from '../config.js';
|
|
20
20
|
import { peakDelayMs } from '../schedule.js';
|
|
21
21
|
/**
|
|
@@ -153,8 +153,27 @@ test('redactSecrets removes credential-shaped text and keeps prose', () => {
|
|
|
153
153
|
assert.equal(redactSecrets('AWS AKIAABCDEFGHIJKLMNOP here'), 'AWS [redacted] here');
|
|
154
154
|
assert.equal(redactSecrets('Authorization: Bearer abcdefghijklmnopqrstuvwxyz'), 'Authorization: [redacted]');
|
|
155
155
|
assert.equal(redactSecrets('api_key = "supersecretvalue"'), '[redacted]');
|
|
156
|
+
assert.equal(redactSecrets('路由器管理密码 402402402,登录后取 token'), '路由器[redacted],登录后取 token');
|
|
157
|
+
assert.equal(redactSecrets('默认口令是 Mubea2026!,旧口令已被黑名单拦截'), '[redacted],旧口令已被黑名单拦截');
|
|
158
|
+
assert.equal(redactSecrets('快照里的口令未知,密码不对或命中弱口令黑名单'), '快照里的口令未知,密码不对或命中弱口令黑名单');
|
|
156
159
|
assert.equal(redactSecrets('plain prose about pnpm'), 'plain prose about pnpm');
|
|
157
160
|
});
|
|
161
|
+
test('mustCoverCandidates skips routine patrol readings and parseExtraction reads closedLoops', () => {
|
|
162
|
+
const candidates = mustCoverCandidates([
|
|
163
|
+
{ seq: 1, text: '2026-11-27 巡检:.dsh 1.72 GiB,无待归位会话、0 项清理,今日无变化。' },
|
|
164
|
+
{ seq: 2, text: '2026-11-27 版本对比巡检:19 项有更新,免费 9 付费 8。' },
|
|
165
|
+
{ seq: 3, text: '约定:生产包必须只发 .pyc 并附带 sha256 清单,发布前先跑全量回放。' },
|
|
166
|
+
]);
|
|
167
|
+
assert.equal(candidates.length, 1);
|
|
168
|
+
assert.equal(candidates[0]?.seq, 3);
|
|
169
|
+
const parsed = parseExtraction(JSON.stringify({
|
|
170
|
+
memories: [],
|
|
171
|
+
loops: [],
|
|
172
|
+
closedLoops: ['loop-1f2eibj', 'loop-1f2eibj', ''],
|
|
173
|
+
summary: 'done',
|
|
174
|
+
}), 5, 's1');
|
|
175
|
+
assert.deepEqual(parsed.closedLoops, ['loop-1f2eibj']);
|
|
176
|
+
});
|
|
158
177
|
test('parseExtraction keeps the string keys and drops the rest', () => {
|
|
159
178
|
const parsed = parseExtraction('{"memories":[{"scope":"global","title":"Prefer pnpm","body":"Use pnpm.","keys":["monorepo",7]}]}', 5, 'session-1');
|
|
160
179
|
assert.deepEqual([...parsed.drafts[0]?.keys ?? []], ['monorepo']);
|
|
@@ -1105,3 +1124,13 @@ test('a backlog is mined from the oldest end, so no message can be skipped', ()
|
|
|
1105
1124
|
}
|
|
1106
1125
|
assert.deepEqual(seen, events.map((event) => event.seq));
|
|
1107
1126
|
});
|
|
1127
|
+
test('resolveLlmRoute treats empty or whitespace provider/model as unset and falls back cleanly', () => {
|
|
1128
|
+
const session = stubSession('/tmp', []);
|
|
1129
|
+
assert.deepEqual(resolveLlmRoute(session, '', '', {}), { provider: 'fake-provider', model: 'fake-model' });
|
|
1130
|
+
assert.deepEqual(resolveLlmRoute(session, ' ', 'm', {}), { provider: 'fake-provider', model: 'fake-model' });
|
|
1131
|
+
assert.deepEqual(resolveLlmRoute(session, 'p', ' ', {}), { provider: 'fake-provider', model: 'fake-model' });
|
|
1132
|
+
assert.deepEqual(resolveLlmRoute(session, 'custom-p', 'custom-m', {}), { provider: 'custom-p', model: 'custom-m' });
|
|
1133
|
+
const bareSession = { id: 'bare', requestHeader: () => undefined };
|
|
1134
|
+
assert.equal(resolveLlmRoute(bareSession, '', '', { provider: '', model: '' }), undefined);
|
|
1135
|
+
assert.deepEqual(resolveLlmRoute(bareSession, '', '', { provider: 'fb-p', model: 'fb-m' }), { provider: 'fb-p', model: 'fb-m' });
|
|
1136
|
+
});
|
package/lib/test/loops.test.js
CHANGED
|
@@ -63,18 +63,19 @@ test('the command view puts the soonest deadline first', () => {
|
|
|
63
63
|
assert.match(view, /今天交报告[\s\S]*后天交报告/u);
|
|
64
64
|
});
|
|
65
65
|
test('extraction keeps a real deadline and drops an invented one', () => {
|
|
66
|
+
const upcoming = new Date(Date.now() + 7 * 86_400_000).toISOString();
|
|
66
67
|
const reply = JSON.stringify({
|
|
67
68
|
memories: [],
|
|
68
69
|
summary: 's',
|
|
69
70
|
loops: [
|
|
70
|
-
{ text: '周五前把合同发出去', dueAt:
|
|
71
|
+
{ text: '周五前把合同发出去', dueAt: upcoming },
|
|
71
72
|
{ text: '顺手清理一下桌面', dueAt: '不是日期' },
|
|
72
73
|
{ text: '' },
|
|
73
74
|
],
|
|
74
75
|
});
|
|
75
76
|
const parsed = parseExtraction(reply, 10, 'session-1');
|
|
76
77
|
assert.equal(parsed.loops.length, 2);
|
|
77
|
-
assert.equal(parsed.loops[0]?.dueAt, Date.parse(
|
|
78
|
+
assert.equal(parsed.loops[0]?.dueAt, Date.parse(upcoming));
|
|
78
79
|
assert.equal(parsed.loops[1]?.dueAt, undefined, 'an unparseable deadline is dropped, never defaulted');
|
|
79
80
|
// A model that reads "things the user would do" and answers with bare strings
|
|
80
81
|
// must not lose the promises: that exact reply shape appeared in the e2e run.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the lightweight stdio MCP server exposing `$DSH_HOME/memories`.
|
|
3
|
+
*
|
|
4
|
+
* @module dsh-cross-memory/test/mcp.test
|
|
5
|
+
*/
|
|
6
|
+
import assert from 'node:assert/strict';
|
|
7
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import test from 'node:test';
|
|
11
|
+
import { handleMcpRequest, defaultMcpOptions } from '../mcp.js';
|
|
12
|
+
import { writePersona } from '../persona.js';
|
|
13
|
+
test('MCP server supports initialize, tools/list, persona, write (with redaction), search, read, and projects', async (t) => {
|
|
14
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-mcp-'));
|
|
15
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
16
|
+
const options = {
|
|
17
|
+
memoriesDir: dir,
|
|
18
|
+
denseEnabled: false,
|
|
19
|
+
denseUrl: 'http://127.0.0.1:11434',
|
|
20
|
+
denseModel: 'qwen3-embedding:0.6b',
|
|
21
|
+
};
|
|
22
|
+
const init = await handleMcpRequest({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26' } }, options);
|
|
23
|
+
assert.equal((init?.result).protocolVersion, '2025-03-26');
|
|
24
|
+
const listed = await handleMcpRequest({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, options);
|
|
25
|
+
const toolNames = ((listed?.result).tools).map((tool) => tool.name);
|
|
26
|
+
assert.deepEqual(toolNames, ['memory_persona', 'memory_search', 'memory_read', 'memory_write', 'memory_projects']);
|
|
27
|
+
await writePersona(dir, '## 他怎么工作\n- 中文短句直给。');
|
|
28
|
+
const personaRes = await handleMcpRequest({
|
|
29
|
+
jsonrpc: '2.0',
|
|
30
|
+
id: 3,
|
|
31
|
+
method: 'tools/call',
|
|
32
|
+
params: { name: 'memory_persona', arguments: {} },
|
|
33
|
+
}, options);
|
|
34
|
+
const personaText = (personaRes?.result).content[0].text;
|
|
35
|
+
assert.match(personaText, /中文短句直给/u);
|
|
36
|
+
// Write global memory with a Chinese password to verify automatic redaction
|
|
37
|
+
const writeGlobal = await handleMcpRequest({
|
|
38
|
+
jsonrpc: '2.0',
|
|
39
|
+
id: 4,
|
|
40
|
+
method: 'tools/call',
|
|
41
|
+
params: {
|
|
42
|
+
name: 'memory_write',
|
|
43
|
+
arguments: {
|
|
44
|
+
scope: 'global',
|
|
45
|
+
title: '路由器管理方式',
|
|
46
|
+
body: '小米路由器使用 mi.sh 管理,管理密码 402402402。',
|
|
47
|
+
kind: 'knowledge',
|
|
48
|
+
keys: ['router', 'mi.sh'],
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
}, options);
|
|
52
|
+
assert.match((writeGlobal?.result).content[0].text, /Remembered global memory/u);
|
|
53
|
+
// Write project memory
|
|
54
|
+
const projectRoot = join(dir, 'fake-repo');
|
|
55
|
+
await handleMcpRequest({
|
|
56
|
+
jsonrpc: '2.0',
|
|
57
|
+
id: 5,
|
|
58
|
+
method: 'tools/call',
|
|
59
|
+
params: {
|
|
60
|
+
name: 'memory_write',
|
|
61
|
+
arguments: {
|
|
62
|
+
scope: 'project',
|
|
63
|
+
projectRoot,
|
|
64
|
+
title: '构建命令用 pnpm build',
|
|
65
|
+
body: '改动源码后必须运行 pnpm build 重新生成 lib/。',
|
|
66
|
+
kind: 'procedure',
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
}, options);
|
|
70
|
+
// Search across project + global
|
|
71
|
+
const searchRes = await handleMcpRequest({
|
|
72
|
+
jsonrpc: '2.0',
|
|
73
|
+
id: 6,
|
|
74
|
+
method: 'tools/call',
|
|
75
|
+
params: { name: 'memory_search', arguments: { query: '路由器 mi.sh', projectRoot } },
|
|
76
|
+
}, options);
|
|
77
|
+
const searchText = (searchRes?.result).content[0].text;
|
|
78
|
+
assert.match(searchText, /路由器管理方式/u);
|
|
79
|
+
// Read back and verify password was redacted
|
|
80
|
+
const readRes = await handleMcpRequest({
|
|
81
|
+
jsonrpc: '2.0',
|
|
82
|
+
id: 7,
|
|
83
|
+
method: 'tools/call',
|
|
84
|
+
params: { name: 'memory_read', arguments: { id: '路由器管理方式', scope: 'global' } },
|
|
85
|
+
}, options);
|
|
86
|
+
const readText = (readRes?.result).content[0].text;
|
|
87
|
+
assert.match(readText, /\[redacted\]/u);
|
|
88
|
+
assert.doesNotMatch(readText, /402402402/u);
|
|
89
|
+
// List projects
|
|
90
|
+
const projectsRes = await handleMcpRequest({
|
|
91
|
+
jsonrpc: '2.0',
|
|
92
|
+
id: 8,
|
|
93
|
+
method: 'tools/call',
|
|
94
|
+
params: { name: 'memory_projects', arguments: {} },
|
|
95
|
+
}, options);
|
|
96
|
+
const projectsText = (projectsRes?.result).content[0].text;
|
|
97
|
+
assert.match(projectsText, /fake-repo \(1 entries\)/u);
|
|
98
|
+
});
|
|
99
|
+
test('defaultMcpOptions keeps dense cache outside memoriesDir', () => {
|
|
100
|
+
const opts = defaultMcpOptions({ DSH_HOME: '/tmp/fake-dsh' });
|
|
101
|
+
assert.equal(opts.memoriesDir, '/tmp/fake-dsh/memories');
|
|
102
|
+
assert.equal(opts.cacheDir, '/tmp/fake-dsh/cache/dsh-cross-memory');
|
|
103
|
+
});
|
package/lib/test/notices.test.js
CHANGED
|
@@ -140,3 +140,70 @@ test('an ambiguous or unknown prefix is refused instead of guessing', () => {
|
|
|
140
140
|
const unknown = ackNotice(queue, 'zzzz', 'acted', NOW);
|
|
141
141
|
assert.equal(unknown.notice, undefined);
|
|
142
142
|
});
|
|
143
|
+
test('gateNotices falls back on empty provider/model and reports stream finish errors', async () => {
|
|
144
|
+
const candidates = [{ id: 'loop-a', title: '还挂着:发报价单', detail: '说了 4 天' }];
|
|
145
|
+
const session = {
|
|
146
|
+
id: 'gate-session',
|
|
147
|
+
requestHeader: () => ({ config: { provider: 'deepseek-account', model: 'deepseek-flash' } }),
|
|
148
|
+
};
|
|
149
|
+
const seen = {};
|
|
150
|
+
const okLlm = {
|
|
151
|
+
stream: (options) => {
|
|
152
|
+
seen.provider = options.provider;
|
|
153
|
+
seen.model = options.model;
|
|
154
|
+
seen.maxTokens = options.maxTokens;
|
|
155
|
+
seen.userText = options.messages[0]?.content[0]?.text;
|
|
156
|
+
return (async function* () {
|
|
157
|
+
yield { type: 'text-delta', index: 0, text: '{"deliver":["loop-a"],"reason":"报价单需要尽快发"}' };
|
|
158
|
+
yield { type: 'finish', reason: { kind: 'stop' } };
|
|
159
|
+
})();
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
const outcome = await gateNotices({
|
|
163
|
+
llm: okLlm,
|
|
164
|
+
session,
|
|
165
|
+
candidates,
|
|
166
|
+
provider: '',
|
|
167
|
+
model: '',
|
|
168
|
+
timeoutMs: 1000,
|
|
169
|
+
signal: new AbortController().signal,
|
|
170
|
+
});
|
|
171
|
+
assert.equal(seen.provider, 'deepseek-account');
|
|
172
|
+
assert.equal(seen.model, 'deepseek-flash');
|
|
173
|
+
assert.ok((seen.maxTokens ?? 0) >= 2048);
|
|
174
|
+
assert.match(seen.userText ?? '', /## Candidates/u);
|
|
175
|
+
assert.deepEqual([...outcome.deliver], ['loop-a']);
|
|
176
|
+
const errLlm = {
|
|
177
|
+
stream: () => (async function* () {
|
|
178
|
+
yield { type: 'finish', reason: { kind: 'error', failure: { message: 'unknown provider', code: 'BAD_ROUTE' } } };
|
|
179
|
+
})(),
|
|
180
|
+
};
|
|
181
|
+
const errOutcome = await gateNotices({
|
|
182
|
+
llm: errLlm,
|
|
183
|
+
session,
|
|
184
|
+
candidates,
|
|
185
|
+
timeoutMs: 1000,
|
|
186
|
+
signal: new AbortController().signal,
|
|
187
|
+
});
|
|
188
|
+
assert.equal(errOutcome.deliver.size, 0);
|
|
189
|
+
assert.equal(errOutcome.skipped, 'failed');
|
|
190
|
+
assert.match(errOutcome.reason, /gate call error: unknown provider/u);
|
|
191
|
+
const truncatedLlm = {
|
|
192
|
+
stream: () => (async function* () {
|
|
193
|
+
yield { type: 'finish', reason: { kind: 'max-tokens' } };
|
|
194
|
+
})(),
|
|
195
|
+
};
|
|
196
|
+
const truncOutcome = await gateNotices({
|
|
197
|
+
llm: truncatedLlm,
|
|
198
|
+
session,
|
|
199
|
+
candidates,
|
|
200
|
+
timeoutMs: 1000,
|
|
201
|
+
signal: new AbortController().signal,
|
|
202
|
+
});
|
|
203
|
+
assert.equal(truncOutcome.deliver.size, 0);
|
|
204
|
+
assert.equal(truncOutcome.skipped, 'failed');
|
|
205
|
+
assert.match(truncOutcome.reason, /hit maxTokens/u);
|
|
206
|
+
const withQuotedProse = parseGateReply('Example shape is {"deliver":[...]} so my reply:\n{"deliver":["loop-a"],"reason":"ok"}', candidates);
|
|
207
|
+
assert.equal(withQuotedProse.failed, false);
|
|
208
|
+
assert.deepEqual([...withQuotedProse.deliver], ['loop-a']);
|
|
209
|
+
});
|
package/lib/test/persona.test.js
CHANGED
|
@@ -14,7 +14,8 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
|
14
14
|
import { tmpdir } from 'node:os';
|
|
15
15
|
import { join } from 'node:path';
|
|
16
16
|
import test from 'node:test';
|
|
17
|
-
import { clearPersona, isPersonaLocked, personaLockPath, personaPath, readPersona, renderPersonaBlock, setPersonaLocked, writePersona } from '../persona.js';
|
|
17
|
+
import { clearPersona, dedupePersona, isNearDuplicateBullet, isPersonaLocked, personaLockPath, personaPath, readPersona, renderPersonaBlock, setPersonaLocked, writePersona } from '../persona.js';
|
|
18
|
+
import { mergePersona } from '../sync.js';
|
|
18
19
|
import { MemoryStore } from '../storage.js';
|
|
19
20
|
import { parsePlan } from '../consolidate.js';
|
|
20
21
|
test('a profile round-trips through the store directory', async (t) => {
|
|
@@ -84,3 +85,41 @@ test('the manual-edit lock is a timestamped marker, and clearing removes the pro
|
|
|
84
85
|
await setPersonaLocked(dir, false);
|
|
85
86
|
assert.equal(await isPersonaLocked(dir), false, 'unlocking removes the marker');
|
|
86
87
|
});
|
|
88
|
+
test('dedupePersona and mergePersona collapse rephrased duplicate bullets within a section', async (t) => {
|
|
89
|
+
const ours = [
|
|
90
|
+
'## 他怎么工作',
|
|
91
|
+
'- 中文短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。',
|
|
92
|
+
'- 做完一轮就 commit + push,不留本地未推提交;公开仓库直接推,私有先问。',
|
|
93
|
+
'',
|
|
94
|
+
'## 他的环境',
|
|
95
|
+
'- Python 一律 uv 管理。',
|
|
96
|
+
].join('\n');
|
|
97
|
+
const theirs = [
|
|
98
|
+
'## 他怎么工作',
|
|
99
|
+
'- 中文交流、短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。',
|
|
100
|
+
'- 做完一轮改动就 commit + push 到 origin,不留本地未推提交;公开仓库直接推,私有或新建仓库先问。',
|
|
101
|
+
'- 对客户只问对方能拍板的业务口径,实现细节自己定。',
|
|
102
|
+
'',
|
|
103
|
+
'## 他的环境',
|
|
104
|
+
'- Mac 文件管理主用 QSpace Pro。',
|
|
105
|
+
].join('\n');
|
|
106
|
+
assert.equal(isNearDuplicateBullet('- 中文短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。', '- 中文交流、短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。'), true);
|
|
107
|
+
assert.equal(isNearDuplicateBullet('- Python 一律 uv 管理。', '- Mac 文件管理主用 QSpace Pro。'), false);
|
|
108
|
+
const merged = mergePersona(ours, theirs);
|
|
109
|
+
assert.equal((merged.match(/不用客套与 emoji/gu) ?? []).length, 1, 'rephrased duplicate is not appended');
|
|
110
|
+
assert.equal((merged.match(/commit \+ push/gu) ?? []).length, 1, 'tightened duplicate is not appended');
|
|
111
|
+
assert.match(merged, /对客户只问对方能拍板的业务口径/u, 'genuinely new bullet from theirs is kept');
|
|
112
|
+
assert.match(merged, /QSpace Pro/u, 'genuinely new bullet in another section is kept');
|
|
113
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-persona-dedupe-'));
|
|
114
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
115
|
+
const doubled = [
|
|
116
|
+
'## 他怎么工作',
|
|
117
|
+
'- 中文短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。',
|
|
118
|
+
'- 中文交流、短句直给,不用客套与 emoji;结论先行、证据随后,事实与推断分开。',
|
|
119
|
+
].join('\n');
|
|
120
|
+
await writePersona(dir, doubled);
|
|
121
|
+
const saved = await readPersona(dir);
|
|
122
|
+
assert.ok(saved !== undefined);
|
|
123
|
+
assert.equal(dedupePersona(saved), saved);
|
|
124
|
+
assert.equal((saved.match(/不用客套与 emoji/gu) ?? []).length, 1);
|
|
125
|
+
});
|
package/lib/test/recall.test.js
CHANGED
|
@@ -14,7 +14,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
|
14
14
|
import { tmpdir } from 'node:os';
|
|
15
15
|
import { join } from 'node:path';
|
|
16
16
|
import test from 'node:test';
|
|
17
|
-
import { MemoriesRuntime } from '../index.js';
|
|
17
|
+
import { MemoriesRuntime, isSubagentSession } from '../index.js';
|
|
18
18
|
import { renderRecall } from '../render.js';
|
|
19
19
|
import { hubTerms, matchCredit } from '../search.js';
|
|
20
20
|
import { Logger } from '@deepseek-ai/cordis';
|
|
@@ -466,3 +466,56 @@ test('the stronger lexical match is listed first, even when a weaker one is fres
|
|
|
466
466
|
assert.ok(weaker >= 0, `the weaker match is still worth a slot, got: ${text}`);
|
|
467
467
|
assert.ok(exact < weaker, `the memory the turn is about comes first, got: ${text}`);
|
|
468
468
|
});
|
|
469
|
+
test('recallFor deduplicates repeated steps within the same human user turn and continuation turns', async (t) => {
|
|
470
|
+
const { dir, runtime } = await fixture(t, { ragRecall: true });
|
|
471
|
+
const entries = join(dir, 'entries');
|
|
472
|
+
await mkdir(entries, { recursive: true });
|
|
473
|
+
await writeFile(join(entries, 'alpha.md'), [
|
|
474
|
+
'---',
|
|
475
|
+
'id: alpha',
|
|
476
|
+
'scope: global',
|
|
477
|
+
'kind: fact',
|
|
478
|
+
'title: 阿尔法构建规矩',
|
|
479
|
+
'tags: build',
|
|
480
|
+
'keys: alpha, build',
|
|
481
|
+
'created: 2026-01-01T00:00:00.000Z',
|
|
482
|
+
'updated: 2026-01-01T00:00:00.000Z',
|
|
483
|
+
'source: auto',
|
|
484
|
+
'---',
|
|
485
|
+
'',
|
|
486
|
+
'阿尔法仓库必须先跑 build 再跑 test。',
|
|
487
|
+
].join('\n'));
|
|
488
|
+
let messages = [
|
|
489
|
+
{ id: 'u1', role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: '阿尔法仓库 build 规矩是什么' }] },
|
|
490
|
+
];
|
|
491
|
+
const session = {
|
|
492
|
+
id: 'dedup-turn-session',
|
|
493
|
+
header: { version: 0, id: 'dedup-turn-session', createdAt: 0, cwd: dir, isSeeded: false },
|
|
494
|
+
seq: 1,
|
|
495
|
+
requestHeader: () => undefined,
|
|
496
|
+
deriveMessages: () => messages,
|
|
497
|
+
};
|
|
498
|
+
const agent = stubAgent(session);
|
|
499
|
+
// Simulate RAG excerpts on the first step; second step and continuation turn must not duplicate them.
|
|
500
|
+
let ragCalls = 0;
|
|
501
|
+
runtime.ragExcerpts = async () => {
|
|
502
|
+
ragCalls += 1;
|
|
503
|
+
return [{ sessionId: 'other-session', seq: 1, role: 'assistant', text: '阿尔法仓库 build 规矩:先 build 再 test,这是一段历史对话原文片段。' }];
|
|
504
|
+
};
|
|
505
|
+
const first = await runtime.recallFor(agent);
|
|
506
|
+
assert.ok(first !== undefined, 'first step recalls');
|
|
507
|
+
assert.equal(ragCalls, 1);
|
|
508
|
+
// Simulate tool-call step 2 AND a refusal-guard continuation message on the same user turn.
|
|
509
|
+
messages = [
|
|
510
|
+
...messages,
|
|
511
|
+
{ id: 'c1', role: 'user', source: { kind: 'cordis-host-runner' }, content: [{ type: 'text', text: '继续' }] },
|
|
512
|
+
];
|
|
513
|
+
const second = await runtime.recallFor(agent);
|
|
514
|
+
assert.equal(second, undefined, 'same user turn must not trigger duplicate RAG or recall');
|
|
515
|
+
assert.equal(ragCalls, 1, 'ragExcerpts must not re-run for the same user turn');
|
|
516
|
+
});
|
|
517
|
+
test('isSubagentSession detects subagent origin and delegationDepth', () => {
|
|
518
|
+
assert.equal(isSubagentSession({ header: { origin: 'subagent' } }), true);
|
|
519
|
+
assert.equal(isSubagentSession({ header: { delegationDepth: 1 } }), true);
|
|
520
|
+
assert.equal(isSubagentSession({ header: { origin: 'interactive', delegationDepth: 0 } }), false);
|
|
521
|
+
});
|