dsh-cross-memory 0.2.6 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/lib/backfill.js +3 -1
- package/lib/bm25.js +100 -0
- package/lib/cards.js +188 -0
- package/lib/client.js +229 -1
- package/lib/config.js +60 -4
- package/lib/extract.js +232 -13
- package/lib/index.js +171 -45
- package/lib/raw-recall.js +149 -0
- package/lib/render.js +71 -18
- package/lib/search.js +33 -53
- package/lib/test/extract.test.js +33 -3
- package/lib/test/injection.test.js +18 -2
- package/lib/test/proposal-card.test.js +353 -0
- package/lib/test/recall.test.js +4 -2
- package/lib/tokenize.js +68 -0
- package/lib/types/bm25.d.ts +66 -0
- package/lib/types/cards.d.ts +186 -0
- package/lib/types/config.d.ts +64 -4
- package/lib/types/extract.d.ts +54 -0
- package/lib/types/index.d.ts +37 -8
- package/lib/types/raw-recall.d.ts +28 -0
- package/lib/types/render.d.ts +1 -0
- package/lib/types/search.d.ts +1 -21
- package/lib/types/test/proposal-card.test.d.ts +1 -0
- package/lib/types/tokenize.d.ts +39 -0
- package/package.json +8 -4
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guards for the consolidation confirmation card.
|
|
3
|
+
*
|
|
4
|
+
* Two halves are pinned here. The Host kind is exercised against fake
|
|
5
|
+
* `actionCards`/`skills` services, because a real composition would mount the
|
|
6
|
+
* whole memory runtime: what matters is that accept applies the pending batch
|
|
7
|
+
* and records its counts, reject clears it, and reconciliation notices a
|
|
8
|
+
* proposal that was decided or replaced elsewhere. The browser body is then
|
|
9
|
+
* rendered with the same hand-written hook runtime the disputes panel uses, so
|
|
10
|
+
* the three buttons and the settled copy are real clicks rather than a text
|
|
11
|
+
* snapshot.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-cross-memory/test/proposal-card.test
|
|
14
|
+
*/
|
|
15
|
+
import assert from 'node:assert/strict';
|
|
16
|
+
import { readFile } from 'node:fs/promises';
|
|
17
|
+
import test from 'node:test';
|
|
18
|
+
import { PROPOSAL_ACTION, PROPOSAL_DETAILS, PROPOSAL_SKILL, PROPOSAL_SKILL_CONTENT, registerProposalCard } from '../cards.js';
|
|
19
|
+
/** The proposal the injected note describes. */
|
|
20
|
+
const DETAILS = { label: 'alpha', count: 3, stagedAt: 1_760_000_000_000 };
|
|
21
|
+
/** One card as the Host hands it to the kind. */
|
|
22
|
+
const PROPOSAL = {
|
|
23
|
+
cardId: 'card-1',
|
|
24
|
+
action: PROPOSAL_ACTION,
|
|
25
|
+
title: '确认这批记忆变更',
|
|
26
|
+
brief: '确认后才会改动存储。',
|
|
27
|
+
details: DETAILS,
|
|
28
|
+
};
|
|
29
|
+
/** A live root; the fake services never read it. */
|
|
30
|
+
const AGENT = { id: 'agent-1', session: {} };
|
|
31
|
+
/** Fake Host services: recorded kind, decisions, providers and disposers. */
|
|
32
|
+
function fakeServices(initial = {}) {
|
|
33
|
+
const decisions = { ...initial };
|
|
34
|
+
const kinds = [];
|
|
35
|
+
const recorded = [];
|
|
36
|
+
const providers = [];
|
|
37
|
+
let kindDisposed = 0;
|
|
38
|
+
let skillDisposed = 0;
|
|
39
|
+
const cards = {
|
|
40
|
+
view: () => ({ decisions }),
|
|
41
|
+
register: (kind) => {
|
|
42
|
+
kinds.push(kind);
|
|
43
|
+
return () => { kindDisposed += 1; };
|
|
44
|
+
},
|
|
45
|
+
record: (_agent, decision) => {
|
|
46
|
+
recorded.push(decision);
|
|
47
|
+
decisions[decision.cardId] = decision;
|
|
48
|
+
},
|
|
49
|
+
skillProvider: (candidate, get) => (control) => {
|
|
50
|
+
// Same contract as the Host service: `enabled` is the service's to apply.
|
|
51
|
+
control.signal.throwIfAborted();
|
|
52
|
+
return { name: candidate.provider, list: () => Promise.resolve([candidate]), get };
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
const skills = {
|
|
56
|
+
registerProvider: (create) => {
|
|
57
|
+
providers.push(create);
|
|
58
|
+
return () => { skillDisposed += 1; };
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
cards,
|
|
63
|
+
skills,
|
|
64
|
+
kinds,
|
|
65
|
+
recorded,
|
|
66
|
+
providers,
|
|
67
|
+
disposers: () => ({ kindDisposed, skillDisposed }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** A store seam over one mutable pending value. */
|
|
71
|
+
function fakeRuntime(initial, applied = { written: 3, retired: 1 }) {
|
|
72
|
+
const state = { pending: initial };
|
|
73
|
+
const runtime = {
|
|
74
|
+
pending: () => Promise.resolve(state.pending),
|
|
75
|
+
apply: () => {
|
|
76
|
+
// Real `applyPendingPlan` reports `undefined` when nothing is staged.
|
|
77
|
+
const counts = state.pending === undefined ? undefined : applied;
|
|
78
|
+
state.pending = undefined;
|
|
79
|
+
return Promise.resolve(counts);
|
|
80
|
+
},
|
|
81
|
+
reject: () => {
|
|
82
|
+
const count = state.pending?.count;
|
|
83
|
+
state.pending = undefined;
|
|
84
|
+
return Promise.resolve(count);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
return { runtime, state };
|
|
88
|
+
}
|
|
89
|
+
test('the kind registers accept/reject, validates details, and publishes its skill', async () => {
|
|
90
|
+
const services = fakeServices();
|
|
91
|
+
const { runtime } = fakeRuntime({ ...DETAILS });
|
|
92
|
+
const dispose = registerProposalCard(services.cards, services.skills, runtime);
|
|
93
|
+
assert.equal(services.kinds.length, 1);
|
|
94
|
+
const kind = services.kinds[0];
|
|
95
|
+
assert.ok(kind !== undefined);
|
|
96
|
+
assert.equal(kind.action, PROPOSAL_ACTION);
|
|
97
|
+
assert.deepEqual(kind.verbs, { accept: { writes: true }, reject: { writes: true } });
|
|
98
|
+
assert.deepEqual(kind.openPhases, ['failed']);
|
|
99
|
+
assert.deepEqual(kind.statusFields, ['written', 'retired']);
|
|
100
|
+
assert.match(kind.statusGuidance ?? '', /do not offer that same proposal again/iu);
|
|
101
|
+
assert.equal(PROPOSAL_DETAILS.safeParse({ ...DETAILS, count: 0 }).success, false, 'a card with no decisions is no card');
|
|
102
|
+
assert.equal(PROPOSAL_DETAILS.safeParse({ ...DETAILS, count: 1.5 }).success, false);
|
|
103
|
+
assert.equal(PROPOSAL_DETAILS.safeParse({ ...DETAILS, label: '' }).success, false);
|
|
104
|
+
assert.equal(PROPOSAL_DETAILS.safeParse(DETAILS).success, true);
|
|
105
|
+
assert.equal(services.providers.length, 1);
|
|
106
|
+
const provider = services.providers[0]?.({ signal: new AbortController().signal, invalidate: () => { } });
|
|
107
|
+
assert.ok(provider !== undefined);
|
|
108
|
+
assert.equal(provider.name, 'dsh-cross-memory');
|
|
109
|
+
const listed = await provider.list({});
|
|
110
|
+
assert.equal(listed.length, 1);
|
|
111
|
+
assert.equal(listed[0]?.name, PROPOSAL_SKILL);
|
|
112
|
+
const loaded = await provider.get(listed[0], {});
|
|
113
|
+
assert.match(loaded?.content ?? '', /action-card/u);
|
|
114
|
+
assert.match(loaded?.content ?? '', /resolve_memory_proposal/u);
|
|
115
|
+
assert.match(loaded?.content ?? '', /只提议当前 pending 文件里那一批|当前 pending 文件里那一批/u);
|
|
116
|
+
assert.match(PROPOSAL_SKILL_CONTENT, /details\.count/u);
|
|
117
|
+
dispose();
|
|
118
|
+
assert.deepEqual(services.disposers(), { kindDisposed: 1, skillDisposed: 1 }, 'one disposer removes both halves');
|
|
119
|
+
});
|
|
120
|
+
test('accept applies the pending batch and records written/retired', async () => {
|
|
121
|
+
const services = fakeServices();
|
|
122
|
+
const { runtime, state } = fakeRuntime({ ...DETAILS });
|
|
123
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
124
|
+
const kind = services.kinds[0];
|
|
125
|
+
assert.ok(kind !== undefined);
|
|
126
|
+
const result = await kind.act(AGENT, PROPOSAL, 'accept', undefined);
|
|
127
|
+
assert.equal(result.status, 'settled');
|
|
128
|
+
if (result.status !== 'settled')
|
|
129
|
+
return;
|
|
130
|
+
assert.equal(result.decision.phase, 'applied');
|
|
131
|
+
assert.deepEqual(result.decision.data, { written: 3, retired: 1 });
|
|
132
|
+
assert.deepEqual(services.recorded, [{ cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'applied', data: { written: 3, retired: 1 } }]);
|
|
133
|
+
assert.equal(state.pending, undefined);
|
|
134
|
+
});
|
|
135
|
+
test('reject clears the pending batch and records the rejection', async () => {
|
|
136
|
+
const services = fakeServices();
|
|
137
|
+
const { runtime, state } = fakeRuntime({ ...DETAILS });
|
|
138
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
139
|
+
const kind = services.kinds[0];
|
|
140
|
+
assert.ok(kind !== undefined);
|
|
141
|
+
const result = await kind.act(AGENT, PROPOSAL, 'reject', undefined);
|
|
142
|
+
assert.equal(result.status, 'settled');
|
|
143
|
+
if (result.status !== 'settled')
|
|
144
|
+
return;
|
|
145
|
+
assert.equal(result.decision.phase, 'rejected');
|
|
146
|
+
assert.equal(result.decision.data, undefined);
|
|
147
|
+
assert.equal(state.pending, undefined);
|
|
148
|
+
});
|
|
149
|
+
test('a failed apply keeps the card retryable instead of claiming success', async () => {
|
|
150
|
+
const services = fakeServices();
|
|
151
|
+
const state = { pending: { ...DETAILS } };
|
|
152
|
+
const runtime = {
|
|
153
|
+
pending: () => Promise.resolve(state.pending),
|
|
154
|
+
// `applyPendingPlan` reports the rollback by leaving the proposal in place.
|
|
155
|
+
apply: () => Promise.resolve({ written: 0, retired: 0 }),
|
|
156
|
+
reject: () => Promise.resolve(undefined),
|
|
157
|
+
};
|
|
158
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
159
|
+
const kind = services.kinds[0];
|
|
160
|
+
assert.ok(kind !== undefined);
|
|
161
|
+
const result = await kind.act(AGENT, PROPOSAL, 'accept', undefined);
|
|
162
|
+
if (result.status !== 'settled')
|
|
163
|
+
return assert.fail('a failed apply still settles the card');
|
|
164
|
+
assert.equal(result.decision.phase, 'failed');
|
|
165
|
+
assert.equal(result.decision.data, undefined, 'a rollback wrote nothing, so it reports no counts');
|
|
166
|
+
assert.ok(state.pending !== undefined, 'the batch is still there for the retry');
|
|
167
|
+
});
|
|
168
|
+
test('accepting a batch that another entry already cleared settles as elsewhere', async () => {
|
|
169
|
+
const services = fakeServices();
|
|
170
|
+
const { runtime } = fakeRuntime(undefined);
|
|
171
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
172
|
+
const kind = services.kinds[0];
|
|
173
|
+
assert.ok(kind !== undefined);
|
|
174
|
+
const result = await kind.act(AGENT, PROPOSAL, 'accept', undefined);
|
|
175
|
+
if (result.status !== 'settled')
|
|
176
|
+
return assert.fail('a vanished batch settles the card');
|
|
177
|
+
assert.equal(result.decision.phase, 'settled-elsewhere');
|
|
178
|
+
});
|
|
179
|
+
test('reconcile records settled-elsewhere when the proposal disappeared', async () => {
|
|
180
|
+
const services = fakeServices();
|
|
181
|
+
const { runtime } = fakeRuntime(undefined);
|
|
182
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
183
|
+
const kind = services.kinds[0];
|
|
184
|
+
assert.ok(kind !== undefined);
|
|
185
|
+
await kind.reconcile?.(AGENT, PROPOSAL);
|
|
186
|
+
assert.deepEqual(services.recorded, [{ cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'settled-elsewhere' }]);
|
|
187
|
+
});
|
|
188
|
+
test('reconcile supersedes a card whose proposal was replaced, and leaves a matching one alone', async () => {
|
|
189
|
+
const services = fakeServices();
|
|
190
|
+
const { runtime, state } = fakeRuntime({ ...DETAILS, count: 4 });
|
|
191
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
192
|
+
const kind = services.kinds[0];
|
|
193
|
+
assert.ok(kind !== undefined);
|
|
194
|
+
await kind.reconcile?.(AGENT, PROPOSAL);
|
|
195
|
+
assert.deepEqual(services.recorded, [{ cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'superseded' }]);
|
|
196
|
+
state.pending = { ...DETAILS };
|
|
197
|
+
await kind.reconcile?.(AGENT, PROPOSAL);
|
|
198
|
+
assert.equal(services.recorded.length, 1, 'the exact pending proposal is not re-recorded');
|
|
199
|
+
});
|
|
200
|
+
test('reconcile never rewrites a card that is already terminal', async () => {
|
|
201
|
+
const services = fakeServices({ 'card-1': { cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'applied', data: { written: 1, retired: 0 } } });
|
|
202
|
+
const { runtime } = fakeRuntime(undefined);
|
|
203
|
+
registerProposalCard(services.cards, services.skills, runtime);
|
|
204
|
+
const kind = services.kinds[0];
|
|
205
|
+
assert.ok(kind !== undefined);
|
|
206
|
+
await kind.reconcile?.(AGENT, PROPOSAL);
|
|
207
|
+
assert.deepEqual(services.recorded, [], 'an applied card keeps its outcome on every later action');
|
|
208
|
+
});
|
|
209
|
+
/** The compiled browser part, resolved from the compiled test's own location. */
|
|
210
|
+
const BODY = new URL('../../.client-build/parts/action-card.js', import.meta.url);
|
|
211
|
+
/** Load the body factory and copy table. */
|
|
212
|
+
async function loadBody() {
|
|
213
|
+
const source = await readFile(BODY, 'utf8');
|
|
214
|
+
return new Function(`${source}\nreturn { createProposalCardBody, PROPOSAL_COPY }`)();
|
|
215
|
+
}
|
|
216
|
+
/** Every element in a rendered tree, depth first. */
|
|
217
|
+
function* walk(node) {
|
|
218
|
+
if (Array.isArray(node)) {
|
|
219
|
+
for (const child of node)
|
|
220
|
+
yield* walk(child);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (node === null || typeof node !== 'object')
|
|
224
|
+
return;
|
|
225
|
+
const element = node;
|
|
226
|
+
if (element.props !== undefined && (typeof element.type === 'string' || typeof element.type === 'function'))
|
|
227
|
+
yield element;
|
|
228
|
+
if (element.props?.children !== undefined)
|
|
229
|
+
yield* walk(element.props.children);
|
|
230
|
+
}
|
|
231
|
+
/** The text a rendered subtree would show. */
|
|
232
|
+
function textOf(node) {
|
|
233
|
+
if (typeof node === 'string' || typeof node === 'number')
|
|
234
|
+
return String(node);
|
|
235
|
+
if (Array.isArray(node))
|
|
236
|
+
return node.map(textOf).join('');
|
|
237
|
+
if (node === null || typeof node !== 'object')
|
|
238
|
+
return '';
|
|
239
|
+
return textOf(node.props.children);
|
|
240
|
+
}
|
|
241
|
+
/** The first element with this tag whose text contains `text`. */
|
|
242
|
+
function findByText(tree, tag, text) {
|
|
243
|
+
for (const element of walk(tree)) {
|
|
244
|
+
if (element.type === tag && textOf(element).includes(text))
|
|
245
|
+
return element;
|
|
246
|
+
}
|
|
247
|
+
throw new Error(`no <${tag}> showing ${JSON.stringify(text)}`);
|
|
248
|
+
}
|
|
249
|
+
/** Click one element's `onClick`. */
|
|
250
|
+
function click(element) {
|
|
251
|
+
const handler = element.props.onClick;
|
|
252
|
+
assert.equal(typeof handler, 'function', 'the button must carry a click handler');
|
|
253
|
+
handler();
|
|
254
|
+
}
|
|
255
|
+
/** Mount the body against a stand-in hook runtime and a recording `act`. */
|
|
256
|
+
function mountBody(module, props, act) {
|
|
257
|
+
const state = [];
|
|
258
|
+
let cursor = 0;
|
|
259
|
+
const react = {
|
|
260
|
+
createElement: (type, value, ...children) => ({
|
|
261
|
+
type,
|
|
262
|
+
props: { ...(value ?? {}), children: children.length <= 1 ? children[0] : children },
|
|
263
|
+
}),
|
|
264
|
+
useState: (initial) => {
|
|
265
|
+
const index = cursor++;
|
|
266
|
+
if (!(index in state))
|
|
267
|
+
state[index] = typeof initial === 'function' ? initial() : initial;
|
|
268
|
+
return [state[index], (next) => {
|
|
269
|
+
state[index] = typeof next === 'function' ? next(state[index]) : next;
|
|
270
|
+
}];
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
const Body = module.createProposalCardBody(react);
|
|
274
|
+
const copy = module.PROPOSAL_COPY.zh ?? {};
|
|
275
|
+
const t = (key, params) => {
|
|
276
|
+
const template = copy[key] ?? key;
|
|
277
|
+
return template.replace(/\{(\w+)\}/gu, (_match, name) => params?.[name] ?? '');
|
|
278
|
+
};
|
|
279
|
+
const render = () => {
|
|
280
|
+
cursor = 0;
|
|
281
|
+
return Body({ ...props, t, act });
|
|
282
|
+
};
|
|
283
|
+
return { render };
|
|
284
|
+
}
|
|
285
|
+
/** The frame props for one card. */
|
|
286
|
+
function frameProps(decision) {
|
|
287
|
+
return {
|
|
288
|
+
proposal: { cardId: 'card-1', action: PROPOSAL_ACTION, title: '确认这批记忆变更', brief: '确认后才会改动存储。', details: DETAILS },
|
|
289
|
+
decision,
|
|
290
|
+
summary: 'summary',
|
|
291
|
+
fallback: 'fallback',
|
|
292
|
+
act: () => Promise.resolve({ status: 'settled' }),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
test('the body shows the batch and sends accept/reject/dismiss', async () => {
|
|
296
|
+
const module = await loadBody();
|
|
297
|
+
const calls = [];
|
|
298
|
+
const act = (verb) => {
|
|
299
|
+
calls.push(verb);
|
|
300
|
+
return Promise.resolve({ status: 'settled' });
|
|
301
|
+
};
|
|
302
|
+
const { render } = mountBody(module, frameProps(undefined), act);
|
|
303
|
+
const card = render();
|
|
304
|
+
const shown = textOf(card);
|
|
305
|
+
assert.match(shown, /范围:alpha/u);
|
|
306
|
+
assert.match(shown, /3 条变更待确认/u);
|
|
307
|
+
assert.match(shown, /提案生成于/u);
|
|
308
|
+
click(findByText(card, 'button', '确认应用'));
|
|
309
|
+
await new Promise((resolve) => { setTimeout(resolve, 10); });
|
|
310
|
+
assert.deepEqual(calls, ['accept'], 'the primary button sends accept');
|
|
311
|
+
click(findByText(render(), 'button', '拒绝'));
|
|
312
|
+
await new Promise((resolve) => { setTimeout(resolve, 10); });
|
|
313
|
+
click(findByText(render(), 'button', '稍后'));
|
|
314
|
+
await new Promise((resolve) => { setTimeout(resolve, 10); });
|
|
315
|
+
assert.deepEqual(calls, ['accept', 'reject', 'dismiss'], 'reject and Not now use their own verbs');
|
|
316
|
+
});
|
|
317
|
+
test('a settled card shows its outcome and offers no buttons', async () => {
|
|
318
|
+
const module = await loadBody();
|
|
319
|
+
const applied = renderWith(module, { cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'applied', data: { written: 3, retired: 1 } });
|
|
320
|
+
const text = textOf(applied);
|
|
321
|
+
assert.match(text, /已应用:3 条写回,1 条退役。/u);
|
|
322
|
+
assert.equal(findByTextOptional(applied, 'button', '确认应用'), undefined, 'no action survives a decision');
|
|
323
|
+
assert.equal(findByTextOptional(applied, 'button', '稍后'), undefined);
|
|
324
|
+
const rejected = renderWith(module, { cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'rejected' });
|
|
325
|
+
assert.match(textOf(rejected), /已拒绝/u);
|
|
326
|
+
assert.equal(findByTextOptional(rejected, 'button', '拒绝'), undefined);
|
|
327
|
+
const elsewhere = renderWith(module, { cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'settled-elsewhere' });
|
|
328
|
+
assert.match(textOf(elsewhere), /已在别处处理/u);
|
|
329
|
+
});
|
|
330
|
+
test('a failed card stays retryable, and unreadable details fall back to the frame', async () => {
|
|
331
|
+
const module = await loadBody();
|
|
332
|
+
const failed = renderWith(module, { cardId: 'card-1', action: PROPOSAL_ACTION, phase: 'failed' });
|
|
333
|
+
assert.match(textOf(failed), /应用失败,存储已回滚/u);
|
|
334
|
+
assert.ok(findByTextOptional(failed, 'button', '确认应用') !== undefined, 'a rollback can be retried');
|
|
335
|
+
const invalid = mountBody(module, {
|
|
336
|
+
...frameProps(undefined),
|
|
337
|
+
proposal: { cardId: 'card-1', action: PROPOSAL_ACTION, title: 't', brief: 'b', details: { ...DETAILS, count: 0 } },
|
|
338
|
+
}, () => Promise.resolve({ status: 'settled' })).render();
|
|
339
|
+
assert.equal(invalid, 'fallback', 'a card whose details fail the schema renders the frame fallback');
|
|
340
|
+
});
|
|
341
|
+
/** Render the body with one recorded decision. */
|
|
342
|
+
function renderWith(module, decision) {
|
|
343
|
+
return mountBody(module, frameProps(decision), () => Promise.resolve({ status: 'settled' })).render();
|
|
344
|
+
}
|
|
345
|
+
/** Like {@link findByText}, but undefined instead of throwing. */
|
|
346
|
+
function findByTextOptional(tree, tag, text) {
|
|
347
|
+
try {
|
|
348
|
+
return findByText(tree, tag, text);
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
}
|
package/lib/test/recall.test.js
CHANGED
|
@@ -50,7 +50,9 @@ function stubAgent(session) {
|
|
|
50
50
|
/** A runtime over a temp store. */
|
|
51
51
|
async function fixture(t, settings = {}) {
|
|
52
52
|
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-recall-'));
|
|
53
|
-
|
|
53
|
+
// The raw channel is on by default now; these tests are about the MEMORY half,
|
|
54
|
+
// so they switch it off unless a test asks for it.
|
|
55
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false, ragRecall: false, ...settings });
|
|
54
56
|
t.after(() => {
|
|
55
57
|
runtime.dispose();
|
|
56
58
|
return rm(dir, { recursive: true, force: true });
|
|
@@ -85,7 +87,7 @@ async function loggedFixture(t, settings = {}) {
|
|
|
85
87
|
return Logger.format({}, { ts: Date.now(), type, name: 'dsh-cross-memory', args });
|
|
86
88
|
}
|
|
87
89
|
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-recall-'));
|
|
88
|
-
const runtime = new MemoriesRuntime(context, { memoriesDir: dir, autoExtract: false, ...settings });
|
|
90
|
+
const runtime = new MemoriesRuntime(context, { memoriesDir: dir, autoExtract: false, ragRecall: false, ...settings });
|
|
89
91
|
t.after(() => {
|
|
90
92
|
runtime.dispose();
|
|
91
93
|
return rm(dir, { recursive: true, force: true });
|
package/lib/tokenize.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tokenizer shared by every lexical path in the plugin.
|
|
3
|
+
*
|
|
4
|
+
* Split out of `search.ts` so the BM25 ranker can use the exact same terms as
|
|
5
|
+
* the hand-weighted scorer without a circular import: the two rankers are
|
|
6
|
+
* supposed to agree on what a "term" is, and a copy of this file would be the
|
|
7
|
+
* first thing to drift.
|
|
8
|
+
*
|
|
9
|
+
* Chinese is the reason this module exists. A query with no spaces
|
|
10
|
+
* ("该插件是否有日志") tokenizes to one indivisible run under any whitespace
|
|
11
|
+
* splitter, so a whole-run substring test is the only thing that could match —
|
|
12
|
+
* and a memory almost never contains a whole question verbatim. Every
|
|
13
|
+
* comparison therefore runs over CJK character bigrams as well.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-cross-memory/tokenize
|
|
16
|
+
*/
|
|
17
|
+
/** A CJK ideograph, including the extension blocks in common use. */
|
|
18
|
+
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u;
|
|
19
|
+
/** A CJK character inside a query or a memory field. */
|
|
20
|
+
const CJK_CHAR = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/gu;
|
|
21
|
+
/** Lowercase Latin, digits, and underscore — the "word" case. */
|
|
22
|
+
const WORD = /[a-z0-9_]+/gu;
|
|
23
|
+
/** Split text into searchable terms: ASCII words and CJK character bigrams.
|
|
24
|
+
*
|
|
25
|
+
* A CJK run also contributes bigrams of its neighbours, so "该插件是否有日志"
|
|
26
|
+
* yields "该插","插件","件是","是否","否有","有日","日志". A one-character run
|
|
27
|
+
* contributes itself, since a lone ideograph has no bigram.
|
|
28
|
+
*
|
|
29
|
+
* @param text - raw text.
|
|
30
|
+
* @returns lowercase terms; a run that yields nothing contributes nothing.
|
|
31
|
+
*/
|
|
32
|
+
export function tokenize(text) {
|
|
33
|
+
const lower = text.toLowerCase();
|
|
34
|
+
const terms = [];
|
|
35
|
+
for (const word of lower.match(WORD) ?? [])
|
|
36
|
+
terms.push(word);
|
|
37
|
+
const chars = lower.match(CJK_CHAR) ?? [];
|
|
38
|
+
if (chars.length === 1)
|
|
39
|
+
terms.push(chars[0]);
|
|
40
|
+
for (let index = 0; index + 1 < chars.length; index += 1) {
|
|
41
|
+
terms.push(`${chars[index]}${chars[index + 1]}`);
|
|
42
|
+
}
|
|
43
|
+
return terms;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A term's weight for scoring purposes.
|
|
47
|
+
*
|
|
48
|
+
* One CJK bigram is a much weaker claim than one Latin word — "日志" occurs in
|
|
49
|
+
* countless texts where "logging" does not — so a bigram earns less. Without
|
|
50
|
+
* this every Chinese question would clear the recall gate on noise alone.
|
|
51
|
+
*
|
|
52
|
+
* @param term - one term from {@link tokenize}.
|
|
53
|
+
* @returns a multiplier in `(0, 1]`.
|
|
54
|
+
*/
|
|
55
|
+
export function termWeight(term) {
|
|
56
|
+
const cjk = (term.match(CJK_CHAR) ?? []).length;
|
|
57
|
+
if (cjk === 0)
|
|
58
|
+
return 1;
|
|
59
|
+
// Two-character bigram: half credit. A longer CJK term cannot occur (the
|
|
60
|
+
// tokenizer emits bigrams), but treat it as stronger if it ever does.
|
|
61
|
+
return cjk <= 2 ? 0.5 : Math.min(1, 0.5 + (cjk - 2) * 0.15);
|
|
62
|
+
}
|
|
63
|
+
/** A short token carries little signal and is skipped as a query term. */
|
|
64
|
+
export function isNoise(token) {
|
|
65
|
+
if (CJK.test(token))
|
|
66
|
+
return false;
|
|
67
|
+
return token.length < 2;
|
|
68
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Okapi BM25 over the memory fields, used as the ORDERING ranker.
|
|
3
|
+
*
|
|
4
|
+
* The hand-weighted scorer in `search.ts` stays the gatekeeper: its evidence
|
|
5
|
+
* rule (a substantive term, a phrase, an entity) decides what may be recalled
|
|
6
|
+
* at all, and its `relevance` keeps the meaning of `recallMinScore`. What BM25
|
|
7
|
+
* replaces is the *ordering* — which of the entries that cleared the gate comes
|
|
8
|
+
* first — and there it measured better than the hand weights.
|
|
9
|
+
*
|
|
10
|
+
* Why a second ranker instead of retuning the first: the shipped scorer is a
|
|
11
|
+
* sum of hand-set field weights (title 8, keys 7, body 2 …), and on the clean
|
|
12
|
+
* query batch its top-1 was 60.0% against BM25's 76.0%, top-5 81.3% against
|
|
13
|
+
* 92.0%. The gap is structural, not a constant: the hand weights cannot express
|
|
14
|
+
* "a term that appears in 100 of 176 entries is worth less than one that appears
|
|
15
|
+
* in three", which is exactly what separates 「同步」 from a file name. BM25's
|
|
16
|
+
* idf does that, and it is why a query with only 42.5% lexical overlap with its
|
|
17
|
+
* target still finds it.
|
|
18
|
+
*
|
|
19
|
+
* Same tokenizer as the gatekeeper (`tokenize.js`), same field weighting as
|
|
20
|
+
* `bench/run-bench.mts` so the bench numbers and the shipped behaviour are the
|
|
21
|
+
* same experiment. k1 = 1.2, b = 0.75 — the best cell of the 64-cell
|
|
22
|
+
* sensitivity audit, and the shipped bench's configuration.
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-cross-memory/bm25
|
|
25
|
+
*/
|
|
26
|
+
import type { MemoryEntry } from './types.js';
|
|
27
|
+
/** Term frequency saturation, from the sensitivity audit's best cell. */
|
|
28
|
+
export declare const BM25_K1 = 1.2;
|
|
29
|
+
/** Length normalisation, from the same cell. */
|
|
30
|
+
export declare const BM25_B = 0.75;
|
|
31
|
+
/** Field multiplicity: a title word counts twice, a key twice, the rest once. */
|
|
32
|
+
export declare const BM25_FIELDS: {
|
|
33
|
+
readonly title: 2;
|
|
34
|
+
readonly keys: 2;
|
|
35
|
+
readonly tags: 1;
|
|
36
|
+
readonly appliesTo: 1;
|
|
37
|
+
readonly body: 1;
|
|
38
|
+
};
|
|
39
|
+
/** A built index: scores a query against the entries it was built from. */
|
|
40
|
+
export interface Bm25Index {
|
|
41
|
+
/** The entries in index order. */
|
|
42
|
+
readonly entries: readonly MemoryEntry[];
|
|
43
|
+
/**
|
|
44
|
+
* Score every entry against one query.
|
|
45
|
+
* @param query - raw query text.
|
|
46
|
+
* @returns id → score, only entries with a positive score.
|
|
47
|
+
*/
|
|
48
|
+
score(query: string): Map<string, number>;
|
|
49
|
+
}
|
|
50
|
+
/** Build (or reuse) the index for one entry array.
|
|
51
|
+
*
|
|
52
|
+
* @param entries - the entries to rank, in any order.
|
|
53
|
+
* @returns the index; repeated calls with the same array are free.
|
|
54
|
+
*/
|
|
55
|
+
export declare function createBm25Index(entries: readonly MemoryEntry[]): Bm25Index;
|
|
56
|
+
/**
|
|
57
|
+
* Rank entries against a query by BM25, strongest first.
|
|
58
|
+
*
|
|
59
|
+
* Only entries with a positive score are returned: an entry that shares no term
|
|
60
|
+
* with the query is not a candidate, exactly as the gatekeeper sees it.
|
|
61
|
+
*
|
|
62
|
+
* @param entries - the entries to rank.
|
|
63
|
+
* @param query - raw query text.
|
|
64
|
+
* @returns entries in descending score order.
|
|
65
|
+
*/
|
|
66
|
+
export declare function bm25Rank(entries: readonly MemoryEntry[], query: string): MemoryEntry[];
|