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,260 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """P4 灰度 A/B 采样记账(附录 C P4 的最小骨架)。
4
+
5
+ 背景:五段式装配(assembler.plan_from_report)是"预算裁剪版",与现有整段注入
6
+ (legacy)并存。要判断灰度到底省了多少,必须有可比数据:同一份注入包在两种装配下
7
+ 各占多少 token、省了多少比例。本模块只做三件事:
8
+
9
+ record(mode, report, plan) 记一次装配对比:默认关闭;开启后按 sample 采样落盘
10
+ summary(days) 聚合近 N 天样本:样本数、均值/p50/p95 节省比例、按 mode 分组
11
+ context_mode(cfg) 读 config.context_mode(legacy / budgeted),默认 legacy
12
+
13
+ 落盘:~/.brain-memory/metrics.jsonl(与每日 metrics 同文件,用 kind="context_ab" 区分),
14
+ 单文件超过 512KB 自动轮转为 metrics.jsonl.1(思路同 failures.py 的 512KB 轮转)。
15
+
16
+ 约定:
17
+ - 默认 context_ab.enabled=false → 连对比都不算、一个字节都不写,装配路径行为不变;
18
+ - record 本身绝不抛异常(观测代码不能成为故障源),失败返回 None;
19
+ - context_ab.log=false 时只算不落盘(给未来的面板实时对比用);
20
+ - summary 只读、只聚合 A/B 行,不碰每日 metrics 行。
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import math
26
+ import random
27
+ import time
28
+ from pathlib import Path
29
+
30
+ import assembler
31
+
32
+ MAX_BYTES = 512 * 1024 # 单文件上限,超了轮转成 metrics.jsonl.1
33
+ METRICS_NAME = "metrics.jsonl"
34
+ KIND = "context_ab" # 与每日 metrics 行区分的标记字段
35
+ AB_DEFAULTS = {"enabled": False, "sample": 0.1, "log": True}
36
+ VALID_MODES = ("legacy", "budgeted")
37
+
38
+
39
+ # ---------------------------------------------------------------- 路径 / 配置
40
+
41
+ def _home(home=None) -> Path:
42
+ if home:
43
+ return Path(home)
44
+ try:
45
+ import core
46
+ return Path(core.HOME)
47
+ except Exception:
48
+ return Path.home() / ".brain-memory"
49
+
50
+
51
+ def path(home=None) -> Path:
52
+ """A/B 记账落盘路径(默认跟着 core.HOME,测试/--home 可显式指定)。"""
53
+ return _home(home) / METRICS_NAME
54
+
55
+
56
+ def _ab_cfg(cfg: dict | None = None) -> dict:
57
+ """取 context_ab 配置,老 config / 半截配置都按默认值补齐;坏值静默回退。"""
58
+ out = dict(AB_DEFAULTS)
59
+ try:
60
+ if cfg is None:
61
+ import core
62
+ cfg = core.load_config()
63
+ raw = (cfg or {}).get("context_ab")
64
+ if isinstance(raw, dict):
65
+ out.update({k: raw[k] for k in AB_DEFAULTS if k in raw})
66
+ except Exception:
67
+ pass
68
+ out["enabled"] = bool(out.get("enabled"))
69
+ out["log"] = bool(out.get("log", True))
70
+ try:
71
+ out["sample"] = min(1.0, max(0.0, float(out.get("sample", 0.1))))
72
+ except (TypeError, ValueError):
73
+ out["sample"] = 0.1
74
+ return out
75
+
76
+
77
+ def context_mode(cfg: dict | None = None) -> str:
78
+ """当前装配模式(config.context_mode):legacy(默认)/ budgeted;非法值回退 legacy。
79
+
80
+ 灰度期只是把开关读出来;真正按模式装配由后续调用方决定(本任务不改变默认路径)。
81
+ """
82
+ try:
83
+ if cfg is None:
84
+ import core
85
+ cfg = core.load_config()
86
+ mode = str((cfg or {}).get("context_mode") or "legacy").strip().lower()
87
+ except Exception:
88
+ mode = "legacy"
89
+ return mode if mode in VALID_MODES else "legacy"
90
+
91
+
92
+ # ---------------------------------------------------------------- 写记账
93
+
94
+ def _row(mode: str, report: dict, plan: dict, session: str) -> dict:
95
+ """把一次装配的 report + plan 压成一行记账(数字全部来自 compare / plan)。"""
96
+ budget = plan.get("budget") or report.get("budget")
97
+ cmp = assembler.compare(report, budget)
98
+ legacy_tokens = int(report.get("total_tokens") or 0)
99
+ if legacy_tokens <= 0: # 手工构造的 report 可能没填 tokens:按字符/比例兜底
100
+ chars = int(cmp.get("legacy_chars") or 0)
101
+ try:
102
+ ratio = float(report.get("chars_per_token") or 2) or 2.0
103
+ except (TypeError, ValueError):
104
+ ratio = 2.0
105
+ legacy_tokens = int(math.ceil(chars / ratio))
106
+ return {
107
+ "kind": KIND,
108
+ "ts": int(time.time()),
109
+ "session": str(session or "default")[:80],
110
+ "mode": str(mode or "legacy")[:20],
111
+ "legacy_tokens": legacy_tokens,
112
+ "budgeted_tokens": int(plan.get("total_tokens") or 0),
113
+ "saved_pct": float(cmp.get("saved_pct") or 0.0),
114
+ # 下面三个是排障用的附加字段(spec 要求的 6 个字段之外)
115
+ "legacy_chars": int(cmp.get("legacy_chars") or 0),
116
+ "budgeted_chars": int(cmp.get("budgeted_chars") or 0),
117
+ "degraded": list(cmp.get("degraded") or []),
118
+ }
119
+
120
+
121
+ def _append(row: dict, home=None) -> None:
122
+ """追加一行 JSONL;超 512KB 先轮转(思路同 failures.record),写锁复用 core。"""
123
+ p = path(home)
124
+ p.parent.mkdir(parents=True, exist_ok=True)
125
+ try:
126
+ if p.exists() and p.stat().st_size > MAX_BYTES:
127
+ p.replace(p.with_name(p.name + ".1"))
128
+ except OSError:
129
+ pass # 轮转失败不拦记账:顶多文件继续长大
130
+ try:
131
+ import core
132
+ core._append_jsonl(p, row)
133
+ return
134
+ except Exception:
135
+ pass # core 不可用(脱离灵枢环境 import)时退回裸追加
136
+ with open(p, "a", encoding="utf-8", newline="\n") as f:
137
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
138
+
139
+
140
+ def record(mode: str, report: dict, plan: dict, *, session: str = "default",
141
+ home=None, cfg: dict | None = None, force: bool = False) -> dict | None:
142
+ """按采样率记一次装配对比,返回记下的行(log=false 时只算不写);未采样/关闭返回 None。
143
+
144
+ 参数:
145
+ mode "legacy" | "budgeted"(本次装配实际用的模式)
146
+ report memory.build_injection(report=...) 填好的分段账单
147
+ plan assembler.plan(...) / plan_from_report(...) 的装配计划
148
+ force True 时跳过采样(测试/手动补记),仍受 enabled 开关约束
149
+ 任何异常都不外抛:观测账本不能把正常装配带崩。
150
+ """
151
+ try:
152
+ if not isinstance(report, dict) or not isinstance(plan, dict):
153
+ return None
154
+ c = _ab_cfg(cfg)
155
+ if not c["enabled"]:
156
+ return None
157
+ if not force and random.random() >= c["sample"]:
158
+ return None
159
+ row = _row(mode, report, plan, session)
160
+ if c["log"]:
161
+ _append(row, home)
162
+ return row
163
+ except Exception:
164
+ return None
165
+
166
+
167
+ # ---------------------------------------------------------------- 读聚合
168
+
169
+ def _read(home=None) -> list[dict]:
170
+ """读回轮转前后两个文件的所有合法 JSON 行。"""
171
+ p = path(home)
172
+ out: list[dict] = []
173
+ for f in (p.with_name(p.name + ".1"), p):
174
+ try:
175
+ text = f.read_text(encoding="utf-8", errors="replace")
176
+ except OSError:
177
+ continue
178
+ for line in text.splitlines():
179
+ line = line.strip()
180
+ if not line:
181
+ continue
182
+ try:
183
+ obj = json.loads(line)
184
+ except ValueError:
185
+ continue
186
+ if isinstance(obj, dict):
187
+ out.append(obj)
188
+ return out
189
+
190
+
191
+ def _is_ab_row(r: dict) -> bool:
192
+ """过滤出 A/B 行:优先认 kind 标记,兼容手写/旧行时按字段形状识别。"""
193
+ if not isinstance(r, dict):
194
+ return False
195
+ if r.get("kind") == KIND:
196
+ return True
197
+ return ("mode" in r and "legacy_tokens" in r and "saved_pct" in r
198
+ and "date" not in r)
199
+
200
+
201
+ def percentile(values, q: float):
202
+ """线性插值分位数(与 numpy 默认口径一致);空列表返回 None。"""
203
+ vals = sorted(float(v) for v in (values or []))
204
+ if not vals:
205
+ return None
206
+ if len(vals) == 1:
207
+ return round(vals[0], 2)
208
+ q = min(100.0, max(0.0, float(q)))
209
+ pos = (len(vals) - 1) * q / 100.0
210
+ lo = int(math.floor(pos))
211
+ hi = min(lo + 1, len(vals) - 1)
212
+ val = vals[lo] + (vals[hi] - vals[lo]) * (pos - lo)
213
+ return round(val, 2)
214
+
215
+
216
+ def _stats(rows: list[dict]) -> dict:
217
+ """一组样本的节省比例 / token 统计。"""
218
+ pcts = [float(r.get("saved_pct") or 0.0) for r in rows]
219
+ lts = [float(r.get("legacy_tokens") or 0.0) for r in rows]
220
+ bts = [float(r.get("budgeted_tokens") or 0.0) for r in rows]
221
+ n = len(rows)
222
+ return {
223
+ "count": n,
224
+ "mean_saved_pct": round(sum(pcts) / n, 2) if n else None,
225
+ "p50_saved_pct": percentile(pcts, 50),
226
+ "p95_saved_pct": percentile(pcts, 95),
227
+ "mean_legacy_tokens": int(round(sum(lts) / n)) if n else None,
228
+ "mean_budgeted_tokens": int(round(sum(bts) / n)) if n else None,
229
+ }
230
+
231
+
232
+ def summary(days: float = 7, *, home=None, now: float | None = None) -> dict:
233
+ """聚合近 days 天的 A/B 样本:样本数、均值/p50/p95 节省比例、按 mode 分组。
234
+
235
+ 只读:不建目录、不写盘;没有样本时返回 total=0 的空壳(各统计量为 None)。
236
+ """
237
+ now = time.time() if now is None else float(now)
238
+ try:
239
+ window = max(0.0, float(days))
240
+ except (TypeError, ValueError):
241
+ window = 7.0
242
+ since = now - window * 86400
243
+ rows: list[dict] = []
244
+ for r in _read(home):
245
+ if not _is_ab_row(r):
246
+ continue
247
+ try:
248
+ ts = float(r.get("ts") or 0)
249
+ except (TypeError, ValueError):
250
+ continue
251
+ if ts >= since:
252
+ rows.append(r)
253
+ top = _stats(rows)
254
+ modes = sorted({str(r.get("mode") or "legacy") for r in rows})
255
+ top["window_days"] = window
256
+ top["total"] = len(rows)
257
+ top["by_mode"] = {m: _stats([r for r in rows if str(r.get("mode") or "legacy") == m])
258
+ for m in modes}
259
+ top["generated_ts"] = int(now)
260
+ return top