dsh-cross-memory 0.2.3 → 0.2.5
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 +93 -95
- 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 +84 -35
- package/lib/extract.js +136 -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 +132 -3
- 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/sweep.test.js +3 -1
- package/lib/test/sync.test.js +70 -1
- package/lib/tool.js +9 -1
- package/lib/types/backfill.d.ts +10 -0
- package/lib/types/config.d.ts +81 -30
- 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 +18 -0
- package/lib/types/types.d.ts +8 -0
- package/package.json +1 -1
package/lib/config.js
CHANGED
|
@@ -37,10 +37,20 @@ export const DEFAULT_SYNC_INTERVAL_MINUTES = 10;
|
|
|
37
37
|
export const DEFAULT_SYNC_CLOCK = '12:05,18:05';
|
|
38
38
|
/** Default debounce before a burst of memory writes becomes one commit, in seconds. */
|
|
39
39
|
export const DEFAULT_SYNC_DEBOUNCE_SECONDS = 2;
|
|
40
|
-
/**
|
|
41
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Default byte budget for the injected memory summary.
|
|
42
|
+
*
|
|
43
|
+
* 4096 was sized when a store held a few dozen entries. On a real long-lived
|
|
44
|
+
* store the summary is the ONLY projection most conversations ever see, and at
|
|
45
|
+
* 4 KB it could not even list the dozen entries the per-scope cap allowed once
|
|
46
|
+
* the entries were Chinese (measured on the Ornn8 six-persona benchmark: a
|
|
47
|
+
* 5120-byte budget rendered 12 of 149-326 live entries, so 96% of the store was
|
|
48
|
+
* invisible unless the on-demand recall happened to fire). 8192 roughly doubles
|
|
49
|
+
* the rendered set at the cost of one extra cached prefix block per session.
|
|
50
|
+
*/
|
|
51
|
+
export const DEFAULT_MAX_SUMMARY_BYTES = 8192;
|
|
42
52
|
/** Default cap on entries listed in the injected summary per scope. */
|
|
43
|
-
export const DEFAULT_MAX_SUMMARY_ENTRIES =
|
|
53
|
+
export const DEFAULT_MAX_SUMMARY_ENTRIES = 20;
|
|
44
54
|
/**
|
|
45
55
|
* Whether a conversation is told about memories written after its summary.
|
|
46
56
|
*
|
|
@@ -52,6 +62,16 @@ export const DEFAULT_MAX_SUMMARY_ENTRIES = 12;
|
|
|
52
62
|
* paragraph rather than a second summary.
|
|
53
63
|
*/
|
|
54
64
|
export const DEFAULT_INJECT_DELTA = true;
|
|
65
|
+
/**
|
|
66
|
+
* Byte budget for one delta block.
|
|
67
|
+
*
|
|
68
|
+
* 800 was the first guess and it is too tight to be useful: a complete entry
|
|
69
|
+
* renders at 200-350 bytes once the title, kind, tags and a body preview are
|
|
70
|
+
* in, so the block admitted two entries at most and often one. A late
|
|
71
|
+
* conversation that changed topic then got almost nothing. 1600 fits four to
|
|
72
|
+
* six, which is the size of a topic shift rather than of a single note.
|
|
73
|
+
*/
|
|
74
|
+
export const DEFAULT_DELTA_MAX_BYTES = 1600;
|
|
55
75
|
/**
|
|
56
76
|
* How many additional memories one conversation lists by title only.
|
|
57
77
|
*
|
|
@@ -86,9 +106,11 @@ export const DEFAULT_ROTATION_MAX_BYTES = 1600;
|
|
|
86
106
|
* on global entries, and in every session the same six were unrelated to the
|
|
87
107
|
* workspace (a plugin's logger threshold, a sidebar adapter, a model catalog).
|
|
88
108
|
* Four keeps the portable half visible without letting it bury the scope that is
|
|
89
|
-
* actually about this conversation.
|
|
109
|
+
* actually about this conversation. Six follows the per-scope raise: the global
|
|
110
|
+
* half is what every unrelated conversation can use, and four was leaving the
|
|
111
|
+
* same six entries to compete for a budget that now has room.
|
|
90
112
|
*/
|
|
91
|
-
export const DEFAULT_GLOBAL_SUMMARY_ENTRIES =
|
|
113
|
+
export const DEFAULT_GLOBAL_SUMMARY_ENTRIES = 6;
|
|
92
114
|
/**
|
|
93
115
|
* Default byte budget for the global section alone, inside {@link DEFAULT_MAX_SUMMARY_BYTES}.
|
|
94
116
|
*
|
|
@@ -120,27 +142,36 @@ export const DEFAULT_SUMMARY_FRESH_SLOTS = 3;
|
|
|
120
142
|
/**
|
|
121
143
|
* Default cap on stored entries per scope before the least recently used are evicted.
|
|
122
144
|
*
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
export const DEFAULT_MAX_ENTRIES_PER_SCOPE =
|
|
145
|
+
* There is no cap by default (`0`). A cap is a storage decision, not a memory
|
|
146
|
+
* decision: the store is files on disk, the recall path reads an inverted index
|
|
147
|
+
* (`prefilterEntries`), and the summary already selects a bounded, ranked slice,
|
|
148
|
+
* so a large store costs index size rather than correctness. When a cap IS set,
|
|
149
|
+
* the least-attended entries are archived (never deleted) and `pinned`,
|
|
150
|
+
* `permanent` and `user`-written entries are exempt.
|
|
151
|
+
*/
|
|
152
|
+
export const DEFAULT_MAX_ENTRIES_PER_SCOPE = 0;
|
|
131
153
|
/** Default hours between periodic maintenance sweeps; `0` disables the sweep. */
|
|
132
154
|
export const DEFAULT_SWEEP_INTERVAL_HOURS = 12;
|
|
133
|
-
/**
|
|
134
|
-
|
|
155
|
+
/**
|
|
156
|
+
* Default days an unused memory survives before it is archived; `0` disables archival.
|
|
157
|
+
*
|
|
158
|
+
* Off by default for the same reason the cap is: an entry nobody has happened to
|
|
159
|
+
* read yet is not a stale entry, and archiving it removes it from recall without
|
|
160
|
+
* a person having decided anything. Retrieval already ranks by decay and use, so
|
|
161
|
+
* an unused memory sinks instead of being lost. Set a number to re-enable the
|
|
162
|
+
* age-based sweep.
|
|
163
|
+
*/
|
|
164
|
+
export const DEFAULT_MAX_UNUSED_DAYS = 0;
|
|
135
165
|
/**
|
|
136
166
|
* Default days a `snapshot` memory survives before it is archived; `0` disables.
|
|
137
167
|
*
|
|
138
168
|
* A reading taken at one moment is wrong from the day after it was taken, and
|
|
139
169
|
* reading it does not make it right, so it cannot be judged by the unused clock
|
|
140
|
-
* that a convention is judged by.
|
|
141
|
-
*
|
|
170
|
+
* that a convention is judged by. Off by default: the decay ranking already
|
|
171
|
+
* pushes an old reading down, and archiving it outright is a loss nobody asked
|
|
172
|
+
* for. Set a number to re-enable snapshot expiry.
|
|
142
173
|
*/
|
|
143
|
-
export const DEFAULT_SNAPSHOT_MAX_AGE_DAYS =
|
|
174
|
+
export const DEFAULT_SNAPSHOT_MAX_AGE_DAYS = 0;
|
|
144
175
|
/** Default share of title/body tokens two memories must have in common to be merged. */
|
|
145
176
|
export const DEFAULT_DEDUPE_SIMILARITY = 0.7;
|
|
146
177
|
/** Default recall mode: how much of a conversation pays for cross-session memory. */
|
|
@@ -152,12 +183,14 @@ export const DEFAULT_RECALL_MODE = 'on-demand';
|
|
|
152
183
|
* paraphrase that shares two bigrams with a title scores around 9-12, so nothing
|
|
153
184
|
* ever cleared it. The floor is now a strictness knob, and the PRECISION lives in
|
|
154
185
|
* `recallMinTerms` — the structural evidence gate, which a score threshold cannot
|
|
155
|
-
* replace.
|
|
156
|
-
*
|
|
186
|
+
* replace. 6 is deliberately below the 8 a single shared title bigram scores: a
|
|
187
|
+
* one-bigram paraphrase (「北街南街」 against 「南街文具店」) is a real match that
|
|
188
|
+
* the old floor refused, and the term gate plus the hub discount are what keep a
|
|
189
|
+
* shared common word from recalling everything.
|
|
157
190
|
*/
|
|
158
|
-
export const DEFAULT_RECALL_MIN_SCORE =
|
|
191
|
+
export const DEFAULT_RECALL_MIN_SCORE = 6;
|
|
159
192
|
/** Default cap on recall deltas injected into one conversation. */
|
|
160
|
-
export const DEFAULT_RECALL_MAX_PER_CONVERSATION =
|
|
193
|
+
export const DEFAULT_RECALL_MAX_PER_CONVERSATION = 8;
|
|
161
194
|
/**
|
|
162
195
|
* Default byte budget for one recall delta block.
|
|
163
196
|
*
|
|
@@ -166,7 +199,7 @@ export const DEFAULT_RECALL_MAX_PER_CONVERSATION = 4;
|
|
|
166
199
|
* entry costs about 90. At 800 a two-entry block would not fit, which is why
|
|
167
200
|
* this is not 400 as it was when a delta could only ever hold one memory.
|
|
168
201
|
*/
|
|
169
|
-
export const DEFAULT_RECALL_MAX_BYTES =
|
|
202
|
+
export const DEFAULT_RECALL_MAX_BYTES = 2_400;
|
|
170
203
|
/** Default minimum length of a user turn worth a recall decision. */
|
|
171
204
|
export const DEFAULT_RECALL_MIN_QUERY_CHARS = 2;
|
|
172
205
|
/**
|
|
@@ -183,12 +216,16 @@ export const DEFAULT_RAW_RECALL_EXCERPTS = 3;
|
|
|
183
216
|
/**
|
|
184
217
|
* Default number of distinct strong-field terms a recall needs.
|
|
185
218
|
*
|
|
186
|
-
* Two
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
219
|
+
* Two was the old precision gate, but a Chinese paraphrase of a stored fact
|
|
220
|
+
* routinely shares exactly ONE substantive word with it: a benchmark turn asking
|
|
221
|
+
* 「理零票第一步」 against a memory filed as 「整理小票先按日期分堆」 shares only
|
|
222
|
+
* 票, and 「点碗粉加两个小菜」 against 「不吃香菜」 shares only 菜. Two terms made
|
|
223
|
+
* those unreachable no matter how high the relevance score was. One term plus the
|
|
224
|
+
* relevance floor is the gate now; the floor (8) is what keeps a shared common
|
|
225
|
+
* word like 插件 or 日志 from recalling everything, and the entity path in
|
|
226
|
+
* `recallFor` adds a second, stronger signal on top.
|
|
190
227
|
*/
|
|
191
|
-
export const DEFAULT_RECALL_MIN_TERMS =
|
|
228
|
+
export const DEFAULT_RECALL_MIN_TERMS = 1;
|
|
192
229
|
/**
|
|
193
230
|
* Every valid recall mode.
|
|
194
231
|
*
|
|
@@ -242,8 +279,16 @@ export const DEFAULT_EXTRACT_INTERVAL_MINUTES = 30;
|
|
|
242
279
|
export const DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS = 8192;
|
|
243
280
|
/** Default timeout for one extraction call. */
|
|
244
281
|
export const DEFAULT_EXTRACT_TIMEOUT_MS = 120_000;
|
|
245
|
-
/**
|
|
246
|
-
|
|
282
|
+
/**
|
|
283
|
+
* Default max drafts one extraction may produce.
|
|
284
|
+
*
|
|
285
|
+
* 8 rather than 5: on a real production session, an audit of 50 Mubea
|
|
286
|
+
* Invoice-Insight conversations found 247 durable facts, and the cap of 5 was
|
|
287
|
+
* the single biggest cause of missed material on long sessions (one audit
|
|
288
|
+
* session held 16 facts and kept 5). Eight keeps a long session's findings
|
|
289
|
+
* without letting a short one pad itself.
|
|
290
|
+
*/
|
|
291
|
+
export const DEFAULT_EXTRACT_MAX_MEMORIES = 8;
|
|
247
292
|
/** Default idle hours a session must accumulate before it is mined. */
|
|
248
293
|
export const DEFAULT_MIN_IDLE_HOURS = 6;
|
|
249
294
|
/** Default age limit: sessions idle longer than this are never mined. */
|
|
@@ -332,13 +377,13 @@ export const Config = z.object({
|
|
|
332
377
|
/** Max entries listed for the global scope, which every session shares. */
|
|
333
378
|
globalSummaryEntries: z.number().default(DEFAULT_GLOBAL_SUMMARY_ENTRIES).description('How many memories the GLOBAL section may list, capped below maxSummaryEntries. Both scopes share one byte budget and global renders first, so without this the global half grows to fill whatever the project half leaves (measured: 87% of a small project\'s summary). 0 removes the global section entirely.').volatile(),
|
|
334
379
|
/** Byte budget for the global section alone. */
|
|
335
|
-
globalSummaryBytes: z.number().default(DEFAULT_GLOBAL_SUMMARY_BYTES).description('Byte budget for the GLOBAL section, inside maxSummaryBytes. A count cap is not enough because Chinese entries are ~3 bytes per character:
|
|
380
|
+
globalSummaryBytes: z.number().default(DEFAULT_GLOBAL_SUMMARY_BYTES).description('Byte budget for the GLOBAL section, inside maxSummaryBytes. A count cap is not enough because Chinese entries are ~3 bytes per character: a handful of them still fills a large share of the block. 0 removes the global section entirely.').volatile(),
|
|
336
381
|
/** How many of those entries are reserved for never-listed memories. */
|
|
337
382
|
summaryFreshSlots: z.number().default(DEFAULT_SUMMARY_FRESH_SLOTS).description('How many of each scope\'s summary entries are reserved for memories that have never been listed before, preferring ones written deliberately over extracted ones. 0 leaves selection to the ranking alone, which on a full scope never shows anything new.').volatile(),
|
|
338
383
|
/** How the injected summary is refreshed as the conversation moves on. */
|
|
339
384
|
recallMode: z.string().default(DEFAULT_RECALL_MODE).description('once injects the summary once per conversation; on-demand also injects a small delta when the current turn clearly matches a memory; off disables injection and leaves only the memory tool.').volatile(),
|
|
340
385
|
/** Minimum relevance a recall delta must reach. */
|
|
341
|
-
recallMinScore: z.number().default(DEFAULT_RECALL_MIN_SCORE).description('Minimum relevance a memory must reach before it is injected as a recall delta.
|
|
386
|
+
recallMinScore: z.number().default(DEFAULT_RECALL_MIN_SCORE).description('Minimum relevance a memory must reach before it is injected as a recall delta. Together with recallMinTerms this is the precision gate: with the default of one term, the score floor is what keeps a shared common word like 插件 or 日志 from recalling every memory. Raise it to demand a stronger lexical match.').volatile(),
|
|
342
387
|
/** Cap on recall deltas injected into one conversation. */
|
|
343
388
|
recallMaxPerConversation: z.number().default(DEFAULT_RECALL_MAX_PER_CONVERSATION).description('Maximum recall deltas injected into one conversation, counted per memory. 0 disables them.').volatile(),
|
|
344
389
|
/** Byte budget for one recall delta block. */
|
|
@@ -349,7 +394,7 @@ export const Config = z.object({
|
|
|
349
394
|
/** Shortest user turn worth a recall decision. */
|
|
350
395
|
recallMinQueryChars: z.number().default(DEFAULT_RECALL_MIN_QUERY_CHARS).description('Shortest user turn, in characters, that may trigger a recall delta. Short acknowledgements are skipped instead of scanning the store.').volatile(),
|
|
351
396
|
/** Distinct strong-field terms a recall needs before it is credited. */
|
|
352
|
-
recallMinTerms: z.number().default(DEFAULT_RECALL_MIN_TERMS).description('Distinct query terms that must land in the title, keys, tags, or appliesTo before a memory may be recalled on demand.
|
|
397
|
+
recallMinTerms: z.number().default(DEFAULT_RECALL_MIN_TERMS).description('Distinct query terms that must land in the title, keys, tags, or appliesTo before a memory may be recalled on demand. 1 (the default) admits a one-word paraphrase, which a Chinese rewrite of a stored fact routinely is, and lets the relevance floor do the precision work; 2 demands two shared words and misses single-word paraphrases; 0 disables the check entirely.').volatile(),
|
|
353
398
|
/**
|
|
354
399
|
* Whether memories written after the summary was injected get a small delta.
|
|
355
400
|
*
|
|
@@ -357,6 +402,8 @@ export const Config = z.object({
|
|
|
357
402
|
* the `memory` tool and the on-demand recall path still work.
|
|
358
403
|
*/
|
|
359
404
|
injectDelta: z.boolean().default(DEFAULT_INJECT_DELTA).description('Inject a small block when memories are written after the summary was already shown (at most twice per conversation). Off keeps the summary as the only automatic block.').volatile(),
|
|
405
|
+
/** Byte budget for one delta block. */
|
|
406
|
+
deltaMaxBytes: z.number().default(DEFAULT_DELTA_MAX_BYTES).description('Byte budget for one late-injection delta block. One complete entry costs 200-350 bytes, so 800 admitted one or two; raise it for a longer block, lower it to spend fewer bytes per conversation. 0 disables the delta entirely.').volatile(),
|
|
360
407
|
/**
|
|
361
408
|
* How many extra memories one conversation lists by title only.
|
|
362
409
|
*
|
|
@@ -376,7 +423,7 @@ export const Config = z.object({
|
|
|
376
423
|
*/
|
|
377
424
|
rotationEveryTurns: z.number().default(DEFAULT_ROTATION_EVERY_TURNS).description('Inside one conversation, emit a fresh rotation block every this many user turns (0 keeps the old once-per-conversation behaviour).').volatile(),
|
|
378
425
|
/** Max stored entries per scope; the least-recently-updated are evicted. */
|
|
379
|
-
maxEntriesPerScope: z.number().default(DEFAULT_MAX_ENTRIES_PER_SCOPE).description('Stored memories per scope; past this cap the least
|
|
426
|
+
maxEntriesPerScope: z.number().default(DEFAULT_MAX_ENTRIES_PER_SCOPE).description('Stored memories per scope; past this cap the least-attended are archived (pinned, permanent and user-written entries are exempt). 0 (the default) means no cap: the store grows and retrieval ranks it.').volatile(),
|
|
380
427
|
/** Days an unused memory survives before it is archived. `0` disables archival. */
|
|
381
428
|
maxUnusedDays: z.number().default(DEFAULT_MAX_UNUSED_DAYS).description('Days an unused memory survives before it is archived. Archived entries are recoverable with /memories restore. 0 disables archival.').volatile(),
|
|
382
429
|
/** Days a snapshot memory survives regardless of use. `0` disables. */
|
|
@@ -484,6 +531,7 @@ export const MEMORIES_SETTINGS_DEFAULTS = {
|
|
|
484
531
|
recallMinQueryChars: DEFAULT_RECALL_MIN_QUERY_CHARS,
|
|
485
532
|
recallMinTerms: DEFAULT_RECALL_MIN_TERMS,
|
|
486
533
|
injectDelta: DEFAULT_INJECT_DELTA,
|
|
534
|
+
deltaMaxBytes: DEFAULT_DELTA_MAX_BYTES,
|
|
487
535
|
rotationEntries: DEFAULT_ROTATION_ENTRIES,
|
|
488
536
|
rotationEveryTurns: DEFAULT_ROTATION_EVERY_TURNS,
|
|
489
537
|
maxEntriesPerScope: DEFAULT_MAX_ENTRIES_PER_SCOPE,
|
|
@@ -590,9 +638,10 @@ export function normalizeSettings(input) {
|
|
|
590
638
|
recallMinQueryChars: positive(value.recallMinQueryChars, DEFAULT_RECALL_MIN_QUERY_CHARS, 0),
|
|
591
639
|
recallMinTerms: positive(value.recallMinTerms, DEFAULT_RECALL_MIN_TERMS, 0),
|
|
592
640
|
injectDelta: value.injectDelta ?? DEFAULT_INJECT_DELTA,
|
|
641
|
+
deltaMaxBytes: positive(value.deltaMaxBytes, DEFAULT_DELTA_MAX_BYTES, 0),
|
|
593
642
|
rotationEntries: positive(value.rotationEntries, DEFAULT_ROTATION_ENTRIES, 0),
|
|
594
643
|
rotationEveryTurns: positive(value.rotationEveryTurns, DEFAULT_ROTATION_EVERY_TURNS, 0),
|
|
595
|
-
maxEntriesPerScope: positive(value.maxEntriesPerScope, DEFAULT_MAX_ENTRIES_PER_SCOPE),
|
|
644
|
+
maxEntriesPerScope: positive(value.maxEntriesPerScope, DEFAULT_MAX_ENTRIES_PER_SCOPE, 0),
|
|
596
645
|
maxUnusedDays: positive(value.maxUnusedDays, DEFAULT_MAX_UNUSED_DAYS, 0),
|
|
597
646
|
snapshotMaxAgeDays: positive(value.snapshotMaxAgeDays, DEFAULT_SNAPSHOT_MAX_AGE_DAYS, 0),
|
|
598
647
|
dedupeSimilarity: clampUnit(value.dedupeSimilarity, DEFAULT_DEDUPE_SIMILARITY),
|
package/lib/extract.js
CHANGED
|
@@ -13,6 +13,46 @@ import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
|
13
13
|
import { deriveEventMessage } from '@deepseek-ai/dsh-session/surface';
|
|
14
14
|
import { SessionSeq } from '@deepseek-ai/dsh-session';
|
|
15
15
|
import { MEMORY_SOURCE_KIND, toMemoryKind } from './types.js';
|
|
16
|
+
import { tokenize } from './search.js';
|
|
17
|
+
/**
|
|
18
|
+
* Pick the known titles most worth showing one extraction window.
|
|
19
|
+
*
|
|
20
|
+
* The list used to be taken in time order and cut at a fixed cap, which on a
|
|
21
|
+
* store larger than the cap hid every older title from the extractor: it could
|
|
22
|
+
* not recognise a fact it had already recorded, and wrote a second entry under
|
|
23
|
+
* a re-worded title. Ranking by overlap with the window fixes that within the
|
|
24
|
+
* same budget — the titles the window is actually about are the ones it might
|
|
25
|
+
* re-derive — while the recency tie-break keeps a representative sample when
|
|
26
|
+
* nothing overlaps.
|
|
27
|
+
*
|
|
28
|
+
* @param candidates - every title in the scopes this pass may write to.
|
|
29
|
+
* @param windowText - the transcript window about to be mined.
|
|
30
|
+
* @param limit - most titles to return; `0` returns none.
|
|
31
|
+
* @returns the selected titles, most relevant first.
|
|
32
|
+
*/
|
|
33
|
+
export function selectKnownTitles(candidates, windowText, limit) {
|
|
34
|
+
if (limit <= 0)
|
|
35
|
+
return [];
|
|
36
|
+
if (candidates.length <= limit)
|
|
37
|
+
return candidates.map((candidate) => candidate.title);
|
|
38
|
+
const queryTerms = new Set(tokenize(windowText));
|
|
39
|
+
const scored = candidates.map((candidate, index) => {
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
let overlap = 0;
|
|
42
|
+
for (const term of tokenize(candidate.title)) {
|
|
43
|
+
if (seen.has(term))
|
|
44
|
+
continue;
|
|
45
|
+
seen.add(term);
|
|
46
|
+
if (queryTerms.has(term))
|
|
47
|
+
overlap += 1;
|
|
48
|
+
}
|
|
49
|
+
return { title: candidate.title, overlap, updatedAt: candidate.updatedAt, index };
|
|
50
|
+
});
|
|
51
|
+
scored.sort((left, right) => right.overlap - left.overlap
|
|
52
|
+
|| right.updatedAt - left.updatedAt
|
|
53
|
+
|| left.index - right.index);
|
|
54
|
+
return scored.slice(0, limit).map((item) => item.title);
|
|
55
|
+
}
|
|
16
56
|
/**
|
|
17
57
|
* The system instruction for the extraction call.
|
|
18
58
|
*
|
|
@@ -30,11 +70,13 @@ import { MEMORY_SOURCE_KIND, toMemoryKind } from './types.js';
|
|
|
30
70
|
* truncation keep everything that finished.
|
|
31
71
|
*/
|
|
32
72
|
export const EXTRACT_SYSTEM = [
|
|
33
|
-
'You maintain long-term memory for
|
|
73
|
+
'You maintain long-term memory for an AI assistant\'s user.',
|
|
34
74
|
'Read the supplied conversation transcript and extract only durable, reusable facts that would help in a FUTURE session.',
|
|
35
75
|
'',
|
|
36
|
-
'Record: stable user preferences and working style; project architecture and conventions; build/test/deploy commands; environment and tooling facts; non-obvious gotchas; decisions and their reasons.',
|
|
37
|
-
'Do NOT record: transient task state, one-off debugging output, secrets, API keys, tokens, credentials, personal data, restatements of the code the assistant just wrote, or anything already stated in the transcript as a question rather than a fact.',
|
|
76
|
+
'Record: stable user preferences and working style; project architecture and conventions; build/test/deploy commands; environment and tooling facts; non-obvious gotchas; decisions and their reasons; the user\'s personal background and relationships (family, colleagues, friends, neighbours); personal habits, routines and plans; creative collaborations and shared stories; commitments and promises with their deadlines.',
|
|
77
|
+
'Do NOT record: transient task state, one-off debugging output, secrets, API keys, tokens, credentials, sensitive personal data (ID numbers, medical records, financial account details), restatements of the code the assistant just wrote, or anything already stated in the transcript as a question rather than a fact.',
|
|
78
|
+
'Do NOT record what the repository already answers: a config key and its value, an i18n key that is there to be read, the list of entry files, a script\'s CLI flags, a bug that is already fixed (name the fix only when the failure mode is non-obvious). If a later session can get it by opening the file, it is not memory.',
|
|
79
|
+
'REPORTS: when the transcript is an implementation/audit/review report (often a subagent\'s), record what the report LEARNED — the mechanism, the interface trap, the root cause, the measured result, the open gap — and skip what it was ASKED to do: the task boundary ("只改这 5 个文件", "不要 git commit"), the verification commands, the review verdict, the commit hash. Those expire with the task; the finding does not.',
|
|
38
80
|
'',
|
|
39
81
|
'Write every title and body in Simplified Chinese. Keep paths, commands, identifiers, product names and error strings exactly as they are.',
|
|
40
82
|
'The injected summary shows only the title and roughly the first 100 characters of the body (the budget forces short previews), so lead with the trigger and the decision; put the detail after.',
|
|
@@ -42,13 +84,19 @@ export const EXTRACT_SYSTEM = [
|
|
|
42
84
|
'When a number IS the point of the memory (a measured pass rate, a corpus size, the current state of a system), set "durability":"snapshot" and give "asOf" as the date it was measured; it is then shown with that date and retired once it is old. Everything else is "durable" and needs neither field.',
|
|
43
85
|
'A problem that is already fixed is recorded as fixed ("已修 in <commit>"); never leave it reading as an open problem.',
|
|
44
86
|
'',
|
|
87
|
+
'TIME: a fact carrying a relative time (明天/上周五/前天/下周三/上个月) MUST also carry its absolute date in the body, resolved against the today\'s date given below ("前天(2026-05-25)"). A later turn may ask exactly "那次是几号", and the relative word alone cannot answer it.',
|
|
88
|
+
'UPDATES: when the transcript CHANGES an existing fact — a correction, a changed plan, a new version, a story retcon — do NOT overwrite the old state. Keep the timeline in the body: "旧:<old>;新:<new>(<date> 改)". A later turn may ask what was true BEFORE the change (改口/纠错/真实变化), and only the timeline answers it.',
|
|
89
|
+
'CONFLICTS: when the user says two things about the same subject that do not agree and the transcript does not explain why, record BOTH ("两种说法:<A>;<B>;原因未明"). Never pick one side and drop the other.',
|
|
90
|
+
'CONDITIONS: a rule or preference is usually BOUNDED — "下雨才喝", "当周有早班或盘点就不碰", "只在雨夜、最多两指", "戒到 5 月 10 日". The condition is the memory: a later turn asks "今晚那瓶能开不" and only the bounded rule answers it. Copy the condition and any deadline into the body exactly as the user set it ("条件:当周有早班或盘点则不喝;雨夜才喝,最多两指;戒到 2026-05-10"), and never record the bare preference without its bounds.',
|
|
91
|
+
'',
|
|
45
92
|
'Choose the scope of each memory:',
|
|
46
|
-
'- "global": true across the developer\'s machines and projects — how they like to work, general preferences, tooling, machine and path facts, network and proxy setup, how to move work between machines.',
|
|
93
|
+
'- "global": true across the developer\'s machines and projects — how they like to work, general preferences, tooling, machine and path facts, network and proxy setup, how to move work between machines, and the user\'s personal background and relationships.',
|
|
47
94
|
'- "project": true only for this workspace (its architecture, commands, conventions, gotchas).',
|
|
48
95
|
'Choose by breadth, not by wording: naming a machine, drive letter, repository path, host, employer or customer is NOT by itself evidence of project scope. A durable fact about the developer\'s own environment is global even when it names such a thing, because global memories are what every unrelated project reads. A fact becomes "project" only when it would be wrong or meaningless outside this one workspace.',
|
|
49
96
|
'',
|
|
50
97
|
'Each memory has a short imperative title (max 80 characters), a 1-3 sentence body, up to 5 lowercase keyword tags, and 1-5 search keys: the aliases and keyphrases a future session would actually type (for example "monorepo" for a pnpm-workspace fact).',
|
|
51
98
|
'Search keys are how a memory is found at all, so spend them on the words a person would use who has NOT read the memory: the other name for the same thing, the command, the file, the error text, the product\'s own term. Include the English technical term when the memory is written in Chinese and vice versa — a turn that mixes them ("这个排序改动会不会动到 system prompt") shares no characters with "前缀缓存", and the keys are the only place that gap can be closed. Retrieval is lexical: it matches characters, not meaning.',
|
|
99
|
+
'Also give each memory "entities": the people, places, organisations, objects and dates it is about, each as a short exact name ("刘莹", "南街文具店", "叶楠", "2026-05-25"). A later turn that names one of them ("北街南街分别买了什么") may share no other word with the memory, and the entity list is what makes it reachable.',
|
|
52
100
|
'Give each memory a kind, because the kinds are recalled differently:',
|
|
53
101
|
'- "preference": how the user wants work done, or a correction they issued.',
|
|
54
102
|
'- "failure": something that went wrong and how to avoid repeating it.',
|
|
@@ -59,7 +107,8 @@ export const EXTRACT_SYSTEM = [
|
|
|
59
107
|
'Every memory must also carry "quote": one continuous passage copied VERBATIM from a single message in the transcript above (8-200 characters), keeping its punctuation and wording exactly, and without the "USER:"/"ASSISTANT:" line prefix. Choose the sentence that carries the claim — the user stating it, or the assistant\'s conclusion you are recording — not a greeting, a question or your own summary. Never paraphrase the quote, combine two messages, or invent one. The quote is checked as an exact substring of the transcript before the memory is written, and a memory whose quote does not appear there is discarded, so a paraphrased quote loses the memory.',
|
|
60
108
|
'',
|
|
61
109
|
'Mark whose words a memory preserves with "voice":',
|
|
62
|
-
'- "user" when the user themselves stated it: how they want work done, a correction they issued, a habit, an opinion, a rule they set ("以后都…", "不要…", "我喜欢…").',
|
|
110
|
+
'- "user" when the user themselves stated it: how they want work done, a correction they issued, a habit, an opinion, a rule they set ("以后都…", "不要…", "我喜欢…"), or a fact about their own life.',
|
|
111
|
+
'- "assistant" when the memory preserves the ASSISTANT\'s own words, suggestion or promise. Never file the assistant\'s words as the user\'s: a later turn asking "你当时建议什么" must not be answered with "你说过…".',
|
|
63
112
|
'- Record the SUBSTANCE faithfully but in the form that will be found and understood later: rewrite for clarity when their sentence was context-bound, and keep their exact phrasing only where the wording itself carries the rule (a threshold, a condition, a turn of phrase they will repeat). The voice field records whose claim it is, not a transcript.',
|
|
64
113
|
'- omit the field (the default) when the memory is your own conclusion, an observation about the code, or a fact you looked up.',
|
|
65
114
|
'Never attribute your own conclusion to the user. A profile of this person is rebuilt from the "user" entries, so a misattributed guess becomes a false belief about them.',
|
|
@@ -68,9 +117,10 @@ export const EXTRACT_SYSTEM = [
|
|
|
68
117
|
'- One short sentence each, in the user\'s framing, naming the object ("把报价单发出去", not "邮件相关").',
|
|
69
118
|
'- NEVER drop the time word: if the user said 明天/周五/下周三, the loop text must start with it ("明天把登录页的截图补齐"), because a later question may be exactly "我明天要做什么"; resolve "dueAt" to the absolute ISO date computed from today\'s date given above, and omit it when no deadline was said.',
|
|
70
119
|
'- "dueAt" only when a deadline was actually said, as ISO date or date-time. Never invent one: a loop without a deadline is a note, and nagging somebody about a note turns help into supervision.',
|
|
120
|
+
'- PROGRESS: when the user reports that part of an existing obligation is done ("先还一件,还剩两件"), the loop text MUST be the REMAINING part with the original promise\'s wording kept ("还剩两件夜班见闻(原欠三件)"), because the ledger recognises it as the same promise and replaces the old amount. A loop that still states the full original amount ("三天内讲完欠的三件") is WRONG after a progress report: it leaves the ledger owing what is already done. Skip the obligation entirely only when nothing is left.',
|
|
71
121
|
'- Skip what the session shows as already done, and skip the assistant\'s own to-dos. An empty array is the normal result.',
|
|
72
122
|
'Prefer few high-value memories over many trivial ones. Return at most the requested number.',
|
|
73
|
-
'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"appliesTo":string,"quote":string}],"loops":[{"text":string,"dueAt":string?}],"summary":string}',
|
|
123
|
+
'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"entities":string[],"appliesTo":string,"quote":string,"voice":"user"|"assistant"}],"loops":[{"text":string,"dueAt":string?}],"summary":string}',
|
|
74
124
|
'Write the "memories" array first and the "summary" paragraph last: the reply is capped, and a summary written first can spend the whole budget before the first memory is complete.',
|
|
75
125
|
'Write "summary" as one paragraph (2-4 sentences) saying what this session was about — the task, the decisions, and anything that would help someone judge the memories above later. It is stored as the evidence behind them.',
|
|
76
126
|
'When nothing is worth remembering, reply exactly {"memories":[],"summary":""}.'
|
|
@@ -100,6 +150,7 @@ export const EXTRACT_JSON_SCHEMA = {
|
|
|
100
150
|
body: { type: 'string' },
|
|
101
151
|
tags: { type: 'array', items: { type: 'string' } },
|
|
102
152
|
keys: { type: 'array', items: { type: 'string' } },
|
|
153
|
+
entities: { type: 'array', items: { type: 'string' } },
|
|
103
154
|
appliesTo: { type: 'string' },
|
|
104
155
|
quote: { type: 'string' },
|
|
105
156
|
voice: { type: 'string', enum: ['user', 'assistant'] },
|
|
@@ -210,10 +261,13 @@ function blockText(content) {
|
|
|
210
261
|
* @param session - session to read.
|
|
211
262
|
* @param afterSeq - last surface seq already mined (exclusive).
|
|
212
263
|
* @param maxMessages - message cap.
|
|
213
|
-
* @param maxChars - transcript character cap
|
|
214
|
-
* @
|
|
264
|
+
* @param maxChars - transcript character cap.
|
|
265
|
+
* @param order - which end of the backlog to keep. `newest` (the default) is
|
|
266
|
+
* the right window for a session that is nearly caught up; `oldest` is the
|
|
267
|
+
* contiguous one, and it is the only order that cannot skip a message.
|
|
268
|
+
* @returns the rendered window, the highest included seq, and how much it left out.
|
|
215
269
|
*/
|
|
216
|
-
export function collectWindow(session, afterSeq, maxMessages, maxChars) {
|
|
270
|
+
export function collectWindow(session, afterSeq, maxMessages, maxChars, order = 'newest') {
|
|
217
271
|
const floor = SessionSeq(Math.max(0, Math.trunc(afterSeq)));
|
|
218
272
|
const lines = [];
|
|
219
273
|
for (const seq of session.surface.nodes) {
|
|
@@ -234,27 +288,71 @@ export function collectWindow(session, afterSeq, maxMessages, maxChars) {
|
|
|
234
288
|
continue;
|
|
235
289
|
lines.push({ seq, role: message.role === 'user' ? 'user' : 'assistant', text });
|
|
236
290
|
}
|
|
237
|
-
|
|
291
|
+
// `newest` keeps the tail and admits lines backwards from it; `oldest` keeps
|
|
292
|
+
// the head and admits forward. Both keep at least one line even when that line
|
|
293
|
+
// alone blows the character budget: a window that is empty for budget reasons
|
|
294
|
+
// would stall the watermark on the same message forever.
|
|
295
|
+
const selected = order === 'oldest' ? lines.slice(0, maxMessages) : lines.slice(-maxMessages);
|
|
238
296
|
const kept = [];
|
|
239
297
|
let used = 0;
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
298
|
+
if (order === 'oldest') {
|
|
299
|
+
let admitted = 0;
|
|
300
|
+
for (const line of selected) {
|
|
301
|
+
const cost = `${line.role === 'user' ? 'USER' : 'ASSISTANT'}: ${line.text}`.length + 1;
|
|
302
|
+
if (used + cost > maxChars && admitted > 0)
|
|
303
|
+
break;
|
|
304
|
+
used += cost;
|
|
305
|
+
admitted += 1;
|
|
306
|
+
kept.push(line);
|
|
307
|
+
}
|
|
249
308
|
}
|
|
250
|
-
|
|
309
|
+
else {
|
|
310
|
+
for (let index = selected.length - 1; index >= 0; index -= 1) {
|
|
311
|
+
const line = selected[index];
|
|
312
|
+
if (line === undefined)
|
|
313
|
+
continue;
|
|
314
|
+
const cost = `${line.role === 'user' ? 'USER' : 'ASSISTANT'}: ${line.text}`.length + 1;
|
|
315
|
+
if (used + cost > maxChars && kept.length > 0)
|
|
316
|
+
break;
|
|
317
|
+
used += cost;
|
|
318
|
+
kept.unshift(line);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
// The highest seq the window actually covers. For `newest` that is the newest
|
|
322
|
+
// line; for `oldest` it is the newest line of the contiguous head, which is
|
|
323
|
+
// what lets the watermark advance one backlog chunk at a time.
|
|
324
|
+
const lastSeq = kept.at(-1)?.seq;
|
|
251
325
|
return {
|
|
252
326
|
text: kept.map((line) => `${line.role === 'user' ? 'USER' : 'ASSISTANT'}: ${line.text}`).join('\n\n'),
|
|
253
327
|
lastSeq,
|
|
254
328
|
messages: kept.length,
|
|
255
329
|
sources: kept.map((line) => ({ seq: line.seq, text: line.text })),
|
|
330
|
+
skipped: lines.length - kept.length,
|
|
256
331
|
};
|
|
257
332
|
}
|
|
333
|
+
/**
|
|
334
|
+
* The window one extraction pass should mine, preferring contiguity.
|
|
335
|
+
*
|
|
336
|
+
* The newest window is what a session that is nearly caught up wants: it is the
|
|
337
|
+
* most recent material. It cannot be the only order, because the message cap
|
|
338
|
+
* silently drops everything between the watermark and the tail — measured on a
|
|
339
|
+
* long session, one 400-message gap left 340 messages never mined while the
|
|
340
|
+
* watermark stepped over all of them. So: take the newest window, and when it
|
|
341
|
+
* reports a backlog, take the oldest contiguous one instead. The pass cadence
|
|
342
|
+
* then drains the backlog chunk by chunk and nothing is skipped.
|
|
343
|
+
*
|
|
344
|
+
* @param session - session to read.
|
|
345
|
+
* @param afterSeq - last surface seq already mined (exclusive).
|
|
346
|
+
* @param maxMessages - message cap per window.
|
|
347
|
+
* @param maxChars - character cap per window.
|
|
348
|
+
* @returns the window to mine.
|
|
349
|
+
*/
|
|
350
|
+
export function collectExtractionWindow(session, afterSeq, maxMessages, maxChars) {
|
|
351
|
+
const newest = collectWindow(session, afterSeq, maxMessages, maxChars);
|
|
352
|
+
if (newest.skipped === 0)
|
|
353
|
+
return newest;
|
|
354
|
+
return collectWindow(session, afterSeq, maxMessages, maxChars, 'oldest');
|
|
355
|
+
}
|
|
258
356
|
/**
|
|
259
357
|
* Resolve the provider/model route for a model call.
|
|
260
358
|
*
|
|
@@ -346,6 +444,7 @@ export function parseExtraction(text, maxMemories, sessionId) {
|
|
|
346
444
|
? record['tags'].filter((tag) => typeof tag === 'string')
|
|
347
445
|
: [];
|
|
348
446
|
const keys = Array.isArray(record['keys']) ? record['keys'].filter((key) => typeof key === 'string') : [];
|
|
447
|
+
const entities = Array.isArray(record['entities']) ? record['entities'].filter((entity) => typeof entity === 'string') : [];
|
|
349
448
|
const appliesTo = typeof record['appliesTo'] === 'string'
|
|
350
449
|
? redactSecrets(record['appliesTo'].replace(/\s+/gu, ' ').trim()).slice(0, 160)
|
|
351
450
|
: '';
|
|
@@ -359,9 +458,10 @@ export function parseExtraction(text, maxMemories, sessionId) {
|
|
|
359
458
|
const quote = typeof record['quote'] === 'string'
|
|
360
459
|
? redactSecrets(record['quote'].replace(/\s+/gu, ' ').trim()).slice(0, 300)
|
|
361
460
|
: '';
|
|
362
|
-
// "assistant" is
|
|
363
|
-
//
|
|
364
|
-
|
|
461
|
+
// "assistant" is stored explicitly (the assistant's own words are a different
|
|
462
|
+
// claim from the user's); the absent default means "the extractor's own
|
|
463
|
+
// conclusion", which is what every entry written before this field existed is.
|
|
464
|
+
const voice = record['voice'] === 'user' ? 'user' : record['voice'] === 'assistant' ? 'assistant' : undefined;
|
|
365
465
|
usable.push({
|
|
366
466
|
scope: scope,
|
|
367
467
|
kind: toMemoryKind(record['kind']),
|
|
@@ -369,6 +469,7 @@ export function parseExtraction(text, maxMemories, sessionId) {
|
|
|
369
469
|
body: cleanBody,
|
|
370
470
|
tags,
|
|
371
471
|
keys,
|
|
472
|
+
entities,
|
|
372
473
|
...voice === undefined ? {} : { voice },
|
|
373
474
|
...appliesTo.length > 0 ? { appliesTo } : {},
|
|
374
475
|
...quote.length > 0 && quote !== '[redacted]' ? { quote } : {},
|
|
@@ -411,21 +512,30 @@ function squash(value) {
|
|
|
411
512
|
*/
|
|
412
513
|
export function bindEvidence(drafts, sources) {
|
|
413
514
|
const verified = [];
|
|
515
|
+
const dropped = [];
|
|
414
516
|
let unsupported = 0;
|
|
415
517
|
for (const draft of drafts) {
|
|
416
518
|
const quote = draft.quote === undefined ? '' : squash(draft.quote);
|
|
519
|
+
const preview = quote.slice(0, 60);
|
|
520
|
+
if (quote.length === 0) {
|
|
521
|
+
unsupported += 1;
|
|
522
|
+
dropped.push({ title: draft.title, quotePreview: '', reason: 'no-quote' });
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
417
525
|
if (quote.length < MIN_QUOTE_CHARS) {
|
|
418
526
|
unsupported += 1;
|
|
527
|
+
dropped.push({ title: draft.title, quotePreview: preview, reason: 'quote-too-short' });
|
|
419
528
|
continue;
|
|
420
529
|
}
|
|
421
530
|
const source = sources.find((candidate) => squash(candidate.text).includes(quote));
|
|
422
531
|
if (source === undefined) {
|
|
423
532
|
unsupported += 1;
|
|
533
|
+
dropped.push({ title: draft.title, quotePreview: preview, reason: 'not-in-transcript' });
|
|
424
534
|
continue;
|
|
425
535
|
}
|
|
426
536
|
verified.push({ ...draft, evidenceSeq: source.seq });
|
|
427
537
|
}
|
|
428
|
-
return { drafts: verified, unsupported };
|
|
538
|
+
return { drafts: verified, unsupported, dropped };
|
|
429
539
|
}
|
|
430
540
|
/** The user's local calendar date, as `YYYY-MM-DD`, for resolving relative times. */
|
|
431
541
|
function localDate(now = new Date()) {
|
|
@@ -519,6 +629,7 @@ export async function runExtraction(llm, request) {
|
|
|
519
629
|
summary: salvaged.summary,
|
|
520
630
|
dropped: salvaged.dropped,
|
|
521
631
|
unsupported: bound.unsupported,
|
|
632
|
+
...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped },
|
|
522
633
|
route,
|
|
523
634
|
truncated: true,
|
|
524
635
|
...usage === undefined ? {} : { usage },
|
|
@@ -536,7 +647,7 @@ export async function runExtraction(llm, request) {
|
|
|
536
647
|
if (bound.drafts.length === 0) {
|
|
537
648
|
return { kind: 'none', reason: 'unsupported-evidence', route, ...usage === undefined ? {} : { usage } };
|
|
538
649
|
}
|
|
539
|
-
return { kind: 'memories', drafts: bound.drafts, loops: parsed.loops, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, route, ...usage === undefined ? {} : { usage } };
|
|
650
|
+
return { kind: 'memories', drafts: bound.drafts, loops: parsed.loops, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, ...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped }, route, ...usage === undefined ? {} : { usage } };
|
|
540
651
|
}
|
|
541
652
|
/**
|
|
542
653
|
* Close a JSON reply the output cap cut in half.
|