dsh-xuyi-memory 1.0.1 → 1.0.2

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.
@@ -172,6 +172,20 @@ def render_line(piece, today=None):
172
172
 
173
173
  expansion_rounds = 3
174
174
  AUTO_RELATED_BUDGET = 300
175
+ GROUP_LINES = 2 # 群里一次最多递几条原话
176
+ GROUP_HEADER = HEADER + "以下是这个群里的聊天记录,只在本群用;[ ] 里是谁说的。\n"
177
+ # 群里不当众说的私事(本人问自己的除外):心情、病、感情、钱、家里的事。
178
+ # 过敏、忌口不算:一起点外卖、聚餐时群里知道反而有用(用户定,2026-11-17)。
179
+ GROUP_PRIVATE = re.compile(r"难过|伤心|哭|焦虑|抑郁|失眠|崩溃|压力|孤单|委屈|医院|看医生|吃药|生病|病了|住院|手术|体检|怀孕|"
180
+ r"分手|离婚|吵架|失恋|前任|工资|月薪|存款|存了|欠钱|借钱|房贷|去世|走了")
181
+ # 本人在群里问自己的私事:原话照给,但提醒她当着大家只轻轻带过(用户定,2026-11-17)。
182
+ GROUP_OWN_PRIVATE_NOTE = ("|这是TA自己的私事,现在是在群里:只轻轻带过(比如「你前阵子说睡得不太好」),"
183
+ "别说出病名、吃药、钱数、感情这些细节;想细聊就让TA私聊你")
184
+ HER_ANSWER_LIMIT = 2
185
+ HER_ROOM_LIMIT = 30 # 找她自己的喜好时,最多再看这么多个别的聊天
186
+ # 问她喜好时的壳:「你最喜欢什么X」里能用来对上以前那句问话的只有 X。
187
+ HER_QUESTION_SHELL = {"最喜", "喜欢", "欢什", "你最", "最爱", "爱吃", "爱喝", "你喜", "你爱"}
188
+ ABOUT_ME_BUDGET = 600 # 问自己的事时自动带的原话,最多这么多(字节),免得把提示词撑大
175
189
  RARE_DF = 8
176
190
  MUNDANE = {"天气", "时间", "时候", "东西", "问题", "地方", "感觉", "事情", "事情",
177
191
  "工作", "学习", "吃饭", "睡觉", "视频", "照片", "表情", "今天", "明天",
@@ -182,7 +196,7 @@ MUNDANE = {"天气", "时间", "时候", "东西", "问题", "地方", "感觉",
182
196
  FUNCTION_TERMS = {
183
197
  "什么", "来着", "记得", "还记", "你还", "得我", "是不", "不是", "有没", "没有", "怎么", "那个", "这个",
184
198
  "一下", "我们", "你们", "他们", "知道", "告诉", "你说", "我说", "叫啥", "啥来", "了吗", "我的", "你的",
185
- "我是", "我在", "我有", "我要", "我想", "最近", "今天", "现在", "时候", "是什", "么时", "什么时",
199
+ "我是", "我在", "我有", "我要", "我想", "我最", "最近", "今天", "现在", "时候", "是什", "么时", "什么时",
186
200
  "the", "and", "for", "with", "what", "when", "where", "who", "why", "how", "did", "does", "was", "were",
187
201
  "his", "her", "their", "they", "she", "has", "have", "had", "about", "from", "that", "this", "which",
188
202
  }
@@ -252,12 +266,30 @@ def rank_penalty(piece, now=None):
252
266
  FOCUS_DAY = 12
253
267
 
254
268
 
269
+ # 问句里的单字名词(「我的猫都叫什么」里的「猫」):原话「我有两只猫」和问句没有共同的双字词。
270
+ # 只认这一小批:「最近」的「近」、「换过」的「换」这种字一放开,就会抓到不相干的话。
271
+ SINGLE_NOUNS = set("猫狗鸟鱼兔龟车房书歌剧茶酒烟药牙腰腿膝胃眼")
272
+
273
+
274
+ def own_single_match(piece, singles):
275
+ """单字只在用户说自己的事时算数:「我有两只猫」算,「路上看到一只橘猫」不算。"""
276
+ return (bool(singles) and piece.get('role') == 'user' and '我' in piece['text']
277
+ and any(ch in piece['text'] for ch in singles))
278
+
279
+
280
+ def content_chars(query):
281
+ return {ch for ch in query if ch in SINGLE_NOUNS}
282
+
283
+
255
284
  def informative_terms(query, df, chunks):
256
285
  """Query terms that can vouch for a line: multi-character, not scaffolding, not ubiquitous."""
257
286
  out = set()
258
287
  for term in set(terms(query)):
259
288
  if len(term) < 2 or term in FUNCTION_TERMS:
260
289
  continue
290
+ # 「我一般」的「我一」跨了词,会碰上「我一直在」;「我妈」「我姐」这种留着。
291
+ if len(term) == 2 and term[0] in "我你他她" and term[1] in GLUE_CHARS | NOT_LINKING:
292
+ continue
261
293
  if chunks >= 30 and df(term) > FOCUS_MAX_DF * chunks:
262
294
  continue
263
295
  out.add(term)
@@ -291,7 +323,7 @@ def is_hedge(piece):
291
323
 
292
324
 
293
325
  # 不带「更正」字样的改口:较新的一句带这些字眼、又和较旧的一句有共同实词,就以新的为准。
294
- CHANGE_TEXT = re.compile(r"搬家|搬到|搬去|改到|改成|改为|改去|改喝|改吃|换成|换到|换了|跳槽|离职|辞职|入职"
326
+ CHANGE_TEXT = re.compile(r"搬家|搬到|搬去|搬完家|搬了家|换工作|换了工作|新公司|新单位|改到|改成|改为|改去|改喝|改吃|换成|换到|换了|跳槽|离职|辞职|入职"
295
327
  r"|不再|戒了|已经不|又捡|又养|又买|又多了|又开始|重新开始|恢复|现在")
296
328
  CHANGE_WINDOW = 8 # 只在排名前几条里找(都是和问题相关的行)
297
329
  LATER_POOL = 300 # 「后来又提到」只看这件事之后最近的 300 句
@@ -300,7 +332,7 @@ LATER_COSINE = 0.75 # 语义很近
300
332
  LATER_COSINE_NUMBER = 0.70 # 两句都带数字时,较近就算(数值变了);不能再低:月薪/房租、体重/身高约 0.68
301
333
  LATER_HEAD = 3 # 只给排在最前的 3 条用户原话找后续
302
334
  # 「带数字」:阿拉伯数字,或中文数字后面跟量词/单位(「一万二」「三斤」;「一盒巧克力」不算)。
303
- NUMBER = re.compile(r"\d|[一二两三四五六七八九十百千万]+[万千百块元斤岁公里米分]")
335
+ NUMBER = re.compile(r"\d|[一二两三四五六七八九十百千万]+[万千百块元斤岁公里米分点度号]")
304
336
  # 判断「两句说的是同一件事」时,共有词里至少一个字不是虚字:「我最」不算,「酒了」「只猫」「在住」算。
305
337
  GLUE_CHARS = set("我你他她它的了是在最很都也就还又和吧呢啊吗被把给让要会能想喜欢爱吃喝个这那有没不么什好")
306
338
  # 判断「专有名字」更严:每个字都不能是功能字(「叫阿」这种跨词碎片不算名字)。
@@ -312,11 +344,29 @@ def topic_terms(text):
312
344
  and any(ch not in GLUE_CHARS for ch in t)}
313
345
 
314
346
 
315
- def newer_versions(candidates, df=None, total=0, anchor=None):
347
+ # 问句里能把新旧两句连起来的字:「我存了多少钱」的「存」连起「存了2万」和「存到5万了」。
348
+ # 数字、问句的壳、代词虚字都不算。
349
+ NOT_LINKING = set("什么啥哪谁几多少怎样吗呢来着嘛么般常平时候现在最近"
350
+ "一二两三四五六七八九十百千万零点度号块元斤岁米分") | set("0123456789")
351
+
352
+
353
+ def linking_chars(query):
354
+ return {ch for ch in re.sub(r"[^㐀-鿿]", "", query or "")
355
+ if ch not in NAME_GLUE and ch not in NOT_LINKING}
356
+
357
+
358
+ def same_subject(old_text, new_text, query):
359
+ """两句说的是问句里的同一件事,而且数字变了(存了2万→存到5万;十二点睡→十一点睡)。"""
360
+ shared = linking_chars(query) & set(old_text) & set(new_text)
361
+ return bool(shared) and bool(NUMBER.search(old_text)) and bool(NUMBER.search(new_text))
362
+
363
+
364
+ def newer_versions(candidates, df=None, total=0, anchor=None, query=None):
316
365
  """{旧行 event_id: 更新说法那一行};只看用户原话。
317
366
 
318
367
  anchor:问题里的有效词。旧说法本身要和问题相关(含这些词),或者它是相关行的新说法
319
368
  (「字节上班」→「去了腾讯」→「在米哈游」连成一串);否则两行碰巧都在前几名也不算。
369
+ query:问句原文。数字变了、且和问句共有一个实字的两句,不带改变字眼也算新说法(存到5万了)。
320
370
  """
321
371
  def content(piece):
322
372
  return {t for t in topic_terms(piece['text'])
@@ -328,13 +378,13 @@ def newer_versions(candidates, df=None, total=0, anchor=None):
328
378
  while grew:
329
379
  grew = False
330
380
  for new in sorted(top, key=_moment_key):
331
- if not CHANGE_TEXT.search(new['text']):
332
- continue
381
+ changed = bool(CHANGE_TEXT.search(new['text']))
333
382
  for old in top:
334
- if old['event_id'] not in relevant or old['event_id'] == new['event_id'] \
335
- or _moment_key(old) >= _moment_key(new):
383
+ if old['event_id'] == new['event_id'] or _moment_key(old) >= _moment_key(new):
336
384
  continue
337
- if content(old) & content(new):
385
+ # 和问句共有实字、数字变了的两句,本身就和问题相关,不用再看锚点。
386
+ if same_subject(old['text'], new['text'], query) \
387
+ or (old['event_id'] in relevant and changed and content(old) & content(new)):
338
388
  current = found.get(old['event_id'])
339
389
  if current is None or _moment_key(new) > _moment_key(current):
340
390
  found[old['event_id']] = new
@@ -346,7 +396,12 @@ def newer_versions(candidates, df=None, total=0, anchor=None):
346
396
 
347
397
  # 问大类时把具体的词也带上(拷问集二批问题 7:「宠物」只找回了猫)。
348
398
  CATEGORY_WORDS = {
399
+ # 原话常只说品种(「养了只柯基」),问的是「狗」「猫」。
400
+ re.compile(r"狗"): ("柯基", "金毛", "泰迪", "哈士奇", "柴犬", "边牧", "拉布拉多", "比熊", "博美", "萨摩"),
401
+ re.compile(r"猫"): ("布偶", "英短", "美短", "暹罗", "狸花", "蓝猫", "加菲"),
349
402
  re.compile(r"宠物|养了?(?:哪些|什么|啥)"): ("猫", "狗", "仓鼠", "兔子", "鹦鹉", "乌龟", "金鱼", "柯基", "金毛", "泰迪"),
403
+ re.compile(r"(?:在哪|哪里|哪儿|什么地方)(?:上班|工作)|(?:上班|工作)的?(?:地方|在哪)|哪家公司|公司在哪"):
404
+ ("公司", "单位", "上班", "工作", "入职", "跳槽"),
350
405
  re.compile(r"家人|家里(?:人|都有|有谁)|亲人"): ("爸", "妈", "妹妹", "弟弟", "哥哥", "姐姐", "爷爷", "奶奶", "老公", "老婆"),
351
406
  # 问「怎么称呼我」,原话是「叫我… / 别喊我…」(第四批盲测「别叫我宝宝」)。
352
407
  re.compile(r"称呼|怎么(?:叫|喊)我|(?:叫|喊)我(?:什么|啥)"): ("叫我", "喊我", "别叫", "别喊", "称呼"),
@@ -363,9 +418,47 @@ PROMISE_QUERY = re.compile(r"你.{0,4}(?:答应|保证|说好|承诺)|说好的"
363
418
  PROMISE_PHRASES = ("提醒你", "帮你", "我会", "放心", "包在我", "答应你", "一定")
364
419
 
365
420
 
421
+ # 同一件事的不同说法(问「发型」原话是「头发剪短了」,问「视力」原话是「近视六百度」)。
422
+ # 问句里出现组里任何一个词,就把同组的其他词也带上;两字以内的词还能当锚点。
423
+ SAME_THING = (
424
+ ("头发", "发型", "理发", "剪头", "剪发", "烫发", "染发", "刘海"),
425
+ ("打算", "计划", "准备", "决定", "考虑", "纠结", "想要"),
426
+ ("饮料", "提神", "喝的", "咖啡", "奶茶", "可乐", "果汁"),
427
+ ("视力", "眼睛", "近视", "眼镜", "度数", "隐形"),
428
+ ("运动", "锻炼", "健身", "跑步", "游泳", "瑜伽", "羽毛球", "篮球", "骑车", "爬山", "打球"),
429
+ ("电视剧", "追剧", "在追", "美剧", "韩剧", "综艺", "番剧"),
430
+ ("周末", "周六", "周日", "星期六", "星期天", "星期日", "礼拜六", "礼拜天"),
431
+ ("女儿", "闺女"), ("儿子", "男孩"), ("老公", "丈夫", "先生"), ("老婆", "妻子", "媳妇"),
432
+ ("爸爸", "我爸", "父亲", "老爸"), ("妈妈", "我妈", "母亲", "老妈"),
433
+ ("早餐", "早饭", "早上吃"), ("午饭", "午餐", "中午吃"), ("晚饭", "晚餐", "晚上吃"),
434
+ ("看牙", "牙医", "牙疼", "智齿", "拔牙", "补牙"),
435
+ ("体重", "多重", "公斤", "斤"),
436
+ ("身高", "多高"),
437
+ ("抽烟", "吸烟", "戒烟", "烟"),
438
+ ("喝酒", "戒酒", "酒量"),
439
+ ("乐器", "吉他", "钢琴", "尤克里里", "小提琴", "架子鼓"),
440
+ ("中学", "高中", "初中"),
441
+ ("爱好", "兴趣", "迷上", "爱上", "喜欢上", "入坑", "沉迷"),
442
+ ("睡眠", "睡觉", "失眠", "睡不着", "睡不好", "熬夜", "早睡", "晚睡"),
443
+ ("备考", "考试", "考研", "考公", "公务员", "雅思", "托福", "刷题"),
444
+ ("唱歌", "歌手", "听歌", "的歌"),
445
+ )
446
+
447
+
448
+ ASK_SHELL = re.compile(r"什么|啥|来着|最近|多少|哪儿|哪里|哪|谁|怎么样|怎么|[吗呢嘛][??!!。~~\s]*$|[??]")
449
+
450
+
451
+ def same_thing(query):
452
+ extra = []
453
+ for group in SAME_THING:
454
+ if any(word in query for word in group if len(word) >= 2):
455
+ extra.extend(word for word in group if word not in query)
456
+ return extra
457
+
458
+
366
459
  def focus_expansion(query):
367
460
  """(排序用的查询, 可以当锚点的额外词, 是否在问她自己说过的话, 是否在问最近的状态)"""
368
- extra = []
461
+ extra = same_thing(query)
369
462
  for pattern, words in CATEGORY_WORDS.items():
370
463
  if pattern.search(query):
371
464
  extra.extend(words)
@@ -378,9 +471,14 @@ def focus_expansion(query):
378
471
  mood = bool(MOOD_QUERY.search(query.strip()))
379
472
  if mood:
380
473
  extra.extend(MOOD_WORDS)
474
+ # 排序时去掉问句的壳(「什么/啥/来着」),否则「什么牌子的」这种闲聊会排到证据前面。
475
+ ranked = ASK_SHELL.sub(' ', query).strip() or query
476
+ # 「我一般」→「我 一般」:跨词的「我一」会把「我一直在」排到前面。
477
+ ranked = ''.join(ch + (' ' if ch in "我你他她" and nxt in GLUE_CHARS | NOT_LINKING else '')
478
+ for ch, nxt in zip(ranked, ranked[1:] + ' '))
381
479
  if not extra:
382
- return query, set(), her, mood
383
- return query + ' ' + ' '.join(extra), set(extra), her, mood
480
+ return ranked, set(), her, mood
481
+ return ranked + ' ' + ' '.join(extra), set(extra), her, mood
384
482
 
385
483
 
386
484
  def stale_highlight(store, scope, record, source_events):
@@ -416,7 +514,7 @@ def is_echo(piece, query):
416
514
  return piece.get('start', 0) == 0 and piece['text'].strip() == query.strip()
417
515
 
418
516
 
419
- def auto_remember(store, scope, query, budget=AUTO_RELATED_BUDGET, counter=None):
517
+ def auto_remember(store, scope, query, budget=AUTO_RELATED_BUDGET, counter=None, later=None, pair_budget=None):
420
518
  """Topic-triggered recall for non-question turns.
421
519
 
422
520
  Fires only when the top indexed chunk shares a RARE term (df<=RARE_DF)
@@ -425,9 +523,10 @@ def auto_remember(store, scope, query, budget=AUTO_RELATED_BUDGET, counter=None)
425
523
  never runs when a highlight was found. Zero-injection otherwise.
426
524
  """
427
525
  from . import index as xuyi_index
428
- from .highlights import HISTORY_QUERY, OTHER_OWNER
526
+ from .highlights import HISTORY_QUERY, OTHER_OWNER, _asks_someone_else
429
527
  counter = counter or ByteCounter()
430
- if not query.strip() or HISTORY_QUERY.search(query) or OTHER_OWNER.search(query):
528
+ if not query.strip() or HISTORY_QUERY.search(query) or OTHER_OWNER.search(query) \
529
+ or _asks_someone_else(query):
431
530
  return None
432
531
  if not scope.startswith("qq:c2c:") or not xuyi_index.fresh(store, scope):
433
532
  return None
@@ -441,6 +540,22 @@ def auto_remember(store, scope, query, budget=AUTO_RELATED_BUDGET, counter=None)
441
540
  and xuyi_index.document_frequency(store, scope, term) <= RARE_DF]
442
541
  if not shared:
443
542
  return None
543
+ newer = None
544
+ if piece.get("role") == "user":
545
+ found = newer_versions(top, anchor=grams)
546
+ newer = found.get(piece["event_id"]) or (later(piece) if later else None)
547
+ if newer and newer["event_id"] != piece["event_id"]:
548
+ replaced = bool(newer.get("number_update")) or bool(CHANGE_TEXT.search(newer["text"]))
549
+ if replaced:
550
+ piece = newer # 确定改过了(搬家/换工作/数值变了):只给新的那句
551
+ else:
552
+ # 拿不准后一句是不是推翻了前一句(「汤圆4月1号捡到的」→「汤圆今天生病了」):两句都给,让回复的模型判断。
553
+ old_line = render_line(piece) + "|后来又提到过(见下一行)"
554
+ new_line = render_line(newer) + "|这是后来又提到的"
555
+ both = HEADER + old_line + "\n" + new_line
556
+ if counter.count(both) <= (pair_budget or budget):
557
+ return {"context": both, "sources": [dict(piece, unverified_related=True), dict(newer, unverified_related=True)],
558
+ "budget": budget, "used": counter.count(both), "unit": counter.unit, "shared_terms": shared[:4]}
444
559
  line = render_line(piece)
445
560
  context = HEADER + line
446
561
  if counter.count(context) > budget:
@@ -519,7 +634,125 @@ class Retriever:
519
634
  'origin': event['origin'], 'recorded_at': event['recorded_at'], 'start': 0,
520
635
  'end': len(event['text']), 'text': event['text']}
521
636
 
522
- def _reply_after(self, scope, event_id):
637
+ def _her_answers(self, scope, query, limit=HER_ANSWER_LIMIT):
638
+ """问她自己的喜好(「你最喜欢什么零食」):以前被问过同样的事,她当时怎么答的。
639
+
640
+ [(当时的问句, 她的回答)],最新的在前。她的回答常常不带问句里的词(「薯片吧」),
641
+ 所以不按词找回答,而是找以前那句问话,再取紧跟着的回答。
642
+ """
643
+ from .highlights import asks_her
644
+ if not asks_her(query) or not scope.startswith(("qq:c2c:", "qq:group:")):
645
+ return []
646
+ # 她在哪儿都是同一个人:私聊里说最爱海苔,群里也该是海苔。所以各个房间都找,
647
+ # 但只取她自己的回答;别的房间里那句问话不带出来(那是别处的聊天)。
648
+ rooms = [scope] + [other for other in self.store.scopes()
649
+ if other != scope and other.startswith(("qq:c2c:", "qq:group:"))][:HER_ROOM_LIMIT]
650
+ found, seen = [], set()
651
+ for room in rooms:
652
+ if not index.fresh(self.store, room):
653
+ continue
654
+ total = index.chunk_count(self.store, room) or 0
655
+ df = lambda term, room=room: index.document_frequency(self.store, room, term)
656
+ wanted = informative_terms(query, df, total) - HER_QUESTION_SHELL
657
+ if not wanted:
658
+ continue
659
+ asking = self._latest_user_event(room) if room == scope else None
660
+ for piece in index.ranked_pieces(self.store, room, ASK_SHELL.sub(' ', query), 60):
661
+ if piece.get('role') != 'user' or piece['event_id'] == asking or not asks_her(piece['text']) \
662
+ or not wanted & set(terms(piece['text'])):
663
+ continue
664
+ reply = self._reply_after(room, piece['event_id'], min_len=1)
665
+ if reply and reply['text'] not in seen:
666
+ seen.add(reply['text'])
667
+ found.append((piece if room == scope else None, reply))
668
+ found.sort(key=lambda pair: _moment_key(pair[1]), reverse=True)
669
+ return found[:limit]
670
+
671
+ @staticmethod
672
+ def _her_line(asked, reply):
673
+ where = f"你以前被问「{asked['text'].strip()}」时的回答" if asked else "你以前在别处说过的自己的喜好"
674
+ return render_line(reply) + f"|这是{where};这次说法要和它一致"
675
+
676
+ def _group_recall(self, scope, query, speaker, budget, her=False):
677
+ """群里的自动提醒:只查这个群;最多 GROUP_LINES 条,每条写明是谁说的。
678
+
679
+ - 问的是「我…」:只查正在说话的这个人自己说过的话;
680
+ - 点了某个群友的名字(「小王养了啥」):只查那个群友说过的话;
681
+ - 问她自己的喜好:带上她以前的回答(各个聊天里找,她是同一个人);
682
+ - 不是本人在问的话,心情、病、感情、钱这类私事不当众递出去。
683
+ """
684
+ empty = {'context': '', 'sources': [], 'budget': budget, 'used': 0, 'unit': self.counter.unit}
685
+ from .highlights import asks_her
686
+ if not scope.startswith("qq:group:") or not query.strip():
687
+ return empty
688
+ names = self.store.member_names(scope)
689
+ lines, sources = [], []
690
+ used = self.counter.count(GROUP_HEADER)
691
+
692
+ def add(line, piece):
693
+ nonlocal used
694
+ cost = self.counter.count(line) + 1
695
+ if len(lines) >= GROUP_LINES or used + cost > budget:
696
+ return False
697
+ used += cost
698
+ lines.append(line)
699
+ sources.append(piece)
700
+ return True
701
+
702
+ if asks_her(query):
703
+ if her:
704
+ for asked, reply in self._her_answers(scope, query):
705
+ add(self._her_line(asked, reply), reply)
706
+ else:
707
+ target = speaker if speaker and re.search(r"我|俺|咱", query) else None
708
+ if target is None:
709
+ for sender, name in sorted(names.items(), key=lambda pair: -len(pair[1])):
710
+ if len(name) >= 2 and name in query:
711
+ target = sender
712
+ break
713
+ found = self.recall(scope, ASK_SHELL.sub(' ', query).strip() or query, 1600,
714
+ sender_id=target, focus=True, strict=True, speaker=speaker)
715
+ for piece in found['sources']:
716
+ if piece.get('role') != 'user' or piece.get('answer_to'):
717
+ continue
718
+ if GROUP_PRIVATE.search(piece['text']) and not (speaker and piece['sender_id'] == speaker):
719
+ continue # 别人的私事不当众说;本人问自己的事可以
720
+ who = names.get(piece['sender_id'], '群友')
721
+ line = render_line(piece).replace(f"| {str(piece['sender_id'])[:16]}]", f"| {who}]", 1)
722
+ if GROUP_PRIVATE.search(piece['text']):
723
+ line += GROUP_OWN_PRIVATE_NOTE # 走到这里只可能是本人问自己的
724
+ if not add(line, piece):
725
+ break
726
+ if not lines:
727
+ return empty
728
+ context = GROUP_HEADER + '\n' + '\n'.join(lines)
729
+ self._log(scope, query, sources)
730
+ return {'context': context, 'sources': sources, 'budget': budget,
731
+ 'used': self.counter.count(context), 'unit': self.counter.unit}
732
+
733
+ def _her_own(self, scope, query, budget):
734
+ """自动提醒:问她自己的喜好时,把她以前的回答递给她,这次说法要一致。"""
735
+ pairs = self._her_answers(scope, query)
736
+ if not pairs:
737
+ return None
738
+ lines, sources = [], []
739
+ used = self.counter.count(HEADER)
740
+ for asked, reply in pairs:
741
+ line = self._her_line(asked, reply)
742
+ cost = self.counter.count(line) + 1
743
+ if used + cost > min(budget, ABOUT_ME_BUDGET):
744
+ break
745
+ used += cost
746
+ lines.append(line)
747
+ sources.append(reply)
748
+ if not lines:
749
+ return None
750
+ context = HEADER + '\n' + '\n'.join(lines)
751
+ self._log(scope, query, sources)
752
+ return {'context': context, 'sources': sources, 'budget': budget,
753
+ 'used': self.counter.count(context), 'unit': self.counter.unit}
754
+
755
+ def _reply_after(self, scope, event_id, min_len=8):
523
756
  """The assistant line immediately following an event in this scope, as a whole-event piece.
524
757
 
525
758
  问句和回答分开打分,回答常常不含问句里的词:真机问「哪家的好喝」,只找回了问话,
@@ -532,12 +765,32 @@ class Retriever:
532
765
  return None
533
766
  event = json.loads(row[0])
534
767
  # 太短的回答(「哈哈哈」「在」)带上只是噪音,不占预算。
535
- if event['role'] != 'assistant' or not 8 <= len(event['text']) <= 180:
768
+ if event['role'] != 'assistant' or not min_len <= len(event['text']) <= 180:
536
769
  return None
537
770
  return {'event_id': event['event_id'], 'sender_id': event['sender_id'], 'role': event['role'],
538
771
  'origin': event['origin'], 'recorded_at': event['recorded_at'], 'start': 0,
539
772
  'end': len(event['text']), 'text': event['text']}
540
773
 
774
+ def _about_me(self, scope, query, budget):
775
+ """自动提醒的第二步:问的是用户自己的事(「我老公叫啥」「我多高」),六类重点都不管,
776
+ 就按模型主动查记忆的办法找一遍,但只要和问题有实质共同词的原话,一条猜的都不给。"""
777
+ from .highlights import HISTORY_QUERY, OTHER_OWNER, _asks_someone_else
778
+ if not scope.startswith("qq:c2c:") or HISTORY_QUERY.search(query) or OTHER_OWNER.search(query) \
779
+ or _asks_someone_else(query):
780
+ return None
781
+ if not re.search(r"我|俺|咱", query):
782
+ # 「泡泡还好吗」:只有问到档案里的专名(很少几句提过)才找;「天气怎么样」不翻旧账。
783
+ name = re.match(r"[\u3400-\u9fffA-Za-z]{1,6}?(?=还好|怎么样|最近|现在)", query.strip())
784
+ df = index.document_frequency(self.store, scope, name.group(0)) if name else 0
785
+ if not name or len(name.group(0)) < 2 or name.group(0) in MUNDANE or not 0 < df <= RARE_DF:
786
+ return None
787
+ found = self.recall(scope, query, min(budget, ABOUT_ME_BUDGET), focus=True, strict=True)
788
+ if not found['sources'] or found.get('mode') == 'span-empty':
789
+ return None
790
+ context = found['context'].replace(TOOL_RULE, '', 1)
791
+ return {'context': context, 'sources': found['sources'], 'budget': budget,
792
+ 'used': self.counter.count(context), 'unit': self.counter.unit}
793
+
541
794
  def _later_mention(self, scope, piece, query, df=None, skip=()):
542
795
  """这件旧事后来又被提到的那句(最新的一句),没有就 None。
543
796
 
@@ -556,8 +809,8 @@ class Retriever:
556
809
  text = event.get('text') or ''
557
810
  if event.get('role') != 'user' or event['event_id'] in skip or not text.strip() \
558
811
  or len(text) > 180 or is_bare_question({'role': 'user', 'text': text}) \
559
- or _moment_key(event) <= since:
560
- continue
812
+ or _moment_key(event) <= since or text.strip() == piece['text'].strip():
813
+ continue # 一字不差的复读不是「后来又提到」,没有新内容
561
814
  later.append({'event_id': event['event_id'], 'sender_id': event['sender_id'], 'role': 'user',
562
815
  'origin': event['origin'], 'recorded_at': event['recorded_at'],
563
816
  'start': 0, 'end': len(text), 'text': text})
@@ -571,6 +824,10 @@ class Retriever:
571
824
  shared = {t for t in mine & topic_terms(new['text']) if not set(t) & NAME_GLUE}
572
825
  if shared and df and any(df(t) <= LATER_RARE_DF for t in shared):
573
826
  return new
827
+ for new in later:
828
+ # 没有语义模型时也认数字变了:「存了2万」→「存到5万了」共有问句里的「存」。
829
+ if same_subject(piece['text'], new['text'], query):
830
+ return dict(new, number_update=True)
574
831
  if self.embedder:
575
832
  vectors, _ = self._vectors(scope, [piece] + later)
576
833
  base = vectors[0]
@@ -676,9 +933,12 @@ class Retriever:
676
933
  return [window[i] for i in fused[:take]], new_vectors
677
934
 
678
935
  def recall(self, scope, query, budget=6000, sender_id=None, limit=32, *, highlight_only=False,
679
- dedup=0.0, expansion=False, related=False, ordinal=False, focus=False):
936
+ dedup=0.0, expansion=False, related=False, ordinal=False, focus=False,
937
+ about_me=False, strict=False, her=False, group=False, speaker=None):
680
938
  if isinstance(budget,bool) or not isinstance(budget,int) or budget<0:raise MemoryError('预算必须是非负整数')
681
939
  if not isinstance(query,str):raise MemoryError('问题必须是字符串')
940
+ if group:
941
+ return self._group_recall(scope, query, speaker, budget, her)
682
942
  if not isinstance(limit,int) or not 1<=limit<=256:raise MemoryError('候选上限必须为1至256')
683
943
  if not isinstance(dedup,(int,float)) or not 0<=dedup<1:raise MemoryError('去冗阈值必须在0到1之间')
684
944
  if expansion not in (True,False):raise MemoryError('扩展开关必须是布尔值')
@@ -740,13 +1000,27 @@ class Retriever:
740
1000
  if fits(render_line(evidence[0])):
741
1001
  selected.append(first)
742
1002
  for extra in evidence[1:]:
743
- if not fits(render_line(extra)):break
1003
+ line = render_line(extra)
1004
+ if _moment_key(extra) < _moment_key(evidence[0]):
1005
+ line += '|之后有更新的说法,以新的为准'
1006
+ if not fits(line):break
744
1007
  selected.append(extra)
745
1008
  omitted = set(replaced) | {event['event_id'] for event in source_events}
746
1009
  if highlight_only:
1010
+ if not lines and her:
1011
+ mine = self._her_own(scope, query, budget)
1012
+ if mine:
1013
+ return mine
1014
+ if not lines and about_me:
1015
+ mine = self._about_me(scope, query, budget)
1016
+ if mine:
1017
+ return mine
747
1018
  if not lines and related:
1019
+ df = lambda term: index.document_frequency(self.store, scope, term)
748
1020
  fallback = auto_remember(self.store, scope, query, budget=min(budget, AUTO_RELATED_BUDGET),
749
- counter=self.counter)
1021
+ counter=self.counter, pair_budget=min(budget, 2 * AUTO_RELATED_BUDGET),
1022
+ later=lambda piece: self._later_mention(scope, piece, query, df,
1023
+ set(forgotten) | {piece['event_id']}))
750
1024
  if fallback and any(piece['event_id'] in forgotten for piece in fallback['sources']):
751
1025
  fallback = None
752
1026
  if fallback:
@@ -874,6 +1148,7 @@ class Retriever:
874
1148
  if ordinal and candidates:
875
1149
  replaced = self._supersessions(scope, sender_id, load_events())
876
1150
  informative = None
1151
+ asking_her = False
877
1152
  if focus and candidates:
878
1153
  # Focused recall (the model's own lookup): stop filling the budget with
879
1154
  # lines that only share a character or a question word with the query.
@@ -887,6 +1162,15 @@ class Retriever:
887
1162
  # 短的扩展词(猫/狗/推荐)按词元比;长短语(可以看看)词元里没有,按原文子串比。
888
1163
  informative = informative_terms(query, df, total) | {e for e in extra_terms if len(e) <= 2}
889
1164
  long_extra = tuple(e for e in extra_terms if len(e) > 2)
1165
+ from .highlights import asks_her
1166
+ asking_her = asks_her(query) and not her_words
1167
+ if asking_her:
1168
+ # 问她自己的喜好(「你最喜欢什么零食」):用户说的「我最喜欢辣条」是用户的,不能递给她当自己的。
1169
+ candidates = [p for p in candidates if p.get('role') == 'assistant']
1170
+ # 以前被问过同样的事:她当时的回答排最前(「薯片吧」不带问句里的词,按词找不回来)。
1171
+ for asked, reply in self._her_answers(scope, query):
1172
+ if fits(self._her_line(asked, reply)):
1173
+ selected.append(reply)
890
1174
  if her_words:
891
1175
  # 问的是她说过的话:她自己的原话排前面(稳定排序,原有先后不变)。
892
1176
  candidates = sorted(candidates, key=lambda p: p.get('role') != 'assistant')
@@ -895,7 +1179,9 @@ class Retriever:
895
1179
  moody = [p for p in candidates if p.get('role') == 'user' and any(w in p['text'] for w in MOOD_WORDS)]
896
1180
  moody.sort(key=_moment_key, reverse=True)
897
1181
  candidates = moody + [p for p in candidates if p not in moody]
898
- anchored = any(informative & set(terms(p['text'])) for p in candidates if not is_echo(p, query))
1182
+ singles = {ch for ch in content_chars(query) if total < 30 or df(ch) <= FOCUS_MAX_DF * total}
1183
+ anchored = any(informative & set(terms(p['text'])) or own_single_match(p, singles)
1184
+ for p in candidates if not is_echo(p, query))
899
1185
  if forgotten:
900
1186
  candidates = [p for p in candidates if p['event_id'] not in forgotten]
901
1187
  if focus and candidates:
@@ -906,6 +1192,10 @@ class Retriever:
906
1192
  candidates = [p for p in candidates if p['event_id'] != asking]
907
1193
  if focus and candidates:
908
1194
  candidates = [p for p in candidates if not is_hedge(p)]
1195
+ if focus and candidates and scope.startswith("qq:group:"):
1196
+ # 群里翻记忆:别人的私事(心情、病、感情、钱)不翻出来;正在说话的人问自己的可以。
1197
+ candidates = [p for p in candidates if not (p.get('role') == 'user' and GROUP_PRIVATE.search(p['text'])
1198
+ and p.get('sender_id') != speaker)]
909
1199
  if focus and candidates:
910
1200
  # 拷问集二批问题 2:今天问过的问句排在最前、挤掉证据。问句排到证据后面;
911
1201
  # 她的回答也没内容(「嗯嗯」)的问句直接不要——带回来只会让模型以为"聊过"。
@@ -918,7 +1208,7 @@ class Retriever:
918
1208
  if focus and candidates:
919
1209
  # 拷问集二批问题 3:新说法排到旧说法前面,旧的标「以新的为准」。
920
1210
  newer = newer_versions(candidates, df if informative is not None else None,
921
- total if informative is not None else 0, informative)
1211
+ total if informative is not None else 0, informative, query)
922
1212
  for old_id, new_piece in newer.items():
923
1213
  ids = [p['event_id'] for p in candidates]
924
1214
  if old_id in ids and new_piece['event_id'] in ids \
@@ -956,17 +1246,34 @@ class Retriever:
956
1246
 
957
1247
  kept = 0
958
1248
  followed = 0
1249
+ # 新说法跟着旧说法进来,前提是旧说法自己就和问题对得上:每天一句「今天第13次刷到猫猫视频」
1250
+ # 只是数字不同,不能靠「数字变了」一句串一句地混进来。
1251
+ vouched = set()
1252
+ if informative is not None:
1253
+ for old_id, new_piece in newer.items():
1254
+ old_piece = next((p for p in candidates if p['event_id'] == old_id), None)
1255
+ if old_piece is None or informative & set(terms(old_piece['text'])) \
1256
+ or own_single_match(old_piece, singles):
1257
+ vouched.add(new_piece['event_id'])
959
1258
  for piece in candidates:
960
1259
  if is_echo(piece, query):continue
1260
+ # 自动提醒只递用户自己的原话:她当时的回应(「我一直在」)会把旁边的伤心事一起带出来。
1261
+ if strict and piece.get('role') == 'assistant':continue
961
1262
  # 已作为别的行的「前一句 / 回答」带出来过的,不再出第二次(真实档案里同一行出现了两遍)。
962
1263
  if any(p['event_id'] == piece['event_id'] and p['start'] == piece['start'] for p in selected):continue
1264
+ # 一字不差的重复(每天都说一遍的「下班路上看到橘猫」)只留排在最前的那条,别占掉证据的位置。
1265
+ if any(p['text'].strip() == piece['text'].strip() and p.get('role') == piece.get('role')
1266
+ for p in selected):continue
963
1267
  # The ranker's top line always stays (dense rescues: "噩梦" vs "做梦"); after it,
964
1268
  # anchored queries keep only lines sharing an informative term, unanchored
965
1269
  # ones ("宠物" vs "猫") keep the ranker's first few guesses.
966
1270
  if informative is not None and not informative & set(terms(piece['text'])) \
967
- and piece['event_id'] not in {p['event_id'] for p in newer.values()} \
1271
+ and not own_single_match(piece, singles) \
1272
+ and piece['event_id'] not in vouched \
968
1273
  and not any(e in piece['text'] for e in long_extra) \
969
- and kept >= (FOCUS_DAY if day is not None else (1 if anchored else FOCUS_HEAD)):continue
1274
+ and (strict or (piece.get('role') == 'assistant' and not her_words and not asking_her)
1275
+ or kept >= (FOCUS_DAY if day is not None else (1 if anchored else FOCUS_HEAD))):continue
1276
+ # ↑ 没有共同词时只猜用户自己的原话:她的回应(「我一直在」)一被猜中,就会把前一句伤心事带出来。
970
1277
  kept += 1
971
1278
  if dedup:
972
1279
  grams=bigrams(piece['text'])
@@ -981,6 +1288,8 @@ class Retriever:
981
1288
  if piece['event_id'] in semantic_only:
982
1289
  line+='|仅语义近似,非字面命中'
983
1290
  line += stale_flag(piece)
1291
+ if scope.startswith("qq:group:") and piece.get('role') == 'user' and GROUP_PRIVATE.search(piece['text']):
1292
+ line += GROUP_OWN_PRIVATE_NOTE # 群里留下的私事只会是正在说话的人自己的
984
1293
  if replaced:
985
1294
  successors = []
986
1295
  for begin, newest in replaced.get(piece['event_id'], ()):
@@ -998,7 +1307,10 @@ class Retriever:
998
1307
  prompt = self._prompt_before(scope, piece['event_id'])
999
1308
  if prompt and not is_echo(prompt, query) \
1000
1309
  and not any(p['event_id'] == prompt['event_id'] for p in selected):
1001
- prompt_line = render_line(prompt) + stale_flag(prompt)
1310
+ prompt_line = render_line(prompt) + (stale_flag(prompt) or (
1311
+ '|之后有更新的说法,以新的为准' if any(
1312
+ c.get('role') == 'user' and _moment_key(c) > _moment_key(prompt)
1313
+ and same_subject(prompt['text'], c['text'], query) for c in candidates) else ''))
1002
1314
  if fits(prompt_line):
1003
1315
  selected.append(prompt)
1004
1316
  follow = None
@@ -1045,6 +1357,11 @@ class Retriever:
1045
1357
  if not fits(canonical({'unverified_state_candidate': record})):break
1046
1358
  included.append(record)
1047
1359
  context = header+'\n'+'\n'.join(lines) if lines else ''
1360
+ if context and scope.startswith("qq:group:"):
1361
+ # 群里写明是谁说的:成员编号换成群昵称(只换不比编号长的,不会超预算)。
1362
+ for sender, name in self.store.member_names(scope).items():
1363
+ if len(name.encode('utf-8')) <= len(sender[:16]):
1364
+ context = context.replace(f"| {sender[:16]}]", f"| {name}]")
1048
1365
  used=self.counter.count(context)
1049
1366
  assert used<=budget
1050
1367
  if lines: