dsh-cross-memory 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +27 -0
- package/docs/DETAIL.md +13 -0
- package/docs/DETAIL.zh.md +17 -0
- package/icon.svg +1 -0
- package/lib/backfill.js +273 -0
- package/lib/citations.js +305 -0
- package/lib/client.js +1550 -0
- package/lib/config.js +736 -0
- package/lib/consolidate.js +1119 -0
- package/lib/extract.js +570 -0
- package/lib/gate.js +137 -0
- package/lib/git-origin.js +224 -0
- package/lib/index.js +4475 -0
- package/lib/log.js +260 -0
- package/lib/loops.js +186 -0
- package/lib/notices.js +195 -0
- package/lib/notify.js +33 -0
- package/lib/persona.js +112 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +455 -0
- package/lib/render.js +678 -0
- package/lib/retention.js +64 -0
- package/lib/schedule.js +245 -0
- package/lib/search.js +1068 -0
- package/lib/skills.js +220 -0
- package/lib/state.js +701 -0
- package/lib/storage.js +1424 -0
- package/lib/sync-runtime.js +268 -0
- package/lib/sync.js +620 -0
- package/lib/test/activity.test.js +74 -0
- package/lib/test/archive.test.js +182 -0
- package/lib/test/backfill.test.js +144 -0
- package/lib/test/citations.test.js +91 -0
- package/lib/test/client-wiring.test.js +134 -0
- package/lib/test/consolidate-job.test.js +95 -0
- package/lib/test/consolidate.test.js +430 -0
- package/lib/test/consolidation-selection.test.js +152 -0
- package/lib/test/dedupe-keys.test.js +230 -0
- package/lib/test/delta.test.js +93 -0
- package/lib/test/derived.test.js +110 -0
- package/lib/test/disputes-panel.test.js +314 -0
- package/lib/test/eval.test.js +171 -0
- package/lib/test/expand.test.js +164 -0
- package/lib/test/extract.test.js +1020 -0
- package/lib/test/git-origin.test.js +189 -0
- package/lib/test/injection.test.js +440 -0
- package/lib/test/kind-filter.test.js +49 -0
- package/lib/test/legacy-state.test.js +69 -0
- package/lib/test/log.test.js +156 -0
- package/lib/test/loops.test.js +86 -0
- package/lib/test/memory.test.js +855 -0
- package/lib/test/notices.test.js +140 -0
- package/lib/test/persona.test.js +73 -0
- package/lib/test/prefilter.test.js +73 -0
- package/lib/test/preset.test.js +77 -0
- package/lib/test/raw-recall.test.js +186 -0
- package/lib/test/recall.test.js +433 -0
- package/lib/test/reflection.test.js +64 -0
- package/lib/test/remote.test.js +227 -0
- package/lib/test/retention.test.js +117 -0
- package/lib/test/retrieval.test.js +142 -0
- package/lib/test/rotation.test.js +228 -0
- package/lib/test/schedule.test.js +112 -0
- package/lib/test/settings-card.test.js +58 -0
- package/lib/test/skills.test.js +129 -0
- package/lib/test/state.test.js +212 -0
- package/lib/test/subagent-contract.test.js +139 -0
- package/lib/test/sweep.test.js +159 -0
- package/lib/test/sync.test.js +314 -0
- package/lib/test/time.test.js +171 -0
- package/lib/time.js +303 -0
- package/lib/tool.js +330 -0
- package/lib/types/backfill.d.ts +96 -0
- package/lib/types/citations.d.ts +105 -0
- package/lib/types/config.d.ts +811 -0
- package/lib/types/consolidate.d.ts +742 -0
- package/lib/types/extract.d.ts +352 -0
- package/lib/types/gate.d.ts +83 -0
- package/lib/types/git-origin.d.ts +23 -0
- package/lib/types/index.d.ts +1316 -0
- package/lib/types/log.d.ts +144 -0
- package/lib/types/loops.d.ts +82 -0
- package/lib/types/notices.d.ts +117 -0
- package/lib/types/notify.d.ts +12 -0
- package/lib/types/persona.d.ts +43 -0
- package/lib/types/query.d.ts +45 -0
- package/lib/types/raw-recall.d.ts +84 -0
- package/lib/types/reflection.d.ts +122 -0
- package/lib/types/remote.d.ts +233 -0
- package/lib/types/render.d.ts +286 -0
- package/lib/types/retention.d.ts +66 -0
- package/lib/types/schedule.d.ts +116 -0
- package/lib/types/search.d.ts +583 -0
- package/lib/types/skills.d.ts +71 -0
- package/lib/types/state.d.ts +294 -0
- package/lib/types/storage.d.ts +458 -0
- package/lib/types/sync-runtime.d.ts +103 -0
- package/lib/types/sync.d.ts +222 -0
- package/lib/types/test/activity.test.d.ts +1 -0
- package/lib/types/test/archive.test.d.ts +1 -0
- package/lib/types/test/backfill.test.d.ts +1 -0
- package/lib/types/test/citations.test.d.ts +1 -0
- package/lib/types/test/client-wiring.test.d.ts +1 -0
- package/lib/types/test/consolidate-job.test.d.ts +1 -0
- package/lib/types/test/consolidate.test.d.ts +1 -0
- package/lib/types/test/consolidation-selection.test.d.ts +1 -0
- package/lib/types/test/dedupe-keys.test.d.ts +1 -0
- package/lib/types/test/delta.test.d.ts +1 -0
- package/lib/types/test/derived.test.d.ts +1 -0
- package/lib/types/test/disputes-panel.test.d.ts +1 -0
- package/lib/types/test/eval.test.d.ts +1 -0
- package/lib/types/test/expand.test.d.ts +1 -0
- package/lib/types/test/extract.test.d.ts +1 -0
- package/lib/types/test/git-origin.test.d.ts +1 -0
- package/lib/types/test/injection.test.d.ts +1 -0
- package/lib/types/test/kind-filter.test.d.ts +1 -0
- package/lib/types/test/legacy-state.test.d.ts +1 -0
- package/lib/types/test/log.test.d.ts +1 -0
- package/lib/types/test/loops.test.d.ts +1 -0
- package/lib/types/test/memory.test.d.ts +1 -0
- package/lib/types/test/notices.test.d.ts +1 -0
- package/lib/types/test/persona.test.d.ts +1 -0
- package/lib/types/test/prefilter.test.d.ts +1 -0
- package/lib/types/test/preset.test.d.ts +1 -0
- package/lib/types/test/raw-recall.test.d.ts +1 -0
- package/lib/types/test/recall.test.d.ts +1 -0
- package/lib/types/test/reflection.test.d.ts +1 -0
- package/lib/types/test/remote.test.d.ts +1 -0
- package/lib/types/test/retention.test.d.ts +1 -0
- package/lib/types/test/retrieval.test.d.ts +1 -0
- package/lib/types/test/rotation.test.d.ts +1 -0
- package/lib/types/test/schedule.test.d.ts +1 -0
- package/lib/types/test/settings-card.test.d.ts +1 -0
- package/lib/types/test/skills.test.d.ts +1 -0
- package/lib/types/test/state.test.d.ts +1 -0
- package/lib/types/test/subagent-contract.test.d.ts +1 -0
- package/lib/types/test/sweep.test.d.ts +1 -0
- package/lib/types/test/sync.test.d.ts +1 -0
- package/lib/types/test/time.test.d.ts +1 -0
- package/lib/types/time.d.ts +67 -0
- package/lib/types/tool.d.ts +9 -0
- package/lib/types/types.d.ts +374 -0
- package/lib/types/workspace.d.ts +20 -0
- package/lib/types.js +47 -0
- package/lib/workspace.js +65 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +126 -4
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for on-demand recall and the per-session memory switch.
|
|
3
|
+
*
|
|
4
|
+
* The once-per-conversation summary is cheap but static; a recall delta is what
|
|
5
|
+
* answers a memory that only becomes relevant ten turns in. These tests pin the
|
|
6
|
+
* three bounds that keep it from becoming a second, unbounded injection path —
|
|
7
|
+
* a score threshold, a per-conversation cap, and never repeating an entry — and
|
|
8
|
+
* the switch that turns the whole thing off for one session.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/test/recall.test
|
|
11
|
+
*/
|
|
12
|
+
import assert from 'node:assert/strict';
|
|
13
|
+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import test from 'node:test';
|
|
17
|
+
import { MemoriesRuntime } from '../index.js';
|
|
18
|
+
import { renderRecall } from '../render.js';
|
|
19
|
+
import { hubTerms, matchCredit } from '../search.js';
|
|
20
|
+
import { Logger } from '@deepseek-ai/cordis';
|
|
21
|
+
import { MEMORY_SOURCE_KIND } from '../types.js';
|
|
22
|
+
/** A context stand-in exposing only what the runtime touches. */
|
|
23
|
+
const stubContext = {
|
|
24
|
+
get: () => undefined,
|
|
25
|
+
logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* A session stand-in whose surface carries at most one user message.
|
|
29
|
+
*
|
|
30
|
+
* The id is unique per call: state (usage counters, memory mode) is keyed by
|
|
31
|
+
* session id on disk, and node:test runs tests in the same file concurrently, so
|
|
32
|
+
* a shared id would let one test's writes change another's recall ranking.
|
|
33
|
+
*/
|
|
34
|
+
let sessionCounter = 0;
|
|
35
|
+
function stubSession(cwd, userText = '', id = `test-session-${++sessionCounter}`) {
|
|
36
|
+
return {
|
|
37
|
+
id,
|
|
38
|
+
header: { version: 0, id, createdAt: 0, cwd, isSeeded: false },
|
|
39
|
+
seq: 1,
|
|
40
|
+
requestHeader: () => undefined,
|
|
41
|
+
deriveMessages: () => userText.length === 0
|
|
42
|
+
? []
|
|
43
|
+
: [{ role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: userText }] }],
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** An agent stand-in. */
|
|
47
|
+
function stubAgent(session) {
|
|
48
|
+
return { id: session.id, session, status: 'idle' };
|
|
49
|
+
}
|
|
50
|
+
/** A runtime over a temp store. */
|
|
51
|
+
async function fixture(t, settings = {}) {
|
|
52
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-recall-'));
|
|
53
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false, ...settings });
|
|
54
|
+
t.after(() => {
|
|
55
|
+
runtime.dispose();
|
|
56
|
+
return rm(dir, { recursive: true, force: true });
|
|
57
|
+
});
|
|
58
|
+
return { dir, runtime };
|
|
59
|
+
}
|
|
60
|
+
/** The text of one message's content blocks. */
|
|
61
|
+
function textOf(message) {
|
|
62
|
+
return JSON.stringify(message?.content ?? '');
|
|
63
|
+
}
|
|
64
|
+
/** The raw text of the single memory block in one message. */
|
|
65
|
+
function blockText(message) {
|
|
66
|
+
const blocks = (message?.content ?? []);
|
|
67
|
+
return blocks.filter((block) => block.type === 'text').map((block) => block.text ?? '').join('');
|
|
68
|
+
}
|
|
69
|
+
/** A runtime over a temp store, with every log line captured. */
|
|
70
|
+
async function loggedFixture(t, settings = {}) {
|
|
71
|
+
const lines = [];
|
|
72
|
+
// Rendered through the host's OWN formatter, not a hand-rolled stand-in: the
|
|
73
|
+
// point is to see the line the plugin's log file would actually contain, and a
|
|
74
|
+
// stub that skipped formatting would have hidden the very bug this covers.
|
|
75
|
+
const context = {
|
|
76
|
+
get: () => undefined,
|
|
77
|
+
logger: {
|
|
78
|
+
info: (...args) => void lines.push(render('info', args)),
|
|
79
|
+
warn: (...args) => void lines.push(render('warn', args)),
|
|
80
|
+
debug: (...args) => void lines.push(render('debug', args)),
|
|
81
|
+
error: (...args) => void lines.push(render('error', args)),
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
function render(type, args) {
|
|
85
|
+
return Logger.format({}, { ts: Date.now(), type, name: 'dsh-cross-memory', args });
|
|
86
|
+
}
|
|
87
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-recall-'));
|
|
88
|
+
const runtime = new MemoriesRuntime(context, { memoriesDir: dir, autoExtract: false, ...settings });
|
|
89
|
+
t.after(() => {
|
|
90
|
+
runtime.dispose();
|
|
91
|
+
return rm(dir, { recursive: true, force: true });
|
|
92
|
+
});
|
|
93
|
+
return { runtime, lines };
|
|
94
|
+
}
|
|
95
|
+
test('a recall that fires, and a near miss that is refused, both reach the log', async (t) => {
|
|
96
|
+
// A stock `logLevel` keeps `info` and drops `debug`, and this plugin has
|
|
97
|
+
// already paid for a 32-hour background stall that was invisible for exactly
|
|
98
|
+
// that reason. A delta fires at most `recallMaxPerConversation` times, so it
|
|
99
|
+
// is never worth suppressing.
|
|
100
|
+
const { runtime, lines } = await loggedFixture(t);
|
|
101
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
102
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm, not npm.', tags: [] }, 'tool');
|
|
103
|
+
await runtime.recallFor(stubAgent(session));
|
|
104
|
+
assert.ok(lines.some((line) => line.includes('recalled')), `a fired delta is logged at info, got: ${lines.join(' | ')}`);
|
|
105
|
+
// The refusal that hides a mis-tuned gate: the memory CLEARS the relevance
|
|
106
|
+
// floor and is still turned away by the evidence gate. Reported once per
|
|
107
|
+
// conversation so it cannot become noise on a long session.
|
|
108
|
+
const { runtime: other, lines: otherLines } = await loggedFixture(t);
|
|
109
|
+
const gated = stubSession(process.cwd(), '该插件是否有日志');
|
|
110
|
+
// Tagged with the shared word, so the turn really does clear the relevance
|
|
111
|
+
// floor: that is what makes the refusal the evidence gate's doing, and what
|
|
112
|
+
// makes it worth a line in the log.
|
|
113
|
+
await other.write(gated, { scope: 'global', title: '插件注册顺序', body: '插件在启动时注册。'.repeat(6), tags: ['插件'] }, 'tool');
|
|
114
|
+
await other.recallFor(stubAgent(gated));
|
|
115
|
+
const nearMisses = () => otherLines.filter((line) => line.includes('near miss worth reading')).length;
|
|
116
|
+
assert.equal(nearMisses(), 1, 'the refused-but-close case is reported');
|
|
117
|
+
await other.recallFor(stubAgent(gated));
|
|
118
|
+
assert.equal(nearMisses(), 1, 'and only once per conversation');
|
|
119
|
+
// The host's formatter is cordis `Logger.format`, which matches only a single
|
|
120
|
+
// letter after `%` and only knows `s d i f o O c C`. So `%.1f` is not even a
|
|
121
|
+
// placeholder, and `%j` has no formatter and is emitted verbatim with its
|
|
122
|
+
// argument appended unformatted. These lines exist to be read after the fact;
|
|
123
|
+
// the `recalled` one had been unreadable in the field the whole time.
|
|
124
|
+
for (const line of [...lines, ...otherLines]) {
|
|
125
|
+
assert.doesNotMatch(line, /%[.a-zA-Z]|\$\{/u, `a log line must render its values, not its placeholders: ${line}`);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
test('an on-demand delta surfaces the memory the current turn matches', async (t) => {
|
|
129
|
+
const { runtime } = await fixture(t);
|
|
130
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
131
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm, not npm.', tags: [] }, 'tool');
|
|
132
|
+
const delta = await runtime.recallFor(stubAgent(session));
|
|
133
|
+
assert.ok(delta !== undefined, 'a strong match injects');
|
|
134
|
+
assert.match(textOf(delta), /<memory-recall>/u);
|
|
135
|
+
assert.match(textOf(delta), /Prefer pnpm/u);
|
|
136
|
+
assert.equal(delta?.source.kind, MEMORY_SOURCE_KIND);
|
|
137
|
+
});
|
|
138
|
+
test('a delta is injected once per entry and capped per conversation', async (t) => {
|
|
139
|
+
const { runtime } = await fixture(t);
|
|
140
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
141
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
142
|
+
const agent = stubAgent(session);
|
|
143
|
+
assert.ok(await runtime.recallFor(agent) !== undefined);
|
|
144
|
+
assert.equal(await runtime.recallFor(agent), undefined, 'the same entry is never repeated');
|
|
145
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm hoisting', body: 'Hoist pnpm deps.', tags: [] }, 'tool');
|
|
146
|
+
assert.ok(await runtime.recallFor(agent) !== undefined, 'a second unseen entry still fits');
|
|
147
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm store', body: 'Share the pnpm store.', tags: [] }, 'tool');
|
|
148
|
+
assert.ok(await runtime.recallFor(agent) !== undefined, 'up to three');
|
|
149
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm audit', body: 'Audit pnpm deps.', tags: [] }, 'tool');
|
|
150
|
+
assert.ok(await runtime.recallFor(agent) !== undefined, 'the fourth memory still fits the default cap');
|
|
151
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm dedupe', body: 'Dedupe pnpm deps.', tags: [] }, 'tool');
|
|
152
|
+
assert.equal(await runtime.recallFor(agent), undefined, 'the cap stops further deltas');
|
|
153
|
+
});
|
|
154
|
+
test('one delta carries every memory the same turn matches, best first', async (t) => {
|
|
155
|
+
const { runtime } = await fixture(t);
|
|
156
|
+
const session = stubSession(process.cwd(), 'pnpm workspace hoisting');
|
|
157
|
+
// Both entries clear the evidence gate (each shares two of the turn's words
|
|
158
|
+
// with its title), and they clear it by different margins: the first carries
|
|
159
|
+
// the turn's words in its title AND body, the second only in its title. So the
|
|
160
|
+
// order is decided by relevance, not by which entry was written last.
|
|
161
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm workspace', body: 'One pnpm workspace, hoisted for speed.', tags: [] }, 'tool');
|
|
162
|
+
await runtime.write(session, { scope: 'global', title: 'pnpm hoisting', body: 'A short note.', tags: [] }, 'tool');
|
|
163
|
+
const delta = await runtime.recallFor(stubAgent(session));
|
|
164
|
+
assert.ok(delta !== undefined);
|
|
165
|
+
const text = textOf(delta);
|
|
166
|
+
assert.match(text, /pnpm workspace/u, 'the stronger match is listed');
|
|
167
|
+
assert.match(text, /pnpm hoisting/u, 'and so is the second one the turn matched');
|
|
168
|
+
assert.ok(text.indexOf('pnpm workspace') < text.indexOf('pnpm hoisting'), 'ranked by relevance, best first');
|
|
169
|
+
// One block, not two: the whole point of a delta is that it costs one message.
|
|
170
|
+
assert.equal((text.match(/<memory-recall>/gu) ?? []).length, 1);
|
|
171
|
+
});
|
|
172
|
+
test('the delta byte budget bounds one block instead of dropping it', async (t) => {
|
|
173
|
+
const { runtime } = await fixture(t, { recallMaxBytes: 500 });
|
|
174
|
+
const session = stubSession(process.cwd(), 'pnpm note number seven');
|
|
175
|
+
for (let index = 0; index < 8; index += 1) {
|
|
176
|
+
// Each entry shares two of the turn's words (pnpm, note) with its TITLE, so
|
|
177
|
+
// all eight clear the evidence gate and the byte budget is the only thing
|
|
178
|
+
// limiting how many can be listed.
|
|
179
|
+
await runtime.write(session, {
|
|
180
|
+
scope: 'global',
|
|
181
|
+
title: `pnpm note number ${index}`,
|
|
182
|
+
body: `A note about pnpm, padded out so that a preview takes up real room.`,
|
|
183
|
+
tags: [],
|
|
184
|
+
}, 'tool');
|
|
185
|
+
}
|
|
186
|
+
const delta = await runtime.recallFor(stubAgent(session));
|
|
187
|
+
assert.ok(delta !== undefined, 'a budget too small for everything still yields a block');
|
|
188
|
+
const text = blockText(delta);
|
|
189
|
+
assert.ok(Buffer.byteLength(text, 'utf8') <= 500, 'the block respects its budget');
|
|
190
|
+
assert.match(text, /<memory-recall>/u);
|
|
191
|
+
assert.match(text, /<\/memory-recall>/u, 'the closing frame survives the budget, or dedupe breaks');
|
|
192
|
+
const listed = (text.match(/^- \[/gmu) ?? []).length;
|
|
193
|
+
assert.ok(listed >= 1, 'at least one memory is listed');
|
|
194
|
+
assert.ok(listed < 8, 'and the budget stopped it short of the whole store');
|
|
195
|
+
});
|
|
196
|
+
test('a bare acknowledgement does not trigger a store scan', async (t) => {
|
|
197
|
+
const { runtime } = await fixture(t, { recallMinQueryChars: 2 });
|
|
198
|
+
const session = stubSession(process.cwd(), '好');
|
|
199
|
+
await runtime.write(session, { scope: 'global', title: '好习惯', body: '每天提交。', tags: [] }, 'tool');
|
|
200
|
+
assert.equal(await runtime.recallFor(stubAgent(session)), undefined, 'a one-character turn is skipped');
|
|
201
|
+
});
|
|
202
|
+
test('a Chinese turn reaches a memory it shares a phrase with', async (t) => {
|
|
203
|
+
const { runtime } = await fixture(t);
|
|
204
|
+
// The question and the title genuinely share the three consecutive characters
|
|
205
|
+
// 件的日, while the title's own wording differs around them.
|
|
206
|
+
const session = stubSession(process.cwd(), '这个插件的日志在哪里?');
|
|
207
|
+
await runtime.write(session, {
|
|
208
|
+
scope: 'global',
|
|
209
|
+
title: '件的日志该去哪里看',
|
|
210
|
+
body: '日志写在 dsh-cross-memory.log 里。',
|
|
211
|
+
tags: [],
|
|
212
|
+
}, 'tool');
|
|
213
|
+
const delta = await runtime.recallFor(stubAgent(session));
|
|
214
|
+
assert.ok(delta !== undefined, 'a Chinese turn with no spaces still recalls');
|
|
215
|
+
assert.match(textOf(delta), /件的日志该去哪里看/u);
|
|
216
|
+
});
|
|
217
|
+
test('a Chinese turn reaches a memory it names in two non-adjacent pairs', async (t) => {
|
|
218
|
+
const { runtime } = await fixture(t);
|
|
219
|
+
// The turn and the title are unmistakably about the same thing and share NO
|
|
220
|
+
// three-character run: the pairs 改动 and 提交 sit in different places in each.
|
|
221
|
+
// Requiring a shared phrase meant this never surfaced — measured on the real
|
|
222
|
+
// store, six ordinary mid-conversation turns recalled nothing for exactly this
|
|
223
|
+
// reason, with the right memory sitting one shared pair away.
|
|
224
|
+
const session = stubSession(process.cwd(), '帮我把这次改动提交一下');
|
|
225
|
+
await runtime.write(session, {
|
|
226
|
+
scope: 'global',
|
|
227
|
+
title: '把混装的工作区改动拆成两笔提交',
|
|
228
|
+
body: '同一文件里混装了两批无关改动时,按 hunk 重建文件,把每批改动拆成独立的提交,分阶段跑测试。',
|
|
229
|
+
tags: [],
|
|
230
|
+
}, 'tool');
|
|
231
|
+
const delta = await runtime.recallFor(stubAgent(session));
|
|
232
|
+
assert.ok(delta !== undefined, 'two shared topic pairs are enough, adjacent or not');
|
|
233
|
+
assert.match(textOf(delta), /把混装的工作区改动拆成两笔提交/u);
|
|
234
|
+
});
|
|
235
|
+
test('a Chinese turn that only shares common pairs recalls nothing', async (t) => {
|
|
236
|
+
const { runtime } = await fixture(t);
|
|
237
|
+
const session = stubSession(process.cwd(), '该插件是否有日志');
|
|
238
|
+
// Shares the isolated pair 插件 with the question and nothing longer. It also
|
|
239
|
+
// scores 12, above any floor low enough to admit a paraphrase, so a score
|
|
240
|
+
// threshold cannot be the thing that keeps this out — the evidence gate is.
|
|
241
|
+
await runtime.write(session, {
|
|
242
|
+
scope: 'global',
|
|
243
|
+
title: '插件注册顺序',
|
|
244
|
+
body: '插件在启动时注册,日志级别由配置决定。',
|
|
245
|
+
tags: [],
|
|
246
|
+
}, 'tool');
|
|
247
|
+
assert.equal(await runtime.recallFor(stubAgent(session)), undefined, 'the same characters are not the same phrase');
|
|
248
|
+
// One pair is one term, and recall needs two. The body also says 日志, but a
|
|
249
|
+
// body word is not evidence: a long memory mentions many things.
|
|
250
|
+
const counted = matchCredit((await runtime.search(session, '该插件是否有日志', { limit: 1 }))[0].entry, '该插件是否有日志', 9, 2);
|
|
251
|
+
assert.equal(counted.evidence.strongTerms, 1, 'exactly one pair is credited, and it is not enough');
|
|
252
|
+
});
|
|
253
|
+
test('appliesTo is what makes a memory reachable when the title shares no noun', async (t) => {
|
|
254
|
+
const { runtime } = await fixture(t);
|
|
255
|
+
const session = stubSession(process.cwd(), '准备推送代码');
|
|
256
|
+
await runtime.write(session, {
|
|
257
|
+
scope: 'global',
|
|
258
|
+
title: '提交后主动推送',
|
|
259
|
+
body: '本项目的约定是提交后主动推送,不要留在本地。',
|
|
260
|
+
tags: [],
|
|
261
|
+
appliesTo: '准备推送代码之前',
|
|
262
|
+
}, 'tool');
|
|
263
|
+
assert.ok(await runtime.recallFor(stubAgent(session)) !== undefined, 'the appliesTo phrase is exactly the signal for a turn like this');
|
|
264
|
+
});
|
|
265
|
+
test('a weak match and an unrelated turn inject nothing', async (t) => {
|
|
266
|
+
const { runtime } = await fixture(t);
|
|
267
|
+
const session = stubSession(process.cwd(), 'what is the weather tomorrow');
|
|
268
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
269
|
+
assert.equal(await runtime.recallFor(stubAgent(session)), undefined);
|
|
270
|
+
});
|
|
271
|
+
test('the score threshold gates the delta', async (t) => {
|
|
272
|
+
const { runtime } = await fixture(t, { recallMinScore: 1_000 });
|
|
273
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
274
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
275
|
+
assert.equal(await runtime.recallFor(stubAgent(session)), undefined);
|
|
276
|
+
});
|
|
277
|
+
test('recallMode once keeps the single summary, and off keeps nothing', async (t) => {
|
|
278
|
+
const once = await fixture(t, { recallMode: 'once' });
|
|
279
|
+
const onceSession = stubSession(process.cwd(), 'pnpm');
|
|
280
|
+
await once.runtime.write(onceSession, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
281
|
+
assert.ok(await once.runtime.injectionFor(stubAgent(onceSession)) !== undefined, 'the summary still injects');
|
|
282
|
+
assert.equal(await once.runtime.recallFor(stubAgent(onceSession)), undefined, 'no delta in once mode');
|
|
283
|
+
const off = await fixture(t, { recallMode: 'off' });
|
|
284
|
+
const offSession = stubSession(process.cwd(), 'pnpm');
|
|
285
|
+
await off.runtime.write(offSession, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
286
|
+
assert.equal(await off.runtime.injectionFor(stubAgent(offSession)), undefined, 'off disables the summary');
|
|
287
|
+
assert.equal(await off.runtime.recallFor(stubAgent(offSession)), undefined, 'and the delta');
|
|
288
|
+
});
|
|
289
|
+
test('a delta does not suppress the summary, and the summary suppresses a repeat', async (t) => {
|
|
290
|
+
const { runtime } = await fixture(t);
|
|
291
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
292
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
293
|
+
const agent = stubAgent(session);
|
|
294
|
+
assert.ok(await runtime.recallFor(agent) !== undefined);
|
|
295
|
+
// The delta carries the same `form`, but not the summary's frame, so the
|
|
296
|
+
// conversation is still owed its once-per-conversation block.
|
|
297
|
+
assert.ok(await runtime.injectionFor(agent) !== undefined, 'the summary still arrives');
|
|
298
|
+
const other = stubSession(process.cwd(), 'pnpm', 'second-session');
|
|
299
|
+
const secondAgent = stubAgent(other);
|
|
300
|
+
await runtime.write(other, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
301
|
+
assert.ok(await runtime.injectionFor(secondAgent) !== undefined);
|
|
302
|
+
assert.equal(await runtime.recallFor(secondAgent), undefined, 'the summary already listed the only entry');
|
|
303
|
+
});
|
|
304
|
+
test('the per-session switch suspends injection and deltas until it is turned back on', async (t) => {
|
|
305
|
+
const { runtime } = await fixture(t);
|
|
306
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
307
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
308
|
+
assert.match(runtime.setSessionMode(session, ''), /Memory is on/u);
|
|
309
|
+
assert.match(runtime.setSessionMode(session, 'sideways'), /Usage: \/memories mode/u);
|
|
310
|
+
assert.match(runtime.setSessionMode(session, 'off'), /off for this session/u);
|
|
311
|
+
assert.equal(runtime.sessionMode(session), 'off');
|
|
312
|
+
assert.equal(await runtime.injectionFor(stubAgent(session)), undefined);
|
|
313
|
+
assert.equal(await runtime.recallFor(stubAgent(session)), undefined);
|
|
314
|
+
runtime.setSessionMode(session, 'on');
|
|
315
|
+
assert.equal(runtime.sessionMode(session), 'on');
|
|
316
|
+
assert.ok(await runtime.injectionFor(stubAgent(session)) !== undefined, 'turning it back on re-arms the summary');
|
|
317
|
+
});
|
|
318
|
+
test('resetInjection re-arms both the summary and the delta budget', async (t) => {
|
|
319
|
+
const { runtime } = await fixture(t);
|
|
320
|
+
const session = stubSession(process.cwd(), 'pnpm');
|
|
321
|
+
await runtime.write(session, { scope: 'global', title: 'Prefer pnpm', body: 'Use pnpm.', tags: [] }, 'tool');
|
|
322
|
+
const agent = stubAgent(session);
|
|
323
|
+
assert.ok(await runtime.recallFor(agent) !== undefined);
|
|
324
|
+
assert.equal(await runtime.recallFor(agent), undefined);
|
|
325
|
+
runtime.resetInjection(session);
|
|
326
|
+
assert.ok(await runtime.recallFor(agent) !== undefined, 'a cleared conversation may see the memory again');
|
|
327
|
+
});
|
|
328
|
+
test('a hub term does not count as one of the two pieces of evidence', () => {
|
|
329
|
+
// Two entries share the hub word `dsh`; only one is about the logger.
|
|
330
|
+
const make = (id, title, tags) => ({
|
|
331
|
+
id, scope: 'global', kind: 'fact', title, body: 'body text', tags, keys: [],
|
|
332
|
+
createdAt: 0, updatedAt: 0, uses: 0, lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto',
|
|
333
|
+
});
|
|
334
|
+
const store = [
|
|
335
|
+
make('logger', 'dsh plugin logger threshold', ['dsh', 'plugin']),
|
|
336
|
+
make('other', 'dsh install path', ['dsh']),
|
|
337
|
+
make('unrelated', 'surge proxy helpers', ['surge']),
|
|
338
|
+
];
|
|
339
|
+
const hub = hubTerms(store, 0.5); // 2 of 3 entries carry `dsh`
|
|
340
|
+
assert.equal(hub('dsh'), true, 'a word in two thirds of the store is a hub');
|
|
341
|
+
assert.equal(hub('plugin'), false);
|
|
342
|
+
const entry = store[0];
|
|
343
|
+
const query = 'dsh plugin';
|
|
344
|
+
// `singleTerm: false` is how the summary's topical tier calls this; the recall
|
|
345
|
+
// path leaves the one-strong-term escape hatch on, which would admit the entry
|
|
346
|
+
// on relevance alone and hide what the discount did to the evidence count.
|
|
347
|
+
const without = matchCredit(entry, query, 9, 2, { singleTerm: false });
|
|
348
|
+
const withHub = matchCredit(entry, query, 9, 2, { singleTerm: false, hub });
|
|
349
|
+
assert.equal(without.about, true, 'two terms with no discount');
|
|
350
|
+
assert.equal(withHub.about, false, 'the hub word leaves one real term');
|
|
351
|
+
assert.equal(without.evidence.strongTerms, 2);
|
|
352
|
+
assert.equal(withHub.evidence.strongTerms, 1, 'the hub word is not counted');
|
|
353
|
+
assert.equal(withHub.relevance, without.relevance, 'the discount changes evidence, not relevance');
|
|
354
|
+
assert.equal(withHub.score, without.score, 'and not the ranking score either');
|
|
355
|
+
});
|
|
356
|
+
test('a query with two real terms still clears the gate when a hub word is present', () => {
|
|
357
|
+
const make = (id, title, tags) => ({
|
|
358
|
+
id, scope: 'global', kind: 'fact', title, body: 'body text', tags, keys: [],
|
|
359
|
+
createdAt: 0, updatedAt: 0, uses: 0, lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto',
|
|
360
|
+
});
|
|
361
|
+
const store = [
|
|
362
|
+
make('logger', 'dsh plugin logger threshold', ['dsh']),
|
|
363
|
+
make('other', 'dsh install path', ['dsh']),
|
|
364
|
+
make('third', 'dsh random note', ['dsh']),
|
|
365
|
+
];
|
|
366
|
+
const hub = hubTerms(store, 0.5);
|
|
367
|
+
const entry = store[0];
|
|
368
|
+
assert.equal(matchCredit(entry, 'dsh plugin logger', 9, 2, { hub }).about, true);
|
|
369
|
+
});
|
|
370
|
+
test('an archived memory renders with an explicit marker, after any live ones', () => {
|
|
371
|
+
const make = (id, title, body) => ({
|
|
372
|
+
id, scope: 'global', kind: 'fact', title, body, tags: [], keys: [],
|
|
373
|
+
createdAt: 0, updatedAt: 0, uses: 0, lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto',
|
|
374
|
+
});
|
|
375
|
+
const live = make('live', 'Current rule', 'this is what we do now');
|
|
376
|
+
const retired = make('retired', 'Old rule', 'this is what we used to do');
|
|
377
|
+
const mixed = renderRecall([live], 4_000, [retired]);
|
|
378
|
+
assert.ok(mixed !== undefined);
|
|
379
|
+
assert.match(mixed ?? '', /\[archived\] Old rule/u, 'a retired memory says so');
|
|
380
|
+
assert.ok((mixed ?? '').indexOf('Current rule') < (mixed ?? '').indexOf('[archived]'), 'live entries come first');
|
|
381
|
+
const onlyRetired = renderRecall([], 4_000, [retired]);
|
|
382
|
+
assert.ok(onlyRetired !== undefined, 'an archived-only block is still worth emitting');
|
|
383
|
+
assert.match(onlyRetired ?? '', /以前是这么说的/u);
|
|
384
|
+
assert.equal(renderRecall([], 4_000, []), undefined, 'nothing to say renders nothing');
|
|
385
|
+
});
|
|
386
|
+
test('the stronger lexical match is listed first, even when a weaker one is fresher and better read', async (t) => {
|
|
387
|
+
// Ordering a recall block by relevance × importance × decay is not a tie-break:
|
|
388
|
+
// importance spans 1–5 and decay 0.25–1, so a stale, never-read memory that the
|
|
389
|
+
// turn actually names loses its slot to a fresher, well-read memory that merely
|
|
390
|
+
// shares the topic. Measured on 150 hand-written turns against a real 732-entry
|
|
391
|
+
// store (bench/ablate.mjs), the attention-first sort put the turn's own memory
|
|
392
|
+
// first 42% of the time and in the four injected slots 75%; relevance first
|
|
393
|
+
// gives 80% / 91%. This pins the ordering so a later "let recency win" patch has
|
|
394
|
+
// to face the measurement again.
|
|
395
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-order-'));
|
|
396
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
|
|
397
|
+
t.after(() => {
|
|
398
|
+
runtime.dispose();
|
|
399
|
+
return rm(dir, { recursive: true, force: true });
|
|
400
|
+
});
|
|
401
|
+
const days = (count) => new Date(Date.now() - count * 86_400_000).toISOString();
|
|
402
|
+
const entries = join(dir, 'entries');
|
|
403
|
+
await mkdir(entries, { recursive: true });
|
|
404
|
+
const write = (id, title, body, ageDays, uses) => writeFile(join(entries, `${id}.md`), [
|
|
405
|
+
'---',
|
|
406
|
+
`id: ${id}`,
|
|
407
|
+
'scope: global',
|
|
408
|
+
'kind: fact',
|
|
409
|
+
`title: ${title}`,
|
|
410
|
+
'tags: 同步',
|
|
411
|
+
`created: ${days(ageDays)}`,
|
|
412
|
+
`updated: ${days(ageDays)}`,
|
|
413
|
+
'source: auto',
|
|
414
|
+
`uses: ${uses}`,
|
|
415
|
+
'---',
|
|
416
|
+
'',
|
|
417
|
+
body,
|
|
418
|
+
].join('\n'));
|
|
419
|
+
// The entry the turn is about: old and never read.
|
|
420
|
+
await write('sync-conflict-at', '记忆库同步冲突按 at 取新', '两边都改过同一个条目时,按 updated 时间戳取新的那份,旧的作为归档留下。', 200, 0);
|
|
421
|
+
// Shares the topic, nothing more: fresh and read five times, so it wins on both
|
|
422
|
+
// attention factors and loses on the one that means "this is the memory".
|
|
423
|
+
await write('sync-general', '记忆库同步', '同步是后台任务,按间隔运行,不阻塞对话。', 0, 5);
|
|
424
|
+
const session = stubSession(process.cwd(), '记忆库同步冲突怎么合并,两边都改过了');
|
|
425
|
+
const text = blockText(await runtime.recallFor(stubAgent(session)));
|
|
426
|
+
// Body-unique markers, not titles: one title is a prefix of the other, and an
|
|
427
|
+
// indexOf on the shorter one would find the longer entry and pass either way.
|
|
428
|
+
const exact = text.indexOf('两边都改过');
|
|
429
|
+
const weaker = text.indexOf('不阻塞对话');
|
|
430
|
+
assert.ok(exact >= 0, `the turn's own memory must be recalled, got: ${text}`);
|
|
431
|
+
assert.ok(weaker >= 0, `the weaker match is still worth a slot, got: ${text}`);
|
|
432
|
+
assert.ok(exact < weaker, `the memory the turn is about comes first, got: ${text}`);
|
|
433
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the reflection layer.
|
|
3
|
+
*
|
|
4
|
+
* The rule under test is the one that separates a reflection from a plausible
|
|
5
|
+
* paragraph: no evidence, no observation. Also pinned: the pass refuses thin
|
|
6
|
+
* material, and it runs at most weekly.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-cross-memory/test/reflection
|
|
9
|
+
*/
|
|
10
|
+
import assert from 'node:assert/strict';
|
|
11
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import test from 'node:test';
|
|
15
|
+
import { REFLECTION_INTERVAL_MS, REFLECTION_MIN_ENTRIES, listReflections, parseReflection, replyStats, previousInsights, reflectionDue, renderReflectionFile, writeReflection, } from '../reflection.js';
|
|
16
|
+
const NOW = Date.parse('2026-10-24T03:00:00Z');
|
|
17
|
+
const known = new Set(['mem-a', 'mem-b']);
|
|
18
|
+
test('an observation that cannot cite the store is dropped', () => {
|
|
19
|
+
const reply = JSON.stringify({
|
|
20
|
+
insights: [
|
|
21
|
+
{ text: '他总是在同一个项目上先写测试再改实现', evidence: ['mem-a', 'mem-b'] },
|
|
22
|
+
{ text: '他大概喜欢深色主题', evidence: ['made-up'] },
|
|
23
|
+
{ text: '没有依据的泛泛之谈,看起来像结论', evidence: [] },
|
|
24
|
+
{ text: '短', evidence: ['mem-a'] },
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
const insights = parseReflection(reply, known);
|
|
28
|
+
assert.equal(insights.length, 1);
|
|
29
|
+
assert.equal(insights[0]?.text, '他总是在同一个项目上先写测试再改实现');
|
|
30
|
+
assert.deepEqual(insights[0]?.evidence, ['mem-a', 'mem-b']);
|
|
31
|
+
});
|
|
32
|
+
test('a reply that is not JSON yields nothing rather than throwing', () => {
|
|
33
|
+
assert.deepEqual(parseReflection('I think the user is nice.', known), []);
|
|
34
|
+
assert.deepEqual(parseReflection('{"insights": "nope"}', known), []);
|
|
35
|
+
});
|
|
36
|
+
test('the pass refuses thin material and runs at most weekly', () => {
|
|
37
|
+
assert.equal(reflectionDue(0, NOW, REFLECTION_MIN_ENTRIES - 1), false, 'too few memories to synthesize');
|
|
38
|
+
assert.equal(reflectionDue(0, NOW, REFLECTION_MIN_ENTRIES), true, 'never reflected, material present');
|
|
39
|
+
assert.equal(reflectionDue(NOW - 1000, NOW, 80), false, 'once a week, not once an hour');
|
|
40
|
+
assert.equal(reflectionDue(NOW - REFLECTION_INTERVAL_MS, NOW, 80), true);
|
|
41
|
+
});
|
|
42
|
+
test('a reflection round-trips as a dated markdown file with its evidence', async (t) => {
|
|
43
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-reflection-'));
|
|
44
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
45
|
+
const insights = [{ text: '他会为一个错误重启三次,然后要求把验证做成探针', evidence: ['mem-a'] }];
|
|
46
|
+
const rendered = renderReflectionFile(insights, NOW);
|
|
47
|
+
assert.match(rendered, /^---\ncreated:/u);
|
|
48
|
+
assert.match(rendered, /依据:mem-a/u, 'the file carries the ids, not just the claim');
|
|
49
|
+
const path = await writeReflection(dir, insights, NOW);
|
|
50
|
+
assert.match(path, /2026-10-24\.md$/u);
|
|
51
|
+
const files = await listReflections(dir);
|
|
52
|
+
assert.equal(files.length, 1);
|
|
53
|
+
assert.deepEqual(previousInsights(files), ['他会为一个错误重启三次,然后要求把验证做成探针']);
|
|
54
|
+
});
|
|
55
|
+
test('a zero result reports whether the reply was empty or merely uncited', () => {
|
|
56
|
+
const reply = JSON.stringify({ insights: [
|
|
57
|
+
{ text: '有依据的观察', evidence: ['mem-a'] },
|
|
58
|
+
{ text: '没有依据的观察', evidence: ['made-up'] },
|
|
59
|
+
{ text: '也提了依据', evidence: ['mem-b'] },
|
|
60
|
+
] });
|
|
61
|
+
assert.deepEqual(replyStats(reply, known), { raw: 3, cited: 2 });
|
|
62
|
+
assert.equal(replyStats('not json', known), undefined);
|
|
63
|
+
assert.deepEqual(replyStats('{"insights":"nope"}', known), { raw: 0, cited: 0 });
|
|
64
|
+
});
|