dsh-memu-memory 1.2.7 → 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 (49) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/memory-semantics.md +23 -3
  5. package/lib/backup.js +1 -1
  6. package/lib/budget.js +31 -0
  7. package/lib/commitment.js +138 -0
  8. package/lib/consolidation-receipt.js +2 -0
  9. package/lib/consolidation-worker.js +3 -0
  10. package/lib/freshness.js +24 -0
  11. package/lib/inject.js +117 -10
  12. package/lib/lexicon.js +1 -1
  13. package/lib/local-vector-service.js +4 -1
  14. package/lib/memory.js +565 -32
  15. package/lib/memu.js +4 -0
  16. package/lib/private.js +5 -3
  17. package/lib/prompts/private-consolidation.mixed.md +2 -2
  18. package/lib/prompts/private-consolidation.rp.md +6 -1
  19. package/lib/prompts/private-policy.rp.md +4 -0
  20. package/lib/prompts/system-guide.rp.md +3 -0
  21. package/lib/recall-cache.js +10 -2
  22. package/lib/rpc.js +9 -2
  23. package/lib/snippet.js +25 -0
  24. package/lib/temporal.js +329 -0
  25. package/lib/text-retrieval.js +71 -0
  26. package/lib/tools.js +81 -4
  27. package/package.json +1 -1
  28. package/scripts/bench-recall.mjs +2 -2
  29. package/scripts/check-seed-compat.mjs +1 -1
  30. package/tests/backup.test.mjs +2 -2
  31. package/tests/commitment.test.mjs +144 -0
  32. package/tests/consolidation-fork.test.mjs +3 -3
  33. package/tests/disclosure.test.mjs +34 -17
  34. package/tests/fact-version.test.mjs +128 -0
  35. package/tests/help-page.test.mjs +1 -1
  36. package/tests/inject-conflict.test.mjs +94 -0
  37. package/tests/inject-guide.test.mjs +5 -3
  38. package/tests/inject.test.mjs +2 -2
  39. package/tests/injection-intent-budget.test.mjs +92 -0
  40. package/tests/lexicon-frequency.test.mjs +1 -1
  41. package/tests/memory-chain.test.mjs +140 -0
  42. package/tests/memory-fields.test.mjs +134 -0
  43. package/tests/memu-resident.test.mjs +33 -0
  44. package/tests/prompt-semantics.test.mjs +51 -0
  45. package/tests/query-decompose.test.mjs +62 -0
  46. package/tests/recall-cache.test.mjs +4 -2
  47. package/tests/recall-intent.test.mjs +100 -0
  48. package/tests/speaker-provenance.test.mjs +120 -0
  49. package/tests/temporal.test.mjs +124 -0
package/lib/memu.js CHANGED
@@ -178,6 +178,10 @@ for _line in sys.stdin:
178
178
  const RESIDENT_READY_TIMEOUT_MS = 30_000
179
179
  const RESIDENT_LINE_LIMIT = 8 << 20
180
180
 
181
+ // 常驻引擎的进程级单例。之前漏了这个声明:所有更新点都在写它,第一次真正 spawn
182
+ // 时直接 ReferenceError(MEMU_SPAWN_FAILED: residentRecord is not defined)。
183
+ let residentRecord = null
184
+
181
185
  function residentKey(current) {
182
186
  return `${current.python}\u0000${String(current.version || '')}`
183
187
  }
package/lib/private.js CHANGED
@@ -584,12 +584,14 @@ function snapshotMetaOf(snapshot) {
584
584
  // 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
585
585
  // 开始写。实测(2026-11-02,935 条事件的会话):第一次 180 s 到点时刚写完 3 条、
586
586
  // 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算,
587
- // 并夹在 [180 s, 600 s]:小会话维持原来的 3 分钟,大会话不再必然撞墙,卡死的 fork
588
- // 也仍会在 10 分钟内被收掉。显式传 maxWaitMs 的调用(含工具/测试)原样生效。
587
+ // 并夹在 [420 s, 600 s]:慢推理模型(GLM-5.3-Flash 实测)单次 worker 回合就能吃满
588
+ // 180 s 旧下限且一个工具都没调(1.2.7 后内部评测复现),下限抬到 7 分钟给长思考留
589
+ // 余量;600 s 封顶不变,卡死的 fork 仍会在 10 分钟内被收掉。显式传 maxWaitMs 的
590
+ // 调用(含工具/测试)原样生效。
589
591
  export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
590
592
  baseMs: 120_000,
591
593
  perEventMs: 350,
592
- minMs: 180_000,
594
+ minMs: 420_000,
593
595
  maxMs: 600_000,
594
596
  })
595
597
 
@@ -13,9 +13,9 @@
13
13
  - 对方现实生活的具体事实(作息、行程、口味、健康、家人朋友、在忙的事)单独成条:`owner=about_user`,平实短条,不装进瞬间或技术模板,也不与剧情、技术条目合并;单次提及压低 confidence 或用 `short_term`,重复出现才升级,一次客套不推导长期偏好。
14
14
  - 两边都出现时分成两条,不要混成一条。
15
15
  - 技术侧用中性工程笔记,人物侧用角色自己的话,不打关系分、不写抒情流水账;OOC 写作偏好和剧情经历分开。
16
- - 仅按实际提供或成功检索到的旧条目去重;兼容内容可合并,矛盾留证据与时间供复核,不抹旧事实或自行宣布取代。没有旧索引时不假称已核对。
16
+ - 仅按实际提供或成功检索到的旧条目去重;兼容内容可合并,矛盾留证据与时间供复核,不抹旧事实或自行宣布取代。同一件事前后有两种说法时,两种说法必须各自成条(写清轮次或时间和说话人),不得合并;用户先前说过的话不能记成助手说的,也不能因后面改口删掉先前那条。
17
17
  - tags 可标 coding/rp/ooc 辅助检索,不代替说话人、角色、世界线、分支与 knownBy 边界。工具 waiting/sleep 不算人物经历,角色喜好不推导现实用户属性。
18
- - 最多新增 3 条,优先会影响之后决定或相处的事项,没有值得留下的就不写。
18
+ - 最多新增 10 条。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)即使琐碎也要独立写入;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。
19
19
 
20
20
  字段:
21
21
  - title:8–40 字,写具体事实(项目/模块/人物/事件/结论的关键词)。锚点/召回只显示标题、不显示正文,所以标题就是目录项;
@@ -11,7 +11,12 @@
11
11
  - 这轮真实发生了什么?谁答应了什么?谁知道了什么?哪些只是气氛?
12
12
  - 事实、约定、知情这三层要准;感受层允许模糊。
13
13
  - 只和实际提供或成功检索到的旧条目比对;同一事件的兼容细节可合并,矛盾说法保留各自来源、时间和视角供复核,不覆写旧事实,不自行宣布取代。
14
- - 每轮最多新增 3 条。
14
+ - 同一件事前后有两种说法时,两种说法必须各自成条(写清轮次或时间和说话人),不得合并成一条;用户先前说过的话不能记成助手说的,也不能因为后面改口就删掉先前那条。
15
+ - 写库前先落 `speaker_id`、`source_kind`、`absolute_date`;相对日期不能只留原文。
16
+ - 同一件事有两种说法:各写一条,`conflicts_with` 互指;不要合并成一条,也不要自行裁决。
17
+ - 承诺/约定写 `commitment`(对谁/做什么/`due_at`/`status`);梦、假设、转述标 `source_kind`。
18
+ - 助手说过的承诺和计划同样要写;不要只收用户消息。
19
+ - 每轮最多新增 10 条。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)即使琐碎也要独立写入;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。
15
20
 
16
21
  写什么(活人感):
17
22
  - 用角色的口吻、第一人称写,像在回想,不像在归档。
@@ -25,6 +25,10 @@
25
25
  三条纪律:
26
26
  - 写之前先 `memu_private_recall` 查一眼。对方提到以前的事、问你记不记得、要许下什么承诺之前都先查;凭印象编比记不清糟得多。
27
27
  - 新印象和旧记忆冲突时,写新条进入待复核,保留旧版本的事实与时间;不要用 update 抹掉旧说法。角色的误解写清 `source: inferred/imagined`,低置信不是随意改史的许可;关系、承诺与事件可用带理由的 `memu_private_link` 连接。
28
+ - 相对日期写入时落 `absolute_date`;无法解析就标 `date_precision=unknown`,不要猜。
29
+ - 同一事实的两种说法各写一条,用 `conflicts_with` 互指;明确取代才用 `supersedes`,旧正文不删。
30
+ - 承诺/约定写成 `commitment`:对谁、做什么、`due_at`、`status`;到期未完成要能被后续注入看到。
31
+ - 助手说过的承诺、计划、事实也要写;`source_kind=assistant_said`,不能记成用户说的。
28
32
  - 出戏的话(换写法、停一下、补充设定)不是剧情里发生的事。要记就记成「关于我们怎么写这个故事的约定」,别混进故事。
29
33
  - 回忆在回应中多体现为自然的称呼、选择或分寸,不每轮翻旧账、重复口头禅或解释机制。工具 waiting/sleep 的时长与日志不是剧情事件,不据此制造冷落、好感变化或时间跳跃。
30
34
 
@@ -9,6 +9,9 @@
9
9
  - 群聊先辨认当前说话人、被回应的人和话题归属;不同人的称呼、承诺、私聊秘密不能混在一起,不把所有消息都理解成在对你说话。长时间 waiting、工具 sleep 或日志本身不是人物被冷落、时间跳跃或关系变化的证据。
10
10
 
11
11
  - 先查再开口:对方提到以前的事、问你记不记得、或者要许下什么之前,先用 `memu_private_recall` 找一找。想不起细节时可以说想不起来——但只有在真的查过之后,说不记得才是可信的。
12
+ - 相对日期先按这一轮的时间换算:昨天、明天、下周X、月底都要落到具体日期;算不出来就说不知道,不要把旧计划当现在。
13
+ - 记忆里有两版说法时,先把两版按时间摆出来再回答;不要替对方裁决哪版为准,也不要用后一版悄悄覆盖前一版。
14
+ - 分清是谁说的:对方说的、我说过的、听别人说的、我脑补的,不能混成一句。
12
15
  - 允许想不起细节、感受偏心或理解改变;事实不能为了人味而记错。不确定就说明未知并降低 confidence,不能用低置信度给改写历史开许可。内心猜测与梦境标明 inferred/imagined,不当成对方真实的想法。
13
16
  - 一致性优先于戏剧性:宁可平淡,也不要为了好看改掉已经发生过的事。
14
17
  - 正常入戏时不主动报数据库、注入或工具日志;用户出戏询问机制、来源或是否记得时如实回答,不假装查过、一直记得或经历过没有发生的事。
@@ -35,6 +35,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
35
35
  let misses = 0
36
36
  let evictions = 0
37
37
  let errors = 0
38
+ let staleSkipped = 0
38
39
  let lastError = null
39
40
 
40
41
  const fail = (op, error, key = null) => {
@@ -55,6 +56,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
55
56
  if (expired(entry)) {
56
57
  map.delete(ck)
57
58
  evictions += 1
59
+ staleSkipped += 1
58
60
  return null
59
61
  }
60
62
  // LRU 新鲜度:命中即挪到 Map 尾部(删除再插入)。
@@ -101,7 +103,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
101
103
  try {
102
104
  gen += 1
103
105
  for (const [ck, entry] of map) {
104
- if (entry.gen !== gen) { map.delete(ck); evictions += 1 }
106
+ if (entry.gen !== gen) { map.delete(ck); evictions += 1; staleSkipped += 1 }
105
107
  }
106
108
  } catch (error) { fail('bumpGeneration', error) }
107
109
  },
@@ -117,6 +119,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
117
119
  map.delete(ck)
118
120
  removed += 1
119
121
  evictions += 1
122
+ staleSkipped += 1
120
123
  }
121
124
  } catch {}
122
125
  }
@@ -163,7 +166,7 @@ export function createRecallCache({ max = 256, ttlMs = 120000, now = () => Date.
163
166
  return run
164
167
  },
165
168
  stats() {
166
- return { size: map.size, hits, misses, evictions, generations: gen, errors, lastError, inflight: inflight.size }
169
+ return { size: map.size, hits, misses, evictions, staleSkipped, generations: gen, errors, lastError, inflight: inflight.size }
167
170
  },
168
171
  /** 接错误观察者(memory.js 接 warn,规则 10 的可观测信号)。 */
169
172
  setErrorHandler(handler) {
@@ -202,3 +205,8 @@ export function recallCacheKey({ query, topK, libraryId, byId, route, generation
202
205
 
203
206
  /** 模块级默认单例:memory.js 直接使用。 */
204
207
  export const recallCache = createRecallCache()
208
+
209
+ /** S10:只读统计快照(RPC/运维用);调用方不持有缓存内部状态。 */
210
+ export function recallCacheStats() {
211
+ return recallCache.stats()
212
+ }
package/lib/rpc.js CHANGED
@@ -16,6 +16,7 @@ import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJob
16
16
  import { maybeMigrateLibraries } from './migrate.js'
17
17
  import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
18
18
  import { statsView } from './stats.js'
19
+ import { recallCacheStats } from './recall-cache.js'
19
20
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
20
21
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
21
22
  import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAsset, SETTINGS_PATH } from './webui.js'
@@ -698,6 +699,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
698
699
  pinnedCount: privateEntries.filter((e) => e.layer === 'must_remember' && e.status !== 'archived').length,
699
700
  globalCount: globalEntries.filter((e) => (e.status || 'active') === 'active').length,
700
701
  jobs: listCurationJobs().slice(-10),
702
+ recallCache: recallCacheStats(),
701
703
  }
702
704
  }
703
705
  case 'diagnoseSession': {
@@ -1724,7 +1726,12 @@ async function dispatch(ctx, endpoint, payload = {}) {
1724
1726
  const sessionId = requireSessionId(payload)
1725
1727
  // Explicit button press: the user already decided this conversation is worth
1726
1728
  // summarizing, so the automatic "is there anything in it" gate does not apply.
1727
- return requestPrivateConsolidation(ctx, sessionId, { force: true })
1729
+ // 评测/联调可显式指定 trigger:trigger='backlog' + force=false 时走积压口径
1730
+ // (事件 ≥200 或人类回合 ≥10 才放行),用来验证水位触发本身。
1731
+ return requestPrivateConsolidation(ctx, sessionId, {
1732
+ force: payload?.force !== false,
1733
+ ...(payload?.trigger ? { trigger: String(payload.trigger) } : {}),
1734
+ })
1728
1735
  }
1729
1736
  case 'generateGlobal': {
1730
1737
  const sessionId = requireSessionId(payload)
@@ -1885,7 +1892,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1885
1892
  })
1886
1893
  case 'switchLocalVectorProfile':
1887
1894
  if (payload?.confirmed !== true) throw new Error('switching the local vector profile requires explicit confirmation')
1888
- return await switchLocalVectorProfile({ id: payload?.id })
1895
+ return await switchLocalVectorProfile({ id: payload?.id, force: payload?.force === true })
1889
1896
  case 'rollbackLocalVectorProfile':
1890
1897
  if (payload?.confirmed !== true) throw new Error('rolling back the local vector profile requires explicit confirmation')
1891
1898
  return await rollbackLocalVectorProfile()
package/lib/snippet.js CHANGED
@@ -61,3 +61,28 @@ export function centeredSnippet(text, query, { before = 40, after = 120 } = {})
61
61
  const tail = end < body.length ? ELLIPSIS : ''
62
62
  return head + body.slice(start, end) + tail
63
63
  }
64
+
65
+ function clip(value, max) {
66
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
67
+ return text.length <= max ? text : text.slice(0, Math.max(0, max - 1)) + ELLIPSIS
68
+ }
69
+
70
+ /**
71
+ * S2/S6 冲突卡:两条对同一事实的不同说法并排,不替模型裁决。
72
+ * 单卡 200 字以内;两个 id 都必须出现,否则调用方应丢弃这张卡。
73
+ */
74
+ export function conflictCard({ factKey, left, right } = {}) {
75
+ if (!left?.id || !right?.id) return ''
76
+ const side = (item, label) => {
77
+ const entry = item.entry || {}
78
+ const title = entry.title || entry.content || '(untitled)'
79
+ const date = entry.absolute_date ? `(${entry.absolute_date})` : ''
80
+ return `- ${label} [${item.id}] ${clip(title, 40)}${date}`
81
+ }
82
+ return clip([
83
+ `冲突 · ${clip(factKey || '同一事实', 60)}`,
84
+ side(left, 'A'),
85
+ side(right, 'B'),
86
+ '- 未确认哪版为准',
87
+ ].join('\n'), 200)
88
+ }
@@ -0,0 +1,329 @@
1
+ // 相对日期 → 绝对日期。
2
+ //
3
+ // 相对日期不能靠模型心算。写入时按这一轮的逻辑时间(sceneTime)解析,
4
+ // 召回时也先把查询里的相对日期解析成绝对日期再拼检索词。这是个纯函数模块:
5
+ // 不做 IO、不读系统时钟(除非调用方不传 now),失败返回 null,绝不猜。
6
+
7
+ const DAY_MS = 86_400_000
8
+ const DEFAULT_TIME_ZONE = 'Asia/Shanghai'
9
+ const YEAR_MIN = 1900
10
+ const YEAR_MAX = 2999
11
+
12
+ const WEEKDAY_INDEX = new Map([
13
+ ['一', 0], ['二', 1], ['三', 2], ['四', 3], ['五', 4], ['六', 5], ['日', 6], ['天', 6],
14
+ ['1', 0], ['2', 1], ['3', 2], ['4', 3], ['5', 4], ['6', 5], ['7', 6],
15
+ ])
16
+
17
+ const RELATIVE_DAY_TERMS = [
18
+ ['大后天', 3], ['大前天', -3],
19
+ ['后天', 2], ['前天', -2],
20
+ ['明天', 1], ['昨天', -1], ['今天', 0],
21
+ ['明日', 1], ['昨日', -1], ['今日', 0],
22
+ ].sort((a, b) => b[0].length - a[0].length)
23
+
24
+ const EN_RELATIVE_DAYS = new Map([
25
+ ['today', 0], ['tomorrow', 1], ['yesterday', -1],
26
+ ['the day after tomorrow', 2], ['the day before yesterday', -2],
27
+ ])
28
+
29
+ const formatterCache = new Map()
30
+
31
+ function pad2(value) {
32
+ return String(value).padStart(2, '0')
33
+ }
34
+
35
+ function formatDate({ y, m, d }) {
36
+ return `${String(y).padStart(4, '0')}-${pad2(m)}-${pad2(d)}`
37
+ }
38
+
39
+ function daysInMonth(y, m) {
40
+ return new Date(Date.UTC(y, m, 0)).getUTCDate()
41
+ }
42
+
43
+ function validCalendar(y, m, d) {
44
+ if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return false
45
+ if (y < YEAR_MIN || y > YEAR_MAX || m < 1 || m > 12 || d < 1) return false
46
+ return d <= daysInMonth(y, m)
47
+ }
48
+
49
+ function addDays({ y, m, d }, days) {
50
+ const at = new Date(Date.UTC(y, m - 1, d) + Number(days) * DAY_MS)
51
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1, d: at.getUTCDate() }
52
+ }
53
+
54
+ function weekdayMondayIndex({ y, m, d }) {
55
+ return (new Date(Date.UTC(y, m - 1, d)).getUTCDay() + 6) % 7
56
+ }
57
+
58
+ function mondayOfWeek({ y, m, d }) {
59
+ return addDays({ y, m, d }, -weekdayMondayIndex({ y, m, d }))
60
+ }
61
+
62
+ function addMonths({ y, m }, months) {
63
+ const at = new Date(Date.UTC(y, m - 1 + Number(months), 1))
64
+ return { y: at.getUTCFullYear(), m: at.getUTCMonth() + 1 }
65
+ }
66
+
67
+ function formatterFor(timeZone) {
68
+ const key = String(timeZone || '')
69
+ if (formatterCache.has(key)) return formatterCache.get(key)
70
+ let formatter
71
+ try {
72
+ formatter = new Intl.DateTimeFormat('en-US', {
73
+ timeZone: key || DEFAULT_TIME_ZONE,
74
+ year: 'numeric', month: '2-digit', day: '2-digit',
75
+ })
76
+ } catch {
77
+ formatter = new Intl.DateTimeFormat('en-US', {
78
+ timeZone: DEFAULT_TIME_ZONE,
79
+ year: 'numeric', month: '2-digit', day: '2-digit',
80
+ })
81
+ }
82
+ formatterCache.set(key, formatter)
83
+ return formatter
84
+ }
85
+
86
+ function instantOf(now) {
87
+ if (now instanceof Date) return Number.isFinite(now.getTime()) ? now : new Date()
88
+ if (typeof now === 'number') {
89
+ const at = new Date(now)
90
+ return Number.isFinite(at.getTime()) ? at : new Date()
91
+ }
92
+ if (typeof now === 'string' && now.trim()) {
93
+ const at = new Date(now)
94
+ if (Number.isFinite(at.getTime())) return at
95
+ }
96
+ return new Date()
97
+ }
98
+
99
+ function zonedCalendar(instant, timeZone) {
100
+ const parts = formatterFor(timeZone).formatToParts(instant)
101
+ const values = {}
102
+ for (const part of parts) {
103
+ if (part.type === 'year' || part.type === 'month' || part.type === 'day') values[part.type] = Number(part.value)
104
+ }
105
+ if (!validCalendar(values.year, values.month, values.day)) {
106
+ return { y: instant.getUTCFullYear(), m: instant.getUTCMonth() + 1, d: instant.getUTCDate() }
107
+ }
108
+ return { y: values.year, m: values.month, d: values.day }
109
+ }
110
+
111
+ function candidate(index, sourceText, calendar, precision, dateSource, priority) {
112
+ if (!validCalendar(calendar.y, calendar.m, calendar.d)) return null
113
+ return {
114
+ absoluteDate: formatDate(calendar),
115
+ precision,
116
+ sourceText: String(sourceText || '').trim(),
117
+ dateSource,
118
+ index: Number(index) || 0,
119
+ priority,
120
+ calendar,
121
+ }
122
+ }
123
+
124
+ function matchesOf(re, text, build) {
125
+ const out = []
126
+ re.lastIndex = 0
127
+ let match
128
+ while ((match = re.exec(text)) !== null) {
129
+ const item = build(match)
130
+ if (item) out.push(item)
131
+ if (match[0].length === 0) re.lastIndex += 1
132
+ }
133
+ return out
134
+ }
135
+
136
+ function explicitCandidates(text, today) {
137
+ // 只认完整年月日;不带年份的 MM-DD 是周年日,不是某一天。
138
+ const re = /(?<![\d])(\d{4})\s*[-/年]\s*(\d{1,2})\s*[-/月]\s*(\d{1,2})\s*[日号]?(?![\d])/g
139
+ return matchesOf(re, text, (match) => candidate(
140
+ match.index,
141
+ match[0],
142
+ { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) },
143
+ 'day',
144
+ 'explicit',
145
+ 0,
146
+ ))
147
+ }
148
+
149
+ function relativeDayCandidates(text, today) {
150
+ const out = []
151
+ for (const [term, offset] of RELATIVE_DAY_TERMS) {
152
+ let from = 0
153
+ while (from < text.length) {
154
+ const at = text.indexOf(term, from)
155
+ if (at < 0) break
156
+ // "大后天" 里的 "后天" 不单独算一次:长度更长的词优先。
157
+ const longerBefore = at > 0 && RELATIVE_DAY_TERMS.some(([other]) => other.length > term.length
158
+ && text.slice(Math.max(0, at - (other.length - term.length)), at + term.length) === other)
159
+ const longerAt = RELATIVE_DAY_TERMS.some(([other]) => other.length > term.length
160
+ && text.slice(at, at + other.length) === other)
161
+ if (!longerBefore && !longerAt) {
162
+ const item = candidate(at, term, addDays(today, offset), 'day', 'relative', 10)
163
+ if (item) out.push(item)
164
+ }
165
+ from = at + term.length
166
+ }
167
+ }
168
+ const en = /(?<![a-z])(the day after tomorrow|the day before yesterday|today|tomorrow|yesterday)(?![a-z])/gi
169
+ for (const match of matchesOf(en, text, (item) => item)) {
170
+ const offset = EN_RELATIVE_DAYS.get(match[0].toLowerCase())
171
+ if (offset === undefined) continue
172
+ const item = candidate(match.index, match[0], addDays(today, offset), 'day', 'relative', 10)
173
+ if (item) out.push(item)
174
+ }
175
+ return out
176
+ }
177
+
178
+ function weekCandidates(text, today) {
179
+ const re = /(上上|上|下个|下|这个|这|本)\s*(?:周|星期|礼拜)\s*([一二三四五六日天1-7])/g
180
+ return matchesOf(re, text, (match) => {
181
+ const prefix = match[1]
182
+ const weekday = WEEKDAY_INDEX.get(match[2])
183
+ if (weekday === undefined) return null
184
+ let weeks = 0
185
+ if (prefix === '下' || prefix === '下个') weeks = 1
186
+ else if (prefix === '上') weeks = -1
187
+ else if (prefix === '上上') weeks = -2
188
+ const monday = mondayOfWeek(today)
189
+ return candidate(match.index, match[0], addDays(monday, weeks * 7 + weekday), 'day', 'relative', 20)
190
+ })
191
+ }
192
+
193
+ function monthDayCandidates(text, today) {
194
+ const re = /(下个?月|下月份?|本月|这个月份?)\s*(\d{1,2})\s*[号日]/g
195
+ return matchesOf(re, text, (match) => {
196
+ const day = Number(match[2])
197
+ const month = match[1].startsWith('下') ? addMonths(today, 1) : { y: today.y, m: today.m }
198
+ if (day < 1 || day > daysInMonth(month.y, month.m)) return null
199
+ return candidate(match.index, match[0], { y: month.y, m: month.m, d: day }, 'day', 'relative', 30)
200
+ })
201
+ }
202
+
203
+ function monthBoundaryCandidates(text, today) {
204
+ const re = /(下个?月|下月份?|本月|这个月份?|月)\s*(?:底|末)/g
205
+ return matchesOf(re, text, (match) => {
206
+ const prefix = match[1]
207
+ const month = prefix.startsWith('下') ? addMonths(today, 1) : { y: today.y, m: today.m }
208
+ return candidate(match.index, match[0], { y: month.y, m: month.m, d: daysInMonth(month.y, month.m) }, 'month', 'relative', 40)
209
+ })
210
+ }
211
+
212
+ function yearBoundaryCandidates(text, today) {
213
+ const out = []
214
+ for (const match of text.matchAll(/年初/g)) {
215
+ const item = candidate(match.index, match[0], { y: today.y, m: 1, d: 1 }, 'year', 'relative', 50)
216
+ if (item) out.push(item)
217
+ }
218
+ for (const match of text.matchAll(/(?:年底|年末)/g)) {
219
+ const item = candidate(match.index, match[0], { y: today.y, m: 12, d: 31 }, 'year', 'relative', 50)
220
+ if (item) out.push(item)
221
+ }
222
+ return out
223
+ }
224
+
225
+ function offsetDayCandidates(text, today) {
226
+ const out = []
227
+ const after = /(\d{1,3})\s*天\s*(?:之|以)?后/g
228
+ for (const match of text.matchAll(after)) {
229
+ const days = Number(match[1])
230
+ if (!Number.isFinite(days)) continue
231
+ const item = candidate(match.index, match[0], addDays(today, days), 'day', 'relative', 12)
232
+ if (item) out.push(item)
233
+ }
234
+ const before = /(\d{1,3})\s*天\s*(?:之|以)?前/g
235
+ for (const match of text.matchAll(before)) {
236
+ const days = Number(match[1])
237
+ if (!Number.isFinite(days)) continue
238
+ const item = candidate(match.index, match[0], addDays(today, -days), 'day', 'relative', 12)
239
+ if (item) out.push(item)
240
+ }
241
+ return out
242
+ }
243
+
244
+ function allCandidates(text, { now, timeZone } = {}) {
245
+ const normalized = String(text ?? '').normalize('NFKC')
246
+ if (!normalized.trim()) return []
247
+ const today = zonedCalendar(instantOf(now), timeZone)
248
+ const found = [
249
+ ...explicitCandidates(normalized, today),
250
+ ...relativeDayCandidates(normalized, today),
251
+ ...weekCandidates(normalized, today),
252
+ ...monthDayCandidates(normalized, today),
253
+ ...monthBoundaryCandidates(normalized, today),
254
+ ...yearBoundaryCandidates(normalized, today),
255
+ ...offsetDayCandidates(normalized, today),
256
+ ]
257
+ // 同一位置同一句只留最具体的一条(显式日期 > 相对日 > 周 > 月日 > 月底 > 年)。
258
+ const best = new Map()
259
+ for (const item of found) {
260
+ const key = `${item.index}:${item.sourceText}`
261
+ const current = best.get(key)
262
+ if (!current || item.priority < current.priority) best.set(key, item)
263
+ }
264
+ return [...best.values()].sort((a, b) => a.index - b.index || a.priority - b.priority)
265
+ }
266
+
267
+ /**
268
+ * 解析文本里最可信的一个日期表达。
269
+ * @returns {{absoluteDate: string, precision: 'day'|'month'|'year', sourceText: string,
270
+ * dateSource: 'explicit'|'relative', index: number}|null}
271
+ */
272
+ export function parseTemporalExpression(text, { now = new Date(), timeZone = DEFAULT_TIME_ZONE } = {}) {
273
+ const found = allCandidates(text, { now, timeZone })
274
+ if (found.length === 0) return null
275
+ const ordered = found.slice().sort((a, b) => a.priority - b.priority || a.index - b.index)
276
+ const chosen = ordered[0]
277
+ return {
278
+ absoluteDate: chosen.absoluteDate,
279
+ precision: chosen.precision,
280
+ sourceText: chosen.sourceText,
281
+ dateSource: chosen.dateSource,
282
+ index: chosen.index,
283
+ }
284
+ }
285
+
286
+ /** 文本里所有可解析的日期表达,按出现顺序。 */
287
+ export function extractTemporalExpressions(text, options = {}) {
288
+ return allCandidates(text, options).map((item) => ({
289
+ absoluteDate: item.absoluteDate,
290
+ precision: item.precision,
291
+ sourceText: item.sourceText,
292
+ dateSource: item.dateSource,
293
+ index: item.index,
294
+ }))
295
+ }
296
+
297
+ /** 查询侧:文本里所有绝对日期,去重后按出现顺序。 */
298
+ export function resolveQueryDates(text, options = {}) {
299
+ const dates = []
300
+ for (const item of extractTemporalExpressions(text, options)) {
301
+ if (!dates.includes(item.absoluteDate)) dates.push(item.absoluteDate)
302
+ }
303
+ return dates
304
+ }
305
+
306
+ /** 有相对时间词、但可能解析不出来(例如只说“下周”)。 */
307
+ export function hasTemporalHint(text) {
308
+ const value = String(text ?? '').normalize('NFKC')
309
+ return /大后天|大前天|后天|前天|明天|昨天|今天|今日|明日|昨日|下周|这周|本周|下周|上周|下个?月|本月|这个月|月底|月末|年初|年底|年末|\d\s*天\s*(?:之|以)?[前后]|(?<![a-z])(today|tomorrow|yesterday)(?![a-z])/i.test(value)
310
+ }
311
+
312
+ /** 严格 YYYY-MM-DD;非法日期返回 null(不猜)。 */
313
+ export function parseAbsoluteDate(value) {
314
+ const text = String(value ?? '').trim()
315
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
316
+ if (!match) return null
317
+ const y = Number(match[1])
318
+ const m = Number(match[2])
319
+ const d = Number(match[3])
320
+ if (!validCalendar(y, m, d)) return null
321
+ return formatDate({ y, m, d })
322
+ }
323
+
324
+ /** 某个瞬间在指定时区里的本地日期(YYYY-MM-DD)。 */
325
+ export function localDateKeyInZone(value = new Date(), timeZone = DEFAULT_TIME_ZONE) {
326
+ return formatDate(zonedCalendar(instantOf(value), timeZone))
327
+ }
328
+
329
+ export { DEFAULT_TIME_ZONE, DAY_MS }
@@ -53,6 +53,7 @@ import {
53
53
  tokenStreamV2,
54
54
  tokenize as tokenizeV2,
55
55
  } from './tokenizer-v2.js'
56
+ import { hasTemporalHint, resolveQueryDates, DEFAULT_TIME_ZONE } from './temporal.js'
56
57
 
57
58
  // —— §4.1 分词 ——
58
59
 
@@ -852,3 +853,73 @@ export function buildCandidateClusters(index, options = {}) {
852
853
  for (let i = 0; i < out.length; i++) out[i].cluster_id = `cl-${i + 1}`
853
854
  return { clusters: out.slice(0, maxClusters), truncated, scanned: pool.length }
854
855
  }
856
+
857
+ // —— S5 查询意图与分解 ——
858
+ //
859
+ // 召回入口只需要知道“这句话在问哪一类事”,然后决定过滤与取数策略:
860
+ // date 时间题:先解析相对日期,按 absolute_date 过滤/排序
861
+ // entity 实体题:抽出实体名/别名,按实体索引扩展一跳
862
+ // conflict 冲突题:按 fact_key / conflicts_with 成对取
863
+ // commitment 约定题:未完成/到期承诺优先
864
+ // boundary 边界题:只有用户明确问到时才注入 only_if_asked
865
+ // general 普通题
866
+ // 纯规则,无外部模型,无网络;识别不出来就是 general,不猜。
867
+
868
+ const CONFLICT_RE = /矛盾|冲突|到底|哪一版|哪个版本|哪边|前后说法|说法不一|改口|不一致|不是说|谁对|真的吗|相反|contradict|conflict|which version/i
869
+ const COMMITMENT_RE = /答应|承诺|约定|说好|欠|兑现|到期|还没|什么时候还|做到|提醒我|promise|commitment|owe/i
870
+ const BOUNDARY_RE = /秘密|保密|别说|别告诉|不要告诉|不能说|不能提|隐私|瞒着|never[-_ ]?say|only if asked|secret/i
871
+ const DATE_QUERY_RE = /什么时候|哪天|几号|日期|时间|多久|几点|星期几|上次|之前|后来|最近|when|what time|which day/i
872
+
873
+ /**
874
+ * @returns {'date'|'entity'|'conflict'|'commitment'|'boundary'|'general'}
875
+ */
876
+ export function detectQueryIntent(query, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
877
+ const text = String(query || '').trim()
878
+ if (!text) return 'general'
879
+ if (CONFLICT_RE.test(text)) return 'conflict'
880
+ if (COMMITMENT_RE.test(text)) return 'commitment'
881
+ if (BOUNDARY_RE.test(text)) return 'boundary'
882
+ if (hasTemporalHint(text) || DATE_QUERY_RE.test(text) || /\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(text)) return 'date'
883
+ if (extractQueryEntities(text, { knownEntities }).length > 0) return 'entity'
884
+ return 'general'
885
+ }
886
+
887
+ const QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
888
+ const AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
889
+
890
+ /** 实体抽取只用“明确标注”的名字:引号、@、已知实体表。宁缺毋滥。 */
891
+ export function extractQueryEntities(query, { knownEntities = [] } = {}) {
892
+ const text = String(query || '')
893
+ const found = []
894
+ const add = (value) => {
895
+ const name = String(value || '').trim()
896
+ if (name.length < 2 || name.length > 30) return
897
+ if (!found.includes(name)) found.push(name)
898
+ }
899
+ for (const match of text.matchAll(QUOTED_RE)) add(match[1])
900
+ for (const match of text.matchAll(AT_RE)) add(match[1])
901
+ for (const name of Array.isArray(knownEntities) ? knownEntities : []) {
902
+ if (typeof name === 'string' && name.trim().length >= 2 && text.includes(name)) add(name)
903
+ }
904
+ return found.slice(0, 6)
905
+ }
906
+
907
+ /**
908
+ * 把查询拆成召回能直接用的零件。`expanded` 是拼给词法/向量检索的查询,
909
+ * `dates`/`entities` 同时供过滤与排序使用。
910
+ */
911
+ export function decomposeQuery(query, intent = null, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
912
+ const text = String(query || '')
913
+ const resolvedIntent = intent || detectQueryIntent(text, { now, timeZone, knownEntities })
914
+ const dates = resolveQueryDates(text, { now, timeZone })
915
+ const entities = extractQueryEntities(text, { knownEntities })
916
+ const terms = [...new Set([...dates, ...entities])]
917
+ return {
918
+ query: text,
919
+ intent: resolvedIntent,
920
+ dates,
921
+ entities,
922
+ terms,
923
+ expanded: [text, ...terms].filter(Boolean).join(' ').trim(),
924
+ }
925
+ }