@furongjun1999/dsh-memory 0.9.17 → 0.9.21

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 (30) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/README.md +3 -2
  3. package/docs/mdcg/CCG/345/205/255/350/246/201/347/264/240/347/274/226/350/257/221.md +30 -0
  4. package/docs/mdcg/MCP/345/267/245/345/205/267/345/220/215/345/217/243/345/276/204_v1.0.md +41 -0
  5. package/docs/mdcg/cogmap_ops.md +36 -0
  6. package/docs/mdcg/guardrail-charter.md +168 -0
  7. package/docs/mdcg/recall_metadata.md +41 -0
  8. package/docs/mdcg//344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_/344/275/277/347/224/250/344/270/216/350/277/220/347/273/264_v1.0.md +384 -0
  9. package/docs/mdcg//345/206/231/345/205/245/345/210/253/345/220/215aliases/350/247/204/350/214/203_v0.6.md +128 -0
  10. package/lib/hooks.d.ts +9 -1
  11. package/lib/hooks.js +78 -19
  12. package/md_cg/mdcg.py +33 -2
  13. package/md_cg/mdcos.py +80 -6
  14. package/md_cg/repeat_guard.py +122 -0
  15. package/md_cg/security.py +9 -2
  16. package/md_cg/test_722_aliases_thin.py +85 -0
  17. package/md_cg/test_722_condition_quality.py +83 -0
  18. package/md_cg/test_723_permission_wildcard.py +80 -0
  19. package/md_cg/test_aliases_r2r3.py +92 -0
  20. package/md_cg/test_issue712_session_window_attribution.py +225 -0
  21. package/md_cg/test_logref.py +4 -4
  22. package/md_cg/test_mode_parity.py +11 -0
  23. package/md_cg/test_p27_docindex.py +12 -7
  24. package/md_cg/test_p45_session_identity.py +6 -4
  25. package/md_cg/test_repeat_guard_charter15.py +89 -0
  26. package/md_cg/writegate.py +101 -1
  27. package/package.json +9 -2
  28. package/src/hooks.ts +84 -7
  29. package/ui/minimal/payload/web/app.js +1 -1
  30. package/web/app.js +1 -1
@@ -0,0 +1,89 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:宪章第十五条(复读污染)守卫——注入过滤 / history 去重 / 污染清除
3
+ # 生效条件:python -X utf8 -m md_cg.test_repeat_guard_charter15;被测面=md_cg/repeat_guard.py 的 scan/annotate/dedupe
4
+ # 子功能:①长文本重复被判、短指令重复不判(minChars 保护非空转)②minCount 分界 ③dedupe 只留最新一条且幂等 ④annotate/dedupe 不改入参 dict(只改副本)⑤脏数据容错 ⑥text_suffix 确定性
5
+ # 执行:纯函数级断言,不依赖真实库与磁盘
6
+ # 验证方式:全部 PASS exit 0;每条都写明「怎么让它红」
7
+ # 不适用条件:不判模型侧是否真的复读(本模块只判事件窗口内的重复);不判注入面渲染(接入在 session_recall,另批)
8
+ """宪章第十五条此前**只有条文没有实现**(`src/` 与 `md_cg/` 搜「复读/degenerat」零命中)。
9
+
10
+ 本守卫盯的是实现里的三个易错点:
11
+ ① `minChars` 保护是否空转(短指令「好」「继续」重复属正常对话,不该判污染);
12
+ ② `dedupe` 是否真的「只留最新一条」且**幂等**;
13
+ ③ `annotate`/`dedupe` 是否**不改入参**(库内正文保真,只改注入副本)。
14
+ """
15
+ import os
16
+ import sys
17
+
18
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ sys.path.insert(0, ROOT)
20
+
21
+ from md_cg import repeat_guard as rg # noqa: E402
22
+
23
+ _PASS, _FAIL = [], []
24
+
25
+
26
+ def ok(cond, msg, detail=""):
27
+ (_PASS if cond else _FAIL).append(msg)
28
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
29
+
30
+
31
+ def main():
32
+ LONG = "这是一条足够长的测试消息内容,用于验证重复检测"
33
+ print("== A minChars 保护(防短指令误判)")
34
+ short_evs = [{"role": "user", "text": "好", "t": i} for i in range(5)]
35
+ ok(len(rg.scan(short_evs, min_count=3, min_chars=0)) == 1,
36
+ "A1 minChars=0 时「好」×5 **会**被判(证明该参数真的在起作用)",
37
+ rg.scan(short_evs, min_count=3, min_chars=0))
38
+ ok(len(rg.scan(short_evs, min_count=3, min_chars=12)) == 0,
39
+ "A2 minChars=12 时「好」×5 **不**被判(正确:短指令重复属正常对话)",
40
+ rg.scan(short_evs, min_count=3, min_chars=12))
41
+
42
+ print("== B minCount 分界")
43
+ evs = [{"role": "assistant", "text": LONG, "t": i} for i in range(4)]
44
+ ok(len(rg.scan(evs, min_count=3)) == 1, "B1 ×4 且 minCount=3 → 命中")
45
+ ok(len(rg.scan(evs, min_count=5)) == 0,
46
+ "B2 ×4 且 minCount=5 → **不**命中(阈值真的生效,非恒真)")
47
+
48
+ print("== C dedupe:只留最新一条 + 幂等")
49
+ seq = [{"role": "assistant", "text": LONG, "t": i, "tag": "v%d" % i} for i in range(5)]
50
+ out = rg.dedupe(seq, min_count=3)
51
+ ok(len(out) == 1, "C1 5 条重复折叠成 1 条", len(out))
52
+ ok(out[0].get("tag") == "v4",
53
+ "C2 **保留的是最新一条**(v4,不是 v0)——去重方向不能搞反", out[0].get("tag"))
54
+ ok((out[0].get("repeat") or {}).get("count") == 5,
55
+ "C3 折叠后的条目带 repeat.count=5(信息不丢)", out[0].get("repeat"))
56
+ ok(len(rg.dedupe(out, min_count=3)) == 1,
57
+ "C4 幂等:对已折叠结果再跑一次,条数不变")
58
+
59
+ print("== D 不改入参(库内正文保真)")
60
+ lst = [{"role": "assistant", "text": LONG, "t": i} for i in range(4)]
61
+ ann = rg.annotate(lst, min_count=3)
62
+ ok(all("repeat" not in r for r in lst),
63
+ "D1 annotate **不改入参 dict**(只改返回副本)", [r for r in lst if "repeat" in r][:1])
64
+ ok(any("repeat" in r for r in ann), "D2 返回的副本带 repeat 标注")
65
+ ok(len(ann) == len(lst), "D3 annotate 不改变条数(只标不折)")
66
+
67
+ print("== E 容错")
68
+ dirty = [None, 1, "x", {"text": None}, {"role": None, "text": LONG}]
69
+ try:
70
+ h = rg.scan(dirty, min_count=1)
71
+ ok(True, "E1 脏数据(None/数字/字符串/text=None)不抛异常", len(h))
72
+ except Exception as e: # noqa: BLE001
73
+ ok(False, "E1 脏数据不抛异常", "%s: %s" % (type(e).__name__, e))
74
+
75
+ print("== F text_suffix 确定性")
76
+ ok(rg.text_suffix(LONG) == rg.text_suffix(LONG), "F1 同一 text 恒得同一串(可用作判据)")
77
+ ok(rg.text_suffix(LONG) != rg.text_suffix(LONG + "x"), "F2 不同 text 得不同串")
78
+ ok(len(rg.text_suffix("")) == 8, "F3 空串也返回 8 位(不抛)")
79
+
80
+ print()
81
+ print("宪章第十五条守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
82
+ if _FAIL:
83
+ for f in _FAIL:
84
+ print(" -", f)
85
+ return 0 if not _FAIL else 1
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
@@ -180,4 +180,104 @@ def decide_write(layer, reviewers=None, channels=None, mode=None, environ=None):
180
180
  if gap:
181
181
  return {"decision": "require_review", "tier": tier, "mode": m, "missing": gap,
182
182
  "reason": "该层需 " + "/".join(need) + " 复核,仍缺 " + "/".join(gap)}
183
- return {"decision": "allow", "tier": tier, "mode": m, "missing": [], "reason": "复核齐备"}
183
+ return {"decision": "allow", "tier": tier, "mode": m, "missing": [], "reason": "复核齐备"}
184
+
185
+ # ── issue #722 / 规范 v0.5:生效条件是否在描述「元数据」而非「什么时候该用」──
186
+ #
187
+ # ⚠️ 判据演进(2026-10-31,四次实测修正留痕,勿重蹈):
188
+ # ① 正向「所有词项都含元数据特征」→ 失败:含「源文档 a/b/c.md」时被 / 切成路径片段,all() 恒 False,
189
+ # 120 抽样元数据判出 0 条。
190
+ # ② 反向「不含任何场景标志词」→ 失败:单字标志词「时」被「全时窗」误触发。
191
+ # ⇒ **放弃自然语言启发式**,改用**结构化判据**:看槽标签。
192
+ #
193
+ # 结构化判据的依据:CCG「生效条件」若由 `condition_space` 四槽合成,必然带槽标签;
194
+ # 实测 14/20 的条件形如「载体/位置:…;时间:…;方法:…;约束:…」。
195
+ # 真正的"触发场景"(如 #722 报告人改写的「当他说"不想你被换掉"时」)**不会**带这些标签。
196
+ _SLOT_LABELS = ("载体/位置:", "载体/位置:", "载体=", "时间:", "时间:", "方法:", "方法:", "约束:", "约束:")
197
+
198
+
199
+ # 生效条件:cond_text 为假值时返回 False(无条件是另一类问题,不由本函数判);
200
+ # 否则:若同时含**载体/位置**类槽标签与**约束/方法**类槽标签 ⇒ 判为元数据(四槽合成形态)。
201
+ # 只用于写入把关,**不参与判定**——实测证明"跳元数据词项"不能改善判定。
202
+ def cond_is_metadata(cond_text) -> bool:
203
+ """生效条件是否在描述「元数据」(载体/路径/方法/约束),而非「什么时候该用」。
204
+
205
+ 实测背景(2026-10-31,全库 32842 抽样):约 14/20 的条件是四槽合成形态
206
+ `载体/位置:本地文档仓(大域=xxx);时间:全时窗;方法:md…;约束:源文档 a/b.md`,
207
+ **0 条**是「用户会怎么说」。
208
+
209
+ 判据(结构化,非词义猜测):**同时**出现 `载体/位置` 类标签与 `约束`/`方法` 类标签。
210
+ 这样「当他说"不想你被换掉"时」这类真场景条件不会被误判(它没有槽标签)。
211
+ """
212
+ text = str(cond_text or "")
213
+ if not text.strip():
214
+ return False
215
+ has_carrier = ("载体/位置:" in text or "载体/位置:" in text or "载体=" in text)
216
+ has_other = any(k in text for k in ("时间:", "时间:", "方法:", "方法:", "约束:", "约束:"))
217
+ return bool(has_carrier and has_other)
218
+
219
+
220
+ # ── issue #722 / 规范 v0.5 第四节:写入把关(warn 优先,不阻断)─────────
221
+ # 生效条件:content 为节点正文(str 或 None)时,取「# 生效条件」行判其是否为元数据;
222
+ # 无该行时返回 ok=True(无条件是另一类问题,见规范 v0.5「不适用条件 1」)。
223
+ # **不抛异常**:任何内部错误都返回 ok=True + error 字段(写入把关绝不阻断写入)。
224
+ def check_condition_quality(content) -> dict:
225
+ """检查节点的「生效条件」是否为元数据(载体/路径/方法),而非触发场景。
226
+
227
+ 返回 {"ok": bool, "is_metadata": bool, "cond": str, "hint": str}。
228
+ `ok=False` 仅表示"条件质量可疑",**不表示写入应被拒绝**——
229
+ 按 v0.5 第四节,默认档是 `warn`(计数 + 提示),不是 enforce。
230
+ """
231
+ try:
232
+ text = str(content or "")
233
+ cond = ""
234
+ for line in text.splitlines():
235
+ s = line.strip()
236
+ if s.startswith("#") and "生效条件" in s:
237
+ if ":" in s:
238
+ cond = s.split(":", 1)[1].strip()
239
+ elif ":" in s:
240
+ cond = s.split(":", 1)[1].strip()
241
+ break
242
+ if not cond:
243
+ return {"ok": True, "is_metadata": False, "cond": "", "hint": "无生效条件行"}
244
+ meta = cond_is_metadata(cond)
245
+ return {"ok": not meta, "is_metadata": meta, "cond": cond,
246
+ "hint": ("生效条件在描述载体/路径/方法(元数据),不是在描述"
247
+ "「什么时候该用」——检索时它几乎不可能被自然问法命中"
248
+ "(实测库内 76.5% 节点如此)") if meta else ""}
249
+ except Exception as exc: # noqa: BLE001 —— 把关绝不阻断
250
+ return {"ok": True, "is_metadata": False, "cond": "",
251
+ "hint": "检查失败(不影响写入):%s: %s" % (type(exc).__name__, exc)}
252
+
253
+
254
+ # ── 规范 v0.6 第 2.3 节:别名是否"薄"(写入把关用)───────────────────
255
+ # 生效条件:fm 为节点 frontmatter(dict 或 None)、content 为正文(str 或 None)时——
256
+ # 无 aliases(缺失/非 list/空 list)⇒ True;否则若**每个**别名都能在 content 里原样
257
+ # 找到 ⇒ True(只重复已有词、没扩召回首);只要有一个别名在正文里找不到 ⇒ False(有扩展)。
258
+ # **不判数量**——3 个精准别名可能胜过 10 个噪声别名。不抛异常。
259
+ def aliases_is_thin(fm, content) -> bool:
260
+ """别名是否"薄"(无别名,或只重复正文里已有的词)。
261
+
262
+ 实测依据(2026-10-31):issue #722 的条件 `聊交接、换会话、压缩…`
263
+ 与查询 `我不想你被换掉` —— 整词 / 二元组 / 查询扩展 / 现有同义词表**四条路全废**,
264
+ 只有 `aliases=[换掉, 被换, 别消失, 舍不得, …]` 能让 `_like` 从不命中变为命中。
265
+ 而库内 aliases 覆盖率为 **0/120 = 0%** ⇒ 这是最大的一次性改进空间。
266
+ """
267
+ try:
268
+ f = fm if isinstance(fm, dict) else {}
269
+ al = f.get("aliases")
270
+ if not isinstance(al, list) or not al:
271
+ return True
272
+ body = str(content or "")
273
+ if not body:
274
+ return False # 无正文可判,保守认为有扩展
275
+ for a in al:
276
+ s = str(a or "").strip()
277
+ if not s:
278
+ continue
279
+ if s not in body:
280
+ return False # 找到扩召回词
281
+ return True # 全部重复正文已有词 ⇒ 薄
282
+ except Exception: # noqa: BLE001 —— 把关绝不抛
283
+ return True
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@furongjun1999/dsh-memory",
3
- "version": "0.9.17",
3
+ "version": "0.9.21",
4
4
  "description": "灵枢(Lingshu·líng shū)DeepSeek Harness 插件:完整大脑——长期记忆/知识飞轮/自我认知/递归反思接入 DSH,对话自动沉淀进 md_cg 认知图(md 文档)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -37,7 +37,14 @@
37
37
  "docs/工作纪律_认知图条目_v1.1.json",
38
38
  "scripts/workspace_index.py",
39
39
  "ui",
40
- "web"
40
+ "web",
41
+ "docs/mdcg/写入别名aliases规范_v0.6.md",
42
+ "docs/mdcg/CCG六要素编译.md",
43
+ "docs/mdcg/guardrail-charter.md",
44
+ "docs/mdcg/MCP工具名口径_v1.0.md",
45
+ "docs/mdcg/recall_metadata.md",
46
+ "docs/mdcg/世界模型功能端_使用与运维_v1.0.md",
47
+ "docs/mdcg/cogmap_ops.md"
41
48
  ],
42
49
  "keywords": [
43
50
  "deepseek",
package/src/hooks.ts CHANGED
@@ -493,8 +493,12 @@ export function renderIdentityAnchors(payload: unknown): string {
493
493
  const WINDOW_BUDGET_TOKENS = 600
494
494
  /** 单条窗口条目预览上限(字符)。 */
495
495
  const WINDOW_ITEM_CHARS = 120
496
- /** 窗口块总长上限(字符)。 */
497
- const WINDOW_MAX_CHARS = 800
496
+ /** 窗口块总长上限(字符)。
497
+ *
498
+ * issue #712(2026-10-30):归因前缀(`[MM-DD HH:mm|会话|密级] `,约 20 字符/行)
499
+ * 会占预算,故由 800 上调到 **900**(10 行 × 20 = 200,实测内容量持平)。
500
+ * 该块定位仍是「存在性锚点 / 接续提示」——宁可少注入几条,不挤占宿主上下文。 */
501
+ const WINDOW_MAX_CHARS = 900
498
502
  /** 单条窗口条目的 role 字段上限(字符,issue #354 [P1-12])。
499
503
  *
500
504
  * 缺陷:`text` 有 120 字上限,`role` 却**完全不限长**——一条 3000 字的恶意
@@ -515,7 +519,18 @@ const WINDOW_ROLE_CHARS = 32
515
519
  *
516
520
  * 空载荷 / 无 recent 段 / 全空条目 → 返回空串(调用方据此**不 push** 第二块)。 */
517
521
  // issue #563:同上,导出仅为可测。
518
- export function formatSessionWindow(payload: unknown, limit: number): string {
522
+ export interface SessionWindowOptions {
523
+ /** 当前会话 id;提供时用于标注「本会话」还是「其他会话」(不用于过滤——
524
+ * 过滤由服务端 `session_recall` 按 `meta.session` 完成,前端再滤一次
525
+ * 会与服务端判据分裂成两份,本仓已多次栽在这上面)。 */
526
+ session?: string
527
+ /** 是否渲染归因前缀(默认 true)。设 false 可得旧格式(仅测试/回退用)。 */
528
+ attribution?: boolean
529
+ }
530
+
531
+ export function formatSessionWindow(
532
+ payload: unknown, limit: number, opts: SessionWindowOptions = {},
533
+ ): string {
519
534
  const items = (payload && typeof payload === 'object'
520
535
  && Array.isArray((payload as { recent?: unknown }).recent))
521
536
  ? (payload as { recent: Array<Record<string, unknown>> }).recent
@@ -523,6 +538,32 @@ export function formatSessionWindow(payload: unknown, limit: number): string {
523
538
  const rows: string[] = []
524
539
  const max = Math.max(1, Math.floor(limit) || 10)
525
540
  let used = 0
541
+ const curSid = String(opts.session ?? '').trim()
542
+ const wantAttr = opts.attribution !== false
543
+ // issue #712(2026-10-30):归因前缀——让模型能区分「本会话/其他会话」「私有/共有」
544
+ // 「刚刚/过去」。库层与注入面已带齐四要素(md_cg/mdcos.py 的 recent 段),此处负责
545
+ // **渲染出来**;不渲染等于模型永远看不到,等于没做(这正是 PR #712 的原病灶)。
546
+ // ⚠️ 本改动**变更输出格式**(BREAKING):原 `[role] text` → `[MM-DD HH:mm|会话|密级] [role] text`。
547
+ // 前缀会占预算,故 WINDOW_MAX_CHARS 同步上调(见该常量注释)。
548
+ const stamp = (t: unknown): string => {
549
+ const n = Number(t)
550
+ if (!Number.isFinite(n) || n <= 0) return '??-?? ??:??'
551
+ const d = new Date(n * 1000)
552
+ const p = (x: number): string => String(x).padStart(2, '0')
553
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
554
+ }
555
+ const sessTag = (s: unknown): string => {
556
+ const v = String(s ?? '').trim()
557
+ if (!v) return '?'
558
+ if (curSid && v === curSid) return '本'
559
+ return `会话${v.slice(-4)}`
560
+ }
561
+ const sensTag = (s: unknown): string => {
562
+ const v = String(s ?? '').trim().toLowerCase()
563
+ if (v === 'private' || v === 'secret') return '私'
564
+ if (v === 'public' || v === 'internal' || v === 'restricted') return '共'
565
+ return '?'
566
+ }
526
567
  for (const it of items.slice(0, max)) {
527
568
  // issue #354 [P1-12]:role 与 text 同受单条上限约束——只限 text 时一条超长
528
569
  // role 就能让首行突破整块预算并把后续历史全部挤出(首行 used===0 绕过了
@@ -535,7 +576,10 @@ export function formatSessionWindow(payload: unknown, limit: number): string {
535
576
  const body = safe.length > WINDOW_ITEM_CHARS
536
577
  ? safe.slice(0, WINDOW_ITEM_CHARS) + '…'
537
578
  : safe
538
- const row = `[${role}] ${body}`
579
+ const attr = wantAttr
580
+ ? `[${stamp(it['t'])}|${sessTag(it['session'])}|${sensTag(it['sensitivity'])}] `
581
+ : ''
582
+ const row = `${attr}[${role}] ${body}`
539
583
  const next = used === 0 ? row.length : used + 1 + row.length
540
584
  // issue #354 [P1-12]:单条超预算时不再「首条整放」——超过 WINDOW_MAX_CHARS 的
541
585
  // 行一律不放(截断 body 已在上面做完,理论上不可达,作 fail-closed 兜底)。
@@ -711,6 +755,7 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
711
755
  * **逐位等价**(差异窗口「本实例未观测 ∧ 模块单点非空」单实例下不可达;
712
756
  * HMR 重载时新实例回落 '' 属更保守行为)。 */
713
757
  let observedSession = false
758
+ let warnedEmptySid = false
714
759
 
715
760
  /** 记忆沉淀(fire-and-forget)。认知图未就绪则跳过并告警(不退回 AEIS)。
716
761
  * `role`=null 表示**读预热**(user-recall)——审计只统计写入路径,
@@ -800,6 +845,12 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
800
845
  const hostCtx = (_ctx as unknown) as { agent?: { session?: unknown } } | undefined
801
846
  const sid = sessionIdOf(hostCtx?.agent?.session)
802
847
  || (observedSession ? currentSession() : '')
848
+ // 会话 id 为空时后端会退回全局滚动窗口(跨会话串台)。只告警一次,
849
+ // 避免每个 assemble step 刷日志;不改注入内容或数据路径。
850
+ if (!sid && !warnedEmptySid) {
851
+ warnedEmptySid = true
852
+ ctx.logger.warn('dsh-memory: 会话 id 为空,短期窗口可能退回全局滚动窗口(跨会话串台);请检查 host.agent.session 或会话观测是否可用')
853
+ }
803
854
  // 逢十轮提醒的消费面(#657):不受 autoRecall 门控。
804
855
  if (sid) {
805
856
  const pending = pendingReminder.get(sid)
@@ -829,8 +880,25 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
829
880
  // 非永久层 → 既有「最近记忆」块;self/anchor → 独立「身份锚点」块(独立预算)。
830
881
  const identityOn = opts.autoRecallIdentity === true
831
882
  const timelinePayload = await graph.timeline(
832
- identityOn ? recallLimit + IDENTITY_MAX_ITEMS : recallLimit,
883
+ recallLimit,
833
884
  sid ? { session: sid } : {})
885
+ // issue #715(2026-10-30 外部报告,逐行复现):**身份块必须单独取数**。
886
+ //
887
+ // 病灶:此前身份块复用上面这份**带会话过滤**的 payload(还把 limit 加 3 试图
888
+ // 「多取 3 条」),但 `self`/`anchor` 节点的 `session` **恒为 `unattributed`**
889
+ // ——身份锚点在语义上就注定跨会话(`identity` 写入不带 session_id 时即如此,
890
+ // 状态卡与关系节点同理)。两者叠加 ⇒ 永久层被会话过滤全部滤掉 ⇒
891
+ // `renderIdentityAnchors` 拿到空集 ⇒ **块从不出现且无任何报错**(静默失效)。
892
+ //
893
+ // 这正是《身份与人格》理论的 R3:**人格的可见性不该由会话决定**。
894
+ // 用会话过滤去筛人格节点是**类别错误**,不是参数没调好。
895
+ //
896
+ // 故身份块改为**不带会话过滤**取数(不传 session ⇒ 跨会话视图),
897
+ // 再由 `renderIdentityAnchors` 只挑 self/anchor(其余层照样被它跳过)。
898
+ // 「最近记忆」块保持会话隔离不变——那是工作记忆,本就该跟会话走。
899
+ const identityPayload = identityOn
900
+ ? await graph.timeline(IDENTITY_MAX_ITEMS * 3, {})
901
+ : null
834
902
  const text = formatTimelineDecayed(timelinePayload)
835
903
  if (text) {
836
904
  // 注入边界转义(issue #16):宿主 system-prompt 对 context 文本做严格
@@ -866,13 +934,21 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
866
934
  }
867
935
  if (identityOn) {
868
936
  try {
869
- const idText = renderIdentityAnchors(timelinePayload)
937
+ // issue #715:用**独立取数**的 payload(不带会话过滤),不再复用已滤会话的那份。
938
+ const idText = renderIdentityAnchors(identityPayload)
870
939
  if (idText) {
871
940
  assembly.contexts.push({
872
941
  name: 'lingshu:identity-anchor',
873
942
  text: escapePromptBraces(renderUntrustedMemoryBlock(
874
943
  '【灵枢身份锚点】(self/anchor 层,独立预算)\n' + idText)),
875
944
  })
945
+ } else {
946
+ // issue #715(静默失效):此前「开关开了但块从不出现」与「库里确实没有
947
+ // self/anchor 节点」**完全不可分辨**——catch 不触发(没抛错),也没有任何
948
+ // 提示。开着的功能不生效却无声,比报错更难查。故此处显式留痕。
949
+ ctx.logger.info(
950
+ 'dsh-memory: autoRecallIdentity 已开启但无可注入的身份节点'
951
+ + '(self/anchor 层为空——请用 cg(op=identity, action=anchor) 建立锚点)')
876
952
  }
877
953
  } catch (err) {
878
954
  // issue #128 同款纪律:fail-soft 但不静默——空 catch 会被
@@ -892,7 +968,8 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
892
968
  if (cwEnabled) {
893
969
  try {
894
970
  const win = await graph.sessionRecall(sid, cwTurns, WINDOW_BUDGET_TOKENS)
895
- const winText = formatSessionWindow(win, cwTurns)
971
+ // issue #712:传 sid 用于**标注**(本会话/其他会话),不用于过滤。
972
+ const winText = formatSessionWindow(win, cwTurns, { session: sid })
896
973
  if (winText) {
897
974
  // 注入边界同规(文件头硬约束):不可信内容边界 + `{{` 转义,
898
975
  // 都只改注入副本——窗口原文在库内保真。
@@ -60,7 +60,7 @@
60
60
  try { renderResult(await call(tool,args,true)); } catch(e) { const target=$('result'); if(target) target.innerHTML=errorHTML(e); }
61
61
  finally { button.disabled=false; button.textContent=original; }
62
62
  }
63
- function permissionNote(op) { const allowed=info?.whoami?.principal?.ops_allow; return allowed && !allowed.includes(op) ? `<div class="notice">当前令牌未声明 ${esc(op)} 权限。入口保留,调用仍由灵枢权限系统裁定;本界面不会自动扩权。</div>`:''; }
63
+ function permissionNote(op) { const allowed=info?.whoami?.principal?.ops_allow; return allowed && !allowed.includes('*') && !allowed.includes(op) ? `<div class="notice">当前令牌未声明 ${esc(op)} 权限。入口保留,调用仍由灵枢权限系统裁定;本界面不会自动扩权。</div>`:''; }
64
64
  async function overview(token) {
65
65
  $('main').innerHTML=title('让认知,有迹可循。','COGNITIVE WORKSPACE','记忆、目标与自我,在同一张认知图中延续。','<button id="new-memory" class="button primary">+ 记录记忆</button>')+loading();
66
66
  $('new-memory').onclick=()=>navigate('memory',true);
package/web/app.js CHANGED
@@ -60,7 +60,7 @@
60
60
  try { renderResult(await call(tool,args,true)); } catch(e) { const target=$('result'); if(target) target.innerHTML=errorHTML(e); }
61
61
  finally { button.disabled=false; button.textContent=original; }
62
62
  }
63
- function permissionNote(op) { const allowed=info?.whoami?.principal?.ops_allow; return allowed && !allowed.includes(op) ? `<div class="notice">当前令牌未声明 ${esc(op)} 权限。入口保留,调用仍由灵枢权限系统裁定;本界面不会自动扩权。</div>`:''; }
63
+ function permissionNote(op) { const allowed=info?.whoami?.principal?.ops_allow; return allowed && !allowed.includes('*') && !allowed.includes(op) ? `<div class="notice">当前令牌未声明 ${esc(op)} 权限。入口保留,调用仍由灵枢权限系统裁定;本界面不会自动扩权。</div>`:''; }
64
64
  async function overview(token) {
65
65
  $('main').innerHTML=title('让认知,有迹可循。','COGNITIVE WORKSPACE','记忆、目标与自我,在同一张认知图中延续。','<button id="new-memory" class="button primary">+ 记录记忆</button>')+loading();
66
66
  $('new-memory').onclick=()=>navigate('memory',true);