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.
- package/CHANGELOG.md +2605 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4867 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2028 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4417 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""行为基线:record → check(借自 rust-anything 的"每一步都能证明行为没变")。
|
|
3
|
+
|
|
4
|
+
为什么需要
|
|
5
|
+
----------
|
|
6
|
+
拆大模块(`memory.py` / `cli.py` / `growth.py` 都在 4000 行量级)时,现有保障只有
|
|
7
|
+
"测试断言集合不变"。但断言是**抽样**——它能证明测试覆盖到的部分没坏,证明不了
|
|
8
|
+
"同一份输入产出的文本仍然逐字相同"。而灵枢的核心产物恰恰是**文本**(注入包、
|
|
9
|
+
召回结果、日报),一个字变了就是行为变了。
|
|
10
|
+
|
|
11
|
+
rust-anything 的做法值得抄:先把原程序在固定输入上的输出**录下来**(record),
|
|
12
|
+
改造完**重放**(replay)逐字比对,差异为空才算过门(gate)。本文件就是那层。
|
|
13
|
+
|
|
14
|
+
用法
|
|
15
|
+
----
|
|
16
|
+
python scripts/behavior_baseline.py record # 录基线(改造前跑一次)
|
|
17
|
+
python scripts/behavior_baseline.py check # 重放比对(改造后跑)
|
|
18
|
+
python scripts/behavior_baseline.py diff # 只打印差异,不判退出码
|
|
19
|
+
|
|
20
|
+
基线文件 `tests/behavior-baseline.json`:与 `bench-baseline.json` 同处,**不进发布
|
|
21
|
+
manifest**(tests 不进清单),随仓库走即可。
|
|
22
|
+
|
|
23
|
+
为什么能逐字比对:本工具在**临时 HOME** 里用固定的种子数据重建同一个库,所以
|
|
24
|
+
时间戳、随机 id 之外的一切都应当是确定性的。不能确定的部分(时间、id、耗时)
|
|
25
|
+
在 `_normalize()` 里统一抹平成占位符——**抹平要写清楚抹了什么**,否则基线会变成
|
|
26
|
+
"看起来一样"的自欺。
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import argparse
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import re
|
|
34
|
+
import shutil
|
|
35
|
+
import subprocess
|
|
36
|
+
import sys
|
|
37
|
+
import tempfile
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
ROOT = Path(__file__).resolve().parent
|
|
41
|
+
SKILL_ROOT = ROOT.parent
|
|
42
|
+
BASELINE = SKILL_ROOT / "tests" / "behavior-baseline.json"
|
|
43
|
+
|
|
44
|
+
# 固定种子:改这里等于换基线样本,必须重新 record
|
|
45
|
+
SEED_MEMORIES = [
|
|
46
|
+
("约定:提交前必须跑五项发布检查", "preference", 0.9, ["流程", "发布"]),
|
|
47
|
+
("本机 python 是 shim,会吞退出码,验证一律用真解释器", "fact", 0.85, ["环境", "python"]),
|
|
48
|
+
("决策:不做 DiskGenius 文件恢复,别再建议这一步", "preference", 0.8, ["决定"]),
|
|
49
|
+
("洞察:插件异常必须吞掉,否则会回滚会话——所以失败要留痕", "insight", 0.75, ["插件", "设计"]),
|
|
50
|
+
("事件:v3.53 记忆静默停录,根因是找不到 brain.py", "episode", 0.7, ["事故"]),
|
|
51
|
+
("习惯:改完代码先跑 run_tests.py 再谈结论", "habit", 0.6, ["习惯"]),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
QUERIES = ["发布检查", "python 解释器", "插件失败", "插件", ""]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _normalize(text: str) -> str:
|
|
58
|
+
"""把不可确定的部分抹平——**只抹这些**,其余逐字比对。
|
|
59
|
+
|
|
60
|
+
抹平项与理由:
|
|
61
|
+
· 记忆 id(m_<时间戳>_<随机>):时间戳与随机后缀天然每次不同
|
|
62
|
+
· 10 位以上时间戳数字:同上
|
|
63
|
+
· ISO / 本地日期时间:同上
|
|
64
|
+
· 毫秒耗时数字:性能不是本基线的目的(那是 bench.py 的事)
|
|
65
|
+
· 时段描述(下午/夜晚 + 一句节奏说明 + 今天周末):startup 注入会把当前
|
|
66
|
+
真实时段写进去,上午录的基线下午 check 必然不同——它不是被比对的行为,
|
|
67
|
+
只是"现在几点"的投影。抹成 <TOD> 占位符。
|
|
68
|
+
"""
|
|
69
|
+
text = re.sub(r"m_\d{10}_[0-9a-f]{8,}", "m_<ID>", text)
|
|
70
|
+
text = re.sub(r"\b1[6-9]\d{8}\b", "<TS>", text)
|
|
71
|
+
text = re.sub(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?", "<DATETIME>", text)
|
|
72
|
+
text = re.sub(r"\d{4}-\d{2}-\d{2}", "<DATE>", text)
|
|
73
|
+
text = re.sub(r"\b\d+(\.\d+)?\s*(ms|毫秒)\b", "<DUR>", text)
|
|
74
|
+
# 时段描述:`<DATETIME>,下午,正事多在此时(今天周末)。` / `<DATETIME>,深夜(…)——…。`
|
|
75
|
+
# 一律抹到句末句号(时段词后面可能是逗号,也可能是括号,格式随时段而变)。
|
|
76
|
+
text = re.sub(r",(凌晨|早晨|上午|中午|下午|傍晚|夜晚|深夜)[^\n]*?。",
|
|
77
|
+
",<TOD>。", text)
|
|
78
|
+
return text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# 固定种子时间基准:种子记忆的 created 全部由它派生,保证每次 record 都是同一组数值
|
|
82
|
+
SEED_BASE_TS = 1795000000
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _pin_times(home: Path) -> None:
|
|
86
|
+
"""把种子记忆的 created/last_access 钉成**固定且互不相同**的值。
|
|
87
|
+
|
|
88
|
+
为什么必须这么做:注入的「刚刚发生(本会话新增)」段取的是
|
|
89
|
+
`[m for m in _recent40 if created >= last_startup][:4]`——**前 4 条**。种子记忆若是
|
|
90
|
+
同一秒写入,created 全相等,`recent()` 的排序就并列,哪 4 条进入该段取决于
|
|
91
|
+
JSONL 的文件先后(进而受写入顺序/哈希影响),于是同一份库每次产出不同顺序的
|
|
92
|
+
注入包(实测 4 次 check 里 3 次报差异)。
|
|
93
|
+
钉成 base - i*600 之后:时间各不相同、排序唯一,`last_startup` 也写死成中间值,
|
|
94
|
+
切分点每次完全一致。
|
|
95
|
+
"""
|
|
96
|
+
base = SEED_BASE_TS
|
|
97
|
+
for layer in ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl",
|
|
98
|
+
"knowledge.jsonl", "notes.jsonl", "verbatim.jsonl"):
|
|
99
|
+
f = home / layer
|
|
100
|
+
if not f.is_file():
|
|
101
|
+
continue
|
|
102
|
+
rows = []
|
|
103
|
+
for line in f.read_text(encoding="utf-8").splitlines():
|
|
104
|
+
line = line.strip()
|
|
105
|
+
if not line:
|
|
106
|
+
continue
|
|
107
|
+
try:
|
|
108
|
+
rows.append(json.loads(line))
|
|
109
|
+
except Exception:
|
|
110
|
+
continue
|
|
111
|
+
# **只按 text 定序**,不看 created:6 条种子在同一秒内写入时 created 相等,
|
|
112
|
+
# 但只要写入跨过秒边界(实测 1/3 概率),按 created 排序的结果就每次不同,
|
|
113
|
+
# 于是"谁拿到最新时间戳"跟着变、`[:4]` 的切分点也变(实测表现为
|
|
114
|
+
# 「事件」与「习惯」两条在「最近的记忆」和「刚刚发生」之间来回跳)。
|
|
115
|
+
# 文本互不相同,按它排序才是真正稳定的。
|
|
116
|
+
rows.sort(key=lambda m: str(m.get("text") or ""))
|
|
117
|
+
with f.open("w", encoding="utf-8", newline="\n") as fh:
|
|
118
|
+
for i, m in enumerate(rows):
|
|
119
|
+
ts = base - i * 600
|
|
120
|
+
m["created"] = ts
|
|
121
|
+
m["last_access"] = ts
|
|
122
|
+
fh.write(json.dumps(m, ensure_ascii=False) + "\n")
|
|
123
|
+
# last_startup 钉在"第 3 条之后"——稳定地把最新 2 条判为「刚刚发生」
|
|
124
|
+
cfg_path = home / "config.json"
|
|
125
|
+
try:
|
|
126
|
+
cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) if cfg_path.is_file() else {}
|
|
127
|
+
except Exception:
|
|
128
|
+
cfg = {}
|
|
129
|
+
cfg["last_startup"] = {"ts": base - 600 + 1, "query": "baseline"}
|
|
130
|
+
cfg["wake_count"] = 1
|
|
131
|
+
(home).mkdir(parents=True, exist_ok=True)
|
|
132
|
+
cfg_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _seed(home: Path) -> None:
|
|
136
|
+
"""在给定 HOME 里造一份确定性的库(用子进程,避免污染本进程状态)。"""
|
|
137
|
+
code = (
|
|
138
|
+
"import sys; sys.path.insert(0, %r)\n"
|
|
139
|
+
"import core, brain\n"
|
|
140
|
+
"core.HOME = __import__('pathlib').Path(%r)\n"
|
|
141
|
+
"core._sync_state()\n"
|
|
142
|
+
"brain.ensure_home()\n"
|
|
143
|
+
"seeds = %r\n"
|
|
144
|
+
"for text, kind, imp, tags in seeds:\n"
|
|
145
|
+
" brain.remember(text, kind=kind, importance=imp, tags=tags)\n"
|
|
146
|
+
"print('seeded', len(seeds))\n"
|
|
147
|
+
) % (str(ROOT), str(home), SEED_MEMORIES)
|
|
148
|
+
env = dict(os.environ, BRAIN_MEMORY_HOME=str(home), PYTHONIOENCODING="utf-8",
|
|
149
|
+
PYTHONHASHSEED="0")
|
|
150
|
+
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
|
|
151
|
+
encoding="utf-8", errors="replace", env=env, timeout=300)
|
|
152
|
+
if r.returncode != 0:
|
|
153
|
+
raise SystemExit(f"[错误] 造种子库失败:{r.stderr[:400]}")
|
|
154
|
+
_pin_times(home)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _capture(home: Path) -> dict:
|
|
158
|
+
"""在给定 HOME 上采集所有"文本类输出"的快照。"""
|
|
159
|
+
code = (
|
|
160
|
+
"import json, sys; sys.path.insert(0, %r)\n"
|
|
161
|
+
"import core, brain, memory\n"
|
|
162
|
+
"core.HOME = __import__('pathlib').Path(%r)\n"
|
|
163
|
+
"core._sync_state()\n"
|
|
164
|
+
"out = {}\n"
|
|
165
|
+
"out['injection'] = memory.build_injection('')\n"
|
|
166
|
+
"for q in %r:\n"
|
|
167
|
+
" out['recall:' + q] = memory.build_injection(q)\n"
|
|
168
|
+
"out['recall_json'] = json.dumps(\n"
|
|
169
|
+
" [ {k: m.get(k) for k in ('kind','text','importance','tags')}\n"
|
|
170
|
+
" for m in sorted(brain.load_all(), key=lambda x: str(x.get('text'))) ],\n"
|
|
171
|
+
" ensure_ascii=False, sort_keys=True)\n"
|
|
172
|
+
"print(json.dumps(out, ensure_ascii=False))\n"
|
|
173
|
+
) % (str(ROOT), str(home), QUERIES)
|
|
174
|
+
env = dict(os.environ, BRAIN_MEMORY_HOME=str(home), PYTHONIOENCODING="utf-8",
|
|
175
|
+
# 固定哈希种子:recall 内部用 set 收集命中/实体/标签,集合遍历顺序随
|
|
176
|
+
# 字符串哈希随机化而变,会让"同一份库"产出不同顺序的注入包(实测:
|
|
177
|
+
# 4 次采集指纹全一致 vs 不固定时 1/3 概率不同)。这不是产品行为差异,
|
|
178
|
+
# 是解释器级别的随机化——比对金标准文本的工具必须把它钉住。
|
|
179
|
+
PYTHONHASHSEED="0")
|
|
180
|
+
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
|
|
181
|
+
encoding="utf-8", errors="replace", env=env, timeout=300)
|
|
182
|
+
if r.returncode != 0:
|
|
183
|
+
raise SystemExit(f"[错误] 采集行为快照失败:{r.stderr[:400]}")
|
|
184
|
+
raw = json.loads(r.stdout)
|
|
185
|
+
return {k: _normalize(v) for k, v in raw.items()}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _fresh_capture() -> dict:
|
|
189
|
+
"""新 HOME → 造种子 → 采集。每次都用全新临时目录,保证同样输入同样输出。"""
|
|
190
|
+
home = Path(tempfile.mkdtemp(prefix="ls-behavior-"))
|
|
191
|
+
try:
|
|
192
|
+
_seed(home)
|
|
193
|
+
return _capture(home)
|
|
194
|
+
finally:
|
|
195
|
+
shutil.rmtree(home, ignore_errors=True)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def record(quiet: bool = False) -> int:
|
|
199
|
+
snap = _fresh_capture()
|
|
200
|
+
BASELINE.parent.mkdir(parents=True, exist_ok=True)
|
|
201
|
+
BASELINE.write_text(json.dumps({"version": 1, "snapshot": snap},
|
|
202
|
+
ensure_ascii=False, indent=2, sort_keys=True) + "\n",
|
|
203
|
+
encoding="utf-8")
|
|
204
|
+
if not quiet:
|
|
205
|
+
total = sum(len(v) for v in snap.values())
|
|
206
|
+
print(f"[record] 基线已保存:{BASELINE}")
|
|
207
|
+
print(f"[record] 采集 {len(snap)} 个输出,共 {total} 字符(已抹平 id/时间/耗时)")
|
|
208
|
+
return 0
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _diff(old: dict, new: dict) -> list[str]:
|
|
212
|
+
"""逐 key、逐行比对;返回人可读的差异清单。"""
|
|
213
|
+
diffs: list[str] = []
|
|
214
|
+
for key in sorted(set(old) | set(new)):
|
|
215
|
+
a, b = old.get(key), new.get(key)
|
|
216
|
+
if a == b:
|
|
217
|
+
continue
|
|
218
|
+
if a is None or b is None:
|
|
219
|
+
diffs.append(f"[{key}] 该输出{'消失' if b is None else '新增'}")
|
|
220
|
+
continue
|
|
221
|
+
al, bl = a.splitlines(), b.splitlines()
|
|
222
|
+
for i in range(max(len(al), len(bl))):
|
|
223
|
+
x = al[i] if i < len(al) else "<缺失>"
|
|
224
|
+
y = bl[i] if i < len(bl) else "<缺失>"
|
|
225
|
+
if x != y:
|
|
226
|
+
diffs.append(f"[{key}] 第 {i + 1} 行\n - {x[:160]}\n + {y[:160]}")
|
|
227
|
+
if len(diffs) >= 40:
|
|
228
|
+
diffs.append("…(差异过多,已截断)")
|
|
229
|
+
return diffs
|
|
230
|
+
return diffs
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def check(quiet: bool = False) -> int:
|
|
234
|
+
if not BASELINE.is_file():
|
|
235
|
+
print(f"[错误] 没有基线:{BASELINE}(先跑 record)", file=sys.stderr)
|
|
236
|
+
return 2
|
|
237
|
+
old = json.loads(BASELINE.read_text(encoding="utf-8"))["snapshot"]
|
|
238
|
+
new = _fresh_capture()
|
|
239
|
+
diffs = _diff(old, new)
|
|
240
|
+
if not diffs:
|
|
241
|
+
if not quiet:
|
|
242
|
+
print(f"[check] OK:{len(new)} 个输出与基线逐字一致")
|
|
243
|
+
return 0
|
|
244
|
+
print(f"[check] 行为变了:{len(diffs)} 处差异", file=sys.stderr)
|
|
245
|
+
for d in diffs:
|
|
246
|
+
print(" " + d, file=sys.stderr)
|
|
247
|
+
print("\n如果这是**有意**的行为变更:跑 record 重录基线,并在提交信息里写明为什么变。",
|
|
248
|
+
file=sys.stderr)
|
|
249
|
+
return 1
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def diff_only() -> int:
|
|
253
|
+
if not BASELINE.is_file():
|
|
254
|
+
print(f"[错误] 没有基线:{BASELINE}", file=sys.stderr)
|
|
255
|
+
return 2
|
|
256
|
+
old = json.loads(BASELINE.read_text(encoding="utf-8"))["snapshot"]
|
|
257
|
+
new = _fresh_capture()
|
|
258
|
+
diffs = _diff(old, new)
|
|
259
|
+
if not diffs:
|
|
260
|
+
print("[diff] 无差异")
|
|
261
|
+
return 0
|
|
262
|
+
for d in diffs:
|
|
263
|
+
print(" " + d)
|
|
264
|
+
return 0
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def main(argv: list[str]) -> int:
|
|
268
|
+
ap = argparse.ArgumentParser(description="行为基线:逐字比对改造前后输出")
|
|
269
|
+
ap.add_argument("action", nargs="?", default="check", choices=("record", "check", "diff"))
|
|
270
|
+
ap.add_argument("-q", "--quiet", action="store_true")
|
|
271
|
+
a = ap.parse_args(argv)
|
|
272
|
+
if a.action == "record":
|
|
273
|
+
return record(a.quiet)
|
|
274
|
+
if a.action == "diff":
|
|
275
|
+
return diff_only()
|
|
276
|
+
return check(a.quiet)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
if __name__ == "__main__":
|
|
280
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 —— 性能基准(第四轮提案 #5)。
|
|
4
|
+
|
|
5
|
+
生成 N 条合成记忆到**临时隔离 HOME**(绝不碰真实记忆库),量四条主路径的
|
|
6
|
+
p50/p95 耗时,回答"5000 条时还快不快"这类问题——改召回阈值/换 embed 兜底
|
|
7
|
+
前后各跑一次,用数字代替手感。
|
|
8
|
+
|
|
9
|
+
用法:
|
|
10
|
+
python scripts/bench.py # 默认 1000 条,常规套件
|
|
11
|
+
python scripts/bench.py --n 5000 # 大库压力
|
|
12
|
+
python scripts/bench.py --quick # 300 条,1 分钟内出结果
|
|
13
|
+
python scripts/bench.py --quick --save # 把本次 p50/p95 存成基线
|
|
14
|
+
python scripts/bench.py --quick --check # 与基线比对,超 1.5 倍即失败
|
|
15
|
+
|
|
16
|
+
零依赖,纯标准库。退出码 0=全部完成;--check 超阈值退出 1。
|
|
17
|
+
基线文件放 tests/bench-baseline.json(tests 不进发布 manifest,随仓库走)。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import random
|
|
25
|
+
import shutil
|
|
26
|
+
import statistics
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import tempfile
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
ROOT = Path(__file__).resolve().parent
|
|
34
|
+
BRAIN = ROOT / "brain.py"
|
|
35
|
+
BASELINE = ROOT.parent / "tests" / "bench-baseline.json"
|
|
36
|
+
CHECK_RATIO = 1.5
|
|
37
|
+
|
|
38
|
+
TOPICS = ["部署", "数据库", "前端", "算法", "会议", "测试", "文档", "安全",
|
|
39
|
+
"缓存", "权限", "日志", "重构", "网络", "备份", "监控", "配置"]
|
|
40
|
+
USERS = ["alice", "bob", "carol"]
|
|
41
|
+
PROJECTS = ["proj-alpha", "proj-beta", "proj-gamma"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _run(args: list, home: Path, timeout: float = 120, strict: bool = True) -> tuple[float, str]:
|
|
45
|
+
"""跑一次 brain.py 子进程,返回 (耗时秒, stdout)。strict=False 时不校验退出码。"""
|
|
46
|
+
env = {**__import__("os").environ,
|
|
47
|
+
"BRAIN_MEMORY_HOME": str(home),
|
|
48
|
+
"BRAIN_MEMORY_BACKUP_DIR": str(home / "backups")}
|
|
49
|
+
t0 = time.perf_counter()
|
|
50
|
+
r = subprocess.run([sys.executable, str(BRAIN), *args],
|
|
51
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
|
52
|
+
dt = time.perf_counter() - t0
|
|
53
|
+
if strict and r.returncode not in (0,):
|
|
54
|
+
raise RuntimeError(f"brain.py {' '.join(args)} 退出码 {r.returncode}: {r.stderr[-300:]}")
|
|
55
|
+
return dt, r.stdout
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _pctl(samples: list) -> dict:
|
|
59
|
+
"""p50 / p95(样本少时 p95 就是最大值近似)。"""
|
|
60
|
+
xs = sorted(samples)
|
|
61
|
+
n = len(xs)
|
|
62
|
+
return {"p50": statistics.median(xs),
|
|
63
|
+
"p95": xs[max(0, int(round(n * 0.95)) - 1)] if n else 0.0,
|
|
64
|
+
"n": n}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _save_baseline(n: int, results: dict) -> None:
|
|
68
|
+
"""把本次 p50/p95 写成基线(同机同 n 的后续 --check 用它比对)。"""
|
|
69
|
+
data = {"n": n, "generated": time.strftime("%Y-%m-%d %H:%M"),
|
|
70
|
+
"results": {k: _pctl(v) for k, v in results.items() if v}}
|
|
71
|
+
BASELINE.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
BASELINE.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
|
73
|
+
encoding="utf-8")
|
|
74
|
+
print(f"[bench] 基线已保存:{BASELINE}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _check_baseline(n: int, results: dict) -> int:
|
|
78
|
+
"""与基线比对 p50;超过 CHECK_RATIO 倍告警并返回 1。
|
|
79
|
+
|
|
80
|
+
不同 n / 不同机器之间绝对值不可比,所以只做"同机回归"的粗门禁;
|
|
81
|
+
没有基线文件时直接放行(首次接入不阻塞)。
|
|
82
|
+
"""
|
|
83
|
+
if not BASELINE.is_file():
|
|
84
|
+
print(f"[bench] 未找到基线 {BASELINE},跳过比对(先跑一次 --save)")
|
|
85
|
+
return 0
|
|
86
|
+
try:
|
|
87
|
+
base = json.loads(BASELINE.read_text(encoding="utf-8-sig"))
|
|
88
|
+
except (OSError, ValueError) as e:
|
|
89
|
+
print(f"[bench] 基线读取失败({e}),跳过比对")
|
|
90
|
+
return 0
|
|
91
|
+
base_res = base.get("results") or {}
|
|
92
|
+
if int(base.get("n") or 0) != n:
|
|
93
|
+
print(f"[bench] 基线 n={base.get('n')} 与本轮 n={n} 不同,仅打印不判定")
|
|
94
|
+
worst = 0
|
|
95
|
+
print("\n===== 与基线比对(阈值 ×{:.1f})=====".format(CHECK_RATIO))
|
|
96
|
+
for name, samples in results.items():
|
|
97
|
+
if not samples or name not in base_res:
|
|
98
|
+
continue
|
|
99
|
+
cur = _pctl(samples)["p50"]
|
|
100
|
+
old = float(base_res[name].get("p50") or 0)
|
|
101
|
+
if old <= 0:
|
|
102
|
+
continue
|
|
103
|
+
ratio = cur / old
|
|
104
|
+
flag = "WARN" if ratio > CHECK_RATIO else "ok"
|
|
105
|
+
print(f"{name:<10} 基线 {old*1000:7.0f} ms → 本次 {cur*1000:7.0f} ms ×{ratio:.2f} [{flag}]")
|
|
106
|
+
if ratio > CHECK_RATIO:
|
|
107
|
+
worst = 1
|
|
108
|
+
return worst
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main() -> int:
|
|
113
|
+
ap = argparse.ArgumentParser(description="灵枢性能基准(隔离临时库,不碰真实数据)")
|
|
114
|
+
ap.add_argument("--n", type=int, default=1000, help="合成记忆条数(默认 1000)")
|
|
115
|
+
ap.add_argument("--quick", action="store_true", help="快速模式:n=300")
|
|
116
|
+
ap.add_argument("--keep", action="store_true", help="保留临时库(调试用)")
|
|
117
|
+
ap.add_argument("--save", action="store_true", help="把本次结果存为基线")
|
|
118
|
+
ap.add_argument("--check", action="store_true", help="与基线比对,超 1.5 倍退出 1")
|
|
119
|
+
opts = ap.parse_args()
|
|
120
|
+
if opts.quick:
|
|
121
|
+
opts.n = min(opts.n, 300)
|
|
122
|
+
|
|
123
|
+
home = Path(tempfile.mkdtemp(prefix="lingshu-bench-"))
|
|
124
|
+
print(f"[bench] 隔离 HOME:{home}")
|
|
125
|
+
rng = random.Random(20261115)
|
|
126
|
+
|
|
127
|
+
results: dict[str, list] = {"remember": [], "recall": [], "inject": [], "doctor": []}
|
|
128
|
+
try:
|
|
129
|
+
# 0. 初始化
|
|
130
|
+
_run(["init"], home)
|
|
131
|
+
|
|
132
|
+
# 1. 写入基准:批量 remember(每条一个子进程也量得到真实端到端成本)
|
|
133
|
+
print(f"[bench] 生成 {opts.n} 条合成记忆…")
|
|
134
|
+
t0 = time.perf_counter()
|
|
135
|
+
for i in range(opts.n):
|
|
136
|
+
topic = TOPICS[i % len(TOPICS)]
|
|
137
|
+
text = (f"{topic}方案第{i}条:{rng.choice(['决定', '发现', '总结'])}"
|
|
138
|
+
f"{topic}相关做法{rng.randint(1, 999)},注意版本{rng.randint(1, 9)}")
|
|
139
|
+
_run(["remember", text, "--kind", "fact", "--importance",
|
|
140
|
+
str(rng.choice([0.4, 0.5, 0.7, 0.7, 0.8, 0.9])),
|
|
141
|
+
"--project", PROJECTS[i % len(PROJECTS)]], home, timeout=60)
|
|
142
|
+
results["remember"].append(time.perf_counter() - t0)
|
|
143
|
+
t0 = time.perf_counter()
|
|
144
|
+
# 批量写完后再补几条批量型写入:单条走 --importance 的解析已覆盖,
|
|
145
|
+
# 这里换 fast 路径量小查询延迟基线(在空查询上测意义不大,略)。
|
|
146
|
+
|
|
147
|
+
# 2. 召回基准:混合 fast/deep 模式查询
|
|
148
|
+
for i in range(20):
|
|
149
|
+
q = rng.choice(TOPICS) + rng.choice(["方案", "做法", "决定"])
|
|
150
|
+
dt, _ = _run(["recall", q, "--k", "8"], home, timeout=60)
|
|
151
|
+
results["recall"].append(dt)
|
|
152
|
+
# 同项目召回(第四轮#3 加成路径)
|
|
153
|
+
for i in range(5):
|
|
154
|
+
dt, _ = _run(["recall", "方案做法", "--k", "8",
|
|
155
|
+
"--project", rng.choice(PROJECTS)], home, timeout=60)
|
|
156
|
+
results["recall"].append(dt)
|
|
157
|
+
|
|
158
|
+
# 3. 注入基准:build_injection 主路径(空 query = 无定向注入)
|
|
159
|
+
for i in range(10):
|
|
160
|
+
dt, _ = _run(["inject", "--budget", "2000", ""], home, timeout=60)
|
|
161
|
+
results["inject"].append(dt)
|
|
162
|
+
|
|
163
|
+
# 4. 体检基准:doctor 全检查(含 engine-sync 子进程)——隔离 HOME 下
|
|
164
|
+
# engine-sync 等检查项可能报 FAIL/WARN 属预期(退出码 2),只量耗时
|
|
165
|
+
dt, _ = _run(["doctor"], home, timeout=120, strict=False)
|
|
166
|
+
results["doctor"].append(dt)
|
|
167
|
+
|
|
168
|
+
# 报告
|
|
169
|
+
print("\n===== 灵枢性能基准结果 =====")
|
|
170
|
+
print(f"库规模:{opts.n} 条合成记忆 | 隔离 HOME:{home if opts.keep else '(已清理)'}")
|
|
171
|
+
for name, samples in results.items():
|
|
172
|
+
if not samples:
|
|
173
|
+
continue
|
|
174
|
+
p = _pctl(samples)
|
|
175
|
+
print(f"{name:<10} n={p['n']:>3} p50={p['p50']*1000:8.0f} ms "
|
|
176
|
+
f"p95={p['p95']*1000:8.0f} ms")
|
|
177
|
+
print("说明:单次调用含 Python 启动 ~100ms 基线;关注相对变化而非绝对值。")
|
|
178
|
+
if opts.save:
|
|
179
|
+
_save_baseline(opts.n, results)
|
|
180
|
+
if opts.check:
|
|
181
|
+
return _check_baseline(opts.n, results)
|
|
182
|
+
return 0
|
|
183
|
+
except Exception as e:
|
|
184
|
+
print(f"[bench] 失败:{e}", file=sys.stderr)
|
|
185
|
+
return 1
|
|
186
|
+
finally:
|
|
187
|
+
if not opts.keep:
|
|
188
|
+
shutil.rmtree(home, ignore_errors=True)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__":
|
|
192
|
+
sys.exit(main())
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 —— 类脑记忆引擎入口。
|
|
4
|
+
|
|
5
|
+
v2.22 起实现按领域拆到同目录的 core/memory/emotion/persona/dream/cli:
|
|
6
|
+
本文件只做命名空间合并与 re-export,保证 `python scripts/brain.py <子命令>`
|
|
7
|
+
以及外部 `import brain` 的全部旧名字照旧可用。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
import core
|
|
15
|
+
import memory
|
|
16
|
+
import emotion
|
|
17
|
+
import persona
|
|
18
|
+
import dream
|
|
19
|
+
import cli
|
|
20
|
+
|
|
21
|
+
_MODULES = (core, memory, emotion, persona, dream, cli)
|
|
22
|
+
|
|
23
|
+
# 拆分前所有函数共用同一个模块命名空间,靠名字互相调用。拆分后先把各模块命名空间
|
|
24
|
+
# 合并进本模块,再原样回灌给每个子模块——跨模块调用仍按名字解析(过渡桥,
|
|
25
|
+
# 以后可以逐步改成显式 import,但不影响命令行兼容)。
|
|
26
|
+
for _m in _MODULES:
|
|
27
|
+
globals().update({k: v for k, v in _m.__dict__.items() if not k.startswith("__")})
|
|
28
|
+
|
|
29
|
+
for _m in _MODULES:
|
|
30
|
+
_m.__dict__.update({k: v for k, v in globals().items() if not k.startswith("__")})
|
|
31
|
+
|
|
32
|
+
# --home / --ro 会改 core 里的 HOME/READONLY;登记同步目标后,派生路径与只读状态
|
|
33
|
+
# 都会在切换时同步到所有子模块(原先单文件时天然共享,拆分后不会)。
|
|
34
|
+
# brain 模块自身也要登记:panels 等扩展模块 import 的是 brain.HOME,
|
|
35
|
+
# 漏掉自己会让 --home 切换后 brain.HOME 仍是旧目录(core 已换、brain 没换)。
|
|
36
|
+
core._SYNC_TARGETS = [sys.modules[__name__], *list(_MODULES)]
|
|
37
|
+
core._sync_state()
|
|
38
|
+
core._recompute_paths()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def main(argv=None) -> int:
|
|
42
|
+
return cli.main(argv)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
sys.exit(main())
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""水位阈值双份默认值一致性检查(P6 #28)。
|
|
4
|
+
|
|
5
|
+
core.py 的 PRESSURE_DEFAULTS 与 lingshu-cron/plugin.js 的同名常量是两份默认值
|
|
6
|
+
(config.json 的 pressure 段可覆盖两边,所以只有"改默认值忘改另一边"才是风险)。
|
|
7
|
+
本检查从两处源码各解析一份字面量,不一致就 exit=1,让"改一处忘另一处"在提交前
|
|
8
|
+
被拦住,而不是等用户发现提示档位与实际执行档位错位。
|
|
9
|
+
|
|
10
|
+
用法:python scripts/check_pressure_sync.py
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
19
|
+
PY_FILE = ROOT / "scripts" / "core.py"
|
|
20
|
+
JS_FILE = ROOT / "cordis-plugin" / "lingshu-cron" / "plugin.js"
|
|
21
|
+
KEYS = ("lazy_at", "minimal_at", "hard_at", "force_at")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _parse_py() -> dict:
|
|
25
|
+
m = re.search(r"PRESSURE_DEFAULTS\s*=\s*\{([^}]*)\}", PY_FILE.read_text(encoding="utf-8"))
|
|
26
|
+
if not m:
|
|
27
|
+
raise SystemExit("[压力阈值检查] core.py 未找到 PRESSURE_DEFAULTS 字面量")
|
|
28
|
+
return {k: int(v) for k, v in re.findall(r'["\']?(\w+)["\']?\s*:\s*(\d+)', m.group(1))}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _parse_js() -> dict:
|
|
32
|
+
m = re.search(r"const PRESSURE_DEFAULTS\s*=\s*\{([^}]*)\}", JS_FILE.read_text(encoding="utf-8"))
|
|
33
|
+
if not m:
|
|
34
|
+
raise SystemExit("[压力阈值检查] plugin.js 未找到 PRESSURE_DEFAULTS 字面量")
|
|
35
|
+
return {k: int(v) for k, v in re.findall(r'["\']?(\w+)["\']?\s*:\s*(\d+)', m.group(1))}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main() -> int:
|
|
39
|
+
py, js = _parse_py(), _parse_js()
|
|
40
|
+
bad = []
|
|
41
|
+
for k in KEYS:
|
|
42
|
+
a, b = py.get(k), js.get(k)
|
|
43
|
+
if a != b:
|
|
44
|
+
bad.append(f"{k}: core.py={a} / plugin.js={b}")
|
|
45
|
+
if bad:
|
|
46
|
+
print("[压力阈值检查] 不一致(两边默认值必须相同,或同步改 config 的 pressure 段):")
|
|
47
|
+
for line in bad:
|
|
48
|
+
print(" - " + line)
|
|
49
|
+
return 1
|
|
50
|
+
print(f"[压力阈值检查] OK:{', '.join(f'{k}={py[k]}' for k in KEYS)}")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
if __name__ == "__main__":
|
|
55
|
+
sys.exit(main())
|