lingshu-skill 0.0.0-stage → 3.82.0

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 (135) hide show
  1. package/CHANGELOG.md +2605 -0
  2. package/LICENSE +21 -0
  3. package/README.md +698 -3
  4. package/SKILL-lite.md +45 -0
  5. package/SKILL-tiny.md +37 -0
  6. package/SKILL.md +379 -0
  7. package/assets/panel.html +5616 -0
  8. package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
  9. package/cordis-plugin/lingshu-cron/index.js +4 -0
  10. package/cordis-plugin/lingshu-cron/package.json +34 -0
  11. package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
  12. package/cordis-plugin/lingshu-guard/plugin.js +473 -0
  13. package/cordis-plugin/lingshu-im/plugin.js +635 -0
  14. package/cordis-plugin/lingshu-startup/README.md +123 -0
  15. package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
  16. package/cordis-plugin/lingshu-startup/index.js +4 -0
  17. package/cordis-plugin/lingshu-startup/package.json +25 -0
  18. package/cordis-plugin/lingshu-startup/plugin.js +352 -0
  19. package/cordis.patch.yml +3 -0
  20. package/docs/commands.md +243 -0
  21. package/docs/mechanics.md +610 -0
  22. package/docs/models.md +52 -0
  23. package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
  24. package/docs/panel-api.md +198 -0
  25. package/docs/recovery.md +90 -0
  26. package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
  27. package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
  28. package/index.js +102 -0
  29. package/package.json +52 -6
  30. package/scripts/_panel_smoke_v299.py +27 -0
  31. package/scripts/_smoke_v299.py +31 -0
  32. package/scripts/_sync_trae_cn.py +34 -0
  33. package/scripts/assembler.py +197 -0
  34. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
  35. package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
  36. package/scripts/astrbot_plugin_lingshu/README.md +58 -0
  37. package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
  38. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
  39. package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
  40. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
  41. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
  42. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
  43. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
  44. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
  45. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
  46. package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
  47. package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
  48. package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
  49. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
  50. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
  51. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
  52. package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
  53. package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
  54. package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
  55. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
  56. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
  57. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
  58. package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
  59. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
  62. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
  63. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
  64. package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
  65. package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
  66. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
  67. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
  68. package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
  69. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
  70. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
  71. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
  72. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
  73. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
  74. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
  75. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
  76. package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
  77. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
  78. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
  79. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
  80. package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
  81. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
  82. package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
  83. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
  84. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
  85. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
  86. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
  87. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
  88. package/scripts/astrbot_plugin_lingshu/main.py +703 -0
  89. package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
  90. package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
  91. package/scripts/behavior_baseline.py +280 -0
  92. package/scripts/bench.py +192 -0
  93. package/scripts/brain.py +46 -0
  94. package/scripts/check_pressure_sync.py +55 -0
  95. package/scripts/check_tag.py +215 -0
  96. package/scripts/check_version.py +265 -0
  97. package/scripts/checkpoint.py +165 -0
  98. package/scripts/cli.py +4867 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2028 -0
  101. package/scripts/dream.py +1137 -0
  102. package/scripts/emotion.py +1180 -0
  103. package/scripts/failures.py +107 -0
  104. package/scripts/fallback_embed.py +114 -0
  105. package/scripts/growth.py +4745 -0
  106. package/scripts/growth_parts.py +263 -0
  107. package/scripts/hooks/pre-commit +18 -0
  108. package/scripts/hooks/pre-push +20 -0
  109. package/scripts/insights.py +131 -0
  110. package/scripts/make_dsh_tgz.py +92 -0
  111. package/scripts/make_manifest.py +254 -0
  112. package/scripts/make_plugin_zip.py +88 -0
  113. package/scripts/mem_dialogue.py +242 -0
  114. package/scripts/mem_embed.py +159 -0
  115. package/scripts/mem_lesson.py +160 -0
  116. package/scripts/mem_score.py +210 -0
  117. package/scripts/mem_topic.py +177 -0
  118. package/scripts/memory.py +4417 -0
  119. package/scripts/npm_prepack.py +31 -0
  120. package/scripts/panel_build.py +115 -0
  121. package/scripts/panel_cloud.py +609 -0
  122. package/scripts/panel_server.py +2703 -0
  123. package/scripts/panels.py +591 -0
  124. package/scripts/persona.py +2309 -0
  125. package/scripts/recreate_push.ps1 +117 -0
  126. package/scripts/retriever.py +195 -0
  127. package/scripts/run_tests.py +91 -0
  128. package/scripts/safety.py +368 -0
  129. package/scripts/session_import.py +736 -0
  130. package/scripts/session_rag.py +228 -0
  131. package/scripts/session_summary.py +123 -0
  132. package/scripts/summarizer.py +252 -0
  133. package/scripts/sync_engine.py +139 -0
  134. package/scripts/update_dsh_copy.ps1 +107 -0
  135. package/start-panel.bat +60 -0
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """检索接入(附录 C · P3)——优先问 session-rag 服务,没有就退回灵枢自己的召回。
4
+
5
+ 统一契约(附录 B §4):
6
+ POST {session_rag.url}/v1/search {"query": "...", "k": 20}
7
+ -> {"results": [{"id","text","score","source"}]}
8
+
9
+ 拿不到服务(没配 / 超时 / 报错 / 返回不可解析)→ **回退 `memory.recall()`**,
10
+ 并在结果里标 `source='lingshu'` + warning。绝不因为检索坏了阻塞注入。
11
+
12
+ 二段式:`search()` 拿候选 → `select()` 按预算挑(模型可选,失败退回打分顺序)。
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import urllib.request
18
+
19
+ DEFAULT_BUDGET_TOKENS = 800
20
+ CHARS_PER_TOKEN = 2
21
+
22
+
23
+ def _cfg(cfg: dict | None) -> dict:
24
+ if cfg is not None:
25
+ return dict(cfg.get("session_rag") or {})
26
+ try:
27
+ import core
28
+ return dict((core.load_config() or {}).get("session_rag") or {})
29
+ except Exception:
30
+ return {}
31
+
32
+
33
+ def estimate_tokens(text: str) -> int:
34
+ n = len(str(text or ""))
35
+ return (n + CHARS_PER_TOKEN - 1) // CHARS_PER_TOKEN
36
+
37
+
38
+ def _normalize(items) -> list[dict]:
39
+ out = []
40
+ for it in items or []:
41
+ if not isinstance(it, dict):
42
+ continue
43
+ text = str(it.get("text") or it.get("content") or "").strip()
44
+ if not text:
45
+ continue
46
+ out.append({
47
+ "id": str(it.get("id") or it.get("memory_id") or ""),
48
+ "text": text,
49
+ "score": float(it.get("score") or 0.0),
50
+ "source": str(it.get("source") or it.get("platform") or ""),
51
+ })
52
+ return out
53
+
54
+
55
+ def http_search(query: str, k: int = 20, *, cfg: dict | None = None, call=None,
56
+ timeout: float | None = None) -> list[dict] | None:
57
+ """问 session-rag 的 /v1/search;失败返回 None(由上层回退)。"""
58
+ c = _cfg(cfg)
59
+ url = str(c.get("url") or "").rstrip("/")
60
+ if not url and call is None:
61
+ return None
62
+ if call is not None:
63
+ try:
64
+ return _normalize(call(query, k))
65
+ except Exception:
66
+ return None
67
+ body = json.dumps({"query": query, "k": int(k)}).encode("utf-8")
68
+ req = urllib.request.Request(url + "/v1/search", data=body, method="POST",
69
+ headers={"Content-Type": "application/json"})
70
+ try:
71
+ with urllib.request.urlopen(req, timeout=timeout or float(c.get("timeout") or 3)) as r:
72
+ # 响应上限 2MB:服务异常/恶意代理返回超大 body 时不能把内存打满
73
+ data = json.loads(r.read(2 * 1024 * 1024).decode("utf-8", "replace"))
74
+ rows = data.get("results") if isinstance(data, dict) else data
75
+ return _normalize(rows)
76
+ except Exception as exc: # noqa: BLE001
77
+ try:
78
+ import failures
79
+ failures.record("retriever.session_rag", f"{type(exc).__name__}: {exc}",
80
+ ctx={"url": url})
81
+ except Exception:
82
+ pass
83
+ return None
84
+
85
+
86
+ def recall_search(query: str, k: int = 20) -> list[dict]:
87
+ """灵枢本地召回(词面/实体/向量混合,取决于配置),失败返回空。"""
88
+ try:
89
+ import memory
90
+ rows = memory.recall(query, k=int(k))
91
+ except Exception:
92
+ return []
93
+ out = []
94
+ for item in rows or []:
95
+ try:
96
+ m, score, _parts = item
97
+ except Exception:
98
+ continue
99
+ out.append({
100
+ "id": str(m.get("id") or ""),
101
+ "text": str(m.get("text") or ""),
102
+ "score": float(score or 0.0),
103
+ "source": "lingshu",
104
+ })
105
+ return out
106
+
107
+
108
+ def search(query: str, k: int = 20, *, cfg: dict | None = None, call=None) -> dict:
109
+ """先服务后本地,返回 {results, source, warnings}。"""
110
+ warnings: list[str] = []
111
+ rows = http_search(query, k, cfg=cfg, call=call)
112
+ if rows is not None:
113
+ return {"results": rows, "source": "session-rag", "warnings": warnings}
114
+ c = _cfg(cfg)
115
+ if c.get("url"):
116
+ warnings.append("session-rag 不可用,已回退灵枢本地召回")
117
+ rows = recall_search(query, k)
118
+ return {"results": rows, "source": "lingshu", "warnings": warnings}
119
+
120
+
121
+ # ---------------------------------------------------------------- 挑选
122
+
123
+ def _heuristic(cands: list[dict], budget_tokens: int) -> list[dict]:
124
+ kept, used = [], 0
125
+ for it in cands:
126
+ t = estimate_tokens(it["text"])
127
+ if kept and used + t > budget_tokens:
128
+ continue
129
+ kept.append(it)
130
+ used += t
131
+ if used >= budget_tokens:
132
+ break
133
+ return kept
134
+
135
+
136
+ def _model_select(cands: list[dict], query: str, call) -> list[dict] | None:
137
+ """让模型从候选里挑:只要 id 列表,不重写正文。"""
138
+ brief = "\n".join(f"{i+1}. id={c['id']} 摘要={c['text'][:120]}"
139
+ for i, c in enumerate(cands))
140
+ prompt = (f"查询:{query}\n下面是从记忆里检索到的候选片段。只挑和查询真正相关的,"
141
+ f"最多 5 条。只输出 JSON:{{\"keep\":[\"id\", ...]}}\n\n{brief}")
142
+ try:
143
+ raw = call(prompt)
144
+ data = json.loads(str(raw or "").strip())
145
+ keep = [str(x) for x in (data.get("keep") or [])]
146
+ except Exception:
147
+ return None
148
+ if not keep:
149
+ return None
150
+ by_id = {c["id"]: c for c in cands}
151
+ out = [by_id[i] for i in keep if i in by_id]
152
+ return out or None
153
+
154
+
155
+ def select(cands: list[dict], query: str = "", *, budget_tokens: int | None = None,
156
+ cfg: dict | None = None, call=None) -> dict:
157
+ """候选 → 选中(模型优先,失败/超预算退回启发式)。"""
158
+ c = _cfg(cfg)
159
+ budget = int(budget_tokens or c.get("budget_tokens") or DEFAULT_BUDGET_TOKENS)
160
+ cands = _normalize(cands)
161
+ if not cands:
162
+ return {"kept": [], "source": "empty", "warnings": []}
163
+ warnings: list[str] = []
164
+ kept = None
165
+ if call is not None or c.get("select_model"):
166
+ caller = call
167
+ if caller is None:
168
+ try:
169
+ from summarizer import openai_chat
170
+ caller = lambda p: openai_chat(p, dict(c.get("select") or {}))
171
+ except Exception:
172
+ caller = None
173
+ if caller is not None:
174
+ kept = _model_select(cands, query, caller)
175
+ if kept is None:
176
+ warnings.append("模型挑选失败/不可用,退回打分顺序")
177
+ source = "model" if kept is not None else "heuristic"
178
+ if kept is None:
179
+ kept = _heuristic(cands, budget)
180
+ return {"kept": kept, "source": source, "warnings": warnings,
181
+ "tokens": sum(estimate_tokens(x["text"]) for x in kept)}
182
+
183
+
184
+ def build_snippet(query: str, k: int = 20, *, budget_tokens: int | None = None,
185
+ cfg: dict | None = None, call=None) -> str:
186
+ """一步到位:检索 → 挑选 → 拼成带来源标记的文本块(空结果返回 "")。"""
187
+ res = search(query, k, cfg=cfg)
188
+ picked = select(res["results"], query, budget_tokens=budget_tokens, cfg=cfg, call=call)
189
+ if not picked["kept"]:
190
+ return ""
191
+ lines = [f"## 检索到的相关片段(来源:{res['source']})"]
192
+ for it in picked["kept"]:
193
+ tag = f"[{it['source'] or 'mem'}:{it['id']}]" if it["id"] else f"[{it['source'] or 'mem'}]"
194
+ lines.append(f"- {tag} {it['text'][:400]}")
195
+ return "\n".join(lines)
@@ -0,0 +1,368 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢 —— 数据目录与破坏性操作的护栏。
4
+
5
+ 为什么要有这一层(真实事故):用户的用户目录被某个未知进程整片清空,
6
+ 灵枢记忆库 `~/.brain-memory` 一起没了;事后翻备份才发现,那阵子的备份
7
+ 默认落在 `~/Documents/brain-memory-backups` —— 备份和用户内容在同一个
8
+ 目录、同一块盘,被同一次事故一起端掉,等于没有备份。最后只能靠更早的
9
+ 一块独立盘(D:)上的旧备份把人格救回来。
10
+
11
+ 三条规则,写死在代码里,不靠自觉:
12
+
13
+ 1. **不能把记忆库放在「会被清理的东西」里**。盘符根、用户主目录本体、
14
+ 用户库文件夹(桌面/文档/下载/图片/视频/音乐/OneDrive)、系统目录,
15
+ 一律拒绝当记忆库。`not set` 也不行,必须是「一个自己的目录」。
16
+ 2. **删整库之前先证明这确实是灵枢库**。靠标记文件判断,不靠路径长得像;
17
+ 认不出来的文件一律不删(restore --exact 也保留)。
18
+ 3. **备份尽量跨卷**。同卷备份 = 同一个炸弹上的两个引信。
19
+
20
+ 所有函数都不写盘(除了 `pick_backup_dir` 会 mkdir 备份目录),
21
+ 可以在只读降级下安全调用。
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import string
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ __all__ = [
31
+ "UnsafeHomeError",
32
+ "dangerous_reason",
33
+ "assert_safe_home",
34
+ "is_managed_home",
35
+ "assert_managed_home",
36
+ "is_managed_relpath",
37
+ "same_volume",
38
+ "backup_dir_candidates",
39
+ "pick_backup_dir",
40
+ "is_interactive",
41
+ "confirm_destructive",
42
+ "MANAGED_TOP_FILES",
43
+ "MANAGED_TOP_DIRS",
44
+ ]
45
+
46
+ # 用户库文件夹的**磁盘真名**(Windows 本地化只影响显示名,落盘永远是这些英文名)。
47
+ # 刻意不收中文「文档/下载」:中文目录名太常见,会误伤 D:\文档\xxx 这种正常布局。
48
+ LIBRARY_FOLDER_NAMES = frozenset({
49
+ "desktop", "documents", "downloads", "pictures", "videos", "movies", "music",
50
+ "onedrive", "favorites", "saved games", "searches", "links", "contacts",
51
+ })
52
+
53
+ # 明确不能当记忆库的系统目录(小写、绝对路径前缀)。
54
+ # 注意不要写 "c:\\users":用户自己的数据本来就住在 C:\Users\<name>\ 下面。
55
+ _SYSTEM_PREFIXES = (
56
+ "c:\\windows", "c:\\program files", "c:\\program files (x86)",
57
+ "c:\\programdata", "c:\\$recycle.bin",
58
+ "/etc", "/usr", "/bin", "/sbin", "/var", "/boot", "/dev", "/proc", "/sys",
59
+ )
60
+
61
+ # 判定「这像不像灵枢库」的标记文件:任意一个存在即认为像。
62
+ MARKER_FILES = ("_meta.json", "persona.json", "config.json",
63
+ "hippocampus.jsonl", "cortex.jsonl")
64
+
65
+ # 灵枢自己管理的顶层文件(restore --exact 允许删除的白名单)。
66
+ MANAGED_TOP_FILES = frozenset({
67
+ "_meta.json", "config.json", "persona.json",
68
+ "hippocampus.jsonl", "cortex.jsonl", "dust.jsonl", "archive.jsonl",
69
+ "assoc.jsonl", "topics.jsonl", "working.jsonl", "emotions.jsonl",
70
+ "desires.json", "desire_history.jsonl", "notes.jsonl", "knowledge.jsonl",
71
+ "evolution.jsonl", "audit.jsonl", "consent.json", "daily_state.json",
72
+ "dream_state.json", "last_retrieval.json", "recall_usage.jsonl",
73
+ "metrics.jsonl", "failures.jsonl", "persona_pending.jsonl",
74
+ "persona_snapshots.jsonl", "skills.json", "update_check.json",
75
+ "lingshu.user.md", "lingshu.log", "session_rag.db",
76
+ "session_rag.db-shm", "session_rag.db-wal",
77
+ })
78
+
79
+ # 灵枢自己管理的顶层目录。
80
+ MANAGED_TOP_DIRS = frozenset({
81
+ "dreams", "dream-snapshots", "persona_snapshots", "skills", "verbatim",
82
+ "knowledge", "extensions", "panels", "backups", "handoffs", "sessions",
83
+ "downloads",
84
+ })
85
+
86
+
87
+ class UnsafeHomeError(RuntimeError):
88
+ """记忆库指向了一个不该被当作记忆库的目录。"""
89
+
90
+
91
+ def _expand(p: Path | str) -> Path:
92
+ return Path(p).expanduser()
93
+
94
+
95
+ def _resolved(p: Path | str) -> Path:
96
+ try:
97
+ return _expand(p).resolve()
98
+ except OSError: # 目录还不存在 / 短路径解析失败时退回字面路径
99
+ return _expand(p)
100
+
101
+
102
+ def _is_drive_root(p: Path) -> bool:
103
+ """盘符根(C:\\、D:\\)或 POSIX 的 /。"""
104
+ if p.parent == p: # "/" 或 "C:\\"
105
+ return True
106
+ anchor = p.anchor # "C:\\" / "/" / "\\\\server\\share\\"
107
+ try:
108
+ return p == Path(anchor) or str(p) in (anchor, anchor.rstrip("\\/"))
109
+ except Exception:
110
+ return False
111
+
112
+
113
+ def _is_home_dir(p: Path) -> bool:
114
+ try:
115
+ return p == Path.home().resolve()
116
+ except OSError:
117
+ return False
118
+
119
+
120
+ def dangerous_reason(home: Path | str) -> str | None:
121
+ """这个路径为什么不能当记忆库?返回中文原因,安全则返回 None。"""
122
+ raw = _expand(home)
123
+ r = _resolved(home)
124
+ if _is_drive_root(r):
125
+ return "盘符根目录不能当记忆库(会把整盘的文件当成自己的)"
126
+ if _is_home_dir(r):
127
+ return "用户主目录本体不能当记忆库(restore --exact 会清空整个用户目录)"
128
+ low = str(r).lower().replace("/", "\\") if sys.platform == "win32" else str(r).lower()
129
+ for pref in _SYSTEM_PREFIXES:
130
+ if low == pref or low.startswith(pref.rstrip("\\") + "\\"):
131
+ return f"系统目录不能当记忆库:{raw}"
132
+ # 所有用户的父目录(C:\Users 本身)
133
+ try:
134
+ if r.name.lower() == "users" and r.parent == Path(r.anchor):
135
+ return "用户根目录(所有账户的父目录)不能当记忆库"
136
+ except OSError:
137
+ pass
138
+ # 用户库文件夹及其内部:~/Documents、~/Desktop/brain-memory …
139
+ # 按「相对主目录的第一段」比,且**不区分大小写**:
140
+ # - Windows 的路径比较本来就不区分大小写,旧写法 `r == user_home / name` 在那边没问题;
141
+ # - 但 POSIX 区分大小写,而 macOS 的真实目录名是 ~/Documents、Linux 上也常是大写 D,
142
+ # 旧写法只认全小写名 → 整个用户库文件夹在 Linux/macOS 上漏判(v3.48 的 CI 红)。
143
+ # 这条规则是"别把记忆库放在会被整片清理的地方",大小写只是写法,不该影响判定。
144
+ try:
145
+ user_home = Path.home().resolve()
146
+ except OSError:
147
+ user_home = Path.home()
148
+ try:
149
+ rel_parts = r.relative_to(user_home).parts
150
+ except ValueError:
151
+ rel_parts = ()
152
+ if rel_parts and rel_parts[0].lower() in LIBRARY_FOLDER_NAMES:
153
+ return (f"路径落在用户库文件夹「{rel_parts[0]}」里 —— 这类目录最容易被清理、"
154
+ f"重装或误删整片带走,备份也会跟着一起没")
155
+ return None
156
+
157
+
158
+ def assert_safe_home(home: Path | str, action: str = "使用") -> None:
159
+ """危险路径直接抛异常;`BRAIN_MEMORY_ALLOW_UNSAFE_HOME=1` 可强行越过。
160
+
161
+ 越过时会往 stderr 打一行醒目的警告 —— 允许,但不装作没发生。
162
+ """
163
+ reason = dangerous_reason(home)
164
+ if not reason:
165
+ return
166
+ if os.environ.get("BRAIN_MEMORY_ALLOW_UNSAFE_HOME") == "1":
167
+ print(f"[警告] {action}记忆库的路径选择不安全:{reason}\n"
168
+ f" 已按 BRAIN_MEMORY_ALLOW_UNSAFE_HOME=1 强制继续,风险自负。",
169
+ file=sys.stderr)
170
+ return
171
+ raise UnsafeHomeError(
172
+ f"拒绝{action}记忆库:{reason}\n"
173
+ f" 路径:{_expand(home)}\n"
174
+ f" 换一个独立目录,例如:{_suggest_safe_home()}\n"
175
+ f" (万不得已要强行使用,设 BRAIN_MEMORY_ALLOW_UNSAFE_HOME=1)"
176
+ )
177
+
178
+
179
+ def _suggest_safe_home() -> str:
180
+ return str(Path.home() / ".brain-memory")
181
+
182
+
183
+ def is_managed_home(home: Path | str) -> bool:
184
+ """目录里有没有灵枢的标记文件 —— 有才敢对它做整库删除。"""
185
+ r = _resolved(home)
186
+ try:
187
+ return any((r / name).exists() for name in MARKER_FILES)
188
+ except OSError:
189
+ return False
190
+
191
+
192
+ def assert_managed_home(home: Path | str) -> None:
193
+ """整库删除前的第二道闸:不像灵枢库就拒绝。"""
194
+ if is_managed_home(home):
195
+ return
196
+ raise UnsafeHomeError(
197
+ f"拒绝整库删除:{_expand(home)} 里找不到任何灵枢标记文件"
198
+ f"({ '、'.join(MARKER_FILES) })。\n"
199
+ f" 目录不像记忆库时,清空它只会毁掉别的数据。"
200
+ )
201
+
202
+
203
+ def is_managed_relpath(rel: Path | str) -> bool:
204
+ """rel 是相对记忆库根的路径:这个路径归灵枢管吗?
205
+
206
+ True = 可删可覆盖;False = 用户自己放进去的东西,任何“清空/恢复”都不许碰。
207
+ """
208
+ rel = Path(rel)
209
+ parts = rel.parts
210
+ if not parts:
211
+ return False
212
+ # 灵枢自己的临时件与锁文件
213
+ name = parts[-1]
214
+ if name.startswith(".restore-tmp-") or name == ".write-probe":
215
+ return True
216
+ if name.endswith((".lock", ".tmp")):
217
+ return True
218
+ if len(parts) == 1:
219
+ return name in MANAGED_TOP_FILES or name in MANAGED_TOP_DIRS
220
+ return parts[0] in MANAGED_TOP_DIRS
221
+
222
+
223
+ def same_volume(a: Path | str, b: Path | str) -> bool:
224
+ """两个路径是不是同一块卷(Windows 按盘符,POSIX 按 st_dev)。"""
225
+ try:
226
+ ra, rb = _resolved(a), _resolved(b)
227
+ except OSError:
228
+ return True
229
+ if sys.platform == "win32":
230
+ return (ra.drive or "").lower() == (rb.drive or "").lower()
231
+ try:
232
+ return ra.stat().st_dev == rb.stat().st_dev
233
+ except OSError:
234
+ return True
235
+
236
+
237
+ def _windows_drives() -> list[Path]:
238
+ drives = []
239
+ for letter in string.ascii_uppercase:
240
+ root = Path(f"{letter}:\\")
241
+ try:
242
+ if root.exists():
243
+ drives.append(root)
244
+ except OSError:
245
+ continue
246
+ return drives
247
+
248
+
249
+ def backup_dir_candidates(home: Path | str) -> list[Path]:
250
+ """备份目录候选,**跨卷优先**。
251
+
252
+ 顺序:别卷根 → 记忆库同级盘上的固定名 → 记忆库内部(最后兜底)。
253
+ 刻意不再用 ~/Documents 和 ~/Desktop:那正是会被整片清掉的地方。
254
+ """
255
+ home = _expand(home)
256
+ out: list[Path] = []
257
+ if sys.platform == "win32":
258
+ for root in _windows_drives():
259
+ if same_volume(root, home):
260
+ continue
261
+ out.append(root / "brain-memory-backups")
262
+ else:
263
+ for root in (Path("/mnt"), Path("/media"), Path("/Volumes")):
264
+ if root.is_dir():
265
+ for child in sorted(root.iterdir()):
266
+ if child.is_dir() and not same_volume(child, home):
267
+ out.append(child / "brain-memory-backups")
268
+ out.append(home / "backups")
269
+ seen: set[str] = set()
270
+ uniq: list[Path] = []
271
+ for p in out:
272
+ key = str(p).lower()
273
+ if key not in seen:
274
+ seen.add(key)
275
+ uniq.append(p)
276
+ return uniq
277
+
278
+
279
+ def pick_backup_dir(home: Path | str) -> Path:
280
+ """挑一个能建的备份目录并 mkdir;全都建不了就退回 `<home>/backups`。
281
+
282
+ 返回的目录保证**已经存在且可写**(除极端情况)。
283
+ """
284
+ home = _expand(home)
285
+ for cand in backup_dir_candidates(home):
286
+ try:
287
+ cand.mkdir(parents=True, exist_ok=True)
288
+ probe = cand / ".write-probe"
289
+ probe.write_text("ok", encoding="ascii")
290
+ probe.unlink()
291
+ return cand
292
+ except Exception:
293
+ continue
294
+ fallback = home / "backups"
295
+ try:
296
+ fallback.mkdir(parents=True, exist_ok=True)
297
+ except Exception:
298
+ pass
299
+ return fallback
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # 破坏性操作的统一确认(v3.52)
304
+ #
305
+ # 之前 restore 自己写了一套 input() 询问、purge 用 --confirm 令牌,两套规则并存:
306
+ # 同一种"会覆盖/删除数据"的操作,在不同命令上要求不同的确认方式,用户和宿主都难记。
307
+ # 现在统一走 confirm_destructive():
308
+ #
309
+ # 1. **先打印影响面**(动哪个目录、会不会删备份之后新增的文件),无论是否交互;
310
+ # 2. `--yes` → 直接放行(脚本/宿主/CI 用);
311
+ # 3. 不是终端(管道、AI 调用、计划任务)→ **拒绝**,并说清必须加 --yes;
312
+ # 4. 是终端 → 问 y/N,默认 N。
313
+ #
314
+ # 例外:`backup` 不加口令时只**提示**不拦截——它不销毁数据,只是生成明文 zip;
315
+ # 且 restore 前的自动备份传 assume_yes=True,不能被这条规则挡住。
316
+ # ---------------------------------------------------------------------------
317
+
318
+
319
+ def is_interactive() -> bool:
320
+ """当前 stdin 是不是终端。宿主/AI 调用、管道、计划任务里通常是 False。"""
321
+ try:
322
+ return bool(sys.stdin is not None and sys.stdin.isatty())
323
+ except Exception:
324
+ return False
325
+
326
+
327
+ def confirm_destructive(action: str, impact: str | list[str], *,
328
+ assume_yes: bool = False,
329
+ hint: str = "",
330
+ stream=None) -> bool:
331
+ """破坏性操作的统一确认。返回 True=可以继续,False=调用方应中止(或被取消)。
332
+
333
+ 参数:
334
+ action :操作名,如 "恢复"、"生成明文备份"、"物理删除记忆"
335
+ impact :影响面清单(一条字符串或字符串列表),会逐行打印
336
+ assume_yes:对应 `--yes`;True 时跳过询问(但仍打印影响面)
337
+ hint :拒绝/取消时给用户的下一步建议(可选)
338
+ stream :影响面输出位置,默认 stdout(测试可传 io.StringIO)
339
+ """
340
+ out = stream if stream is not None else sys.stdout
341
+ lines = [impact] if isinstance(impact, str) else list(impact)
342
+ print(f"[{action}] 影响面:", file=out)
343
+ for line in lines:
344
+ print(f" - {line}", file=out)
345
+
346
+ if assume_yes:
347
+ print(f"[{action}] 已通过 --yes 确认。", file=out)
348
+ if hint:
349
+ print(f" {hint}", file=out)
350
+ return True
351
+
352
+ if not is_interactive():
353
+ print(f"[错误] 非交互环境下{action}会改动或覆盖数据,必须显式加 --yes 确认。",
354
+ file=sys.stderr)
355
+ if hint:
356
+ print(f" {hint}", file=sys.stderr)
357
+ return False
358
+
359
+ try:
360
+ ans = input(f"确认执行{action}?[y/N] ")
361
+ except (EOFError, KeyboardInterrupt):
362
+ ans = ""
363
+ if ans.strip().lower() in ("y", "yes"):
364
+ return True
365
+ print("已取消。", file=out)
366
+ if hint:
367
+ print(f" {hint}", file=out)
368
+ return False