constraint-runtime 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.
fence_rule_engine.py ADDED
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # Copyright 2026 元极恒一
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+ """fence_rule_engine.py — 约束运行时·围栏规则引擎 v0.1(架构补齐方案组件一,2026-11-22)
19
+
20
+ 定位:约束线四件组件的第一件。把「模型给出决策之后、执行之前,过一道与模型不同源的
21
+ 硬规则校验」固化为可调用契约。规则是数据(JSON 规则包),引擎是代码——引擎不用模型判,
22
+ 天然满足「裁判与被测不同源」。
23
+
24
+ 核心原则:
25
+ 1. fail-closed:规则包损坏、字段缺失、单条规则求值异常——一律拒绝放行,宁可停机等人。
26
+ 2. 影子优先:规则可标 shadow(只记不拦),转正标准量化(连续窗口零破口零误伤),
27
+ 引擎只负责记账,转正动作由人拍板。
28
+ 3. 全程留痕:每次评估返回完整命中明细,可直接写入留痕重放器。
29
+
30
+ 规则包格式(JSON):
31
+ {
32
+ "package": "示例包", "version": "v0.1", "fail_closed": true,
33
+ "rules": [
34
+ {"id": "R1", "title": "单笔限额", "status": "live",
35
+ "match": {"all": [
36
+ {"field": "fields.amount", "op": ">", "value": 3000},
37
+ {"field": "fields.category", "op": "==", "value": "餐饮"}
38
+ ]},
39
+ "message": "餐饮单笔超过 3000,须分级审批"}
40
+ ]
41
+ }
42
+
43
+ match 支持组合:
44
+ {"all": [条件...]} 全部命中才命中
45
+ {"any": [条件...]} 任一命中即命中
46
+ 条件:{"field": "点分路径", "op": ">", "value": ...}
47
+ op ∈ > >= < <= == != contains regex in not_in exists not_exists
48
+
49
+ 用法:
50
+ from fence_rule_engine import FenceEngine
51
+ engine = FenceEngine("/path/to/rules.json")
52
+ verdict = engine.evaluate({"action": "...", "fields": {...}, "text": "..."})
53
+ # verdict = {"decision": "BLOCK"/"PASS"/"FAIL_CLOSED", "hits": [...], "notes": [...]}
54
+
55
+ CLI 自检:
56
+ fence_rule_engine.py selftest
57
+ """
58
+
59
+ import json
60
+ import os
61
+ import re
62
+ import sys
63
+ from collections import defaultdict
64
+
65
+ ENGINE_VERSION = "fence-rule-engine v0.1"
66
+
67
+ _OPS = {
68
+ ">": lambda a, b: a > b,
69
+ ">=": lambda a, b: a >= b,
70
+ "<": lambda a, b: a < b,
71
+ "<=": lambda a, b: a <= b,
72
+ "==": lambda a, b: a == b,
73
+ "!=": lambda a, b: a != b,
74
+ "contains": lambda a, b: b in a,
75
+ "regex": lambda a, b: re.search(b, a) is not None,
76
+ "in": lambda a, b: a in b,
77
+ "not_in": lambda a, b: a not in b,
78
+ "exists": lambda a, b: a is not None,
79
+ "not_exists": lambda a, b: a is None,
80
+ }
81
+
82
+
83
+ def _dig(obj, path):
84
+ """点分路径取值;路径不存在返回 None。"""
85
+ cur = obj
86
+ for part in path.split("."):
87
+ if isinstance(cur, dict) and part in cur:
88
+ cur = cur[part]
89
+ else:
90
+ return None
91
+ return cur
92
+
93
+
94
+ def _eval_condition(cond, event):
95
+ """单条件求值;求值异常向上抛,由规则层捕获转 fail-closed。
96
+ 字段缺失(None)视为不命中——缺字段是正常业务状态,不是规则损坏;
97
+ 未知算子、规则包结构错误仍按 fail-closed 处理。"""
98
+ op = cond["op"]
99
+ if op not in _OPS:
100
+ raise ValueError("unknown op: %s" % op)
101
+ actual = _dig(event, cond.get("field", ""))
102
+ if actual is None and op not in ("exists", "not_exists"):
103
+ return False
104
+ return _OPS[op](actual, cond.get("value"))
105
+
106
+
107
+ def _eval_match(match, event):
108
+ """组合条件求值:all / any / 单条件。"""
109
+ if "all" in match:
110
+ return all(_eval_match(c, event) for c in match["all"])
111
+ if "any" in match:
112
+ return any(_eval_match(c, event) for c in match["any"])
113
+ return _eval_condition(match, event)
114
+
115
+
116
+ class FenceEngine:
117
+ """围栏规则引擎:加载规则包,逐事件评估,输出放行/拦截/影子记账。"""
118
+
119
+ def __init__(self, rules_path):
120
+ self.rules_path = rules_path
121
+ self.stats = defaultdict(lambda: {"hits": 0, "blocks": 0, "notes": 0})
122
+ self._load(rules_path)
123
+
124
+ def _load(self, path):
125
+ with open(path, "r", encoding="utf-8") as f:
126
+ pkg = json.load(f)
127
+ if not isinstance(pkg, dict) or not isinstance(pkg.get("rules"), list):
128
+ raise ValueError("rule package malformed: missing rules[]")
129
+ self.package = pkg.get("package", "unnamed")
130
+ self.package_version = pkg.get("version", "?")
131
+ self.fail_closed = pkg.get("fail_closed", True)
132
+ self.rules = pkg["rules"]
133
+
134
+ def reload(self):
135
+ """规则包热更新(换制度不换引擎)。"""
136
+ self._load(self.rules_path)
137
+
138
+ def evaluate(self, event):
139
+ """评估一个事件。返回 verdict dict,可直接入留痕。"""
140
+ hits, notes, errors = [], [], []
141
+ for rule in self.rules:
142
+ rid = rule.get("id", "?")
143
+ status = rule.get("status", "live")
144
+ try:
145
+ matched = _eval_match(rule.get("match", {}), event)
146
+ except Exception as exc: # 单条规则异常 → 整体 fail-closed
147
+ errors.append({"rule": rid, "error": str(exc)})
148
+ continue
149
+ if not matched:
150
+ continue
151
+ entry = {"rule": rid, "title": rule.get("title", ""),
152
+ "status": status, "message": rule.get("message", "")}
153
+ if status == "shadow":
154
+ notes.append(entry)
155
+ self.stats[rid]["hits"] += 1
156
+ self.stats[rid]["notes"] += 1
157
+ else:
158
+ hits.append(entry)
159
+ self.stats[rid]["hits"] += 1
160
+ self.stats[rid]["blocks"] += 1
161
+
162
+ if errors and self.fail_closed:
163
+ return {"decision": "FAIL_CLOSED", "hits": hits, "notes": notes,
164
+ "errors": errors, "engine": ENGINE_VERSION}
165
+ if hits:
166
+ decision = "BLOCK"
167
+ elif errors:
168
+ decision = "PASS_WITH_ERRORS" # fail_closed=False 时降级放行但留痕
169
+ else:
170
+ decision = "PASS"
171
+ return {"decision": decision, "hits": hits, "notes": notes,
172
+ "errors": errors, "engine": ENGINE_VERSION}
173
+
174
+ def shadow_report(self):
175
+ """影子规则记账:转正评估的原料(零破口零误伤由人核对后拍板)。"""
176
+ return {"package": self.package, "version": self.package_version,
177
+ "rules": {rid: dict(v) for rid, v in sorted(self.stats.items())}}
178
+
179
+
180
+ def selftest():
181
+ """内置自检:live 拦截 / shadow 记账 / 放行 / fail-closed / 热更新。"""
182
+ import tempfile
183
+ ok = True
184
+
185
+ def check(name, cond):
186
+ nonlocal ok
187
+ print((" PASS " if cond else " FAIL ") + name)
188
+ ok = ok and cond
189
+
190
+ live_pkg = {
191
+ "package": "自检包", "version": "t1", "fail_closed": True,
192
+ "rules": [
193
+ {"id": "R1", "title": "大额拦截", "status": "live",
194
+ "match": {"field": "fields.amount", "op": ">", "value": 3000},
195
+ "message": "超限"},
196
+ {"id": "R2", "title": "敏感词影子", "status": "shadow",
197
+ "match": {"field": "text", "op": "contains", "value": "加急"},
198
+ "message": "出现施压话术"},
199
+ ],
200
+ }
201
+ broken_pkg = {"package": "坏包", "version": "t2", "fail_closed": True,
202
+ "rules": [{"id": "RX", "match": {"field": "fields.amount",
203
+ "op": "不存在的op", "value": 1}}]}
204
+
205
+ with tempfile.TemporaryDirectory() as td:
206
+ p1 = os.path.join(td, "live.json")
207
+ p2 = os.path.join(td, "broken.json")
208
+ for p, pkg in ((p1, live_pkg), (p2, broken_pkg)):
209
+ with open(p, "w", encoding="utf-8") as f:
210
+ json.dump(pkg, f, ensure_ascii=False)
211
+
212
+ eng = FenceEngine(p1)
213
+ v = eng.evaluate({"fields": {"amount": 5000}, "text": "麻烦加急处理"})
214
+ check("live 大额命中 → BLOCK", v["decision"] == "BLOCK" and len(v["hits"]) == 1)
215
+ check("shadow 施压话术只记不拦", len(v["notes"]) == 1 and v["decision"] == "BLOCK")
216
+
217
+ v = eng.evaluate({"fields": {"amount": 100}, "text": "正常报销"})
218
+ check("正常事件 → PASS", v["decision"] == "PASS" and not v["hits"] and not v["notes"])
219
+
220
+ v = eng.evaluate({"fields": {"amount": 100}, "text": "加急"})
221
+ check("纯影子命中 → PASS 但记账", v["decision"] == "PASS" and len(v["notes"]) == 1)
222
+
223
+ rep = eng.shadow_report()
224
+ check("影子记账可出报告", rep["rules"]["R2"]["notes"] == 2)
225
+
226
+ bad = FenceEngine(p2)
227
+ v = bad.evaluate({"fields": {"amount": 1}})
228
+ check("规则求值异常 → FAIL_CLOSED", v["decision"] == "FAIL_CLOSED")
229
+
230
+ # 热更新:把坏包修好再 reload
231
+ broken_pkg["rules"][0]["match"]["op"] = ">"
232
+ with open(p2, "w", encoding="utf-8") as f:
233
+ json.dump(broken_pkg, f, ensure_ascii=False)
234
+ bad.reload()
235
+ v = bad.evaluate({"fields": {"amount": 0}})
236
+ check("修复后热更新 → 恢复正常判定", v["decision"] == "PASS")
237
+
238
+ print("SELFTEST %s" % ("PASS" if ok else "FAIL"))
239
+ return 0 if ok else 1
240
+
241
+
242
+ if __name__ == "__main__":
243
+ if len(sys.argv) > 1 and sys.argv[1] == "selftest":
244
+ sys.exit(selftest())
245
+ print(__doc__)
mcp_server.py ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """constraint-runtime MCP 服务壳
4
+
5
+ 把五个约束组件(围栏规则引擎/影子运行器/熔断停机器/留痕重放器/结算凭证闸)
6
+ 以 MCP 工具形式对外暴露,供任意 MCP 客户端(Claude、Cursor 等)调用。
7
+ 组件本体零依赖纯标准库;本壳仅依赖 mcp 包。
8
+
9
+ 启动配置(stdio):
10
+ {
11
+ "mcpServers": {
12
+ "constraint-runtime": {
13
+ "command": "python3",
14
+ "args": ["-m", "mcp_server"],
15
+ "env": {
16
+ "CONSTRAINT_RULES_PATH": "/path/to/rules.json",
17
+ "CONSTRAINT_LEDGER_PATH": "/path/to/ledger.jsonl"
18
+ }
19
+ }
20
+ }
21
+ }
22
+
23
+ 工具一览:
24
+ fence_evaluate 围栏判定:事件过规则包,live 拦截 / shadow 只记
25
+ fence_reload 规则热更:重新加载规则包(规则是数据)
26
+ shadow_feed 影子投喂:基线判定 vs 影子判定,破口/误伤分账
27
+ shadow_report 影子报告:分账统计 + 转正建议(人工拍板)
28
+ breaker 熔断控制:status/success/failure/trip 四个动作
29
+ ledger_append 台账入链:判定写入哈希链,篡改可发现
30
+ ledger_verify 校验重放:链校验 + 用当前规则包离线重放比对
31
+ """
32
+ import json
33
+ import os
34
+ import sys
35
+
36
+ from mcp.server.fastmcp import FastMCP
37
+
38
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
39
+
40
+ from circuit_breaker import CircuitBreaker # noqa: E402
41
+ from fence_rule_engine import FenceEngine # noqa: E402
42
+ from replay_ledger import ReplayLedger # noqa: E402
43
+ from shadow_runner import ShadowRunner # noqa: E402
44
+
45
+ RULES_PATH = os.environ.get("CONSTRAINT_RULES_PATH")
46
+ LEDGER_PATH = os.environ.get("CONSTRAINT_LEDGER_PATH") or None
47
+
48
+ mcp = FastMCP("constraint-runtime")
49
+
50
+ _engine = FenceEngine(RULES_PATH) if RULES_PATH else None
51
+ _shadow = ShadowRunner()
52
+ _breaker = CircuitBreaker()
53
+ _ledger = ReplayLedger(LEDGER_PATH)
54
+
55
+
56
+ def _need_engine():
57
+ if _engine is None:
58
+ raise RuntimeError("未配置 CONSTRAINT_RULES_PATH,无法使用围栏工具")
59
+ return _engine
60
+
61
+
62
+ @mcp.tool()
63
+ def fence_evaluate(event: dict) -> str:
64
+ """围栏判定:把一个事件交给规则包裁决。live 规则命中即拦截(fail-closed),
65
+ shadow 规则命中只记不拦。event 示例:
66
+ {"fields": {"amount": 5000, "category": "餐饮"}, "text": "加急"}"""
67
+ eng = _need_engine()
68
+ verdict = eng.evaluate(event)
69
+ return json.dumps(verdict, ensure_ascii=False)
70
+
71
+
72
+ @mcp.tool()
73
+ def fence_reload() -> str:
74
+ """规则热更:重新从 CONSTRAINT_RULES_PATH 加载规则包,规则是数据,改规则不用改代码。"""
75
+ eng = _need_engine()
76
+ eng.reload()
77
+ version = json.load(open(eng.rules_path, encoding="utf-8")).get("version", "?")
78
+ return json.dumps({"ok": True, "version": version}, ensure_ascii=False)
79
+
80
+
81
+ @mcp.tool()
82
+ def shadow_feed(event_id: str, baseline_decision: str, shadow_decision: str,
83
+ rule_hits: list = None) -> str:
84
+ """影子投喂:记录一次基线判定与影子判定对照。影子比基线松=破口,比基线严=误伤,
85
+ 分账累计,连续 N 窗口零破口零误伤才给转正建议。"""
86
+ _shadow.feed(event_id, baseline_decision, shadow_decision, rule_hits)
87
+ return json.dumps({"ok": True, "total_fed": _shadow.total["fed"]}, ensure_ascii=False)
88
+
89
+
90
+ @mcp.tool()
91
+ def shadow_report() -> str:
92
+ """影子报告:当前分账统计 + 是否达到转正建议条件(转正仍需人工拍板)。"""
93
+ return json.dumps({"report": _shadow.report(),
94
+ "promotion": _shadow.promotion_check()}, ensure_ascii=False)
95
+
96
+
97
+ @mcp.tool()
98
+ def breaker(action: str, reason: str = "") -> str:
99
+ """熔断控制。action 取值:
100
+ status=查看状态;success=记录一次成功;failure=记录一次失败(连续失败或失败率越界自动熔断);
101
+ trip=显式熔断。熔断后冷却期放行探针,探针成功才恢复。"""
102
+ actions = {"status", "success", "failure", "trip"}
103
+ if action not in actions:
104
+ return json.dumps({"error": f"action 须为 {sorted(actions)}"}, ensure_ascii=False)
105
+ if action == "success":
106
+ _breaker.record_success()
107
+ elif action == "failure":
108
+ _breaker.record_failure(reason)
109
+ elif action == "trip":
110
+ _breaker.trip(reason or "显式熔断信号")
111
+ return json.dumps({"action": action, "report": _breaker.report()}, ensure_ascii=False)
112
+
113
+
114
+ @mcp.tool()
115
+ def ledger_append(event: dict, verdict: dict) -> str:
116
+ """台账入链:把一次判定写入哈希链台账,任何篡改都会被链校验发现。"""
117
+ h = _ledger.append(event, verdict)
118
+ return json.dumps({"ok": True, "hash": h}, ensure_ascii=False)
119
+
120
+
121
+ @mcp.tool()
122
+ def ledger_verify() -> str:
123
+ """校验重放:先验哈希链完整性,再用当前规则包离线重放全部台账,
124
+ 重算结论与原判一致 = 可复算。"""
125
+ chain_ok = _ledger.verify_chain()
126
+ replay = _ledger.replay(_engine) if _engine else {"skipped": "未配置规则包"}
127
+ return json.dumps({"chain_ok": chain_ok, "replay": replay}, ensure_ascii=False)
128
+
129
+
130
+ def main():
131
+ mcp.run(transport="stdio")
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
replay_ledger.py ADDED
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # Copyright 2026 元极恒一
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+ """replay_ledger.py — 约束运行时·留痕重放器 v0.1(架构补齐方案组件四,2026-11-22)
19
+
20
+ 定位:每一次判定都入哈希链台账;第三方可用留存的事件与规则包离线重放,
21
+ 重算结论与原判一致才算「可复算」。与评测侧证据链同构,覆盖运行时干预。
22
+
23
+ 核心概念:
24
+ - 台账:append-only,每条 = 序号 + 时间戳 + 事件 + 原判 + 前链哈希,条目哈希环环相扣。
25
+ - 链校验:任何一条被篡改,从该条起哈希对不上(诚实边界:不防能同时改文件与
26
+ 台账的本地攻击者,防篡改主张仅限「对账不一致可发现」)。
27
+ - 重放:用当前规则包对留存事件重新求值,比对原判——一致率即「可复算」的直接证据。
28
+
29
+ 用法:
30
+ from replay_ledger import ReplayLedger
31
+ led = ReplayLedger("/path/to/ledger.jsonl")
32
+ led.append(event, verdict)
33
+ ok, detail = led.verify_chain()
34
+ mismatches = led.replay(engine) # engine = fence_rule_engine.FenceEngine
35
+
36
+ CLI 自检:
37
+ replay_ledger.py selftest
38
+ """
39
+
40
+ import hashlib
41
+ import json
42
+ import os
43
+ import time
44
+
45
+
46
+ def _entry_hash(seq, ts, event, verdict, prev):
47
+ payload = json.dumps({"seq": seq, "ts": ts, "event": event,
48
+ "verdict": verdict, "prev": prev},
49
+ ensure_ascii=False, sort_keys=True)
50
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
51
+
52
+
53
+ class ReplayLedger:
54
+ def __init__(self, path=None):
55
+ self.path = path
56
+ self.entries = []
57
+ if path and os.path.exists(path):
58
+ self._load()
59
+
60
+ def _load(self):
61
+ with open(self.path, "r", encoding="utf-8") as f:
62
+ for line in f:
63
+ line = line.strip()
64
+ if line:
65
+ self.entries.append(json.loads(line))
66
+
67
+ def append(self, event, verdict, ts=None):
68
+ """追加一条判定留痕;返回条目哈希。"""
69
+ seq = len(self.entries)
70
+ ts = ts if ts is not None else time.time()
71
+ prev = self.entries[-1]["hash"] if self.entries else "GENESIS"
72
+ h = _entry_hash(seq, ts, event, verdict, prev)
73
+ entry = {"seq": seq, "ts": ts, "event": event,
74
+ "verdict": verdict, "prev": prev, "hash": h}
75
+ self.entries.append(entry)
76
+ if self.path:
77
+ with open(self.path, "a", encoding="utf-8") as f:
78
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
79
+ return h
80
+
81
+ def verify_chain(self):
82
+ """全链校验:逐条重算哈希并核对前链指针。"""
83
+ prev = "GENESIS"
84
+ for e in self.entries:
85
+ expect = _entry_hash(e["seq"], e["ts"], e["event"], e["verdict"], prev)
86
+ if e["prev"] != prev:
87
+ return False, {"broken_at": e["seq"], "reason": "前链指针不符"}
88
+ if e["hash"] != expect:
89
+ return False, {"broken_at": e["seq"], "reason": "条目哈希不符(疑似篡改)"}
90
+ prev = e["hash"]
91
+ return True, {"entries": len(self.entries), "head": prev}
92
+
93
+ def replay(self, engine):
94
+ """用当前规则包重放全部留存事件,返回与原判不一致的清单。"""
95
+ mismatches = []
96
+ for e in self.entries:
97
+ try:
98
+ v = engine.evaluate(e["event"])
99
+ if v["decision"] != e["verdict"].get("decision"):
100
+ mismatches.append({"seq": e["seq"],
101
+ "original": e["verdict"].get("decision"),
102
+ "replayed": v["decision"]})
103
+ except Exception as exc:
104
+ mismatches.append({"seq": e["seq"], "original": e["verdict"].get("decision"),
105
+ "replayed": "ERROR", "error": str(exc)})
106
+ total = len(self.entries)
107
+ return {"total": total, "consistent": total - len(mismatches),
108
+ "mismatches": mismatches,
109
+ "reproducible": (total > 0 and not mismatches)}
110
+
111
+
112
+ def selftest():
113
+ import tempfile
114
+ ok = True
115
+
116
+ def check(name, cond):
117
+ nonlocal ok
118
+ print((" PASS " if cond else " FAIL ") + name)
119
+ ok = ok and cond
120
+
121
+ pkg = {"package": "自检", "version": "t1", "fail_closed": True,
122
+ "rules": [{"id": "R1", "title": "大额", "status": "live",
123
+ "match": {"field": "fields.amount", "op": ">", "value": 3000},
124
+ "message": "超限"}]}
125
+
126
+ with tempfile.TemporaryDirectory() as td:
127
+ rp = os.path.join(td, "rules.json")
128
+ lp = os.path.join(td, "ledger.jsonl")
129
+ with open(rp, "w", encoding="utf-8") as f:
130
+ json.dump(pkg, f, ensure_ascii=False)
131
+
132
+ # 引擎与台账(延迟导入避免循环依赖;自检时同目录)
133
+ sys_path = os.path.dirname(os.path.abspath(__file__))
134
+ if sys_path not in __import__("sys").path:
135
+ __import__("sys").path.insert(0, sys_path)
136
+ from fence_rule_engine import FenceEngine
137
+ eng = FenceEngine(rp)
138
+
139
+ led = ReplayLedger(lp)
140
+ ev1 = {"fields": {"amount": 5000}}
141
+ ev2 = {"fields": {"amount": 100}}
142
+ led.append(ev1, eng.evaluate(ev1))
143
+ led.append(ev2, eng.evaluate(ev2))
144
+
145
+ chain_ok, detail = led.verify_chain()
146
+ check("哈希链校验通过", chain_ok and detail["entries"] == 2)
147
+
148
+ rep = led.replay(eng)
149
+ check("重放与原判完全一致(可复算)", rep["reproducible"] and rep["consistent"] == 2)
150
+
151
+ # 篡改中间一条的事件内容 → 链校验应发现
152
+ led.entries[0]["event"]["fields"]["amount"] = 1
153
+ chain_ok, detail = led.verify_chain()
154
+ check("篡改条目 → 链校验发现不一致", not chain_ok and detail["broken_at"] == 0)
155
+
156
+ # 持久化:新实例从文件恢复后链仍可校验
157
+ led2 = ReplayLedger(lp)
158
+ # 注意:文件里是未篡改的正本
159
+ chain_ok2, _ = led2.verify_chain()
160
+ check("从文件恢复后链校验仍通过", chain_ok2)
161
+
162
+ print("SELFTEST %s" % ("PASS" if ok else "FAIL"))
163
+ return 0 if ok else 1
164
+
165
+
166
+ if __name__ == "__main__":
167
+ import sys
168
+ if len(sys.argv) > 1 and sys.argv[1] == "selftest":
169
+ sys.exit(selftest())
170
+ print(__doc__)