siwpan-agent 1.0.2__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.
- agent/__init__.py +3 -0
- agent/__main__.py +264 -0
- agent/assembly.py +27 -0
- agent/audit.py +215 -0
- agent/bridges/__init__.py +84 -0
- agent/brief.py +157 -0
- agent/capabilities.py +235 -0
- agent/chain.py +117 -0
- agent/check.py +191 -0
- agent/contracts/__init__.py +13 -0
- agent/facts.py +116 -0
- agent/flow.py +62 -0
- agent/guide.py +305 -0
- agent/home.py +101 -0
- agent/hosts.py +195 -0
- agent/kb.py +196 -0
- agent/ledger.py +664 -0
- agent/rollout.py +424 -0
- agent/roots.py +33 -0
- agent/wiring.py +321 -0
- siwpan_agent-1.0.2.dist-info/METADATA +8 -0
- siwpan_agent-1.0.2.dist-info/RECORD +26 -0
- siwpan_agent-1.0.2.dist-info/WHEEL +5 -0
- siwpan_agent-1.0.2.dist-info/entry_points.txt +2 -0
- siwpan_agent-1.0.2.dist-info/licenses/LICENSE +16 -0
- siwpan_agent-1.0.2.dist-info/top_level.txt +1 -0
agent/__init__.py
ADDED
agent/__main__.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""agent —— 总控入口(控制面,不持有事实、不写被治理仓)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .assembly import MANAGED, assemble
|
|
11
|
+
from .roots import REPOS
|
|
12
|
+
|
|
13
|
+
# 根定位见 roots.py(单一事实来源);REPOS 已含 AGENT_REPOS_ROOT 安装态回退。
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
"""把 parser 造出来,而不是在 main() 里顺手造。
|
|
18
|
+
|
|
19
|
+
分开的理由不是好看:能力目录要能**反查真实子命令**(capabilities 的 C4,
|
|
20
|
+
「活着的都登记了吗」)。反查必须问 parser 本身,不能正则扫源码——
|
|
21
|
+
扫源码会漏掉变量拼出来的子命令,也会把注释里的 `sub.add_parser(` 算进去。
|
|
22
|
+
"""
|
|
23
|
+
ap = argparse.ArgumentParser(prog="agent")
|
|
24
|
+
sub = ap.add_subparsers(dest="cmd", required=False)
|
|
25
|
+
ck = sub.add_parser("check", help="四仓例行判据:逐个跑 govrule,任一 fail 即 exit 1")
|
|
26
|
+
ck.add_argument("--json", action="store_true")
|
|
27
|
+
entry = sub.add_parser("entry", help="总入口:选路到被治理仓")
|
|
28
|
+
entry.add_argument("--repo", choices=MANAGED, help="要进入的仓")
|
|
29
|
+
entry.add_argument("--list", action="store_true", help="列出被治理仓与入口")
|
|
30
|
+
sub.add_parser("verify", help="核对三个仓的 agent.contract.yml")
|
|
31
|
+
au = sub.add_parser("audit", help="用验证者信任根核对 run/receipt 签名(失败即 exit 1)")
|
|
32
|
+
au.add_argument("--trust", default="trust/keys")
|
|
33
|
+
au.add_argument("--json", action="store_true")
|
|
34
|
+
au.add_argument("--limit", type=int, default=20)
|
|
35
|
+
au.add_argument("--legacy", action="store_true")
|
|
36
|
+
au.add_argument("--record", action="store_true")
|
|
37
|
+
au.add_argument("--freshness-days", type=int, default=0)
|
|
38
|
+
au.add_argument("--ca-review-days", type=int, default=0)
|
|
39
|
+
wr = sub.add_parser("wiring", help="四仓接线静态自检(契约/证据/目标)")
|
|
40
|
+
wr.add_argument("--json", action="store_true")
|
|
41
|
+
br = sub.add_parser("brief", help="一段式上下文:事实 + 知识 + 链条 + 契约(只读)")
|
|
42
|
+
br.add_argument("--topic", help="知识检索主题(不给则跳过知识段)")
|
|
43
|
+
br.add_argument("--budget", type=int, default=1200)
|
|
44
|
+
br.add_argument("--json", action="store_true", help="机读:一份 payload 拿全四段")
|
|
45
|
+
fx = sub.add_parser("facts", help="三处事实源的联邦读(转发 allin,不搬运/不缓存)")
|
|
46
|
+
fx.add_argument("--json", action="store_true", help="机读(payload 原样透传)")
|
|
47
|
+
fx.add_argument("--strict", action="store_true", help="交叉校验有不一致即 exit 1")
|
|
48
|
+
kb = sub.add_parser("kb", help="agent 大脑:跨仓知识库 build/check/search/stats")
|
|
49
|
+
kb.add_argument("action", nargs="?", default="search",
|
|
50
|
+
choices=["build", "check", "search", "stats"])
|
|
51
|
+
kb.add_argument("--query", default="")
|
|
52
|
+
kb.add_argument("--budget", type=int, default=4000)
|
|
53
|
+
kb.add_argument("--json", action="store_true")
|
|
54
|
+
cap = sub.add_parser("capabilities", help="能力目录:四仓清单 + 逐条探活")
|
|
55
|
+
cap.add_argument("--check", action="store_true", help="逐条跑 --help,死的报 FAIL")
|
|
56
|
+
cap.add_argument("--group", help="只查某一组")
|
|
57
|
+
cap.add_argument("--json", action="store_true")
|
|
58
|
+
st = sub.add_parser("status", help="链条视图:order → run → flow → receipt(只读,调子仓 CLI)")
|
|
59
|
+
st.add_argument("--json", action="store_true")
|
|
60
|
+
doc = sub.add_parser("doctor", help="总入口自检:各仓虚拟环境体检(委派 governance 能力)")
|
|
61
|
+
doc.add_argument("--repo", choices=MANAGED, help="只查一个仓")
|
|
62
|
+
doc.add_argument("--json", action="store_true")
|
|
63
|
+
lg = sub.add_parser("ledger", help="本机月账:status 看差 / tick 按日追加(幂等、只增不改)")
|
|
64
|
+
lg.add_argument("action", nargs="?", default="status",
|
|
65
|
+
choices=["status", "tick", "push", "install-automation"])
|
|
66
|
+
lg.add_argument("--month", help="YYYY-MM(默认本月)")
|
|
67
|
+
lg.add_argument("--host", help="机器标识(默认 hostname)")
|
|
68
|
+
lg.add_argument("--source", help="WorkBuddy 根(默认 ~/WorkBuddy 或 ALLIN_WORKBUDDY_ROOT)")
|
|
69
|
+
lg.add_argument("--ledger", help="账本路径(默认 docs/事实源/机器/<host>/月账/<月>.md)")
|
|
70
|
+
lg.add_argument("--dry-run", action="store_true", help="tick 只打印将追加的内容")
|
|
71
|
+
lg.add_argument("--max", type=int, default=31, help="tick 一次最多补几天(默认 31)")
|
|
72
|
+
lg.add_argument("--today", action="store_true", help="tick 也结当天(默认留到明天)")
|
|
73
|
+
lg.add_argument("--commit", action="store_true", help="tick 后本地提交(推送另见 ledger push)")
|
|
74
|
+
lg.add_argument("--all", action="store_true", help="只读汇总各机最新入账日期")
|
|
75
|
+
lg.add_argument("--json", action="store_true")
|
|
76
|
+
hs = sub.add_parser("hosts", help="四仓在 gitee/GitHub/PyPI 的位置与拓扑缺口(只读)")
|
|
77
|
+
hs.add_argument("--json", action="store_true")
|
|
78
|
+
ro = sub.add_parser("rollout", help="掌权比例状态机(判定/状态/锁全内嵌)")
|
|
79
|
+
ro.add_argument("--config", default="config/rollout.yml")
|
|
80
|
+
ro.add_argument("action", nargs="?", default="validate",
|
|
81
|
+
choices=["show", "advance", "guard", "reverse", "validate"])
|
|
82
|
+
ro.add_argument("--rule", help="被掌权的 rule_id(validate 不需要)")
|
|
83
|
+
ro.add_argument("--new-divergence", action="store_true")
|
|
84
|
+
ro.add_argument("--void-rate", type=float, default=0.0)
|
|
85
|
+
ro.add_argument("--ref-unavailable", action="store_true")
|
|
86
|
+
ro.add_argument("--json", action="store_true")
|
|
87
|
+
fl = sub.add_parser("flow", help="allin 全流程巡检(转发 auto_flow;绝不 push)")
|
|
88
|
+
fl.add_argument("--quick", action="store_true", help="只做同步核对 + 状态汇总")
|
|
89
|
+
fl.add_argument("--no-fetch", action="store_true", help="跳过 git fetch(离线)")
|
|
90
|
+
fl.add_argument("--with-platform", action="store_true", help="门禁额外跑 platform check/test/harness")
|
|
91
|
+
fl.add_argument("--json", action="store_true")
|
|
92
|
+
gd = sub.add_parser("guide", help="新人指南:构建 / 校验 / 跑命令(docs/guide)")
|
|
93
|
+
gd.add_argument("action", nargs="?", default="check",
|
|
94
|
+
choices=["build", "check", "run", "versions"])
|
|
95
|
+
gd.add_argument("--full", action="store_true", help="run 时包含慢命令")
|
|
96
|
+
gd.add_argument("--scope", choices=["repo", "cleanroom"], default="repo",
|
|
97
|
+
help="run 时读哪一册:repo=开发册,cleanroom=使用册")
|
|
98
|
+
return ap
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def subcommands() -> list[str]:
|
|
102
|
+
"""真实注册的子命令名(能力目录 C4 反查用)。
|
|
103
|
+
|
|
104
|
+
用鸭子类型找 `_SubParsersAction`(它的 `choices` 就是 `{名字: parser}`),
|
|
105
|
+
不去碰 `argparse._SubParsersAction` 这个私有名——它在 3.11 与 3.13 都存在,
|
|
106
|
+
但私有名不是契约,`choices` 是。
|
|
107
|
+
"""
|
|
108
|
+
for act in _build_parser()._actions: # noqa: SLF001
|
|
109
|
+
choices = getattr(act, "choices", None)
|
|
110
|
+
if isinstance(choices, dict):
|
|
111
|
+
return sorted(choices)
|
|
112
|
+
return []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main(argv: list[str] | None = None) -> int:
|
|
116
|
+
ap = _build_parser()
|
|
117
|
+
args = ap.parse_args(argv)
|
|
118
|
+
|
|
119
|
+
if not args.cmd:
|
|
120
|
+
from .home import main as home_main
|
|
121
|
+
return home_main(REPOS)
|
|
122
|
+
|
|
123
|
+
if args.cmd == "check":
|
|
124
|
+
from .check import run as check_run
|
|
125
|
+
return check_run(REPOS, as_json=args.json)
|
|
126
|
+
|
|
127
|
+
if args.cmd == "hosts":
|
|
128
|
+
from .hosts import main as hosts_main
|
|
129
|
+
return hosts_main(REPOS, ["--json"] if args.json else [])
|
|
130
|
+
|
|
131
|
+
if args.cmd == "flow":
|
|
132
|
+
from .flow import main as flow_main
|
|
133
|
+
return flow_main(REPOS, (["--quick"] if args.quick else [])
|
|
134
|
+
+ (["--no-fetch"] if args.no_fetch else [])
|
|
135
|
+
+ (["--with-platform"] if args.with_platform else [])
|
|
136
|
+
+ (["--json"] if args.json else []))
|
|
137
|
+
|
|
138
|
+
if args.cmd == "ledger":
|
|
139
|
+
from .ledger import main as ledger_main
|
|
140
|
+
return ledger_main(REPOS, args)
|
|
141
|
+
|
|
142
|
+
if args.cmd == "rollout":
|
|
143
|
+
from .rollout import main as rollout_main
|
|
144
|
+
return rollout_main([
|
|
145
|
+
"--config", args.config, args.action,
|
|
146
|
+
*(["--rule", args.rule] if args.rule else []),
|
|
147
|
+
*(["--new-divergence"] if args.new_divergence else []),
|
|
148
|
+
"--void-rate", str(args.void_rate),
|
|
149
|
+
*(["--ref-unavailable"] if args.ref_unavailable else []),
|
|
150
|
+
*(["--json"] if args.json else []),
|
|
151
|
+
])
|
|
152
|
+
|
|
153
|
+
if args.cmd == "audit":
|
|
154
|
+
from .audit import main as audit_main
|
|
155
|
+
return audit_main((["--trust", args.trust] if args.trust else []) +
|
|
156
|
+
(["--json"] if args.json else []) +
|
|
157
|
+
["--limit", str(args.limit)] +
|
|
158
|
+
(["--record"] if args.record else []) +
|
|
159
|
+
(["--freshness-days", str(args.freshness_days)]
|
|
160
|
+
if args.freshness_days else []) +
|
|
161
|
+
(["--ca-review-days", str(args.ca_review_days)]
|
|
162
|
+
if args.ca_review_days else []) +
|
|
163
|
+
(["--legacy"] if getattr(args, "legacy", False) else []))
|
|
164
|
+
|
|
165
|
+
if args.cmd == "guide":
|
|
166
|
+
from . import guide as guide_mod
|
|
167
|
+
return guide_mod.main([args.action]
|
|
168
|
+
+ (["--full"] if args.full else [])
|
|
169
|
+
+ ["--scope", args.scope])
|
|
170
|
+
|
|
171
|
+
if args.cmd == "wiring":
|
|
172
|
+
from .wiring import main as wiring_main
|
|
173
|
+
return wiring_main(["--json"] if args.json else [])
|
|
174
|
+
|
|
175
|
+
if args.cmd == "brief":
|
|
176
|
+
from .brief import main as brief_main
|
|
177
|
+
return brief_main((["--topic", args.topic] if args.topic else [])
|
|
178
|
+
+ ["--budget", str(args.budget)]
|
|
179
|
+
+ (["--json"] if args.json else []))
|
|
180
|
+
|
|
181
|
+
if args.cmd == "facts":
|
|
182
|
+
from .facts import main as facts_main
|
|
183
|
+
return facts_main((["--json"] if args.json else [])
|
|
184
|
+
+ (["--strict"] if args.strict else []))
|
|
185
|
+
|
|
186
|
+
if args.cmd == "kb":
|
|
187
|
+
from .kb import main as kb_main
|
|
188
|
+
return kb_main([args.action, "--budget", str(args.budget)]
|
|
189
|
+
+ (["--query", args.query] if args.query else [])
|
|
190
|
+
+ (["--json"] if args.json else []))
|
|
191
|
+
|
|
192
|
+
if args.cmd == "capabilities":
|
|
193
|
+
from .capabilities import main as cap_main
|
|
194
|
+
# 括号必须包住整个条件表达式:`A if c else [] + B` 的 `+` 只粘在 `[]` 上,
|
|
195
|
+
# 于是 `--check` 一旦为真,`--group` / `--json` 全被丢掉(实测:分组探活仍跑 59 条)。
|
|
196
|
+
return cap_main((["--check"] if args.check else [])
|
|
197
|
+
+ (["--group", args.group] if args.group else [])
|
|
198
|
+
+ (["--json"] if args.json else []))
|
|
199
|
+
|
|
200
|
+
if args.cmd == "status":
|
|
201
|
+
from .chain import render, snapshot
|
|
202
|
+
state = snapshot(REPOS / "govrule")
|
|
203
|
+
print(json.dumps(state, ensure_ascii=False, indent=2) if args.json else render(state))
|
|
204
|
+
return 0
|
|
205
|
+
|
|
206
|
+
report = assemble(REPOS)
|
|
207
|
+
|
|
208
|
+
if args.cmd == "doctor":
|
|
209
|
+
import subprocess
|
|
210
|
+
targets = [args.repo] if args.repo else list(MANAGED)
|
|
211
|
+
rc_all = 0
|
|
212
|
+
for name in targets:
|
|
213
|
+
root = REPOS / name
|
|
214
|
+
py = root / ".venv" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
|
|
215
|
+
exe = str(py) if py.is_file() else sys.executable
|
|
216
|
+
proc = subprocess.run(
|
|
217
|
+
[exe, "-m", "allin_governance", "venv", "check",
|
|
218
|
+
"--root", str(root)] + (["--json"] if args.json else []),
|
|
219
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
220
|
+
out = (proc.stdout or "") + (proc.stderr or "")
|
|
221
|
+
if "No module named allin_governance" in out or "invalid choice: 'venv'" in out:
|
|
222
|
+
probe = subprocess.run([exe, "-c", "import sys; print(sys.version.split()[0])"],
|
|
223
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
224
|
+
pip = subprocess.run([exe, "-m", "pip", "--version"],
|
|
225
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
226
|
+
ok = probe.returncode == 0
|
|
227
|
+
print(f"== {name}: {'fallback' if ok else 'BROKEN'}(该仓无公共核,仅解释器/pip)"
|
|
228
|
+
f" python={(probe.stdout or '-').strip()} pip={'ok' if pip.returncode == 0 else 'MISSING'}")
|
|
229
|
+
rc_all = rc_all or (0 if ok else 1)
|
|
230
|
+
continue
|
|
231
|
+
print(f"== {name} (exit {proc.returncode})")
|
|
232
|
+
print(out.rstrip())
|
|
233
|
+
rc_all = rc_all or proc.returncode
|
|
234
|
+
return rc_all
|
|
235
|
+
|
|
236
|
+
if args.cmd == "entry" and args.list:
|
|
237
|
+
for row in report["repos"]:
|
|
238
|
+
state = "OK" if row["ok"] else "MISSING/INVALID"
|
|
239
|
+
print(f"{row['repo']:<20} {state:<16} {(row.get('contract') or {}).get('entrypoint', '-')}")
|
|
240
|
+
return 0 if report["ok"] else 1
|
|
241
|
+
|
|
242
|
+
if args.cmd == "entry":
|
|
243
|
+
row = next(r for r in report["repos"] if r["repo"] == args.repo)
|
|
244
|
+
if not row["ok"]:
|
|
245
|
+
print(f"CONTRACT FAIL: {args.repo} {row.get('reason') or row.get('problems')}", file=sys.stderr)
|
|
246
|
+
return 2
|
|
247
|
+
c = row["contract"]
|
|
248
|
+
print(f"[{args.repo}] role={c.get('role', '-')} entry={c.get('entrypoint', '-')}")
|
|
249
|
+
return 0
|
|
250
|
+
|
|
251
|
+
for row in report["repos"]:
|
|
252
|
+
if row["ok"]:
|
|
253
|
+
print(f"OK {row['repo']}: {row['contract']['role']}")
|
|
254
|
+
else:
|
|
255
|
+
print(f"FAIL {row['repo']}: {row.get('reason') or row.get('problems')}")
|
|
256
|
+
if not report["ok"]:
|
|
257
|
+
print(f"== agent verify: 契约版本 {report['contract_versions']},存在不合规仓", file=sys.stderr)
|
|
258
|
+
return 1
|
|
259
|
+
print(f"== agent verify: 三仓契约齐备(entry v{report['contract_versions']['entry']})")
|
|
260
|
+
return 0
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
if __name__ == "__main__":
|
|
264
|
+
raise SystemExit(main())
|
agent/assembly.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""装配:把「三个被治理仓 + 各自契约」装成一张可校验的表。
|
|
2
|
+
|
|
3
|
+
借鉴 superengine:装配期校验(fail-loud),运行期只读装配结果。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .bridges import contract_state
|
|
11
|
+
from .contracts import CONTRACT_VERSIONS, SUPPORTED_ENTRY
|
|
12
|
+
|
|
13
|
+
MANAGED = ("allin", "allin-governance", "govrule")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def assemble(repos_root: Path) -> dict:
|
|
17
|
+
rows = []
|
|
18
|
+
for name in MANAGED:
|
|
19
|
+
state = contract_state(Path(repos_root) / name, Path(repos_root) / "govrule")
|
|
20
|
+
rows.append({"repo": name, **state})
|
|
21
|
+
ok = all(r["ok"] for r in rows)
|
|
22
|
+
return {
|
|
23
|
+
"contract_versions": dict(CONTRACT_VERSIONS),
|
|
24
|
+
"supported_entry": list(SUPPORTED_ENTRY),
|
|
25
|
+
"ok": ok,
|
|
26
|
+
"repos": rows,
|
|
27
|
+
}
|
agent/audit.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""例行复验:用验证者信任根核对签名,不依赖签名者仓内的公钥。
|
|
2
|
+
|
|
3
|
+
与 `status` 的分工:
|
|
4
|
+
- status 看「链条通不通」(不做门禁、永远 exit 0);
|
|
5
|
+
- audit 看「签名还成不成立」(失败即 exit 1)——它是一次检查,不是展示。
|
|
6
|
+
|
|
7
|
+
只调子仓 CLI:`govrule identity verify` / `govrule receipt verify`。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import datetime as _dt
|
|
18
|
+
import json
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _py(repo: Path) -> str:
|
|
22
|
+
exe = repo / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
23
|
+
return str(exe) if exe.is_file() else sys.executable
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _say(repo: Path, *args: str) -> tuple[int, str]:
|
|
27
|
+
p = subprocess.run([_py(repo), "-m", "govrule", *args], cwd=str(repo),
|
|
28
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
29
|
+
timeout=180)
|
|
30
|
+
return p.returncode, ((p.stdout or "") + (p.stderr or "")).strip()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _log_path(repo: Path) -> Path:
|
|
34
|
+
return repo / "trust" / "audit-log.jsonl"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def record(repo: Path, res: dict) -> Path:
|
|
38
|
+
p = _log_path(repo)
|
|
39
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
entry = {"at": _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds"),
|
|
41
|
+
"checked": res["checked"], "failed": len(res["failed"]),
|
|
42
|
+
"unsigned": len(res["unsigned"]), "ok": not res["failed"]}
|
|
43
|
+
with p.open("a", encoding="utf-8") as fh:
|
|
44
|
+
fh.write(json.dumps(entry, ensure_ascii=False) + chr(10))
|
|
45
|
+
return p
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def ca_review(repo: Path, warn_days: int) -> dict:
|
|
49
|
+
"""CA 锚复审到期检查:分「已过期」「即将到期」「正常」三档。
|
|
50
|
+
|
|
51
|
+
只读索引,不联网、不续期。复审过期 = 信任升级的依据失效,
|
|
52
|
+
所以它算失败;即将到期只提示,不阻断。
|
|
53
|
+
"""
|
|
54
|
+
idx_path = repo / "trust" / "ca" / "index.json"
|
|
55
|
+
if not idx_path.is_file():
|
|
56
|
+
return {"ok": False, "reason": f"缺 {idx_path}"}
|
|
57
|
+
try:
|
|
58
|
+
entries = json.loads(idx_path.read_text(encoding="utf-8")).get("entries", [])
|
|
59
|
+
except Exception as exc: # noqa: BLE001
|
|
60
|
+
return {"ok": False, "reason": f"索引不可读:{exc}"}
|
|
61
|
+
today = _dt.date.today()
|
|
62
|
+
overdue, soon, ok, missing = [], [], [], []
|
|
63
|
+
for e in entries:
|
|
64
|
+
due = (e.get("review_due") or "").strip()
|
|
65
|
+
if not due:
|
|
66
|
+
missing.append({"file": e.get("file"), "reason": "缺 review_due"})
|
|
67
|
+
continue
|
|
68
|
+
try:
|
|
69
|
+
d = _dt.date.fromisoformat(due)
|
|
70
|
+
except Exception: # noqa: BLE001
|
|
71
|
+
missing.append({"file": e.get("file"), "reason": f"review_due 不可解析:{due}"})
|
|
72
|
+
continue
|
|
73
|
+
days = (d - today).days
|
|
74
|
+
row = {"file": e.get("file"), "review_due": due, "days": days}
|
|
75
|
+
# 当天算 DUE(还没过),严格小于今天才是 OVERDUE
|
|
76
|
+
(overdue if days < 0 else soon if days <= warn_days else ok).append(row)
|
|
77
|
+
soon.sort(key=lambda r: r["days"])
|
|
78
|
+
# 缺日期必须失败:无到期日的台账会退化成永久信任
|
|
79
|
+
return {"ok": not overdue and not missing, "overdue": overdue,
|
|
80
|
+
"soon": soon, "fine": ok, "missing": missing}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def legacy_keys(govrule_repo: Path, trust_dir: Path) -> dict:
|
|
84
|
+
"""委派 govrule 盘点 legacy 钥:数量、到期后使用、剩余天数。"""
|
|
85
|
+
py = _py(govrule_repo)
|
|
86
|
+
runs = govrule_repo / "evidence" / "runs"
|
|
87
|
+
receipts = govrule_repo / "evidence" / "receipts"
|
|
88
|
+
cmd = [py, "-m", "govrule", "identity", "audit-legacy",
|
|
89
|
+
"--trust", str(trust_dir),
|
|
90
|
+
"--records-dir", str(runs), "--records-dir", str(receipts)]
|
|
91
|
+
p = subprocess.run(cmd, cwd=str(govrule_repo), capture_output=True, text=True,
|
|
92
|
+
encoding="utf-8", errors="replace", timeout=120)
|
|
93
|
+
try:
|
|
94
|
+
data = json.loads(p.stdout)
|
|
95
|
+
except Exception: # noqa: BLE001
|
|
96
|
+
return {"ok": False, "reason": (p.stderr or p.stdout or "无输出")[:200]}
|
|
97
|
+
return {"ok": p.returncode == 0, "exit": p.returncode, **data}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def freshness(repo: Path, max_age_days: int) -> tuple[bool, str]:
|
|
101
|
+
"""最近一次**成功** audit 是否在窗口内。停摆要单独报,不能混进失败。"""
|
|
102
|
+
p = _log_path(repo)
|
|
103
|
+
if not p.is_file():
|
|
104
|
+
return False, "从未记录过 audit——无法判断是否停摆"
|
|
105
|
+
last_ok = None
|
|
106
|
+
for line in p.read_text(encoding="utf-8").splitlines():
|
|
107
|
+
if not line.strip():
|
|
108
|
+
continue
|
|
109
|
+
try:
|
|
110
|
+
e = json.loads(line)
|
|
111
|
+
except Exception: # noqa: BLE001
|
|
112
|
+
continue
|
|
113
|
+
if e.get("ok"):
|
|
114
|
+
last_ok = e.get("at")
|
|
115
|
+
if not last_ok:
|
|
116
|
+
return False, "没有一次成功的 audit 记录"
|
|
117
|
+
try:
|
|
118
|
+
t = _dt.datetime.fromisoformat(last_ok)
|
|
119
|
+
except Exception: # noqa: BLE001
|
|
120
|
+
return False, f"最后成功时间不可解析:{last_ok}"
|
|
121
|
+
age = (_dt.datetime.now(_dt.timezone.utc) - t).total_seconds() / 86400
|
|
122
|
+
if age > max_age_days:
|
|
123
|
+
return False, f"最近一次成功 audit 已 {age:.0f} 天(> {max_age_days})——停摆"
|
|
124
|
+
return True, f"最近成功 {age:.1f} 天前"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def run(govrule_repo: Path, trust_dir: Path, limit: int = 20) -> dict:
|
|
128
|
+
targets: list[dict] = []
|
|
129
|
+
runs_dir = govrule_repo / "evidence" / "runs"
|
|
130
|
+
receipts_dir = govrule_repo / "evidence" / "receipts"
|
|
131
|
+
|
|
132
|
+
# 不止看最近几条:默认 20,--limit 可调(调研:只扫 3 条会漏掉旧记录)
|
|
133
|
+
for f in sorted(runs_dir.glob("*.json"))[-limit:]:
|
|
134
|
+
rc, out = _say(govrule_repo, "identity", "verify", "--record", str(f),
|
|
135
|
+
"--trust", str(trust_dir))
|
|
136
|
+
detail = out.splitlines()[-1] if out else ""
|
|
137
|
+
targets.append({"kind": "run", "file": f.name,
|
|
138
|
+
"ok": rc == 0 or "无签名" in detail,
|
|
139
|
+
"unsigned": "无签名" in detail, "detail": detail})
|
|
140
|
+
|
|
141
|
+
for f in sorted(receipts_dir.glob("*.json")):
|
|
142
|
+
if f.name.endswith(".consume.json"):
|
|
143
|
+
continue
|
|
144
|
+
rc, out = _say(govrule_repo, "receipt", "verify", "--receipt", str(f),
|
|
145
|
+
"--trust", str(trust_dir))
|
|
146
|
+
detail = out.splitlines()[-1] if out else ""
|
|
147
|
+
targets.append({"kind": "receipt", "file": f.name,
|
|
148
|
+
"ok": rc == 0 or "无签名" in detail,
|
|
149
|
+
"unsigned": "无签名" in detail, "detail": detail})
|
|
150
|
+
|
|
151
|
+
return {"trust": str(trust_dir), "checked": len(targets),
|
|
152
|
+
"failed": [t for t in targets if not t["ok"]],
|
|
153
|
+
"unsigned": [t for t in targets if t.get("unsigned")],
|
|
154
|
+
"targets": targets}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def main(argv: list[str] | None = None) -> int:
|
|
158
|
+
import argparse
|
|
159
|
+
ap = argparse.ArgumentParser(prog="audit", description="用验证者信任根核对签名")
|
|
160
|
+
ap.add_argument("--trust", default="trust/keys")
|
|
161
|
+
ap.add_argument("--json", action="store_true")
|
|
162
|
+
ap.add_argument("--limit", type=int, default=20)
|
|
163
|
+
ap.add_argument("--legacy", action="store_true", help="同时盘点 legacy 钥")
|
|
164
|
+
ap.add_argument("--record", action="store_true", help="把本次结果追加到 trust/audit-log.jsonl")
|
|
165
|
+
ap.add_argument("--ca-review-days", type=int, default=0,
|
|
166
|
+
help="检查 CA 锚复审期:N 天内到期即提示,已过期记失败")
|
|
167
|
+
ap.add_argument("--freshness-days", type=int, default=0,
|
|
168
|
+
help="检查停摆:最近一次成功 audit 超过 N 天即失败")
|
|
169
|
+
args = ap.parse_args(argv)
|
|
170
|
+
|
|
171
|
+
from .roots import DATA_ROOT
|
|
172
|
+
trust = (DATA_ROOT / args.trust) if not Path(args.trust).is_absolute() else Path(args.trust)
|
|
173
|
+
if not trust.exists():
|
|
174
|
+
print(f"信任根不存在:{trust}", file=sys.stderr)
|
|
175
|
+
return 2
|
|
176
|
+
if args.ca_review_days:
|
|
177
|
+
ca = ca_review(root, args.ca_review_days)
|
|
178
|
+
if not ca["ok"]:
|
|
179
|
+
print(f"CA-REVIEW FAIL {ca.get('reason', '')}".rstrip())
|
|
180
|
+
for r in ca.get("overdue", []):
|
|
181
|
+
print(f" OVERDUE {r['file']} review_due={r['review_due']} days={r['days']}")
|
|
182
|
+
for r in ca.get("missing", []):
|
|
183
|
+
print(f" MISSING {r['file']} {r['reason']}")
|
|
184
|
+
return 1
|
|
185
|
+
for r in ca.get("soon", []):
|
|
186
|
+
print(f"CA-REVIEW DUE {r['file']} 还有 {r['days']} 天({r['review_due']})")
|
|
187
|
+
print(f"CA-REVIEW OK {len(ca['fine'])} 份锚未临期")
|
|
188
|
+
|
|
189
|
+
if args.freshness_days:
|
|
190
|
+
ok, reason = freshness(root, args.freshness_days)
|
|
191
|
+
print(("OK " if ok else "STALE ") + reason)
|
|
192
|
+
if not ok:
|
|
193
|
+
return 1
|
|
194
|
+
|
|
195
|
+
res = run(root.parent / "govrule", trust, args.limit)
|
|
196
|
+
if args.legacy:
|
|
197
|
+
lk = legacy_keys(root.parent / "govrule", trust)
|
|
198
|
+
print(f"LEGACY {lk.get('legacy', '?')} 把(到期后仍在用 "
|
|
199
|
+
f"{lk.get('still_used_after_deadline', '?')})")
|
|
200
|
+
for k in lk.get("keys", []):
|
|
201
|
+
print(f" {k['fingerprint']} 用 {k['records']}/{k['records_scanned']} 条,"
|
|
202
|
+
f"剩 {k['days_left']} 天,到期后 {k['records_after_effective']}")
|
|
203
|
+
if not lk.get("ok", False):
|
|
204
|
+
return lk.get("exit", 1)
|
|
205
|
+
if args.record:
|
|
206
|
+
print(f"log: {record(root, res)}")
|
|
207
|
+
if args.json:
|
|
208
|
+
print(json.dumps(res, ensure_ascii=False, indent=2))
|
|
209
|
+
else:
|
|
210
|
+
for t in res["targets"]:
|
|
211
|
+
mark = "UNSIGNED" if t.get("unsigned") else ("OK " if t["ok"] else "FAIL")
|
|
212
|
+
print(f"{mark:<9} {t['kind']:<8} {t['file']:<34} {t['detail']}")
|
|
213
|
+
print(f"== audit: {res['checked']} 项,失败 {len(res['failed'])},"
|
|
214
|
+
f"未签名 {len(res['unsigned'])}(未签名不等于被篡改,但不可验证)")
|
|
215
|
+
return 0 if not res["failed"] else 1
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""桥接层:**唯一**读被治理仓的地方。
|
|
2
|
+
|
|
3
|
+
superengine 的纪律:唯一 import 三仓的地方是 bridges/,且只经友好接口。
|
|
4
|
+
这里的「友好接口」是各仓根下的 agent.contract.yml,不读源码、不解析内部结构。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
CONTRACT = "agent.contract.yml"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_contract(repo_root: Path) -> dict:
|
|
17
|
+
"""读一个仓的入口契约。解析失败抛 ValueError——装配期失败好过运行期猜。"""
|
|
18
|
+
path = Path(repo_root) / CONTRACT
|
|
19
|
+
if not path.is_file():
|
|
20
|
+
raise FileNotFoundError(f"缺 {CONTRACT}:{path}")
|
|
21
|
+
text = path.read_text(encoding="utf-8")
|
|
22
|
+
try:
|
|
23
|
+
import yaml
|
|
24
|
+
data = yaml.safe_load(text) or {}
|
|
25
|
+
except ImportError: # 零依赖降级:契约是扁平 key: value
|
|
26
|
+
data = {}
|
|
27
|
+
for line in text.splitlines():
|
|
28
|
+
if not line.strip() or line.lstrip().startswith("#") or ":" not in line:
|
|
29
|
+
continue
|
|
30
|
+
k, v = line.split(":", 1)
|
|
31
|
+
v = v.strip().strip('"').strip("'")
|
|
32
|
+
if v:
|
|
33
|
+
data[k.strip()] = v
|
|
34
|
+
if not isinstance(data, dict):
|
|
35
|
+
raise ValueError(f"{path} 不是键值映射")
|
|
36
|
+
return data
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _python(repo_root: Path) -> str:
|
|
40
|
+
"""优先用该仓自己的 venv 解释器;没有就退回当前解释器。"""
|
|
41
|
+
for rel in ("Scripts/python.exe", "bin/python"):
|
|
42
|
+
cand = Path(repo_root) / ".venv" / rel
|
|
43
|
+
if cand.is_file():
|
|
44
|
+
return str(cand)
|
|
45
|
+
return sys.executable
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def judge_via_govrule(govrule_repo: Path, repo_root: Path) -> dict:
|
|
49
|
+
"""**委派** govrule 判契约:判据只有一份,agent 不自己实现(A3)。
|
|
50
|
+
|
|
51
|
+
agent 的定位是总入口——它靠 govrule 才能对全局起作用。所以「契约是否合规」
|
|
52
|
+
这件事不在本仓判:只调 `govrule run --rule agent.entrypoint`,读四值结论。
|
|
53
|
+
govrule 不可达时**不假装通过**:ok=False + reason,让调用方看见「没判」。
|
|
54
|
+
"""
|
|
55
|
+
rules = Path(govrule_repo) / "rules"
|
|
56
|
+
if not rules.is_dir():
|
|
57
|
+
return {"ok": False, "verdict": "unknown", "reason": f"govrule 不可达:缺 {rules}"}
|
|
58
|
+
cmd = [_python(Path(govrule_repo)), "-m", "govrule", "run",
|
|
59
|
+
"--rules", str(rules), "--root", str(repo_root),
|
|
60
|
+
"--rule", "agent.entrypoint", "--quiet"]
|
|
61
|
+
proc = subprocess.run(cmd, cwd=str(govrule_repo), capture_output=True,
|
|
62
|
+
text=True, encoding="utf-8", errors="replace")
|
|
63
|
+
verdict = {0: "pass", 1: "fail", 3: "unknown"}.get(proc.returncode, "error")
|
|
64
|
+
lines = [ln.strip() for ln in (proc.stdout or proc.stderr or "").splitlines() if ln.strip()]
|
|
65
|
+
# 取带 verdict 的那一行(govrule 的汇总行),没有就退回最后一行——证据原样转述。
|
|
66
|
+
detail = next((ln for ln in reversed(lines) if "verdict" in ln), lines[-1] if lines else "")
|
|
67
|
+
return {
|
|
68
|
+
"ok": proc.returncode == 0,
|
|
69
|
+
"verdict": verdict,
|
|
70
|
+
"reason": detail.lstrip("= ").strip() or f"govrule exit {proc.returncode}",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def contract_state(repo_root: Path, govrule_repo: Path | None = None) -> dict:
|
|
75
|
+
"""读契约(用于展示 role/entry),**判定交给 govrule**。"""
|
|
76
|
+
try:
|
|
77
|
+
data = read_contract(repo_root)
|
|
78
|
+
except Exception as exc: # noqa: BLE001
|
|
79
|
+
return {"ok": False, "reason": str(exc)}
|
|
80
|
+
if govrule_repo is None:
|
|
81
|
+
return {"ok": False, "reason": "没给 govrule 仓路径,无法判定(不假装通过)",
|
|
82
|
+
"contract": data}
|
|
83
|
+
judged = judge_via_govrule(Path(govrule_repo), Path(repo_root))
|
|
84
|
+
return {**judged, "contract": data}
|