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
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
|
package/lib/test/extract.test.js
CHANGED
|
@@ -15,7 +15,7 @@ import { tmpdir } from 'node:os';
|
|
|
15
15
|
import { join } from 'node:path';
|
|
16
16
|
import test from 'node:test';
|
|
17
17
|
import { MemoriesRuntime } from '../index.js';
|
|
18
|
-
import { EXTRACT_JSON_SCHEMA, bindEvidence, collectExtractionWindow, collectWindow, parseExtraction, redactSecrets, runExtraction, selectKnownTitles } from '../extract.js';
|
|
18
|
+
import { EXTRACT_JSON_SCHEMA, bindEvidence, collectExtractionWindow, collectWindow, mustCoverCandidates, parseExtraction, redactSecrets, renderMustCover, resolveRelativeTimes, runExtraction, selectKnownTitles } from '../extract.js';
|
|
19
19
|
import { normalizeSettings } from '../config.js';
|
|
20
20
|
import { peakDelayMs } from '../schedule.js';
|
|
21
21
|
/**
|
|
@@ -62,7 +62,7 @@ function transcriptQuote(options) {
|
|
|
62
62
|
const prompt = options.messages
|
|
63
63
|
.map((message) => message.content.filter((block) => block.type === 'text').map((block) => block.text ?? '').join(''))
|
|
64
64
|
.join('\n');
|
|
65
|
-
const line = /(?:^|\n)(?:USER|ASSISTANT): ([^\n]+)/u.exec(prompt)?.[1];
|
|
65
|
+
const line = /(?:^|\n)(?:USER|ASSISTANT): (?:\[[^\]]*\] )?([^\n]+)/u.exec(prompt)?.[1];
|
|
66
66
|
return line === undefined ? undefined : line.trim().slice(0, 160);
|
|
67
67
|
}
|
|
68
68
|
/** Add `quote` to every memory of a canned reply that does not already carry one. */
|
|
@@ -161,6 +161,33 @@ test('parseExtraction keeps the string keys and drops the rest', () => {
|
|
|
161
161
|
// A reply that omits keys is normal: they are an optimization, not a contract.
|
|
162
162
|
assert.deepEqual([...parseExtraction('{"memories":[{"scope":"global","title":"x","body":"y"}]}', 5, 's').drafts[0]?.keys ?? []], []);
|
|
163
163
|
});
|
|
164
|
+
test('mustCoverCandidates names the turns an extractor is most likely to skip', () => {
|
|
165
|
+
const sources = [
|
|
166
|
+
{ seq: 1, text: '你好,今天天气不错。' },
|
|
167
|
+
{ seq: 2, text: '师傅说周五前把报价单发出去,人天按 35 算。' },
|
|
168
|
+
{ seq: 3, text: '行,那就这样。' },
|
|
169
|
+
{ seq: 4, text: '新来的同事叫沈知夏,负责 SAP 投递。' },
|
|
170
|
+
];
|
|
171
|
+
const picked = mustCoverCandidates(sources);
|
|
172
|
+
// The greeting scores nothing; the promise and the new person both make the cut.
|
|
173
|
+
assert.deepEqual(picked.map((row) => row.seq), [2, 4]);
|
|
174
|
+
const rendered = renderMustCover(picked);
|
|
175
|
+
assert.match(rendered ?? '', /本窗必写候选/u);
|
|
176
|
+
assert.match(rendered ?? '', /\[2\]/u);
|
|
177
|
+
assert.match(rendered ?? '', /要么写成一条记忆/u);
|
|
178
|
+
assert.equal(renderMustCover([]), undefined);
|
|
179
|
+
});
|
|
180
|
+
test('resolveRelativeTimes names the absolute day for every relative time', () => {
|
|
181
|
+
// 2026-05-27 is a Wednesday.
|
|
182
|
+
const base = new Date(2026, 4, 27);
|
|
183
|
+
assert.equal(resolveRelativeTimes('前天搬窗边', base), '前天(2026-05-25)搬窗边');
|
|
184
|
+
assert.equal(resolveRelativeTimes('昨天替班', base), '昨天(2026-05-26)替班');
|
|
185
|
+
assert.equal(resolveRelativeTimes('上周五是生日', base), '上周五(2026-05-22)是生日');
|
|
186
|
+
assert.equal(resolveRelativeTimes('下周三交报告', base), '下周三(2026-06-03)交报告');
|
|
187
|
+
// An absolute date is left alone, and an unresolvable word is left alone.
|
|
188
|
+
assert.equal(resolveRelativeTimes('2026-05-25 已记下', base), '2026-05-25 已记下');
|
|
189
|
+
assert.equal(resolveRelativeTimes('上周的事', base), '上周的事');
|
|
190
|
+
});
|
|
164
191
|
test('parseExtraction accepts a bare object, a fenced object, and rejects junk', () => {
|
|
165
192
|
const payload = '{"summary":"The user set up a pnpm workflow.","memories":[{"scope":"global","title":"Prefer pnpm","body":"Use pnpm.","tags":["tooling"]}]}';
|
|
166
193
|
const parsed = parseExtraction(payload, 5, 'session-1');
|
|
@@ -590,7 +617,10 @@ test('a capped window cools down, and retries the moment the cap it blamed chang
|
|
|
590
617
|
yield { type: 'finish', reason: { kind: 'max-tokens' } };
|
|
591
618
|
return;
|
|
592
619
|
}
|
|
593
|
-
|
|
620
|
+
const facts = Array.from({ length: 8 }, (_, index) => ({
|
|
621
|
+
scope: 'project', title: `A fact ${index}`, body: 'A fact.', tags: ['x'], quote: 'worth remembering',
|
|
622
|
+
}));
|
|
623
|
+
yield textChunk(JSON.stringify({ memories: facts }));
|
|
594
624
|
yield stopChunk();
|
|
595
625
|
})();
|
|
596
626
|
},
|
|
@@ -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');
|