vecrecall 2.2.0__py3-none-any.whl

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.
vecrecall/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ # VecRecall
2
+ from vecrecall.core.engine import (
3
+ VecRecall,
4
+ Memory,
5
+ RetrievalResult,
6
+ ContextBundle,
7
+ VectorBackend,
8
+ NumpyVectorBackend,
9
+ SqliteVectorBackend,
10
+ EmbeddingBackend,
11
+ HashEmbeddingBackend,
12
+ BagOfWordsEmbeddingBackend,
13
+ OllamaEmbeddingBackend,
14
+ APIEmbeddingBackend,
15
+ build_embedding_backend,
16
+ estimate_tokens,
17
+ memory_to_dict,
18
+ )
19
+ from vecrecall.core.extractor import (
20
+ Extraction,
21
+ MemoryExtractor,
22
+ HeuristicExtractor,
23
+ LLMExtractor,
24
+ build_extractor,
25
+ heuristic_importance,
26
+ heuristic_summary,
27
+ )
28
+ from vecrecall.core.crypto import Cipher
29
+ from vecrecall.core.forgetting import ForgettingCurve
30
+ from vecrecall.core.temporal_graph import TemporalGraph, normalize_entity
31
+ from vecrecall.core.redaction import (
32
+ RedactionResult, RedactionRule, RULES as REDACTION_RULES,
33
+ has_meaningful_payload, redact_memory_payload,
34
+ )
35
+ from vecrecall.core.writeback import (
36
+ BufferedDecision, EnqueueResult, SqliteOutbox,
37
+ WritebackDecision, WritebackGovernor,
38
+ )
39
+ from vecrecall.core.recall_policy import (
40
+ RecallDecision, RecallPolicy, AcceptanceResult,
41
+ build_query_intent, decide_recall, evaluate_memory,
42
+ )
43
+ from vecrecall.repomap import build_repo_map, detect_updates, validate_repo_map
44
+
45
+ __version__ = "2.2.0"
46
+ __all__ = [
47
+ "VecRecall", "Memory", "RetrievalResult", "ContextBundle",
48
+ "VectorBackend", "NumpyVectorBackend", "SqliteVectorBackend",
49
+ "EmbeddingBackend", "HashEmbeddingBackend", "BagOfWordsEmbeddingBackend",
50
+ "OllamaEmbeddingBackend", "APIEmbeddingBackend",
51
+ "build_embedding_backend",
52
+ "estimate_tokens", "memory_to_dict",
53
+ "Extraction", "MemoryExtractor", "HeuristicExtractor", "LLMExtractor",
54
+ "build_extractor", "heuristic_importance", "heuristic_summary",
55
+ "TemporalGraph", "normalize_entity", "ForgettingCurve", "Cipher",
56
+ "RedactionResult", "RedactionRule", "REDACTION_RULES",
57
+ "has_meaningful_payload", "redact_memory_payload",
58
+ "BufferedDecision", "EnqueueResult", "SqliteOutbox",
59
+ "WritebackDecision", "WritebackGovernor",
60
+ "RecallDecision", "RecallPolicy", "AcceptanceResult",
61
+ "build_query_intent", "decide_recall", "evaluate_memory",
62
+ "build_repo_map", "detect_updates", "validate_repo_map",
63
+ ]
@@ -0,0 +1,4 @@
1
+ # VecRecall HTTP REST API
2
+ from vecrecall.api.server import VecRecallHTTPServer, VecRecallHTTPHandler
3
+
4
+ __all__ = ["VecRecallHTTPServer", "VecRecallHTTPHandler"]
@@ -0,0 +1,374 @@
1
+ """
2
+ VecRecall — HTTP REST API Server
3
+
4
+ 为传统软件(非 MCP 客户端)提供 HTTP JSON 接口,零依赖,
5
+ 基于 Python 标准库 http.server。任何语言(curl / requests /
6
+ Java / C# / Node / Go ...)都能通过 HTTP 接入。
7
+
8
+ 启动:
9
+ vr api --dir ~/.vecrecall --port 8791 --embedder ollama
10
+ vr-api --dir ~/.vecrecall --port 8791
11
+
12
+ 端点一览:
13
+ GET /health 健康检查
14
+ GET /stats 统计
15
+ GET /wings 列出 wings
16
+ GET /topics?wing= 列出话题
17
+ GET /memories 记忆列表(?wing=&topic=&limit=&offset=&full=&sort=)
18
+ GET /memories/{id} 单条记忆(含原文)
19
+ POST /memories 添加记忆
20
+ POST /memories/batch 批量添加
21
+ POST /search 语义搜索
22
+ POST /context 构建四层上下文
23
+ POST /prune 清理低价值记忆
24
+ POST /reindex 重建向量索引
25
+ POST /verify 验证哈希链
26
+ PUT /memories/{id} 更新记忆
27
+ DELETE /memories/{id} 删除记忆
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import os
35
+ import secrets
36
+ import sys
37
+ import threading
38
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
39
+ from urllib.parse import urlparse, parse_qs
40
+
41
+ # 把父目录加入 path(支持直接 python -m 运行)
42
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
43
+
44
+ from vecrecall.core.engine import (
45
+ VecRecall, build_embedding_backend, memory_to_dict,
46
+ )
47
+
48
+ __version__ = "2.2.0"
49
+
50
+
51
+ def _err(msg: str) -> dict:
52
+ return {"error": msg}
53
+
54
+
55
+ def resolve_api_key(cli_key: str | None, host: str) -> str | None:
56
+ """解析 REST API 访问令牌。
57
+
58
+ 优先级:--api-key > 环境变量 VR_API_KEY > None(本机免认证)。
59
+ 监听非本机地址(如 0.0.0.0)时若未提供 token,直接拒绝启动。
60
+ """
61
+ key = cli_key or os.environ.get("VR_API_KEY")
62
+ if not key and host not in ("127.0.0.1", "localhost", "::1"):
63
+ print("[VecRecall API] 错误:监听非本机地址必须提供 --api-key 或 VR_API_KEY",
64
+ file=sys.stderr)
65
+ sys.exit(1)
66
+ return key
67
+
68
+
69
+ class VecRecallHTTPHandler(BaseHTTPRequestHandler):
70
+ """HTTP → VecRecall 引擎的桥接,全部返回 JSON。"""
71
+
72
+ @property
73
+ def palace(self) -> VecRecall:
74
+ return self.server.palace
75
+
76
+ @property
77
+ def lock(self):
78
+ return self.server.lock
79
+
80
+ # ── 响应辅助 ──
81
+ @property
82
+ def api_key(self) -> str | None:
83
+ return getattr(self.server, "api_key", None)
84
+
85
+ @property
86
+ def cors_origin(self) -> str | None:
87
+ return getattr(self.server, "cors_origin", None)
88
+
89
+ def _authorized(self) -> bool:
90
+ """校验 Bearer Token(Authorization 头或 ?key= 查询参数)。"""
91
+ key = self.api_key
92
+ if not key:
93
+ return True # 未配置 token 时不强制(仅建议本机使用)
94
+ auth = self.headers.get("Authorization", "")
95
+ if auth.startswith("Bearer ") and secrets.compare_digest(auth[7:], key):
96
+ return True
97
+ qkey = parse_qs(urlparse(self.path).query).get("key", [None])[0]
98
+ return bool(qkey) and secrets.compare_digest(qkey, key)
99
+
100
+ def _is_public(self) -> bool:
101
+ """无需认证的路径(健康检查)。"""
102
+ return self.path.rstrip("/") in ("/health", "")
103
+
104
+ def _send(self, obj, status: int = 200):
105
+ body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
106
+ self.send_response(status)
107
+ self.send_header("Content-Type", "application/json; charset=utf-8")
108
+ self.send_header("Content-Length", str(len(body)))
109
+ if self.cors_origin:
110
+ self.send_header("Access-Control-Allow-Origin", self.cors_origin)
111
+ self.send_header("Access-Control-Allow-Methods",
112
+ "GET, POST, PUT, DELETE, OPTIONS")
113
+ self.send_header("Access-Control-Allow-Headers",
114
+ "Content-Type, Authorization")
115
+ self.end_headers()
116
+ self.wfile.write(body)
117
+
118
+ def _read_json(self) -> dict:
119
+ length = int(self.headers.get("Content-Length") or 0)
120
+ if length <= 0:
121
+ return {}
122
+ raw = self.rfile.read(length)
123
+ if not raw:
124
+ return {}
125
+ try:
126
+ return json.loads(raw.decode("utf-8"))
127
+ except json.JSONDecodeError:
128
+ return {}
129
+
130
+ def _handle(self, fn):
131
+ """统一认证校验 + 异常处理 + 串行化(保护 SQLite 并发写)。"""
132
+ with self.lock:
133
+ try:
134
+ if not self._is_public() and not self._authorized():
135
+ self._send(_err("未授权:缺少或错误的 API Key"), 401)
136
+ return
137
+ self._send(fn())
138
+ except ValueError as e:
139
+ self._send(_err(str(e)), 400)
140
+ except KeyError as e:
141
+ self._send(_err(f"缺少参数: {e}"), 400)
142
+ except Exception as e: # noqa: BLE001
143
+ self._send(_err(f"服务器内部错误: {e}"), 500)
144
+
145
+ # ── HTTP 方法 ──
146
+ def do_OPTIONS(self):
147
+ self.send_response(204)
148
+ if self.cors_origin:
149
+ self.send_header("Access-Control-Allow-Origin", self.cors_origin)
150
+ self.send_header("Access-Control-Allow-Methods",
151
+ "GET, POST, PUT, DELETE, OPTIONS")
152
+ self.send_header("Access-Control-Allow-Headers",
153
+ "Content-Type, Authorization")
154
+ self.end_headers()
155
+
156
+ def do_GET(self):
157
+ self._handle(self._route_get)
158
+
159
+ def do_POST(self):
160
+ self._handle(self._route_post)
161
+
162
+ def do_PUT(self):
163
+ self._handle(self._route_put)
164
+
165
+ def do_DELETE(self):
166
+ self._handle(self._route_delete)
167
+
168
+ # ── 路由辅助 ──
169
+ def _parts(self):
170
+ parsed = urlparse(self.path)
171
+ path = parsed.path.rstrip("/") or "/"
172
+ query = parse_qs(parsed.query)
173
+ segs = [s for s in path.split("/") if s]
174
+ return segs, query
175
+
176
+ # ── GET ──
177
+ def _route_get(self):
178
+ p = self.palace
179
+ segs, q = self._parts()
180
+
181
+ if not segs:
182
+ return {"name": "vecrecall", "version": __version__, "status": "ok",
183
+ "embedding": type(p._emb).__name__,
184
+ "vector": type(p._vec).__name__}
185
+ head = segs[0]
186
+
187
+ if head == "health":
188
+ return {"status": "ok", "name": "vecrecall", "version": __version__}
189
+ if head == "stats":
190
+ return p.stats()
191
+ if head == "wings":
192
+ return {"wings": p.list_wings()}
193
+ if head == "topics":
194
+ return {"topics": p.list_topics(q.get("wing", [None])[0])}
195
+ if head == "memories":
196
+ if len(segs) == 1:
197
+ return p.list_memories(
198
+ wing=q.get("wing", [None])[0],
199
+ topic=q.get("topic", [None])[0],
200
+ limit=int(q.get("limit", ["50"])[0]),
201
+ offset=int(q.get("offset", ["0"])[0]),
202
+ full=q.get("full", ["0"])[0].lower() in ("1", "true", "yes"),
203
+ sort=q.get("sort", ["importance"])[0],
204
+ )
205
+ m = p._kg.get(segs[1])
206
+ if not m:
207
+ raise ValueError(f"记忆不存在: {segs[1]}")
208
+ return memory_to_dict(m, full=True)
209
+
210
+ raise ValueError(f"未知路径: /{'/'.join(segs)}")
211
+
212
+ # ── POST ──
213
+ def _route_post(self):
214
+ p = self.palace
215
+ segs, q = self._parts()
216
+ body = self._read_json()
217
+
218
+ if not segs:
219
+ raise ValueError("未知路径")
220
+ head = segs[0]
221
+
222
+ if head == "memories":
223
+ if len(segs) == 2 and segs[1] == "batch":
224
+ ms = p.add_batch(body.get("items", []))
225
+ return {"added": len(ms), "ids": [m.id for m in ms]}
226
+ m = p.add(
227
+ content=body["content"],
228
+ topic=body.get("topic", "general"),
229
+ wing=body.get("wing"),
230
+ importance=body.get("importance"),
231
+ session_id=body.get("session_id", ""),
232
+ ui_summary=body.get("ui_summary", ""),
233
+ metadata=body.get("metadata"),
234
+ )
235
+ return {"ok": True, "id": m.id, "wing": m.wing,
236
+ "topic": m.topic, "importance": m.importance}
237
+
238
+ if head == "search":
239
+ results = p.search(
240
+ body["query"], body.get("n", 10),
241
+ body.get("min_score"), body.get("hybrid", False),
242
+ )
243
+ return {"results": [
244
+ {**memory_to_dict(r.memory),
245
+ "score": round(r.score, 4), "layer": r.layer}
246
+ for r in results
247
+ ]}
248
+
249
+ if head == "context":
250
+ ctx = p.build_context(
251
+ body.get("current_query", ""),
252
+ body.get("load_l2", True),
253
+ body.get("load_l3", False),
254
+ body.get("hybrid", False),
255
+ )
256
+ return {
257
+ "l0": ctx.l0_identity,
258
+ "l1": [memory_to_dict(r.memory) for r in ctx.l1_key_moments],
259
+ "l2": [memory_to_dict(r.memory) for r in ctx.l2_topic_context],
260
+ "l3": [memory_to_dict(r.memory) for r in ctx.l3_deep_results],
261
+ "total_tokens_estimate": ctx.total_tokens_estimate,
262
+ }
263
+
264
+ if head == "prune":
265
+ victims = p.prune(
266
+ min_importance=body.get("min_importance"),
267
+ older_than_days=body.get("older_than_days"),
268
+ wing=body.get("wing"),
269
+ dry_run=body.get("dry_run", True),
270
+ )
271
+ return {"candidates": len(victims),
272
+ "dry_run": body.get("dry_run", True),
273
+ "ids": [m.id for m in victims[:200]]}
274
+
275
+ if head == "reindex":
276
+ return {"reindexed": p.reindex()}
277
+
278
+ if head == "verify":
279
+ return p.verify_integrity(body.get("wing"))
280
+
281
+ raise ValueError(f"未知路径: /{'/'.join(segs)}")
282
+
283
+ # ── PUT ──
284
+ def _route_put(self):
285
+ p = self.palace
286
+ segs, q = self._parts()
287
+ body = self._read_json()
288
+ if len(segs) == 2 and segs[0] == "memories":
289
+ m = p.update(
290
+ segs[1],
291
+ content=body.get("content"),
292
+ topic=body.get("topic"),
293
+ importance=body.get("importance"),
294
+ ui_summary=body.get("ui_summary"),
295
+ )
296
+ return {"ok": True, "id": m.id, "importance": m.importance}
297
+ raise ValueError(f"未知路径: /{'/'.join(segs)}")
298
+
299
+ # ── DELETE ──
300
+ def _route_delete(self):
301
+ p = self.palace
302
+ segs, q = self._parts()
303
+ if len(segs) == 2 and segs[0] == "memories":
304
+ ok = p.delete(segs[1])
305
+ return {"ok": ok, "deleted": ok}
306
+ raise ValueError(f"未知路径: /{'/'.join(segs)}")
307
+
308
+
309
+ class VecRecallHTTPServer(ThreadingHTTPServer):
310
+ daemon_threads = True
311
+
312
+ def __init__(self, addr, palace: VecRecall,
313
+ api_key: str | None = None,
314
+ cors_origin: str | None = None):
315
+ super().__init__(addr, VecRecallHTTPHandler)
316
+ self.palace = palace
317
+ self.lock = threading.RLock()
318
+ self.api_key = api_key
319
+ self.cors_origin = cors_origin
320
+
321
+
322
+ def main():
323
+ parser = argparse.ArgumentParser(description="VecRecall HTTP REST API Server")
324
+ parser.add_argument("--dir", default=os.path.expanduser("~/.vecrecall"),
325
+ help="数据存储目录")
326
+ parser.add_argument("--wing", default="default", help="默认 wing")
327
+ parser.add_argument("--host", default="127.0.0.1", help="监听地址")
328
+ parser.add_argument("--port", type=int, default=8791, help="监听端口")
329
+ parser.add_argument("--chain", action="store_true", help="启用哈希链")
330
+ parser.add_argument("--embedder", default="auto",
331
+ choices=["auto", "bow", "sentence", "ollama", "api"],
332
+ help="嵌入后端(默认 auto)")
333
+ parser.add_argument("--embed-model", default=None, help="嵌入模型名")
334
+ parser.add_argument("--embed-url", default=None, help="Ollama/API 服务地址")
335
+ parser.add_argument("--embed-api-key", default=None, help="远程 API Key")
336
+ parser.add_argument("--api-key", default=None,
337
+ help="REST API 访问令牌(缺省读环境变量 VR_API_KEY)")
338
+ parser.add_argument("--cors-origin", default=None,
339
+ help="允许跨域的 Origin(默认禁止跨域,防止浏览器网页盗读)")
340
+ args = parser.parse_args()
341
+
342
+ api_key = resolve_api_key(args.api_key, args.host)
343
+
344
+ emb = build_embedding_backend(
345
+ args.embedder, model=args.embed_model,
346
+ base_url=args.embed_url, api_key=args.embed_api_key,
347
+ )
348
+ palace = VecRecall(
349
+ base_dir=args.dir, wing=args.wing,
350
+ use_blockchain=args.chain, embedding_backend=emb,
351
+ )
352
+
353
+ server = VecRecallHTTPServer((args.host, args.port), palace,
354
+ api_key=api_key, cors_origin=args.cors_origin)
355
+ auth_note = ("已启用 API Key 认证" if api_key
356
+ else "无认证(仅本机,建议生产环境提供 --api-key)")
357
+ cors_note = ("跨域受限" if not args.cors_origin
358
+ else f"允许跨域 Origin={args.cors_origin}")
359
+ print(f"[VecRecall API] 监听 http://{args.host}:{args.port} "
360
+ f"embedder={type(emb).__name__} wing={args.wing}",
361
+ file=sys.stderr)
362
+ print(f"[VecRecall API] 安全: {auth_note} | {cors_note}",
363
+ file=sys.stderr)
364
+ try:
365
+ server.serve_forever()
366
+ except KeyboardInterrupt:
367
+ pass
368
+ finally:
369
+ server.server_close()
370
+ palace.close()
371
+
372
+
373
+ if __name__ == "__main__":
374
+ main()
@@ -0,0 +1,20 @@
1
+ # VecRecall Blockchain Module
2
+ from vecrecall.blockchain.block import Block, BlockGroup
3
+ from vecrecall.blockchain.chain import BlockChain
4
+ from vecrecall.blockchain.indexer import extract_keywords, extract_from_messages
5
+ from vecrecall.blockchain.hooks import (
6
+ OpenClawBlockchainHook,
7
+ HermesBlockchainHook,
8
+ ClaudeCodeBlockchainHook,
9
+ create_hook,
10
+ )
11
+
12
+ __all__ = [
13
+ "Block", "BlockGroup",
14
+ "BlockChain",
15
+ "extract_keywords", "extract_from_messages",
16
+ "OpenClawBlockchainHook",
17
+ "HermesBlockchainHook",
18
+ "ClaudeCodeBlockchainHook",
19
+ "create_hook",
20
+ ]
@@ -0,0 +1,202 @@
1
+ """
2
+ VecRecall Blockchain — Block 区块数据结构
3
+
4
+ 每个区块对应一个上下文窗口的完整存档。
5
+
6
+ 区块结构:
7
+ - block_id 唯一标识
8
+ - index 区块序号(0, 1, 2...)
9
+ - timestamp 创建时间
10
+ - prev_hash 前一个区块的哈希(哈希链)
11
+ - content 完整原文(逐字存储)
12
+ - token_count token 数量估算
13
+ - keywords 关键词列表(用于检索)
14
+ - date_label 日期标签 YYYY-MM-DD
15
+ - wing 所属 wing
16
+ - session_id 来源会话 ID
17
+ - trigger 触发方式(auto_75/manual/compaction)
18
+ - hash 本区块哈希(由以上所有字段生成)
19
+ - group_id 所属大区块 ID(多个小区块组合时使用)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ import time
27
+ import uuid
28
+ from dataclasses import dataclass, field, asdict
29
+ from datetime import datetime
30
+ from typing import Optional
31
+
32
+
33
+ @dataclass
34
+ class Block:
35
+ """单个上下文区块"""
36
+ block_id: str
37
+ index: int
38
+ timestamp: float
39
+ prev_hash: str
40
+ content: str
41
+ token_count: int
42
+ keywords: list[str]
43
+ date_label: str
44
+ wing: str
45
+ session_id: str
46
+ trigger: str # auto_75 | manual | compaction | session_end
47
+ hash: str = ""
48
+ group_id: str = "" # 归属的大区块 ID,空表示未归组
49
+ metadata: dict = field(default_factory=dict)
50
+
51
+ def __post_init__(self):
52
+ if not self.hash:
53
+ self.hash = self._compute_hash()
54
+
55
+ def _compute_hash(self) -> str:
56
+ """基于区块所有核心字段生成哈希,保证不可篡改"""
57
+ data = {
58
+ "block_id": self.block_id,
59
+ "index": self.index,
60
+ "timestamp": self.timestamp,
61
+ "prev_hash": self.prev_hash,
62
+ "content": self.content,
63
+ "token_count": self.token_count,
64
+ "keywords": sorted(self.keywords),
65
+ "date_label": self.date_label,
66
+ "wing": self.wing,
67
+ "session_id": self.session_id,
68
+ "trigger": self.trigger,
69
+ }
70
+ raw = json.dumps(data, ensure_ascii=False, sort_keys=True)
71
+ return hashlib.sha256(raw.encode('utf-8')).hexdigest()
72
+
73
+ def verify(self) -> bool:
74
+ """验证区块哈希是否被篡改"""
75
+ return self.hash == self._compute_hash()
76
+
77
+ def to_dict(self) -> dict:
78
+ return asdict(self)
79
+
80
+ @classmethod
81
+ def from_dict(cls, d: dict) -> "Block":
82
+ return cls(**d)
83
+
84
+ @classmethod
85
+ def create(
86
+ cls,
87
+ index: int,
88
+ prev_hash: str,
89
+ content: str,
90
+ wing: str = "default",
91
+ session_id: str = "",
92
+ trigger: str = "manual",
93
+ keywords: list[str] | None = None,
94
+ metadata: dict | None = None,
95
+ ) -> "Block":
96
+ now = time.time()
97
+ date_label = datetime.fromtimestamp(now).strftime("%Y-%m-%d")
98
+ token_count = len(content) // 4 # 粗略估算:1 token ≈ 4 字符
99
+
100
+ return cls(
101
+ block_id=str(uuid.uuid4()),
102
+ index=index,
103
+ timestamp=now,
104
+ prev_hash=prev_hash,
105
+ content=content,
106
+ token_count=token_count,
107
+ keywords=keywords or [],
108
+ date_label=date_label,
109
+ wing=wing,
110
+ session_id=session_id or str(uuid.uuid4()),
111
+ trigger=trigger,
112
+ metadata=metadata or {},
113
+ )
114
+
115
+ @property
116
+ def summary(self) -> str:
117
+ """区块摘要,用于展示"""
118
+ kb = len(self.content.encode('utf-8')) / 1024
119
+ return (f"Block #{self.index} | {self.date_label} | "
120
+ f"{self.token_count:,} tokens | {kb:.1f}KB | "
121
+ f"trigger={self.trigger} | "
122
+ f"keywords=[{', '.join(self.keywords[:5])}]")
123
+
124
+
125
+ @dataclass
126
+ class BlockGroup:
127
+ """
128
+ 大区块:多个小区块的组合。
129
+ 当小区块数量达到阈值时,自动组合成大区块。
130
+ 大区块可以继续组合成更大的区块(树状结构)。
131
+ """
132
+ group_id: str
133
+ level: int # 层级:1=小区块组,2=大区块组,3=超大区块组...
134
+ block_ids: list[str] # 包含的区块/子组 ID
135
+ timestamp: float
136
+ date_range: tuple[str, str] # (开始日期, 结束日期)
137
+ total_tokens: int
138
+ keywords: list[str] # 合并所有子块关键词
139
+ wing: str
140
+ hash: str = ""
141
+
142
+ def __post_init__(self):
143
+ if not self.hash:
144
+ self.hash = self._compute_hash()
145
+
146
+ def _compute_hash(self) -> str:
147
+ data = {
148
+ "group_id": self.group_id,
149
+ "level": self.level,
150
+ "block_ids": self.block_ids,
151
+ "timestamp": self.timestamp,
152
+ "date_range": list(self.date_range),
153
+ "total_tokens": self.total_tokens,
154
+ "wing": self.wing,
155
+ }
156
+ raw = json.dumps(data, ensure_ascii=False, sort_keys=True)
157
+ return hashlib.sha256(raw.encode('utf-8')).hexdigest()
158
+
159
+ def to_dict(self) -> dict:
160
+ d = asdict(self)
161
+ d['date_range'] = list(self.date_range)
162
+ return d
163
+
164
+ @classmethod
165
+ def from_dict(cls, d: dict) -> "BlockGroup":
166
+ d['date_range'] = tuple(d['date_range'])
167
+ return cls(**d)
168
+
169
+ @classmethod
170
+ def create(
171
+ cls,
172
+ blocks: list[Block],
173
+ level: int = 1,
174
+ wing: str = "default",
175
+ ) -> "BlockGroup":
176
+ now = time.time()
177
+ dates = sorted(set(b.date_label for b in blocks))
178
+ all_keywords = []
179
+ for b in blocks:
180
+ all_keywords.extend(b.keywords)
181
+ # 去重保留高频关键词
182
+ kw_freq = {}
183
+ for kw in all_keywords:
184
+ kw_freq[kw] = kw_freq.get(kw, 0) + 1
185
+ top_keywords = sorted(kw_freq, key=lambda k: kw_freq[k], reverse=True)[:20]
186
+
187
+ return cls(
188
+ group_id=str(uuid.uuid4()),
189
+ level=level,
190
+ block_ids=[b.block_id for b in blocks],
191
+ timestamp=now,
192
+ date_range=(dates[0] if dates else "", dates[-1] if dates else ""),
193
+ total_tokens=sum(b.token_count for b in blocks),
194
+ keywords=top_keywords,
195
+ wing=wing,
196
+ )
197
+
198
+ @property
199
+ def summary(self) -> str:
200
+ return (f"Group L{self.level} | {self.date_range[0]} ~ {self.date_range[1]} | "
201
+ f"{len(self.block_ids)} blocks | {self.total_tokens:,} tokens | "
202
+ f"keywords=[{', '.join(self.keywords[:5])}]")