lingshu-skill 0.0.0-stage → 3.79.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 +2571 -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 +802 -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 +2571 -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 +4850 -0
  60. package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
  61. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -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 +4352 -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 +4850 -0
  99. package/scripts/context_ab.py +260 -0
  100. package/scripts/core.py +2025 -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 +4352 -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,117 @@
1
+ # 同名重建后的一次性推送脚本(灵枢)
2
+ #
3
+ # 背景:仓库历史里曾有两个提交署了 lingshu@users.noreply.github.com,GitHub 把它们
4
+ # 算成了一位真实用户(Kun (Emma) Chen)。现行 main 已经不含她任何提交,但 GitHub 侧
5
+ # 还留着旧对象与贡献者统计缓存。同名重建 + 只推干净历史,是唯一能立刻根治的办法。
6
+ #
7
+ # 本脚本只做三件事,且每步都先校验:
8
+ # 1. 校验:工作区干净、HEAD 是预期版本、每个 tag 剥开后都在 main 链上;
9
+ # 2. 推送:main + 逐个 tag(每个 tag 单独推,可以看清是哪个失败);
10
+ # 3. 复核:远端 main == 本地 HEAD、远端 tag 数量 == 白名单数量。
11
+ #
12
+ # 用法(默认干跑,不推任何东西):
13
+ # powershell -ExecutionPolicy Bypass -File scripts\recreate_push.ps1
14
+ # powershell -ExecutionPolicy Bypass -File scripts\recreate_push.ps1 -Run
15
+ # 可选 -SkipTags 只推 main(不重建任何 Release)
16
+ # 可选 -Remote gitee|origin(默认 origin)
17
+
18
+ param(
19
+ [switch]$Run,
20
+ [switch]$SkipTags,
21
+ [string]$Remote = "origin"
22
+ )
23
+
24
+ # 注意用 Continue:git 的 push 正常输出走 stderr("To https://..."),
25
+ # 在 PowerShell 5.1 里配合 Stop 会把正常输出当成终止错误直接中断脚本。
26
+ $ErrorActionPreference = "Continue"
27
+ $repo = Split-Path -Parent $PSScriptRoot
28
+ Set-Location $repo
29
+
30
+ # GitHub 直连在本机需要这组参数(实测:默认 0/3,HTTP/1.1+OpenSSL 3/3)
31
+ $tls = @("-c", "http.version=HTTP/1.1", "-c", "http.sslBackend=openssl")
32
+
33
+ Write-Host "== 1. 本地预检 ==" -ForegroundColor Cyan
34
+ # 只看已跟踪文件的改动:仓库根那份交接笔记是有意不入库的,不该挡推送
35
+ $dirty = git status --porcelain --untracked-files=no
36
+ if ($dirty) {
37
+ Write-Host "[中止] 工作区不干净,先提交或 stash:" -ForegroundColor Red
38
+ $dirty | Select-Object -First 10 | ForEach-Object { Write-Host " $_" }
39
+ exit 1
40
+ }
41
+ $head = (git rev-parse HEAD).Trim()
42
+ $ver = (Select-String -Path "SKILL.md" -Pattern '^version:\s*(\S+)' | Select-Object -First 1).Matches.Groups[1].Value
43
+ Write-Host " HEAD : $head"
44
+ Write-Host " 版本 : v$ver"
45
+
46
+ $badTags = @()
47
+ $tags = @(git tag --list)
48
+ foreach ($t in $tags) {
49
+ $c = (git rev-list -n 1 $t).Trim()
50
+ git merge-base --is-ancestor $c $head 2>$null
51
+ if ($LASTEXITCODE -ne 0) { $badTags += "$t -> $c" }
52
+ }
53
+ if ($badTags.Count -gt 0) {
54
+ Write-Host "[中止] 以下 tag 不在 main 链上,推上去会把旧历史带回来:" -ForegroundColor Red
55
+ $badTags | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
56
+ exit 1
57
+ }
58
+ Write-Host " tag : $($tags.Count) 个,全部在 main 链上 ✔"
59
+
60
+ Write-Host "== 2. 远端状态 ==" -ForegroundColor Cyan
61
+ $remoteRefs = git @tls ls-remote --heads $Remote 2>&1
62
+ if ($LASTEXITCODE -ne 0) {
63
+ Write-Host "[中止] 连不上远端 $Remote(网络/TLS),稍后重试" -ForegroundColor Red
64
+ exit 1
65
+ }
66
+ if ($remoteRefs) {
67
+ Write-Host " 远端现有分支:" -ForegroundColor Yellow
68
+ $remoteRefs | ForEach-Object { Write-Host " $_" }
69
+ Write-Host " 如果这是重建后的空仓库,这里应该是空的。若仍非空,说明还没删干净。" -ForegroundColor Yellow
70
+ } else {
71
+ Write-Host " 远端为空(重建后的状态)✔"
72
+ }
73
+
74
+ Write-Host "== 3. 将执行 ==" -ForegroundColor Cyan
75
+ Write-Host " git $($tls -join ' ') push $Remote main"
76
+ if (-not $SkipTags) {
77
+ Write-Host " 逐个推 $($tags.Count) 个 tag(每个都会触发一次 release 流水线)"
78
+ }
79
+
80
+ if (-not $Run) {
81
+ Write-Host ""
82
+ Write-Host "== 干跑结束;加 -Run 才真的推 ==" -ForegroundColor Green
83
+ exit 0
84
+ }
85
+
86
+ Write-Host "== 4. 推 main ==" -ForegroundColor Cyan
87
+ git @tls push $Remote main
88
+ if ($LASTEXITCODE -ne 0) { Write-Host "[失败] main 没推上去" -ForegroundColor Red; exit 1 }
89
+
90
+ $failed = @()
91
+ if (-not $SkipTags) {
92
+ Write-Host "== 5. 逐个推 tag ==" -ForegroundColor Cyan
93
+ $i = 0
94
+ foreach ($t in $tags) {
95
+ $i++
96
+ $out = git @tls push $Remote "refs/tags/$t" 2>&1
97
+ if ($LASTEXITCODE -ne 0) { $failed += $t; Write-Host (" [{0}/{1}] {2} 失败" -f $i, $tags.Count, $t) -ForegroundColor Yellow }
98
+ else { Write-Host (" [{0}/{1}] {2} OK" -f $i, $tags.Count, $t) -ForegroundColor DarkGray }
99
+ }
100
+ }
101
+
102
+ Write-Host "== 6. 复核 ==" -ForegroundColor Cyan
103
+ $rHead = (git @tls ls-remote --heads $Remote main 2>&1 | ForEach-Object { ($_ -split '\s+')[0] })
104
+ Write-Host " 远端 main: $rHead"
105
+ Write-Host " 本地 HEAD: $head"
106
+ if ($rHead -ne $head) { Write-Host " [注意] 远端 main 与本地 HEAD 不一致" -ForegroundColor Yellow }
107
+ $rTags = @(git @tls ls-remote --tags $Remote 2>&1 | Where-Object { $_ -notmatch '\^\{\}' })
108
+ Write-Host " 远端 tag : $($rTags.Count) 个(白名单 $($tags.Count) 个)"
109
+
110
+ if ($failed.Count -gt 0) {
111
+ Write-Host "[部分失败] 重跑:针对这几个 tag 再推一次" -ForegroundColor Yellow
112
+ $failed | ForEach-Object { Write-Host " git $($tls -join ' ') push $Remote refs/tags/$_" }
113
+ exit 1
114
+ }
115
+ Write-Host ""
116
+ Write-Host "[完成] 去 GitHub 看:仓库页 Contributors 应只剩 1 个。" -ForegroundColor Green
117
+ Write-Host " 若仍显示 2,那是页面缓存——用无痕窗口打开,或等几分钟。" -ForegroundColor Green
@@ -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,91 @@
1
+ # -*- coding: utf-8 -*-
2
+ """灵枢测试统一入口:**先隔离 HOME,再逐个跑**。
3
+
4
+ 为什么需要它:测试都是纯标准库脚本,直接 `python tests/test_xxx.py` 跑时,
5
+ `BRAIN_MEMORY_HOME` 没设就是真实记忆库——有些用例(如 `test_release_drift` 里
6
+ 模拟扫描失败的那条)会通过 `core.log_event` 往真实 `~/.brain-memory/lingshu.log`
7
+ 写日志。2026-11-20 就因此在本机真库日志里留下两条假的「扫描 DSH 副本失败」,
8
+ 排障时把我自己带偏过一次。
9
+
10
+ 本入口做三件事:
11
+ 1. 把 `BRAIN_MEMORY_HOME` / `LINGSHU_GLOBAL_SKILLS` 指到临时目录(每个测试文件
12
+ 一个独立目录,互不干扰,跑完删掉);
13
+ 2. 逐个运行 `tests/test_*.py`,失败时打印该文件最后 40 行输出;
14
+ 3. 汇总 `N/M 通过`,有失败则退出码 1。
15
+
16
+ 用法:
17
+ python scripts/run_tests.py # 全量
18
+ python scripts/run_tests.py restore # 只跑文件名含 restore 的
19
+ python scripts/run_tests.py -v # 打印每个文件的 PASS 行
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ from pathlib import Path
29
+
30
+ ROOT = Path(__file__).resolve().parent.parent
31
+ TESTS = ROOT / "tests"
32
+
33
+
34
+ def main(argv: list[str]) -> int:
35
+ verbose = "-v" in argv or "--verbose" in argv
36
+ keywords = [a for a in argv if not a.startswith("-")]
37
+ files = sorted(TESTS.glob("test_*.py"))
38
+ if keywords:
39
+ files = [f for f in files if any(k in f.name for k in keywords)]
40
+ if not files:
41
+ print("[错误] 没有匹配的测试文件", file=sys.stderr)
42
+ return 2
43
+
44
+ print(f"共 {len(files)} 个测试文件(每个独立临时 HOME)")
45
+ failed: list[tuple[str, str]] = []
46
+ ran = 0
47
+ for f in files:
48
+ ran += 1
49
+ tmp = Path(tempfile.mkdtemp(prefix="ls-test-"))
50
+ env = dict(os.environ)
51
+ env["BRAIN_MEMORY_HOME"] = str(tmp / "home")
52
+ env["LINGSHU_GLOBAL_SKILLS"] = str(tmp / "skills")
53
+ env["PYTHONIOENCODING"] = "utf-8"
54
+ (tmp / "home").mkdir(parents=True, exist_ok=True)
55
+ (tmp / "skills").mkdir(parents=True, exist_ok=True)
56
+ try:
57
+ r = subprocess.run([sys.executable, str(f)], capture_output=True, text=True,
58
+ encoding="utf-8", errors="replace", timeout=1800, env=env)
59
+ except subprocess.TimeoutExpired:
60
+ failed.append((f.name, "超时(>30 分钟)"))
61
+ print(f"FAIL {f.name} 超时")
62
+ shutil.rmtree(tmp, ignore_errors=True)
63
+ continue
64
+ out = (r.stdout or "") + (r.stderr or "")
65
+ if r.returncode == 0:
66
+ print(f"PASS {f.name}")
67
+ if verbose:
68
+ for line in out.splitlines():
69
+ if line.startswith(("PASS ", "FAIL ", "ERROR ", " SKIP")):
70
+ print(" " + line)
71
+ else:
72
+ tail = "\n".join(out.strip().splitlines()[-40:])
73
+ failed.append((f.name, tail))
74
+ print(f"FAIL {f.name}(exit {r.returncode})")
75
+ shutil.rmtree(tmp, ignore_errors=True)
76
+
77
+ print()
78
+ if failed:
79
+ for name, detail in failed:
80
+ print("=" * 70)
81
+ print(f"失败:{name}")
82
+ print(detail)
83
+ print()
84
+ print(f"{ran - len(failed)}/{ran} 通过,{len(failed)} 个失败")
85
+ return 1
86
+ print(f"{ran}/{ran} 通过")
87
+ return 0
88
+
89
+
90
+ if __name__ == "__main__":
91
+ sys.exit(main(sys.argv[1:]))