dsh-memu-memory 1.2.8 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/backup.js +154 -25
  5. package/lib/binding-diagnostics.js +1 -2
  6. package/lib/budget.js +0 -9
  7. package/lib/client.js +221 -128
  8. package/lib/commitment.js +3 -3
  9. package/lib/consolidation-ledger.js +5 -2
  10. package/lib/curator-policy.js +23 -0
  11. package/lib/cycle.js +8 -4
  12. package/lib/embedding-download.js +168 -28
  13. package/lib/embedding-runtime.js +76 -17
  14. package/lib/engine.js +0 -6
  15. package/lib/freshness.js +2 -2
  16. package/lib/graph.js +139 -11
  17. package/lib/index.js +71 -20
  18. package/lib/inject.js +50 -7
  19. package/lib/lexicon.js +61 -16
  20. package/lib/local-vector-service.js +21 -1
  21. package/lib/media.js +49 -12
  22. package/lib/memory.js +662 -116
  23. package/lib/paths.js +0 -7
  24. package/lib/preset-scope.js +6 -1
  25. package/lib/private.js +45 -7
  26. package/lib/prompts.js +0 -7
  27. package/lib/rpc.js +95 -17
  28. package/lib/snippet.js +18 -2
  29. package/lib/state.js +109 -30
  30. package/lib/stats.js +2 -2
  31. package/lib/temporal.js +19 -0
  32. package/lib/text-retrieval.js +120 -44
  33. package/lib/text-similarity.js +205 -24
  34. package/lib/tokenizer-v2.js +0 -24
  35. package/lib/vector-migration.js +15 -0
  36. package/lib/vector-profile.js +81 -8
  37. package/lib/visibility.js +0 -4
  38. package/lib/webui/standalone.css +17 -22
  39. package/lib/webui/standalone.js +27 -9
  40. package/lib/webui.js +4 -4
  41. package/package.json +3 -2
  42. package/scripts/acceptance-local.mjs +2 -2
  43. package/scripts/check-all.mjs +3 -1
  44. package/scripts/check-i18n.mjs +35 -1
  45. package/scripts/migrate-visibility.mjs +3 -3
  46. package/scripts/prune-sessions.mjs +34 -0
  47. package/scripts/prune-vectors.mjs +24 -0
  48. package/tests/appendix-b.test.mjs +5 -4
  49. package/tests/audit-batch3.test.mjs +247 -0
  50. package/tests/audit-regression.test.mjs +2 -2
  51. package/tests/backup.test.mjs +83 -83
  52. package/tests/browser.test.mjs +6 -1
  53. package/tests/client-render.test.mjs +2 -2
  54. package/tests/curator-clusters.test.mjs +18 -0
  55. package/tests/curator-pairing.test.mjs +59 -16
  56. package/tests/dynamic-rrf.test.mjs +22 -19
  57. package/tests/dynamic-threshold.test.mjs +52 -0
  58. package/tests/fact-version.test.mjs +18 -0
  59. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  60. package/tests/graph-cascade.test.mjs +29 -0
  61. package/tests/graph.test.mjs +45 -0
  62. package/tests/inject-conflict.test.mjs +18 -0
  63. package/tests/lexical-bm25.test.mjs +171 -0
  64. package/tests/lexicon-frequency.test.mjs +16 -0
  65. package/tests/lexicon-inject.test.mjs +21 -0
  66. package/tests/lexicon-perf.test.mjs +37 -9
  67. package/tests/lexicon-scope.test.mjs +2 -2
  68. package/tests/lexicon-ui.test.mjs +1 -1
  69. package/tests/managed-memory.test.mjs +19 -0
  70. package/tests/ops-hardening.test.mjs +209 -0
  71. package/tests/package-shipping.test.mjs +4 -0
  72. package/tests/recall-intent.test.mjs +23 -0
  73. package/tests/slot-similarity.test.mjs +153 -0
  74. package/tests/state-gc.test.mjs +34 -0
  75. package/tests/state.test.mjs +2 -2
  76. package/tests/tokenizer-v2.test.mjs +1 -1
  77. package/tests/vector-gc.test.mjs +37 -0
  78. package/tests/webui.test.mjs +27 -0
package/lib/paths.js CHANGED
@@ -267,13 +267,6 @@ export function windowsSystemEnv(platform = process.platform, env = process.env)
267
267
  return overlay
268
268
  }
269
269
 
270
- export function safeSegment(value, fallback = 'unknown') {
271
- const text = String(value ?? '').trim()
272
- if (!text) return fallback
273
- const cleaned = text.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')
274
- return cleaned || fallback
275
- }
276
-
277
270
  export function isSafeId(value) {
278
271
  return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value) && value !== '.' && value !== '..'
279
272
  }
@@ -114,8 +114,13 @@ export function registerPresetAttachment(ctx, { log = () => {}, intervalMs = ATT
114
114
  timer.unref?.()
115
115
  return () => {
116
116
  clearInterval(timer)
117
- for (const [, dispose] of attached.entries()) {
117
+ for (const [agentCtx, dispose] of attached.entries()) {
118
118
  try { dispose?.() } catch {}
119
+ // S-5: this Map is a strong reference. Detaching without deleting left every
120
+ // disposed agent context reachable for the life of the process, and a context
121
+ // that ever came back through the same key would still read as "attached" and
122
+ // never be registered again.
123
+ attached.delete(agentCtx)
119
124
  }
120
125
  }
121
126
  }
package/lib/private.js CHANGED
@@ -533,9 +533,14 @@ function workerToolsMeta(workerTools) {
533
533
  }
534
534
 
535
535
  const inFlight = new Map()
536
+ // How long a cancelled fork gets to finish the tool call it was in the middle of.
537
+ // Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
538
+ // the alternative — disposing immediately — is what let a write land after the range
539
+ // was already handed back to pending.
540
+ const WORKER_STOP_GRACE_MS = 5_000
536
541
 
537
542
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
538
- // 的 file:line 当成诊断契约(当前 lib/private.js:528),修改位置时同步更新该诊断映射,
543
+ // 的 file:line 当成诊断契约(当前 lib/private.js:535),修改位置时同步更新该诊断映射,
539
544
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
540
545
  import { warn } from './paths.js'
541
546
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
@@ -615,6 +620,34 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
615
620
  inFlight.set(sessionId, abort)
616
621
  let handle = null
617
622
  let offSession = null
623
+ let idle = null
624
+ // Stopped once, callable twice: the timeout path and `finally` both need it.
625
+ let stopped = false
626
+ // The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
627
+ // wait for a tool call in flight, and this fork writes memories *through tools*, so
628
+ // "the fork was stopped" was not true when the timeout path returned: failJob had
629
+ // already handed the range back and the next pass could fork the same window while
630
+ // the old child was still writing. Bounded, because a child that ignores the cancel
631
+ // must not hang the sweep.
632
+ const stopWorker = async () => {
633
+ if (stopped) return
634
+ stopped = true
635
+ try { abort.abort() } catch {}
636
+ try { offSession?.() } catch {}
637
+ if (idle) {
638
+ try {
639
+ await Promise.race([
640
+ idle.then(() => {}, () => {}),
641
+ // Deliberately NOT unref'd: this promise is what we are awaiting, so an
642
+ // unref'd timer lets the event loop drain while the await is still pending
643
+ // and the caller (or the test runner) is left holding a promise that can
644
+ // never settle. A <=5s hold on the loop is the correct trade.
645
+ new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
646
+ ])
647
+ } catch {}
648
+ }
649
+ try { await handle?.dispose?.() } catch {}
650
+ }
618
651
  let turnEnd = null
619
652
  let jobId = null
620
653
  let scopeChanged = null
@@ -1024,7 +1057,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1024
1057
  handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
1025
1058
  // followup only queues. whenIdle says the driver stopped; turn/end says
1026
1059
  // whether that turn actually succeeded, so both are checked below.
1027
- const idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
1060
+ idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
1028
1061
  let timer = null
1029
1062
  let outcome
1030
1063
  try {
@@ -1113,7 +1146,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1113
1146
  // `result.error` and an empty string there is indistinguishable from a click
1114
1147
  // that did nothing at all (observed: two clicks, no feedback, no memories).
1115
1148
  if (outcome === 'timeout') {
1116
- safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'timeout', error: 'timed out before a receipt' }))
1149
+ // Stop the writer before releasing the range, not after. Waiting matters here
1150
+ // because a tool call already in flight can still land a memory on disk, and the
1151
+ // range going back to pending is what lets the next pass redo this window.
1152
+ await stopWorker()
1153
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'timeout', error: 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written' }))
1117
1154
  return finish({
1118
1155
  ok: false,
1119
1156
  sessionId,
@@ -1121,7 +1158,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1121
1158
  settled: false,
1122
1159
  timedOut: true,
1123
1160
  reasonCode: 'timeout',
1124
- error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
1161
+ // The next pass must not assume this window left nothing behind: the range is
1162
+ // pending again and some writes may already have landed.
1163
+ partialWritesPossible: true,
1164
+ error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
1125
1165
  })
1126
1166
  }
1127
1167
  return finish({
@@ -1153,10 +1193,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1153
1193
  return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
1154
1194
  } finally {
1155
1195
  inFlight.delete(sessionId)
1156
- abort.abort()
1157
- try { offSession?.() } catch {}
1196
+ try { await stopWorker() } catch {}
1158
1197
  try { workerTools?.dispose?.() } catch {}
1159
- try { await handle?.dispose?.() } catch {}
1160
1198
  try { if (childId) deleteSessionBinding(childId) } catch {}
1161
1199
  }
1162
1200
  }
package/lib/prompts.js CHANGED
@@ -302,11 +302,4 @@ export function syncPromptDefaults() {
302
302
  return getPromptStates()
303
303
  }
304
304
 
305
- export function promptDefaultsVersion() {
306
- return allDefs().map((def) => {
307
- const text = readText(defaultPath(def)) || ''
308
- return `${def.key}:${hash(text)}`
309
- }).join(',')
310
- }
311
-
312
305
  export { DEFAULT_DIR }
package/lib/rpc.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
9
9
  } from './state.js'
10
10
  import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
11
- import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
11
+ import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, previewDelete, restoreDeleted, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, recordImportBatch, revertImportBatch, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
14
14
  import { listHostModelOptions, discoverForkModels, redactConsolidationSettings, disposeConsolidationRoute } from './fork-model.js'
@@ -23,7 +23,7 @@ import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH }
23
23
  import { getGraph, listEntities, createEntity, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
24
24
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
25
25
  import { listEvents, logStats, clearEvents } from './activity-log.js'
26
- import { warn } from './paths.js'
26
+ import { redactSecrets, warn } from './paths.js'
27
27
  import { GLOBAL_LEXICON_ID } from './lexicon.js'
28
28
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
29
29
 
@@ -100,6 +100,21 @@ function routeLibraryId(endpoint, payload) {
100
100
 
101
101
  let capabilityAbsentWarned = false
102
102
 
103
+ // Everything that leaves this file as an error string goes through here.
104
+ //
105
+ // The RPC boundary is the one place a message reaches a renderer, a log file and a
106
+ // bug report at once, and the errors that flow through it are not all ours: a
107
+ // provider SDK quotes the request URL and sometimes the Authorization header, a
108
+ // Python traceback can echo a connection string, and a config error can print the
109
+ // key it choked on. `memu.js` already redacts per command line; this is the same rule
110
+ // applied once at the exit, so no single forgotten path can leak. The length cap
111
+ // keeps a wall of traceback out of the UI as well.
112
+ const RPC_ERROR_MAX_CHARS = 600
113
+ function rpcErrorMessage(error) {
114
+ const raw = String(error?.message || error || 'unknown error')
115
+ try { return redactSecrets(raw).slice(0, RPC_ERROR_MAX_CHARS) } catch { return raw.slice(0, RPC_ERROR_MAX_CHARS) }
116
+ }
117
+
103
118
  // One capability gate for both routes: absent callback falls back to the HTTP
104
119
  // boundary (requestRejection) and warns once; a present callback is strict true.
105
120
  // Keeping one helper makes the session-first / capability-second order identical
@@ -296,7 +311,10 @@ async function mergeLexiconImport(libraryId, member) {
296
311
  if (!byKey.has(key)) byKey.set(key, { termId, entry: e })
297
312
  }
298
313
  }
299
- const report = { version: 1, applied: 0, added: 0, updated: 0, revisions: 0, skipped: [], failed: [] }
314
+ // `addedTermIds` is what makes the import reversible: a term created by this package
315
+ // has no memory id to find it by later, and an updated one must not be deleted on
316
+ // revert (it existed before). Only creations are recorded.
317
+ const report = { version: 1, applied: 0, added: 0, updated: 0, revisions: 0, addedTermIds: [], skipped: [], failed: [] }
300
318
  for (const raw of member.terms) {
301
319
  const label = typeof raw?.term === 'string' ? raw.term : ''
302
320
  try {
@@ -359,11 +377,15 @@ async function mergeLexiconImport(libraryId, member) {
359
377
  })
360
378
  report.applied += 1
361
379
  if (out?.created === false) report.updated += 1
362
- else report.added += 1
380
+ else {
381
+ report.added += 1
382
+ const termId = out?.term?.id || out?.term?.termId || null
383
+ if (termId) report.addedTermIds.push(String(termId))
384
+ }
363
385
  // revisions 在当前生命周期恒为 0(§2.1 不再生成 pending revision);字段保留只为报告
364
386
  // 形状稳定,旧客户端继续拿到一个数字。
365
387
  } catch (error) {
366
- report.failed.push({ term: label, reason: String(error?.message || error).slice(0, 300) })
388
+ report.failed.push({ term: label, reason: rpcErrorMessage(error).slice(0, 300) })
367
389
  }
368
390
  }
369
391
  return report
@@ -1162,7 +1184,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1162
1184
  const id = String(payload?.libraryId || '')
1163
1185
  if (!getLibrary(id)) throw new Error('library not found')
1164
1186
  if (getLibrary(id).archived !== true) throw new Error('archive the library before deleting it')
1165
- const safety = backupDatabases()
1187
+ const safety = await backupDatabases()
1166
1188
  const result = deleteLibrary(id)
1167
1189
  if (!result.ok) throw new Error(result.error)
1168
1190
  return { ok: true, safety, archived: archivedLibraryView() }
@@ -1276,16 +1298,37 @@ async function dispatch(ctx, endpoint, payload = {}) {
1276
1298
  case 'importMemories': {
1277
1299
  const id = String(payload?.libraryId || '')
1278
1300
  if (!getLibrary(id)) throw new Error('library not found')
1301
+ if (payload?.revertBatchId) {
1302
+ const reverted = await revertImportBatch({ libraryId: id, batchId: String(payload.revertBatchId) })
1303
+ // Lexicon terms live behind a lazily loaded module that memory.js must not
1304
+ // reach across for, so the undo happens here, where the api already exists.
1305
+ let lexiconReverted = 0
1306
+ if (reverted.lexiconTermIds?.length) {
1307
+ try {
1308
+ const lexicon = await lexiconApi()
1309
+ for (const termId of reverted.lexiconTermIds) {
1310
+ try { lexicon.deleteLexiconTerm({ libraryId: id, termId }); lexiconReverted += 1 } catch (error) {
1311
+ warn(`revert import: lexicon term ${termId} kept: ${error?.message || error}`)
1312
+ }
1313
+ }
1314
+ } catch (error) {
1315
+ warn(`revert import: lexicon module unavailable, terms kept: ${error?.message || error}`)
1316
+ }
1317
+ }
1318
+ return { ...reverted, lexiconReverted }
1319
+ }
1279
1320
  // The payload may be the parsed export (memories array) or the raw file text.
1280
1321
  let memories = payload?.memories
1281
1322
  let graphData = payload?.graph || null
1282
1323
  let lexiconData = payload?.lexicon && typeof payload.lexicon === 'object' && !Array.isArray(payload.lexicon) ? payload.lexicon : null
1283
1324
  let missingAttachments = 0
1325
+ let bundleId = payload?.bundleId ? String(payload.bundleId) : null
1284
1326
  if (payload?.archiveBase64) {
1285
1327
  const archive = importMediaBundle(id, Buffer.from(String(payload.archiveBase64), 'base64'))
1286
1328
  memories = archive.memories
1287
1329
  graphData = archive.graph
1288
1330
  missingAttachments = archive.missing
1331
+ bundleId = bundleId || archive.bundleId || null
1289
1332
  }
1290
1333
  if (typeof memories === 'string') {
1291
1334
  let parsed = null
@@ -1294,6 +1337,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1294
1337
  if (Array.isArray(parsed.memories)) {
1295
1338
  memories = parsed.memories
1296
1339
  graphData = parsed.graph || null
1340
+ bundleId = bundleId || (parsed.bundleId ? String(parsed.bundleId) : null)
1297
1341
  lexiconData = lexiconData || (parsed.lexicon && typeof parsed.lexicon === 'object' && !Array.isArray(parsed.lexicon) ? parsed.lexicon : null)
1298
1342
  }
1299
1343
  else throw new Error('this JSON has no "memories" array')
@@ -1301,13 +1345,25 @@ async function dispatch(ctx, endpoint, payload = {}) {
1301
1345
  else throw new Error('this JSON has no "memories" array')
1302
1346
  }
1303
1347
  if (!Array.isArray(memories)) throw new Error('memories must be an array')
1304
- const result = await importMemories({ libraryId: id, memories })
1305
- if (graphData && result.idMap) restoreGraphData(id, graphData, result.idMap)
1348
+ // One batch id per install: every entry created by this import carries it, so
1349
+ // `revertBatchId` can undo exactly this package without touching old rows.
1350
+ const importBatchId = bundleId || (payload?.importBatchId ? String(payload.importBatchId) : `bnd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`)
1351
+ const result = await importMemories({ libraryId: id, memories, importBatchId })
1352
+ const graphRestore = graphData && result.idMap ? restoreGraphData(id, graphData, result.idMap, { origin: importBatchId }) : null
1306
1353
  // 词典是版本化 member(§4.4):包里带了才合并恢复;term 冲突(规范化后同词)
1307
1354
  // 更新既有词条,active+sensitive 一律跳过并上报,超长字段按核心 clip 落地、
1308
1355
  // term 本身越界/归一化为空才进 failed。
1309
1356
  const lexiconReport = lexiconData ? await mergeLexiconImport(id, lexiconData) : null
1310
- const value = { libraryId: id, ...result, missingAttachments }
1357
+ // Record the manifest before answering: an import whose ledger is missing still
1358
+ // reverts its memories (index tag), but loses the graph and lexicon halves.
1359
+ recordImportBatch({
1360
+ libraryId: id,
1361
+ batchId: importBatchId,
1362
+ memories: result.ids || [],
1363
+ entities: graphRestore?.createdEntityIds || [],
1364
+ lexicon: lexiconReport?.addedTermIds || [],
1365
+ })
1366
+ const value = { libraryId: id, ...result, missingAttachments, importBatchId }
1311
1367
  return lexiconReport ? { ...value, lexicon: lexiconReport } : value
1312
1368
  }
1313
1369
  case 'exportLibrary': {
@@ -1323,10 +1379,11 @@ async function dispatch(ctx, endpoint, payload = {}) {
1323
1379
  const data = lexicon.loadLexicon(id)
1324
1380
  lexiconMember = { version: 1, terms: Object.entries(data.terms || {}).map(([termId, e]) => ({ id: termId, ...e })) }
1325
1381
  } catch (error) {
1326
- lexiconMember.unavailable = String(error?.message || error).slice(0, 300)
1382
+ lexiconMember.unavailable = rpcErrorMessage(error).slice(0, 300)
1327
1383
  }
1328
1384
  const exported = {
1329
1385
  format: 'dsh-memu-memory-library@1',
1386
+ bundleId: `bnd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1330
1387
  exportedAt: new Date().toISOString(),
1331
1388
  library: { id: lib.id, name: lib.name, scopeKey: lib.scopeKey || null, domain: lib.domain || null },
1332
1389
  memories: Object.entries(index.entries || {}).map(([memId, e]) => ({ id: memId, ...e })),
@@ -1767,9 +1824,17 @@ async function dispatch(ctx, endpoint, payload = {}) {
1767
1824
  const libraryId = String(payload?.libraryId || '')
1768
1825
  if (!libraryId) throw new Error('libraryId is required')
1769
1826
  if (!getLibrary(libraryId)) throw new Error('library not found')
1827
+ if (payload?.preview === true) return previewDelete({ libraryId, id })
1828
+ if (payload?.restore === true) return restoreDeleted({ libraryId, id })
1770
1829
  const entry = loadPrivateIndex(libraryId).entries[id]
1771
1830
  if (!entry || !['archived', 'suppressed', 'expired'].includes(entry.status)) throw new Error('only archived memories can be deleted permanently; archive it first')
1772
- const safety = backupDatabases()
1831
+ // Same gate every other irreversible operation in this file uses. The status check
1832
+ // above is a lifecycle rule, not consent: a caller that reached this line by
1833
+ // accident should not be able to erase a memory just because it happened to be
1834
+ // archived. Order matters — keeping this after the status check preserves the
1835
+ // "archive it first" refusal old callers depend on.
1836
+ if (payload?.confirmed !== true) throw new Error('permanently deleting a memory requires explicit confirmation')
1837
+ const safety = await backupDatabases()
1773
1838
  return { ...await privateDelete({ libraryId, id }), safety }
1774
1839
  }
1775
1840
  case 'setup': {
@@ -1809,7 +1874,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1809
1874
  return { ...result, backups: listBackups() }
1810
1875
  }
1811
1876
  case 'restoreBackup': {
1812
- const result = restoreBackup(String(payload?.name || ''), {
1877
+ const result = await restoreBackup(String(payload?.name || ''), {
1813
1878
  // Take a fresh backup of the live data before anything is replaced, so a
1814
1879
  // mistaken restore is itself reversible.
1815
1880
  beforeRestore: () => backupDatabases(),
@@ -1940,6 +2005,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1940
2005
  return { cleared: cleared.removed, feed: await consolidationFeed(ctx, payload) }
1941
2006
  }
1942
2007
  case 'clearActivityLog':
2008
+ // Bulk diagnostic evidence removal is destructive; the adjacent delete /
2009
+ // archive paths require an explicit confirmation and this one used to be a
2010
+ // single accidental click away.
2011
+ if (payload?.confirmed !== true) throw new Error('clearing the activity log requires explicit confirmation')
1943
2012
  return clearEvents()
1944
2013
  default:
1945
2014
  throw new Error(`unknown endpoint: ${endpoint}`)
@@ -1955,10 +2024,19 @@ export function registerRpc(ctx) {
1955
2024
  kind: 'prefix',
1956
2025
  path: ENDPOINT,
1957
2026
  handler: async (req, res) => {
1958
- const rejection = c.connection.requestRejection(req)
2027
+ // Capability probe, not a version check: `requestRejection` exists on
2028
+ // 0.1.2-rc.x and later of dsh-client-connection and not at all on the rc.8
2029
+ // / 0.1.1-rc.2 copies, where the service only exposes
2030
+ // `isTrustedApiRequest`. Calling it blindly threw a TypeError out of the
2031
+ // request handler, which the host turns into a 500 — an unauthenticated
2032
+ // caller then learned the route exists instead of being refused.
2033
+ const rejection = typeof c.connection?.requestRejection === 'function'
2034
+ ? c.connection.requestRejection(req)
2035
+ : undefined
1959
2036
  if (rejection !== undefined) {
1960
- res.writeHead(rejection)
1961
- res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
2037
+ const status = rejection === 401 ? 401 : 403
2038
+ res.writeHead(status)
2039
+ res.end(status === 401 ? 'unauthorized' : 'forbidden')
1962
2040
  return
1963
2041
  }
1964
2042
  const requestUrl = new URL(req.url || '/', 'http://dsh.internal')
@@ -1997,7 +2075,7 @@ export function registerRpc(ctx) {
1997
2075
  res.end(JSON.stringify({ ok: true, value: { ...value, missingAttachments: bundle.missing } }))
1998
2076
  } catch (error) {
1999
2077
  res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
2000
- res.end(JSON.stringify({ ok: false, error: { message: String(error.message || error) } }))
2078
+ res.end(JSON.stringify({ ok: false, error: { message: rpcErrorMessage(error) } }))
2001
2079
  }
2002
2080
  return
2003
2081
  }
@@ -2103,7 +2181,7 @@ export function registerRpc(ctx) {
2103
2181
  ok: false,
2104
2182
  error: {
2105
2183
  code: error?.code || 'dsh-memu-memory/error',
2106
- message: String(error?.message || error),
2184
+ message: rpcErrorMessage(error),
2107
2185
  details: {},
2108
2186
  },
2109
2187
  }
package/lib/snippet.js CHANGED
@@ -70,7 +70,20 @@ function clip(value, max) {
70
70
  /**
71
71
  * S2/S6 冲突卡:两条对同一事实的不同说法并排,不替模型裁决。
72
72
  * 单卡 200 字以内;两个 id 都必须出现,否则调用方应丢弃这张卡。
73
+ * P1-2: A/B 顺序只按本地 fact_authority + 时间排,不增加任何文字。
73
74
  */
75
+ const FACT_AUTHORITY = { user_said: 3, tool: 2, told: 2, inferred: 1, imagined: 0 }
76
+
77
+ function authorityOf(entry) {
78
+ const explicit = Number(entry?.fact_authority)
79
+ if (Number.isFinite(explicit)) return explicit
80
+ return FACT_AUTHORITY[entry?.source_kind || entry?.source] ?? 0
81
+ }
82
+
83
+ function observedOf(entry) {
84
+ return String(entry?.observed_at || entry?.updatedAt || entry?.createdAt || '')
85
+ }
86
+
74
87
  export function conflictCard({ factKey, left, right } = {}) {
75
88
  if (!left?.id || !right?.id) return ''
76
89
  const side = (item, label) => {
@@ -79,10 +92,13 @@ export function conflictCard({ factKey, left, right } = {}) {
79
92
  const date = entry.absolute_date ? `(${entry.absolute_date})` : ''
80
93
  return `- ${label} [${item.id}] ${clip(title, 40)}${date}`
81
94
  }
95
+ const ordered = [left, right].sort((a, b) => authorityOf(b.entry) - authorityOf(a.entry)
96
+ || observedOf(b.entry).localeCompare(observedOf(a.entry))
97
+ || String(a.id).localeCompare(String(b.id)))
82
98
  return clip([
83
99
  `冲突 · ${clip(factKey || '同一事实', 60)}`,
84
- side(left, 'A'),
85
- side(right, 'B'),
100
+ side(ordered[0], 'A'),
101
+ side(ordered[1], 'B'),
86
102
  '- 未确认哪版为准',
87
103
  ].join('\n'), 200)
88
104
  }
package/lib/state.js CHANGED
@@ -6,12 +6,12 @@ import {
6
6
  ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
7
7
  } from './paths.js'
8
8
  import {
9
- activeLeases, createBackup, deleteBackupEntry, listBackupEntries,
10
- pruneBackups, restoreFromBackup, withBackupLock,
9
+ createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
11
10
  } from './backup.js'
12
11
  import { migrateIndexVisibility } from './visibility.js'
13
12
  import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
14
13
  import { normalizeEmotion, derivedValence } from './mood.js'
14
+ import { localCalendarDay } from './temporal.js'
15
15
 
16
16
  const STATE_FILE = () => path.join(dataDir(), 'state.json')
17
17
  const GLOBAL_DB = () => path.join(dataDir(), 'global.sqlite3')
@@ -255,6 +255,11 @@ export function updateState(fn) {
255
255
  return next
256
256
  }
257
257
 
258
+ // Codes that mean "the store was momentarily unavailable", not "this write can never
259
+ // succeed". Only these are re-armed; a read-only filesystem or a corrupt path would
260
+ // otherwise retry forever at FLUSH_MS.
261
+ const RETRYABLE_FLUSH_CODES = ['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES']
262
+
258
263
  function scheduleFlush() {
259
264
  if (flushTimer) return
260
265
  flushTimer = setTimeout(() => {
@@ -263,7 +268,7 @@ function scheduleFlush() {
263
268
  flushState()
264
269
  } catch (error) {
265
270
  warnSinkSafe(`state flush failed: ${error?.message || error}`)
266
- if (['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES'].includes(error?.code)) scheduleFlush()
271
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
267
272
  }
268
273
  }, FLUSH_MS)
269
274
  flushTimer.unref?.()
@@ -276,7 +281,18 @@ export function flushState() {
276
281
  flushTimer = null
277
282
  }
278
283
  if (!dirty || !cache) return
279
- return withFileLock(STATE_FILE(), flushStateLocked)
284
+ try {
285
+ return withFileLock(STATE_FILE(), flushStateLocked)
286
+ } catch (error) {
287
+ // S-10: the timer was already cleared above, so a failed flush used to leave the
288
+ // pending bookkeeping dirty with nothing scheduled — one busy lock was enough to
289
+ // strand inbound pending / lastRecallError / sleepRetryAt in memory until the next
290
+ // unrelated write (or a crash). Re-arm before rethrowing so the batch is retried;
291
+ // the caller still sees the error.
292
+ warnSinkSafe(`state flush failed: ${error?.message || error}`)
293
+ if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
294
+ throw error
295
+ }
280
296
  }
281
297
 
282
298
  function mergeChanges(base, local, disk) {
@@ -1045,8 +1061,7 @@ export function markAnniversaryShown(sessionId, memoryId, dayKey) {
1045
1061
  const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
1046
1062
 
1047
1063
  function localDayKeyOf(date) {
1048
- const d = date instanceof Date ? date : new Date(date)
1049
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
1064
+ return localCalendarDay(date)
1050
1065
  }
1051
1066
 
1052
1067
  function prunedOpenLoopReminded(sessionId, now = new Date()) {
@@ -1329,12 +1344,22 @@ export function loadPrivateIndex(libraryId) {
1329
1344
  })
1330
1345
  }
1331
1346
 
1332
- export function savePrivateIndex(libraryId, index) {
1347
+ /**
1348
+ * Persist one library index.
1349
+ *
1350
+ * `bumpRevision: false` exists for writes that cannot change what recall would find:
1351
+ * the injector's own bookkeeping (injectCount / lastInjectAt) runs *after* every
1352
+ * successful injection, so bumping the revision there guaranteed that the next turn's
1353
+ * recall and BM25 corpus both missed. The write still happens, still notifies
1354
+ * listeners and still records the write event — only the "something a cached result
1355
+ * depends on changed" claim is withheld, because it is not true.
1356
+ */
1357
+ export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {}) {
1333
1358
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
1334
1359
  if (!validIndex(index)) throw new Error('invalid memory index shape')
1335
1360
  const file = path.join(indexDir(), `${libraryId}.json`)
1336
1361
  const saved = writeIndex(file, index)
1337
- bumpMemoryRevision()
1362
+ if (bumpRevision) bumpMemoryRevision()
1338
1363
  noteMemoryWrite('private', libraryId)
1339
1364
  for (const listener of indexWriteListeners) {
1340
1365
  try { listener(libraryId, saved) } catch (error) { warn(`memory sidecar update failed: ${error?.message || error}`) }
@@ -1354,10 +1379,10 @@ function validIndex(value) {
1354
1379
  && Object.values(value.entries).every(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
1355
1380
  }
1356
1381
 
1357
- export function saveGlobalIndex(index) {
1382
+ export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
1358
1383
  if (!validIndex(index)) throw new Error('invalid memory index shape')
1359
1384
  writeIndex(GLOBAL_INDEX(), index)
1360
- bumpMemoryRevision()
1385
+ if (bumpRevision) bumpMemoryRevision()
1361
1386
  noteMemoryWrite('global', null)
1362
1387
  }
1363
1388
 
@@ -1419,12 +1444,12 @@ export function newMemoryId(prefix = 'mem') {
1419
1444
  * Returns the published directory: callers (engine switch, library delete,
1420
1445
  * scripts) treat the return value as a path.
1421
1446
  */
1422
- export function backupDatabases(options = {}) {
1447
+ export async function backupDatabases(options = {}) {
1423
1448
  // Pending bookkeeping changes live in memory for up to 50ms; a backup taken
1424
1449
  // before a flush would silently capture the previous state.
1425
1450
  let report
1426
1451
  try {
1427
- report = createBackup({ ...options, flushState })
1452
+ report = await createBackup({ ...options, flushState })
1428
1453
  } catch (error) {
1429
1454
  // A refusal is the safety property working, not something to swallow: a
1430
1455
  // database the engine could not snapshot aborts the backup, and the reason
@@ -1468,22 +1493,6 @@ export function deleteBackup(name) {
1468
1493
  return { deleted: result.deleted, status: result.status }
1469
1494
  }
1470
1495
 
1471
- /**
1472
- * Applies the retention rule on demand. Creation already prunes, so this exists
1473
- * for the paths that must reclaim the space a protected restore target kept
1474
- * alive, and for callers that want the report without making a backup.
1475
- */
1476
- export function pruneOldBackups(options = {}) {
1477
- const result = pruneBackups(options)
1478
- lastBackupReport = { at: stamp(), action: 'prune', ...result }
1479
- return result
1480
- }
1481
-
1482
- /** Names of backups that a running restore or migration is reading right now. */
1483
- export function leasedBackups() {
1484
- return Object.keys(activeLeases())
1485
- }
1486
-
1487
1496
  /**
1488
1497
  * Puts a backup back. The target is leased and its whole inventory is verified
1489
1498
  * before anything is written; the live root is saved as a safety backup next;
@@ -1493,8 +1502,8 @@ export function leasedBackups() {
1493
1502
  * vector-active pointer, so recall falls back to text instead of querying
1494
1503
  * databases that no longer match the restored index.
1495
1504
  */
1496
- export function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1497
- const result = restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1505
+ export async function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
1506
+ const result = await restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
1498
1507
  lastBackupReport = { at: stamp(), action: 'restore', ...result }
1499
1508
  return result
1500
1509
  }
@@ -1510,3 +1519,73 @@ export function clearCaches() {
1510
1519
  bumpMemoryRevision()
1511
1520
  noteMemoryWrite('restore', null)
1512
1521
  }
1522
+
1523
+ /**
1524
+ * P2-5: explicit session-binding GC. Idle time is not an automatic deletion
1525
+ * trigger (docs/binding-lifecycle.md); this is a dry-run-first maintenance call.
1526
+ * A binding with no parseable lastTurnAt is never a candidate.
1527
+ */
1528
+ /**
1529
+ * Session-binding garbage collection.
1530
+ *
1531
+ * This deletes bindings, which is not recoverable. Three guards, because the old
1532
+ * version had none and a `--days 0` invocation wiped every binding in the store:
1533
+ *
1534
+ * · `olderThanDays` must be strictly positive. Zero/negative is a mistake, not a
1535
+ * "clean everything" request, so it throws instead of quietly becoming one.
1536
+ * · `isBusy(sessionId)` lets the caller veto a candidate: a session with a live
1537
+ * consolidation lease is in the middle of writing, and lastTurnAt is not the only
1538
+ * clock that matters.
1539
+ * · the apply pass re-reads each candidate inside `updateState`. A dry-run and an
1540
+ * apply are two separate loads, and a conversation that woke up in between must
1541
+ * not be deleted on the strength of the earlier snapshot.
1542
+ */
1543
+ export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now = Date.now(), isBusy = null } = {}) {
1544
+ const days = Number(olderThanDays)
1545
+ if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
1546
+ const cutoff = Number(now) - days * 86_400_000
1547
+ const state = loadState()
1548
+ const candidates = []
1549
+ const skipped = []
1550
+ for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
1551
+ const at = Date.parse(String(binding?.lastTurnAt || ''))
1552
+ if (!Number.isFinite(at) || at >= cutoff) continue
1553
+ if (typeof isBusy === 'function') {
1554
+ let busy = false
1555
+ try { busy = isBusy(sessionId) === true } catch (error) {
1556
+ // An unreadable lease file is not permission to delete: treat it as busy.
1557
+ busy = true
1558
+ warn(`prune-session-bindings: liveness check failed for ${sessionId} (${error?.message || error}); kept`)
1559
+ }
1560
+ if (busy) {
1561
+ skipped.push({ sessionId, reason: 'a consolidation lease is still live' })
1562
+ continue
1563
+ }
1564
+ }
1565
+ candidates.push({ sessionId, lastTurnAt: binding.lastTurnAt, libraryId: binding.libraryId || null })
1566
+ }
1567
+ const base = {
1568
+ dryRun: dryRun !== false,
1569
+ olderThanDays: days,
1570
+ cutoff: new Date(cutoff).toISOString(),
1571
+ candidates,
1572
+ skipped,
1573
+ }
1574
+ if (dryRun !== false || candidates.length === 0) return { ...base, removed: [] }
1575
+ const removed = []
1576
+ const revalidated = []
1577
+ updateState((next) => {
1578
+ for (const item of candidates) {
1579
+ const current = next.sessions?.[item.sessionId]
1580
+ if (!current) continue
1581
+ const at = Date.parse(String(current.lastTurnAt || ''))
1582
+ // Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
1583
+ // would still delete a binding that just came back with a stale lastTurnAt.
1584
+ if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
1585
+ delete next.sessions[item.sessionId]
1586
+ removed.push(item.sessionId)
1587
+ }
1588
+ return next
1589
+ })
1590
+ return { ...base, removed, revalidated }
1591
+ }