dsh-cross-memory 0.2.8 → 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.
@@ -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
+ }
@@ -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[];
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The `resolve_memory_proposal` action card: a staged consolidation proposal
3
+ * offered in the answer, decided by a click.
4
+ *
5
+ * Before 0.2.9 a staged proposal could only wait for `/memories plan` +
6
+ * `/memories apply|reject` or the settings page, and the notification pump that
7
+ * pointed at it is unusable on macOS in this deployment (no osascript channel).
8
+ * A card is the same question where the user already is: the model loads a
9
+ * skill, ends its answer with an `action-card` block, and the buttons apply or
10
+ * discard the whole waiting batch.
11
+ *
12
+ * The kind owns no state of its own: every action reads the real pending file
13
+ * through {@link ProposalCardRuntime}, so a card can never apply a proposal the
14
+ * store no longer has, and the same pending batch stays actionable from the
15
+ * command and the settings panel.
16
+ *
17
+ * The Host services are described by the small structural interfaces below
18
+ * instead of importing `@deepseek-ai/dsh-action-cards` / `dsh-skill` types. Two
19
+ * reasons: the card mechanism is an optional capability (an older Host has no
20
+ * `skillProvider` and this plugin must still compose), and both packages ship
21
+ * their own `schemastery` copy, whose duplicate type identity made this
22
+ * package's `Config` declaration non-portable.
23
+ *
24
+ * @module dsh-cross-memory/cards
25
+ */
26
+ import { z } from 'zod';
27
+ import type { Agent } from '@deepseek-ai/dsh-agent';
28
+ import type { Session } from '@deepseek-ai/dsh-session';
29
+ /** Value of the card's `action` field; also what the skill's block names. */
30
+ export declare const PROPOSAL_ACTION = "resolve_memory_proposal";
31
+ /** Skill name that tells the model when to offer the card. */
32
+ export declare const PROPOSAL_SKILL = "memory-proposal";
33
+ /** Fields the model writes into the answer block; validated on both sides. */
34
+ export interface ProposalDetails {
35
+ /** Scope label of the waiting proposal, as the store wrote it. */
36
+ readonly label: string;
37
+ /** Number of decisions waiting for the user. */
38
+ readonly count: number;
39
+ /** Epoch milliseconds when the pass staged the proposal. */
40
+ readonly stagedAt: number;
41
+ }
42
+ /** Host validation for one card's `details`. */
43
+ export declare const PROPOSAL_DETAILS: z.ZodObject<{
44
+ label: z.ZodString;
45
+ count: z.ZodNumber;
46
+ stagedAt: z.ZodNumber;
47
+ }, z.core.$strip>;
48
+ /** The staged proposal as the card reads it; identical to the injected note's fields. */
49
+ export interface PendingProposal {
50
+ readonly label: string;
51
+ readonly count: number;
52
+ readonly stagedAt: number;
53
+ }
54
+ /**
55
+ * What the card needs from the memory runtime.
56
+ *
57
+ * A seam rather than the runtime itself: the kind is testable with three tiny
58
+ * functions, and it cannot reach the store, the model or the session directly.
59
+ */
60
+ export interface ProposalCardRuntime {
61
+ /** The proposal waiting right now, or `undefined` when nothing is staged. */
62
+ pending(): Promise<PendingProposal | undefined>;
63
+ /**
64
+ * Apply every waiting decision.
65
+ * @param agent - live root of the card's Session, as the Host resolved it.
66
+ * @returns the written/retired counts, or `undefined` when nothing was staged.
67
+ */
68
+ apply(agent: Agent): Promise<{
69
+ readonly written: number;
70
+ readonly retired: number;
71
+ } | undefined>;
72
+ /** Discard every waiting decision, returning how many were dropped. */
73
+ reject(): Promise<number | undefined>;
74
+ }
75
+ /** One decision recorded for a card, as the Host stores it. */
76
+ export interface ProposalDecision {
77
+ readonly cardId: string;
78
+ readonly action: string;
79
+ readonly phase: string;
80
+ readonly data?: Readonly<Record<string, unknown>>;
81
+ }
82
+ /** One card as the Host hands it to `reconcile` and `act`. */
83
+ export interface ProposalRef {
84
+ readonly cardId: string;
85
+ readonly action: string;
86
+ readonly title: string;
87
+ readonly brief: string;
88
+ readonly details: ProposalDetails;
89
+ }
90
+ /** What a card action returns to the browser. */
91
+ export type ProposalResult = {
92
+ readonly status: 'accepted';
93
+ } | {
94
+ readonly status: 'settled';
95
+ readonly decision: ProposalDecision;
96
+ } | {
97
+ readonly status: 'refused';
98
+ readonly reason: string;
99
+ } | {
100
+ readonly status: 'unconfirmed';
101
+ readonly reason: string;
102
+ };
103
+ /** The zod-like field validator the Host calls before every action. */
104
+ export interface ProposalDetailsSchema {
105
+ safeParse(value: unknown): {
106
+ readonly success: true;
107
+ readonly data: ProposalDetails;
108
+ } | {
109
+ readonly success: false;
110
+ };
111
+ }
112
+ /** One Host action kind, narrowed to the fields this plugin sets. */
113
+ export interface ProposalKind {
114
+ readonly action: string;
115
+ readonly details: ProposalDetailsSchema;
116
+ readonly verbs: Readonly<Record<string, {
117
+ readonly writes?: true;
118
+ readonly global?: true;
119
+ }>>;
120
+ readonly openPhases?: readonly string[];
121
+ readonly statusGuidance?: string;
122
+ readonly statusFields?: readonly string[];
123
+ reconcile?(agent: Agent, proposal: ProposalRef): Promise<void>;
124
+ act(agent: Agent, proposal: ProposalRef, verb: string, payload: Readonly<Record<string, unknown>> | undefined): Promise<ProposalResult>;
125
+ }
126
+ /** One skill catalog entry, as `ctx.skills` takes it. */
127
+ export interface ProposalSkillCandidate {
128
+ readonly name: string;
129
+ readonly description: string;
130
+ readonly invocation: {
131
+ readonly modelInvocable: boolean;
132
+ readonly userInvocable: boolean;
133
+ };
134
+ readonly source: string;
135
+ readonly provider: string;
136
+ readonly rank: number;
137
+ readonly locator: unknown;
138
+ }
139
+ /** One loaded skill definition. */
140
+ export type ProposalSkillDefinition = Omit<ProposalSkillCandidate, 'rank' | 'locator'> & {
141
+ readonly content: string;
142
+ };
143
+ /** Options a provider receives when listing or loading a skill. */
144
+ export interface ProposalSkillOptions {
145
+ readonly signal?: AbortSignal;
146
+ }
147
+ /** What a provider receives when the registry binds it. */
148
+ export interface ProposalSkillControl {
149
+ readonly signal: AbortSignal;
150
+ readonly invalidate: () => void;
151
+ }
152
+ /** One skill provider, narrowed to what this plugin implements. */
153
+ export interface ProposalSkillProvider {
154
+ readonly name: string;
155
+ readonly list: (options: ProposalSkillOptions) => Promise<readonly ProposalSkillCandidate[]>;
156
+ readonly get: (candidate: ProposalSkillCandidate, options: ProposalSkillOptions) => Promise<ProposalSkillDefinition | undefined>;
157
+ }
158
+ /** The Host action-card service, narrowed to what this kind uses. */
159
+ export interface ProposalCards {
160
+ view(session: Session): {
161
+ readonly decisions: Readonly<Record<string, ProposalDecision>>;
162
+ };
163
+ register(kind: ProposalKind): () => void;
164
+ record(agent: Agent, decision: ProposalDecision): void;
165
+ /** Present only from 0.2.3-alpha.2; the composition checks it before calling. */
166
+ skillProvider(candidate: ProposalSkillCandidate, get: ProposalSkillProvider['get']): (control: ProposalSkillControl) => ProposalSkillProvider;
167
+ }
168
+ /** The Host skill registry, narrowed to provider registration. */
169
+ export interface ProposalSkills {
170
+ registerProvider(create: (control: ProposalSkillControl) => ProposalSkillProvider): () => void;
171
+ }
172
+ /** What the model is told when it loads the skill. */
173
+ export declare const PROPOSAL_SKILL_CONTENT: string;
174
+ /**
175
+ * Register the card kind and the skill that offers it for the caller's lifetime.
176
+ *
177
+ * The caller must run this inside `ctx.inject(['actionCards', 'skills'], …)` and
178
+ * hold the returned disposer in `ctx.effect`; disposing removes both, so an
179
+ * unloaded plugin leaves no half-registered card behind.
180
+ *
181
+ * @param cards - the Host action-card service.
182
+ * @param skills - the Host skill registry.
183
+ * @param runtime - the store seam described by {@link ProposalCardRuntime}.
184
+ * @returns disposer removing the kind and the skill provider.
185
+ */
186
+ export declare function registerProposalCard(cards: ProposalCards, skills: ProposalSkills, runtime: ProposalCardRuntime): () => void;