dsh-cross-memory 0.2.3 → 0.2.4
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 +92 -94
- package/docs/DETAIL.md +75 -10
- package/docs/DETAIL.zh.md +74 -13
- package/lib/backfill.js +1 -0
- package/lib/client.js +6 -1
- package/lib/config.js +50 -18
- package/lib/extract.js +133 -25
- package/lib/index.js +194 -43
- package/lib/loops.js +9 -4
- package/lib/render.js +2 -2
- package/lib/search.js +141 -18
- package/lib/storage.js +8 -0
- package/lib/sync.js +96 -1
- package/lib/test/extract.test.js +59 -2
- package/lib/test/recall.test.js +59 -26
- package/lib/test/retrieval.test.js +46 -1
- package/lib/test/rotation.test.js +5 -2
- package/lib/test/sync.test.js +46 -1
- package/lib/tool.js +9 -1
- package/lib/types/backfill.d.ts +10 -0
- package/lib/types/config.d.ts +49 -15
- package/lib/types/extract.d.ts +95 -3
- package/lib/types/index.d.ts +52 -4
- package/lib/types/search.d.ts +68 -0
- package/lib/types/sync.d.ts +12 -0
- package/lib/types/types.d.ts +8 -0
- package/package.json +1 -1
package/lib/search.js
CHANGED
|
@@ -35,6 +35,7 @@ const WORD = /[a-z0-9_]+/gu;
|
|
|
35
35
|
export const FIELD_WEIGHTS = {
|
|
36
36
|
title: 40,
|
|
37
37
|
keys: 26,
|
|
38
|
+
entities: 24,
|
|
38
39
|
tags: 20,
|
|
39
40
|
appliesTo: 18,
|
|
40
41
|
body: 12,
|
|
@@ -49,6 +50,7 @@ export const FIELD_WEIGHTS = {
|
|
|
49
50
|
export const TERM_WEIGHTS = {
|
|
50
51
|
title: 8,
|
|
51
52
|
keys: 7,
|
|
53
|
+
entities: 7,
|
|
52
54
|
tags: 6,
|
|
53
55
|
appliesTo: 5,
|
|
54
56
|
body: 2,
|
|
@@ -164,17 +166,20 @@ function searchable(entry) {
|
|
|
164
166
|
const title = entry.title.toLowerCase();
|
|
165
167
|
const body = entry.body.toLowerCase();
|
|
166
168
|
const keys = entry.keys.join(' ').toLowerCase();
|
|
169
|
+
const entities = (entry.entities ?? []).join(' ').toLowerCase();
|
|
167
170
|
const tags = entry.tags.join(' ').toLowerCase();
|
|
168
171
|
const appliesTo = (entry.appliesTo ?? '').toLowerCase();
|
|
169
172
|
return {
|
|
170
173
|
title,
|
|
171
174
|
body,
|
|
172
175
|
keys,
|
|
176
|
+
entities,
|
|
173
177
|
tags,
|
|
174
178
|
appliesTo,
|
|
175
179
|
titleWords: words(title),
|
|
176
180
|
bodyWords: words(body),
|
|
177
181
|
keyWords: words(keys),
|
|
182
|
+
entityWords: words(entities),
|
|
178
183
|
tagWords: words(tags),
|
|
179
184
|
appliesWords: words(appliesTo),
|
|
180
185
|
};
|
|
@@ -236,7 +241,7 @@ export function termIndex(entries) {
|
|
|
236
241
|
};
|
|
237
242
|
entries.forEach((entry, at) => {
|
|
238
243
|
const fields = searchable(entry);
|
|
239
|
-
for (const text of [fields.title, fields.body, fields.keys, fields.tags, fields.appliesTo]) {
|
|
244
|
+
for (const text of [fields.title, fields.body, fields.keys, fields.entities, fields.tags, fields.appliesTo]) {
|
|
240
245
|
for (const term of tokenize(text))
|
|
241
246
|
add(term, at);
|
|
242
247
|
// A single CJK character is only reachable through `includes`, which a
|
|
@@ -284,31 +289,37 @@ export function prefilterEntries(entries, query) {
|
|
|
284
289
|
* @param normalized - one lowercased, trimmed query string.
|
|
285
290
|
* @returns the score and the evidence behind it.
|
|
286
291
|
*/
|
|
287
|
-
function matchOne(entry, normalized, hub) {
|
|
292
|
+
function matchOne(entry, normalized, hub, only) {
|
|
288
293
|
const fields = searchable(entry);
|
|
294
|
+
/** Whether one field may be scored at all; an absent restriction allows all. */
|
|
295
|
+
const on = (field) => only === undefined || only.has(field);
|
|
289
296
|
let score = 0;
|
|
290
297
|
// The whole query as a phrase. CJK quirk: `tags`/`keys` hold several values in
|
|
291
298
|
// one string, and Japanese/Chinese text has no word boundaries, so a phrase
|
|
292
299
|
// test is meaningful there; for Latin fields it means the query is a phrase
|
|
293
300
|
// in that field, which is exactly the strong signal it should be.
|
|
294
301
|
let phrase = false;
|
|
295
|
-
if (matches(fields.title, fields.titleWords, normalized)) {
|
|
302
|
+
if (on('title') && matches(fields.title, fields.titleWords, normalized)) {
|
|
296
303
|
score += FIELD_WEIGHTS.title;
|
|
297
304
|
phrase = true;
|
|
298
305
|
}
|
|
299
|
-
if (matches(fields.keys, fields.keyWords, normalized)) {
|
|
306
|
+
if (on('keys') && matches(fields.keys, fields.keyWords, normalized)) {
|
|
300
307
|
score += FIELD_WEIGHTS.keys;
|
|
301
308
|
phrase = true;
|
|
302
309
|
}
|
|
303
|
-
if (matches(fields.
|
|
310
|
+
if (on('entities') && matches(fields.entities, fields.entityWords, normalized)) {
|
|
311
|
+
score += FIELD_WEIGHTS.entities;
|
|
312
|
+
phrase = true;
|
|
313
|
+
}
|
|
314
|
+
if (on('tags') && matches(fields.tags, fields.tagWords, normalized)) {
|
|
304
315
|
score += FIELD_WEIGHTS.tags;
|
|
305
316
|
phrase = true;
|
|
306
317
|
}
|
|
307
|
-
if (matches(fields.appliesTo, fields.appliesWords, normalized)) {
|
|
318
|
+
if (on('appliesTo') && matches(fields.appliesTo, fields.appliesWords, normalized)) {
|
|
308
319
|
score += FIELD_WEIGHTS.appliesTo;
|
|
309
320
|
phrase = true;
|
|
310
321
|
}
|
|
311
|
-
if (matches(fields.body, fields.bodyWords, normalized))
|
|
322
|
+
if (on('body') && matches(fields.body, fields.bodyWords, normalized))
|
|
312
323
|
score += FIELD_WEIGHTS.body;
|
|
313
324
|
const strong = new Set();
|
|
314
325
|
// Only the strong fields feed the evidence count: a term in the BODY is
|
|
@@ -316,7 +327,12 @@ function matchOne(entry, normalized, hub) {
|
|
|
316
327
|
// word is the weakest claim available.
|
|
317
328
|
const queryRuns = cjkRuns(normalized);
|
|
318
329
|
const cjkBacked = new Set();
|
|
319
|
-
|
|
330
|
+
const strongFields = [
|
|
331
|
+
['title', fields.title], ['keys', fields.keys], ['entities', fields.entities], ['tags', fields.tags], ['appliesTo', fields.appliesTo],
|
|
332
|
+
];
|
|
333
|
+
for (const [name, field] of strongFields) {
|
|
334
|
+
if (!on(name))
|
|
335
|
+
continue;
|
|
320
336
|
for (const run of sharedRuns(queryRuns, field, MIN_SHARED_RUN)) {
|
|
321
337
|
// Every bigram of a shared run is marked, so a query sharing 插件日志的
|
|
322
338
|
// counts 插件, 插件日, and 日志 rather than one anonymous run.
|
|
@@ -329,19 +345,23 @@ function matchOne(entry, normalized, hub) {
|
|
|
329
345
|
continue;
|
|
330
346
|
const weight = termWeight(term);
|
|
331
347
|
let strongHit = false;
|
|
332
|
-
if (matches(fields.title, fields.titleWords, term)) {
|
|
348
|
+
if (on('title') && matches(fields.title, fields.titleWords, term)) {
|
|
333
349
|
score += (TERM_WEIGHTS.title + (CJK.test(term) ? 0 : occurrences(fields.title, term))) * weight;
|
|
334
350
|
strongHit = true;
|
|
335
351
|
}
|
|
336
|
-
if (matches(fields.keys, fields.keyWords, term)) {
|
|
352
|
+
if (on('keys') && matches(fields.keys, fields.keyWords, term)) {
|
|
337
353
|
score += TERM_WEIGHTS.keys * weight;
|
|
338
354
|
strongHit = true;
|
|
339
355
|
}
|
|
340
|
-
if (matches(fields.
|
|
356
|
+
if (on('entities') && matches(fields.entities, fields.entityWords, term)) {
|
|
357
|
+
score += TERM_WEIGHTS.entities * weight;
|
|
358
|
+
strongHit = true;
|
|
359
|
+
}
|
|
360
|
+
if (on('tags') && matches(fields.tags, fields.tagWords, term)) {
|
|
341
361
|
score += TERM_WEIGHTS.tags * weight;
|
|
342
362
|
strongHit = true;
|
|
343
363
|
}
|
|
344
|
-
if (matches(fields.appliesTo, fields.appliesWords, term)) {
|
|
364
|
+
if (on('appliesTo') && matches(fields.appliesTo, fields.appliesWords, term)) {
|
|
345
365
|
score += TERM_WEIGHTS.appliesTo * weight;
|
|
346
366
|
strongHit = true;
|
|
347
367
|
}
|
|
@@ -354,7 +374,8 @@ function matchOne(entry, normalized, hub) {
|
|
|
354
374
|
strong.add(term);
|
|
355
375
|
}
|
|
356
376
|
}
|
|
357
|
-
|
|
377
|
+
if (on('body'))
|
|
378
|
+
score += Math.min(BODY_TERM_CAP, occurrences(fields.body, term)) * TERM_WEIGHTS.body * weight;
|
|
358
379
|
}
|
|
359
380
|
return { score, evidence: { strongTerms: strong.size, phrase } };
|
|
360
381
|
}
|
|
@@ -385,14 +406,14 @@ export function relevanceOfOne(entry, query) {
|
|
|
385
406
|
return matchOf(entry, query).score;
|
|
386
407
|
}
|
|
387
408
|
/** Score every candidate query of a turn and keep the strongest. */
|
|
388
|
-
function bestMatch(entry, query, hub) {
|
|
409
|
+
function bestMatch(entry, query, hub, only) {
|
|
389
410
|
const messages = queryMessages(query);
|
|
390
411
|
let bestScore = 0;
|
|
391
412
|
let bestEvidence = { strongTerms: 0, phrase: false };
|
|
392
413
|
let best = '';
|
|
393
414
|
let mentions = 0;
|
|
394
415
|
for (const message of messages) {
|
|
395
|
-
const { score, evidence } = matchOne(entry, message, hub);
|
|
416
|
+
const { score, evidence } = matchOne(entry, message, hub, only);
|
|
396
417
|
if (score > 0)
|
|
397
418
|
mentions += 1;
|
|
398
419
|
if (score > bestScore || (score === bestScore && evidence.strongTerms > bestEvidence.strongTerms)) {
|
|
@@ -696,21 +717,69 @@ export function matchCredit(entry, query, minScore, minTerms, options = {}) {
|
|
|
696
717
|
const now = options.now ?? Date.now();
|
|
697
718
|
const singleTerm = options.singleTerm ?? true;
|
|
698
719
|
const window = options.range === undefined ? parseTimeRange(query, now) : options.range ?? undefined;
|
|
699
|
-
const
|
|
720
|
+
const only = options.fields === undefined ? undefined : new Set(options.fields);
|
|
721
|
+
const match = bestMatch(entry, query, options.hub, only);
|
|
700
722
|
const distinctive = match.relevance >= minScore * QUALIFIED_SCORE_FACTOR;
|
|
723
|
+
// A turn that NAMES one of the memory's entities is about it even when nothing
|
|
724
|
+
// else overlaps: 「北街南街分别买了什么」 shares only 街 with a memory filed as
|
|
725
|
+
// 「南街文具店补买描图纸」, and the entity list is what makes that reachable.
|
|
726
|
+
const entityHit = only === undefined || only.has('entities') ? sharesEntity(entry, query) : false;
|
|
701
727
|
const credited = match.evidence.phrase
|
|
728
|
+
|| entityHit
|
|
702
729
|
|| match.evidence.strongTerms >= minTerms
|
|
703
730
|
|| (singleTerm && match.evidence.strongTerms >= 1 && distinctive);
|
|
704
731
|
return {
|
|
705
|
-
about: match.relevance >= minScore && credited,
|
|
732
|
+
about: (match.relevance >= minScore && credited) || entityHit,
|
|
706
733
|
distinctive,
|
|
707
734
|
credited,
|
|
708
|
-
relevance: match.relevance,
|
|
735
|
+
relevance: entityHit ? Math.max(match.relevance, minScore) : match.relevance,
|
|
709
736
|
best: match.best,
|
|
710
737
|
evidence: match.evidence,
|
|
711
738
|
score: match.relevance * importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window),
|
|
712
739
|
};
|
|
713
740
|
}
|
|
741
|
+
/**
|
|
742
|
+
* Whether the query names one of the entry's entities.
|
|
743
|
+
*
|
|
744
|
+
* Entities are exact names, so the test is a substring match on each query term
|
|
745
|
+
* (a CJK bigram or a Latin word) against the entity list. A single shared
|
|
746
|
+
* character is not enough: 「票」 alone would make every receipt memory answer
|
|
747
|
+
* every question about tickets.
|
|
748
|
+
*
|
|
749
|
+
* @param entry - the memory whose entity list is tested.
|
|
750
|
+
* @param query - the turn.
|
|
751
|
+
* @returns true when at least one query term appears in the entity list.
|
|
752
|
+
*/
|
|
753
|
+
export function sharesEntity(entry, query) {
|
|
754
|
+
const entities = (entry.entities ?? []).join(' ').toLowerCase();
|
|
755
|
+
if (entities.trim().length === 0)
|
|
756
|
+
return false;
|
|
757
|
+
for (const term of tokenize(query)) {
|
|
758
|
+
if (term.length < 2)
|
|
759
|
+
continue;
|
|
760
|
+
if (entities.includes(term))
|
|
761
|
+
return true;
|
|
762
|
+
}
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* The relevance floor an alias-only match must clear, as a share of the normal one.
|
|
767
|
+
*
|
|
768
|
+
* An alias pass scores `keys` and `appliesTo` only, so the full floor is
|
|
769
|
+
* unreachable by construction. Measured with `recallMinScore` 9 against this
|
|
770
|
+
* scorer: one CJK alias term scores 6 at most (7×0.5 in `keys` plus 5×0.5 in
|
|
771
|
+
* `appliesTo`) and one Latin word 12, while the strict gate needs 9 — so keeping
|
|
772
|
+
* the same number would have let the fallback fire for English turns and never
|
|
773
|
+
* for Chinese ones, the language most of this store is written in. That is the
|
|
774
|
+
* same "dead in practice" failure a keys-only search had, one layer down.
|
|
775
|
+
*
|
|
776
|
+
* Half the floor, and deliberately no lower: with one CJK term in `keys` alone
|
|
777
|
+
* the pass scores 3.5 and stays refused, so an alias has to be filed in two of
|
|
778
|
+
* the scored fields before it can carry a recall. The structural rule (a
|
|
779
|
+
* substantive term, meaning a CJK pair inside a shared run of three characters,
|
|
780
|
+
* or a Latin word of three) and the hub discount are unchanged.
|
|
781
|
+
*/
|
|
782
|
+
export const ALIAS_FLOOR_SHARE = 0.5;
|
|
714
783
|
/**
|
|
715
784
|
* Query terms too common in one scope to count as evidence.
|
|
716
785
|
*
|
|
@@ -1038,6 +1107,60 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1038
1107
|
}
|
|
1039
1108
|
return [...unique.values()].sort(byWords).slice(0, limit);
|
|
1040
1109
|
}
|
|
1110
|
+
/**
|
|
1111
|
+
* The aliases and tags a store files memories under, ranked against one query.
|
|
1112
|
+
*
|
|
1113
|
+
* The main search is lexical, so a query written in the user's words finds
|
|
1114
|
+
* nothing when the store was filed under the product's words: the model then
|
|
1115
|
+
* reports "no memories match" and stops, although the memory exists under a
|
|
1116
|
+
* name it did not guess. Re-running the search with different words is the
|
|
1117
|
+
* only fix, and this is what makes that possible without a model call —
|
|
1118
|
+
* `keys` and `tags` already hold every other name for every memory.
|
|
1119
|
+
*
|
|
1120
|
+
* A hint, never a result: the terms it returns are vocabulary, not claims, so
|
|
1121
|
+
* a caller must not present them as matches.
|
|
1122
|
+
*
|
|
1123
|
+
* @param groups - per-scope entry lists.
|
|
1124
|
+
* @param query - the query that found nothing.
|
|
1125
|
+
* @param limit - most terms to return.
|
|
1126
|
+
* @returns shared terms first, then the most widely used ones.
|
|
1127
|
+
*/
|
|
1128
|
+
export function suggestAliases(groups, query, limit = 12) {
|
|
1129
|
+
if (limit <= 0)
|
|
1130
|
+
return [];
|
|
1131
|
+
const counts = new Map();
|
|
1132
|
+
for (const group of groups) {
|
|
1133
|
+
for (const entry of group.entries) {
|
|
1134
|
+
for (const value of [...entry.keys, ...entry.tags]) {
|
|
1135
|
+
const term = value.trim().toLowerCase();
|
|
1136
|
+
if (term.length === 0)
|
|
1137
|
+
continue;
|
|
1138
|
+
counts.set(term, (counts.get(term) ?? 0) + 1);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
if (counts.size === 0)
|
|
1143
|
+
return [];
|
|
1144
|
+
const queryTerms = [...new Set(tokenize(query))];
|
|
1145
|
+
const scored = [];
|
|
1146
|
+
for (const [term, carriers] of counts) {
|
|
1147
|
+
let matched = 0;
|
|
1148
|
+
for (const item of queryTerms) {
|
|
1149
|
+
// Character-level containment, deliberately: an alias is usually longer
|
|
1150
|
+
// than one query token ("日志轮转" against the bigram 日志), and that
|
|
1151
|
+
// partial overlap is exactly what tells the caller to retry.
|
|
1152
|
+
if (item.length > 0 && term.includes(item))
|
|
1153
|
+
matched += 1;
|
|
1154
|
+
}
|
|
1155
|
+
scored.push({ term, carriers, matched });
|
|
1156
|
+
}
|
|
1157
|
+
const overlapping = scored.filter((item) => item.matched > 0);
|
|
1158
|
+
const pool = overlapping.length > 0 ? overlapping : scored;
|
|
1159
|
+
pool.sort((left, right) => right.matched - left.matched
|
|
1160
|
+
|| right.carriers - left.carriers
|
|
1161
|
+
|| left.term.localeCompare(right.term));
|
|
1162
|
+
return pool.slice(0, limit);
|
|
1163
|
+
}
|
|
1041
1164
|
/**
|
|
1042
1165
|
* Select entries without a text query — used by `memory_search`'s browse mode
|
|
1043
1166
|
* and by the injector.
|
package/lib/storage.js
CHANGED
|
@@ -119,6 +119,7 @@ export const LEGACY_PROJECT_SLUG = /^.+?-[0-9a-f]{8}$/u;
|
|
|
119
119
|
export function formatEntry(entry) {
|
|
120
120
|
const tags = entry.tags.length > 0 ? `tags: ${entry.tags.join(', ')}` : 'tags:';
|
|
121
121
|
const keys = entry.keys.length > 0 ? `keys: ${entry.keys.join(', ')}` : undefined;
|
|
122
|
+
const entities = entry.entities !== undefined && entry.entities.length > 0 ? `entities: ${entry.entities.join(', ')}` : undefined;
|
|
122
123
|
return [
|
|
123
124
|
FENCE,
|
|
124
125
|
`id: ${entry.id}`,
|
|
@@ -127,6 +128,7 @@ export function formatEntry(entry) {
|
|
|
127
128
|
`title: ${entry.title}`,
|
|
128
129
|
tags,
|
|
129
130
|
...keys === undefined ? [] : [keys],
|
|
131
|
+
...entities === undefined ? [] : [entities],
|
|
130
132
|
...entry.appliesTo !== undefined && entry.appliesTo.length > 0 ? [`appliesTo: ${entry.appliesTo}`] : [],
|
|
131
133
|
...entry.durability === 'snapshot' ? ['durability: snapshot'] : [],
|
|
132
134
|
...entry.durability === 'snapshot' && entry.asOf !== undefined ? [`asOf: ${new Date(entry.asOf).toISOString()}`] : [],
|
|
@@ -208,6 +210,7 @@ export function parseEntry(text, scope, fallbackId) {
|
|
|
208
210
|
// use; an entry written before the field existed simply has none.
|
|
209
211
|
const derivedFrom = (fields.get('derivedfrom') ?? '').split(',').map((value) => value.trim()).filter((value) => value.length > 0);
|
|
210
212
|
const keys = (fields.get('keys') ?? '').split(',').map(normalizeKey).filter((key) => key.length > 0);
|
|
213
|
+
const entities = (fields.get('entities') ?? '').split(',').map((value) => value.replace(/\s+/gu, ' ').trim()).filter((value) => value.length > 0);
|
|
211
214
|
return {
|
|
212
215
|
id: fields.get('id') ?? fallbackId,
|
|
213
216
|
scope,
|
|
@@ -218,6 +221,7 @@ export function parseEntry(text, scope, fallbackId) {
|
|
|
218
221
|
body,
|
|
219
222
|
tags: (fields.get('tags') ?? '').split(',').map(normalizeTag).filter((tag) => tag.length > 0),
|
|
220
223
|
keys,
|
|
224
|
+
...entities.length > 0 ? { entities } : {},
|
|
221
225
|
...appliesTo !== undefined && appliesTo.length > 0 ? { appliesTo } : {},
|
|
222
226
|
...durability === 'snapshot' ? { durability, ...asOf > 0 ? { asOf } : {} } : {},
|
|
223
227
|
...pinned ? { pinned: true } : {},
|
|
@@ -1040,6 +1044,9 @@ export class MemoryStore {
|
|
|
1040
1044
|
: await this.entryFile(draft.scope, projectRoot, keepId);
|
|
1041
1045
|
const tags = [...new Set(draft.tags.map(normalizeTag).filter((tag) => tag.length > 0))].slice(0, 12);
|
|
1042
1046
|
const keys = [...new Set((draft.keys ?? existing?.keys ?? []).map(normalizeKey).filter((key) => key.length > 0))].slice(0, 12);
|
|
1047
|
+
// Entities accumulate the same way keys do: a rewrite that names a new
|
|
1048
|
+
// person/place keeps the old ones, because a later turn may name either.
|
|
1049
|
+
const entities = [...new Set((draft.entities ?? existing?.entities ?? []).map((value) => value.replace(/\s+/gu, ' ').trim()).filter((value) => value.length > 0))].slice(0, 12);
|
|
1043
1050
|
// A rewrite that omits `appliesTo` KEEPS the existing one, exactly like
|
|
1044
1051
|
// `kind` and `keys`. Dropping it silently is a leak nothing downstream can
|
|
1045
1052
|
// undo: measured on a real store, one background consolidation erased the
|
|
@@ -1115,6 +1122,7 @@ export class MemoryStore {
|
|
|
1115
1122
|
body: draft.body.trim(),
|
|
1116
1123
|
tags,
|
|
1117
1124
|
keys,
|
|
1125
|
+
...entities.length > 0 ? { entities } : {},
|
|
1118
1126
|
...appliesTo !== undefined && appliesTo.length > 0 ? { appliesTo } : {},
|
|
1119
1127
|
...durability === 'snapshot' ? { durability, ...asOf === undefined || asOf <= 0 ? { asOf: now } : { asOf } } : {},
|
|
1120
1128
|
...pinned ? { pinned: true } : {},
|
package/lib/sync.js
CHANGED
|
@@ -92,6 +92,75 @@ export function sessionNoteStamp(text) {
|
|
|
92
92
|
const parsed = Date.parse(stamp);
|
|
93
93
|
return Number.isNaN(parsed) ? 0 : parsed;
|
|
94
94
|
}
|
|
95
|
+
/** Whether one path is a persona file: prose the assistant maintains for the user. */
|
|
96
|
+
export function isPersonaPath(path) {
|
|
97
|
+
return /(^|\/)persona\/[^/]+\.md$/u.test(path);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Merge two versions of a persona file as a bullet union.
|
|
101
|
+
*
|
|
102
|
+
* A persona file is headings plus bullet lists; both machines append their own
|
|
103
|
+
* observations, so a line-level union keeps every rule either machine recorded.
|
|
104
|
+
* Bullets are matched on their trimmed text (duplicates are dropped), inserted
|
|
105
|
+
* after the last bullet of the same section, and a whole section that only
|
|
106
|
+
* `theirs` has is appended at the end. Non-bullet lines come from `ours`.
|
|
107
|
+
*/
|
|
108
|
+
export function mergePersona(ours, theirs) {
|
|
109
|
+
const result = ours.split('\n');
|
|
110
|
+
const seen = new Set();
|
|
111
|
+
for (const line of result) {
|
|
112
|
+
if (line.startsWith('- '))
|
|
113
|
+
seen.add(line.trim());
|
|
114
|
+
}
|
|
115
|
+
// Bucket the bullets that only the other side has, by their section heading.
|
|
116
|
+
const pending = new Map();
|
|
117
|
+
let section = '';
|
|
118
|
+
for (const line of theirs.split('\n')) {
|
|
119
|
+
if (line.startsWith('#'))
|
|
120
|
+
section = line.trim();
|
|
121
|
+
else if (line.startsWith('- ')) {
|
|
122
|
+
const key = line.trim();
|
|
123
|
+
if (seen.has(key))
|
|
124
|
+
continue;
|
|
125
|
+
seen.add(key);
|
|
126
|
+
const bucket = pending.get(section) ?? [];
|
|
127
|
+
bucket.push(line);
|
|
128
|
+
pending.set(section, bucket);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (pending.size === 0)
|
|
132
|
+
return ours;
|
|
133
|
+
// Insert each bucket after the last line that belongs to its section.
|
|
134
|
+
const sectionRanges = [];
|
|
135
|
+
let current;
|
|
136
|
+
for (let i = 0; i < result.length; i += 1) {
|
|
137
|
+
const line = result[i];
|
|
138
|
+
if (line?.startsWith('#')) {
|
|
139
|
+
if (current !== undefined)
|
|
140
|
+
current.end = i - 1;
|
|
141
|
+
current = { heading: line.trim(), start: i, end: i };
|
|
142
|
+
sectionRanges.push(current);
|
|
143
|
+
}
|
|
144
|
+
else if (current !== undefined && line !== undefined && line.trim() !== '') {
|
|
145
|
+
current.end = i;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
let offset = 0;
|
|
149
|
+
for (const range of sectionRanges) {
|
|
150
|
+
const bucket = pending.get(range.heading);
|
|
151
|
+
if (bucket === undefined)
|
|
152
|
+
continue;
|
|
153
|
+
result.splice(range.end + 1 + offset, 0, ...bucket);
|
|
154
|
+
offset += bucket.length;
|
|
155
|
+
pending.delete(range.heading);
|
|
156
|
+
}
|
|
157
|
+
for (const [heading, bucket] of pending) {
|
|
158
|
+
if (heading !== '')
|
|
159
|
+
result.push('', heading);
|
|
160
|
+
result.push(...bucket);
|
|
161
|
+
}
|
|
162
|
+
return result.join('\n');
|
|
163
|
+
}
|
|
95
164
|
/**
|
|
96
165
|
* Resolve one conflicting session note by keeping the later `at:` stamp.
|
|
97
166
|
*
|
|
@@ -524,14 +593,33 @@ export class MemorySync {
|
|
|
524
593
|
const cont = await tryGit(this.dir, ['rebase', '--continue'], this.options.networkTimeoutMs);
|
|
525
594
|
if (cont !== undefined)
|
|
526
595
|
return { conflicts, resolvedByResolver, resolvedByTime, mergedByStructure };
|
|
596
|
+
// An empty commit (its change is already upstream) makes --continue
|
|
597
|
+
// refuse forever; with a clean index/tree the only way forward is --skip.
|
|
598
|
+
const dirty = await tryGit(this.dir, ['status', '--porcelain'], this.options.gitTimeoutMs);
|
|
599
|
+
if ((dirty ?? '').trim() === '') {
|
|
600
|
+
const skipped = await tryGit(this.dir, ['rebase', '--skip'], this.options.gitTimeoutMs);
|
|
601
|
+
if (skipped !== undefined) {
|
|
602
|
+
mergedByStructure += 1;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
527
606
|
continue;
|
|
528
607
|
}
|
|
529
608
|
for (const path of paths) {
|
|
530
609
|
const ours = await tryGit(this.dir, ['show', ':' + '2:' + path], this.options.gitTimeoutMs);
|
|
531
610
|
const theirs = await tryGit(this.dir, ['show', ':' + '3:' + path], this.options.gitTimeoutMs);
|
|
532
|
-
if (ours === undefined
|
|
611
|
+
if (ours === undefined && theirs === undefined)
|
|
533
612
|
continue;
|
|
534
613
|
conflicts += 1;
|
|
614
|
+
// modify/delete: one side removed the file while the other edited it.
|
|
615
|
+
// Keep the surviving text — a machine's edit must not vanish because the
|
|
616
|
+
// other machine retired the row; consolidation can retire it later.
|
|
617
|
+
if (ours === undefined || theirs === undefined) {
|
|
618
|
+
await writeFile(join(this.dir, path), (ours ?? theirs));
|
|
619
|
+
mergedByStructure += 1;
|
|
620
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
535
623
|
// Both sides already agree byte for byte: nothing to decide, and git only
|
|
536
624
|
// stopped because the replayed commit touched a file upstream had also
|
|
537
625
|
// rewritten to the same text. This is common for per-host descriptors
|
|
@@ -564,6 +652,13 @@ export class MemorySync {
|
|
|
564
652
|
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
565
653
|
continue;
|
|
566
654
|
}
|
|
655
|
+
const persona = isPersonaPath(path) ? mergePersona(ours, theirs) : undefined;
|
|
656
|
+
if (persona !== undefined) {
|
|
657
|
+
await writeFile(join(this.dir, path), persona);
|
|
658
|
+
mergedByStructure += 1;
|
|
659
|
+
await git(this.dir, ['add', path], this.options.gitTimeoutMs);
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
567
662
|
await tryGit(this.dir, ['rebase', '--abort'], this.options.gitTimeoutMs);
|
|
568
663
|
this.options.log.warn('dsh-cross-memory: 记忆库 rebase 遇到不可自动处理的冲突(%s),已回滚本次同步', path);
|
|
569
664
|
return { conflicts, resolvedByResolver, resolvedByTime, mergedByStructure, stoppedBy: path };
|
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, collectWindow, parseExtraction, redactSecrets, runExtraction } from '../extract.js';
|
|
18
|
+
import { EXTRACT_JSON_SCHEMA, bindEvidence, collectExtractionWindow, collectWindow, parseExtraction, redactSecrets, runExtraction, selectKnownTitles } from '../extract.js';
|
|
19
19
|
import { normalizeSettings } from '../config.js';
|
|
20
20
|
import { peakDelayMs } from '../schedule.js';
|
|
21
21
|
/**
|
|
@@ -301,7 +301,7 @@ test('runExtraction reports an empty window and a missing route without calling
|
|
|
301
301
|
const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'hi' }]);
|
|
302
302
|
const empty = await runExtraction(fakeLlm('{}'), {
|
|
303
303
|
session,
|
|
304
|
-
window: { text: '', lastSeq: undefined, messages: 0, sources: [] },
|
|
304
|
+
window: { text: '', lastSeq: undefined, messages: 0, sources: [], skipped: 0 },
|
|
305
305
|
projectLabel: 'project:work',
|
|
306
306
|
maxOutputTokens: 128,
|
|
307
307
|
maxMemories: 1,
|
|
@@ -1018,3 +1018,60 @@ test('the exit flush still mines what arrived after a periodic pass', async (t)
|
|
|
1018
1018
|
assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 2);
|
|
1019
1019
|
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
1020
1020
|
});
|
|
1021
|
+
test('bindEvidence names what it dropped, not just how many', () => {
|
|
1022
|
+
const bound = bindEvidence([
|
|
1023
|
+
{ scope: 'global', title: 'kept', body: 'b', tags: [], quote: 'I always deploy with pnpm run ship.' },
|
|
1024
|
+
{ scope: 'global', title: 'no quote', body: 'b', tags: [] },
|
|
1025
|
+
{ scope: 'global', title: 'too short', body: 'b', tags: [], quote: 'pnpm' },
|
|
1026
|
+
{ scope: 'global', title: 'invented', body: 'b', tags: [], quote: 'The moon is made of cheese.' },
|
|
1027
|
+
], [{ seq: 7, text: 'I always deploy with pnpm run ship.' }]);
|
|
1028
|
+
assert.deepEqual(bound.drafts.map((draft) => draft.title), ['kept']);
|
|
1029
|
+
assert.equal(bound.unsupported, 3);
|
|
1030
|
+
// The reason is the actionable half: "no quote at all" is a prompt problem,
|
|
1031
|
+
// "quoted something the transcript does not contain" is an invention.
|
|
1032
|
+
assert.deepEqual(bound.dropped.map((item) => [item.title, item.reason]), [
|
|
1033
|
+
['no quote', 'no-quote'],
|
|
1034
|
+
['too short', 'quote-too-short'],
|
|
1035
|
+
['invented', 'not-in-transcript'],
|
|
1036
|
+
]);
|
|
1037
|
+
assert.equal(bound.dropped[2]?.quotePreview, 'The moon is made of cheese.');
|
|
1038
|
+
});
|
|
1039
|
+
test('selectKnownTitles ranks the window over every stored title, not the newest 80', () => {
|
|
1040
|
+
// 120 titles, only the OLDEST one shares vocabulary with the window: a
|
|
1041
|
+
// time-ordered cut would hide exactly the title the extractor needs.
|
|
1042
|
+
const candidates = Array.from({ length: 120 }, (_, index) => ({
|
|
1043
|
+
title: index === 0 ? '日志轮转用 xz 归档' : `无关条目 ${index}`,
|
|
1044
|
+
updatedAt: 1_000 + index,
|
|
1045
|
+
}));
|
|
1046
|
+
const selected = selectKnownTitles(candidates, '那个日志轮转是怎么做的', 10);
|
|
1047
|
+
assert.equal(selected.length, 10);
|
|
1048
|
+
assert.equal(selected[0], '日志轮转用 xz 归档');
|
|
1049
|
+
// With nothing overlapping, the newest still win — a representative sample.
|
|
1050
|
+
const unrelated = selectKnownTitles(candidates, 'zzz', 2);
|
|
1051
|
+
assert.deepEqual(unrelated, ['无关条目 119', '无关条目 118']);
|
|
1052
|
+
// Under the cap the whole set passes through untouched.
|
|
1053
|
+
assert.deepEqual(selectKnownTitles(candidates.slice(0, 3), 'zzz', 10), ['日志轮转用 xz 归档', '无关条目 1', '无关条目 2']);
|
|
1054
|
+
});
|
|
1055
|
+
test('a backlog is mined from the oldest end, so no message can be skipped', () => {
|
|
1056
|
+
const events = Array.from({ length: 20 }, (_, index) => ({ seq: index + 1, role: 'user', text: `line ${index}` }));
|
|
1057
|
+
const session = stubSession('C:\\work', events);
|
|
1058
|
+
// Newest-first steps over lines 2..17 and the watermark would jump past them.
|
|
1059
|
+
const newest = collectWindow(session, 0, 3, 100_000);
|
|
1060
|
+
assert.equal(newest.skipped, 17);
|
|
1061
|
+
const window = collectExtractionWindow(session, 0, 3, 100_000);
|
|
1062
|
+
assert.equal(window.skipped, 17);
|
|
1063
|
+
assert.equal(window.lastSeq, 3, 'a backlog window ends on the contiguous head');
|
|
1064
|
+
assert.match(window.text, /line 0/u);
|
|
1065
|
+
// Walking the watermark forward reaches every message exactly once.
|
|
1066
|
+
const seen = [];
|
|
1067
|
+
let after = 0;
|
|
1068
|
+
for (let pass = 0; pass < 20; pass += 1) {
|
|
1069
|
+
const next = collectExtractionWindow(session, after, 3, 100_000);
|
|
1070
|
+
if (next.lastSeq === undefined)
|
|
1071
|
+
break;
|
|
1072
|
+
for (const source of next.sources)
|
|
1073
|
+
seen.push(source.seq);
|
|
1074
|
+
after = next.lastSeq;
|
|
1075
|
+
}
|
|
1076
|
+
assert.deepEqual(seen, events.map((event) => event.seq));
|
|
1077
|
+
});
|