agh-gestalt 2.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.
agh/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """AGH v3.1 —— M0 垂直切片。
2
+
3
+ 设计纪律(来自方案 §0):裁判冻结、准入严格、回滚第一、消融验证。
4
+ 每个规格缺陷修复在代码里都有注释标记 D1..D12,便于对照文档。
5
+ """
6
+
7
+ __version__ = "2.1.0"
8
+ SCHEMA_VERSION = "agh-3.1"
agh/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
agh/ablation.py ADDED
@@ -0,0 +1,216 @@
1
+ """消融套件(§4)。
2
+
3
+ 方案要求「9 组消融」:完整链路 + 8 个单点关闭。这里把每个消融定义成
4
+ 对 ArenaConfig 的一处改动(或关掉硬过滤/异议),跑同一批种子,
5
+ 用配对 bootstrap + Holm 判断「关掉这一项,分数是否真的掉了」。
6
+
7
+ 注意:规则子级下这些数字只说明链路行为,不是模型结论。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable, Sequence
13
+ from dataclasses import dataclass, field, replace
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from .arena import (
18
+ ArenaConfig,
19
+ CompetitiveCandidate,
20
+ arbitrate,
21
+ evaluate_dissent,
22
+ hard_filter,
23
+ score_candidate,
24
+ )
25
+ from .contracts import AbstractSignature, GestaltReconstruction, Skeleton
26
+ from .evalstats import Interval, bootstrap_pvalue, holm, paired_bootstrap_ci
27
+ from .experiment import Arm
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Ablation:
32
+ name: str
33
+ description: str
34
+ weights: dict[str, float] | None = None
35
+ dissent_tau: float | None = None
36
+ diversity_min_clusters: int | None = None
37
+ dissent: bool = True
38
+ arena: bool = True
39
+
40
+ def config(self, cfg: ArenaConfig) -> ArenaConfig:
41
+ weights = dict(cfg.weights)
42
+ if self.weights:
43
+ weights.update(self.weights)
44
+ return replace(
45
+ cfg,
46
+ weights=weights,
47
+ dissent_tau=cfg.dissent_tau if self.dissent_tau is None else self.dissent_tau,
48
+ diversity_min_clusters=(
49
+ cfg.diversity_min_clusters
50
+ if self.diversity_min_clusters is None
51
+ else self.diversity_min_clusters
52
+ ),
53
+ )
54
+
55
+
56
+ ABLATIONS: tuple[Ablation, ...] = (
57
+ Ablation("no_vertical", "垂直一致性权重归零", weights={"vertical": 0.0}),
58
+ Ablation("no_coverage", "覆盖率权重归零", weights={"coverage": 0.0}),
59
+ Ablation("no_structural", "结构距离权重归零", weights={"structural": 0.0}),
60
+ Ablation("no_update", "更新量权重归零", weights={"update": 0.0}),
61
+ Ablation("no_confidence", "校准置信权重归零", weights={"confidence": 0.0}),
62
+ Ablation("no_dissent", "异议永不成立", dissent_tau=1e9),
63
+ Ablation("no_arena", "不做仲裁,直接取第一个候选", arena=False),
64
+ Ablation("no_diversity", "关闭多样性门槛", diversity_min_clusters=0),
65
+ )
66
+
67
+
68
+ @dataclass
69
+ class AblationRow:
70
+ name: str
71
+ description: str
72
+ delta: Interval
73
+ p_value: float
74
+ holm_threshold: float
75
+ significant: bool
76
+
77
+
78
+ @dataclass
79
+ class AblationReport:
80
+ seeds: int
81
+ rows: list[AblationRow] = field(default_factory=list)
82
+
83
+ def as_dict(self) -> dict[str, Any]:
84
+ return {
85
+ "seeds": self.seeds,
86
+ "rows": [
87
+ {
88
+ "name": r.name,
89
+ "description": r.description,
90
+ "delta": {
91
+ "mean": round(r.delta.mean, 5),
92
+ "lo": round(r.delta.lo, 5),
93
+ "hi": round(r.delta.hi, 5),
94
+ "n": r.delta.n,
95
+ },
96
+ "p_value": round(r.p_value, 4),
97
+ "holm_threshold": round(r.holm_threshold, 4),
98
+ "significant": r.significant,
99
+ }
100
+ for r in self.rows
101
+ ],
102
+ }
103
+
104
+ def write(self, path: str | Path) -> Path:
105
+ import json
106
+
107
+ target = Path(path)
108
+ target.parent.mkdir(parents=True, exist_ok=True)
109
+ target.write_text(json.dumps(self.as_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
110
+ return target
111
+
112
+
113
+ def _winner_score(
114
+ arms: Sequence[Arm],
115
+ skeleton: Skeleton,
116
+ cfg: ArenaConfig,
117
+ contract_id: str,
118
+ parent_sig: AbstractSignature | None,
119
+ seed: int,
120
+ ablation: Ablation,
121
+ ) -> float | None:
122
+ candidates: list[CompetitiveCandidate] = []
123
+ for arm in arms:
124
+ try:
125
+ recon: GestaltReconstruction = arm.child.reconstruct(contract_id)
126
+ except Exception:
127
+ continue
128
+ if not hard_filter(recon, skeleton).passed:
129
+ continue
130
+ score = score_candidate(
131
+ recon, skeleton, cfg, verifier_score=None, parent_signature=parent_sig
132
+ )
133
+ decision = None
134
+ if ablation.dissent:
135
+ decision = evaluate_dissent(
136
+ recon,
137
+ score,
138
+ pool=[list(parent_sig.features)] if parent_sig else [],
139
+ abstractions=[],
140
+ cfg=cfg,
141
+ )
142
+ candidates.append(CompetitiveCandidate(recon, score, dissent=decision))
143
+ if not candidates:
144
+ return None
145
+ if not ablation.arena:
146
+ return candidates[0].breakdown.score
147
+ result = arbitrate(candidates, seed=seed, cfg=cfg)
148
+ winner = next((c for c in candidates if c.reconstruction.child_id == result.winner), None)
149
+ if winner is None:
150
+ # 仲裁可能因为所有候选都是 0 分而不选任何人;消融里按 0 分处理
151
+ return 0.0
152
+ return winner.breakdown.score
153
+
154
+
155
+ def run_ablation(
156
+ arms: Sequence[Arm],
157
+ skeleton: Skeleton,
158
+ cfg: ArenaConfig,
159
+ *,
160
+ contract_id: str = "ct-ablation",
161
+ parent_features: Sequence[str] | None = None,
162
+ seeds: Iterable[int] = range(50),
163
+ resamples: int = 2_000,
164
+ alpha: float = 0.05,
165
+ ) -> AblationReport:
166
+ if not arms:
167
+ raise ValueError("至少需要一个子级")
168
+ parent_sig = (
169
+ AbstractSignature(signature_id="parent-ablation", features=list(parent_features))
170
+ if parent_features
171
+ else None
172
+ )
173
+ full = Ablation("full", "完整链路")
174
+ deltas: dict[str, list[float]] = {a.name: [] for a in ABLATIONS}
175
+ used = 0
176
+ for seed in seeds:
177
+ base = _winner_score(arms, skeleton, cfg, contract_id, parent_sig, seed, full)
178
+ if base is None:
179
+ continue
180
+ used += 1
181
+ for ablation in ABLATIONS:
182
+ variant = _winner_score(
183
+ arms, skeleton, ablation.config(cfg), contract_id, parent_sig, seed, ablation
184
+ )
185
+ if variant is not None:
186
+ deltas[ablation.name].append(variant - base)
187
+
188
+ pending: list[tuple[Ablation, Interval, float]] = []
189
+ for ablation in ABLATIONS:
190
+ values = deltas[ablation.name]
191
+ if len(values) < 2:
192
+ continue
193
+ ci = paired_bootstrap_ci(values, resamples=resamples, seed=0)
194
+ p = bootstrap_pvalue(values, resamples=resamples, seed=0)
195
+ pending.append((ablation, ci, p))
196
+
197
+ rows: list[AblationRow] = []
198
+ if pending:
199
+ corrected = holm([p for *_, p in pending], alpha=alpha)
200
+ by_index = {idx: (threshold, reject) for idx, threshold, reject in corrected}
201
+ for i, (ablation, ci, p) in enumerate(pending):
202
+ threshold, reject = by_index[i]
203
+ rows.append(
204
+ AblationRow(
205
+ name=ablation.name,
206
+ description=ablation.description,
207
+ delta=ci,
208
+ p_value=p,
209
+ holm_threshold=threshold,
210
+ significant=reject,
211
+ )
212
+ )
213
+ return AblationReport(seeds=used, rows=rows)
214
+
215
+
216
+ __all__ = ["ABLATIONS", "Ablation", "AblationReport", "AblationRow", "run_ablation"]
agh/anchoring.py ADDED
@@ -0,0 +1,263 @@
1
+ """事件日志的外部锚定。
2
+
3
+ 本地哈希链能发现「悄悄改一行」,但发现不了「整条链被替换」:
4
+ 删掉 events.jsonl 重写一条自洽的新链,链本身校验完全通过。
5
+ 锚定的做法是把链头与长度写到日志之外,并(可选)签名:
6
+
7
+ - 只写锚点、不签名:能防「日志被改」,防不了「锚点和日志一起被改」
8
+ - 用 Ed25519 签锚点:没有私钥的人改不了锚点,也就无法替换整条链
9
+ - 两者都不做等于没锚定:`check_log` 会在返回值里明确标出来
10
+
11
+ 真正的外部锚定(第三方时间戳、另一台机器)由调用方把 AnchorStore 换掉即可;
12
+ 这里只内置本地 JSONL 存储,不假装它是第三方。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from dataclasses import dataclass
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from .crypto import Key, KeyRing, ProvenanceError, sha256_hex, sign_with, verify_with
24
+ from .eventlog import EventLog
25
+
26
+ ANCHOR_VERSION = 1
27
+ DEFAULT_KID = "gw-dev"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Anchor:
32
+ head: str
33
+ size: int
34
+ log_path: str = ""
35
+ label: str = ""
36
+ created_at: str = ""
37
+ signer: str = ""
38
+ signature: str = ""
39
+ version: int = ANCHOR_VERSION
40
+
41
+ def as_dict(self) -> dict[str, Any]:
42
+ return {
43
+ "version": self.version,
44
+ "head": self.head,
45
+ "size": self.size,
46
+ "log_path": self.log_path,
47
+ "label": self.label,
48
+ "created_at": self.created_at,
49
+ "signer": self.signer,
50
+ "signature": self.signature,
51
+ }
52
+
53
+ def message(self) -> str:
54
+ """签名覆盖的字段;不含 signature 自身。"""
55
+ return sha256_hex(
56
+ {
57
+ "version": self.version,
58
+ "head": self.head,
59
+ "size": self.size,
60
+ "log_path": self.log_path,
61
+ "label": self.label,
62
+ "created_at": self.created_at,
63
+ "signer": self.signer,
64
+ }
65
+ )
66
+
67
+
68
+ def _resolved(path: str | Path | None) -> str:
69
+ return str(Path(path).resolve()) if path is not None else ""
70
+
71
+
72
+ def anchor_log(
73
+ log: EventLog,
74
+ *,
75
+ key: Key | None = None,
76
+ label: str = "",
77
+ log_path: str | None = None,
78
+ clock: Any = None,
79
+ ) -> Anchor:
80
+ """把日志当前的链头与长度固化成锚点。"""
81
+ created_at = clock().isoformat() if clock is not None else datetime.now(UTC).isoformat()
82
+ anchor = Anchor(
83
+ head=log.head(),
84
+ size=log.size(),
85
+ log_path=log_path if log_path is not None else _resolved(log.path),
86
+ label=label,
87
+ created_at=created_at,
88
+ signer=key.kid if key is not None else "",
89
+ )
90
+ if key is not None:
91
+ anchor = Anchor(
92
+ head=anchor.head,
93
+ size=anchor.size,
94
+ log_path=anchor.log_path,
95
+ label=anchor.label,
96
+ created_at=anchor.created_at,
97
+ signer=anchor.signer,
98
+ signature=sign_with(key, anchor.message()),
99
+ )
100
+ return anchor
101
+
102
+
103
+ def verify_anchor(anchor: Anchor, keyring: KeyRing | None, *, kid: str | None = None) -> bool:
104
+ """校验锚点签名。未签名的锚点返回 False(调用方据此降级为「未锚定」)。"""
105
+ if not anchor.signature:
106
+ return False
107
+ if keyring is None:
108
+ return False
109
+ try:
110
+ key = keyring.get(kid or anchor.signer or DEFAULT_KID)
111
+ except ProvenanceError:
112
+ return False
113
+ return verify_with(key, anchor.message(), anchor.signature)
114
+
115
+
116
+ def check_log(
117
+ log: EventLog,
118
+ anchor: Anchor,
119
+ *,
120
+ keyring: KeyRing | None = None,
121
+ ) -> bool:
122
+ """校验日志是否仍是锚定时的样子;返回签名是否可信。
123
+
124
+ - 链头/长度不符 → 抛 LogTampered(日志被改或被截断)
125
+ - 签名不符 → 抛 LogTampered(锚点被改,或签名密钥不对)
126
+ - 未签名锚点 → 返回 False,表示「顺序与完整性可信,但未锚定」
127
+ """
128
+ fresh = EventLog(Path(log.path)) if log.path is not None else log
129
+ fresh.verify_against(anchor.head, anchor.size)
130
+ if not anchor.signature:
131
+ return False
132
+ if not verify_anchor(anchor, keyring):
133
+ from .eventlog import LogTampered
134
+
135
+ raise LogTampered("锚点签名校验失败(锚点被替换,或密钥不对)")
136
+ return True
137
+
138
+
139
+ class AnchorStore:
140
+ """锚点存储:一行一个 JSON。换掉它就能换外部位置,接口不变。"""
141
+
142
+ def __init__(self, path: str | Path) -> None:
143
+ self.path = Path(path)
144
+
145
+ def append(self, anchor: Anchor) -> None:
146
+ self.path.parent.mkdir(parents=True, exist_ok=True)
147
+ with self.path.open("a", encoding="utf-8", newline="\n") as fh:
148
+ fh.write(json.dumps(anchor.as_dict(), ensure_ascii=False, sort_keys=True) + "\n")
149
+
150
+ def read(self) -> list[Anchor]:
151
+ if not self.path.exists():
152
+ return []
153
+ out: list[Anchor] = []
154
+ for line in self.path.read_text(encoding="utf-8").splitlines():
155
+ if not line.strip():
156
+ continue
157
+ data = json.loads(line)
158
+ out.append(
159
+ Anchor(
160
+ head=data["head"],
161
+ size=int(data["size"]),
162
+ log_path=data.get("log_path", ""),
163
+ label=data.get("label", ""),
164
+ created_at=data.get("created_at", ""),
165
+ signer=data.get("signer", ""),
166
+ signature=data.get("signature", ""),
167
+ version=int(data.get("version", ANCHOR_VERSION)),
168
+ )
169
+ )
170
+ return out
171
+
172
+ def latest(self, log_path: str | None = None) -> Anchor | None:
173
+ target = _resolved(log_path)
174
+ candidates = [a for a in self.read() if log_path is None or _resolved(a.log_path) == target]
175
+ return candidates[-1] if candidates else None
176
+
177
+ def check(self, log: EventLog, *, keyring: KeyRing | None = None) -> bool:
178
+ anchor = self.latest(str(log.path))
179
+ if anchor is None:
180
+ from .eventlog import LogTampered
181
+
182
+ raise LogTampered(f"没有针对 {log.path} 的锚点")
183
+ return check_log(log, anchor, keyring=keyring)
184
+
185
+
186
+
187
+ class GitTagStore:
188
+ """把锚点写成 git tag:远程仓库就是外部存储。
189
+
190
+ 本地文件可以被删、被改;推送过的 tag 想无声改写,得先改远程仓库。
191
+ 这不是第三方时间戳,但比「同一个目录里的另一个文件」离「外部」更近一步。
192
+ """
193
+
194
+ def __init__(self, repo: str | Path, prefix: str = "agh-anchor") -> None:
195
+ self.repo = Path(repo)
196
+ self.prefix = prefix
197
+
198
+ def _run(self, *args: str) -> str:
199
+ import subprocess
200
+
201
+ proc = subprocess.run(
202
+ ["git", "-C", str(self.repo), *args],
203
+ check=True,
204
+ capture_output=True,
205
+ text=True,
206
+ )
207
+ return proc.stdout
208
+
209
+ def append(self, anchor: Anchor) -> str:
210
+ name = f"{self.prefix}/{digest_of(anchor)[:16]}"
211
+ message = json.dumps(anchor.as_dict(), ensure_ascii=False, sort_keys=True)
212
+ self._run("tag", "-a", name, "-m", message, "--cleanup=verbatim")
213
+ return name
214
+
215
+ def read(self) -> list[Anchor]:
216
+ out = self._run(
217
+ "for-each-ref",
218
+ "--format=%(contents:subject)%00%(contents:body)",
219
+ f"refs/tags/{self.prefix}/*",
220
+ )
221
+ anchors: list[Anchor] = []
222
+ for line in out.splitlines():
223
+ if not line.strip():
224
+ continue
225
+ payload = line.replace("\x00", "\n").strip()
226
+ try:
227
+ data = json.loads(payload)
228
+ except json.JSONDecodeError:
229
+ continue
230
+ anchors.append(
231
+ Anchor(
232
+ head=data["head"],
233
+ size=int(data["size"]),
234
+ log_path=data.get("log_path", ""),
235
+ label=data.get("label", ""),
236
+ created_at=data.get("created_at", ""),
237
+ signer=data.get("signer", ""),
238
+ signature=data.get("signature", ""),
239
+ version=int(data.get("version", ANCHOR_VERSION)),
240
+ )
241
+ )
242
+ return anchors
243
+
244
+ def latest(self, log_path: str | None = None) -> Anchor | None:
245
+ target = _resolved(log_path)
246
+ candidates = [a for a in self.read() if log_path is None or _resolved(a.log_path) == target]
247
+ return candidates[-1] if candidates else None
248
+
249
+ def digest_of(anchor: Anchor) -> str:
250
+ """锚点自身的摘要,方便把它写进别处(issue tracker、另一份日志)。"""
251
+ return sha256_hex(anchor.as_dict())
252
+
253
+
254
+ __all__ = [
255
+ "ANCHOR_VERSION",
256
+ "Anchor",
257
+ "AnchorStore",
258
+ "GitTagStore",
259
+ "anchor_log",
260
+ "check_log",
261
+ "digest_of",
262
+ "verify_anchor",
263
+ ]