dsh-cross-memory 0.2.12 → 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/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: 1_200,
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/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
- supersedes = previous !== undefined && carriesForward(previous, draft) ? similar : undefined;
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
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';
@@ -97,20 +98,28 @@ export function isPersonaPath(path) {
97
98
  return /(^|\/)persona\/[^/]+\.md$/u.test(path);
98
99
  }
99
100
  /**
100
- * Merge two versions of a persona file as a bullet union.
101
+ * Merge two versions of a persona file as a deduplicated bullet union.
101
102
  *
102
103
  * A persona file is headings plus bullet lists; both machines append their own
103
- * observations, so a line-level union keeps every rule either machine recorded.
104
- * Bullets are matched on their trimmed text (duplicates are dropped), inserted
105
- * after the last bullet of the same section, and a whole section that only
106
- * `theirs` has is appended at the end. Non-bullet lines come from `ours`.
104
+ * observations, so a section-aware union keeps every rule either machine
105
+ * recorded. Bullets are matched not only on exact text but also on near-duplicate
106
+ * token overlap within the same section — otherwise a consolidation pass that
107
+ * tightens wording on one machine causes the next sync to append the older
108
+ * phrasing beside it and double every section. Non-bullet lines come from `ours`.
107
109
  */
108
110
  export function mergePersona(ours, theirs) {
109
- const result = ours.split('\n');
110
- const seen = new Set();
111
+ const result = dedupePersona(ours).split('\n');
112
+ const sectionBullets = new Map();
113
+ let oursSection = '';
111
114
  for (const line of result) {
112
- if (line.startsWith('- '))
113
- seen.add(line.trim());
115
+ if (line.startsWith('#')) {
116
+ oursSection = line.trim();
117
+ }
118
+ else if (line.startsWith('- ')) {
119
+ const list = sectionBullets.get(oursSection) ?? [];
120
+ list.push(line.trim());
121
+ sectionBullets.set(oursSection, list);
122
+ }
114
123
  }
115
124
  // Bucket the bullets that only the other side has, by their section heading.
116
125
  const pending = new Map();
@@ -120,16 +129,18 @@ export function mergePersona(ours, theirs) {
120
129
  section = line.trim();
121
130
  else if (line.startsWith('- ')) {
122
131
  const key = line.trim();
123
- if (seen.has(key))
132
+ const existing = sectionBullets.get(section) ?? [];
133
+ if (existing.some((item) => isNearDuplicateBullet(item, key)))
124
134
  continue;
125
- seen.add(key);
135
+ existing.push(key);
136
+ sectionBullets.set(section, existing);
126
137
  const bucket = pending.get(section) ?? [];
127
138
  bucket.push(line);
128
139
  pending.set(section, bucket);
129
140
  }
130
141
  }
131
142
  if (pending.size === 0)
132
- return ours;
143
+ return result.join('\n');
133
144
  // Insert each bucket after the last line that belongs to its section.
134
145
  const sectionRanges = [];
135
146
  let current;
@@ -159,7 +170,7 @@ export function mergePersona(ours, theirs) {
159
170
  result.push('', heading);
160
171
  result.push(...bucket);
161
172
  }
162
- return result.join('\n');
173
+ return dedupePersona(result.join('\n'));
163
174
  }
164
175
  /**
165
176
  * Resolve one conflicting session note by keeping the later `at:` stamp.
@@ -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 of 0.2.1-rc.2 takes the child's tool set from the preset it
127
- // names; `toolFilter` and `persona` are gone from the start request, and the
128
- // model-facing subagent tool rejects both outright.
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 { result: Promise.resolve({ output: [{ type: 'text', text: reply }], structured: undefined, stopReason: { kind: 'completed' } }) };
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.request.agentPreset, 'memories-consolidator');
151
- assert.equal(spec.request.maxDepth, 1, 'the child runs, but cannot delegate further');
152
- assert.ok(spec.request.outputSchema !== undefined, 'the child must answer through the JSON schema');
153
- assert.equal(spec.request.toolFilter, undefined, 'the new request carries no tool filter');
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
+ });
@@ -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
+ });
@@ -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: '2026-10-30T00:00:00Z' },
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('2026-10-30T00:00:00Z'));
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,98 @@
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 } 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
+ });
@@ -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
+ });
@@ -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
+ });
@@ -12,7 +12,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
12
12
  import { tmpdir } from 'node:os';
13
13
  import { join } from 'node:path';
14
14
  import test from 'node:test';
15
- import { REFLECTION_INTERVAL_MS, REFLECTION_MIN_ENTRIES, listReflections, parseReflection, replyStats, previousInsights, reflectionDue, renderReflectionFile, writeReflection, } from '../reflection.js';
15
+ import { REFLECTION_INTERVAL_MS, REFLECTION_MIN_ENTRIES, listReflections, parseReflection, replyStats, previousInsights, reflectionDue, renderReflectionFile, runReflection, writeReflection, } from '../reflection.js';
16
16
  const NOW = Date.parse('2026-10-24T03:00:00Z');
17
17
  const known = new Set(['mem-a', 'mem-b']);
18
18
  test('an observation that cannot cite the store is dropped', () => {
@@ -62,3 +62,62 @@ test('a zero result reports whether the reply was empty or merely uncited', () =
62
62
  assert.equal(replyStats('not json', known), undefined);
63
63
  assert.deepEqual(replyStats('{"insights":"nope"}', known), { raw: 0, cited: 0 });
64
64
  });
65
+ test('runReflection falls back on empty provider/model and reports stream finish errors', async () => {
66
+ const entries = Array.from({ length: REFLECTION_MIN_ENTRIES }, (_, index) => ({
67
+ id: index === 0 ? 'mem-a' : `mem-${index}`,
68
+ scope: 'global',
69
+ kind: 'fact',
70
+ title: `title ${index}`,
71
+ body: `body ${index}`,
72
+ tags: [],
73
+ keys: [],
74
+ createdAt: NOW,
75
+ updatedAt: NOW,
76
+ uses: 0,
77
+ lastUsedAt: 0,
78
+ lastSurfacedAt: 0,
79
+ source: 'auto',
80
+ }));
81
+ const session = {
82
+ id: 'reflect-session',
83
+ requestHeader: () => ({ config: { provider: 'deepseek-account', model: 'deepseek-flash' } }),
84
+ };
85
+ const seen = {};
86
+ const okLlm = {
87
+ stream: (options) => {
88
+ seen.provider = options.provider;
89
+ seen.model = options.model;
90
+ return (async function* () {
91
+ yield { type: 'text-delta', index: 0, text: JSON.stringify({ insights: [{ text: '他总是在同一个项目上先写测试再改实现', evidence: ['mem-a'] }] }) };
92
+ yield { type: 'finish', reason: { kind: 'stop' } };
93
+ })();
94
+ },
95
+ };
96
+ const outcome = await runReflection({
97
+ llm: okLlm,
98
+ session,
99
+ entries,
100
+ provider: '',
101
+ model: '',
102
+ timeoutMs: 1000,
103
+ signal: new AbortController().signal,
104
+ });
105
+ assert.equal(seen.provider, 'deepseek-account');
106
+ assert.equal(seen.model, 'deepseek-flash');
107
+ assert.equal(outcome.insights.length, 1);
108
+ const errLlm = {
109
+ stream: () => (async function* () {
110
+ yield { type: 'finish', reason: { kind: 'error', failure: { message: 'empty route', code: 'BAD_ROUTE' } } };
111
+ })(),
112
+ };
113
+ const errOutcome = await runReflection({
114
+ llm: errLlm,
115
+ session,
116
+ entries,
117
+ timeoutMs: 1000,
118
+ signal: new AbortController().signal,
119
+ });
120
+ assert.equal(errOutcome.insights.length, 0);
121
+ assert.equal(errOutcome.skipped, 'failed');
122
+ assert.match(errOutcome.reason, /reflection call error: empty route/u);
123
+ });