zifu-memory 0.1.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.
- memory_machine.py +401 -0
- zifu_contract.py +160 -0
- zifu_index.py +168 -0
- zifu_mcp_server.py +194 -0
- zifu_memory-0.1.0.dist-info/METADATA +103 -0
- zifu_memory-0.1.0.dist-info/RECORD +11 -0
- zifu_memory-0.1.0.dist-info/WHEEL +5 -0
- zifu_memory-0.1.0.dist-info/entry_points.txt +2 -0
- zifu_memory-0.1.0.dist-info/licenses/LICENSE +202 -0
- zifu_memory-0.1.0.dist-info/top_level.txt +5 -0
- zifu_scope.py +116 -0
memory_machine.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
数字空间记忆机 · 第一版实验(V0.1)
|
|
5
|
+
|
|
6
|
+
分层设计:
|
|
7
|
+
热层(正本) = 本目录 events/ 事件流(JSONL 追加写)+ memory.db 索引
|
|
8
|
+
快照(对账) = snapshots/ 定期状态快照(JSON + SHA256 指纹)
|
|
9
|
+
冷层(预留) = 打包后推送魔搭私有仓(本版只做本地打包,不联网)
|
|
10
|
+
|
|
11
|
+
核心闭环:
|
|
12
|
+
record -> 事件追加进事件流并写入索引
|
|
13
|
+
snapshot-> 当前状态拍快照并记指纹
|
|
14
|
+
diff -> 两个快照之间算差分
|
|
15
|
+
replay -> 从任一快照 + 事件流重建指定时刻的状态(可核验)
|
|
16
|
+
pack -> 打包冷备(供后续推魔搭)
|
|
17
|
+
|
|
18
|
+
仅依赖 Python 标准库。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import sqlite3
|
|
26
|
+
import sys
|
|
27
|
+
import time
|
|
28
|
+
from datetime import datetime, timedelta
|
|
29
|
+
|
|
30
|
+
DATA_DIR = os.environ.get("ZIFU_HOME", os.path.join(os.path.expanduser("~"), ".zifu"))
|
|
31
|
+
EVENTS_DIR = os.path.join(DATA_DIR, "events")
|
|
32
|
+
SNAPSHOTS_DIR = os.path.join(DATA_DIR, "snapshots")
|
|
33
|
+
PACKS_DIR = os.path.join(DATA_DIR, "packs")
|
|
34
|
+
DB_PATH = os.path.join(DATA_DIR, "memory.db")
|
|
35
|
+
|
|
36
|
+
# 时间分层(秒):7 天内细粒度快照全留,90 天内保留整点快照,更久只留事件册与指纹
|
|
37
|
+
TIER_FINE = 7 * 86400
|
|
38
|
+
TIER_MID = 90 * 86400
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def now_ts():
|
|
42
|
+
return time.time()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def fmt_ts(ts):
|
|
46
|
+
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def snap_hour(ts):
|
|
50
|
+
"""快照文件名按整点对齐,便于分层与去重。"""
|
|
51
|
+
return datetime.fromtimestamp(ts).strftime("%Y%m%d%H")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ensure_dirs():
|
|
55
|
+
for d in (EVENTS_DIR, SNAPSHOTS_DIR, PACKS_DIR):
|
|
56
|
+
os.makedirs(d, exist_ok=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_db():
|
|
60
|
+
conn = sqlite3.connect(DB_PATH)
|
|
61
|
+
conn.execute(
|
|
62
|
+
"""CREATE TABLE IF NOT EXISTS events (
|
|
63
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
64
|
+
ts REAL NOT NULL,
|
|
65
|
+
entity TEXT NOT NULL,
|
|
66
|
+
kind TEXT NOT NULL,
|
|
67
|
+
payload TEXT NOT NULL,
|
|
68
|
+
fingerprint TEXT NOT NULL
|
|
69
|
+
)"""
|
|
70
|
+
)
|
|
71
|
+
conn.execute(
|
|
72
|
+
"CREATE INDEX IF NOT EXISTS idx_events_entity_ts ON events(entity, ts)"
|
|
73
|
+
)
|
|
74
|
+
return conn
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def state_fingerprint(state: dict) -> str:
|
|
78
|
+
"""对状态做确定性指纹:排序后 JSON 序列化再取 SHA256。"""
|
|
79
|
+
blob = json.dumps(state, ensure_ascii=False, sort_keys=True)
|
|
80
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------- 事件流(正本) ----------
|
|
84
|
+
|
|
85
|
+
def event_file_path(ts):
|
|
86
|
+
"""事件流按天分文件,避免单文件无限膨胀。"""
|
|
87
|
+
return os.path.join(
|
|
88
|
+
EVENTS_DIR, datetime.fromtimestamp(ts).strftime("events-%Y%m%d.jsonl")
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def record(entity: str, kind: str, payload: dict, source: str = "internal", **meta) -> dict:
|
|
93
|
+
"""source: internal=体系内部动作(正本,完整);external=外部观测(采样,带证据)
|
|
94
|
+
meta: 可选归属标签(scope/session_id/agent_id/user_id),随事件落正本。"""
|
|
95
|
+
if source not in ("internal", "external"):
|
|
96
|
+
raise ValueError("source 必须是 internal 或 external")
|
|
97
|
+
ts = now_ts()
|
|
98
|
+
event = {
|
|
99
|
+
"ts": ts,
|
|
100
|
+
"entity": entity,
|
|
101
|
+
"kind": kind,
|
|
102
|
+
"source": source,
|
|
103
|
+
"payload": payload,
|
|
104
|
+
}
|
|
105
|
+
event.update(meta)
|
|
106
|
+
line = json.dumps(event, ensure_ascii=False)
|
|
107
|
+
os.makedirs(EVENTS_DIR, exist_ok=True) # 全新部署时目录尚不存在,按需自建
|
|
108
|
+
with open(event_file_path(ts), "a", encoding="utf-8") as f:
|
|
109
|
+
f.write(line + "\n")
|
|
110
|
+
|
|
111
|
+
conn = get_db()
|
|
112
|
+
conn.execute(
|
|
113
|
+
"INSERT INTO events (ts, entity, kind, payload, fingerprint) VALUES (?,?,?,?,?)",
|
|
114
|
+
(ts, entity, kind, json.dumps(payload, ensure_ascii=False), state_fingerprint(event)),
|
|
115
|
+
)
|
|
116
|
+
conn.commit()
|
|
117
|
+
conn.close()
|
|
118
|
+
return event
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def read_events(since_ts: float = 0.0, until_ts: float = None):
|
|
122
|
+
"""顺序读事件流(正本),返回事件 dict 列表(按 ts 升序)。"""
|
|
123
|
+
if until_ts is None:
|
|
124
|
+
until_ts = now_ts()
|
|
125
|
+
out = []
|
|
126
|
+
if not os.path.isdir(EVENTS_DIR):
|
|
127
|
+
return out
|
|
128
|
+
for name in sorted(os.listdir(EVENTS_DIR)):
|
|
129
|
+
if not name.startswith("events-") or not name.endswith(".jsonl"):
|
|
130
|
+
continue
|
|
131
|
+
path = os.path.join(EVENTS_DIR, name)
|
|
132
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
133
|
+
for line in f:
|
|
134
|
+
line = line.strip()
|
|
135
|
+
if not line:
|
|
136
|
+
continue
|
|
137
|
+
ev = json.loads(line)
|
|
138
|
+
if since_ts < ev["ts"] <= until_ts:
|
|
139
|
+
out.append(ev)
|
|
140
|
+
out.sort(key=lambda e: e["ts"])
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ---------- 状态与快照 ----------
|
|
145
|
+
|
|
146
|
+
def apply_event(state: dict, ev: dict) -> dict:
|
|
147
|
+
"""事件如何改变状态。V0.1 用最简语义:
|
|
148
|
+
kind=upsert -> state[entity] = payload
|
|
149
|
+
kind=delete -> state.pop(entity, None)
|
|
150
|
+
其他 kind -> 记录到 state.setdefault('_log', []) 便于观察
|
|
151
|
+
"""
|
|
152
|
+
entity, kind, payload = ev["entity"], ev["kind"], ev["payload"]
|
|
153
|
+
if kind in ("upsert", "observed"):
|
|
154
|
+
# observed = 外部实体的认知状态更新(我们观测到的样子)
|
|
155
|
+
state[entity] = payload
|
|
156
|
+
elif kind == "delete":
|
|
157
|
+
state.pop(entity, None)
|
|
158
|
+
else:
|
|
159
|
+
state.setdefault("_log", []).append(
|
|
160
|
+
{"ts": ev["ts"], "entity": entity, "kind": kind, "payload": payload}
|
|
161
|
+
)
|
|
162
|
+
return state
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def current_state() -> dict:
|
|
166
|
+
state = {}
|
|
167
|
+
for ev in read_events():
|
|
168
|
+
apply_event(state, ev)
|
|
169
|
+
return state
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def snapshot_path(hour_key: str) -> str:
|
|
173
|
+
return os.path.join(SNAPSHOTS_DIR, f"snap-{hour_key}.json")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def take_snapshot() -> dict:
|
|
177
|
+
ts = now_ts()
|
|
178
|
+
state = current_state()
|
|
179
|
+
hour_key = snap_hour(ts)
|
|
180
|
+
# 同一小时重复拍摄:带序号保留多份,不覆盖
|
|
181
|
+
path = snapshot_path(hour_key)
|
|
182
|
+
seq = 1
|
|
183
|
+
while os.path.exists(path):
|
|
184
|
+
seq += 1
|
|
185
|
+
path = os.path.join(SNAPSHOTS_DIR, f"snap-{hour_key}-{seq:02d}.json")
|
|
186
|
+
snap = {
|
|
187
|
+
"hour_key": os.path.basename(path)[len("snap-"):-len(".json")],
|
|
188
|
+
"taken_at": ts,
|
|
189
|
+
"taken_at_str": fmt_ts(ts),
|
|
190
|
+
"fingerprint": state_fingerprint(state),
|
|
191
|
+
"state": state,
|
|
192
|
+
}
|
|
193
|
+
os.makedirs(SNAPSHOTS_DIR, exist_ok=True) # 全新部署时目录尚不存在,按需自建
|
|
194
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
195
|
+
json.dump(snap, f, ensure_ascii=False, indent=2)
|
|
196
|
+
return snap
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def load_snapshot(hour_key: str):
|
|
200
|
+
path = snapshot_path(hour_key)
|
|
201
|
+
if not os.path.exists(path):
|
|
202
|
+
return None
|
|
203
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
204
|
+
return json.load(f)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def latest_snapshot_before(ts: float):
|
|
208
|
+
"""找实际拍摄时间(taken_at)在 ts 之前(含)最近的快照。
|
|
209
|
+
同一小时重复拍摄时保留最新一份,文件名带序号避免覆盖。"""
|
|
210
|
+
best, best_taken = None, -1.0
|
|
211
|
+
if not os.path.isdir(SNAPSHOTS_DIR):
|
|
212
|
+
return None
|
|
213
|
+
for name in sorted(os.listdir(SNAPSHOTS_DIR)):
|
|
214
|
+
if not name.startswith("snap-") or not name.endswith(".json"):
|
|
215
|
+
continue
|
|
216
|
+
with open(os.path.join(SNAPSHOTS_DIR, name), "r", encoding="utf-8") as f:
|
|
217
|
+
snap = json.load(f)
|
|
218
|
+
if snap.get("taken_at", -1.0) <= ts and snap.get("taken_at", -1.0) > best_taken:
|
|
219
|
+
best, best_taken = snap, snap["taken_at"]
|
|
220
|
+
return best
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ---------- 差分与回放 ----------
|
|
224
|
+
|
|
225
|
+
def diff_snapshots(old: dict, new: dict) -> dict:
|
|
226
|
+
"""对比两个快照的状态,输出增/改/删。"""
|
|
227
|
+
a, b = old.get("state", {}), new.get("state", {})
|
|
228
|
+
added = {k: b[k] for k in b.keys() - a.keys()}
|
|
229
|
+
removed = {k: a[k] for k in a.keys() - b.keys()}
|
|
230
|
+
changed = {
|
|
231
|
+
k: {"from": a[k], "to": b[k]}
|
|
232
|
+
for k in a.keys() & b.keys()
|
|
233
|
+
if a[k] != b[k]
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
"from_hour": old.get("hour_key"),
|
|
237
|
+
"to_hour": new.get("hour_key"),
|
|
238
|
+
"added": added,
|
|
239
|
+
"removed": removed,
|
|
240
|
+
"changed": changed,
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def replay(at_ts: float = None) -> dict:
|
|
245
|
+
"""从 at_ts 之前最近的快照出发,重放事件流,重建该时刻状态。
|
|
246
|
+
快照指纹校验通过才继续,保证可核验。"""
|
|
247
|
+
if at_ts is None:
|
|
248
|
+
at_ts = now_ts()
|
|
249
|
+
snap = latest_snapshot_before(at_ts)
|
|
250
|
+
if snap is not None:
|
|
251
|
+
fp = state_fingerprint(snap["state"])
|
|
252
|
+
if fp != snap["fingerprint"]:
|
|
253
|
+
raise RuntimeError(f"快照指纹不匹配:{snap['hour_key']},疑似被篡改或损坏")
|
|
254
|
+
state = json.loads(json.dumps(snap["state"])) # 深拷贝
|
|
255
|
+
base_ts = snap["taken_at"]
|
|
256
|
+
else:
|
|
257
|
+
state, base_ts = {}, 0.0
|
|
258
|
+
for ev in read_events(since_ts=base_ts, until_ts=at_ts):
|
|
259
|
+
apply_event(state, ev)
|
|
260
|
+
return {"at": at_ts, "at_str": fmt_ts(at_ts), "state": state,
|
|
261
|
+
"fingerprint": state_fingerprint(state), "from_snapshot": snap["hour_key"] if snap else None}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---------- 实体级溯源查询(只读) ----------
|
|
265
|
+
|
|
266
|
+
def lookup(keyword: str) -> dict:
|
|
267
|
+
"""按关键词查实体:匹配实体名或 payload 正文(不区分大小写)。
|
|
268
|
+
返回每个匹配实体的事件计数、首末时间、kind 集合与最新一条事件——
|
|
269
|
+
回答「做没做、定没定」,覆盖 record/milestone 等不进实体状态的 kind。"""
|
|
270
|
+
kw = keyword.lower()
|
|
271
|
+
by_entity = {}
|
|
272
|
+
for ev in read_events():
|
|
273
|
+
blob = ev["entity"] + " " + json.dumps(ev["payload"], ensure_ascii=False)
|
|
274
|
+
if kw in blob.lower():
|
|
275
|
+
by_entity.setdefault(ev["entity"], []).append(ev)
|
|
276
|
+
entities = {}
|
|
277
|
+
for ent, evs in sorted(by_entity.items()):
|
|
278
|
+
evs.sort(key=lambda e: e["ts"])
|
|
279
|
+
last = evs[-1]
|
|
280
|
+
entities[ent] = {
|
|
281
|
+
"event_count": len(evs),
|
|
282
|
+
"first_at": fmt_ts(evs[0]["ts"]),
|
|
283
|
+
"last_at": fmt_ts(last["ts"]),
|
|
284
|
+
"kinds": sorted({e["kind"] for e in evs}),
|
|
285
|
+
"latest": {
|
|
286
|
+
"at": fmt_ts(last["ts"]),
|
|
287
|
+
"kind": last["kind"],
|
|
288
|
+
"source": last["source"],
|
|
289
|
+
"payload": last["payload"],
|
|
290
|
+
},
|
|
291
|
+
}
|
|
292
|
+
return {"query": keyword, "matches": len(entities), "entities": entities}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ---------- 冷备打包 ----------
|
|
296
|
+
|
|
297
|
+
def pack() -> str:
|
|
298
|
+
ts = now_ts()
|
|
299
|
+
tag = datetime.fromtimestamp(ts).strftime("%Y%m%d-%H%M%S")
|
|
300
|
+
out = os.path.join(PACKS_DIR, f"memory-pack-{tag}.json")
|
|
301
|
+
manifest = {
|
|
302
|
+
"packed_at": ts,
|
|
303
|
+
"packed_at_str": fmt_ts(ts),
|
|
304
|
+
"events_files": sorted(os.listdir(EVENTS_DIR)) if os.path.isdir(EVENTS_DIR) else [],
|
|
305
|
+
"snapshots": {},
|
|
306
|
+
"note": "本包为冷备正本镜像,可推送魔搭私有仓 zongyuanroot/yuanji-works",
|
|
307
|
+
}
|
|
308
|
+
for name in sorted(os.listdir(SNAPSHOTS_DIR)):
|
|
309
|
+
path = os.path.join(SNAPSHOTS_DIR, name)
|
|
310
|
+
with open(path, "rb") as f:
|
|
311
|
+
manifest["snapshots"][name] = hashlib.sha256(f.read()).hexdigest()
|
|
312
|
+
with open(out, "w", encoding="utf-8") as f:
|
|
313
|
+
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# ---------- 分层清理(V0.1 先只报告不删除,避免误伤) ----------
|
|
318
|
+
|
|
319
|
+
def retention_report() -> dict:
|
|
320
|
+
now = now_ts()
|
|
321
|
+
keep, demote, drop = [], [], []
|
|
322
|
+
if os.path.isdir(SNAPSHOTS_DIR):
|
|
323
|
+
for name in sorted(os.listdir(SNAPSHOTS_DIR)):
|
|
324
|
+
if not (name.startswith("snap-") and name.endswith(".json")):
|
|
325
|
+
continue
|
|
326
|
+
hour_key = name[len("snap-"):-len(".json")]
|
|
327
|
+
try:
|
|
328
|
+
snap_ts = datetime.strptime(hour_key, "%Y%m%d%H").timestamp()
|
|
329
|
+
except ValueError:
|
|
330
|
+
continue
|
|
331
|
+
age = now - snap_ts
|
|
332
|
+
if age <= TIER_FINE:
|
|
333
|
+
keep.append(hour_key)
|
|
334
|
+
elif age <= TIER_MID:
|
|
335
|
+
demote.append(hour_key)
|
|
336
|
+
else:
|
|
337
|
+
drop.append(hour_key)
|
|
338
|
+
return {"keep_fine": keep, "keep_mid": demote, "candidates_drop": drop}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def main():
|
|
342
|
+
parser = argparse.ArgumentParser(description="数字空间记忆机 V0.1")
|
|
343
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
344
|
+
|
|
345
|
+
p = sub.add_parser("record", help="记录一条事件")
|
|
346
|
+
p.add_argument("entity")
|
|
347
|
+
p.add_argument("kind")
|
|
348
|
+
p.add_argument("payload", help='JSON 字符串,如 \'{"status":"ok"}\'')
|
|
349
|
+
p.add_argument("--source", default="internal", choices=["internal", "external"],
|
|
350
|
+
help="internal=内部动作,external=外部观测")
|
|
351
|
+
|
|
352
|
+
sub.add_parser("snapshot", help="对当前状态拍快照")
|
|
353
|
+
sub.add_parser("state", help="查看当前重建状态与指纹")
|
|
354
|
+
sub.add_parser("pack", help="打包冷备")
|
|
355
|
+
sub.add_parser("retention", help="查看时间分层清理报告")
|
|
356
|
+
|
|
357
|
+
p = sub.add_parser("diff", help="对比两个整点快照")
|
|
358
|
+
p.add_argument("old_hour")
|
|
359
|
+
p.add_argument("new_hour")
|
|
360
|
+
|
|
361
|
+
p = sub.add_parser("replay", help="重建指定时刻状态(默认现在)")
|
|
362
|
+
p.add_argument("at", nargs="?", help='时刻,如 "2026-11-26 08:00:00"')
|
|
363
|
+
|
|
364
|
+
p = sub.add_parser("lookup", help="按关键词查实体最新状态(做没做、定没定)")
|
|
365
|
+
p.add_argument("keyword", help="实体名或 payload 关键词,如 PAYATHON、公钥")
|
|
366
|
+
|
|
367
|
+
args = parser.parse_args()
|
|
368
|
+
|
|
369
|
+
ensure_dirs()
|
|
370
|
+
if args.cmd == "record":
|
|
371
|
+
ev = record(args.entity, args.kind, json.loads(args.payload), source=args.source)
|
|
372
|
+
print(json.dumps({"ok": True, "ts": fmt_ts(ev["ts"]), "entity": ev["entity"],
|
|
373
|
+
"kind": ev["kind"], "source": ev["source"]}, ensure_ascii=False))
|
|
374
|
+
elif args.cmd == "snapshot":
|
|
375
|
+
snap = take_snapshot()
|
|
376
|
+
print(json.dumps({"ok": True, "hour": snap["hour_key"],
|
|
377
|
+
"fingerprint": snap["fingerprint"],
|
|
378
|
+
"entities": len([k for k in snap["state"] if k != "_log"])},
|
|
379
|
+
ensure_ascii=False))
|
|
380
|
+
elif args.cmd == "state":
|
|
381
|
+
r = replay()
|
|
382
|
+
print(json.dumps(r, ensure_ascii=False, indent=2))
|
|
383
|
+
elif args.cmd == "diff":
|
|
384
|
+
old, new = load_snapshot(args.old_hour), load_snapshot(args.new_hour)
|
|
385
|
+
if old is None or new is None:
|
|
386
|
+
print(json.dumps({"ok": False, "error": "快照不存在"}, ensure_ascii=False))
|
|
387
|
+
sys.exit(1)
|
|
388
|
+
print(json.dumps(diff_snapshots(old, new), ensure_ascii=False, indent=2))
|
|
389
|
+
elif args.cmd == "replay":
|
|
390
|
+
at = datetime.strptime(args.at, "%Y-%m-%d %H:%M:%S").timestamp() if args.at else None
|
|
391
|
+
print(json.dumps(replay(at), ensure_ascii=False, indent=2))
|
|
392
|
+
elif args.cmd == "lookup":
|
|
393
|
+
print(json.dumps(lookup(args.keyword), ensure_ascii=False, indent=2))
|
|
394
|
+
elif args.cmd == "pack":
|
|
395
|
+
print(json.dumps({"ok": True, "pack": os.path.relpath(pack(), BASE)}, ensure_ascii=False))
|
|
396
|
+
elif args.cmd == "retention":
|
|
397
|
+
print(json.dumps(retention_report(), ensure_ascii=False, indent=2))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
if __name__ == "__main__":
|
|
401
|
+
main()
|
zifu_contract.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
紫府 · 契约模式(V0.2 第二块砖)
|
|
5
|
+
|
|
6
|
+
把记忆契约闸的五契约纪律原生落进紫府自己的账本(不依赖中枢存储):
|
|
7
|
+
契约1 来源指针先行:事实登记必须携带可解析来源指针(事件文件+ts+指纹)
|
|
8
|
+
契约2 重复写即错:同 fact_id 重复登记是确定性错误;改口走 replace 并留痕
|
|
9
|
+
契约3 注入硬预算:zifu_inject 按字符预算确定性装配上下文,结果可复算
|
|
10
|
+
契约4 重放幂等:账本重放任意次结果一致(append-only + 确定性排序)
|
|
11
|
+
契约5 fork 一致视图:zifu_view(at_ts) 返回该时刻状态+当时仍有效的事实
|
|
12
|
+
|
|
13
|
+
账本:facts.jsonl 只追加、禁改删历史(正本)。
|
|
14
|
+
仅依赖 Python 标准库。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
|
|
22
|
+
import memory_machine as mm
|
|
23
|
+
|
|
24
|
+
FACTS_PATH = os.path.join(os.environ.get("ZIFU_HOME", os.path.join(os.path.expanduser("~"), ".zifu")), "facts.jsonl")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _append(entry: dict) -> dict:
|
|
28
|
+
with open(FACTS_PATH, "a", encoding="utf-8") as f:
|
|
29
|
+
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
30
|
+
return entry
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _load_all() -> list[dict]:
|
|
34
|
+
if not os.path.exists(FACTS_PATH):
|
|
35
|
+
return []
|
|
36
|
+
out = []
|
|
37
|
+
with open(FACTS_PATH, "r", encoding="utf-8") as f:
|
|
38
|
+
for line in f:
|
|
39
|
+
line = line.strip()
|
|
40
|
+
if line:
|
|
41
|
+
out.append(json.loads(line))
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _state() -> dict:
|
|
46
|
+
"""重放账本得到事实现状(契约4:确定性重放)。"""
|
|
47
|
+
state: dict[str, dict] = {}
|
|
48
|
+
for entry in _load_all():
|
|
49
|
+
if entry["op"] == "assert":
|
|
50
|
+
state[entry["fact_id"]] = {**entry, "status": "active"}
|
|
51
|
+
elif entry["op"] == "replace":
|
|
52
|
+
old = state.get(entry["old_id"])
|
|
53
|
+
if old is not None:
|
|
54
|
+
old["status"] = "replaced"
|
|
55
|
+
old["replaced_by"] = entry["fact_id"]
|
|
56
|
+
state[entry["fact_id"]] = {**entry, "status": "active"}
|
|
57
|
+
elif entry["op"] == "retire":
|
|
58
|
+
if entry["fact_id"] in state:
|
|
59
|
+
state[entry["fact_id"]]["status"] = "retired"
|
|
60
|
+
state[entry["fact_id"]]["retire_reason"] = entry.get("reason", "")
|
|
61
|
+
return state
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def assert_fact(fact_id: str, statement: str, entity: str,
|
|
65
|
+
pointer: dict) -> dict:
|
|
66
|
+
"""契约1+2:带来源指针登记事实;同 ID 重复登记是确定性错误。"""
|
|
67
|
+
if not pointer or not pointer.get("event_file") or not pointer.get("fingerprint"):
|
|
68
|
+
raise ValueError("契约1拒登:缺少可解析来源指针(event_file/ts/fingerprint)")
|
|
69
|
+
if not os.path.exists(pointer["event_file"]):
|
|
70
|
+
raise ValueError("契约1拒登:来源指针指向的事件文件不存在")
|
|
71
|
+
state = _state()
|
|
72
|
+
if fact_id in state:
|
|
73
|
+
raise ValueError(f"契约2拒登:fact_id={fact_id} 已存在(status={state[fact_id]['status']}),改口请走 replace")
|
|
74
|
+
ev = mm.record(entity=entity, kind="fact_assert",
|
|
75
|
+
payload={"fact_id": fact_id, "statement": statement})
|
|
76
|
+
entry = _append({
|
|
77
|
+
"op": "assert", "fact_id": fact_id, "statement": statement,
|
|
78
|
+
"entity": entity, "ts": ev["ts"],
|
|
79
|
+
"pointer": {"event_file": pointer["event_file"], "ts": pointer["ts"],
|
|
80
|
+
"fingerprint": pointer["fingerprint"]},
|
|
81
|
+
})
|
|
82
|
+
return entry
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def replace_fact(old_id: str, new_statement: str, reason: str,
|
|
86
|
+
entity: str) -> dict:
|
|
87
|
+
"""契约2:改口走 replace,旧事实标记 replaced 并留痕,历史不删。"""
|
|
88
|
+
state = _state()
|
|
89
|
+
if old_id not in state:
|
|
90
|
+
raise ValueError(f"replace 拒绝:fact_id={old_id} 不存在")
|
|
91
|
+
if state[old_id]["status"] != "active":
|
|
92
|
+
raise ValueError(f"replace 拒绝:fact_id={old_id} 当前 status={state[old_id]['status']},只有 active 事实可改口")
|
|
93
|
+
new_id = f"{old_id}.r{sum(1 for e in _load_all() if e.get('old_id') == old_id) + 1}"
|
|
94
|
+
ev = mm.record(entity=entity, kind="fact_replace",
|
|
95
|
+
payload={"old_id": old_id, "new_id": new_id, "reason": reason})
|
|
96
|
+
entry = _append({
|
|
97
|
+
"op": "replace", "old_id": old_id, "fact_id": new_id,
|
|
98
|
+
"statement": new_statement, "entity": entity, "ts": ev["ts"],
|
|
99
|
+
"reason": reason,
|
|
100
|
+
"pointer": {"event_file": mm.event_file_path(ev["ts"]), "ts": ev["ts"],
|
|
101
|
+
"fingerprint": mm.state_fingerprint(ev)},
|
|
102
|
+
})
|
|
103
|
+
return entry
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def retire_fact(fact_id: str, reason: str) -> dict:
|
|
107
|
+
"""事实退役:只标记不删除(账本只追加)。"""
|
|
108
|
+
state = _state()
|
|
109
|
+
if fact_id not in state:
|
|
110
|
+
raise ValueError(f"retire 拒绝:fact_id={fact_id} 不存在")
|
|
111
|
+
if state[fact_id]["status"] == "retired":
|
|
112
|
+
return {"op": "retire", "fact_id": fact_id, "status": "retired", "note": "已是退役态,幂等"}
|
|
113
|
+
ev = mm.record(entity=state[fact_id].get("entity", "unknown"), kind="fact_retire",
|
|
114
|
+
payload={"fact_id": fact_id, "reason": reason})
|
|
115
|
+
return _append({"op": "retire", "fact_id": fact_id, "reason": reason, "ts": ev["ts"]})
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def list_facts(status: str | None = None) -> list[dict]:
|
|
119
|
+
state = _state()
|
|
120
|
+
out = [{"fact_id": k, **{kk: vv for kk, vv in v.items() if kk != "op"}}
|
|
121
|
+
for k, v in sorted(state.items())]
|
|
122
|
+
if status:
|
|
123
|
+
out = [f for f in out if f.get("status") == status]
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def inject(query: str | None = None, budget: int = 400) -> dict:
|
|
128
|
+
"""契约3:硬预算装配。active 事实按 (ts, fact_id) 确定性排序,
|
|
129
|
+
逐条装入直到预算(字符数)用尽;结果可复算。query 提供时先按文义排序。"""
|
|
130
|
+
facts = [f for f in list_facts(status="active")]
|
|
131
|
+
if query:
|
|
132
|
+
import math
|
|
133
|
+
import zifu_index
|
|
134
|
+
qg = zifu_index._fallback_embed(query)
|
|
135
|
+
q_norm = math.sqrt(sum(v * v for v in qg.values()))
|
|
136
|
+
|
|
137
|
+
def _score(f: dict) -> float:
|
|
138
|
+
dg = zifu_index._fallback_embed(f["statement"])
|
|
139
|
+
d_norm = math.sqrt(sum(v * v for v in dg.values()))
|
|
140
|
+
return zifu_index._cosine(qg, dg, q_norm, d_norm)
|
|
141
|
+
|
|
142
|
+
facts.sort(key=lambda f: -_score(f))
|
|
143
|
+
else:
|
|
144
|
+
facts.sort(key=lambda f: (f["ts"], f["fact_id"]))
|
|
145
|
+
picked, used = [], 0
|
|
146
|
+
for f in facts:
|
|
147
|
+
line = f"[{f['fact_id']}] {f['statement']}"
|
|
148
|
+
if used + len(line) > budget:
|
|
149
|
+
continue
|
|
150
|
+
picked.append(line)
|
|
151
|
+
used += len(line)
|
|
152
|
+
return {"budget": budget, "used": used, "count": len(picked), "facts": picked}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def view(at_ts: float | None = None) -> dict:
|
|
156
|
+
"""契约5:fork 一致视图——该时刻的状态重建 + 当时仍 active 的事实。"""
|
|
157
|
+
state_snapshot = mm.replay(at_ts=at_ts)
|
|
158
|
+
ts = at_ts if at_ts is not None else mm.now_ts()
|
|
159
|
+
facts = [f for f in list_facts() if f["ts"] <= ts and f.get("status") == "active"]
|
|
160
|
+
return {"at_ts": ts, "state": state_snapshot, "active_facts": facts}
|