dsh-memu-memory 1.2.6 → 1.2.8

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 (68) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/contributing.md +1 -1
  5. package/docs/host-adaptation.md +1 -1
  6. package/docs/memory-semantics.md +26 -4
  7. package/docs/troubleshooting.md +3 -1
  8. package/lib/backup.js +1 -1
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/budget.js +31 -0
  11. package/lib/client.js +276 -28
  12. package/lib/commitment.js +138 -0
  13. package/lib/consolidation-receipt.js +2 -0
  14. package/lib/consolidation-worker.js +3 -0
  15. package/lib/curator-policy.js +98 -0
  16. package/lib/fork-model.js +312 -0
  17. package/lib/freshness.js +24 -0
  18. package/lib/inject.js +117 -10
  19. package/lib/lexicon.js +1 -1
  20. package/lib/local-vector-service.js +4 -1
  21. package/lib/memory.js +600 -43
  22. package/lib/memu.js +4 -0
  23. package/lib/private.js +49 -8
  24. package/lib/prompts/private-consolidation.mixed.md +3 -2
  25. package/lib/prompts/private-consolidation.rp.md +7 -1
  26. package/lib/prompts/private-policy.mixed.md +1 -0
  27. package/lib/prompts/private-policy.rp.md +5 -1
  28. package/lib/prompts/system-guide.rp.md +3 -0
  29. package/lib/recall-cache.js +212 -0
  30. package/lib/rpc.js +44 -6
  31. package/lib/snippet.js +25 -0
  32. package/lib/state.js +43 -1
  33. package/lib/temporal.js +329 -0
  34. package/lib/text-retrieval.js +292 -28
  35. package/lib/tokenizer-v2.js +295 -0
  36. package/lib/tools.js +81 -4
  37. package/lib/webui/standalone.css +17 -1
  38. package/package.json +1 -1
  39. package/scripts/bench-recall.mjs +142 -0
  40. package/scripts/check-seed-compat.mjs +118 -0
  41. package/tests/backup.test.mjs +2 -2
  42. package/tests/commitment.test.mjs +144 -0
  43. package/tests/consolidation-fork.test.mjs +122 -5
  44. package/tests/curator-clusters.test.mjs +7 -1
  45. package/tests/curator-pairing.test.mjs +52 -8
  46. package/tests/disclosure.test.mjs +34 -17
  47. package/tests/dynamic-rrf.test.mjs +179 -0
  48. package/tests/fact-version.test.mjs +128 -0
  49. package/tests/fork-model.test.mjs +345 -0
  50. package/tests/help-page.test.mjs +1 -1
  51. package/tests/inject-conflict.test.mjs +94 -0
  52. package/tests/inject-guide.test.mjs +5 -3
  53. package/tests/inject.test.mjs +2 -2
  54. package/tests/injection-intent-budget.test.mjs +92 -0
  55. package/tests/lexicon-frequency.test.mjs +1 -1
  56. package/tests/loader.mjs +3 -0
  57. package/tests/memory-chain.test.mjs +140 -0
  58. package/tests/memory-fields.test.mjs +134 -0
  59. package/tests/memu-resident.test.mjs +33 -0
  60. package/tests/negation-polarity.test.mjs +135 -0
  61. package/tests/prompt-semantics.test.mjs +51 -0
  62. package/tests/query-decompose.test.mjs +62 -0
  63. package/tests/recall-cache.test.mjs +292 -0
  64. package/tests/recall-intent.test.mjs +100 -0
  65. package/tests/speaker-provenance.test.mjs +120 -0
  66. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  67. package/tests/temporal.test.mjs +124 -0
  68. package/tests/tokenizer-v2.test.mjs +142 -0
package/lib/client.js CHANGED
@@ -274,11 +274,24 @@ window.__ModuleLoader__.load({
274
274
  warning: '更新到未经验证的最新版可能导致 CLI 变化或记忆功能损坏。只安装插件声明的推荐版本。',
275
275
  memorySettings: '记忆设置',
276
276
  settingsTuning: '注入与召回',
277
+ settingsHeaderNote: '改动即时保存(约 0.25 秒后写盘);「恢复默认」需两次点击确认。',
278
+ settingsGroupRecall: '召回与注入',
279
+ settingsGroupRecallDesc: '每轮注入什么、注入多少:注入模式、召回条数、token 预算与去重。',
280
+ settingsGroupLifecycle: '记忆生命周期',
281
+ settingsGroupLifecycleDesc: '永久上限、短期保留、未了之事复提与归档清理节奏。',
282
+ settingsGroupCuration: '整理与唤醒',
283
+ settingsGroupCurationDesc: '空闲整理与全局自动提炼的节奏,以及日期到点唤醒。',
284
+ settingsGroupEngine: '引擎与后端',
285
+ settingsGroupEngineDesc: 'MemU 存储模式与引擎自动安装。',
286
+ settingsGroupSession: '会话与界面',
287
+ settingsGroupSessionDesc: '新会话提示、侧边栏设置入口与图片描述。',
288
+ settingsGroupIntegration: '集成',
289
+ settingsGroupIntegrationDesc: '对外暴露的消息工具白名单与视觉描述服务。',
277
290
  autoInject: '注入模式',
278
291
  privateTopK: '私有 topK',
279
292
  globalTopK: '全局 topK',
280
293
  crossLibraryRecall: '跨库召回(仅同领域)',
281
- crossLibraryRecallHint: '开启后,自动召回、memu_private_recall、memu_private_list 与侧栏私有列表会合并其它“同领域”私有记忆库;词典的锚点摘要、本回合匹配与 memu_lexicon_search 走同一个作用域。显式浏览某个库时仍只显示该库。写入仍只写当前库(全局词典只有你能写)。跨文件夹读取会改变隔离边界,默认关闭。',
294
+ crossLibraryRecallHint: '开启后,这些读取会合并其它「同领域」私有库:自动召回、memu_private_recall、memu_private_list、侧栏私有列表,以及词典的锚点摘要、本回合匹配与 memu_lexicon_search。\n显式浏览某个库时,仍只显示该库。\n写入不受影响,仍只写当前库;全局词典只有你能写。\n跨库读取改变隔离边界,默认关闭。',
282
295
  mustRememberCap: '永久记忆软上限',
283
296
  shortTermTtlHours: '短期记忆保留(小时,0=关闭)',
284
297
  anchorTokens: '锚点 token',
@@ -297,12 +310,34 @@ window.__ModuleLoader__.load({
297
310
  salientWakeSchedule: '到点唤醒会话',
298
311
  salientWakeHour: '唤醒时间(HH:mm)',
299
312
  salientWakeTimeZone: '唤醒时区(留空跟随系统)',
300
- salientWakeHint: '实验特性,默认关闭。唤醒走宿主定时任务投递,会替会话开一整轮;只有宿主进程活着才会触发,任务在宿主的定时任务界面可见、可手动删除。还没做过真机验收,建议先在测试库里试开。',
313
+ salientWakeHint: '实验特性,默认关闭:唤醒会替会话开一整轮,由宿主定时任务投递。\n只有宿主进程活着才会触发;任务在宿主的定时任务界面可见、可手动删除。\n还没做过真机验收,建议先在测试库里试开。',
301
314
  autoInstall: '自动安装引擎',
302
315
  sleepConsolidation: '空闲后整理记忆',
303
316
  sleepAfterIdleMinutes: '空闲多久后整理(分钟)',
304
317
  autoCurateEveryHours: '全局自动提炼间隔(小时,0=关闭)',
305
318
  autoCurateSessionLimit: '每次最多纳入的对话数',
319
+ consolidationModelMode: '整理模型',
320
+ consolidationModeInherit: '继承当前会话',
321
+ consolidationModeHost: '指定宿主模型',
322
+ consolidationModeCustom: '自定义接入点',
323
+ consolidationHostProvider: '宿主 Provider',
324
+ consolidationHostModel: '宿主模型',
325
+ consolidationProviderPick: '选择 provider',
326
+ consolidationModelPick: '选择模型',
327
+ consolidationCatalogLoading: '正在读取宿主模型目录…',
328
+ consolidationCatalogDegraded: '拿不到宿主模型目录(或目录为空),直接按 provider/model 手填。',
329
+ consolidationHostHint: '这里列出的是宿主已配置的 provider/route,整理 fork 直接指名它,不新建连接。',
330
+ consolidationKeyKeep: '已配置,留空保持不变',
331
+ consolidationKeyEmpty: '选填;本地网关可以没有 key',
332
+ consolidationCustomModel: '模型 ID',
333
+ consolidationCustomApiLabel: '线协议',
334
+ consolidationDiscover: '拉取模型列表',
335
+ consolidationDiscoverDone: '拉到 {n} 个模型',
336
+ consolidationDiscoverFailed: '拉取失败',
337
+ consolidationCustomHint: '每次整理前自动注册这个接入点(无需重启),失败自动降级回继承并在日志里说明;API key 只存本地,不进日志。',
338
+ consolidationCustomUnavailable: '这台宿主缺少挂载自定义接入点的能力(llm.registerAdapter 或 PiAiAdapter 不在),改用「指定宿主模型」或「继承当前会话」。',
339
+ curatorModel: '全局整理模型',
340
+ curatorModelHint: '全局记忆提炼用的模型,格式 provider/model,留空跟随当前会话;与上面的私有整理模型是两条路。',
306
341
  memoryMode: 'MemU 存储模式',
307
342
  memoryModeHint: 'local 把记忆留在本机;cloud 交给 MemU 官方后端,需要 ~/.memu/config.env 里的厂商凭据。',
308
343
  memoryBackend: '记忆后端',
@@ -1043,11 +1078,24 @@ window.__ModuleLoader__.load({
1043
1078
  warning: 'Unverified latest releases can change the CLI or break memory. Only the recommended version declared by the plugin is installed.',
1044
1079
  memorySettings: 'Memory settings',
1045
1080
  settingsTuning: 'Injection & recall',
1081
+ settingsHeaderNote: 'Edits save themselves about 0.25s after each change; Reset defaults asks for a second click.',
1082
+ settingsGroupRecall: 'Recall & injection',
1083
+ settingsGroupRecallDesc: 'What each turn injects and how much: injection mode, topK, token budgets, dedupe.',
1084
+ settingsGroupLifecycle: 'Memory lifecycle',
1085
+ settingsGroupLifecycleDesc: 'Permanent cap, short-term retention, open-loop reminders and archive cleanup.',
1086
+ settingsGroupCuration: 'Curation & wake',
1087
+ settingsGroupCurationDesc: 'Idle consolidation and global auto-curation cadence, plus salient-date wake.',
1088
+ settingsGroupEngine: 'Engine & backend',
1089
+ settingsGroupEngineDesc: 'MemU storage mode and engine auto-install.',
1090
+ settingsGroupSession: 'Session & interface',
1091
+ settingsGroupSessionDesc: 'New-session prompt, sidebar settings entry and image captioning.',
1092
+ settingsGroupIntegration: 'Integration',
1093
+ settingsGroupIntegrationDesc: 'External message tool allowlist and the vision caption service.',
1046
1094
  autoInject: 'Injection mode',
1047
1095
  privateTopK: 'Private topK',
1048
1096
  globalTopK: 'Global topK',
1049
1097
  crossLibraryRecall: 'Cross-library recall (same domain)',
1050
- crossLibraryRecallHint: 'When on, automatic recall, memu_private_recall, memu_private_list and the sidebar private list merge other private libraries that use the same domain; the lexicon anchor, this-turn match and memu_lexicon_search follow the same scope. An explicit library browser still shows only that library. Writes still go to the bound library only (the global lexicon is yours alone to write). Reading across folders changes the isolation boundary, so this is off by default.',
1098
+ crossLibraryRecallHint: 'When on, these reads merge other same-domain private libraries: automatic recall, memu_private_recall, memu_private_list, the sidebar private list, plus the lexicon anchor summaries, this-turn matching and memu_lexicon_search.\nExplicitly browsing a library still shows that library only.\nWrites are unaffected and still go to the current library; the global lexicon stays yours alone to write.\nReading across libraries changes the isolation boundary, so this is off by default.',
1051
1099
  mustRememberCap: 'Permanent memory cap',
1052
1100
  shortTermTtlHours: 'Short-term TTL in hours (0=off)',
1053
1101
  anchorTokens: 'Anchor tokens',
@@ -1066,12 +1114,34 @@ window.__ModuleLoader__.load({
1066
1114
  salientWakeSchedule: 'Wake the conversation',
1067
1115
  salientWakeHour: 'Wake time (HH:mm)',
1068
1116
  salientWakeTimeZone: 'Wake time zone (empty = system)',
1069
- salientWakeHint: 'Experimental and off by default. Delivery goes through the host scheduler and opens a full turn for the conversation. It only fires while the host process is alive, and the tasks are visible (and deletable) in the host schedule UI. Not yet verified on a real install — try it on a test library first.',
1117
+ salientWakeHint: 'Experimental and off by default: a wake opens a full turn for the conversation, delivered by the host scheduler.\nIt only fires while the host process is alive; tasks stay visible (and deletable) in the host schedule UI.\nNot yet verified on a real install — try it on a test library first.',
1070
1118
  autoInstall: 'Auto-install engine',
1071
1119
  sleepConsolidation: 'Consolidate after idle',
1072
1120
  sleepAfterIdleMinutes: 'Idle minutes before consolidating',
1073
1121
  autoCurateEveryHours: 'Auto global curation every N hours (0=off)',
1074
1122
  autoCurateSessionLimit: 'Max conversations per auto run',
1123
+ consolidationModelMode: 'Consolidation model',
1124
+ consolidationModeInherit: 'Inherit the conversation',
1125
+ consolidationModeHost: 'Pick a host model',
1126
+ consolidationModeCustom: 'Custom endpoint',
1127
+ consolidationHostProvider: 'Host provider',
1128
+ consolidationHostModel: 'Host model',
1129
+ consolidationProviderPick: 'Pick a provider',
1130
+ consolidationModelPick: 'Pick a model',
1131
+ consolidationCatalogLoading: 'Loading the host model catalog…',
1132
+ consolidationCatalogDegraded: 'Host catalog unavailable (or empty) — type provider/model directly.',
1133
+ consolidationHostHint: 'These are the providers/routes the host already configured; the consolidation fork names one of them directly, no new connection.',
1134
+ consolidationKeyKeep: 'Configured; leave blank to keep',
1135
+ consolidationKeyEmpty: 'Optional; local gateways may run without a key',
1136
+ consolidationCustomModel: 'Model ID',
1137
+ consolidationCustomApiLabel: 'Wire protocol',
1138
+ consolidationDiscover: 'Fetch model list',
1139
+ consolidationDiscoverDone: 'Found {n} models',
1140
+ consolidationDiscoverFailed: 'Fetch failed',
1141
+ consolidationCustomHint: 'The endpoint is re-registered before every consolidation (no restart needed); on failure the fork falls back to inherit with a log line. The API key stays on this machine and never enters logs.',
1142
+ consolidationCustomUnavailable: 'This host cannot mount a custom endpoint (llm.registerAdapter or PiAiAdapter missing); use "Pick a host model" or "Inherit the conversation".',
1143
+ curatorModel: 'Global curator model',
1144
+ curatorModelHint: 'Model for global memory curation, format provider/model; empty follows the current conversation — a separate path from the private consolidation model above.',
1075
1145
  memoryMode: 'MemU storage mode',
1076
1146
  memoryModeHint: 'local keeps memory on this machine; cloud hands storage to the MemU backend and needs vendor credentials in ~/.memu/config.env.',
1077
1147
  memoryBackend: 'Memory backend',
@@ -3973,6 +4043,17 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3973
4043
  // Which snapshot the painted settings belong to (task E). Refetched only when
3974
4044
  // the marker moves, so a write made in another window lands within one beat.
3975
4045
  const markerRef = React.useRef(null)
4046
+ // 整理 fork 的宿主模型目录(listForkModelOptions):切到 host/custom 时懒加载一次并
4047
+ // 缓存。失败只置 error 状态,相关行降级为手填输入——用户不被卡死。
4048
+ const [forkCatalog, setForkCatalog] = React.useState(null)
4049
+ const [forkCatalogState, setForkCatalogState] = React.useState('idle')
4050
+ // custom 模式的 key 草稿:密码框只养草稿,留空或删光都不覆盖已存的 key
4051
+ //(后端 updateSettings 对空串的语义是「清空」,所以 UI 只在有输入时才写)。
4052
+ const [forkKeyDraft, setForkKeyDraft] = React.useState('')
4053
+ const [forkDiscoverBusy, setForkDiscoverBusy] = React.useState(false)
4054
+ const [forkDiscoverNote, setForkDiscoverNote] = React.useState('')
4055
+ const [forkDiscoverModels, setForkDiscoverModels] = React.useState(null)
4056
+ const forkCatalogLoadingRef = React.useRef(false)
3976
4057
 
3977
4058
  const adoptState = (value) => {
3978
4059
  setState({ ...value, settings: { ...value?.settings, ...pendingSettings.current } })
@@ -4028,6 +4109,22 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4028
4109
  window.addEventListener?.('pagehide', flush)
4029
4110
  return () => { window.removeEventListener?.('pagehide', flush); clearTimeout(settingsTimer.current); flush() }
4030
4111
  }, [flushSettings])
4112
+ // 宿主模型目录懒加载:切到 host/custom 时拉一次,缓存在组件状态里,之后不再重复
4113
+ // 拉。失败不抛——目录拿不到只是降级成手填,设置页不该为一个目录炸掉。
4114
+ const loadForkCatalog = React.useCallback(async () => {
4115
+ if (forkCatalogLoadingRef.current) return
4116
+ forkCatalogLoadingRef.current = true
4117
+ setForkCatalogState('loading')
4118
+ try {
4119
+ setForkCatalog(await call('listForkModelOptions', {}))
4120
+ setForkCatalogState('loaded')
4121
+ } catch {
4122
+ setForkCatalog(null)
4123
+ setForkCatalogState('error')
4124
+ } finally {
4125
+ forkCatalogLoadingRef.current = false
4126
+ }
4127
+ }, [call])
4031
4128
  React.useEffect(() => {
4032
4129
  if (!standalone) return undefined
4033
4130
  const sync = () => {
@@ -4222,6 +4319,13 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4222
4319
  void loadReviews()
4223
4320
  }
4224
4321
  }, [page, foldersLoaded, promptsLoaded, globalLoaded, loadFolders, loadPrompts, loadGlobal, loadSessions, loadReviews])
4322
+ // host 需要 provider/model 枚举,custom 需要 customAvailable/discoveryAvailable
4323
+ // 能力位——三态不在 inherit 时目录才值得拉(一次,之后吃缓存)。
4324
+ React.useEffect(() => {
4325
+ const mode = state?.settings?.consolidationModelMode || 'inherit'
4326
+ if (mode !== 'host' && mode !== 'custom') return
4327
+ if (forkCatalogState === 'idle') void loadForkCatalog()
4328
+ }, [state?.settings?.consolidationModelMode, forkCatalogState, loadForkCatalog])
4225
4329
  React.useEffect(() => {
4226
4330
  if (page !== PAGE.browser || !browseLibId) return undefined
4227
4331
  let alive = true
@@ -4279,9 +4383,6 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4279
4383
  return () => { alive = false; clearInterval(id) }
4280
4384
  }, [page, expandedKey, loadFolderSessions])
4281
4385
 
4282
- const saveSettings = async () => {
4283
- await flushSettings()
4284
- }
4285
4386
  // Defaults live on the server (state.js DEFAULT_SETTINGS): the page asks for
4286
4387
  // them rather than carrying a second copy that would drift from the code.
4287
4388
  const resetSettingsNow = async () => {
@@ -4416,6 +4517,33 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4416
4517
  clearTimeout(settingsTimer.current)
4417
4518
  settingsTimer.current = setTimeout(() => { void flushSettings() }, 250)
4418
4519
  }
4520
+ // 「拉取模型列表」:把草稿端点转给 discoverForkModels。apiKey 是一次性草稿凭据——
4521
+ // 密码框里有输入就带草稿,留空就声明复用已存 key(useStoredKey),两者都不回显、
4522
+ // 不进日志。结果只填下拉,失败给一行自清状态。
4523
+ const discoverConsolidationModels = async () => {
4524
+ setForkDiscoverBusy(true)
4525
+ setForkDiscoverNote('')
4526
+ try {
4527
+ const res = await call('discoverForkModels', {
4528
+ baseURL: state?.settings?.consolidationCustomBaseURL || '',
4529
+ api: state?.settings?.consolidationCustomApi || 'openai-completions',
4530
+ apiKey: forkKeyDraft,
4531
+ useStoredKey: !forkKeyDraft,
4532
+ })
4533
+ if (res?.ok === true) {
4534
+ const models = Array.isArray(res.models) ? res.models : []
4535
+ setForkDiscoverModels(models)
4536
+ setForkDiscoverNote(t('consolidationDiscoverDone').replace('{n}', String(models.length)))
4537
+ } else {
4538
+ setForkDiscoverNote(res?.reason ? `${t('consolidationDiscoverFailed')} · ${res.reason}` : t('consolidationDiscoverFailed'))
4539
+ }
4540
+ } catch (e) {
4541
+ setForkDiscoverNote(`${t('consolidationDiscoverFailed')} · ${String(e?.message || e)}`)
4542
+ } finally {
4543
+ setForkDiscoverBusy(false)
4544
+ }
4545
+ setTimeout(() => setForkDiscoverNote(''), 2600)
4546
+ }
4419
4547
  const setBackend = async (backend) => {
4420
4548
  setSetting('memoryBackend', backend)
4421
4549
  setConfigNotice('')
@@ -5301,13 +5429,120 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5301
5429
 
5302
5430
  )
5303
5431
 
5432
+ // 每组一个 Section(title + desc 走 i18n),组内沿用同一个 dshm-settings-grid。
5433
+ // 这里只是重排 + 分组:行与取值逻辑(含 ?? 回落、反向语义开关)一行不增不减。
5434
+ const settingsGroup = (title, desc, ...rows) => h(Section, { title, desc },
5435
+ h('div', { className: 'dshm-settings-grid' }, rows))
5436
+
5437
+ // —— 整理 fork 的模型选择(三模式)行 ——————————————————————————————
5438
+ // 行随 consolidationModelMode 条件渲染:inherit 只露模式选择;host 露宿主目录的
5439
+ // provider/model 两行(目录拿不到就降级成 provider/model 手填,同样写
5440
+ // consolidationModel,用户不被卡死);custom 露接入点四件套(这台宿主确认挂不了
5441
+ // custom 时整组降级为一行说明)。curatorModel 是全局提炼的模型,与这里的私有
5442
+ // 整理模型是两条路,恒常显示。
5443
+ const consolidationMode = settings.consolidationModelMode || 'inherit'
5444
+ const consolidationModelValue = String(settings.consolidationModel || '')
5445
+ const consolidationSlash = consolidationModelValue.indexOf('/')
5446
+ const consolidationProvider = consolidationSlash > 0 ? consolidationModelValue.slice(0, consolidationSlash) : ''
5447
+ const consolidationModelId = consolidationSlash > 0 ? consolidationModelValue.slice(consolidationSlash + 1) : ''
5448
+ const forkProviders = Array.isArray(forkCatalog?.providers) ? forkCatalog.providers : []
5449
+ const forkCatalogReady = forkCatalogState === 'loaded' && forkProviders.length > 0
5450
+ const forkProviderIds = forkCatalogReady ? forkProviders.map((p) => String(p?.id || '')).filter(Boolean) : []
5451
+ const forkModelEntries = forkCatalogReady ? (forkProviders.find((p) => p?.id === consolidationProvider)?.models || []) : []
5452
+ const forkOptionLabel = (item) => (item?.name && item.name !== item.id ? `${item.name} (${item.id})` : String(item?.id || ''))
5453
+ // 下拉要能显示当前值:已有 consolidationModel 但不在目录里(宿主 route 下线)时
5454
+ // 把当前值补成一个选项,显示与状态不脱节。
5455
+ const providerChoices = []
5456
+ if (!consolidationProvider) providerChoices.push({ id: '', label: t('consolidationProviderPick') })
5457
+ if (consolidationProvider && !forkProviderIds.includes(consolidationProvider)) providerChoices.push({ id: consolidationProvider, label: consolidationProvider })
5458
+ for (const id of forkProviderIds) providerChoices.push({ id, label: forkOptionLabel(forkProviders.find((p) => p?.id === id)) })
5459
+ const modelChoices = []
5460
+ if (!consolidationModelId) modelChoices.push({ id: '', label: t('consolidationModelPick') })
5461
+ if (consolidationModelId && !forkModelEntries.some((m) => m?.id === consolidationModelId)) modelChoices.push({ id: consolidationModelId, label: consolidationModelId })
5462
+ for (const m of forkModelEntries) modelChoices.push({ id: m.id, label: forkOptionLabel(m) })
5463
+ const consolidationModelRows = []
5464
+ if (consolidationMode === 'host') {
5465
+ if (forkCatalogReady) {
5466
+ consolidationModelRows.push(
5467
+ h(Field, { label: t('consolidationHostProvider') },
5468
+ h('select', { style: S.input, value: consolidationProvider, onChange: (e) => {
5469
+ const provider = e.target.value
5470
+ if (!provider) { setSetting('consolidationModel', null); return }
5471
+ // 换 provider 顺手选它的第一个模型,避免留下 "<provider>/" 这种
5472
+ // 解析不过的中间态;该 provider 没目录时才留半截让用户接着选。
5473
+ const first = forkProviders.find((p) => p?.id === provider)?.models?.[0]?.id || ''
5474
+ setSetting('consolidationModel', first ? `${provider}/${first}` : `${provider}/`)
5475
+ } },
5476
+ providerChoices.map((choice) => h('option', { key: choice.id, value: choice.id }, choice.label)))),
5477
+ h(Field, { label: t('consolidationHostModel') },
5478
+ h('select', { style: S.input, value: consolidationModelId, onChange: (e) => {
5479
+ if (!e.target.value || !consolidationProvider) return
5480
+ setSetting('consolidationModel', `${consolidationProvider}/${e.target.value}`)
5481
+ } },
5482
+ modelChoices.map((choice) => h('option', { key: choice.id, value: choice.id }, choice.label)))),
5483
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('consolidationHostHint')))
5484
+ } else {
5485
+ consolidationModelRows.push(
5486
+ h(Field, { label: t('consolidationHostModel') },
5487
+ h('input', { type: 'text', style: S.input, placeholder: 'provider/model', value: consolidationModelValue,
5488
+ onChange: (e) => setSetting('consolidationModel', e.target.value || null) })),
5489
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } },
5490
+ forkCatalogState === 'loading' ? t('consolidationCatalogLoading') : t('consolidationCatalogDegraded')))
5491
+ }
5492
+ }
5493
+ if (consolidationMode === 'custom') {
5494
+ if (forkCatalog && forkCatalog.customAvailable === false) {
5495
+ consolidationModelRows.push(h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('consolidationCustomUnavailable')))
5496
+ } else {
5497
+ const customModelId = String(settings.consolidationCustomModel || '')
5498
+ // key 永不回显明文:占位只给「已配置」+ 服务端打码尾 4 位;草稿有输入才写
5499
+ // setSetting(留空/删光 = 保留原值,因为后端对空串的语义是清空)。
5500
+ const keyConfigured = settings.hasConsolidationCustomApiKey === true || Boolean(String(settings.consolidationCustomApiKey || ''))
5501
+ const keyTail = String(settings.consolidationCustomApiKeyTail || '')
5502
+ const keyPlaceholder = keyConfigured
5503
+ ? t('consolidationKeyKeep') + (keyTail && keyTail !== '****' ? ` ····${keyTail}` : '')
5504
+ : t('consolidationKeyEmpty')
5505
+ const discovered = Array.isArray(forkDiscoverModels) ? forkDiscoverModels : []
5506
+ const customModelChoices = []
5507
+ if (!customModelId) customModelChoices.push({ id: '', label: t('consolidationModelPick') })
5508
+ if (customModelId && !discovered.some((m) => m?.id === customModelId)) customModelChoices.push({ id: customModelId, label: customModelId })
5509
+ for (const m of discovered) customModelChoices.push({ id: m.id, label: forkOptionLabel(m) })
5510
+ consolidationModelRows.push(
5511
+ h(Field, { label: t('baseUrl') },
5512
+ h('input', { type: 'text', style: S.input, placeholder: 'http://127.0.0.1:8899', value: settings.consolidationCustomBaseURL || '',
5513
+ onChange: (e) => setSetting('consolidationCustomBaseURL', e.target.value) })),
5514
+ h(Field, { label: t('apiKey') },
5515
+ h('input', { type: 'password', style: S.input, autoComplete: 'new-password', placeholder: keyPlaceholder, value: forkKeyDraft,
5516
+ onChange: (e) => { const next = e.target.value; setForkKeyDraft(next); if (next) setSetting('consolidationCustomApiKey', next) } })),
5517
+ h(Field, { label: t('consolidationCustomModel') },
5518
+ discovered.length
5519
+ ? h('select', { style: S.input, value: customModelId, onChange: (e) => { if (e.target.value) setSetting('consolidationCustomModel', e.target.value) } },
5520
+ customModelChoices.map((choice) => h('option', { key: choice.id, value: choice.id }, choice.label)))
5521
+ : h('input', { type: 'text', style: S.input, placeholder: 'GLM-5.3-Flash', value: customModelId,
5522
+ onChange: (e) => setSetting('consolidationCustomModel', e.target.value) })),
5523
+ h(Field, { label: t('consolidationCustomApiLabel') },
5524
+ h('select', { style: S.input, value: settings.consolidationCustomApi || 'openai-completions', onChange: (e) => setSetting('consolidationCustomApi', e.target.value) },
5525
+ ['openai-completions', 'openai-responses', 'anthropic-messages'].map((v) => h('option', { key: v, value: v }, v)))),
5526
+ forkCatalog?.discoveryAvailable === true
5527
+ ? h('div', { style: S.row },
5528
+ h(Button, { onClick: discoverConsolidationModels, disabled: forkDiscoverBusy, title: t('consolidationDiscover') },
5529
+ forkDiscoverBusy ? t('loading') : t('consolidationDiscover')),
5530
+ forkDiscoverNote ? h('span', { style: S.muted, role: 'status' }, forkDiscoverNote) : null)
5531
+ : null,
5532
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('consolidationCustomHint')))
5533
+ }
5534
+ }
5535
+
5536
+ // 页首精简头部:标题 + 一句话说明 + 恢复默认。保存机制保持原样:设置项即时保存
5537
+ //(250ms trailing debounce + pagehide flush),页首不放「保存」按钮——改动落盘
5538
+ // 由 debounce 兜底;「恢复默认」仍是两段确认后调 resetSettings RPC。
5304
5539
  const settingsBlock = h(React.Fragment, null, h(Section, {
5305
5540
  title: t('settingsTuning'),
5306
5541
  right: h('div', { style: { display: 'flex', gap: 6, flexShrink: 0 } },
5307
- h(Button, { onClick: resetSettingsNow, disabled: busy, style: S.ghost }, resetArmed ? t('settingsResetConfirm') : t('settingsReset')),
5308
- h(Button, { onClick: saveSettings, disabled: busy, primary: true }, t('save'))),
5542
+ h(Button, { onClick: resetSettingsNow, disabled: busy, style: S.ghost, title: resetArmed ? t('settingsResetConfirm') : t('settingsReset') }, resetArmed ? t('settingsResetConfirm') : t('settingsReset'))),
5309
5543
  },
5310
- h('div', { className: 'dshm-settings-grid' },
5544
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, lineHeight: 1.55 } }, t('settingsHeaderNote'))),
5545
+ settingsGroup(t('settingsGroupRecall'), t('settingsGroupRecallDesc'),
5311
5546
  h(Field, { label: t('autoInject') },
5312
5547
  h('select', { style: S.input, value: settings.autoInject || 'smart', onChange: (e) => setSetting('autoInject', e.target.value) },
5313
5548
  ['smart', 'anchor-only', 'per-turn', 'off'].map((v) => h('option', { key: v, value: v }, enumText(t, INJECT_LABELS, v))))),
@@ -5319,8 +5554,6 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5319
5554
  h(Field, { label: t('globalTopK') }, h('input', { type: 'number', style: S.input, value: settings.globalTopK ?? 5, onChange: (e) => setSetting('globalTopK', Number(e.target.value)) })),
5320
5555
  h(Field, { label: t('crossLibraryRecall') }, h(Toggle, { checked: settings.crossLibraryRecall === true, label: t('crossLibraryRecall'), onChange: value => setSetting('crossLibraryRecall', value) })),
5321
5556
  h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('crossLibraryRecallHint')),
5322
- h(Field, { label: t('mustRememberCap') }, h('input', { type: 'number', style: S.input, value: settings.mustRememberCap ?? 12, onChange: (e) => setSetting('mustRememberCap', Number(e.target.value)) })),
5323
- h(Field, { label: t('shortTermTtlHours') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.shortTermTtlHours ?? 72, onChange: (e) => setSetting('shortTermTtlHours', Number(e.target.value)) })),
5324
5557
  h(Field, { label: t('anchorTokens') }, h('input', { type: 'number', style: S.input, value: settings.anchorTokens ?? 800, onChange: (e) => setSetting('anchorTokens', Number(e.target.value)) })),
5325
5558
  h(Field, { label: t('turnTokens') }, h('input', { type: 'number', style: S.input, value: settings.turnTokens ?? 800, onChange: (e) => setSetting('turnTokens', Number(e.target.value)) })),
5326
5559
  h(Field, { label: t('injectionTotalTokens') }, h('input', { type: 'number', style: S.input, value: settings.injectionTotalTokens ?? 2000, onChange: (e) => setSetting('injectionTotalTokens', Number(e.target.value)) })),
@@ -5329,35 +5562,50 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5329
5562
  h(Field, { label: t('minUserChars') }, h('input', { type: 'number', style: S.input, value: settings.minUserChars ?? 6, onChange: (e) => setSetting('minUserChars', Number(e.target.value)) })),
5330
5563
  h(Field, { label: t('relevanceThreshold') }, h('input', { type: 'number', step: '0.05', min: 0, max: 1, style: S.input, value: settings.relevanceThreshold ?? 0.4, onChange: (e) => setSetting('relevanceThreshold', Number(e.target.value)) })),
5331
5564
  h(Field, { label: t('randomCueChance') }, h('input', { type: 'number', step: '0.01', min: 0, max: 1, style: S.input, value: settings.randomCueChance ?? 0.02, onChange: (e) => setSetting('randomCueChance', Number(e.target.value)) })),
5332
- h(Field, { label: t('openLoopRemindDays') }, h('input', { type: 'number', min: 1, max: 365, style: S.input, value: settings.openLoopRemindDays ?? 7, onChange: (e) => setSetting('openLoopRemindDays', Number(e.target.value)) })),
5333
5565
  h(Field, { label: t('freshnessHint') }, h(Toggle, { checked: settings.freshnessHint !== false, label: t('freshnessHint'), onChange: value => setSetting('freshnessHint', value) })),
5334
5566
  h(Field, { label: t('freshnessDays') }, h('input', { type: 'number', min: 1, max: 3650, style: S.input, value: settings.freshnessDays ?? 30, onChange: (e) => setSetting('freshnessDays', Number(e.target.value)) })),
5335
5567
  h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('freshnessHintHint')),
5568
+ h(Field, { label: t('habitsInjection') }, h('input', { type: 'checkbox', checked: settings.habitsInjection !== false, onChange: (e) => setSetting('habitsInjection', e.target.checked) }))),
5569
+ settingsGroup(t('settingsGroupLifecycle'), t('settingsGroupLifecycleDesc'),
5570
+ h(Field, { label: t('mustRememberCap') }, h('input', { type: 'number', style: S.input, value: settings.mustRememberCap ?? 12, onChange: (e) => setSetting('mustRememberCap', Number(e.target.value)) })),
5571
+ h(Field, { label: t('shortTermTtlHours') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.shortTermTtlHours ?? 72, onChange: (e) => setSetting('shortTermTtlHours', Number(e.target.value)) })),
5572
+ h(Field, { label: t('openLoopRemindDays') }, h('input', { type: 'number', min: 1, max: 365, style: S.input, value: settings.openLoopRemindDays ?? 7, onChange: (e) => setSetting('openLoopRemindDays', Number(e.target.value)) })),
5573
+ h(Field, { label: t('purgeArchivedAfterDays') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.purgeArchivedAfterDays ?? 0, onChange: (e) => setSetting('purgeArchivedAfterDays', Number(e.target.value)) }))),
5574
+ settingsGroup(t('settingsGroupCuration'), t('settingsGroupCurationDesc'),
5575
+ h(Field, { label: t('sleepConsolidation') }, h('input', { type: 'checkbox', checked: settings.sleepConsolidation === true, onChange: (e) => setSetting('sleepConsolidation', e.target.checked) })),
5576
+ h(Field, { label: t('sleepAfterIdleMinutes') }, h('input', { type: 'number', min: 1, style: S.input, value: settings.sleepAfterIdleMinutes ?? 2, onChange: (e) => setSetting('sleepAfterIdleMinutes', Number(e.target.value)) })),
5577
+ h(Field, { label: t('autoCurateEveryHours') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.autoCurateEveryHours ?? 0, onChange: (e) => setSetting('autoCurateEveryHours', Number(e.target.value)) })),
5578
+ h(Field, { label: t('autoCurateSessionLimit') }, h('input', { type: 'number', min: 1, max: 30, style: S.input, value: settings.autoCurateSessionLimit ?? 8, onChange: (e) => setSetting('autoCurateSessionLimit', Number(e.target.value)) })),
5579
+ h(Field, { label: t('consolidationModelMode') },
5580
+ h('select', { style: S.input, value: consolidationMode, onChange: (e) => setSetting('consolidationModelMode', e.target.value) },
5581
+ h('option', { value: 'inherit' }, t('consolidationModeInherit')),
5582
+ h('option', { value: 'host' }, t('consolidationModeHost')),
5583
+ h('option', { value: 'custom' }, t('consolidationModeCustom')))),
5584
+ ...consolidationModelRows,
5585
+ h(Field, { label: t('curatorModel') }, h('input', { type: 'text', style: S.input, placeholder: 'provider/model', value: settings.curatorModel || '', onChange: (e) => setSetting('curatorModel', e.target.value || null) })),
5586
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('curatorModelHint')),
5336
5587
  h(Field, { label: t('salientWake') },
5337
5588
  h('select', { style: S.input, value: settings.salientWake || 'off', onChange: (e) => setSetting('salientWake', e.target.value) },
5338
5589
  h('option', { value: 'off' }, t('salientWakeOff')),
5339
5590
  h('option', { value: 'schedule' }, t('salientWakeSchedule')))),
5340
5591
  h(Field, { label: t('salientWakeHour') }, h('input', { type: 'time', style: S.input, value: settings.salientWakeHour || '09:00', onChange: (e) => setSetting('salientWakeHour', e.target.value) })),
5341
5592
  h(Field, { label: t('salientWakeTimeZone') }, h('input', { type: 'text', style: S.input, placeholder: 'Asia/Shanghai', value: settings.salientWakeTimeZone || '', onChange: (e) => setSetting('salientWakeTimeZone', e.target.value) })),
5342
- h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('salientWakeHint')),
5343
- h(Field, { label: t('autoInstall') }, h('input', { type: 'checkbox', checked: settings.autoInstallEngine !== false, onChange: (e) => setSetting('autoInstallEngine', e.target.checked) })),
5593
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('salientWakeHint'))),
5594
+ settingsGroup(t('settingsGroupEngine'), t('settingsGroupEngineDesc'),
5595
+ h(Field, { label: t('memoryMode') },
5596
+ h('select', { style: S.input, value: settings.memoryMode || 'local', onChange: (e) => setSetting('memoryMode', e.target.value) },
5597
+ ['local', 'cloud'].map((v) => h('option', { key: v, value: v }, v)))),
5598
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('memoryModeHint')),
5599
+ h(Field, { label: t('autoInstall') }, h('input', { type: 'checkbox', checked: settings.autoInstallEngine !== false, onChange: (e) => setSetting('autoInstallEngine', e.target.checked) }))),
5600
+ settingsGroup(t('settingsGroupSession'), t('settingsGroupSessionDesc'),
5344
5601
  h(Field, { label: t('newSessionPrompt') }, h('input', { type: 'checkbox', checked: settings.newSessionPromptDismissed !== true, onChange: (e) => setSetting('newSessionPromptDismissed', !e.target.checked) })),
5345
- h(Field, { label: t('habitsInjection') }, h('input', { type: 'checkbox', checked: settings.habitsInjection !== false, onChange: (e) => setSetting('habitsInjection', e.target.checked) })),
5346
5602
  h(Field, { label: t('sidebarSettings') }, h(Toggle, { checked: settings.sidebarSettings === true, label: t('sidebarSettings'), onChange: value => setSetting('sidebarSettings', value) })),
5347
- h(Field, { label: t('visionCaptionEnabled') }, h(Toggle, { checked: settings.visionCaptionEnabled === true, label: t('visionCaptionEnabled'), onChange: value => setSetting('visionCaptionEnabled', value) })),
5603
+ h(Field, { label: t('visionCaptionEnabled') }, h(Toggle, { checked: settings.visionCaptionEnabled === true, label: t('visionCaptionEnabled'), onChange: value => setSetting('visionCaptionEnabled', value) }))),
5604
+ settingsGroup(t('settingsGroupIntegration'), t('settingsGroupIntegrationDesc'),
5348
5605
  h(Field, { label: t('inboundToolNames') }, h(InboundToolsInput, {
5349
5606
  names: settings.inboundToolNames || [], onChange: values => setSetting('inboundToolNames', values),
5350
- })),
5351
- h(Field, { label: t('sleepConsolidation') }, h('input', { type: 'checkbox', checked: settings.sleepConsolidation === true, onChange: (e) => setSetting('sleepConsolidation', e.target.checked) })),
5352
- h(Field, { label: t('sleepAfterIdleMinutes') }, h('input', { type: 'number', min: 1, style: S.input, value: settings.sleepAfterIdleMinutes ?? 2, onChange: (e) => setSetting('sleepAfterIdleMinutes', Number(e.target.value)) })),
5353
- h(Field, { label: t('autoCurateEveryHours') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.autoCurateEveryHours ?? 0, onChange: (e) => setSetting('autoCurateEveryHours', Number(e.target.value)) })),
5354
- h(Field, { label: t('autoCurateSessionLimit') }, h('input', { type: 'number', min: 1, max: 30, style: S.input, value: settings.autoCurateSessionLimit ?? 8, onChange: (e) => setSetting('autoCurateSessionLimit', Number(e.target.value)) })),
5355
- h(Field, { label: t('purgeArchivedAfterDays') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.purgeArchivedAfterDays ?? 0, onChange: (e) => setSetting('purgeArchivedAfterDays', Number(e.target.value)) })),
5356
- h(Field, { label: t('memoryMode') },
5357
- h('select', { style: S.input, value: settings.memoryMode || 'local', onChange: (e) => setSetting('memoryMode', e.target.value) },
5358
- ['local', 'cloud'].map((v) => h('option', { key: v, value: v }, v)))),
5359
- h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('memoryModeHint')))),
5360
- h(Section, { title: t('visionService') }, h(VisionConfigPanel, { call, config: state.visionConfig, t })))
5607
+ }))),
5608
+ h(Section, { title: t('visionService') }, h(VisionConfigPanel, { call, config: state.visionConfig, t })))
5361
5609
 
5362
5610
  const renderLibraryItem = (lib) => h('div', { key: lib.id, style: S.item },
5363
5611
  h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' } },
@@ -0,0 +1,138 @@
1
+ // 承诺 / 欠账。
2
+ //
3
+ // `commitment.status` 是权威,`open_loop` 只保留做旧数据兼容:
4
+ // open → 还没兑现;done → 已兑现;cancelled → 明确取消;expired → 过期未完成。
5
+ // due_at 接受 YYYY-MM-DD 或 ISO 时间;比较按“到期那一天”算,不按时分秒。
6
+
7
+ export const COMMITMENT_STATUSES = ['open', 'done', 'cancelled', 'expired']
8
+
9
+ const DAY_MS = 86_400_000
10
+ const DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/
11
+
12
+ function cleanText(value, max) {
13
+ if (value === undefined || value === null) return ''
14
+ return String(value).replace(/\s+/g, ' ').trim().slice(0, max)
15
+ }
16
+
17
+ function validDateOnly(text) {
18
+ const match = DATE_ONLY_RE.exec(text)
19
+ if (!match) return false
20
+ const year = Number(match[1])
21
+ const month = Number(match[2])
22
+ const day = Number(match[3])
23
+ if (month < 1 || month > 12 || day < 1) return false
24
+ return day <= new Date(Date.UTC(year, month, 0)).getUTCDate()
25
+ }
26
+
27
+ /** YYYY-MM-DD or an ISO timestamp; anything else is refused. */
28
+ export function normalizeDueAt(value) {
29
+ if (value === undefined || value === null) return null
30
+ const text = String(value).trim()
31
+ if (!text) return null
32
+ if (DATE_ONLY_RE.test(text)) {
33
+ if (!validDateOnly(text)) throw new Error('commitment.due_at must be YYYY-MM-DD or an ISO date/time')
34
+ return text
35
+ }
36
+ const at = Date.parse(text)
37
+ if (!Number.isFinite(at)) throw new Error('commitment.due_at must be YYYY-MM-DD or an ISO date/time')
38
+ return new Date(at).toISOString()
39
+ }
40
+
41
+ function dueDateText(value) {
42
+ if (!value) return null
43
+ if (DATE_ONLY_RE.test(value)) return value
44
+ const at = new Date(value)
45
+ return Number.isFinite(at.getTime()) ? `${at.getUTCFullYear()}-${String(at.getUTCMonth() + 1).padStart(2, '0')}-${String(at.getUTCDate()).padStart(2, '0')}` : null
46
+ }
47
+
48
+ function localDateKey(now) {
49
+ const at = now instanceof Date ? now : new Date(now)
50
+ const safe = Number.isFinite(at.getTime()) ? at : new Date()
51
+ return `${safe.getFullYear()}-${String(safe.getMonth() + 1).padStart(2, '0')}-${String(safe.getDate()).padStart(2, '0')}`
52
+ }
53
+
54
+ function daysBetween(fromKey, toKey) {
55
+ if (!fromKey || !toKey) return null
56
+ const from = Date.UTC(...fromKey.split('-').map((part, index) => index === 1 ? Number(part) - 1 : Number(part)))
57
+ const to = Date.UTC(...toKey.split('-').map((part, index) => index === 1 ? Number(part) - 1 : Number(part)))
58
+ return Math.round((to - from) / DAY_MS)
59
+ }
60
+
61
+ /**
62
+ * 归一一条承诺。显式传对象时字段错误会抛(写盘前拒绝,不静默改),
63
+ * 读取旧数据用 commitmentOf 的宽容口径。
64
+ */
65
+ export function normalizeCommitment(value, { fallbackAction = '', fallbackDueAt = null } = {}) {
66
+ if (value === undefined || value === null) return null
67
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error('commitment must be an object')
68
+ const status = value.status === undefined || value.status === null || value.status === ''
69
+ ? 'open' : String(value.status)
70
+ if (!COMMITMENT_STATUSES.includes(status)) {
71
+ throw new Error(`commitment.status must be ${COMMITMENT_STATUSES.join(', ')}`)
72
+ }
73
+ const action = cleanText(value.action ?? fallbackAction, 500)
74
+ if (!action) throw new Error('commitment.action is required')
75
+ const counterparty = cleanText(value.counterparty, 128) || null
76
+ const due = value.due_at ?? value.dueAt ?? fallbackDueAt
77
+ const dueAt = normalizeDueAt(due)
78
+ const closedByRaw = value.closed_by ?? value.closedBy ?? null
79
+ const evidenceRaw = value.evidence_seq ?? value.evidenceSeq ?? null
80
+ return {
81
+ counterparty,
82
+ action,
83
+ due_at: dueAt,
84
+ status,
85
+ closed_by: closedByRaw === null || closedByRaw === undefined || closedByRaw === ''
86
+ ? null : String(closedByRaw).slice(0, 128),
87
+ evidence_seq: evidenceRaw === null || evidenceRaw === undefined || evidenceRaw === ''
88
+ ? null : (Number.isSafeInteger(Number(evidenceRaw)) ? Number(evidenceRaw) : String(evidenceRaw).slice(0, 128)),
89
+ }
90
+ }
91
+
92
+ /** Tolerant read for stored entries; a malformed object never crashes recall. */
93
+ export function commitmentOf(entry) {
94
+ if (!entry || typeof entry !== 'object' || !entry.commitment || typeof entry.commitment !== 'object') return null
95
+ try {
96
+ return normalizeCommitment(entry.commitment)
97
+ } catch {
98
+ return null
99
+ }
100
+ }
101
+
102
+ /** open_loop 兼容口径:有 commitment 就看 status,没有才看旧布尔值。 */
103
+ export function isOpenThread(entry) {
104
+ const commitment = commitmentOf(entry)
105
+ if (commitment) return commitment.status === 'open'
106
+ return entry?.openLoop === true
107
+ }
108
+
109
+ /** 承诺的到期日(YYYY-MM-DD);没有 due_at 返回 null。 */
110
+ export function commitmentDueDate(entry) {
111
+ const commitment = commitmentOf(entry)
112
+ if (!commitment) return null
113
+ return dueDateText(commitment.due_at)
114
+ }
115
+
116
+ /**
117
+ * 到期状态。`dueSoon` 只覆盖今天和明天:一张每回合都出现的承诺卡会变成噪声,
118
+ * 真正的“到期/逾期”才值得占预算。
119
+ */
120
+ export function commitmentDueState(entryOrCommitment, { now = Date.now() } = {}) {
121
+ const commitment = entryOrCommitment?.status && entryOrCommitment?.action
122
+ ? entryOrCommitment
123
+ : commitmentOf(entryOrCommitment)
124
+ if (!commitment || commitment.status !== 'open' || !commitment.due_at) {
125
+ return { open: commitment?.status === 'open', dueAt: null, daysUntil: null, overdue: false, dueSoon: false }
126
+ }
127
+ const dueAt = dueDateText(commitment.due_at)
128
+ const daysUntil = daysBetween(localDateKey(now), dueAt)
129
+ return {
130
+ open: true,
131
+ dueAt,
132
+ daysUntil,
133
+ overdue: daysUntil !== null && daysUntil < 0,
134
+ dueSoon: daysUntil !== null && daysUntil <= 1,
135
+ }
136
+ }
137
+
138
+ export { DAY_MS }
@@ -197,6 +197,8 @@ export function reconcileReceipt({ receipt, index = null, beforeIds = null, befo
197
197
  for (const id of receipt?.heldIds || []) {
198
198
  const entry = entries[id]
199
199
  if (!entry) { missing.push(id); continue }
200
+ // S7.3:heldIds 只表示“仅 pending_review”。已经以 active 落库的矛盾条目属于
201
+ // 正常写入证据,应写在 createdIds/updatedIds,不能混进 held。
200
202
  if (entry.status !== 'pending_review') { problems.push('held id ' + id + ' is not pending_review'); continue }
201
203
  heldIds.push(id)
202
204
  }
@@ -153,6 +153,9 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
153
153
  '转录开头的 [memory-catalog · 已有记忆目录] 是本库已有条目,只用来去重/合并,不是对话内容,也不是用户发言。',
154
154
  '本轮可用的工具:' + tools + '。',
155
155
  '要做的:先按主题检索相关旧条目去重;同一事实的补充用 memu_private_update 合并(先拿到 id);真正新增、或与已有说法矛盾的内容用 memu_private_remember 一条一件;矛盾不要自己裁决,让它进待复核。',
156
+ '写库前必须落 speaker_id、source_kind、absolute_date:今天/明天/下周X/月底这类相对日期要按本轮时间算成绝对日期,不能只留原文;解析不了就标 date_precision=unknown,不要猜。',
157
+ '同一事实有两种说法时各写一条,用 conflicts_with 互指,不合并、不自行裁决;只有明确取代才用 supersedes,旧正文保留。助手说过的承诺、计划、事实同样要写,source_kind=assistant_said,不能记成用户说的。',
158
+ '承诺/约定写 commitment(对谁/做什么/due_at/status);到期未完成的承诺要留在库里,让后续注入能看到。每窗最多新增 10 条,值得留的日常事实即使琐碎也要写。',
156
159
  '写完(remember/update 拿到 id)后调用 memu_private_link_suggest({ids:[...]}),把本轮创建/更新的 id 都传进去:高置信的记忆↔记忆关联与实体枢纽算法已经自动连好,只有不确定的候选交给你裁决。不回读整段会话,也不为这个另起一次整理。',
157
160
  '候选只用 memu_private_link 裁决:note 要引用转录原话,同一实体或同一事件确有证据才 link;证据不足或拿不准就 noop;互相矛盾就 conflict,不 link。每轮最多确认 5 条,不要为每一对都连;不要为了这件事把整个记忆库读一遍。',
158
161
  '词典抽取:遇到稳定、可复用、有证据的黑话/梗/术语,先用 memu_lexicon_search 查重,再用 memu_lexicon_propose 一条一词写入。term 是索引键(短、稳定、用户的真实写法),meaning 才是解释;不写 sensitive trigger,也不写只属于这一次剧情的一次性词。',