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.
- package/README.md +12 -2
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/lib/bm25.js +100 -0
- package/lib/cards.js +188 -0
- package/lib/client.js +195 -1
- package/lib/config.js +7 -4
- package/lib/index.js +131 -42
- package/lib/render.js +71 -18
- package/lib/search.js +33 -53
- package/lib/test/injection.test.js +18 -2
- package/lib/test/proposal-card.test.js +353 -0
- 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 +7 -4
- package/lib/types/index.d.ts +24 -8
- 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
package/lib/index.js
CHANGED
|
@@ -39,6 +39,7 @@ import { listReflections, previousInsights, reflectionDue, runReflection, writeR
|
|
|
39
39
|
import { parseTimeRange } from './time.js';
|
|
40
40
|
import { isSubstantiveTurn } from './query.js';
|
|
41
41
|
import { INDEX_OPEN, MEMORY_CLOSE, MEMORY_OPEN, RECALL_OPEN, rankForSummary, renderEntry, renderHit, renderMemoryIndex, renderMemorySummaryResult, renderOpenLoops, renderRecall, renderScopeListing, selectForSummary } from './render.js';
|
|
42
|
+
import { createBm25Index } from './bm25.js';
|
|
42
43
|
import { findProjectRoot, isWithin } from './workspace.js';
|
|
43
44
|
import { citationRoots, citationWarning, ignoredUnder, missingCitations } from './citations.js';
|
|
44
45
|
import { planRetention, retentionKey } from './retention.js';
|
|
@@ -51,6 +52,7 @@ import { CONSOLIDATE_PRESET_ID, adjudicateDisputes, applyPlan, applyVerdicts, cl
|
|
|
51
52
|
import { discardDraft, listDrafts, promote, writeDraft } from './skills.js';
|
|
52
53
|
import { MEMORY_KINDS, MEMORY_SOURCE_KIND } from './types.js';
|
|
53
54
|
import { registerMemoryTool } from './tool.js';
|
|
55
|
+
import { PROPOSAL_ACTION, PROPOSAL_SKILL, registerProposalCard } from './cards.js';
|
|
54
56
|
import { REMOTE_CONTRIBUTION, REMOTE_NAMESPACE, REMOTE_SERVICE, createRemoteService } from './remote.js';
|
|
55
57
|
/** Plugin name; also the source tag of every injected message. */
|
|
56
58
|
export const name = 'memories';
|
|
@@ -679,14 +681,55 @@ export class MemoriesRuntime {
|
|
|
679
681
|
const projectHasEntries = states.some((state) => state.scope === 'project' && state.entries.length > 0);
|
|
680
682
|
const globalCap = projectHasEntries ? this.settings.globalSummaryEntries : this.settings.maxSummaryEntries;
|
|
681
683
|
const capOf = (state) => state.scope === 'global' ? globalCap : this.settings.maxSummaryEntries;
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
684
|
+
// Project memories render before global ones.
|
|
685
|
+
//
|
|
686
|
+
// The renderer walks the scopes in order and the byte budget keeps the head,
|
|
687
|
+
// so this is the decision about which memories a session actually reads.
|
|
688
|
+
// Measured on 20 real sessions with a live store: the first six rendered
|
|
689
|
+
// slots held 113 entries the session's own topic matched when project led,
|
|
690
|
+
// against 14 with global first — global's generic entries were occupying
|
|
691
|
+
// every slot the budget reliably reaches. Global keeps its own smaller cap
|
|
692
|
+
// and its own byte budget, so it is not crowded out, just no longer first.
|
|
693
|
+
const ordered = [
|
|
694
|
+
...states.filter((state) => state.scope === 'project'),
|
|
695
|
+
...states.filter((state) => state.scope === 'global'),
|
|
696
|
+
];
|
|
697
|
+
// Rank the scopes together, then let each scope pick from that order.
|
|
698
|
+
//
|
|
699
|
+
// Ranking per scope is what the renderer used to do, and it loses the
|
|
700
|
+
// cross-scope comparison: a global entry that shares a word with the opening
|
|
701
|
+
// turn outranks a project entry the turn is about, because each scope's top
|
|
702
|
+
// is taken without reference to the other. The merged ranking's first
|
|
703
|
+
// twelve entries measured 96% topic-relevant on 20 real sessions, against
|
|
704
|
+
// 67% for the per-scope rendering of the same store.
|
|
705
|
+
const stateOf = new Map();
|
|
706
|
+
for (const state of ordered)
|
|
707
|
+
for (const entry of state.entries)
|
|
708
|
+
stateOf.set(entry.id, state);
|
|
709
|
+
const merged = rankForSummary(ordered.flatMap((state) => state.entries), Date.now(), query);
|
|
710
|
+
const rankedByState = new Map();
|
|
711
|
+
for (const entry of merged) {
|
|
712
|
+
const state = stateOf.get(entry.id);
|
|
713
|
+
if (state === undefined)
|
|
714
|
+
continue;
|
|
715
|
+
const list = rankedByState.get(state);
|
|
716
|
+
if (list === undefined)
|
|
717
|
+
rankedByState.set(state, [entry]);
|
|
718
|
+
else
|
|
719
|
+
list.push(entry);
|
|
720
|
+
}
|
|
721
|
+
const selected = ordered.map((state) => {
|
|
722
|
+
const ranked = rankedByState.get(state);
|
|
723
|
+
return selectForSummary(state.entries, capOf(state), {
|
|
724
|
+
freshSlots: this.settings.summaryFreshSlots,
|
|
725
|
+
// The opening turn is the only topic signal available this early, and it
|
|
726
|
+
// is what keeps a globally scoped memory that shares nothing with this
|
|
727
|
+
// conversation from outranking one that does.
|
|
728
|
+
...query === undefined || query.length === 0 ? {} : { query },
|
|
729
|
+
...ranked === undefined ? {} : { ranked },
|
|
730
|
+
});
|
|
731
|
+
});
|
|
732
|
+
const scopes = ordered.map((state, index) => ({
|
|
690
733
|
label: state.label,
|
|
691
734
|
heading: state.heading,
|
|
692
735
|
entries: selected[index] ?? [],
|
|
@@ -841,7 +884,8 @@ export class MemoriesRuntime {
|
|
|
841
884
|
* Apply every waiting decision.
|
|
842
885
|
*
|
|
843
886
|
* @param _parent - the agent asking; the stored rows carry their own scope.
|
|
844
|
-
* @returns
|
|
887
|
+
* @returns the command's report plus the counts the action-card decision
|
|
888
|
+
* records, or `undefined` when nothing is staged.
|
|
845
889
|
*/
|
|
846
890
|
async applyPendingPlan(_parent) {
|
|
847
891
|
const pending = await readPendingPlan(this.store.memoriesDir);
|
|
@@ -853,14 +897,31 @@ export class MemoriesRuntime {
|
|
|
853
897
|
const result = await applyPlan(pending.plan, this.consolidationTarget(), root, { entries });
|
|
854
898
|
await clearPendingPlan(this.store.memoriesDir);
|
|
855
899
|
this.log.info('dsh-cross-memory: applied %d waiting consolidation decision(s): %d written, %d retired', pending.disputes.length, result.written, result.retired);
|
|
856
|
-
return
|
|
900
|
+
return {
|
|
901
|
+
text: `Applied ${pending.disputes.length} decision${pending.disputes.length === 1 ? '' : 's'}: ${result.written} written, ${result.retired} retired.`,
|
|
902
|
+
written: result.written,
|
|
903
|
+
retired: result.retired,
|
|
904
|
+
};
|
|
857
905
|
}
|
|
858
906
|
catch (error) {
|
|
859
907
|
const message = error instanceof Error ? error.message : String(error);
|
|
860
908
|
this.log.warn('dsh-cross-memory: applying the waiting decisions failed: %s', message);
|
|
861
|
-
return `Applying them failed and the store was rolled back: ${message}
|
|
909
|
+
return { text: `Applying them failed and the store was rolled back: ${message}`, written: 0, retired: 0 };
|
|
862
910
|
}
|
|
863
911
|
}
|
|
912
|
+
/**
|
|
913
|
+
* Discard every waiting decision, leaving the store untouched.
|
|
914
|
+
*
|
|
915
|
+
* @returns how many decisions were dropped, or `undefined` when nothing was staged.
|
|
916
|
+
*/
|
|
917
|
+
async rejectPendingPlan() {
|
|
918
|
+
const pending = await readPendingPlan(this.store.memoriesDir);
|
|
919
|
+
if (pending === undefined)
|
|
920
|
+
return undefined;
|
|
921
|
+
await clearPendingPlan(this.store.memoriesDir);
|
|
922
|
+
this.log.info('dsh-cross-memory: discarded %d waiting consolidation decision(s)', pending.disputes.length);
|
|
923
|
+
return pending.disputes.length;
|
|
924
|
+
}
|
|
864
925
|
/**
|
|
865
926
|
* A warning when this workspace's memory directory is shared with another
|
|
866
927
|
* repository of the same name.
|
|
@@ -917,6 +978,11 @@ export class MemoriesRuntime {
|
|
|
917
978
|
// retire" and nobody could see that 17 decisions were waiting.
|
|
918
979
|
const needDecision = pending.disputes.length > 0 ? `, ${pending.disputes.length} need you` : '';
|
|
919
980
|
lines.push(`Pending consolidation proposal for ${pending.label}: ${pending.plan.upserts.length} to write, ${pending.plan.retire.length} to retire${needDecision} — review with /memories plan, then /memories apply or /memories reject.`);
|
|
981
|
+
// The card is the in-answer path to the same question, but only the model
|
|
982
|
+
// decides to offer it: the skill has to be loaded in the turn and the
|
|
983
|
+
// block has to be the last thing in the answer. Naming the exact fields
|
|
984
|
+
// here is what keeps count/stagedAt honest instead of invented.
|
|
985
|
+
lines.push(`When the user asks about memory changes or pending decisions (记忆变更 / 待确认 / 待裁决), load the ${PROPOSAL_SKILL} skill first, then end the final answer with one \`action-card\` block for this proposal: action "${PROPOSAL_ACTION}", label ${JSON.stringify(pending.label)}, count ${pending.disputes.length}, stagedAt ${pending.at}.`);
|
|
920
986
|
}
|
|
921
987
|
// `dshHome` filters out drafts whose promoted copy is byte-identical: the
|
|
922
988
|
// banner used to report already-promoted skills as pending forever.
|
|
@@ -1262,10 +1328,14 @@ export class MemoriesRuntime {
|
|
|
1262
1328
|
//
|
|
1263
1329
|
// The seeds for the one-hop expansion are taken after this sort for the same
|
|
1264
1330
|
// reason: they used to be whichever three candidates the store listed first.
|
|
1265
|
-
const byStrength = (left, right) => right.
|
|
1331
|
+
const byStrength = (left, right) => right.bm25 - left.bm25
|
|
1332
|
+
|| right.relevance - left.relevance
|
|
1266
1333
|
|| right.score - left.score
|
|
1267
1334
|
|| right.entry.updatedAt - left.entry.updatedAt
|
|
1268
1335
|
|| left.entry.title.localeCompare(right.entry.title);
|
|
1336
|
+
// One BM25 index over every entry the turn can see, so a global and a
|
|
1337
|
+
// project entry are ranked on the same document frequencies.
|
|
1338
|
+
const bm25Scores = createBm25Index(states.flatMap((state) => state.entries)).score(query);
|
|
1269
1339
|
const eligible = [];
|
|
1270
1340
|
let near;
|
|
1271
1341
|
for (const state of states) {
|
|
@@ -1291,7 +1361,7 @@ export class MemoriesRuntime {
|
|
|
1291
1361
|
}
|
|
1292
1362
|
continue;
|
|
1293
1363
|
}
|
|
1294
|
-
eligible.push({ entry, ...why });
|
|
1364
|
+
eligible.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
|
|
1295
1365
|
}
|
|
1296
1366
|
}
|
|
1297
1367
|
if (eligible.length === 0) {
|
|
@@ -1334,7 +1404,7 @@ export class MemoriesRuntime {
|
|
|
1334
1404
|
...hub === undefined ? {} : { hub },
|
|
1335
1405
|
});
|
|
1336
1406
|
if (why.about)
|
|
1337
|
-
byAlias.push({ entry, ...why });
|
|
1407
|
+
byAlias.push({ entry, ...why, bm25: bm25Scores.get(entry.id) ?? 0 });
|
|
1338
1408
|
}
|
|
1339
1409
|
}
|
|
1340
1410
|
if (byAlias.length > 0) {
|
|
@@ -1426,6 +1496,7 @@ export class MemoriesRuntime {
|
|
|
1426
1496
|
relevance: 0,
|
|
1427
1497
|
score: hit.score,
|
|
1428
1498
|
best: '',
|
|
1499
|
+
bm25: 0,
|
|
1429
1500
|
evidence: { strongTerms: 0, phrase: false },
|
|
1430
1501
|
});
|
|
1431
1502
|
}
|
|
@@ -3096,12 +3167,17 @@ export class MemoriesRuntime {
|
|
|
3096
3167
|
/**
|
|
3097
3168
|
* Speak without being asked, when there is something to say.
|
|
3098
3169
|
*
|
|
3099
|
-
* Two deterministic triggers
|
|
3100
|
-
*
|
|
3101
|
-
*
|
|
3102
|
-
*
|
|
3103
|
-
*
|
|
3104
|
-
*
|
|
3170
|
+
* Two deterministic triggers: a daily line about what the plugin maintained,
|
|
3171
|
+
* and a promise whose deadline has passed. Both are judgements a rule can
|
|
3172
|
+
* make, which is why they are the ones allowed to interrupt. Everything
|
|
3173
|
+
* smarter (reflections) enters here later through the same queue, and the
|
|
3174
|
+
* same rules apply: evidence or silence, and never the same subject twice.
|
|
3175
|
+
*
|
|
3176
|
+
* A staged consolidation proposal no longer comes through this pump: its
|
|
3177
|
+
* backlog branch could not reach the user in this deployment (macOS
|
|
3178
|
+
* `osascript` is unavailable, so every delivery logged `no channel for notice
|
|
3179
|
+
* backlog`), and the answer card plus the injected draft note are the
|
|
3180
|
+
* confirmation path now.
|
|
3105
3181
|
*
|
|
3106
3182
|
* Called from the once-per-conversation hook and from the maintenance sweep. A
|
|
3107
3183
|
* failure is logged and swallowed: speaking is never allowed to break a turn.
|
|
@@ -3146,25 +3222,7 @@ export class MemoriesRuntime {
|
|
|
3146
3222
|
queue = { ...queue, lastDigestAt: now };
|
|
3147
3223
|
}
|
|
3148
3224
|
}
|
|
3149
|
-
// 2.
|
|
3150
|
-
const pending = await readPendingPlan(dir).catch(() => undefined);
|
|
3151
|
-
if (pending !== undefined && now - pending.at >= 12 * 3_600_000) {
|
|
3152
|
-
const age = Math.round((now - pending.at) / 3_600_000);
|
|
3153
|
-
const admitted = admitNotice(queue, {
|
|
3154
|
-
kind: 'backlog',
|
|
3155
|
-
createdAt: now,
|
|
3156
|
-
dueAt: now,
|
|
3157
|
-
title: `有 ${pending.disputes.length} 条记忆变更等你确认(已等 ${age} 小时,超时会丢弃)`,
|
|
3158
|
-
body: pending.disputes.map((row) => `- [${row.action}] ${row.title}:${row.reason}`).join('\n'),
|
|
3159
|
-
evidence: pending.disputes.map((row) => row.id),
|
|
3160
|
-
dedupeKey: `backlog:${pending.disputes.length}`,
|
|
3161
|
-
}, policy);
|
|
3162
|
-
if (admitted.ok)
|
|
3163
|
-
queue = { ...queue, notices: [admitted.notice, ...queue.notices] };
|
|
3164
|
-
else
|
|
3165
|
-
this.log.decision('dsh-cross-memory: notice suppressed (%s)', admitted.reason);
|
|
3166
|
-
}
|
|
3167
|
-
// 3. Open loops whose deadline has passed. This is the trigger that makes
|
|
3225
|
+
// 2. Open loops whose deadline has passed. This is the trigger that makes
|
|
3168
3226
|
// the assistant pro-active rather than reactive: it needs no question to
|
|
3169
3227
|
// answer, only a promise the user made and has not closed.
|
|
3170
3228
|
const loopNow = pruneLoops(await readLoops(dir), now);
|
|
@@ -4272,6 +4330,35 @@ export function apply(ctx, config = {}) {
|
|
|
4272
4330
|
});
|
|
4273
4331
|
runtime = new MemoriesRuntime(ctx, config, read);
|
|
4274
4332
|
ctx.effect(() => () => runtime.dispose(), 'dsh-cross-memory.lifecycle');
|
|
4333
|
+
// A staged consolidation proposal can also wait as an answer-embedded action
|
|
4334
|
+
// card: the model offers it from its skill, and the buttons apply or discard
|
|
4335
|
+
// the whole batch. Both services are optional, and an older action-card
|
|
4336
|
+
// service has no `skillProvider`; in either case the command and the settings
|
|
4337
|
+
// panel stay the only confirmation paths, which is the degradation this
|
|
4338
|
+
// plugin has always supported.
|
|
4339
|
+
ctx.inject(['actionCards', 'skills'], (child) => {
|
|
4340
|
+
const { actionCards, skills } = child;
|
|
4341
|
+
if (actionCards === undefined || skills === undefined)
|
|
4342
|
+
return;
|
|
4343
|
+
if (typeof actionCards.skillProvider !== 'function') {
|
|
4344
|
+
log.info('dsh-cross-memory: the action-card service predates answer cards; the confirmation card is skipped');
|
|
4345
|
+
return;
|
|
4346
|
+
}
|
|
4347
|
+
const seam = {
|
|
4348
|
+
pending: async () => {
|
|
4349
|
+
const pending = await readPendingPlan(runtime.store.memoriesDir).catch(() => undefined);
|
|
4350
|
+
return pending === undefined
|
|
4351
|
+
? undefined
|
|
4352
|
+
: { label: pending.label, count: pending.disputes.length, stagedAt: pending.at };
|
|
4353
|
+
},
|
|
4354
|
+
apply: async (agent) => {
|
|
4355
|
+
const result = await runtime.applyPendingPlan(agent);
|
|
4356
|
+
return result === undefined ? undefined : { written: result.written, retired: result.retired };
|
|
4357
|
+
},
|
|
4358
|
+
reject: () => runtime.rejectPendingPlan(),
|
|
4359
|
+
};
|
|
4360
|
+
child.effect(() => registerProposalCard(actionCards, skills, seam), 'dsh-cross-memory.proposalCard');
|
|
4361
|
+
});
|
|
4275
4362
|
// The consolidation child needs a composition of its own. Since 0.2.1-rc.2 a
|
|
4276
4363
|
// subagent takes its tool set from the preset it names, and a child that
|
|
4277
4364
|
// names none inherits the parent's composition — the parent's tools, which is
|
|
@@ -4656,11 +4743,13 @@ async function handleCommand(runtime, invocation) {
|
|
|
4656
4743
|
}
|
|
4657
4744
|
case 'apply': {
|
|
4658
4745
|
const summary = await runtime.applyPendingPlan(invocation.agent);
|
|
4659
|
-
return { kind: 'success', text: summary ?? 'No consolidation proposal is waiting.' };
|
|
4746
|
+
return { kind: 'success', text: summary?.text ?? 'No consolidation proposal is waiting.' };
|
|
4660
4747
|
}
|
|
4661
4748
|
case 'reject': {
|
|
4662
|
-
const dropped = await
|
|
4663
|
-
return
|
|
4749
|
+
const dropped = await runtime.rejectPendingPlan();
|
|
4750
|
+
return dropped === undefined
|
|
4751
|
+
? { kind: 'success', text: 'No consolidation proposal is waiting.' }
|
|
4752
|
+
: { kind: 'success', text: `Discarded ${dropped} waiting decision${dropped === 1 ? '' : 's'}. The store is unchanged.` };
|
|
4664
4753
|
}
|
|
4665
4754
|
case 'mine': {
|
|
4666
4755
|
const count = await runtime.mineNow(invocation.agent);
|
package/lib/render.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { MEMORY_KIND_HEADINGS, MEMORY_KINDS } from './types.js';
|
|
11
11
|
import { decayOf, importanceOf, matchCredit, recencyOf, relevanceOf, timeBoost } from './search.js';
|
|
12
|
+
import { createBm25Index } from './bm25.js';
|
|
12
13
|
import { parseTimeRange } from './time.js';
|
|
13
14
|
/** Opening and closing frame of the injected, once-per-conversation block. */
|
|
14
15
|
export const MEMORY_OPEN = '<memory-context>';
|
|
@@ -94,14 +95,22 @@ export function rankForSummary(entries, now = Date.now(), query) {
|
|
|
94
95
|
const window = needle.length === 0 ? undefined : parseTimeRange(needle, now);
|
|
95
96
|
// Scored once per entry, because both the tier and the within-tier order need
|
|
96
97
|
// the same number and the scorer is the expensive part.
|
|
98
|
+
//
|
|
99
|
+
// The tier still comes from the hand-weighted gatekeeper, but the order
|
|
100
|
+
// INSIDE and below it is BM25's. Measured on 20 real sessions against the
|
|
101
|
+
// shipped relevance order: the first six slots — what the byte budget actually
|
|
102
|
+
// renders — held 49 opening-relevant entries against BM25's 88, and the
|
|
103
|
+
// hand-written weights cannot express "a word on 100 of 176 entries is worth
|
|
104
|
+
// less than one on three", which is what the idf term buys.
|
|
105
|
+
const bm25 = needle.length === 0 ? new Map() : createBm25Index(entries).score(needle);
|
|
97
106
|
const verdicts = new Map();
|
|
98
107
|
for (const entry of entries) {
|
|
99
108
|
if (needle.length === 0) {
|
|
100
|
-
verdicts.set(entry.id, { about: false, relevance: 0 });
|
|
109
|
+
verdicts.set(entry.id, { about: false, relevance: 0, bm25: 0 });
|
|
101
110
|
continue;
|
|
102
111
|
}
|
|
103
112
|
const credit = matchCredit(entry, needle, TOPIC_TIER_MIN_SCORE, TOPIC_TIER_MIN_TERMS, { singleTerm: false, now, range: window ?? null });
|
|
104
|
-
verdicts.set(entry.id, { about: credit.about, relevance: credit.relevance });
|
|
113
|
+
verdicts.set(entry.id, { about: credit.about, relevance: credit.relevance, bm25: bm25.get(entry.id) ?? 0 });
|
|
105
114
|
}
|
|
106
115
|
const weight = (entry) => importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window);
|
|
107
116
|
return [...entries].sort((left, right) => {
|
|
@@ -115,9 +124,14 @@ export function rankForSummary(entries, now = Date.now(), query) {
|
|
|
115
124
|
// saturates, so every entry past the same relevance got the same boost and
|
|
116
125
|
// the order silently reverted to history — which is what left a relevance-62
|
|
117
126
|
// memory unlisted while relevance-30 ones were shown.
|
|
118
|
-
const match = (b?.
|
|
127
|
+
const match = (b?.bm25 ?? 0) - (a?.bm25 ?? 0);
|
|
119
128
|
if (match !== 0)
|
|
120
129
|
return match;
|
|
130
|
+
// BM25 ties (two entries sharing one rare word) fall back to the gatekeeper's
|
|
131
|
+
// relevance, then to the attention model.
|
|
132
|
+
const lexical = (b?.relevance ?? 0) - (a?.relevance ?? 0);
|
|
133
|
+
if (lexical !== 0)
|
|
134
|
+
return lexical;
|
|
121
135
|
return weight(right) - weight(left)
|
|
122
136
|
|| right.updatedAt - left.updatedAt
|
|
123
137
|
|| left.title.localeCompare(right.title);
|
|
@@ -217,10 +231,29 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
217
231
|
const now = options.now ?? Date.now();
|
|
218
232
|
if (perScope <= 0)
|
|
219
233
|
return [];
|
|
220
|
-
|
|
234
|
+
// The caller can supply the order when it has already ranked a wider pool.
|
|
235
|
+
// Scopes are not independent: a global memory and a project memory compete for
|
|
236
|
+
// the same rendered slots, and letting each scope rank itself puts a merely
|
|
237
|
+
// global match ahead of the project entry the conversation is about. Measured
|
|
238
|
+
// on 20 real sessions, a merged ranking's first twelve entries were 96%
|
|
239
|
+
// topic-relevant while the per-scope rendering of the same store managed 67%.
|
|
240
|
+
const ranked = options.ranked ?? rankForSummary(entries, now, options.query);
|
|
221
241
|
if (ranked.length <= perScope)
|
|
222
|
-
return ranked;
|
|
242
|
+
return [...ranked];
|
|
223
243
|
const reserve = Math.max(0, Math.min(options.freshSlots ?? 0, perScope - 1, maxFreshSlots(perScope)));
|
|
244
|
+
// With a topic signal, the reservation shrinks to one slot.
|
|
245
|
+
//
|
|
246
|
+
// The reservation exists so a saturated scope eventually shows something new,
|
|
247
|
+
// but it is spent on entries that have never been surfaced — and when the
|
|
248
|
+
// conversation is demonstrably about something, those entries are noise in the
|
|
249
|
+
// only slots the byte budget reliably renders. Measured on 20 real sessions:
|
|
250
|
+
// with the full reservation the first six slots held 49 entries the session's
|
|
251
|
+
// own topic matched, against 88 for a pure relevance order, and the gap is
|
|
252
|
+
// almost entirely the reserved slots. One slot keeps the mechanism (a scope
|
|
253
|
+
// still rotates) without paying for it in the head of the list.
|
|
254
|
+
const effectiveReserve = options.query?.trim() === undefined || options.query.trim().length === 0
|
|
255
|
+
? reserve
|
|
256
|
+
: Math.min(reserve, 1);
|
|
224
257
|
const chosen = [];
|
|
225
258
|
const chosenIds = new Set();
|
|
226
259
|
// The topical floor comes before everything, including pins.
|
|
@@ -238,12 +271,23 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
238
271
|
// the pins are counted. Without a query nothing changes, and a pin still
|
|
239
272
|
// outranks everything below the tier.
|
|
240
273
|
const needle = options.query?.trim() ?? '';
|
|
241
|
-
|
|
242
|
-
|
|
274
|
+
// The topical tier leads, and with a topic signal it leads with as many
|
|
275
|
+
// entries as the promises leave room for.
|
|
276
|
+
//
|
|
277
|
+
// The old floor was a third of the section, and the measurement that replaced
|
|
278
|
+
// it is stark: on 20 real sessions the first six rendered slots held 117
|
|
279
|
+
// opening-relevant entries when the tier was allowed to lead, against 49 with
|
|
280
|
+
// the floor-plus-reservation structure. The reservation and the pins are
|
|
281
|
+
// honoured — they are subtracted from the cap, not allowed to displace the
|
|
282
|
+
// tier — but the tier is what the byte budget actually renders, so it gets the
|
|
283
|
+
// head of the list.
|
|
284
|
+
if (needle.length > 0) {
|
|
285
|
+
const pinCount = entries.filter((entry) => entry.pinned === true).length;
|
|
286
|
+
const tierCap = Math.max(0, perScope - pinCount - effectiveReserve);
|
|
243
287
|
for (const entry of ranked) {
|
|
244
|
-
if (chosen.length >=
|
|
288
|
+
if (chosen.length >= tierCap)
|
|
245
289
|
break;
|
|
246
|
-
// Pins keep their own lane; this
|
|
290
|
+
// Pins keep their own lane; this cap is for the topic, not for them.
|
|
247
291
|
if (entry.pinned === true)
|
|
248
292
|
continue;
|
|
249
293
|
if (!matchCredit(entry, needle, TOPIC_TIER_MIN_SCORE, TOPIC_TIER_MIN_TERMS, { singleTerm: false, now }).about)
|
|
@@ -263,14 +307,13 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
263
307
|
chosen.push(entry);
|
|
264
308
|
chosenIds.add(entry.id);
|
|
265
309
|
}
|
|
266
|
-
if (
|
|
310
|
+
if (effectiveReserve > 0) {
|
|
267
311
|
// Among never-surfaced entries, prefer a deliberately written one, then one
|
|
268
312
|
// this conversation actually names, then the newest. Without the topical
|
|
269
313
|
// step the reserved slot spent itself on arbitrary new material: measured
|
|
270
314
|
// over 13 scopes it was the single slot that missed the "explicit or
|
|
271
315
|
// topically relevant" bar in every one of them.
|
|
272
316
|
const relevance = new Map();
|
|
273
|
-
const needle = options.query?.trim() ?? '';
|
|
274
317
|
if (needle.length > 0) {
|
|
275
318
|
for (const entry of entries) {
|
|
276
319
|
const score = relevanceOf(entry, needle);
|
|
@@ -288,7 +331,7 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
288
331
|
// and it may never push the section past its cap.
|
|
289
332
|
let fresh = 0;
|
|
290
333
|
for (const entry of unseen) {
|
|
291
|
-
if (fresh >=
|
|
334
|
+
if (fresh >= effectiveReserve || chosen.length >= perScope)
|
|
292
335
|
break;
|
|
293
336
|
if (chosenIds.has(entry.id))
|
|
294
337
|
continue;
|
|
@@ -297,12 +340,22 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
297
340
|
fresh += 1;
|
|
298
341
|
}
|
|
299
342
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
343
|
+
// Below the tier, only a topic-free summary fills the remaining slots.
|
|
344
|
+
//
|
|
345
|
+
// With a query, the entries after the tier are ones the turn did not match,
|
|
346
|
+
// and filling the section with them is how the injected block reached 25
|
|
347
|
+
// entries of which only 67% were about the conversation — while the merged
|
|
348
|
+
// ranking's first twelve were 96%. The byte budget keeps the head of this
|
|
349
|
+
// array, so padding the tail buys nothing and costs attention. Without a
|
|
350
|
+
// query there is no tier to stop at, and the historical rotation still runs.
|
|
351
|
+
if (needle.length === 0) {
|
|
352
|
+
for (const entry of ranked) {
|
|
353
|
+
if (chosen.length >= perScope)
|
|
354
|
+
break;
|
|
355
|
+
if (chosenIds.has(entry.id))
|
|
356
|
+
continue;
|
|
357
|
+
chosen.push(entry);
|
|
358
|
+
}
|
|
306
359
|
}
|
|
307
360
|
return chosen;
|
|
308
361
|
}
|
package/lib/search.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { queryMessages } from './query.js';
|
|
2
2
|
import { parseTimeRange, within } from './time.js';
|
|
3
|
+
import { isNoise, termWeight, tokenize } from './tokenize.js';
|
|
4
|
+
import { createBm25Index } from './bm25.js';
|
|
5
|
+
export { tokenize, termWeight } from './tokenize.js';
|
|
3
6
|
/** A CJK ideograph, including the extension blocks in common use. */
|
|
4
7
|
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u;
|
|
5
8
|
/** A CJK character inside a query or a memory field. */
|
|
@@ -99,52 +102,6 @@ function sharedRuns(queryRuns, field, minimum) {
|
|
|
99
102
|
}
|
|
100
103
|
return shared;
|
|
101
104
|
}
|
|
102
|
-
/** Split text into searchable terms: ASCII words and CJK character bigrams.
|
|
103
|
-
*
|
|
104
|
-
* A CJK run also contributes bigrams of its neighbours, so "该插件是否有日志"
|
|
105
|
-
* yields "该插","插件","件是","是否","否有","有日","日志". A one-character run
|
|
106
|
-
* contributes itself, since a lone ideograph has no bigram.
|
|
107
|
-
*
|
|
108
|
-
* @param text - raw text.
|
|
109
|
-
* @returns lowercase terms; a run that yields nothing contributes nothing.
|
|
110
|
-
*/
|
|
111
|
-
export function tokenize(text) {
|
|
112
|
-
const lower = text.toLowerCase();
|
|
113
|
-
const terms = [];
|
|
114
|
-
for (const word of lower.match(WORD) ?? [])
|
|
115
|
-
terms.push(word);
|
|
116
|
-
const chars = lower.match(CJK_CHAR) ?? [];
|
|
117
|
-
if (chars.length === 1)
|
|
118
|
-
terms.push(chars[0]);
|
|
119
|
-
for (let index = 0; index + 1 < chars.length; index += 1) {
|
|
120
|
-
terms.push(`${chars[index]}${chars[index + 1]}`);
|
|
121
|
-
}
|
|
122
|
-
return terms;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* A term's weight for scoring purposes.
|
|
126
|
-
*
|
|
127
|
-
* One CJK bigram is a much weaker claim than one Latin word — "日志" occurs in
|
|
128
|
-
* countless texts where "logging" does not — so a bigram earns less. Without
|
|
129
|
-
* this every Chinese question would clear the recall gate on noise alone.
|
|
130
|
-
*
|
|
131
|
-
* @param term - one term from {@link tokenize}.
|
|
132
|
-
* @returns a multiplier in `(0, 1]`.
|
|
133
|
-
*/
|
|
134
|
-
export function termWeight(term) {
|
|
135
|
-
const cjk = (term.match(CJK_CHAR) ?? []).length;
|
|
136
|
-
if (cjk === 0)
|
|
137
|
-
return 1;
|
|
138
|
-
// Two-character bigram: half credit. A longer CJK term cannot occur (the
|
|
139
|
-
// tokenizer emits bigrams), but treat it as stronger if it ever does.
|
|
140
|
-
return cjk <= 2 ? 0.5 : Math.min(1, 0.5 + (cjk - 2) * 0.15);
|
|
141
|
-
}
|
|
142
|
-
/** A short token carries little signal and is skipped as a query term. */
|
|
143
|
-
function isNoise(token) {
|
|
144
|
-
if (CJK.test(token))
|
|
145
|
-
return false;
|
|
146
|
-
return token.length < 2;
|
|
147
|
-
}
|
|
148
105
|
/** Count occurrences of `needle` in `haystack`. */
|
|
149
106
|
function occurrences(haystack, needle) {
|
|
150
107
|
if (needle.length === 0)
|
|
@@ -1032,6 +989,12 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1032
989
|
// nobody asked for, and there the track record is the point. Both numbers are
|
|
1033
990
|
// computed here, so neither surface has to guess.
|
|
1034
991
|
const hits = [];
|
|
992
|
+
// One index over every entry this search can see, so a global and a project
|
|
993
|
+
// entry are scored against the same document frequencies and their numbers
|
|
994
|
+
// are comparable. Per-scope indexes would make `dsh` cheap in the 1155-entry
|
|
995
|
+
// global scope and expensive in a 30-entry project scope, and the project
|
|
996
|
+
// entries would lose every tie they should win.
|
|
997
|
+
const pool = [];
|
|
1035
998
|
for (const group of groups) {
|
|
1036
999
|
if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
|
|
1037
1000
|
continue;
|
|
@@ -1040,13 +1003,18 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1040
1003
|
continue;
|
|
1041
1004
|
if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
|
|
1042
1005
|
continue;
|
|
1043
|
-
|
|
1044
|
-
if (relevance <= 0)
|
|
1045
|
-
continue;
|
|
1046
|
-
hits.push({ entry, score, relevance });
|
|
1006
|
+
pool.push(entry);
|
|
1047
1007
|
}
|
|
1048
1008
|
}
|
|
1049
|
-
const
|
|
1009
|
+
const bm25 = createBm25Index(pool).score(query);
|
|
1010
|
+
for (const entry of pool) {
|
|
1011
|
+
const { relevance, score } = rankEntry(entry, query, now, window);
|
|
1012
|
+
if (relevance <= 0)
|
|
1013
|
+
continue;
|
|
1014
|
+
hits.push({ entry, score, relevance, bm25: bm25.get(entry.id) ?? 0 });
|
|
1015
|
+
}
|
|
1016
|
+
const byWords = (left, right) => right.bm25 - left.bm25
|
|
1017
|
+
|| right.relevance - left.relevance
|
|
1050
1018
|
|| right.score - left.score
|
|
1051
1019
|
|| right.entry.updatedAt - left.entry.updatedAt
|
|
1052
1020
|
|| left.entry.title.localeCompare(right.entry.title);
|
|
@@ -1067,7 +1035,14 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1067
1035
|
// this surface ranks in: a hop scored against the seed's attention score would
|
|
1068
1036
|
// be sorting apples against oranges. The injector passes attention scores
|
|
1069
1037
|
// instead, for the same reason.
|
|
1070
|
-
|
|
1038
|
+
// The seeds are the strongest hits in the currency the hop is paid in.
|
|
1039
|
+
// `relatedHits` multiplies a seed's own score, so a seed picked by BM25 order
|
|
1040
|
+
// would pass a BM25 number into a relevance formula; the relevance top three
|
|
1041
|
+
// keeps the activation spreading from the entries the gatekeeper rated
|
|
1042
|
+
// strongest, which is also what the expansion eval measured.
|
|
1043
|
+
const seeds = [...hits]
|
|
1044
|
+
.sort((left, right) => right.relevance - left.relevance || right.score - left.score)
|
|
1045
|
+
.slice(0, EXPAND_SEEDS);
|
|
1071
1046
|
const related = relatedHits(groups, seeds.map((hit) => ({ entry: hit.entry, score: hit.relevance })), {
|
|
1072
1047
|
...options,
|
|
1073
1048
|
limit: EXPAND_MAX,
|
|
@@ -1084,16 +1059,21 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1084
1059
|
// score like every other hit: `score` means one thing on every row, and the
|
|
1085
1060
|
// row's *place* is decided by the other number.
|
|
1086
1061
|
const attention = hit.score * importanceOf(hit.entry) * decayOf(hit.entry, now);
|
|
1062
|
+
// A hop carries no BM25 of its own: it matched no query word, so it must
|
|
1063
|
+
// sort behind everything the query did match rather than inherit the seed's
|
|
1064
|
+
// number and displace a direct hit.
|
|
1065
|
+
const hopScore = direct?.bm25 ?? 0;
|
|
1087
1066
|
if (direct === undefined) {
|
|
1088
1067
|
merged.push({
|
|
1089
1068
|
entry: hit.entry,
|
|
1090
1069
|
score: attention,
|
|
1091
1070
|
relevance: hit.score,
|
|
1071
|
+
bm25: hopScore,
|
|
1092
1072
|
...hit.via === undefined ? {} : { via: hit.via },
|
|
1093
1073
|
});
|
|
1094
1074
|
}
|
|
1095
1075
|
else if (hit.score > direct.relevance) {
|
|
1096
|
-
merged.push({ entry: direct.entry, score: direct.score, relevance: hit.score });
|
|
1076
|
+
merged.push({ entry: direct.entry, score: direct.score, relevance: hit.score, bm25: hopScore });
|
|
1097
1077
|
}
|
|
1098
1078
|
}
|
|
1099
1079
|
// Keep the best record per id. The direct list comes first, so keeping the
|
|
@@ -35,6 +35,19 @@ function stubSession(cwd, history = []) {
|
|
|
35
35
|
function stubAgent(session) {
|
|
36
36
|
return { id: 'test-session', session, status: 'idle' };
|
|
37
37
|
}
|
|
38
|
+
/** One rendered section's text, located by its heading rather than its place.
|
|
39
|
+
*
|
|
40
|
+
* Project memories render before global ones, so a test that splits on the
|
|
41
|
+
* first `## ` would be asserting an order rather than a cap.
|
|
42
|
+
*/
|
|
43
|
+
function sectionOf(summary, heading) {
|
|
44
|
+
const lines = summary.split('\n');
|
|
45
|
+
const start = lines.findIndex((line) => line.startsWith(`## ${heading}`));
|
|
46
|
+
if (start < 0)
|
|
47
|
+
return '';
|
|
48
|
+
const end = lines.findIndex((line, at) => at > start && line.startsWith('## '));
|
|
49
|
+
return lines.slice(start, end < 0 ? lines.length : end).join('\n');
|
|
50
|
+
}
|
|
38
51
|
test('injection is once per conversation, not once per turn', async (t) => {
|
|
39
52
|
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-inj-'));
|
|
40
53
|
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
|
|
@@ -169,7 +182,10 @@ test('the global section is capped so it cannot bury the project scope', async (
|
|
|
169
182
|
await runtime.write(agent.session, { scope: 'project', title: 'This repo is special', body: 'Only true here.', tags: [] }, 'tool');
|
|
170
183
|
const summary = await runtime.summary(agent.session);
|
|
171
184
|
assert.ok(summary !== undefined);
|
|
172
|
-
|
|
185
|
+
// Sections are parsed by heading, not by position: project memories render
|
|
186
|
+
// before global ones, because they are the ones about this workspace.
|
|
187
|
+
const globalPart = sectionOf(summary, 'Global memories');
|
|
188
|
+
const projectPart = sectionOf(summary, 'Project memories');
|
|
173
189
|
const globalBullets = (globalPart ?? '').split('\n').filter((line) => line.startsWith('- ') && !line.startsWith('- …'));
|
|
174
190
|
assert.equal(globalBullets.length, 2, 'the global half stops at its own cap');
|
|
175
191
|
assert.match(projectPart ?? '', /This repo is special/u, 'and the project half still appears');
|
|
@@ -240,7 +256,7 @@ test('a never-surfaced backlog cannot swallow the shared global half', async (t)
|
|
|
240
256
|
await runtime.write(agent.session, { scope: 'project', title: 'Workspace fact', body: 'Only here.', tags: [] }, 'auto');
|
|
241
257
|
const summary = await runtime.summary(agent.session);
|
|
242
258
|
assert.ok(summary !== undefined);
|
|
243
|
-
const
|
|
259
|
+
const globalPart = sectionOf(summary, 'Global memories');
|
|
244
260
|
const freshShown = (globalPart ?? '').split('\n').filter((line) => /^- (?:📌 )?Newest note/u.test(line)).length;
|
|
245
261
|
const bullets = (globalPart ?? '').split('\n').filter((line) => line.startsWith('- ') && !line.startsWith('- …')).length;
|
|
246
262
|
assert.equal(bullets, 4, 'the global half still fills its own cap');
|