HEL-827: implement durable life, receipt-gated disclosure and persona layers

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
白栖知
2026-10-24 09:04:40 +08:00
co-authored by multica-agent
parent 2d97050c7e
commit 4575b27515
18 changed files with 1916 additions and 19 deletions
+46
View File
@@ -0,0 +1,46 @@
"""Explicit one-profile persona backfill. Never called by server startup.
This task exercises this function only on synthetic local databases. Deployment
and authorization for any existing 8310/8320 profile remain a separate handoff.
"""
import argparse
import asyncio
import json
from pathlib import Path
import yaml
from cybergril.config import ModelsConfig
from cybergril.life.model import PersistentBudget
from cybergril.life.persona import Persona, fingerprint
from cybergril.memory.store import Store
from cybergril.think.wiring import build_router_from_config
async def backfill(path, expected):
models = ModelsConfig(**yaml.safe_load(Path("config/models.yaml").read_text()))
router = build_router_from_config(models)
try:
with Store(path) as store:
before = fingerprint(store)
if before != expected:
raise ValueError("core fingerprint does not match explicit authorization")
router.guard = PersistentBudget(store, router.guard)
persona = Persona(store, router, models, enabled=True)
ok = await persona.ensure(backfill=True)
assert fingerprint(store) == before
print(json.dumps({"ok": ok, "core_unchanged": True, "state": persona.view()["state"]}))
return ok
finally:
for tier in router.available_tiers():
await router.provider_for(tier).aclose()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--db", type=Path, required=True)
parser.add_argument("--authorize-core-sha256", required=True)
args = parser.parse_args()
if not args.db.is_file():
parser.error("existing explicitly authorized database required")
raise SystemExit(0 if asyncio.run(backfill(args.db, args.authorize_core_sha256)) else 1)
+73
View File
@@ -0,0 +1,73 @@
"""Four bounded calls, synthetic data only, no server, no production DB.
Run explicitly with --real. No retries or model/config changes on a failure.
"""
import argparse
import asyncio
import json
import tempfile
import time
from pathlib import Path
from uuid import uuid4
import httpx
from cybergril.api.app import create_app
from cybergril.life.model import PersistentBudget
from cybergril.life.persona import Persona, fingerprint
from cybergril.life.runtime import LifeConfig, LifeRuntime
async def run(output):
report = {"synthetic_only": True, "browser_connected": False, "three_day_run": False,
"max_model_calls": 4, "checks": {}}
with tempfile.TemporaryDirectory(prefix="r2-smoke-", dir=output.parent) as directory:
app = create_app(db_path=Path(directory) / "synthetic.db", life_config=LifeConfig(enabled=False))
async with app.router.lifespan_context(app):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://isolated") as c:
response = await c.post("/api/companion", json={"name": "隔离合成人物", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"})
response.raise_for_status()
s, original = app.state.store, fingerprint(app.state.store)
router, models = app.state.life.router, app.state.life.models
router.guard = PersistentBudget(s, router.guard)
persona = Persona(s, router, models, enabled=True)
start = time.monotonic()
report["checks"]["persona"] = await persona.ensure()
report["persona"] = persona.view()
runtime = LifeRuntime(s, router, models, LifeConfig(enabled=True), app.state.sharing, persona)
# An explicit synthetic current-window invocation, not backfilled production history.
await runtime.generate("synthetic-smoke", 0)
life = s.query_one("SELECT * FROM life_event")
report["checks"]["life"] = bool(life)
report["life"] = dict(life) if life else None
if life:
for name, text in (
("narrated", "刚才我这边发生了一件小事:" + life["content"]),
("word_only", "你想聊聊‘" + (life["place"] or "日常") + "’这个词吗?我不是在说自己做过什么。"),
):
tid = str(uuid4())
with s.conn:
row = s.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(?,'companion',?,?,'sent')",
(int(time.time() * 1000), text, tid))
receipt = app.state.sharing.prepare(row.lastrowid, tid, app.state.epoch, text, [life["id"]])
await app.state.sharing.judge(receipt["message_id"])
judged = dict(s.query_one("SELECT state,selected FROM sharing_attempt WHERE message_id=?", (receipt["message_id"],)))
report[name] = judged
report["checks"][name] = judged["state"] == "judged" and json.loads(judged["selected"]) == ([life["id"]] if name == "narrated" else [])
report["checks"]["unacknowledged_hidden"] = not s.query("SELECT * FROM life_event WHERE told=1")
report["checks"]["birth_unchanged"] = fingerprint(s) == original
report["elapsed_seconds"] = round(time.monotonic() - start, 2)
report["conservative_tokens"] = router.guard.used
report["life_runs"] = [dict(r) for r in s.query("SELECT status,reason FROM life_run")]
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"checks": report["checks"], "elapsed_seconds": report["elapsed_seconds"]}, ensure_ascii=False))
return all(report["checks"].values())
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--real", action="store_true", required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
raise SystemExit(0 if asyncio.run(run(args.output)) else 1)