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.
- package/CHANGELOG.md +2571 -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 +802 -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 +2571 -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 +4850 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2025 -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 +4352 -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 +4850 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2025 -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 +4352 -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,228 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""跨会话原文检索服务(附录 B · P0 的最小实现)。
|
|
4
|
+
|
|
5
|
+
零依赖:sqlite3 + FTS5 trigram(中文子串可查)。职责很窄:
|
|
6
|
+
init 建库建表
|
|
7
|
+
ingest 把对话 JSONL 增量写进原文库(按内容哈希幂等)
|
|
8
|
+
search FTS 检索(返回 id/session/role/ts/text;可按 platform/workspace 过滤)
|
|
9
|
+
serve 本地 HTTP:POST /v1/search(附录 B 契约),GET /health
|
|
10
|
+
|
|
11
|
+
刻意不做:向量、模型挑选。多平台导入由 `session_import.py` 负责(P1),
|
|
12
|
+
本模块只提供写入/检索/统计的窄接口,让 `retriever` 的 session-rag 分支
|
|
13
|
+
有个真服务可连。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import sqlite3
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
SCHEMA = """
|
|
23
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
24
|
+
id TEXT PRIMARY KEY,
|
|
25
|
+
session TEXT NOT NULL,
|
|
26
|
+
platform TEXT DEFAULT '',
|
|
27
|
+
workspace TEXT DEFAULT '',
|
|
28
|
+
role TEXT DEFAULT '',
|
|
29
|
+
ts REAL DEFAULT 0,
|
|
30
|
+
text TEXT NOT NULL
|
|
31
|
+
);
|
|
32
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
|
|
33
|
+
text, content='messages', content_rowid='rowid', tokenize='trigram'
|
|
34
|
+
);
|
|
35
|
+
CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
|
|
36
|
+
INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text);
|
|
37
|
+
END;
|
|
38
|
+
CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
|
|
39
|
+
INSERT INTO messages_fts(messages_fts, rowid, text) VALUES('delete', old.rowid, old.text);
|
|
40
|
+
END;
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def db_path(home=None) -> Path:
|
|
45
|
+
try:
|
|
46
|
+
import core
|
|
47
|
+
base = Path(home or core.HOME)
|
|
48
|
+
except Exception:
|
|
49
|
+
base = Path(home or (Path.home() / ".brain-memory"))
|
|
50
|
+
return base / "session_rag.db"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def connect(path=None) -> sqlite3.Connection:
|
|
54
|
+
p = Path(path) if path else db_path()
|
|
55
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
conn = sqlite3.connect(str(p))
|
|
57
|
+
conn.row_factory = sqlite3.Row
|
|
58
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
59
|
+
return conn
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def init_db(path=None) -> dict:
|
|
63
|
+
with connect(path) as conn:
|
|
64
|
+
conn.executescript(SCHEMA)
|
|
65
|
+
rows = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
|
|
66
|
+
return {"ok": True, "path": str(path or db_path()), "messages": rows}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _msg_id(session: str, role: str, ts: float, text: str) -> str:
|
|
70
|
+
raw = f"{session}|{role}|{ts}|{text}".encode("utf-8")
|
|
71
|
+
return "sr_" + hashlib.sha256(raw).hexdigest()[:24]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def ingest_messages(rows, *, session: str = "default", platform: str = "",
|
|
75
|
+
workspace: str = "", path=None) -> dict:
|
|
76
|
+
"""rows: [{"role","content"/"text","ts"}];按内容哈希幂等。"""
|
|
77
|
+
added = skipped = 0
|
|
78
|
+
with connect(path) as conn:
|
|
79
|
+
conn.executescript(SCHEMA)
|
|
80
|
+
for r in rows or []:
|
|
81
|
+
if not isinstance(r, dict):
|
|
82
|
+
continue
|
|
83
|
+
text = r.get("content", r.get("text", ""))
|
|
84
|
+
if isinstance(text, list):
|
|
85
|
+
text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
|
|
86
|
+
text = str(text or "").strip()
|
|
87
|
+
if not text:
|
|
88
|
+
skipped += 1
|
|
89
|
+
continue
|
|
90
|
+
role = str(r.get("role") or "other").lower()
|
|
91
|
+
ts = float(r.get("ts") or r.get("created") or 0)
|
|
92
|
+
mid = _msg_id(session, role, ts, text)
|
|
93
|
+
try:
|
|
94
|
+
conn.execute(
|
|
95
|
+
"INSERT INTO messages(id, session, platform, workspace, role, ts, text)"
|
|
96
|
+
" VALUES (?,?,?,?,?,?,?)",
|
|
97
|
+
(mid, session, platform, workspace, role, ts, text))
|
|
98
|
+
added += 1
|
|
99
|
+
except sqlite3.IntegrityError:
|
|
100
|
+
skipped += 1
|
|
101
|
+
conn.commit()
|
|
102
|
+
total = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
|
|
103
|
+
return {"ok": True, "added": added, "skipped": skipped, "total": total}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def ingest_jsonl(file, *, session: str = "", platform: str = "", workspace: str = "",
|
|
107
|
+
path=None) -> dict:
|
|
108
|
+
p = Path(file)
|
|
109
|
+
rows = []
|
|
110
|
+
for line in p.read_text(encoding="utf-8-sig", errors="replace").splitlines():
|
|
111
|
+
line = line.strip()
|
|
112
|
+
if not line:
|
|
113
|
+
continue
|
|
114
|
+
try:
|
|
115
|
+
rows.append(json.loads(line))
|
|
116
|
+
except ValueError:
|
|
117
|
+
continue
|
|
118
|
+
return ingest_messages(rows, session=session or p.stem, platform=platform,
|
|
119
|
+
workspace=workspace, path=path)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _scope_clauses(*, workspace=None, platform=None,
|
|
123
|
+
prefix: str = "") -> tuple[str, list]:
|
|
124
|
+
"""构造 platform/workspace 过滤的 SQL 片段(参数化;None/空串 = 不过滤)。"""
|
|
125
|
+
clauses: list[str] = []
|
|
126
|
+
params: list = []
|
|
127
|
+
if platform not in (None, ""):
|
|
128
|
+
clauses.append(f"{prefix}platform = ?")
|
|
129
|
+
params.append(str(platform))
|
|
130
|
+
if workspace not in (None, ""):
|
|
131
|
+
clauses.append(f"{prefix}workspace = ?")
|
|
132
|
+
params.append(str(workspace))
|
|
133
|
+
if not clauses:
|
|
134
|
+
return "", params
|
|
135
|
+
return " AND " + " AND ".join(clauses), params
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def search(query: str, k: int = 10, *, path=None, workspace=None,
|
|
139
|
+
platform=None) -> list[dict]:
|
|
140
|
+
"""FTS/LIKE 检索;workspace/platform 为可选精确过滤,缺省不过滤(保持旧行为)。"""
|
|
141
|
+
q = str(query or "").strip()
|
|
142
|
+
if not q:
|
|
143
|
+
return []
|
|
144
|
+
limit = max(1, int(k))
|
|
145
|
+
with connect(path) as conn:
|
|
146
|
+
conn.executescript(SCHEMA)
|
|
147
|
+
# FTS5 trigram 只对 ≥3 字符的词元建索引:中文两字词("云南")MATCH 不到,
|
|
148
|
+
# 短查询走 LIKE 兜底(200k 条内可接受;更长的词仍走 FTS 排序)。
|
|
149
|
+
if len(q) < 3:
|
|
150
|
+
scope, scope_params = _scope_clauses(workspace=workspace, platform=platform)
|
|
151
|
+
rows = conn.execute(
|
|
152
|
+
"SELECT id, session, platform, workspace, role, ts, text, 0.0 AS score"
|
|
153
|
+
f" FROM messages WHERE text LIKE ?{scope} ORDER BY ts DESC LIMIT ?",
|
|
154
|
+
[f"%{q}%", *scope_params, limit]).fetchall()
|
|
155
|
+
return [{"id": r["id"], "session": r["session"], "platform": r["platform"],
|
|
156
|
+
"workspace": r["workspace"], "role": r["role"], "ts": r["ts"],
|
|
157
|
+
"text": r["text"], "score": float(r["score"] or 0.0)} for r in rows]
|
|
158
|
+
try:
|
|
159
|
+
scope, scope_params = _scope_clauses(workspace=workspace, platform=platform,
|
|
160
|
+
prefix="m.")
|
|
161
|
+
rows = conn.execute(
|
|
162
|
+
"SELECT m.id, m.session, m.platform, m.workspace, m.role, m.ts, m.text,"
|
|
163
|
+
" bm25(messages_fts) AS score"
|
|
164
|
+
" FROM messages_fts JOIN messages m ON m.rowid = messages_fts.rowid"
|
|
165
|
+
f" WHERE messages_fts MATCH ?{scope} ORDER BY score LIMIT ?",
|
|
166
|
+
[q, *scope_params, limit]).fetchall()
|
|
167
|
+
except sqlite3.OperationalError as exc:
|
|
168
|
+
try:
|
|
169
|
+
import failures
|
|
170
|
+
failures.record("session_rag.search", f"{type(exc).__name__}: {exc}",
|
|
171
|
+
ctx={"q": q})
|
|
172
|
+
except Exception:
|
|
173
|
+
pass
|
|
174
|
+
return []
|
|
175
|
+
return [{"id": r["id"], "session": r["session"], "platform": r["platform"],
|
|
176
|
+
"workspace": r["workspace"], "role": r["role"], "ts": r["ts"],
|
|
177
|
+
"text": r["text"], "score": float(r["score"] or 0.0)} for r in rows]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def stats(path=None) -> dict:
|
|
181
|
+
"""库概览:总数 + 按 platform/workspace 分组计数(P1 多平台/多工作区可见性)。"""
|
|
182
|
+
with connect(path) as conn:
|
|
183
|
+
conn.executescript(SCHEMA)
|
|
184
|
+
n = conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]
|
|
185
|
+
sess = conn.execute("SELECT count(DISTINCT session) AS n FROM messages").fetchone()["n"]
|
|
186
|
+
by_platform = {str(r["platform"] or ""): r["n"] for r in conn.execute(
|
|
187
|
+
"SELECT platform, count(*) AS n FROM messages GROUP BY platform ORDER BY n DESC")}
|
|
188
|
+
by_workspace = {str(r["workspace"] or ""): r["n"] for r in conn.execute(
|
|
189
|
+
"SELECT workspace, count(*) AS n FROM messages GROUP BY workspace ORDER BY n DESC")}
|
|
190
|
+
return {"messages": n, "sessions": sess, "path": str(path or db_path()),
|
|
191
|
+
"by_platform": by_platform, "by_workspace": by_workspace}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def serve(host: str = "127.0.0.1", port: int = 8791, *, path=None) -> None:
|
|
195
|
+
"""极简 HTTP:POST /v1/search {"query","k"}、GET /health。仅本机。"""
|
|
196
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
197
|
+
|
|
198
|
+
class H(BaseHTTPRequestHandler):
|
|
199
|
+
def log_message(self, *a): # 静默
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
def _json(self, obj, code=200):
|
|
203
|
+
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
|
204
|
+
self.send_response(code)
|
|
205
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
206
|
+
self.send_header("Content-Length", str(len(body)))
|
|
207
|
+
self.end_headers()
|
|
208
|
+
self.wfile.write(body)
|
|
209
|
+
|
|
210
|
+
def do_GET(self):
|
|
211
|
+
if self.path.split("?")[0] == "/health":
|
|
212
|
+
self._json({"ok": True, **stats(path)})
|
|
213
|
+
else:
|
|
214
|
+
self._json({"error": "not found"}, 404)
|
|
215
|
+
|
|
216
|
+
def do_POST(self):
|
|
217
|
+
if self.path.split("?")[0] != "/v1/search":
|
|
218
|
+
self._json({"error": "not found"}, 404)
|
|
219
|
+
return
|
|
220
|
+
try:
|
|
221
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
222
|
+
data = json.loads(self.rfile.read(min(n, 1 << 20)) or b"{}")
|
|
223
|
+
except Exception:
|
|
224
|
+
self._json({"error": "bad json"}, 400)
|
|
225
|
+
return
|
|
226
|
+
self._json({"results": search(data.get("query", ""), data.get("k", 10), path=path)})
|
|
227
|
+
|
|
228
|
+
ThreadingHTTPServer((host, port), H).serve_forever()
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""会话摘要的触发与落盘(附录 C · P2 收尾)。
|
|
4
|
+
|
|
5
|
+
三件事:
|
|
6
|
+
1. **触发规则**:每 N 轮 / 水位 ≥60% / 用户显式要求,三者任一即触发;
|
|
7
|
+
2. **落盘**:`~/.brain-memory/sessions/summaries/<session>.md`,保留最近 3 版;
|
|
8
|
+
3. **回滚**:`rollback(n)` 把上一版恢复成当前版(摘要漂移时的人工兜底)。
|
|
9
|
+
|
|
10
|
+
摘要生成复用 summarizer.summarize()(模型可选、fail-open)。
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
KEEP_VERSIONS = 3
|
|
19
|
+
DEFAULT_TURNS = 8
|
|
20
|
+
DEFAULT_PCT = 0.60
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def summaries_dir(home=None) -> Path:
|
|
24
|
+
return Path(home or _home()) / "sessions" / "summaries"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _home():
|
|
28
|
+
try:
|
|
29
|
+
import core
|
|
30
|
+
return core.HOME
|
|
31
|
+
except Exception:
|
|
32
|
+
return Path.home() / ".brain-memory"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _paths(session_id: str, home=None) -> list[Path]:
|
|
36
|
+
"""[当前, .1, .2] 三个版本槽。"""
|
|
37
|
+
safe = "".join(c if (c.isalnum() or c in "-_.") else "_" for c in str(session_id or "default"))
|
|
38
|
+
base = summaries_dir(home)
|
|
39
|
+
return [base / f"{safe}.md"] + [base / f"{safe}.{i}.md" for i in range(1, KEEP_VERSIONS)]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ---------------------------------------------------------------- 触发
|
|
43
|
+
|
|
44
|
+
def decide(turns_since_last: int = 0, used_pct: float | None = None,
|
|
45
|
+
force: bool = False, cfg: dict | None = None) -> dict:
|
|
46
|
+
"""返回 {trigger: bool, reason: str}。三个条件任一满足就触发。"""
|
|
47
|
+
cfg = cfg or {}
|
|
48
|
+
every = int(cfg.get("summary_turns") or DEFAULT_TURNS)
|
|
49
|
+
pct_th = float(cfg.get("summary_pct") or DEFAULT_PCT)
|
|
50
|
+
if force:
|
|
51
|
+
return {"trigger": True, "reason": "force(用户/命令显式要求)"}
|
|
52
|
+
if used_pct is not None and float(used_pct) >= pct_th * 100:
|
|
53
|
+
return {"trigger": True, "reason": f"水位 {float(used_pct):.0f}% ≥ {pct_th * 100:.0f}%"}
|
|
54
|
+
if turns_since_last >= every:
|
|
55
|
+
return {"trigger": True, "reason": f"距上次摘要 {turns_since_last} 轮 ≥ {every}"}
|
|
56
|
+
return {"trigger": False, "reason": f"未触发({turns_since_last} 轮 / "
|
|
57
|
+
f"{'—' if used_pct is None else f'{float(used_pct):.0f}%'})"}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------- 落盘 / 读取 / 回滚
|
|
61
|
+
|
|
62
|
+
def save(text: str, session_id: str = "default", home=None, meta: dict | None = None) -> dict:
|
|
63
|
+
"""写入当前版,旧版顺次后移(.1 ← 旧当前,.2 ← 旧 .1)。"""
|
|
64
|
+
if not str(text or "").strip():
|
|
65
|
+
return {"ok": False, "reason": "空摘要"}
|
|
66
|
+
paths = _paths(session_id, home)
|
|
67
|
+
paths[0].parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
for i in range(len(paths) - 1, 0, -1):
|
|
69
|
+
if paths[i - 1].exists():
|
|
70
|
+
try:
|
|
71
|
+
paths[i].write_text(paths[i - 1].read_text(encoding="utf-8"), encoding="utf-8")
|
|
72
|
+
except OSError:
|
|
73
|
+
pass
|
|
74
|
+
payload = str(text).rstrip() + "\n"
|
|
75
|
+
if meta:
|
|
76
|
+
payload = f"<!-- {json.dumps(meta, ensure_ascii=False)} -->\n" + payload
|
|
77
|
+
paths[0].write_text(payload, encoding="utf-8")
|
|
78
|
+
return {"ok": True, "path": str(paths[0]), "chars": len(text)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load(session_id: str = "default", home=None) -> str:
|
|
82
|
+
p = _paths(session_id, home)[0]
|
|
83
|
+
try:
|
|
84
|
+
return p.read_text(encoding="utf-8")
|
|
85
|
+
except OSError:
|
|
86
|
+
return ""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def rollback(session_id: str = "default", home=None, steps: int = 1) -> dict:
|
|
90
|
+
"""回滚:把最近一版备份恢复成当前版(保留被替换的那版到 .2)。"""
|
|
91
|
+
paths = _paths(session_id, home)
|
|
92
|
+
steps = max(1, int(steps))
|
|
93
|
+
if steps >= len(paths) or not paths[1].exists():
|
|
94
|
+
return {"ok": False, "reason": "没有可回滚的备份"}
|
|
95
|
+
restored = paths[steps].read_text(encoding="utf-8")
|
|
96
|
+
for i in range(len(paths) - 1, 0, -1):
|
|
97
|
+
if paths[i - 1].exists():
|
|
98
|
+
try:
|
|
99
|
+
paths[i].write_text(paths[i - 1].read_text(encoding="utf-8"), encoding="utf-8")
|
|
100
|
+
except OSError:
|
|
101
|
+
pass
|
|
102
|
+
paths[0].write_text(restored, encoding="utf-8")
|
|
103
|
+
return {"ok": True, "path": str(paths[0]), "chars": len(restored)}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ---------------------------------------------------------------- 一步到位
|
|
107
|
+
|
|
108
|
+
def maybe_summarize(turns: list, *, session_id: str = "default", turns_since_last: int = 0,
|
|
109
|
+
used_pct: float | None = None, force: bool = False,
|
|
110
|
+
cfg: dict | None = None, home=None, prev_summary: str = "",
|
|
111
|
+
max_chars: int = 1500) -> dict:
|
|
112
|
+
"""触发判断 → 生成 → 落盘。不触发时不生成(省一次模型/IO)。"""
|
|
113
|
+
from summarizer import summarize
|
|
114
|
+
d = decide(turns_since_last, used_pct, force, cfg)
|
|
115
|
+
if not d["trigger"]:
|
|
116
|
+
return {"ok": True, "skipped": True, "reason": d["reason"]}
|
|
117
|
+
res = summarize(turns, cfg=cfg, prev_summary=prev_summary or load(session_id, home),
|
|
118
|
+
max_chars=max_chars)
|
|
119
|
+
saved = save(res["text"], session_id, home,
|
|
120
|
+
meta={"ts": int(time.time()), "source": res["source"], "reason": d["reason"]})
|
|
121
|
+
return {"ok": bool(saved.get("ok")), "skipped": False, "reason": d["reason"],
|
|
122
|
+
"source": res["source"], "chars": res["chars"], "path": saved.get("path"),
|
|
123
|
+
"warnings": res.get("warnings") or [], "text": res["text"]}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""会话摘要层(附录 C · P2)——五段式摘要 + 校验 + fail-open。
|
|
4
|
+
|
|
5
|
+
设计要点(照附录 C 与 billion-context 的教训):
|
|
6
|
+
1. **五段固定结构**:目标 / 已做 / 未决 / 约束 / 原话引用。其中「原话引用」必须逐字保留,
|
|
7
|
+
它是摘要漂移时的纠错锚。
|
|
8
|
+
2. **外部便宜模型可选**:配 `config.summary`(OpenAI 兼容 /chat/completions)就走模型;
|
|
9
|
+
没配、超时、报错、输出不合格 → 一律**回退到离线抽取式摘要**,绝不阻塞主流程(fail-open)。
|
|
10
|
+
3. **提交前校验**:长度上限 + 五个小标题齐全 + 不许整段回显 prompt / 代码块。
|
|
11
|
+
4. 纯标准库;模型调用用 urllib,可注入 `call` 便于测试(不联网也能测全部分支)。
|
|
12
|
+
|
|
13
|
+
CLI(在 cli.py 里挂 `summarize`):
|
|
14
|
+
brain.py summarize --input turns.jsonl [--json] [--max-chars 1500]
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import urllib.request
|
|
23
|
+
|
|
24
|
+
HEADERS = ("目标", "已做", "未决", "约束", "原话引用")
|
|
25
|
+
DEFAULT_MAX_CHARS = 1500
|
|
26
|
+
|
|
27
|
+
TEMPLATE = """你是会话摘要器。把下面的对话压成固定五段,供下一轮上下文使用。
|
|
28
|
+
|
|
29
|
+
必须严格输出这五个小标题(顺序不变),每段 1-3 行:
|
|
30
|
+
## 目标
|
|
31
|
+
(用户想要什么;可引用一句原话)
|
|
32
|
+
## 已做
|
|
33
|
+
(已经完成/确认的事实,带路径或命令)
|
|
34
|
+
## 未决
|
|
35
|
+
(还没定的问题、待办、阻塞)
|
|
36
|
+
## 约束
|
|
37
|
+
(用户明确说过的限制:风格、技术栈、不要做什么)
|
|
38
|
+
## 原话引用
|
|
39
|
+
(最多 3 句必须逐字保留的用户原话:纠正、承诺、关键数字)
|
|
40
|
+
|
|
41
|
+
规则:
|
|
42
|
+
- 总长不超过 {max_chars} 字;不要复述本提示,不要输出代码块。
|
|
43
|
+
- 上一版摘要只作参考,发现冲突以最新对话为准。
|
|
44
|
+
|
|
45
|
+
{prev}
|
|
46
|
+
---- 对话 ----
|
|
47
|
+
{turns}
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------- 输入归一
|
|
52
|
+
|
|
53
|
+
def normalize_turns(raw) -> list[dict]:
|
|
54
|
+
"""接受 [{role,content}] / [{role,text}] / {"messages":[...]} / JSONL 行列表。"""
|
|
55
|
+
if isinstance(raw, dict):
|
|
56
|
+
raw = raw.get("messages") or raw.get("turns") or []
|
|
57
|
+
out = []
|
|
58
|
+
for item in raw or []:
|
|
59
|
+
if not isinstance(item, dict):
|
|
60
|
+
continue
|
|
61
|
+
role = str(item.get("role") or item.get("sender") or "other").lower()
|
|
62
|
+
if role in ("human", "me", "用户"):
|
|
63
|
+
role = "user"
|
|
64
|
+
elif role in ("ai", "bot", "model", "助手"):
|
|
65
|
+
role = "assistant"
|
|
66
|
+
text = item.get("content", item.get("text", item.get("message", "")))
|
|
67
|
+
if isinstance(text, list): # OpenAI content parts
|
|
68
|
+
text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
|
|
69
|
+
text = str(text or "").strip()
|
|
70
|
+
if text:
|
|
71
|
+
out.append({"role": role, "text": text})
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_turns(path) -> list[dict]:
|
|
76
|
+
"""读 .jsonl(每行一条)或 .json(数组 / {messages:[...]})。
|
|
77
|
+
|
|
78
|
+
上限保护:导出文件可能几百 MB(整个账号的聊天记录),全量读进内存会炸。
|
|
79
|
+
这里只读前 64MB / 20 万行,超出截断并继续——摘要本来也不需要全量。
|
|
80
|
+
"""
|
|
81
|
+
from pathlib import Path
|
|
82
|
+
p = Path(path)
|
|
83
|
+
MAX_BYTES = 64 * 1024 * 1024
|
|
84
|
+
MAX_LINES = 200_000
|
|
85
|
+
raw = p.read_bytes()
|
|
86
|
+
if len(raw) > MAX_BYTES:
|
|
87
|
+
raw = raw[:MAX_BYTES]
|
|
88
|
+
text = raw.decode("utf-8-sig", errors="replace")
|
|
89
|
+
if p.suffix.lower() == ".jsonl":
|
|
90
|
+
rows = []
|
|
91
|
+
for line in text.splitlines()[:MAX_LINES]:
|
|
92
|
+
line = line.strip()
|
|
93
|
+
if not line:
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
rows.append(json.loads(line))
|
|
97
|
+
except ValueError:
|
|
98
|
+
continue
|
|
99
|
+
return normalize_turns(rows)
|
|
100
|
+
return normalize_turns(json.loads(text))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ---------------------------------------------------------------- 五段校验
|
|
104
|
+
|
|
105
|
+
def validate(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> tuple[bool, str]:
|
|
106
|
+
"""提交前校验:长度、五个小标题、拒绝回显提示/代码块。"""
|
|
107
|
+
t = str(text or "").strip()
|
|
108
|
+
if not t:
|
|
109
|
+
return False, "空摘要"
|
|
110
|
+
if len(t) > max_chars:
|
|
111
|
+
return False, f"超长:{len(t)} > {max_chars}"
|
|
112
|
+
missing = [h for h in HEADERS if f"## {h}" not in t]
|
|
113
|
+
if missing:
|
|
114
|
+
return False, "缺小标题:" + "、".join(missing)
|
|
115
|
+
if "```" in t:
|
|
116
|
+
return False, "包含代码块"
|
|
117
|
+
if "规则:" in t and "上一版摘要" in t:
|
|
118
|
+
return False, "疑似回显提示词"
|
|
119
|
+
return True, ""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------- 离线抽取式(fail-open 兜底)
|
|
123
|
+
|
|
124
|
+
_KEY = re.compile(r"不对|不是|改成|记住|务必|不要|必须|只能|预算|注意|风险|TODO|待办|未决|下次|明天")
|
|
125
|
+
_QUOTE = re.compile(r"不对|不是|改成|记住|务必|别|不要|必须")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _clip(s: str, n: int = 120) -> str:
|
|
129
|
+
s = re.sub(r"\s+", " ", str(s or "")).strip()
|
|
130
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def extractive_fallback(turns: list[dict], max_chars: int = DEFAULT_MAX_CHARS) -> str:
|
|
134
|
+
"""不调模型的确定性摘要:只挑明确信号,不编造。"""
|
|
135
|
+
users = [t["text"] for t in turns if t["role"] == "user"]
|
|
136
|
+
bots = [t["text"] for t in turns if t["role"] == "assistant"]
|
|
137
|
+
goal = _clip(users[0], 160) if users else "(没读到用户消息)"
|
|
138
|
+
done = [f"- {_clip(b)}" for b in bots[-3:] if len(b) >= 8]
|
|
139
|
+
pending = [f"- {_clip(u)}" for u in users[-3:] if _KEY.search(u)]
|
|
140
|
+
constraints = [f"- {_clip(u)}" for u in users
|
|
141
|
+
if re.search(r"不要|必须|只能|务必|别", u)][-3:]
|
|
142
|
+
quotes = [f"- {_clip(u, 80)}" for u in users if _QUOTE.search(u)][-3:]
|
|
143
|
+
|
|
144
|
+
def block(title: str, lines: list[str], empty: str) -> str:
|
|
145
|
+
body = "\n".join(lines) if lines else empty
|
|
146
|
+
return f"## {title}\n{body}"
|
|
147
|
+
|
|
148
|
+
text = "\n".join([
|
|
149
|
+
block("目标", ([f"- {goal}"] if goal else []), "- (未提取到)"),
|
|
150
|
+
block("已做", done, "- (未提取到)"),
|
|
151
|
+
block("未决", pending, "- (未提取到)"),
|
|
152
|
+
block("约束", constraints, "- (未提取到)"),
|
|
153
|
+
block("原话引用", quotes, "- (未提取到)"),
|
|
154
|
+
])
|
|
155
|
+
if len(text) > max_chars:
|
|
156
|
+
text = text[: max_chars - 1].rstrip() + "…"
|
|
157
|
+
return text
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ---------------------------------------------------------------- 模型调用(可选)
|
|
161
|
+
|
|
162
|
+
def _cfg_section(cfg: dict | None) -> dict:
|
|
163
|
+
if cfg is not None:
|
|
164
|
+
return dict(cfg.get("summary") or {})
|
|
165
|
+
try:
|
|
166
|
+
import core
|
|
167
|
+
return dict((core.load_config() or {}).get("summary") or {})
|
|
168
|
+
except Exception:
|
|
169
|
+
return {}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def openai_chat(prompt: str, cfg: dict, timeout: float | None = None) -> str | None:
|
|
173
|
+
"""OpenAI 兼容 /chat/completions;任何失败返回 None(由上层 fail-open)。"""
|
|
174
|
+
base = str(cfg.get("base_url") or "").rstrip("/")
|
|
175
|
+
model = str(cfg.get("model") or "")
|
|
176
|
+
if not base or not model:
|
|
177
|
+
return None
|
|
178
|
+
key_env = str(cfg.get("api_key_env") or "")
|
|
179
|
+
api_key = os.environ.get(key_env, "") if key_env else ""
|
|
180
|
+
body = json.dumps({
|
|
181
|
+
"model": model,
|
|
182
|
+
"temperature": 0.2,
|
|
183
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
184
|
+
}).encode("utf-8")
|
|
185
|
+
url = base if base.endswith("/chat/completions") else base + "/chat/completions"
|
|
186
|
+
req = urllib.request.Request(url, data=body, method="POST",
|
|
187
|
+
headers={"Content-Type": "application/json",
|
|
188
|
+
**({"Authorization": f"Bearer {api_key}"} if api_key else {})})
|
|
189
|
+
try:
|
|
190
|
+
with urllib.request.urlopen(req, timeout=timeout or float(cfg.get("timeout") or 30)) as r:
|
|
191
|
+
data = json.loads(r.read().decode("utf-8", "replace"))
|
|
192
|
+
content = (((data.get("choices") or [{}])[0]).get("message") or {}).get("content")
|
|
193
|
+
return str(content or "").strip() or None
|
|
194
|
+
except Exception as exc: # noqa: BLE001
|
|
195
|
+
try:
|
|
196
|
+
import failures
|
|
197
|
+
failures.record("summary.model", f"{type(exc).__name__}: {exc}",
|
|
198
|
+
ctx={"base_url": base, "model": model})
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ---------------------------------------------------------------- 主入口
|
|
205
|
+
|
|
206
|
+
def build_prompt(turns: list[dict], prev_summary: str = "", max_chars: int = DEFAULT_MAX_CHARS) -> str:
|
|
207
|
+
lines = []
|
|
208
|
+
for t in turns:
|
|
209
|
+
who = "用户" if t["role"] == "user" else ("我" if t["role"] == "assistant" else "其他")
|
|
210
|
+
lines.append(f"{who}: {t['text']}")
|
|
211
|
+
prev = f"上一版摘要:\n{prev_summary.strip()}\n" if prev_summary and prev_summary.strip() else ""
|
|
212
|
+
return TEMPLATE.format(max_chars=max_chars, prev=prev, turns="\n".join(lines))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def summarize(turns: list[dict], *, cfg: dict | None = None, prev_summary: str = "",
|
|
216
|
+
max_chars: int = DEFAULT_MAX_CHARS, call=None) -> dict:
|
|
217
|
+
"""生成五段摘要:模型优先,失败/不合格一律回退抽取式。
|
|
218
|
+
|
|
219
|
+
返回 {text, source: 'model'|'fallback', actions:[...], warnings:[...], chars}
|
|
220
|
+
"""
|
|
221
|
+
turns = normalize_turns(turns)
|
|
222
|
+
actions: list[str] = []
|
|
223
|
+
warnings: list[str] = []
|
|
224
|
+
sec = _cfg_section(cfg)
|
|
225
|
+
if not sec.get("enabled"):
|
|
226
|
+
actions.append("summary.enabled=false:走离线抽取式")
|
|
227
|
+
text = extractive_fallback(turns, max_chars)
|
|
228
|
+
return {"text": text, "source": "fallback", "actions": actions,
|
|
229
|
+
"warnings": warnings, "chars": len(text)}
|
|
230
|
+
|
|
231
|
+
prompt = build_prompt(turns, prev_summary, max_chars)
|
|
232
|
+
caller = call or (lambda p: openai_chat(p, sec))
|
|
233
|
+
try:
|
|
234
|
+
text = caller(prompt)
|
|
235
|
+
except Exception as exc: # noqa: BLE001
|
|
236
|
+
text = None
|
|
237
|
+
warnings.append(f"模型调用异常:{exc!r}")
|
|
238
|
+
if text:
|
|
239
|
+
ok, why = validate(text, max_chars)
|
|
240
|
+
if ok:
|
|
241
|
+
return {"text": text, "source": "model", "actions": actions,
|
|
242
|
+
"warnings": warnings, "chars": len(text)}
|
|
243
|
+
warnings.append(f"模型输出不合格({why}),回退离线摘要")
|
|
244
|
+
else:
|
|
245
|
+
warnings.append("模型调用失败,回退离线摘要")
|
|
246
|
+
text = extractive_fallback(turns, max_chars)
|
|
247
|
+
return {"text": text, "source": "fallback", "actions": actions,
|
|
248
|
+
"warnings": warnings, "chars": len(text)}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def estimate_tokens(text: str, chars_per_token: int = 2) -> int:
|
|
252
|
+
return int(math.ceil(len(text or "") / max(1, chars_per_token)))
|