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,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression guard for the 待裁决 (disputes) panel and the Remote seam under it.
|
|
3
|
+
*
|
|
4
|
+
* Two bugs shipped in this panel, and neither is visible in a diff: the accept
|
|
5
|
+
* button was wired to `props.onResolve`, a prop the settings section never
|
|
6
|
+
* receives, so clicking it silently did nothing; and both buttons called the
|
|
7
|
+
* Remote method positionally (`resolveDispute(row.id, decision)`) while the
|
|
8
|
+
* browser wrapper maps ONE object's fields onto the gateway's positional
|
|
9
|
+
* arguments, so the host answered `args fields do not match the descriptor`.
|
|
10
|
+
*
|
|
11
|
+
* The panel is hand-written `createElement` code with no DOM dependency, so it
|
|
12
|
+
* is rendered here against a tiny hook runtime and its buttons are really
|
|
13
|
+
* clicked; the wrapper is then exercised against a fake namespace to prove a
|
|
14
|
+
* positional call now fails loudly instead of turning into a dead button.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-cross-memory/test/disputes-panel.test
|
|
17
|
+
*/
|
|
18
|
+
import assert from 'node:assert/strict';
|
|
19
|
+
import { readFile } from 'node:fs/promises';
|
|
20
|
+
import test from 'node:test';
|
|
21
|
+
import { REMOTE_INVOCATION_DATA } from '../remote.js';
|
|
22
|
+
/** Every waiting decision the fake host reports. */
|
|
23
|
+
const DISPUTES = [{
|
|
24
|
+
id: 'entry-1',
|
|
25
|
+
scope: 'global',
|
|
26
|
+
action: 'rewrite',
|
|
27
|
+
title: 'A memory that needs a person',
|
|
28
|
+
reason: 'the rewrite is shorter',
|
|
29
|
+
before: 'what it says today',
|
|
30
|
+
after: 'what the pass wants instead',
|
|
31
|
+
}];
|
|
32
|
+
/** The browser half, resolved from the compiled test's own location. */
|
|
33
|
+
const SECTION = new URL('../../client/parts/section.js', import.meta.url);
|
|
34
|
+
const REMOTE = new URL('../../client/parts/remote.js', import.meta.url);
|
|
35
|
+
/** Load the section factory the bundle concatenates. */
|
|
36
|
+
async function loadSection() {
|
|
37
|
+
const source = await readFile(SECTION, 'utf8');
|
|
38
|
+
return new Function(`${source}\nreturn { createMemoriesSection, SECTION_COPY, diffTokens, splitDisputeReason }`)();
|
|
39
|
+
}
|
|
40
|
+
/** Every element in a rendered tree, depth first. */
|
|
41
|
+
function* walk(node) {
|
|
42
|
+
if (Array.isArray(node)) {
|
|
43
|
+
for (const child of node)
|
|
44
|
+
yield* walk(child);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (node === null || typeof node !== 'object')
|
|
48
|
+
return;
|
|
49
|
+
const element = node;
|
|
50
|
+
if (element.props !== undefined && (typeof element.type === 'string' || typeof element.type === 'function'))
|
|
51
|
+
yield element;
|
|
52
|
+
if (element.props?.children !== undefined)
|
|
53
|
+
yield* walk(element.props.children);
|
|
54
|
+
}
|
|
55
|
+
/** The text a rendered subtree would show. */
|
|
56
|
+
function textOf(node) {
|
|
57
|
+
if (typeof node === 'string' || typeof node === 'number')
|
|
58
|
+
return String(node);
|
|
59
|
+
if (Array.isArray(node))
|
|
60
|
+
return node.map(textOf).join('');
|
|
61
|
+
if (node === null || typeof node !== 'object')
|
|
62
|
+
return '';
|
|
63
|
+
return textOf(node.props.children);
|
|
64
|
+
}
|
|
65
|
+
/** The first element with this tag whose text contains `text`. */
|
|
66
|
+
function findByText(tree, tag, text) {
|
|
67
|
+
for (const element of walk(tree)) {
|
|
68
|
+
if (element.type === tag && textOf(element).includes(text))
|
|
69
|
+
return element;
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`no <${tag}> showing ${JSON.stringify(text)}`);
|
|
72
|
+
}
|
|
73
|
+
/** The first element carrying this class, or undefined. */
|
|
74
|
+
function findClass(tree, name) {
|
|
75
|
+
for (const element of walk(tree)) {
|
|
76
|
+
const className = element.props.className;
|
|
77
|
+
if (typeof className === 'string' && className.split(' ').includes(name))
|
|
78
|
+
return element;
|
|
79
|
+
}
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
/** Click one element's `onClick`. */
|
|
83
|
+
function click(element) {
|
|
84
|
+
const handler = element.props.onClick;
|
|
85
|
+
assert.equal(typeof handler, 'function', 'the button must carry a click handler');
|
|
86
|
+
handler();
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Render the section against a stand-in hook runtime.
|
|
90
|
+
*
|
|
91
|
+
* `render` re-renders until the effects it just ran have settled, which is what
|
|
92
|
+
* lets the panel's own data loading — including the disputes fetch — complete
|
|
93
|
+
* before anything is clicked.
|
|
94
|
+
*/
|
|
95
|
+
async function mountSection(api, copy) {
|
|
96
|
+
const state = [];
|
|
97
|
+
const callbacks = [];
|
|
98
|
+
const effectSlots = [];
|
|
99
|
+
let cursor = 0;
|
|
100
|
+
let callbackCursor = 0;
|
|
101
|
+
let effectCursor = 0;
|
|
102
|
+
let dirty = false;
|
|
103
|
+
let pending = [];
|
|
104
|
+
const react = {
|
|
105
|
+
createElement: (type, props, ...children) => ({
|
|
106
|
+
type,
|
|
107
|
+
props: { ...(props ?? {}), children: children.length <= 1 ? children[0] : children },
|
|
108
|
+
}),
|
|
109
|
+
useState: (initial) => {
|
|
110
|
+
const index = cursor++;
|
|
111
|
+
if (!(index in state))
|
|
112
|
+
state[index] = typeof initial === 'function' ? initial() : initial;
|
|
113
|
+
const set = (next) => {
|
|
114
|
+
state[index] = typeof next === 'function' ? next(state[index]) : next;
|
|
115
|
+
dirty = true;
|
|
116
|
+
};
|
|
117
|
+
return [state[index], set];
|
|
118
|
+
},
|
|
119
|
+
// Memoized like React's: a fresh function identity every render would make
|
|
120
|
+
// the panel's `[loadDisputes]` effects re-run forever.
|
|
121
|
+
useCallback: (callback) => {
|
|
122
|
+
const index = callbackCursor++;
|
|
123
|
+
callbacks[index] ??= callback;
|
|
124
|
+
return callbacks[index];
|
|
125
|
+
},
|
|
126
|
+
useEffect: (effect, deps) => {
|
|
127
|
+
const index = effectCursor++;
|
|
128
|
+
const previous = effectSlots[index];
|
|
129
|
+
const changed = deps === undefined || previous === undefined
|
|
130
|
+
|| deps.length !== previous.length || deps.some((value, at) => !Object.is(value, previous[at]));
|
|
131
|
+
if (!changed)
|
|
132
|
+
return;
|
|
133
|
+
effectSlots[index] = deps;
|
|
134
|
+
pending.push(effect);
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
const section = (await loadSection()).createMemoriesSection(react, () => null);
|
|
138
|
+
const props = { api, copy, scope: undefined, useSnapshot: () => undefined };
|
|
139
|
+
const render = async () => {
|
|
140
|
+
let tree = null;
|
|
141
|
+
for (let pass = 0; pass < 25; pass += 1) {
|
|
142
|
+
cursor = 0;
|
|
143
|
+
callbackCursor = 0;
|
|
144
|
+
effectCursor = 0;
|
|
145
|
+
pending = [];
|
|
146
|
+
dirty = false;
|
|
147
|
+
tree = section(props);
|
|
148
|
+
if (pending.length === 0)
|
|
149
|
+
break;
|
|
150
|
+
for (const effect of pending)
|
|
151
|
+
effect();
|
|
152
|
+
await new Promise((resolve) => { setTimeout(resolve, 5); });
|
|
153
|
+
if (!dirty)
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
return tree;
|
|
157
|
+
};
|
|
158
|
+
return { render };
|
|
159
|
+
}
|
|
160
|
+
/** A Remote API stub recording what the panel asks the host to do. */
|
|
161
|
+
function fakeApi(calls, rows = DISPUTES) {
|
|
162
|
+
return {
|
|
163
|
+
overview: () => Promise.resolve({ storePath: '/store', globalCount: 0, projects: [], drafts: [], kinds: [] }),
|
|
164
|
+
list: () => Promise.resolve({ entries: [], total: 0 }),
|
|
165
|
+
disputes: () => Promise.resolve({ disputes: rows }),
|
|
166
|
+
resolveDispute: (args) => {
|
|
167
|
+
calls.push(args);
|
|
168
|
+
return Promise.resolve('Applied.');
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
test('the disputes panel accepts and rejects through the Remote API', async () => {
|
|
173
|
+
const calls = [];
|
|
174
|
+
const module = await loadSection();
|
|
175
|
+
const { render } = await mountSection(fakeApi(calls), (module.SECTION_COPY.zh ?? {}));
|
|
176
|
+
const memories = await render();
|
|
177
|
+
click(findByText(memories, 'button', '待裁决'));
|
|
178
|
+
const panel = await render();
|
|
179
|
+
assert.match(textOf(panel), /A memory that needs a person/u, 'the waiting decision is rendered');
|
|
180
|
+
// The section receives no `onResolve` prop at all: this is exactly the state
|
|
181
|
+
// the shipped bug turned into a permanently dead button.
|
|
182
|
+
click(findByText(panel, 'button', '接受'));
|
|
183
|
+
await new Promise((resolve) => { setTimeout(resolve, 20); });
|
|
184
|
+
assert.deepEqual(calls, [{ id: 'entry-1', decision: 'accept' }], 'accept calls the host with the descriptor fields');
|
|
185
|
+
const afterAccept = await render();
|
|
186
|
+
assert.match(textOf(afterAccept), /Applied\./u, 'the outcome is shown to the reader');
|
|
187
|
+
click(findByText(afterAccept, 'button', '保留原样'));
|
|
188
|
+
await new Promise((resolve) => { setTimeout(resolve, 20); });
|
|
189
|
+
assert.deepEqual(calls.at(-1), { id: 'entry-1', decision: 'reject' }, 'reject goes through the same door');
|
|
190
|
+
});
|
|
191
|
+
test('the browser Remote wrapper takes one object per call and says so otherwise', async () => {
|
|
192
|
+
const seen = [];
|
|
193
|
+
const source = await readFile(REMOTE, 'utf8');
|
|
194
|
+
const mount = new Function(`const REMOTE_INVOCATION_DATA = ${JSON.stringify(REMOTE_INVOCATION_DATA)};\n${source}\nreturn mountMemoriesRemote`)();
|
|
195
|
+
const namespace = {};
|
|
196
|
+
for (const invocation of REMOTE_INVOCATION_DATA) {
|
|
197
|
+
namespace[invocation.method] = (...args) => {
|
|
198
|
+
seen.push(args);
|
|
199
|
+
return Promise.resolve({ ok: true, value: 'done' });
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
const ctx = {
|
|
203
|
+
get: (key) => (key === 'remote' ? { $mount: () => Promise.resolve(() => undefined) } : namespace),
|
|
204
|
+
effect: () => undefined,
|
|
205
|
+
};
|
|
206
|
+
const api = await mount(ctx);
|
|
207
|
+
assert.equal(await api.resolveDispute?.({ id: 'entry-1', decision: 'reject' }), 'done');
|
|
208
|
+
assert.deepEqual(seen.at(-1), ['entry-1', 'reject'], 'the object is spread into the descriptor order');
|
|
209
|
+
// The shape the panel used to pass: two positional values reach the gateway as
|
|
210
|
+
// no fields at all, so the mistake must surface here rather than at the host.
|
|
211
|
+
await assert.rejects(async () => api.resolveDispute?.('entry-1', 'accept'), /takes one object keyed by its parameter names/u);
|
|
212
|
+
});
|
|
213
|
+
/** Mount the disputes tab against one fixture and return the rendered panel. */
|
|
214
|
+
async function renderDisputes(rows) {
|
|
215
|
+
const module = await loadSection();
|
|
216
|
+
const { render } = await mountSection(fakeApi([], rows), (module.SECTION_COPY.zh ?? {}));
|
|
217
|
+
click(findByText(await render(), 'button', '待裁决'));
|
|
218
|
+
return render();
|
|
219
|
+
}
|
|
220
|
+
test('the word diff marks exactly the runs that changed', async () => {
|
|
221
|
+
const module = await loadSection();
|
|
222
|
+
// CJK is compared per character, each change run is merged, and latin words
|
|
223
|
+
// and whitespace groups stay whole so a number change is one mark.
|
|
224
|
+
assert.deepEqual(module.diffTokens('缓存里同步一遍', '缓存中同步一遍'), [
|
|
225
|
+
{ kind: 'same', text: '缓存' },
|
|
226
|
+
{ kind: 'del', text: '里' },
|
|
227
|
+
{ kind: 'ins', text: '中' },
|
|
228
|
+
{ kind: 'same', text: '同步一遍' },
|
|
229
|
+
]);
|
|
230
|
+
assert.deepEqual(module.diffTokens('记忆每天跑一次', '记忆每天运行一次'), [
|
|
231
|
+
{ kind: 'same', text: '记忆每天' },
|
|
232
|
+
{ kind: 'del', text: '跑' },
|
|
233
|
+
{ kind: 'ins', text: '运行' },
|
|
234
|
+
{ kind: 'same', text: '一次' },
|
|
235
|
+
]);
|
|
236
|
+
assert.deepEqual(module.diffTokens('uses 18 条', 'uses 20 条'), [
|
|
237
|
+
{ kind: 'same', text: 'uses ' },
|
|
238
|
+
{ kind: 'del', text: '18' },
|
|
239
|
+
{ kind: 'ins', text: '20' },
|
|
240
|
+
{ kind: 'same', text: ' 条' },
|
|
241
|
+
]);
|
|
242
|
+
// Identical bodies produce one unchanged run, never a fabricated change.
|
|
243
|
+
assert.deepEqual(module.diffTokens('完全一样', '完全一样'), [{ kind: 'same', text: '完全一样' }]);
|
|
244
|
+
});
|
|
245
|
+
test('a rewrite reads as one line with the change marked in place', async () => {
|
|
246
|
+
const panel = await renderDisputes([{
|
|
247
|
+
id: 'entry-2',
|
|
248
|
+
scope: 'global',
|
|
249
|
+
action: 'rewrite',
|
|
250
|
+
title: '整理记忆时别把待裁决项塞进摘要',
|
|
251
|
+
reason: '这条是人手写的;新版正文不到原来的一半',
|
|
252
|
+
before: '整理记忆时不要把待裁决项塞进摘要',
|
|
253
|
+
after: '整理记忆时别把待裁决项塞进摘要',
|
|
254
|
+
}]);
|
|
255
|
+
const removed = findClass(panel, 'dshm-del');
|
|
256
|
+
assert.ok(removed !== undefined, 'the removed words are marked');
|
|
257
|
+
assert.equal(removed.type, 'del');
|
|
258
|
+
assert.equal(textOf(removed), '不要');
|
|
259
|
+
const added = findClass(panel, 'dshm-ins');
|
|
260
|
+
assert.ok(added !== undefined, 'the added words are marked');
|
|
261
|
+
assert.equal(added.type, 'ins');
|
|
262
|
+
assert.equal(textOf(added), '别');
|
|
263
|
+
const diff = findClass(panel, 'dshm-diff');
|
|
264
|
+
assert.ok(diff !== undefined, 'the body is one diff block');
|
|
265
|
+
// One reading line: the stored text with each change inline, no caption pair.
|
|
266
|
+
assert.equal(textOf(diff), '整理记忆时不要别把待裁决项塞进摘要');
|
|
267
|
+
assert.doesNotMatch(textOf(panel), /现在是|改成/u, 'the marks replace a caption');
|
|
268
|
+
// Grounds are individual badges, not one grey paragraph.
|
|
269
|
+
const reasons = findClass(panel, 'dshm-reasons');
|
|
270
|
+
assert.ok(reasons !== undefined);
|
|
271
|
+
assert.ok(Array.isArray(reasons.props.children));
|
|
272
|
+
assert.deepEqual(reasons.props.children.map(textOf), ['这条是人手写的', '新版正文不到原来的一半']);
|
|
273
|
+
});
|
|
274
|
+
test('identical text with a scope move shows the comparison instead of two bodies', async () => {
|
|
275
|
+
const body = '记忆库同步每天 18:10 跑一次。';
|
|
276
|
+
const panel = await renderDisputes([{
|
|
277
|
+
id: 'entry-3',
|
|
278
|
+
scope: 'global',
|
|
279
|
+
action: 'rewrite',
|
|
280
|
+
title: '只换作用域',
|
|
281
|
+
reason: '作用域要从 global 改成 project',
|
|
282
|
+
before: body,
|
|
283
|
+
after: body,
|
|
284
|
+
}]);
|
|
285
|
+
assert.equal(findClass(panel, 'dshm-del'), undefined, 'no word was removed');
|
|
286
|
+
assert.equal(findClass(panel, 'dshm-ins'), undefined, 'no word was added');
|
|
287
|
+
const scope = findClass(panel, 'dshm-scope');
|
|
288
|
+
assert.ok(scope !== undefined, 'the move is stated in the head');
|
|
289
|
+
assert.equal(textOf(scope), '全局→项目');
|
|
290
|
+
assert.equal(findClass(panel, 'dshm-reasons'), undefined, 'a scope move is not a ground');
|
|
291
|
+
// The stored text stays readable, exactly once — deciding whether a memory
|
|
292
|
+
// belongs where it is cannot be done without reading it, and a second copy is
|
|
293
|
+
// the noise this view removes.
|
|
294
|
+
const shown = textOf(panel);
|
|
295
|
+
assert.equal(shown.split('记忆库同步每天').length - 1, 1, 'the body is readable once');
|
|
296
|
+
assert.doesNotMatch(shown, /作用域要从/u);
|
|
297
|
+
});
|
|
298
|
+
test('a retirement strikes the body and renders no replacement', async () => {
|
|
299
|
+
const panel = await renderDisputes([{
|
|
300
|
+
id: 'entry-4',
|
|
301
|
+
scope: 'project',
|
|
302
|
+
action: 'retire',
|
|
303
|
+
title: '从没被读过的条目',
|
|
304
|
+
reason: '它被读到过 3 次',
|
|
305
|
+
before: '这条记忆从没被读过,也没人引用它。',
|
|
306
|
+
after: '',
|
|
307
|
+
}]);
|
|
308
|
+
const retired = findClass(panel, 'dshm-retire');
|
|
309
|
+
assert.ok(retired !== undefined, 'the body is marked as retired');
|
|
310
|
+
assert.equal(retired.type, 'p');
|
|
311
|
+
assert.match(textOf(retired), /这条记忆从没被读过/u);
|
|
312
|
+
assert.equal(findClass(panel, 'dshm-ins'), undefined, 'nothing replaces a retirement');
|
|
313
|
+
assert.equal(findClass(panel, 'dshm-del'), undefined);
|
|
314
|
+
});
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retrieval eval: does a query still find its memory?
|
|
3
|
+
*
|
|
4
|
+
* LongMemEval frames long-term memory as indexing → retrieval → reading and
|
|
5
|
+
* finds most of the win in how keys are built, not in how exotic the store is.
|
|
6
|
+
* This corpus is the cheap, offline half of that: fixed memories, fixed
|
|
7
|
+
* queries, a hit-rate floor. It runs in the normal suite, so changing the
|
|
8
|
+
* scoring formula or the extraction prompts has to face it.
|
|
9
|
+
*
|
|
10
|
+
* Keep the corpus honest: entries should read like real memories, and every
|
|
11
|
+
* query should be phrased the way a future session would actually ask.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-cross-memory/test/eval.test
|
|
14
|
+
*/
|
|
15
|
+
import assert from 'node:assert/strict';
|
|
16
|
+
import test from 'node:test';
|
|
17
|
+
import { relevanceOf, searchMemories } from '../search.js';
|
|
18
|
+
/** Build one corpus entry. */
|
|
19
|
+
function entry(id, title, body, tags = [], keys = [], kind = 'fact') {
|
|
20
|
+
return { id, scope: 'global', kind, title, body, tags, keys, createdAt: 0, updatedAt: 0, uses: 0, lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto' };
|
|
21
|
+
}
|
|
22
|
+
/** The fixed corpus every query is ranked against. */
|
|
23
|
+
const CORPUS = [
|
|
24
|
+
entry('prefer-pnpm-workspaces', 'Prefer pnpm workspaces', 'The repository is one pnpm workspace with several packages; do not run npm install.', ['tooling'], ['monorepo']),
|
|
25
|
+
entry('run-the-test-suite', 'Run the test suite', 'Use node --test for the unit suite; the web tests run through vitest.', ['testing']),
|
|
26
|
+
entry('rimworld-mod-defs', 'RimWorld mod defs', 'Defs live under About/Defs and load through PatchOperations.', ['rimworld'], ['环世界']),
|
|
27
|
+
entry('restart-dsh-web', 'Restart dsh web', 'POST /dsh-market/api/v1/restart restarts the web server without a cookie.', ['dsh'], ['dshmarket']),
|
|
28
|
+
entry('plugin-build-order', 'Plugin build order', 'Run tsc before build-client.mjs, or the client bundle drifts from the host.', ['plugin', 'build']),
|
|
29
|
+
entry('answer-in-chinese', 'Answer in Chinese', 'The user writes Chinese, so answer in Chinese by default.', ['preference']),
|
|
30
|
+
entry('windows-path-separators', 'Windows path separators', 'Use native backslash paths in PowerShell commands, not forward slashes.', ['windows']),
|
|
31
|
+
entry('never-commit-credentials', 'Never commit credentials', 'Redact tokens and keys before anything is written to the memory store.', ['security']),
|
|
32
|
+
entry('state-lives-in-sqlite', 'State lives in SQLite', 'Watermarks, job leases, and usage counters live in state.db, not in JSON.', ['dsh', 'sqlite']),
|
|
33
|
+
entry('promote-skill-drafts', 'Promote skill drafts', 'Staged drafts stay inert until /memories promote <name> copies them into the skill root.', ['skills']),
|
|
34
|
+
entry('injection-is-once', 'Injection is once per conversation', 'The summary enters the conversation once; later recall goes through the memory tool.', ['memory']),
|
|
35
|
+
entry('quota-cooldown', 'Quota cooldown pauses background work', 'A rate-limit refusal pauses extraction until the cooldown elapses.', ['memory', 'quota']),
|
|
36
|
+
entry('中文记忆优先', '中文记忆优先', '用户的偏好是中文优先,中文回复优先于英文。', ['chinese'], ['中文优先', '中文']),
|
|
37
|
+
];
|
|
38
|
+
/** One query and the memory it must find. */
|
|
39
|
+
const QUERIES = [
|
|
40
|
+
{ query: 'pnpm', expect: 'prefer-pnpm-workspaces' },
|
|
41
|
+
// Found by a key, not by any word in the title or body — the point of keys.
|
|
42
|
+
{ query: 'monorepo', expect: 'prefer-pnpm-workspaces' },
|
|
43
|
+
{ query: 'node --test', expect: 'run-the-test-suite' },
|
|
44
|
+
{ query: '环世界', expect: 'rimworld-mod-defs' },
|
|
45
|
+
{ query: 'dshmarket', expect: 'restart-dsh-web' },
|
|
46
|
+
{ query: 'build-client', expect: 'plugin-build-order' },
|
|
47
|
+
{ query: 'Chinese', expect: 'answer-in-chinese' },
|
|
48
|
+
{ query: 'backslash', expect: 'windows-path-separators' },
|
|
49
|
+
{ query: 'credentials', expect: 'never-commit-credentials' },
|
|
50
|
+
{ query: 'state.db', expect: 'state-lives-in-sqlite' },
|
|
51
|
+
{ query: 'promote', expect: 'promote-skill-drafts' },
|
|
52
|
+
{ query: 'rate-limit', expect: 'quota-cooldown' },
|
|
53
|
+
{ query: '中文优先', expect: '中文记忆优先' },
|
|
54
|
+
];
|
|
55
|
+
/** The corpus in the shape the search functions take. */
|
|
56
|
+
const GROUPS = [{ scope: 'global', label: 'global', entries: CORPUS }];
|
|
57
|
+
/** Rank the corpus for one query. */
|
|
58
|
+
function rank(query, limit) {
|
|
59
|
+
return searchMemories(GROUPS, query, { limit }).map((hit) => hit.entry.id);
|
|
60
|
+
}
|
|
61
|
+
test('every eval query finds its memory in the top three', () => {
|
|
62
|
+
const misses = [];
|
|
63
|
+
for (const { query, expect } of QUERIES) {
|
|
64
|
+
const ids = rank(query, 3);
|
|
65
|
+
if (!ids.includes(expect))
|
|
66
|
+
misses.push(`${JSON.stringify(query)} expected ${expect}, got [${ids.join(', ')}]`);
|
|
67
|
+
}
|
|
68
|
+
assert.deepEqual(misses, [], 'a query that cannot find its memory is a recall regression');
|
|
69
|
+
});
|
|
70
|
+
test('the corpus keeps its hit@1 rate', () => {
|
|
71
|
+
const top = QUERIES.filter(({ query, expect }) => rank(query, 1)[0] === expect).length;
|
|
72
|
+
const rate = top / QUERIES.length;
|
|
73
|
+
assert.ok(rate >= 0.75, `hit@1 was ${rate.toFixed(2)}; the retrieval ranking regressed`);
|
|
74
|
+
});
|
|
75
|
+
test('a key-only query still clears the recall threshold', () => {
|
|
76
|
+
// The on-demand delta reads the same score, so an alias that ranks well but
|
|
77
|
+
// scores below the threshold would be unreachable in conversation.
|
|
78
|
+
const hit = searchMemories(GROUPS, 'monorepo', { limit: 1 })[0];
|
|
79
|
+
assert.equal(hit?.entry.id, 'prefer-pnpm-workspaces');
|
|
80
|
+
// The corpus entries carry epoch timestamps, so the decayed score sits at its
|
|
81
|
+
// floor; the gate the delta actually applies is the relevance floor.
|
|
82
|
+
assert.ok(hit !== undefined && relevanceOf(hit.entry, 'monorepo') >= 20, 'the key-only match clears the relevance floor');
|
|
83
|
+
});
|
|
84
|
+
// ── The four shapes a word-matching retriever actually fails ───────────────
|
|
85
|
+
//
|
|
86
|
+
// The corpus above is single-hop and mostly positive: every query shares a noun
|
|
87
|
+
// with its memory, so it measures regressions in the scorer and nothing else —
|
|
88
|
+
// a hundred per cent hit rate there says the formula did not break, not that the
|
|
89
|
+
// retrieval is good. These four are the shapes that make a memory architecture
|
|
90
|
+
// necessary, taken from the failure taxonomy Hindsight's paper reports (multi-hop
|
|
91
|
+
// chains, temporal range, entity consolidation, belief revision). Each case gets
|
|
92
|
+
// its own small store so the mechanism under test is the only thing that can
|
|
93
|
+
// carry the answer, and each is asserted on its own line — a generic hit rate
|
|
94
|
+
// would let one shape regress while another covers for it.
|
|
95
|
+
/** Tuesday, 29 September 2026, 19:00 local — fixed so decay and dates are stable. */
|
|
96
|
+
const NOW = new Date(2026, 8, 29, 19, 0, 0).getTime();
|
|
97
|
+
/** A day, for building timestamps relative to {@link NOW}. */
|
|
98
|
+
const DAY = 86_400_000;
|
|
99
|
+
/** One hard-case entry with explicit links and timestamps. */
|
|
100
|
+
function linked(id, title, body, keys, extra = {}) {
|
|
101
|
+
return {
|
|
102
|
+
id,
|
|
103
|
+
scope: 'global',
|
|
104
|
+
kind: 'fact',
|
|
105
|
+
title,
|
|
106
|
+
body,
|
|
107
|
+
tags: [],
|
|
108
|
+
keys,
|
|
109
|
+
createdAt: NOW - 30 * DAY,
|
|
110
|
+
updatedAt: NOW - 30 * DAY,
|
|
111
|
+
uses: 0,
|
|
112
|
+
lastUsedAt: 0,
|
|
113
|
+
lastSurfacedAt: 0,
|
|
114
|
+
source: 'auto',
|
|
115
|
+
...extra,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Rank one hard corpus for one query. */
|
|
119
|
+
function rankHard(entries, query, limit) {
|
|
120
|
+
return searchMemories([{ scope: 'global', label: 'global', entries }], query, { limit, now: NOW, expand: true })
|
|
121
|
+
.map((hit) => hit.entry.id);
|
|
122
|
+
}
|
|
123
|
+
test('multi-hop: an entry linked to a match but sharing none of its words is still reachable', () => {
|
|
124
|
+
// The query names Alice; the answer is the cluster that failed. Nothing in the
|
|
125
|
+
// outage memory shares a word with the question — it is reachable only by
|
|
126
|
+
// following Alice → Project Atlas → Kubernetes, which is what the keys are for.
|
|
127
|
+
const corpus = [
|
|
128
|
+
linked('alice-role', 'Alice 是 Project Atlas 的技术负责人', '她带这个项目两年了。', ['alice', 'project-atlas']),
|
|
129
|
+
linked('atlas-migration', 'Alice 最近在忙 Project Atlas 的迁移', '她这阵子都在弄这件事。', ['project-atlas', 'kubernetes']),
|
|
130
|
+
linked('cluster-outage', 'Kubernetes 集群周二出过故障', '那次故障持续了四十分钟。', ['kubernetes', 'project-atlas']),
|
|
131
|
+
// Padding, so the three linked entries are not 100% of the scope. A link is
|
|
132
|
+
// only an edge when the scope does not mostly carry it, and `project-atlas`
|
|
133
|
+
// on 2 of 3 entries is exactly such a ubiquitous link.
|
|
134
|
+
...Array.from({ length: 9 }, (_, index) => linked(`unrelated-${index}`, `无关条目 ${index}`, '另一件事的正文。', [`unique-${index}`])),
|
|
135
|
+
];
|
|
136
|
+
const ids = rankHard(corpus, 'Alice 最近有没有受影响', 3);
|
|
137
|
+
assert.ok(ids.includes('alice-role') || ids.includes('atlas-migration'), `no direct match at all: ${ids.join(', ')}`);
|
|
138
|
+
assert.ok(ids.includes('cluster-outage'), `the linked memory was not reached: ${ids.join(', ')}`);
|
|
139
|
+
});
|
|
140
|
+
test('temporal: a question about a period prefers what was learned in it', () => {
|
|
141
|
+
// Identical wording, different months: the only thing that can order these two
|
|
142
|
+
// is the date, which is exactly what the time channel exists to supply.
|
|
143
|
+
const corpus = [
|
|
144
|
+
linked('async-spring', 'Alice 在做异步改造', '她那阵子在改异步数据库调用。', [], { createdAt: new Date(2025, 3, 10).getTime(), updatedAt: new Date(2025, 3, 10).getTime() }),
|
|
145
|
+
linked('async-autumn', 'Alice 在做异步改造', '她那阵子在改异步数据库调用。', [], { createdAt: new Date(2025, 10, 10).getTime(), updatedAt: new Date(2025, 10, 10).getTime() }),
|
|
146
|
+
];
|
|
147
|
+
const query = 'Alice 去年春天在做什么';
|
|
148
|
+
assert.equal(relevanceOf(corpus[0], query), relevanceOf(corpus[1], query), 'the two are lexically identical');
|
|
149
|
+
assert.deepEqual(rankHard(corpus, query, 2), ['async-spring', 'async-autumn']);
|
|
150
|
+
});
|
|
151
|
+
test('entity consolidation: fragments filed under the same account arrive together', () => {
|
|
152
|
+
const KEYS = ['用户账户', 'profile'];
|
|
153
|
+
const corpus = [
|
|
154
|
+
linked('account-login', '用户账户的登录方式', '走的是 SSO。', KEYS),
|
|
155
|
+
linked('account-timezone', '用户偏好的时区', '排期按 Asia/Shanghai 算。', KEYS),
|
|
156
|
+
linked('account-team', '用户所在的团队', '他在平台组。', KEYS),
|
|
157
|
+
linked('account-payment', '用户的支付方式', '走对公转账。', KEYS),
|
|
158
|
+
];
|
|
159
|
+
const ids = rankHard(corpus, '你了解我的账户吗', 4);
|
|
160
|
+
assert.ok(ids.includes('account-login'), `the direct match is missing: ${ids.join(', ')}`);
|
|
161
|
+
const fragments = ids.filter((id) => id !== 'account-login');
|
|
162
|
+
assert.ok(fragments.length >= 2, `only the matching fragment came back: ${ids.join(', ')}`);
|
|
163
|
+
});
|
|
164
|
+
test('belief revision: the newer, deliberately written conclusion outranks the old one', () => {
|
|
165
|
+
const corpus = [
|
|
166
|
+
linked('async-multithread', '用户在 async Python 上挣扎', '最后用多线程跑通了。', [], { source: 'auto' }),
|
|
167
|
+
linked('async-asyncio', '用户已经转向 asyncio', '他已经在写异步数据库调用了。', [], { source: 'tool' }),
|
|
168
|
+
];
|
|
169
|
+
const ids = rankHard(corpus, '用户现在的异步方案是什么', 2);
|
|
170
|
+
assert.deepEqual(ids, ['async-asyncio', 'async-multithread']);
|
|
171
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the one-hop expansion: following the keys and tags the direct hits
|
|
3
|
+
* are filed under.
|
|
4
|
+
*
|
|
5
|
+
* The corpus is built so that the related entries share *no word* with the
|
|
6
|
+
* query — if they did, they would be ordinary hits and the expansion would be
|
|
7
|
+
* untestable. That is also the property the feature has to have: a hop must
|
|
8
|
+
* never be presented as a match.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/test/expand.test
|
|
11
|
+
*/
|
|
12
|
+
import assert from 'node:assert/strict';
|
|
13
|
+
import test from 'node:test';
|
|
14
|
+
import { EXPAND_FACTOR, EXPAND_MAX, relatedHits, searchMemories } from '../search.js';
|
|
15
|
+
import { renderHit } from '../render.js';
|
|
16
|
+
/** Fixed clock so decay never decides these assertions. */
|
|
17
|
+
const NOW = new Date(2026, 8, 29, 19, 0, 0).getTime();
|
|
18
|
+
/** One corpus entry. */
|
|
19
|
+
function entry(id, title, body, extra = {}, kind = 'fact') {
|
|
20
|
+
return {
|
|
21
|
+
id,
|
|
22
|
+
scope: 'global',
|
|
23
|
+
kind,
|
|
24
|
+
title,
|
|
25
|
+
body,
|
|
26
|
+
tags: [],
|
|
27
|
+
keys: [],
|
|
28
|
+
createdAt: NOW - 86_400_000,
|
|
29
|
+
updatedAt: NOW - 86_400_000,
|
|
30
|
+
uses: 0,
|
|
31
|
+
lastUsedAt: 0,
|
|
32
|
+
lastSurfacedAt: 0,
|
|
33
|
+
source: 'auto',
|
|
34
|
+
...extra,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** The seed, plus two entries filed under the same keys and one under a single key. */
|
|
38
|
+
const SEED = entry('state-db', 'SQLite 状态库在哪', '状态库放在 DSH_HOME 下。', { keys: ['state.db', 'sqlite'] });
|
|
39
|
+
const NEIGHBOUR = entry('leases', '任务租约与水位线', '水位线和任务租约都记在那个库里,重启后仍然有效。', { keys: ['state.db', 'sqlite'], updatedAt: NOW - 3_600_000 });
|
|
40
|
+
const NEIGHBOUR_BY_TAG = entry('watermarks', '后台抽取的水位线', '每个会话一条水位线,记录抽到哪一条消息。', { tags: ['state.db', 'sqlite'] });
|
|
41
|
+
const WEAK_LINK = entry('weak', '只共用一个 key 的记忆', '它只提到那个库一次。', { keys: ['state.db'] });
|
|
42
|
+
/**
|
|
43
|
+
* Entries carrying links of their own and nothing else.
|
|
44
|
+
*
|
|
45
|
+
* They exist to give the corpus a realistic size. A link is only an edge when
|
|
46
|
+
* it is not on most of the scope, and a four-entry corpus makes every link look
|
|
47
|
+
* ubiquitous — which is the real behaviour, measured, not a test artefact: a
|
|
48
|
+
* link on 3 of 4 entries really does mean nothing.
|
|
49
|
+
*/
|
|
50
|
+
const FILLERS = Array.from({ length: 12 }, (_, index) => entry(`filler-${index}`, `无关条目 ${index}`, '另一件事的正文。', { keys: [`unique-${index}`] }));
|
|
51
|
+
const GROUPS = [{ scope: 'global', label: 'global', entries: [SEED, NEIGHBOUR, NEIGHBOUR_BY_TAG, WEAK_LINK, ...FILLERS] }];
|
|
52
|
+
test('a hop needs two shared links, not one', () => {
|
|
53
|
+
const hits = searchMemories(GROUPS, '状态库', { expand: true, now: NOW, limit: 10 });
|
|
54
|
+
const ids = hits.map((hit) => hit.entry.id);
|
|
55
|
+
assert.equal(ids[0], 'state-db', 'the direct hit still comes first');
|
|
56
|
+
assert.ok(ids.includes('leases'), 'two shared keys are a link');
|
|
57
|
+
assert.ok(ids.includes('watermarks'), 'two shared tags are a link too');
|
|
58
|
+
assert.ok(!ids.includes('weak'), 'one shared key is not');
|
|
59
|
+
});
|
|
60
|
+
test('an unexpanded search returns only what matched', () => {
|
|
61
|
+
assert.deepEqual(searchMemories(GROUPS, '状态库', { now: NOW, limit: 10 }).map((hit) => hit.entry.id), ['state-db']);
|
|
62
|
+
});
|
|
63
|
+
test('every related hit ranks below every direct hit', () => {
|
|
64
|
+
// The search surface orders by relevance, so this compares *places* rather
|
|
65
|
+
// than numbers: the hop's exact value is asserted where it is computed, on
|
|
66
|
+
// `relatedHits`, whose seeds carry explicit scores.
|
|
67
|
+
const hits = searchMemories(GROUPS, '状态库', { expand: true, now: NOW, limit: 10 });
|
|
68
|
+
const direct = hits.filter((hit) => hit.via === undefined);
|
|
69
|
+
const related = hits.filter((hit) => hit.via !== undefined);
|
|
70
|
+
assert.deepEqual(direct.map((hit) => hit.entry.id), ['state-db']);
|
|
71
|
+
assert.ok(related.length > 0);
|
|
72
|
+
const lastDirect = hits.findLastIndex((hit) => hit.via === undefined);
|
|
73
|
+
const firstRelated = hits.findIndex((hit) => hit.via !== undefined);
|
|
74
|
+
assert.ok(firstRelated > lastDirect, `a hop came before a direct hit: ${hits.map((hit) => `${hit.entry.id}${hit.via === undefined ? '' : '*'}`).join(', ')}`);
|
|
75
|
+
for (const hit of related)
|
|
76
|
+
assert.equal(hit.via, 'state-db', 'the seed it came from is reported');
|
|
77
|
+
});
|
|
78
|
+
test('a link on most of the scope is not an edge', () => {
|
|
79
|
+
// The measured case: in the plugin's own project scope `dsh-cross-memory` sits on
|
|
80
|
+
// 22 of 29 entries, and 18 of its 48 hop-able pairs shared nothing but such
|
|
81
|
+
// links. Here the seed and its neighbour share two links that everything else
|
|
82
|
+
// carries too, so the hop must not happen at all.
|
|
83
|
+
const everywhere = ['common-a', 'common-b'];
|
|
84
|
+
const corpus = [
|
|
85
|
+
entry('seed', '状态库在哪', '状态库放在这里。', { keys: everywhere }),
|
|
86
|
+
entry('neighbour', '另一条', '也说到了状态库。', { keys: everywhere }),
|
|
87
|
+
...Array.from({ length: 6 }, (_, index) => entry(`filler-${index}`, `无关 ${index}`, '无关正文。', { keys: everywhere })),
|
|
88
|
+
];
|
|
89
|
+
const groups = [{ scope: 'global', label: 'global', entries: corpus }];
|
|
90
|
+
const hits = searchMemories(groups, '状态库', { expand: true, now: NOW, limit: 10 });
|
|
91
|
+
assert.ok(hits.every((hit) => hit.via === undefined), 'no hop fired');
|
|
92
|
+
assert.ok(hits.some((hit) => hit.entry.id === 'neighbour'), 'the other direct match is still there');
|
|
93
|
+
});
|
|
94
|
+
test('expansion never grows the result past the limit', () => {
|
|
95
|
+
const crowded = [SEED];
|
|
96
|
+
for (let index = 0; index < 6; index += 1) {
|
|
97
|
+
crowded.push(entry(`n${index}`, `邻居 ${index}`, '同样是那个库的记录。', { keys: ['state.db', 'sqlite'] }));
|
|
98
|
+
}
|
|
99
|
+
const groups = [{ scope: 'global', label: 'global', entries: [...crowded, ...FILLERS] }];
|
|
100
|
+
const hits = searchMemories(groups, '状态库', { expand: true, now: NOW, limit: 10 });
|
|
101
|
+
assert.equal(hits.length, 1 + EXPAND_MAX);
|
|
102
|
+
});
|
|
103
|
+
test('expansion respects the scope and kind filters it was given', () => {
|
|
104
|
+
const projectCopy = entry('project-lease', '项目里的租约', '同样的东西,不同的作用域。', { scope: 'project', keys: ['state.db', 'sqlite'] });
|
|
105
|
+
const groups = [
|
|
106
|
+
{ scope: 'global', label: 'global', entries: [SEED, NEIGHBOUR, ...FILLERS] },
|
|
107
|
+
{ scope: 'project', label: 'project:x', entries: [projectCopy] },
|
|
108
|
+
];
|
|
109
|
+
const scoped = searchMemories(groups, '状态库', { expand: true, now: NOW, limit: 10, scopes: ['global'] });
|
|
110
|
+
assert.deepEqual(scoped.map((hit) => hit.entry.id), ['state-db', 'leases']);
|
|
111
|
+
const kinds = searchMemories(groups, '状态库', { expand: true, now: NOW, limit: 10, kinds: ['procedure'] });
|
|
112
|
+
assert.deepEqual(kinds, [], 'a filtered search does not smuggle entries back in');
|
|
113
|
+
});
|
|
114
|
+
test('relatedHits reports the seed and can be bounded directly', () => {
|
|
115
|
+
const seeds = [{ entry: SEED, score: 100 }];
|
|
116
|
+
const related = relatedHits(GROUPS, seeds, { limit: 1 });
|
|
117
|
+
assert.equal(related.length, 1);
|
|
118
|
+
assert.equal(related[0]?.entry.id, 'leases', 'the strongest hop wins the single slot');
|
|
119
|
+
assert.equal(related[0]?.via, 'state-db');
|
|
120
|
+
assert.deepEqual(relatedHits(GROUPS, []), [], 'no seeds, no hops');
|
|
121
|
+
});
|
|
122
|
+
test('a related hit is marked in the rendering', () => {
|
|
123
|
+
const direct = renderHit({ entry: SEED, score: 10 }, 0);
|
|
124
|
+
const hop = renderHit({ entry: NEIGHBOUR, score: 4, via: 'state-db' }, 1);
|
|
125
|
+
assert.ok(!direct.includes('via='));
|
|
126
|
+
assert.ok(hop.includes('via=state-db'), hop);
|
|
127
|
+
});
|
|
128
|
+
test('a hop is scored from the seed that lit it up, not from the weakest seed', () => {
|
|
129
|
+
// The real-store eval forced this: pegging every hop to the weakest of the top
|
|
130
|
+
// three put the best match's neighbours below entries that shared one word
|
|
131
|
+
// with the turn. Activation spreads from the node that fired.
|
|
132
|
+
const strong = entry('strong', '强命中', '正文。', { keys: ['k1', 'k2'] });
|
|
133
|
+
const weak = entry('weak-seed', '弱命中', '正文。', { keys: ['k3', 'k4'] });
|
|
134
|
+
const nearStrong = entry('near-strong', '强种子的邻居', '正文。', { keys: ['k1', 'k2'] });
|
|
135
|
+
const nearWeak = entry('near-weak', '弱种子的邻居', '正文。', { keys: ['k3', 'k4'] });
|
|
136
|
+
const groups = [{ scope: 'global', label: 'global', entries: [nearStrong, nearWeak] }];
|
|
137
|
+
const related = relatedHits(groups, [{ entry: strong, score: 100 }, { entry: weak, score: 20 }], {});
|
|
138
|
+
assert.deepEqual(related.map((hit) => [hit.entry.id, hit.score, hit.via]), [
|
|
139
|
+
['near-strong', 100 * EXPAND_FACTOR * 0.5, 'strong'],
|
|
140
|
+
['near-weak', 20 * EXPAND_FACTOR * 0.5, 'weak-seed'],
|
|
141
|
+
]);
|
|
142
|
+
});
|
|
143
|
+
test('a weak direct hit is upgraded by the hop, and never marked as a hop', () => {
|
|
144
|
+
// The eval found this: the eighth direct hit is exactly the entry a hop can
|
|
145
|
+
// lift, and "already a direct hit" must not disqualify it — but it did match
|
|
146
|
+
// the query, so it must not be labelled `via` either. The lift is asserted on
|
|
147
|
+
// the number (`relevance`), because whether it also changes the *place*
|
|
148
|
+
// depends on who else is in the corpus.
|
|
149
|
+
const keys = ['k1', 'k2', 'k3', 'k4'];
|
|
150
|
+
const seed = entry('seed', '状态库放在哪里', '状态库的位置记在这里。', { keys });
|
|
151
|
+
const weakHit = entry('weak-hit', '另有一条', '正文里提了一句状态库。', { keys });
|
|
152
|
+
// Three entries that outrank the weak hit, so it is not itself one of the
|
|
153
|
+
// seeds: a seed is excluded from the hop, and with a two-entry corpus the
|
|
154
|
+
// thing under test would have been its own seed.
|
|
155
|
+
const fillers = [1, 2, 3].map((index) => entry(`filler-${index}`, `状态库相关 ${index}`, '无关正文。'));
|
|
156
|
+
const groups = [{ scope: 'global', label: 'global', entries: [seed, weakHit, ...fillers] }];
|
|
157
|
+
const plain = searchMemories(groups, '状态库', { now: NOW, limit: 5 });
|
|
158
|
+
const expanded = searchMemories(groups, '状态库', { now: NOW, limit: 5, expand: true });
|
|
159
|
+
const before = plain.find((hit) => hit.entry.id === 'weak-hit');
|
|
160
|
+
const after = expanded.find((hit) => hit.entry.id === 'weak-hit');
|
|
161
|
+
assert.ok(before !== undefined && after !== undefined);
|
|
162
|
+
assert.ok((after.relevance ?? 0) > (before.relevance ?? 0), `the hop did not lift it: ${before.relevance} -> ${after.relevance}`);
|
|
163
|
+
assert.equal(after.via, undefined, 'it matched the query, so it is not a hop result');
|
|
164
|
+
});
|