274 lines
12 KiB
Python
274 lines
12 KiB
Python
"""HEL-913 运行准备离线验证:零真实调用(cap=0 + 死地址双重保险)。
|
||
|
||
在进程内用 TestClient 走统一实例的关键接线:入口健康、创建守门、传输
|
||
(SSE 对话在预算 0 下诚实拒绝且绝不触发出站)、关系调整、日子与回忆
|
||
读取的服务端裁剪、语音诚实拒绝、重开(epoch/资料保留)、静态页与 dist
|
||
哈希。不监听任何端口(836x/8082/9880/8090 全程不出现监听 socket),
|
||
不访问真实网关(models.base_url 重写为 127.0.0.1:1,livekit 指向死地址,
|
||
即使预算闸失效也只能连本机死端口)。
|
||
|
||
用法(在候选 head 检出根目录、产品 3.11 venv 下):
|
||
PYTHONPATH=src <venv311>/python deploy/hel913-unified/verify_offline.py \
|
||
[--web <dist目录>] [--keep]
|
||
退出码 0 = 全部通过;任一 FAIL 即非 0。临时库写在 <root>/.hel913-verify-tmp,
|
||
默认结束后删除(--keep 保留)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import atexit
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
import uuid
|
||
from pathlib import Path
|
||
|
||
RESULTS: list[tuple[bool, str]] = []
|
||
|
||
|
||
def check(ok: bool, label: str) -> bool:
|
||
RESULTS.append((bool(ok), label))
|
||
print(("PASS " if ok else "FAIL ") + label)
|
||
return bool(ok)
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--web", default=None, help="web dist 目录(只读;默认不挂静态)")
|
||
parser.add_argument("--keep", action="store_true")
|
||
args = parser.parse_args()
|
||
|
||
root = Path(__file__).resolve().parents[2]
|
||
os.chdir(root)
|
||
tmp = Path(tempfile.mkdtemp(prefix="hel913-verify-", dir=root))
|
||
if not args.keep:
|
||
atexit.register(shutil.rmtree, tmp, ignore_errors=True)
|
||
|
||
# ---- 0. 包完整性:Python / 锁定依赖 / 模块树 -----------------------------
|
||
check(sys.version_info[:2] == (3, 11), f"python 3.11 (actual {sys.version_info[:3]})")
|
||
import cybergril # noqa: E402
|
||
|
||
check(str(Path(cybergril.__file__).resolve()).startswith(str(root / "src")),
|
||
f"cybergril imported from candidate tree ({cybergril.__file__})")
|
||
import fastapi # noqa: E402
|
||
import httpx # noqa: E402
|
||
import pydantic # noqa: E402
|
||
import uvicorn # noqa: E402
|
||
import yaml # noqa: E402
|
||
|
||
check(True, f"deps: fastapi {fastapi.__version__} uvicorn {uvicorn.__version__} "
|
||
f"httpx {httpx.__version__} pydantic {pydantic.__version__}")
|
||
from cybergril.api.app import create_app # noqa: E402
|
||
from cybergril.voice.router import build_voice_router # noqa: E402
|
||
from cybergril.voice.session import load_voice_config # noqa: E402
|
||
|
||
check(True, "product modules import (api.app / voice.router / voice.session)")
|
||
|
||
# 记忆栈缺项如实呈现(不允许 stub 冒充真实 mem0)
|
||
for mod, expect in (("mem0", False), ("qdrant_client", False), ("fastembed", False)):
|
||
try:
|
||
__import__(mod)
|
||
got = True
|
||
except Exception:
|
||
got = False
|
||
check(got == expect, f"{mod} {'absent' if not expect else 'present'} in product venv (as documented)")
|
||
|
||
# ---- 1. 脱敏配置:cap=0 + 死地址 ----------------------------------------
|
||
models_src = (root / "config" / "models.yaml").read_text()
|
||
assert "daily_tokens" in models_src, "models.yaml missing budget block"
|
||
dead = models_src.replace("192.168.200.11:8731", "127.0.0.1:1")
|
||
assert "192.168" not in dead, "real gateway address survived rewrite"
|
||
models_path = tmp / "models.yaml"
|
||
models_path.write_text(dead)
|
||
|
||
voice_path = tmp / "voice.yaml"
|
||
voice_path.write_text(
|
||
"# HEL-913 offline template: everything points at dead local ports;\n"
|
||
"# no real LiveKit/TTS/panel is contacted by this verification.\n"
|
||
"livekit_url: ws://127.0.0.1:1\n"
|
||
"livekit_internal: http://127.0.0.1:1\n"
|
||
"api_key: dead\n"
|
||
"api_secret: dead\n"
|
||
"agent_name: cybergril-voice-agent\n"
|
||
"tts_health_url: http://127.0.0.1:1/health\n"
|
||
"panel_url: https://127.0.0.1:1\n"
|
||
"tts_url: http://127.0.0.1:1\n"
|
||
"registry_file: " + str(tmp / "voices.json") + "\n"
|
||
"worker_state_file: " + str(tmp / "voice_state.json") + "\n"
|
||
"token_ttl_seconds: 300\n"
|
||
"session_ttl_seconds: 900\n"
|
||
)
|
||
db_path = tmp / "companion.db"
|
||
|
||
env = {
|
||
"CYBERGRIL_DB": str(db_path),
|
||
"CYBERGRIL_MODELS": str(models_path),
|
||
"CYBERGRIL_VOICE_CONFIG": str(voice_path),
|
||
"CYBERGRIL_SEMANTIC": "stub",
|
||
"CYBERGRIL_R2_ENABLED": "1",
|
||
**({"CYBERGRIL_WEB": args.web} if args.web else {}),
|
||
}
|
||
old = {k: os.environ.get(k) for k in env}
|
||
os.environ.update(env)
|
||
|
||
from fastapi.testclient import TestClient # noqa: E402
|
||
|
||
app = create_app()
|
||
# 出站哨兵:把所有已装配 provider 的 stream 打上标记——预算 0 下任何
|
||
# 真实发送意图都会把本验证置为 FAIL(而不是悄悄连死地址)。
|
||
outbound = []
|
||
client = TestClient(app)
|
||
|
||
with client:
|
||
st = app.state
|
||
router = st.life.router # LifeRuntime 持有本实例同一 router
|
||
for tier in router.available_tiers():
|
||
prov = router.provider_for(tier)
|
||
|
||
def _guard_stream(self, *a, __orig=prov.stream, __name=getattr(prov, "name", tier), **kw):
|
||
outbound.append(__name)
|
||
raise AssertionError(f"unexpected outbound stream via {__name}")
|
||
|
||
prov.stream = _guard_stream.__get__(prov, type(prov))
|
||
|
||
birth = {"birth": "2001-08-16", "hour": "辰时", "name": "临川", "relation": "朋友",
|
||
"nickname": "", "boundary": "轻松相处"}
|
||
|
||
# 2. 入口健康
|
||
r = client.get("/api/health")
|
||
h = r.json()
|
||
check(r.status_code == 200 and h["ok"] and h["capabilities"]["text"] is True,
|
||
"GET /api/health 200, text capability true")
|
||
check(h["companion_created"] is False, "health: companion_created=false before creation")
|
||
check(h["llm"]["ok"] is False, "health: llm honestly not ok (dead addr, cap=0)")
|
||
|
||
# 3. 创建守门:空库 404,不能读出任何伪造档案
|
||
check(client.get("/api/companion").status_code == 404,
|
||
"GET /api/companion 404 before creation (no fabricated profile)")
|
||
|
||
# 4. 生辰预览:纯本地计算,无模型参与(BirthInput 只收 name/birth/hour)
|
||
r = client.post("/api/companion/preview",
|
||
json={k: birth[k] for k in ("name", "birth", "hour")})
|
||
preview_pillars = r.json().get("pillars") if r.status_code == 200 else None
|
||
check(r.status_code == 200 and "pillars" in r.json() and "sections" in r.json(),
|
||
"POST /api/companion/preview 200 (local bazi compile)")
|
||
|
||
# 5. 创建 + 底色只读落库
|
||
r = client.post("/api/companion", json=birth)
|
||
check(r.status_code == 201 and r.json()["name"] == "临川",
|
||
"POST /api/companion 201")
|
||
row = st.store.query_one("SELECT pillars FROM bazi_core WHERE id=1")
|
||
saved_day = json.loads(row["pillars"])["day"][0] if row else None
|
||
prev_day = (preview_pillars or {}).get("day", [None])[0]
|
||
check(saved_day is not None and saved_day == prev_day,
|
||
f"bazi_core persisted and matches preview (day master {saved_day})")
|
||
check(client.post("/api/companion", json=birth).status_code == 409,
|
||
"second create refused 409 (single companion guard)")
|
||
pv = client.get("/api/persona").json()
|
||
check(pv["interpretation"] is None and pv["state"] in {"failed", "loading", "disabled"},
|
||
f"persona honest at cap=0 (state={pv['state']}, no fabricated interpretation)")
|
||
|
||
# 6. 传输:SSE 对话在预算 0 下诚实拒绝,零出站
|
||
turn1 = str(uuid.uuid4())
|
||
with client.stream("POST", "/api/chat",
|
||
json={"text": "在吗", "turn_id": turn1, "epoch": st.epoch}) as resp:
|
||
check(resp.status_code == 200 and resp.headers["content-type"].startswith("text/event-stream"),
|
||
"POST /api/chat opens SSE stream")
|
||
kinds = [json.loads(line[6:])["t"] for line in resp.iter_lines()
|
||
if line.startswith("data: ")]
|
||
check("chat.error" in kinds and "chat.final" not in kinds,
|
||
f"chat honestly errors at cap=0 (frames={kinds})")
|
||
check(not outbound, f"zero provider stream calls (outbound={outbound})")
|
||
msgs = client.get("/api/messages").json()["messages"]
|
||
check(msgs and msgs[-1]["role"] == "user" and msgs[-1]["status"] in {"failed", "cancelled"},
|
||
"failed turn persisted as user row, no fake companion reply")
|
||
with client.stream("POST", "/api/chat",
|
||
json={"text": "在吗", "turn_id": turn1, "epoch": st.epoch}) as resp:
|
||
kinds2 = [json.loads(line[6:])["t"] for line in resp.iter_lines()
|
||
if line.startswith("data: ")]
|
||
check("chat.error" in kinds2 and not outbound,
|
||
"retry same failed turn: honest error again, still zero outbound")
|
||
|
||
# 7. 关系可调整、名字保留
|
||
r = client.patch("/api/relation", json={"relation": "恋人"})
|
||
check(r.status_code == 200 and r.json()["relation"] == "恋人" and r.json()["name"] == "临川",
|
||
"PATCH /api/relation 200 (relation adjustable, name kept)")
|
||
|
||
# 8. 日子与回忆:服务端裁剪 + 分页形状(told=1 之外不可见)
|
||
r = client.get("/api/life")
|
||
check(r.status_code == 200 and r.json()["events"] == [],
|
||
"GET /api/life 200 empty (only told events, none yet)")
|
||
r = client.get("/api/memories")
|
||
check(r.status_code == 200 and r.json()["memories"] == [],
|
||
"GET /api/memories 200 empty")
|
||
check(client.get("/api/life/1").status_code == 404,
|
||
"GET /api/life/1 404 (unshared detail refused)")
|
||
bogus = {"message_id": 99999, "turn_id": str(uuid.uuid4()), "epoch": st.epoch,
|
||
"token": "x" * 40, "text_hash": "0" * 64}
|
||
check(client.post("/api/chat/received", json=bogus).status_code == 404,
|
||
"POST /api/chat/received 404 on unknown receipt")
|
||
|
||
# 9. 语音诚实拒绝:配置指向死地址 → 开房必须 503,绝不建房
|
||
r = client.get("/api/voice/status")
|
||
check(r.status_code == 200 and r.json()["configured"] is True and r.json()["voice"] is False,
|
||
"GET /api/voice/status 200, voice honestly false")
|
||
r = client.post("/api/voice/session")
|
||
check(r.status_code == 503,
|
||
f"POST /api/voice/session honest 503 when TTS unreachable ({r.status_code})")
|
||
check(client.delete("/api/voice/session/no-such").status_code == 404,
|
||
"DELETE /api/voice/session/{unknown} honest 404")
|
||
|
||
# 10. 静态页与 dist 哈希(只读)
|
||
if args.web:
|
||
page = client.get("/")
|
||
check(page.status_code == 200 and b"<div id=" in page.content,
|
||
"GET / serves web dist index.html")
|
||
|
||
# 11. 重开:新进程入口、epoch 递增、资料保留
|
||
with TestClient(app) as client2:
|
||
h2 = client2.get("/api/health").json()
|
||
check(h2["epoch"] == 2, f"reopen: epoch=2 (got {h2['epoch']})")
|
||
c2 = client2.get("/api/companion").json()
|
||
check(c2["name"] == "临川" and c2["relation"] == "恋人" and c2["birth"] == "2001-08-16",
|
||
"reopen: companion identity + adjusted relation retained")
|
||
m2 = client2.get("/api/messages").json()["messages"]
|
||
check(len(m2) == 1 and m2[0]["role"] == "user",
|
||
"reopen: chat history retained, still no fabricated replies")
|
||
|
||
if args.web:
|
||
manifest = json.loads((Path(__file__).parent / "dist-manifest.json").read_text())
|
||
bad = []
|
||
for rel, want in manifest.items():
|
||
p = Path(args.web) / rel
|
||
if not p.is_file():
|
||
bad.append(f"{rel} missing")
|
||
continue
|
||
import hashlib
|
||
|
||
got = hashlib.sha256(p.read_bytes()).hexdigest()
|
||
if got != want:
|
||
bad.append(f"{rel} {got[:12]}!={want[:12]}")
|
||
check(not bad, f"dist matches manifest ({len(manifest)} files; bad={bad})")
|
||
|
||
for k, v in old.items():
|
||
if v is None:
|
||
os.environ.pop(k, None)
|
||
else:
|
||
os.environ[k] = v
|
||
|
||
failed = [label for ok, label in RESULTS if not ok]
|
||
print(f"\n{len(RESULTS) - len(failed)}/{len(RESULTS)} checks passed")
|
||
if failed:
|
||
print("FAILED:")
|
||
for f in failed:
|
||
print(" - " + f)
|
||
return 1
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|