#!/usr/bin/env python3 """模块溯源清单:生成与校验(只用标准库,构建期在装依赖之前就能跑)。 两个子命令: gen 按 deploy/docker/modules.json 扫描仓库,产出 MANIFEST.json 机器可读:每个文件的 sha256 / 行数 / 符号 / 依赖 / 安装路径 模块溯源.md 人可读:功能 → 模块 → 入口 → 探针 的反查表 --strict 时,仓库里任何没登记的 .py / .lua 都算错误(防止新模块悄悄溜进镜像) verify 按 MANIFEST.json 重算 sha256。镜像里跑就是"自证这张镜像没被改动过", 构建期跑就是"证明 wheel / plugins 装进去的和登记的一致"。 用法: python scripts/gen_manifest.py gen --strict python scripts/gen_manifest.py gen --out /out python scripts/gen_manifest.py verify --manifest /service/MANIFEST.json python scripts/gen_manifest.py verify --json """ from __future__ import annotations import argparse import ast import glob import hashlib import json import os import re import subprocess import sys import sysconfig from datetime import datetime, timezone REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REGISTRY = os.path.join("deploy", "docker", "modules.json") MANIFEST_NAME = "MANIFEST.json" MD_NAME = "模块溯源.md" # --strict 扫描范围:这些目录/文件里的 .py .lua 必须登记 SCAN_DIRS = ["middleware", "plugins", "scripts", "tools", "tests", "deploy/docker"] SCAN_ROOT_GLOB = ["*.py"] SKIP_DIR_NAMES = {"__pycache__", ".git", "dist", "build", "models", "_bak_before_openai", "intent_bench", ".venv", "node_modules", ".pytest_cache", ".ruff_cache"} LUA_HOOK_RE = re.compile(r"^function\s+plugin\.(\w+)", re.MULTILINE) # --------------------------------------------------------------------------- # # 基础工具 # --------------------------------------------------------------------------- # def sha256_file(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def read_text(path: str) -> str: try: with open(path, "rb") as fh: return fh.read().decode("utf-8", errors="replace") except OSError: return "" def count_lines(path: str) -> int: with open(path, "rb") as fh: return sum(1 for _ in fh) def rel(path: str, root: str) -> str: return os.path.relpath(path, root).replace(os.sep, "/") def git(*args: str) -> str: try: out = subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True, timeout=10) return out.stdout.strip() if out.returncode == 0 else "" except (OSError, subprocess.SubprocessError): return "" # --------------------------------------------------------------------------- # # 静态事实:符号、内部依赖、Lua 钩子 # --------------------------------------------------------------------------- # def py_facts(path: str) -> tuple[list[str], list[str]]: """返回 (顶层公开符号, 内部模块依赖)。解析失败不报错——源码可能是坏的,那不是本工具的活。""" text = read_text(path) try: tree = ast.parse(text) except SyntaxError: return [], [] symbols, imports = [], [] for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): if not node.name.startswith("_"): symbols.append(node.name) elif isinstance(node, ast.Import): for alias in node.names: if alias.name == "middleware" or alias.name.startswith("middleware."): imports.append(alias.name) elif isinstance(node, ast.ImportFrom): if node.level: # from . import x / from .x import y base = node.module or "" imports.append("middleware." + base if base else "middleware") elif node.module and (node.module == "middleware" or node.module.startswith("middleware.")): imports.append(node.module) return symbols[:8], sorted(set(imports)) def lua_facts(path: str) -> list[str]: return LUA_HOOK_RE.findall(read_text(path)) def module_dep_name(dotted: str) -> str: """'middleware.llm_worker' → 'llm_worker',用于展示。""" parts = dotted.split(".") return parts[1] if len(parts) > 1 else dotted # --------------------------------------------------------------------------- # # 登记表 → 文件列表 # --------------------------------------------------------------------------- # def load_registry(root: str) -> dict: with open(os.path.join(root, REGISTRY), "r", encoding="utf-8") as fh: return json.load(fh) def expand(root: str, registry: dict) -> tuple[list[dict], list[str]]: """把 path / glob 两种写法展开成真实文件;按登记顺序保持稳定。 返回 (entries, missing):missing 是登记了但磁盘上没有的路径。 """ out, seen, missing = [], set(), [] for item in registry["modules"]: if "glob" in item: pattern = os.path.join(root, item["glob"]) paths = sorted(glob.glob(pattern)) # 目录 glob 再往下钻一层 deeper = [] for p in paths: if os.path.isdir(p): for dirpath, dirnames, filenames in os.walk(p): dirnames[:] = [d for d in dirnames if d not in SKIP_DIR_NAMES] deeper.extend(os.path.join(dirpath, f) for f in filenames) for p in paths + sorted(deeper): if not os.path.isfile(p) or p in seen: continue seen.add(p) out.append({**item, "path": rel(p, root), "_abs": p}) else: p = os.path.join(root, item["path"]) if not os.path.isfile(p): missing.append(item["path"]) print(f"[warn] 登记的文件不存在,跳过:{item['path']}", file=sys.stderr) continue if p in seen: continue seen.add(p) out.append({**item, "_abs": p}) return out, missing def install_target(path: str, layer: str) -> dict | None: """镜像里这个文件会出现在哪:包代码在 site-packages,插件和配置在 /service。""" if layer == "wheel": return {"kind": "python", "rel": path} if layer == "image": return {"kind": "service", "rel": path} return None def describe(entry: dict) -> dict: path, abs_path = entry["path"], entry["_abs"] layer = entry["layer"] symbols, imports = ([], []) hooks = [] if path.endswith(".py"): symbols, imports = py_facts(abs_path) elif path.endswith(".lua"): hooks = lua_facts(abs_path) return { "path": path, "layer": layer, "role": entry.get("role", ""), "sha256": sha256_file(abs_path), "bytes": os.path.getsize(abs_path), "loc": count_lines(abs_path), "entry": entry.get("entry", ""), "symbols": symbols, "imports": [module_dep_name(i) for i in imports if module_dep_name(i) not in ("middleware",)], "hooks": hooks, "config": entry.get("config", []), "probe": entry.get("probe", ""), # 允许被挂载覆盖:容器里 -v 换掉它属于部署动作,不算篡改 "overridable": bool(entry.get("overridable", False)), "install": install_target(path, layer), } def find_unregistered(root: str, files: list[dict]) -> list[str]: known = {f["path"] for f in files} found = [] for d in SCAN_DIRS: base = os.path.join(root, d) for dirpath, dirnames, filenames in os.walk(base): dirnames[:] = [n for n in dirnames if n not in SKIP_DIR_NAMES] for name in filenames: if not name.endswith((".py", ".lua")): continue found.append(rel(os.path.join(dirpath, name), root)) for pattern in SCAN_ROOT_GLOB: for p in glob.glob(os.path.join(root, pattern)): found.append(rel(p, root)) return sorted(set(found) - known) # --------------------------------------------------------------------------- # # 输出:MANIFEST.json # --------------------------------------------------------------------------- # def bundle_digest(files: list[dict]) -> str: h = hashlib.sha256() for f in sorted(files, key=lambda x: x["path"]): h.update(f"{f['path']}\0{f['sha256']}\n".encode()) return h.hexdigest() def build_manifest(registry: dict, files: list[dict], unregistered: list[str], missing: list[str] | None = None) -> dict: image_files = [f for f in files if f["layer"] in ("wheel", "image")] return { "schema": 1, "generated_at": datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds"), "generator": "scripts/gen_manifest.py", "image": registry["image"], "source": { "git_rev": git("rev-parse", "--short", "HEAD"), "git_dirty_files": len([l for l in git("status", "--porcelain").splitlines() if l.strip()]), "python": "%d.%d.%d" % sys.version_info[:3], "registry": REGISTRY, }, "bundle_digest": bundle_digest(files), "totals": { "files": len(files), "bytes": sum(f["bytes"] for f in files), "loc": sum(f["loc"] for f in files), "image_files": len(image_files), "image_bytes": sum(f["bytes"] for f in image_files), "image_loc": sum(f["loc"] for f in image_files), }, "unregistered": unregistered, "missing_registered": missing or [], "files": files, } # --------------------------------------------------------------------------- # # 输出:模块溯源.md # --------------------------------------------------------------------------- # def md_cell(text: str, width: int = 0) -> str: clean = (text or "").replace("|", "\\|").replace("\n", " ").strip() if width and len(clean) > width: clean = clean[: width - 1] + "…" return clean or "—" def render_md(manifest: dict, registry: dict) -> str: files = manifest["files"] by_path = {f["path"]: f for f in files} t = manifest["totals"] img = manifest["image"] lines: list[str] = [] a = lines.append a("# 模块溯源清单") a("") a("> 本文件由 `scripts/gen_manifest.py gen` 生成,**不要手改**。") a("> 唯一来源是 `deploy/docker/modules.json`(模块职责)+ 仓库文件本身的 sha256。") a("") a(f"- 生成时间:`{manifest['generated_at']}`  源码版本:`{manifest['source']['git_rev'] or 'unknown'}`" f"({manifest['source']['git_dirty_files']} 个未提交改动)") a(f"- 镜像:`{img['name']}:{img['version']}`,目标 `{'` / `'.join(img['targets'])}`," f"入口 `{img['console_script']}` → `{img['module_entry']}`") a(f"- 登记文件 **{t['files']}** 个 / {t['loc']} 行;其中进镜像 **{t['image_files']}** 个 / " f"{t['image_loc']} 行 / {t['image_bytes'] / 1024:.0f} KB") a(f"- `bundle_digest`:`{manifest['bundle_digest']}`") a("") a("## 1. 怎么溯源") a("") a("```bash") a("# ① 这张镜像是什么时候、从哪个 commit 构建的") a("docker inspect -f '{{json .Config.Labels}}' agent-safe-middleware:core") a("") a("# ② 镜像里每个文件对回仓库的哪一行——清单自带 sha256 与安装路径") a("docker run --rm --entrypoint cat agent-safe-middleware:core /service/MANIFEST.json | head -40") a("") a("# ③ 自证:重算 sha256,证明镜像内容与构建时登记的一致(交付/审计时跑这条)") a("docker run --rm --entrypoint python agent-safe-middleware:core /service/gen_manifest.py verify") a("") a("# ④ 这一层是谁带进来的:镜像层与构建指令") a("docker history --no-trunc agent-safe-middleware:core") a("```") a("") a("## 2. 功能 → 模块 → 探针") a("") a("按“这个能力由谁负责、怎么证明它在跑”反查。探针里的 `:8080` 指中间层容器。") a("") a("| 功能 | 负责模块 | 怎么验证 |") a("|---|---|---|") for feat in registry.get("features", []): mods = "
".join(f"`{m}`" for m in feat["modules"]) a(f"| {md_cell(feat['name'])} | {mods} | {md_cell(feat.get('probe', ''), 90)} |") a("") a("## 3. 进镜像的模块") a("") a("### 3.1 包代码(`wheel` → site-packages)") a("") a("| 文件 | 行 | sha256 | 职责 | 顶层符号 | 内部依赖 |") a("|---|---:|---|---|---|---|") for f in [x for x in files if x["layer"] == "wheel"]: syms = ", ".join(f"`{s}`" for s in f["symbols"]) or "—" deps = ", ".join(f"`{d}`" for d in f["imports"]) or "—" a(f"| `{f['path']}` | {f['loc']} | `{f['sha256'][:12]}` | {md_cell(f['role'], 120)} | {syms} | {deps} |") a("") a("### 3.2 插件与配置(`image` → /service)") a("") a("| 文件 | 行 | sha256 | 职责 | 导出钩子 | 关联配置 |") a("|---|---:|---|---|---|---|") for f in [x for x in files if x["layer"] == "image"]: hooks = ", ".join(f"`{h}`" for h in f["hooks"]) or "—" cfgs = ", ".join(f"`{c}`" for c in f["config"]) or "—" a(f"| `{f['path']}` | {f['loc']} | `{f['sha256'][:12]}` | {md_cell(f['role'], 140)} | {hooks} | {cfgs} |") a("") a("## 4. 不进镜像的文件") a("") a("| 文件 | 层 | 职责 | 备注 |") a("|---|---|---|---|") for f in [x for x in files if x["layer"] not in ("wheel", "image")]: a(f"| `{f['path']}` | `{f['layer']}` | {md_cell(f['role'], 110)} | {md_cell(f['probe'], 60)} |") a("") a("## 5. 配置键 → 落在哪个模块") a("") a("| 配置键 | 读取方 |") a("|---|---|") rows = [(c, f["path"]) for f in files for c in f["config"]] for key, path in sorted(set(rows)): a(f"| `{key}` | `{path}` |") a("") a("## 6. 一致性登记") a("") unreg = manifest["unregistered"] missing = manifest.get("missing_registered", []) a("| 检查项 | 结果 |") a("|---|---|") a(f"| 仓库里未登记的 .py/.lua | {len(unreg)}" + (f":{', '.join('`' + u + '`' for u in unreg)} |" if unreg else " ✔ |")) a(f"| 登记了但磁盘上没有的文件 | {len(missing)}" + (f":{', '.join('`' + m + '`' for m in missing)} |" if missing else " ✔ |")) a(f"| 登记文件总数 | {t['files']} 个 / {t['loc']} 行 |") a(f"| 其中进镜像 | **{t['image_files']}** 个 / {t['image_loc']} 行 / {t['image_bytes']} B |") a(f"| 生成器 | `{manifest['generator']}`(Python {manifest['source']['python']}) |") a("") a("> 交付时把 `MANIFEST.json` 与本文件一起给出:任何一个文件被改,`verify` 都会报出具体路径与新旧 sha256。") a("") return "\n".join(lines) # --------------------------------------------------------------------------- # # gen # --------------------------------------------------------------------------- # def cmd_gen(args: argparse.Namespace) -> int: root = os.path.abspath(args.root) registry = load_registry(root) entries, missing = expand(root, registry) files = [describe(e) for e in entries] unregistered = find_unregistered(root, files) if args.strict and unregistered: print("[strict] 以下模块没有在 %s 里登记:" % REGISTRY, file=sys.stderr) for path in unregistered: print(" - " + path, file=sys.stderr) print("把它们补进 modules.json(写上 role 与 probe)再构建。", file=sys.stderr) return 1 manifest = build_manifest(registry, files, unregistered, missing) out_dir = os.path.abspath(args.out) os.makedirs(out_dir, exist_ok=True) manifest_path = os.path.join(out_dir, MANIFEST_NAME) with open(manifest_path, "w", encoding="utf-8") as fh: json.dump(manifest, fh, ensure_ascii=False, indent=2) fh.write("\n") md_path = os.path.join(out_dir, MD_NAME) with open(md_path, "w", encoding="utf-8") as fh: fh.write(render_md(manifest, registry)) t = manifest["totals"] print(f"[gen] {manifest_path}") print(f"[gen] {md_path}") print(f"[gen] 登记 {t['files']} 个文件 / {t['loc']} 行;进镜像 {t['image_files']} 个 / {t['image_loc']} 行 / " f"{t['image_bytes'] / 1024:.0f} KB;bundle_digest={manifest['bundle_digest'][:16]}…") if unregistered: print(f"[gen] 注意:{len(unregistered)} 个未登记模块(未加 --strict 不拦截)") return 0 # --------------------------------------------------------------------------- # # verify # --------------------------------------------------------------------------- # def resolve_install(item: dict, service_root: str = "/service") -> str | None: """把清单里的安装描述落成真实路径:包代码查此刻解释器的 purelib,插件/配置查镜像里的 /service。""" install = item.get("install") if not install: return None if install["kind"] == "python": return os.path.join(sysconfig.get_paths()["purelib"], install["rel"]) if install["kind"] == "service": return os.path.join(service_root, install["rel"]) return install.get("path") def cmd_verify(args: argparse.Namespace) -> int: """优先核验"镜像里的安装位置",不存在再退回仓库路径——这样在镜像里和仓库里都能跑。""" manifest_path = os.path.abspath(args.manifest) with open(manifest_path, "r", encoding="utf-8") as fh: manifest = json.load(fh) root = os.path.abspath(args.root) ok, missing, changed, skipped, notes = 0, [], [], 0, [] overridden = [] via_repo = 0 service_root = os.path.abspath(args.service_root) for item in manifest["files"]: install = resolve_install(item, service_root) if install is None: skipped += 1 continue target, where = (install, "install") if not os.path.exists(target): fallback = os.path.join(root, item["path"]) if os.path.exists(fallback): target, where = fallback, "repo" via_repo += 1 else: missing.append((item["path"], install)) continue actual = sha256_file(target) if actual != item["sha256"]: if item.get("overridable"): # 设计上就该被 -v 覆盖的路径(如 /service/config.yaml),记一笔但不判失败 overridden.append((item["path"], target, item["sha256"][:12], actual[:12])) else: changed.append((item["path"], target, item["sha256"][:12], actual[:12])) else: ok += 1 total_checked = ok + len(missing) + len(changed) result = { "manifest": manifest_path, "generated_at": manifest.get("generated_at"), "git_rev": manifest.get("source", {}).get("git_rev"), "bundle_digest": manifest.get("bundle_digest"), "checked": total_checked, "ok": ok, "missing": missing, "changed": changed, "overridden": overridden, "skipped": skipped, "via_repo": via_repo, "passed": not missing and not changed, } if args.json: print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if result["passed"] else 1 print(f"校验 {manifest_path}") print(f" 生成于 {manifest.get('generated_at')} 源码 {result['git_rev'] or 'unknown'} " f"bundle_digest {str(result['bundle_digest'])[:16]}…") print(f" 已核验 {total_checked} 个路径:一致 {ok},缺失 {len(missing)},变更 {len(changed)}" + (f",被挂载覆盖 {len(overridden)}(预期)" if overridden else "") + f";跳过 {skipped} 个(build/dev/excluded,不进镜像)") if via_repo: print(f" 提示:{via_repo} 个文件镜像路径不存在,已退回仓库路径比对(在镜像里跑会更严格)") for path, target in missing[:10]: print(f" [缺失] {path} → {target}") for path, target, want, got in overridden[:10]: print(f" [覆盖] {path} → {target}\n 清单 {want}… 实际 {got}…(该路径允许 -v 覆盖,不计失败)") for path, target, want, got in changed[:10]: print(f" [变更] {path} → {target}\n 期望 {want}… 实际 {got}…") if len(missing) + len(changed) > 10: notes.append("差异超过 10 条,其余省略") if notes: print(" " + ";".join(notes)) print(" 结果:" + ("一致,镜像内容未被改动 ✔" if result["passed"] else "不一致 ✘")) return 0 if result["passed"] else 1 # --------------------------------------------------------------------------- # def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="gen_manifest.py", description="agent-safe-middleware 模块溯源清单:生成与校验", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="示例:\n" " %(prog)s gen --strict\n" " %(prog)s gen --out /out\n" " %(prog)s verify --manifest /service/MANIFEST.json\n", ) sub = parser.add_subparsers(dest="cmd", required=True) p_gen = sub.add_parser("gen", help="扫描仓库,生成 MANIFEST.json 与 模块溯源.md") p_gen.add_argument("--root", default=REPO_ROOT, help="仓库根目录(默认本脚本上一级)") p_gen.add_argument("--out", default=None, help="输出目录(默认 docs/)") p_gen.add_argument("--strict", action="store_true", help="有未登记模块即失败") p_gen.set_defaults(func=cmd_gen) p_ver = sub.add_parser("verify", help="按清单重算 sha256,检查内容是否被改动") p_ver.add_argument("--manifest", default="/service/" + MANIFEST_NAME, help="清单路径") p_ver.add_argument("--root", default=REPO_ROOT, help="仓库根(镜像路径缺失时退回这里比对)") p_ver.add_argument("--service-root", default="/service", help="镜像里插件与配置的落点(默认 /service)") p_ver.add_argument("--json", action="store_true", help="输出 JSON") p_ver.set_defaults(func=cmd_verify) args = parser.parse_args(argv) if args.cmd == "gen" and args.out is None: # 默认落在 docs/:仓库根只保留源码,生成物集中一处 args.out = os.path.join(args.root, "docs") return args.func(args) if __name__ == "__main__": sys.exit(main())