@samuelchung2010/dshift 0.0.0-stage → 0.3.0

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +116 -0
  4. package/README.md +116 -3
  5. package/assets/dshift-readme.gif +0 -0
  6. package/client.js +18831 -0
  7. package/cordis.patch.yml +58 -0
  8. package/docs/architecture.md +203 -0
  9. package/docs/configuration.md +103 -0
  10. package/docs/development.md +125 -0
  11. package/docs/limitations.md +74 -0
  12. package/docs/math-boxed-qquad.png +0 -0
  13. package/docs/math-boxed-single.png +0 -0
  14. package/docs/memory-integration.md +111 -0
  15. package/docs/perf/baseline-before.json +4872 -0
  16. package/docs/perf/baseline-before.summary.json +659 -0
  17. package/docs/perf/fixed-after.json +2927 -0
  18. package/docs/perf/fixed-after.summary.json +583 -0
  19. package/docs/perf/long-chat-performance.md +340 -0
  20. package/docs/perf/merged-after.json +1953 -0
  21. package/docs/perf/merged-after.summary.json +382 -0
  22. package/docs/perf/mount-after.json +82 -0
  23. package/docs/perf/mount-baseline.json +82 -0
  24. package/docs/user-guide.md +202 -0
  25. package/icon.svg +13 -0
  26. package/index.js +16 -0
  27. package/lib/api.js +336 -0
  28. package/lib/artifact/approval-bus.js +94 -0
  29. package/lib/artifact/prompt.js +99 -0
  30. package/lib/artifact/service.js +602 -0
  31. package/lib/artifact/workspace.js +260 -0
  32. package/lib/import/convert.js +343 -0
  33. package/lib/import/format.js +262 -0
  34. package/lib/import/index.js +585 -0
  35. package/lib/import/media.js +101 -0
  36. package/lib/import/zip.js +296 -0
  37. package/lib/memory-store.js +629 -0
  38. package/lib/memory-text.js +162 -0
  39. package/lib/memory.js +871 -0
  40. package/lib/model-config.js +280 -0
  41. package/lib/protocol.js +593 -0
  42. package/lib/service.js +2102 -0
  43. package/lib/store.js +1011 -0
  44. package/locale/en.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +49 -6
@@ -0,0 +1,629 @@
1
+ /**
2
+ * Durable long-term memory for Chat mode. One JSON document under
3
+ * `$DSH_HOME/deepseek-chat`, separate from the conversation history, written
4
+ * atomically and serialized per process.
5
+ *
6
+ * A memory is a single durable fact about the user (a standing instruction, a
7
+ * background fact, a project, a preference). The store owns the facts; the
8
+ * memory summary is only a cache derived from them, invalidated whenever the
9
+ * fact set changes. Deleted memories leave a tombstone so an old conversation
10
+ * cannot silently bring them back through automatic extraction.
11
+ */
12
+
13
+ import { promises as fs } from 'node:fs'
14
+ import path from 'node:path'
15
+ import { randomUUID } from 'node:crypto'
16
+ import {
17
+ MAX_MEMORY_CHARS, MEMORY_CATEGORY_IDS, inferMemoryCategory, looksSensitive,
18
+ memoryContentKey, memorySimilarity, normalizeMemoryCategory, normalizeMemoryContent,
19
+ } from './memory-text.js'
20
+
21
+ export const MEMORY_VERSION = 1
22
+ export const MAX_MEMORIES = 400
23
+ export const MAX_IMPORT_ENTRIES = 200
24
+ export const MAX_TOMBSTONES = 400
25
+ export const MAX_SUMMARY_CHARS = 4000
26
+ /** A near-identical wording is merged instead of creating a second entry. */
27
+ export const MERGE_SIMILARITY = 0.76
28
+ /** A looser overlap is still reported as a possible duplicate by import preview. */
29
+ export const MATCH_SIMILARITY = 0.55
30
+ /** A tombstone also blocks a re-worded re-extraction of the same fact. */
31
+ export const TOMBSTONE_SIMILARITY = 0.8
32
+
33
+ const SOURCE_TYPES = new Set(['manual', 'conversation', 'import', 'agent'])
34
+ const PLATFORMS = new Set(['chatgpt', 'claude', 'gemini', 'other'])
35
+
36
+ export function defaultMemorySettings() {
37
+ // The memory feature is useful with an empty store, so it starts enabled;
38
+ // automatic extraction spends model calls and is opt-in.
39
+ return { enabled: true, autoExtract: false }
40
+ }
41
+
42
+ function normalizeSettings(input) {
43
+ const base = defaultMemorySettings()
44
+ if (input === null || typeof input !== 'object') return base
45
+ if (typeof input.enabled === 'boolean') base.enabled = input.enabled
46
+ if (typeof input.autoExtract === 'boolean') base.autoExtract = input.autoExtract
47
+ return base
48
+ }
49
+
50
+ function normalizeSource(input) {
51
+ if (input === null || typeof input !== 'object') return { type: 'manual', platform: null, conversationId: null, label: null }
52
+ const type = SOURCE_TYPES.has(input.type) ? input.type : 'manual'
53
+ const platform = PLATFORMS.has(input.platform) ? input.platform : null
54
+ const conversationId = typeof input.conversationId === 'string' && input.conversationId !== ''
55
+ ? input.conversationId.slice(0, 80)
56
+ : null
57
+ const label = typeof input.label === 'string' && input.label.trim() !== ''
58
+ ? input.label.replace(/\s+/g, ' ').trim().slice(0, 80)
59
+ : null
60
+ return { type, platform, conversationId, label }
61
+ }
62
+
63
+ function normalizeMemory(input) {
64
+ if (input === null || typeof input !== 'object') return null
65
+ const content = normalizeMemoryContent(input.content)
66
+ if (content === '') return null
67
+ const category = normalizeMemoryCategory(input.category) ?? inferMemoryCategory(content)
68
+ const createdAt = typeof input.createdAt === 'number' && Number.isFinite(input.createdAt) ? input.createdAt : Date.now()
69
+ return {
70
+ id: typeof input.id === 'string' && input.id !== '' ? input.id : randomUUID(),
71
+ content,
72
+ category,
73
+ createdAt,
74
+ updatedAt: typeof input.updatedAt === 'number' && Number.isFinite(input.updatedAt) ? input.updatedAt : createdAt,
75
+ source: normalizeSource(input.source),
76
+ }
77
+ }
78
+
79
+ function normalizeSummary(input) {
80
+ if (input === null || typeof input !== 'object') return null
81
+ const text = typeof input.text === 'string' ? input.text.trim().slice(0, MAX_SUMMARY_CHARS) : ''
82
+ if (text === '') return null
83
+ return {
84
+ text,
85
+ locale: input.locale === 'en' ? 'en' : 'zh',
86
+ updatedAt: typeof input.updatedAt === 'number' && Number.isFinite(input.updatedAt) ? input.updatedAt : Date.now(),
87
+ revision: typeof input.revision === 'number' && Number.isFinite(input.revision) ? Math.max(0, Math.floor(input.revision)) : 0,
88
+ }
89
+ }
90
+
91
+ function normalizeTombstones(input) {
92
+ const list = []
93
+ const seen = new Set()
94
+ for (const raw of Array.isArray(input) ? input : []) {
95
+ if (raw === null || typeof raw !== 'object') continue
96
+ const content = normalizeMemoryContent(raw.content)
97
+ const key = memoryContentKey(content)
98
+ if (content === '' || key === '' || seen.has(key)) continue
99
+ seen.add(key)
100
+ list.push({
101
+ key,
102
+ content,
103
+ at: typeof raw.at === 'number' && Number.isFinite(raw.at) ? raw.at : Date.now(),
104
+ })
105
+ }
106
+ return list.slice(-MAX_TOMBSTONES)
107
+ }
108
+
109
+ function emptyState() {
110
+ return {
111
+ version: MEMORY_VERSION,
112
+ settings: defaultMemorySettings(),
113
+ revision: 0,
114
+ memories: [],
115
+ summary: null,
116
+ tombstones: [],
117
+ }
118
+ }
119
+
120
+ function normalizeState(parsed) {
121
+ const memoryRecords = []
122
+ const seenIds = new Set()
123
+ const seenKeys = new Set()
124
+ for (const raw of Array.isArray(parsed?.memories) ? parsed.memories : []) {
125
+ const memory = normalizeMemory(raw)
126
+ if (memory === null || seenIds.has(memory.id)) continue
127
+ const key = memoryContentKey(memory.content)
128
+ if (key === '' || seenKeys.has(key)) continue
129
+ seenIds.add(memory.id)
130
+ seenKeys.add(key)
131
+ memoryRecords.push(memory)
132
+ }
133
+ memoryRecords.sort((left, right) => right.updatedAt - left.updatedAt)
134
+ const revision = typeof parsed?.revision === 'number' && Number.isFinite(parsed.revision)
135
+ ? Math.max(0, Math.floor(parsed.revision))
136
+ : 0
137
+ return {
138
+ version: MEMORY_VERSION,
139
+ settings: normalizeSettings(parsed?.settings),
140
+ revision,
141
+ memories: memoryRecords.slice(0, MAX_MEMORIES),
142
+ summary: normalizeSummary(parsed?.summary),
143
+ tombstones: normalizeTombstones(parsed?.tombstones),
144
+ }
145
+ }
146
+
147
+ function copyMemory(memory) {
148
+ return { ...memory, source: { ...memory.source } }
149
+ }
150
+
151
+ /** Whether a candidate is a near copy of a tombstoned (deleted) memory. */
152
+ function tombstoneHit(tombstones, content) {
153
+ const key = memoryContentKey(content)
154
+ for (const tombstone of tombstones) {
155
+ if (tombstone.key === key) return tombstone
156
+ if (memorySimilarity(content, tombstone.content) >= TOMBSTONE_SIMILARITY) return tombstone
157
+ }
158
+ return null
159
+ }
160
+
161
+ export class MemoryStore {
162
+ /**
163
+ * @param directory - the Chat data directory (`$DSH_HOME/deepseek-chat`).
164
+ * @param options.logger - logger used for recoverable load/save problems.
165
+ */
166
+ constructor(directory, { logger = console } = {}) {
167
+ this.directory = directory
168
+ this.file = path.join(directory, 'memory.json')
169
+ this.logger = logger
170
+ this.state = emptyState()
171
+ this.loaded = false
172
+ this.writeChain = Promise.resolve()
173
+ this.extractionController = new AbortController()
174
+ }
175
+
176
+ async load() {
177
+ if (this.loaded) return this
178
+ await fs.mkdir(this.directory, { recursive: true })
179
+ let raw
180
+ try {
181
+ raw = await fs.readFile(this.file, 'utf8')
182
+ } catch (error) {
183
+ if (error?.code !== 'ENOENT') throw error
184
+ this.loaded = true
185
+ return this
186
+ }
187
+ let parsed
188
+ try {
189
+ parsed = JSON.parse(raw)
190
+ } catch (error) {
191
+ // A corrupt memory file must never break chat. Keep the unreadable
192
+ // document for manual recovery and start from an empty memory set.
193
+ const backup = `${this.file}.corrupt-${Date.now()}`
194
+ await fs.rename(this.file, backup).catch(() => {})
195
+ this.logger.warn?.('deepseek-chat: unreadable memory.json; starting with empty memory', error)
196
+ this.state = emptyState()
197
+ this.loaded = true
198
+ return this
199
+ }
200
+ const sourceVersion = typeof parsed?.version === 'number' ? parsed.version : 1
201
+ this.state = normalizeState(parsed)
202
+ this.loaded = true
203
+ if (sourceVersion < MEMORY_VERSION && this.state.memories.length > 0) {
204
+ // Keep the pre-upgrade document next to the live file so a future format
205
+ // change can always be undone by hand.
206
+ const backup = `${this.file}.v${sourceVersion}-backup-${Date.now()}`
207
+ try {
208
+ await fs.copyFile(this.file, backup)
209
+ this.logger.info?.(`deepseek-chat: backed up memory.json to ${path.basename(backup)} before migrating`)
210
+ await this.save()
211
+ } catch (error) {
212
+ this.logger.warn?.('deepseek-chat: could not migrate memory.json', error)
213
+ }
214
+ }
215
+ return this
216
+ }
217
+
218
+ getSettings() {
219
+ return { ...this.state.settings }
220
+ }
221
+
222
+ getAutoExtractionSignal() {
223
+ const { enabled, autoExtract } = this.state.settings
224
+ return enabled && autoExtract ? this.extractionController.signal : null
225
+ }
226
+
227
+ async updateSettings(patch) {
228
+ const previousSignal = this.getAutoExtractionSignal()
229
+ this.state.settings = normalizeSettings({ ...this.state.settings, ...(patch ?? {}) })
230
+ if (previousSignal !== null && this.getAutoExtractionSignal() === null) {
231
+ this.extractionController.abort()
232
+ this.extractionController = new AbortController()
233
+ }
234
+ await this.save()
235
+ return this.getSettings()
236
+ }
237
+
238
+ /** Whether the stored summary still describes the current fact set. */
239
+ summaryIsStale() {
240
+ if (this.state.memories.length === 0) return false
241
+ const { summary } = this.state
242
+ return summary === null || summary.revision !== this.state.revision
243
+ }
244
+
245
+ status() {
246
+ return {
247
+ enabled: this.state.settings.enabled,
248
+ autoExtract: this.state.settings.autoExtract,
249
+ count: this.state.memories.length,
250
+ revision: this.state.revision,
251
+ summaryUpdatedAt: this.state.summary?.updatedAt ?? null,
252
+ stale: this.summaryIsStale(),
253
+ }
254
+ }
255
+
256
+ /** Every active memory, newest first. */
257
+ list() {
258
+ return this.state.memories
259
+ .map(copyMemory)
260
+ .sort((left, right) => right.updatedAt - left.updatedAt)
261
+ }
262
+
263
+ categories() {
264
+ const counts = new Map(MEMORY_CATEGORY_IDS.map(id => [id, 0]))
265
+ for (const memory of this.state.memories) {
266
+ counts.set(memory.category, (counts.get(memory.category) ?? 0) + 1)
267
+ }
268
+ return MEMORY_CATEGORY_IDS.map(id => ({ id, count: counts.get(id) ?? 0 }))
269
+ }
270
+
271
+ get(id) {
272
+ if (typeof id !== 'string' || id === '') return undefined
273
+ const memory = this.state.memories.find(item => item.id === id)
274
+ return memory === undefined ? undefined : copyMemory(memory)
275
+ }
276
+
277
+ /** The best existing match for one candidate content, if any. */
278
+ findMatch(content, { excludeId = null } = {}) {
279
+ const text = normalizeMemoryContent(content)
280
+ if (text === '') return null
281
+ const key = memoryContentKey(text)
282
+ let best = null
283
+ for (const memory of this.state.memories) {
284
+ if (memory.id === excludeId) continue
285
+ if (memoryContentKey(memory.content) === key) {
286
+ return { kind: 'duplicate', memory: copyMemory(memory), score: 1 }
287
+ }
288
+ const score = memorySimilarity(text, memory.content)
289
+ if (score >= MATCH_SIMILARITY && (best === null || score > best.score)) {
290
+ best = { kind: 'conflict', memory: copyMemory(memory), score }
291
+ }
292
+ }
293
+ return best
294
+ }
295
+
296
+ snapshot() {
297
+ const summary = this.state.summary === null
298
+ ? null
299
+ : {
300
+ text: this.state.summary.text,
301
+ locale: this.state.summary.locale,
302
+ updatedAt: this.state.summary.updatedAt,
303
+ revision: this.state.summary.revision,
304
+ }
305
+ return {
306
+ settings: this.getSettings(),
307
+ memories: this.list(),
308
+ categories: this.categories(),
309
+ summary,
310
+ stale: this.summaryIsStale(),
311
+ revision: this.state.revision,
312
+ count: this.state.memories.length,
313
+ limits: { maxMemories: MAX_MEMORIES, maxContent: MAX_MEMORY_CHARS, maxImportEntries: MAX_IMPORT_ENTRIES },
314
+ }
315
+ }
316
+
317
+ async add({ content, category, source = { type: 'manual' }, origin = 'manual' } = {}) {
318
+ const text = normalizeMemoryContent(content)
319
+ if (text.length < 2) return { status: 'invalid' }
320
+ const normalizedCategory = normalizeMemoryCategory(category) ?? inferMemoryCategory(text)
321
+ if (origin !== 'manual') {
322
+ if (tombstoneHit(this.state.tombstones, text) !== null) return { status: 'skipped' }
323
+ if (looksSensitive(text)) return { status: 'skipped' }
324
+ } else {
325
+ this.forgetTombstone(text)
326
+ }
327
+ const match = this.findMatch(text)
328
+ if (match !== null) {
329
+ if (match.kind === 'duplicate') return { status: 'duplicate', memory: match.memory }
330
+ if (match.score >= MERGE_SIMILARITY) {
331
+ const memory = await this.mergeInto(match.memory.id, { content: text, category: normalizedCategory })
332
+ return memory === undefined ? { status: 'duplicate', memory: match.memory } : { status: 'merged', memory }
333
+ }
334
+ }
335
+ if (this.state.memories.length >= MAX_MEMORIES) {
336
+ return { status: 'limit', limit: MAX_MEMORIES }
337
+ }
338
+ const now = Date.now()
339
+ const memory = {
340
+ id: randomUUID(),
341
+ content: text,
342
+ category: normalizedCategory,
343
+ createdAt: now,
344
+ updatedAt: now,
345
+ source: normalizeSource(source),
346
+ }
347
+ this.state.memories.push(memory)
348
+ this.bumpRevision()
349
+ await this.save()
350
+ return { status: 'added', memory: copyMemory(memory) }
351
+ }
352
+
353
+ /** Merge a duplicate fact into one record, keeping the richer wording. */
354
+ async mergeInto(id, { content, category }) {
355
+ const memory = this.state.memories.find(item => item.id === id)
356
+ if (memory === undefined) return undefined
357
+ const text = normalizeMemoryContent(content)
358
+ if (text === '' || memoryContentKey(text) === '') return undefined
359
+ const previous = memory.content
360
+ const previousCategory = memory.category
361
+ const keepNew = text.length > previous.length + 4
362
+ memory.content = keepNew ? text : previous
363
+ if (normalizeMemoryCategory(category) !== undefined) memory.category = normalizeMemoryCategory(category)
364
+ memory.updatedAt = Date.now()
365
+ if (memory.content !== previous || memory.category !== previousCategory) this.bumpRevision()
366
+ await this.save()
367
+ return copyMemory(memory)
368
+ }
369
+
370
+ async update(id, patch) {
371
+ const memory = this.state.memories.find(item => item.id === id)
372
+ if (memory === undefined) return { status: 'not-found' }
373
+ const nextContent = patch?.content === undefined ? memory.content : normalizeMemoryContent(patch.content)
374
+ if (nextContent.length < 2) return { status: 'invalid' }
375
+ const nextCategory = normalizeMemoryCategory(patch?.category) ?? memory.category
376
+ const contentChanged = nextContent !== memory.content
377
+ const categoryChanged = nextCategory !== memory.category
378
+ if (!contentChanged && !categoryChanged) {
379
+ return { status: 'updated', memory: copyMemory(memory), unchanged: true }
380
+ }
381
+ if (contentChanged) {
382
+ const match = this.findMatch(nextContent, { excludeId: memory.id })
383
+ if (match !== null && (match.kind === 'duplicate' || match.score >= MERGE_SIMILARITY)) {
384
+ const merged = await this.mergeInto(match.memory.id, { content: nextContent, category: nextCategory })
385
+ if (merged !== undefined) {
386
+ this.state.memories = this.state.memories.filter(item => item.id !== memory.id)
387
+ this.state.summary = null
388
+ this.bumpRevision()
389
+ await this.save()
390
+ return { status: 'merged', memory: merged }
391
+ }
392
+ }
393
+ }
394
+ memory.content = nextContent
395
+ memory.category = nextCategory
396
+ memory.updatedAt = Date.now()
397
+ this.bumpRevision()
398
+ await this.save()
399
+ return { status: 'updated', memory: copyMemory(memory) }
400
+ }
401
+
402
+ async remove(id) {
403
+ const index = this.state.memories.findIndex(item => item.id === id)
404
+ if (index < 0) return false
405
+ const [removed] = this.state.memories.splice(index, 1)
406
+ this.rememberTombstone(removed.content)
407
+ this.state.summary = null
408
+ this.bumpRevision()
409
+ await this.save()
410
+ return true
411
+ }
412
+
413
+ /** Remove everything and tombstone it, so old chats cannot restore it. */
414
+ async clear() {
415
+ const count = this.state.memories.length
416
+ for (const memory of this.state.memories) this.rememberTombstone(memory.content)
417
+ this.state.memories = []
418
+ this.state.summary = null
419
+ this.bumpRevision()
420
+ await this.save()
421
+ return count
422
+ }
423
+
424
+ rememberTombstone(content) {
425
+ const text = normalizeMemoryContent(content)
426
+ const key = memoryContentKey(text)
427
+ if (text === '' || key === '') return
428
+ this.state.tombstones = this.state.tombstones.filter(item => item.key !== key)
429
+ this.state.tombstones.push({ key, content: text, at: Date.now() })
430
+ if (this.state.tombstones.length > MAX_TOMBSTONES) {
431
+ this.state.tombstones = this.state.tombstones.slice(-MAX_TOMBSTONES)
432
+ }
433
+ }
434
+
435
+ forgetTombstone(content) {
436
+ const key = memoryContentKey(content)
437
+ if (key === '') return
438
+ const before = this.state.tombstones.length
439
+ this.state.tombstones = this.state.tombstones.filter(item => item.key !== key)
440
+ if (this.state.tombstones.length !== before) this.bumpRevision()
441
+ }
442
+
443
+ bumpRevision() {
444
+ this.state.revision += 1
445
+ }
446
+
447
+ /** Match annotations for the import preview; never mutates anything. */
448
+ previewEntries(entries) {
449
+ const list = Array.isArray(entries) ? entries.slice(0, MAX_IMPORT_ENTRIES) : []
450
+ return {
451
+ entries: list.map((entry) => {
452
+ const content = normalizeMemoryContent(entry?.content)
453
+ const category = normalizeMemoryCategory(entry?.category) ?? inferMemoryCategory(content)
454
+ const match = content === '' ? null : this.findMatch(content)
455
+ return {
456
+ content,
457
+ category,
458
+ sensitive: looksSensitive(content),
459
+ match: match === null ? null : {
460
+ kind: match.kind,
461
+ id: match.memory.id,
462
+ content: match.memory.content,
463
+ category: match.memory.category,
464
+ score: Math.round(match.score * 100) / 100,
465
+ },
466
+ }
467
+ }),
468
+ limits: { maxMemories: MAX_MEMORIES, maxContent: MAX_MEMORY_CHARS, maxImportEntries: MAX_IMPORT_ENTRIES },
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Merge imported or extracted entries into the memory set. Import never
474
+ * replaces the whole store: each entry is added, merged or skipped on its
475
+ * own, so re-importing the same export adds nothing.
476
+ * @param entries - `{ content, category?, date?, mode? }` records.
477
+ * @param source - source metadata written on newly added memories.
478
+ * @param origin - "import" | "conversation" | "agent"; auto extraction
479
+ * additionally filters sensitive content and deleted tombstones.
480
+ */
481
+ async absorb(entries, { source = { type: 'import' }, origin = 'import', signal } = {}) {
482
+ const list = Array.isArray(entries) ? entries.slice(0, MAX_IMPORT_ENTRIES) : []
483
+ const result = { added: 0, merged: 0, updated: 0, skipped: 0, invalid: 0, limit: 0, items: [] }
484
+ let changed = false
485
+ for (const entry of list) {
486
+ if (signal?.aborted) break
487
+ const content = normalizeMemoryContent(entry?.content)
488
+ if (content.length < 2) {
489
+ result.invalid += 1
490
+ result.items.push({ content, status: 'invalid' })
491
+ continue
492
+ }
493
+ const mode = ['auto', 'merge', 'update', 'skip', 'add'].includes(entry?.mode) ? entry.mode : 'auto'
494
+ if (mode === 'skip') {
495
+ result.skipped += 1
496
+ result.items.push({ content, status: 'skipped' })
497
+ continue
498
+ }
499
+ if (origin !== 'manual') {
500
+ if (tombstoneHit(this.state.tombstones, content) !== null) {
501
+ result.skipped += 1
502
+ result.items.push({ content, status: 'skipped' })
503
+ continue
504
+ }
505
+ if (origin === 'conversation' && looksSensitive(content)) {
506
+ result.skipped += 1
507
+ result.items.push({ content, status: 'skipped' })
508
+ continue
509
+ }
510
+ }
511
+ const category = normalizeMemoryCategory(entry?.category) ?? inferMemoryCategory(content)
512
+ const match = this.findMatch(content)
513
+ if (mode === 'update' && match !== null) {
514
+ const updated = await this.update(match.memory.id, { content, category })
515
+ if (updated.status === 'updated' || updated.status === 'merged') {
516
+ changed = true
517
+ result.updated += 1
518
+ result.items.push({ content, status: 'updated', memoryId: updated.memory.id })
519
+ continue
520
+ }
521
+ }
522
+ if (match !== null && (mode === 'merge' || (mode === 'auto' && match.score >= MERGE_SIMILARITY))) {
523
+ if (match.kind === 'duplicate' && mode === 'auto') {
524
+ result.skipped += 1
525
+ result.items.push({ content, status: 'skipped', memoryId: match.memory.id })
526
+ continue
527
+ }
528
+ const merged = await this.mergeInto(match.memory.id, { content, category })
529
+ if (merged !== undefined) {
530
+ changed = true
531
+ result.merged += 1
532
+ result.items.push({ content, status: 'merged', memoryId: merged.id })
533
+ continue
534
+ }
535
+ }
536
+ if (match !== null && match.kind === 'duplicate') {
537
+ result.skipped += 1
538
+ result.items.push({ content, status: 'skipped', memoryId: match.memory.id })
539
+ continue
540
+ }
541
+ if (this.state.memories.length >= MAX_MEMORIES) {
542
+ result.limit += 1
543
+ result.items.push({ content, status: 'limit' })
544
+ continue
545
+ }
546
+ const now = Date.now()
547
+ const memory = {
548
+ id: randomUUID(),
549
+ content,
550
+ category,
551
+ createdAt: now,
552
+ updatedAt: now,
553
+ source: normalizeSource(source),
554
+ }
555
+ this.state.memories.push(memory)
556
+ this.bumpRevision()
557
+ changed = true
558
+ result.added += 1
559
+ result.items.push({ content, status: 'added', memoryId: memory.id })
560
+ }
561
+ if (changed) await this.save()
562
+ return result
563
+ }
564
+
565
+ getSummary() {
566
+ const summary = this.state.summary
567
+ if (summary === null) return null
568
+ return { ...summary }
569
+ }
570
+
571
+ /**
572
+ * Store a generated summary. An empty memory set drops the summary instead;
573
+ * the summary always remembers which fact revision it describes.
574
+ */
575
+ async setSummary(summary, revision = this.state.revision) {
576
+ if (revision !== this.state.revision) return this.getSummary()
577
+ const text = typeof summary?.text === 'string' ? summary.text.trim().slice(0, MAX_SUMMARY_CHARS) : ''
578
+ if (text === '' || this.state.memories.length === 0) {
579
+ this.state.summary = null
580
+ } else {
581
+ this.state.summary = {
582
+ text,
583
+ locale: summary?.locale === 'en' ? 'en' : 'zh',
584
+ updatedAt: Date.now(),
585
+ revision,
586
+ }
587
+ }
588
+ await this.save()
589
+ return this.getSummary()
590
+ }
591
+
592
+ async save() {
593
+ const write = () => this.writeNow()
594
+ this.writeChain = this.writeChain.then(write, write)
595
+ return this.writeChain
596
+ }
597
+
598
+ serializable() {
599
+ return {
600
+ version: MEMORY_VERSION,
601
+ settings: this.state.settings,
602
+ revision: this.state.revision,
603
+ summary: this.state.summary,
604
+ memories: this.state.memories,
605
+ tombstones: this.state.tombstones,
606
+ }
607
+ }
608
+
609
+ async writeNow() {
610
+ const temporary = `${this.file}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`
611
+ await fs.mkdir(this.directory, { recursive: true })
612
+ await fs.writeFile(temporary, `${JSON.stringify(this.serializable())}\n`, 'utf8')
613
+ try {
614
+ await fs.rename(temporary, this.file)
615
+ } catch (error) {
616
+ if (error?.code === 'EEXIST' || error?.code === 'EPERM' || error?.code === 'EACCES') {
617
+ await fs.copyFile(temporary, this.file)
618
+ await fs.rm(temporary, { force: true })
619
+ } else {
620
+ await fs.rm(temporary, { force: true }).catch(() => {})
621
+ throw error
622
+ }
623
+ }
624
+ }
625
+
626
+ async flush() {
627
+ await this.writeChain
628
+ }
629
+ }