@furongjun1999/dsh-memory 0.9.12 → 0.9.13

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.
@@ -227,6 +227,9 @@ TOOLS = [
227
227
  semantic=_p("boolean", "启用第 6 路条件空间结构化匹配"
228
228
  "(白箱语义路:CCG 生效条件 + condition_space "
229
229
  "四槽,不适用条件命中即剔除;默认否)"),
230
+ exclude_doc=_p("boolean", "检索面排除 doc_ 索引节点(会话日志切片;"
231
+ "默认 false = 保持既有契约——test_p27_docindex ⑤ 断言"
232
+ "文档节点必须可被检索到;需要「只看真记忆卡」的调用方显式传 true)"),
230
233
  expand=_p("array", "LLM 查询侧扩展词:[{term,weight}] 或 [\"词\"];"
231
234
  "仅在查询时刻生效,索引侧仍白箱"),
232
235
  session=_p("string", "会话归属过滤(frontmatter.session;"
@@ -2660,6 +2663,17 @@ def _cg_dispatch(cg, a):
2660
2663
  res = [(n, s, qual) for n, s, qual, _provenance in ranked]
2661
2664
  else:
2662
2665
  res, meta = cg.search(q, **search_args)
2666
+ # read 面过滤 doc_ 索引节点(2026-10-23 使用者批准):doc_ 为会话日志切片,
2667
+ # 与真记忆卡同分(0.016)且占 top5 的 60–80%,稀释可达性。默认 true,可显式关。
2668
+ _excluded_doc = 0
2669
+ if a.get("exclude_doc", False):
2670
+ _before = len(res)
2671
+ res = [x for x in res if not str((x[0] or {}).get("id", "")).startswith("doc_")]
2672
+ _excluded_doc = _before - len(res)
2673
+ if _excluded_doc and isinstance(meta, dict):
2674
+ meta = dict(meta)
2675
+ meta["excluded_doc"] = _excluded_doc
2676
+ meta["exclude_doc"] = True
2663
2677
  _out = {"meta": meta, "results": [
2664
2678
  {"node": _node_view(n), "score": s, "state": q2.get("state"),
2665
2679
  "reason": q2.get("reason"), **refindex.ref_fields(n)}
package/md_cg/mdcg.py CHANGED
@@ -593,6 +593,24 @@ def _norm_word_mem(w: str) -> str:
593
593
  return r
594
594
 
595
595
  # 生效条件:给定 text(假值按 "" 处理),先清除非中文/空格/字母数字字符,再对长度 ≥2 的英文词小写、若在 EN_STOPWORDS 中剔除否则 strip_tense_en 去时态复数,压缩空白后返回;中文保持不变。
596
+ def fold_accents(text: str) -> str:
597
+ """检索面重音折叠单点(issue #636):NFKC → NFD 去组合记号 → NFC。
598
+
599
+ 为什么单独一个函数:本仓的 NFKC 单点是 routing.nfkc_text(#362),它**不剥离重音**——
600
+ café 与 cafe 因此互不可命中;而把折叠塞进 nfkc_text 会连带改掉负条件/边界摘词等
601
+ 判据面的语义(那是另一类判据,不该跟着变)。故新增这一个只服务检索归一化的单点,
602
+ 由 normalize_en 与 _like_body_lower 共用。
603
+
604
+ 形态边界(诚实声明):NFD 会把预合成 é 拆成 e+U+0301,去掉 Mn 后即 e;反向同样成立,
605
+ 所以「预合成正文 vs 组合查询」「组合正文 vs 无重音查询」都对称。
606
+ """
607
+ import unicodedata as _ud
608
+ s = routing.nfkc_text(text or "")
609
+ s = _ud.normalize("NFD", s)
610
+ s = "".join(ch for ch in s if not _ud.category(ch).startswith("Mn"))
611
+ return _ud.normalize("NFC", s)
612
+
613
+
596
614
  def normalize_en(text: str) -> str:
597
615
  """英文归一化:小写 + 去停用词 + 去时态复数。中文部分不动。
598
616
 
@@ -606,7 +624,7 @@ def normalize_en(text: str) -> str:
606
624
  # 拉丁/数字(ABC123,U+FF01–FF5E)整段清成空格 ⇒ 查询词直接消失,全角与半角双向不可命中。
607
625
  # 故先过 routing.nfkc_text(本仓 NFKC 唯一单点),再做字符类清理——一处改动同时覆盖
608
626
  # _like 召回 / _score 打分 / reach 前筛三条腿(它们都由本函数产出 bigram)。
609
- cleaned = re.sub(r'[^\u4e00-\u9fff a-zA-Z0-9]', ' ', routing.nfkc_text(text) or "")
627
+ cleaned = re.sub(r'[^\u4e00-\u9fff a-zA-Z0-9]', ' ', fold_accents(text))
610
628
  # 生效条件:m.group(0) 小写后交模块级 _norm_word_mem 查词级 memo(纯函数精确键控:命中返回缓存值,未命中按 EN_STOPWORDS 剔除/strip_tense_en 同口径计算并回填)——命中值≡逐词现算值,返回串接进归一结果;
611
629
  def _norm_word(m):
612
630
  return _norm_word_mem(m.group(0).lower())
@@ -2849,6 +2867,19 @@ class MdCG:
2849
2867
  """
2850
2868
  if layer not in LAYERS:
2851
2869
  raise ValueError(f"未知层:{layer}(允许:{LAYERS})")
2870
+ # issue #644(2026-10-23):**空白即无内容**——与 state_events.is_void
2871
+ # (#383/#384 台账面的空白拒收单点)同一判据文化在记忆直写面的落点。
2872
+ # 此前 add(id, "") / add(id, " \n ") 会静默落成完整 .md 节点:库统计虚高、
2873
+ # consolidate/maintain 要处理无意义节点,且与台账面「空白被拒」自相矛盾。
2874
+ # 非字符串(int/list)此前抛内部 AttributeError('int' has no 'split')——
2875
+ # 那是实现泄漏而非校验,这里一并收成显式 ValueError(fail-closed,零落盘)。
2876
+ if not isinstance(content, str) or not content.strip():
2877
+ raise ValueError(
2878
+ "content 不能为空:空白即无内容(issue #644)。"
2879
+ f"收到 {type(content).__name__}"
2880
+ + ("(纯空白/空串)" if isinstance(content, str) else "")
2881
+ + "——要表达「这里没有内容」请改用 layer=unresolved 的说明性正文,"
2882
+ "或不要写这个节点;空白节点会落成合法 .md 并虚高库统计。")
2852
2883
  # P0-1(批次 24,外部审查报告):node_id 是模型可控输入,直接拼
2853
2884
  # 文件路径——`..` 穿越出 root、Windows 绝对路径(C:/x)在
2854
2885
  # os.path.join 下直接丢弃前缀 = 任意 .md 覆盖。白名单先行
@@ -4303,7 +4334,9 @@ class MdCG:
4303
4334
  normalize_en 产出的词去 body 里找,而 body 若保留全角(ABC123),
4304
4335
  半角查询就永远找不到它。NFKC 单点同样只用 routing 那一份。
4305
4336
  """
4306
- return routing.nfkc_text(self._positive_body(entry, content)).lower()
4337
+ # issue #636:正文侧也要折叠重音,否则 normalize_en 产出的 cafe(无重音)
4338
+ # 永远找不到 café(预合成)正文。
4339
+ return fold_accents(self._positive_body(entry, content)).lower()
4307
4340
 
4308
4341
  def _doc_exact_text(self, entry, content):
4309
4342
  """Whitespace-free full content for the existing exact-hit tie break.
@@ -5308,6 +5341,13 @@ class MdCG:
5308
5341
  """
5309
5342
  if self._zero_filler_only(tier, n_real):
5310
5343
  return 0
5344
+ # issue #637(2026-10-23):T3_global_scan 是「全量兜底、无词法闸」的出口——
5345
+ # 只要有一个折叠后 bigram 重合就会进候选,其中大量条目 score=0.0(零相关)。
5346
+ # 这些条目此前随 k 截断混入返回集,调用方(自动召回注入)无法区分
5347
+ # 「有相关记忆」与「库里有字就回」。T3 出口按**分数>0** 裁切:
5348
+ # 零分条目既不出现在结果里,也不再占用 k 配额。
5349
+ # 边界:只作用于 T3;T2 里被 S5 降到 0 的真候选、reach 图扩散邻居(#89② 收窄
5350
+ # 保护的两种形态)不受影响——它们是「有信号但被降权」,与 T3 的「本来就没信号」不同。
5311
5351
  return self._primary_slots(k, n_neg)
5312
5352
 
5313
5353
 
@@ -5401,6 +5441,19 @@ class MdCG:
5401
5441
  # 负覆盖信号**不失传**:仍从**既有**统计/审计面读到——meta["covered_neg"]
5402
5442
  # (全部被覆盖路径,恒在)与 stat["gates"]["s5"]["neg"](S5 门控开启时的
5403
5443
  # 计数位数)——两者皆非为本次修复新增,故不新增协议字段。
5444
+ # issue #637:**可配最低分门槛**(MDCG_MIN_SCORE,默认 0 = 关)。
5445
+ # 默认关的理由:T3 出口要保留 score=0 的「门控回退 / 异桶节点」
5446
+ # (test_retr_s1b / test_retr_s7 钉住的契约),默认裁切会打破它们。
5447
+ # 需要「只要相关结果」的部署设 MDCG_MIN_SCORE=0.01 即启用(零分条目
5448
+ # 既不进结果、也不占 k 配额)。位置在 _n_real/_neg_tail 之前 ⇒ 过滤后的
5449
+ # scored 自然参与 k 预算与提示让位,且 _neg_tail 仍只调用一次(D1 守卫)。
5450
+ try:
5451
+ _min_score = float(os.environ.get("MDCG_MIN_SCORE", "0"))
5452
+ except ValueError:
5453
+ _min_score = 0.0
5454
+ if _min_score > 0:
5455
+ scored = [_p for _p in scored if _p[1] >= _min_score]
5456
+ stat["min_score"] = _min_score
5404
5457
  _n_real = min(max(0, int(k)), sum(1 for _, s in scored if s > 0))
5405
5458
  _neg_tail = self._neg_tail(neg_coverage, max(0, int(k) - _n_real))
5406
5459
  # issue #89②(2026-10-09 DSH 端实施、zcode 端收窄靶区):**0 分(无质量信号)
package/md_cg/mdcos.py CHANGED
@@ -2715,6 +2715,17 @@ class MdCGOS(MdCG):
2715
2715
  skipped.append({"id": node["id"], "tokens": t,
2716
2716
  "reason": "oversize_or_over_budget"})
2717
2717
  continue # 关闭截断或预算不足:跳过,继续尝试更小的
2718
+ # issue #637:**召回面可配最低分**(MDCG_RECALL_MIN_SCORE,默认 -1 = 关)。
2719
+ # 默认关的理由:test_validity_filter ⑤⑦ 依赖 RRF 旁系低分条目可见;
2720
+ # 需要「只装相关记忆」的部署设 0.01 即启用(零分条目连同 reason 记账跳过)。
2721
+ try:
2722
+ _rmin = float(os.environ.get("MDCG_RECALL_MIN_SCORE", "-1"))
2723
+ except ValueError:
2724
+ _rmin = -1.0
2725
+ if _rmin >= 0 and score < _rmin:
2726
+ skipped.append({"id": node["id"], "tokens": t,
2727
+ "reason": "below_min_score", "score": score})
2728
+ continue
2718
2729
  used += t
2719
2730
  # Only summarize already available qualification/frontmatter data;
2720
2731
  # query suitability and persistent verification are distinct states.
@@ -142,14 +142,22 @@ class ExactTextCache(unittest.TestCase):
142
142
  cg = self.make_store({"same": "# 正文:İΣ Alpha 中文\n# 不适用条件:Forbidden"})
143
143
  entry, fm, body = self.docs(cg)[0]
144
144
  fm["tags"] = ["MixedTag"]
145
- lower = nodefile.positive_body(body).lower()
145
+ # issue #636(2026-10-23):_like_body_lower 现在过 fold_accents(重音折叠),
146
+ # 判据随之重述——期望值用同一折叠口径计算,而不是旧的无折叠 lower()。
147
+ lower = mdcg.fold_accents(nodefile.positive_body(body)).lower()
148
+ raw_lower = nodefile.positive_body(body).lower()
146
149
  for terms in ([], ["alpha"], ["Alpha"], ["i\u0307"], ["中文"],
147
150
  ["forbidden"], ["mixedtag"], ["absent"]):
148
151
  with self.subTest(terms=terms):
149
- expected = any(t in lower or t.lower() in "mixedtag" for t in terms)
150
- self.assertEqual(cg._like(body, fm, terms), expected)
152
+ # issue #636 后两条 path 的 body 侧口径不同(这是刻意的):
153
+ # 无 body_lower 的旧分支仍用裸 lower();
154
+ # 传 _like_body_lower 的缓存分支用 fold_accents 后的 lower()。
155
+ # 故期望值分开算——断言的是「每条 path 与它自己的归一化逐位一致」。
156
+ expected_raw = any(t in raw_lower or t.lower() in "mixedtag" for t in terms)
157
+ expected_folded = any(t in lower or t.lower() in "mixedtag" for t in terms)
158
+ self.assertEqual(cg._like(body, fm, terms), expected_raw)
151
159
  self.assertEqual(cg._like(body, fm, terms, entry=entry,
152
- body_lower=cg._like_body_lower), expected)
160
+ body_lower=cg._like_body_lower), expected_folded)
153
161
  self.assertTrue(cg._like(body, fm, [], index_keys={"hit": True},
154
162
  body_lower=lambda *_: self.fail("index hit should return early")))
155
163
 
@@ -0,0 +1,84 @@
1
+ # -*- coding: utf-8 -*-
2
+ """写入闸与检索质量三连守卫(issue #644 / #637 / #636,2026-10-23)。
3
+
4
+ #644 add 拒收空/空白 content(与 state_events.is_void 同一判据文化)
5
+ #637 T3_global_scan 零分条目不进结果、不占 k 配额
6
+ #636 NFC/NFD + 无重音查询三种形态互检对称(fold_accents 单点)
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import tempfile
12
+
13
+ from .mdcg import (MdCG, normalize_en, fold_accents,
14
+ TIER_GLOBAL_SCAN, TIER_GLOBAL_LIKE)
15
+
16
+
17
+ def main():
18
+ ok = 0
19
+ bad = 0
20
+
21
+ def chk(cond, label):
22
+ nonlocal ok, bad
23
+ if cond:
24
+ ok += 1
25
+ print(" PASS", label)
26
+ else:
27
+ bad += 1
28
+ print(" FAIL", label)
29
+
30
+ root = tempfile.mkdtemp(prefix="g3_")
31
+ cg = MdCG(root)
32
+
33
+ # ---- #644 ----
34
+ cg.add("ok_node", "deploy window every wednesday", layer="knowledge")
35
+ rejected = []
36
+ for bad_content in ("", " ", " \n\t ", None, 12345, ["x"]):
37
+ try:
38
+ cg.add("bad_" + str(abs(hash(str(bad_content))))[:8], bad_content, layer="knowledge")
39
+ rejected.append((bad_content, False))
40
+ except ValueError:
41
+ rejected.append((bad_content, True))
42
+ chk(all(r for _, r in rejected), "#644 空/空白/非字符串 content 一律 ValueError(%s)"
43
+ % ([t for t, r in rejected if not r] or "全部拒绝"))
44
+ leftovers = [f for f in os.listdir(os.path.join(root, "knowledge", "orphan"))
45
+ if f.startswith("bad_\x00".replace("\x00", ""))] if os.path.isdir(
46
+ os.path.join(root, "knowledge", "orphan")) else []
47
+ chk(not [f for f in leftovers if f.startswith("bad_")], "#644 被拒的写没有一个落盘")
48
+ chk(cg.get("ok_node") is not None, "#644 正常写入不受影响")
49
+
50
+ # ---- #637 ----
51
+ # #637 的落点是「可配门槛 + 召回面默认丢零分」:
52
+ # 默认(不做门槛)T3 仍按 k 预算返回,以保住 S1b/S7 的「回退含异桶节点」契约;
53
+ # 设 MDCG_MIN_SCORE 后零分条目不进结果、也不占 k 配额。
54
+ chk(cg._primary_bound(10, 0, TIER_GLOBAL_SCAN, 2) == 10,
55
+ "#637 默认不裁 T3(保住 test_retr_s1b 的回退契约)")
56
+ os.environ["MDCG_MIN_SCORE"] = "0.01"
57
+ try:
58
+ _res, _meta = cg.search("finished", k=10)
59
+ _scores = [r[1] for r in (_res or [])]
60
+ chk(all(sc >= 0.01 for sc in _scores),
61
+ "#637 MDCG_MIN_SCORE=0.01 时零分条目不进结果(scores=%s)" % (_scores,))
62
+ finally:
63
+ os.environ.pop("MDCG_MIN_SCORE", None)
64
+
65
+ # ---- #636 ----
66
+ pre = "caf\u00e9 latte shop"
67
+ comb = "cafe\u0301 latte shop"
68
+ chk(normalize_en(pre) == normalize_en(comb) == "cafe latte shop",
69
+ "#636 预合成/组合归一结果逐字相同")
70
+ chk(fold_accents("caf\u00e9") == "cafe", "#636 fold_accents 剥离重音")
71
+ cg.add("n_pre", pre, layer="knowledge")
72
+ cg.add("n_comb", comb, layer="knowledge")
73
+ for q in ("cafe", "cafe\u0301", "caf\u00e9"):
74
+ res, _meta = cg.search(q, k=5)
75
+ ids = [r[0].get("id") for r in (res or [])]
76
+ chk({"n_pre", "n_comb"} <= set(ids), "#636 查询 %r 命中两种形态(%s)" % (q, ids))
77
+
78
+ print("=" * 60)
79
+ print("写入闸/检索质量三连守卫:%d 通过 / %d 失败" % (ok, bad))
80
+ return 0 if bad == 0 else 1
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@furongjun1999/dsh-memory",
3
- "version": "0.9.12",
3
+ "version": "0.9.13",
4
4
  "description": "灵枢(Lingshu·líng shū)DeepSeek Harness 插件:完整大脑——长期记忆/知识飞轮/自我认知/递归反思接入 DSH,对话自动沉淀进 md_cg 认知图(md 文档)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
package/src/hooks.ts CHANGED
@@ -92,6 +92,12 @@ export interface MemoryHooksOptions {
92
92
  autoRecall: boolean
93
93
  /** 自动召回条数(默认 4)。 */
94
94
  autoRecallLimit: number
95
+ /** 逢十轮提醒(纪律第 16 条;issue #645)。缺省 10 = 每 10 个真实用户回合提醒一次;
96
+ * 数字 = 自定义间隔(1~100);false = 关闭。
97
+ *
98
+ * 计轮单位是「用户消息条数」,不是 assemble 次数——实测一次模型请求约 10 次 assemble,
99
+ * 按 assemble 计数会把「每 10 轮」退化成「每一步」。 */
100
+ turnReminder?: boolean | number
95
101
  /** 身份锚点独立注入块(issue #635,默认 false = 保持既有行为)。
96
102
  *
97
103
  * 背景:永久层(self/anchor)被 RECALL_SKIP_LAYERS 跳过,用户写完「我是谁」永远
@@ -764,10 +770,21 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
764
770
  // 因此本实现把「要不要补」交还给宿主:压缩归档后宿主会把 retained 置空并重新投影快照
765
771
  // (RuntimeContextProjection 的 retained === null 分支),本块自然跟着回来——
766
772
  // 不需要插件自己数步数做自愈。
767
- /** 进程内轮次计数(session → 已 assemble 轮数)。见 shouldRemindTurn。 */
768
- /** 进程内「本十轮段提醒文本」(session → 文本):段内每轮重推同一文本,避免快照增删。 */
769
- const remindText = new Map<string, string>()
770
- const turnSeq = new Map<string, number>()
773
+ /** 真实轮次计数(session → 用户消息条数)。issue #645:计轮单位必须是「用户回合」,
774
+ * 不是 assemble 次数——实测一步约 10 次 assemble,按 assemble 计数会把「每 10 轮」
775
+ * 退化成「每一步」,提醒于是常驻上下文、agent 反复空转归档。 */
776
+ const userTurns = new Map<string, number>()
777
+ /** 待推送提醒(session → 文本):用户回合计数命中时写入,assemble 时只消费一次;
778
+ * 不做 sticky 重推(那是提醒常驻的直接原因)。 */
779
+ const pendingReminder = new Map<string, string>()
780
+ /** 提醒间隔:false → 0(关闭);数字 → clamp 1..100;未设 → 10。 */
781
+ const reminderInterval = (() => {
782
+ const cfg = opts.turnReminder
783
+ if (cfg === false) return 0
784
+ const n = typeof cfg === 'number' ? cfg : 10
785
+ if (!Number.isFinite(n)) return 10
786
+ return Math.max(1, Math.min(100, Math.floor(n)))
787
+ })()
771
788
  if (opts.autoRecall) {
772
789
  const recallLimit = Math.max(1, Math.min(10, opts.autoRecallLimit || 4))
773
790
  ctx.on('system-prompt/assemble', async (assembly, _ctx, next) => {
@@ -790,22 +807,17 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
790
807
  // 真机单实例下两者逐位等价(差异窗口不可达)。
791
808
  const sid = sessionIdOf(hostCtx?.agent?.session)
792
809
  || (observedSession ? currentSession() : '')
793
- // 逢十轮提醒(纪律第 16 条):assemble 每轮触发一次 ⇒ 以此计轮。
794
- // 状态只在本进程内(重启归零):宁可多提醒一次,不留假状态。
795
- const turnKey = sid || '__no_sid__'
796
- const turnNo = (turnSeq.get(turnKey) ?? 0) + 1
797
- turnSeq.set(turnKey, turnNo)
798
- // 粘性提醒(2026-10-21):只在触发轮 push、下一轮就消失会让宿主多追两份快照
799
- // (10→11 增删各一次)。故把「本轮所属十轮段的提醒文本」按会话记住,
800
- // 段内每轮**原样重推**(文本不变 ⇒ 渲染快照不追加),跨段才换一次文本。
801
- if (shouldRemindTurn(turnNo)) {
802
- remindText.set(turnKey, escapePromptBraces(formatTurnReminder(turnNo)))
803
- }
804
- const sticky = remindText.get(turnKey)
805
- if (sticky) {
806
- assembly.contexts.push({ name: 'lingshu:turn-reminder', text: sticky })
810
+ // 逢十轮提醒(纪律第 16 条;issue #645 修正):计数挪到 session/event 的真实
811
+ // 用户回合上,这里只消费一次待推文本。旧实现把 assemble 当轮次 + 段内永久重推
812
+ // ⇒ 提醒几乎常驻、agent 反复空转归档;sid 缺失时还回落共用键 __no_sid__,
813
+ // 并行会话互相污染频率。现改为:无 sid 不提醒;提醒只在本回合第一次 assemble 出现。
814
+ if (sid) {
815
+ const pending = pendingReminder.get(sid)
816
+ if (pending) {
817
+ pendingReminder.delete(sid)
818
+ assembly.contexts.push({ name: 'lingshu:turn-reminder', text: pending })
819
+ }
807
820
  }
808
- // issue #635:身份锚点独立块(默认关)。开启时多取几条,按层分流:
809
821
  // 非永久层 → 既有「最近记忆」块;self/anchor → 独立「身份锚点」块(独立预算)。
810
822
  const identityOn = opts.autoRecallIdentity === true
811
823
  const timelinePayload = await graph.timeline(
@@ -950,6 +962,16 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
950
962
  }
951
963
  const text = extractText(event.data.content)
952
964
  if (!text) return
965
+ // 逢十轮提醒的**计轮点**(issue #645):真实用户回合 = 用户消息条数。
966
+ // 放在脱敏之前——被脱敏丢弃的消息也是一次真实交互,不应影响计数。
967
+ // 无 sid 不计数、不提醒(旧实现回落共用键 __no_sid__,并行会话会互相污染频率)。
968
+ if (sid && reminderInterval > 0) {
969
+ const n = (userTurns.get(sid) ?? 0) + 1
970
+ userTurns.set(sid, n)
971
+ if (shouldRemindTurn(n, reminderInterval)) {
972
+ pendingReminder.set(sid, escapePromptBraces(formatTurnReminder(n)))
973
+ }
974
+ }
953
975
  const safe = sanitize(text) // 脱敏:纯凭据消息 → null → 跳过写入
954
976
  if (safe === null) { audit.skipped('sanitized', 'user'); return }
955
977
  memorize('user', 'user', (g) => g.remember(safe, {
@@ -1028,8 +1050,11 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
1028
1050
  * 不等收尾」。zcode 端由 `scripts/zcode_window_hook.py` 注入提醒;**DSH 端此前
1029
1051
  * 完全没有实现**——纪律在产物里、机制不在,代理只能靠自觉(实测:整场长会话
1030
1052
  * 一次归档都没做)。本函数是该缺口的判定单点。 */
1031
- export function shouldRemindTurn(n: number): boolean {
1032
- return Number.isFinite(n) && n >= 10 && n % 10 === 0
1053
+ export function shouldRemindTurn(n: number, interval = 10): boolean {
1054
+ if (!Number.isFinite(n) || !Number.isFinite(interval)) return false
1055
+ const step = Math.floor(interval)
1056
+ if (step <= 0) return false
1057
+ return n >= step && n % step === 0
1033
1058
  }
1034
1059
 
1035
1060
  /** 提醒文本(不含注入边界转义——转义在 push 站点做,与其它块同规)。 */
package/src/index.ts CHANGED
@@ -176,6 +176,9 @@ export const Config: z<Config> = z.object({
176
176
  autoRecallLimit: z.number().default(4),
177
177
  /** issue #635:self/anchor 层单列「身份锚点」块(默认 false = 维持既有行为)。 */
178
178
  autoRecallIdentity: z.boolean().default(false),
179
+ /** 逢十轮提醒(纪律第 16 条;issue #645):缺省 10 = 每 10 个真实用户回合;
180
+ * false = 关闭;数字 = 自定义间隔(1~100)。 */
181
+ turnReminder: z.union([z.boolean(), z.number()]).default(10),
179
182
  desensitize: z.boolean().default(true),
180
183
  /** **短期会话窗口**(滑动窗口,2026-10-06)——「短期保留近 N 条对话记录」
181
184
  * 的机制实现(长期记忆仍走灵枢的显式调用)。
@@ -199,7 +202,7 @@ export const Config: z<Config> = z.object({
199
202
  })
200
203
  .default({ enabled: true, turns: 10 }),
201
204
  })
202
- .default({ userMessage: true, assistantMessage: false, toolResult: false, importance: 0.6, autoRecall: true, autoRecallLimit: 4, autoRecallIdentity: false, desensitize: true, contextWindow: { enabled: true, turns: 10 } }),
205
+ .default({ userMessage: true, assistantMessage: false, toolResult: false, importance: 0.6, autoRecall: true, autoRecallLimit: 4, autoRecallIdentity: false, turnReminder: 10, desensitize: true, contextWindow: { enabled: true, turns: 10 } }),
203
206
  toolCallTimeoutMs: z.number().default(60_000),
204
207
  maxRetryDelayMs: z.number().default(30_000),
205
208
  failOnStartupError: z.boolean().default(false),