#!/usr/bin/env python3 """HEL-919 · 「同一位她」接续迁移工具(离线、零真实调用、零网络)。 把一份**已有非空档案**(同一位她的库)迁移进本卡专属新实例的隔离资料空间, 证明:非空档案、出生事实/诠释、姓名、习惯、关系、聊天、生活、记忆出处及 向量数据目录可以接续——不走新建人格,也不因已有档案拒绝(旧 deploy/hel914-user/activate.sh 只接受空库,这是它不能续用的原因)。 三条铁律: 1. **源库只读**。一律以 `mode=ro` 打开,任何路径都不写源库;旧封账、旧 计数、冻结值、旧失败记录原样保留在源库,迁移后逐项核对不变。 2. **旧账冻结、新账隔离**。迁移副本中,旧 `budget_total` 的 sealed/sealed_* 标记被移入冻结出处键 `cont_prior_sealed*`(仅删副本里的 live sealed 键,源库不动);token_usage/request_usage 历史行与 total_requests/total_tokens 计数原样保留,新用量由既有 PersistentBudget 机制在**同一副本**上继续累计——新旧在同一份账里天然可分(cont_migrated_at 之前/之后),不存在第二份权威账并发消费。语义嵌入权威账(embed_ops) **不复制**:它仍是唯一权威账文件,经 semantic.template.yaml 的累计上限 算式续账(见 README §语义账)。 3. **幂等与回退**。同一源重复迁移 = 安全 no-op;不同源拒绝;迁移前目标库 如已存在先做一致性备份,`rollback` 按 continuation.json 精确还原或清除。 队列盘点只输出**数量与待处理 ID**(persona_job/growth_job/mem_job/ chat_affect_job/sem_batch/sharing_attempt/reach_out/life_activity),不输出 任何聊天或生活内容。 用法(在本检出根目录,系统 python3 即可,仅标准库): python3 deploy/hel919-continuation/migrate_same_her.py preflight --db SRC python3 deploy/hel919-continuation/migrate_same_her.py migrate --db SRC \ --base /opt/cybergril-hel919 \ [--data-dir SRC_DIR=DST_REL ...] # 向量/推导史目录随实例迁移 python3 deploy/hel919-continuation/migrate_same_her.py rollback \ --base /opt/cybergril-hel919 全部子命令输出 JSON(stdout),失败 rc=1 且错误也走 JSON。 """ from __future__ import annotations import argparse import datetime import hashlib import json import shutil import sqlite3 import time from pathlib import Path # 迁移后必须仍能证明「同一位她」的出处表(计数核对;内容不离开本机)。 SAME_HER_TABLES = ( "bazi_core", # 出生事实(八字底色) "persona_interp", # 出生诠释原文 "persona_seed", # 初始习惯种子 "mem_episodic", # 情景记忆(含 gist 压缩) "mem_semantic", # 语义记忆(事实) "mem_relational", # 关系层(仪式/暗语/相处方式) "chat_message", # 聊天 "life_event", # 生活 "dyad_event", # 关系事件 "identity_change_log", # 底色变化留痕 ) # 队列盘点:表名 → (待处理判定 SQL)。只取数量与 ID,不取内容。 QUEUE_TABLES: dict[str, str] = { "persona_job": "SELECT count(*) n FROM persona_job WHERE state NOT IN ('done')", "growth_job": "SELECT count(*) n FROM growth_job WHERE state NOT IN ('done')", "mem_job": "SELECT count(*) n FROM mem_job WHERE state IN ('queued','pending')", "chat_affect_job": "SELECT count(*) n FROM chat_affect_job WHERE state='pending'", "sem_batch": "SELECT count(*) n FROM sem_batch WHERE state IN ('queued','pending')", "sharing_attempt": "SELECT count(*) n FROM sharing_attempt WHERE state IN ('pending','evaluating')", "reach_out": "SELECT count(*) n FROM reach_out WHERE state='pending'", "life_activity": "SELECT count(*) n FROM life_activity WHERE state IN ('active','interrupted')", } QUEUE_ID_SQL: dict[str, str] = { "persona_job": "SELECT id FROM persona_job WHERE state NOT IN ('done')", "growth_job": "SELECT source||':'||ref_id FROM growth_job WHERE state NOT IN ('done')", "mem_job": "SELECT source||':'||ref_id FROM mem_job WHERE state IN ('queued','pending')", "chat_affect_job": "SELECT message_id FROM chat_affect_job WHERE state='pending'", "sem_batch": "SELECT id FROM sem_batch WHERE state IN ('queued','pending')", "sharing_attempt": "SELECT message_id FROM sharing_attempt WHERE state IN ('pending','evaluating')", "reach_out": "SELECT id FROM reach_out WHERE state='pending'", "life_activity": "SELECT id FROM life_activity WHERE state IN ('active','interrupted')", } LIVE_SEALED_KEYS = ("sealed", "sealed_requests", "sealed_tokens", "sealed_at") PRIOR_KEY = { # live 键 → 冻结出处键(只写进迁移副本) "sealed": "cont_prior_sealed", "sealed_requests": "cont_prior_sealed_requests", "sealed_tokens": "cont_prior_sealed_tokens", "sealed_at": "cont_prior_sealed_at", } def _ro(db: Path) -> sqlite3.Connection: if not db.is_file(): raise SystemExit(json.dumps({"ok": False, "error": f"db_missing:{db}"}, ensure_ascii=False)) conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True) conn.row_factory = sqlite3.Row return conn def _sha256(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def _identity(conn: sqlite3.Connection) -> dict: """身份指纹:companion 行 + bazi_core 出生的可核摘要(不输出全文)。""" comp = conn.execute("SELECT id, identity_json FROM companion").fetchall() if not comp: raise SystemExit(json.dumps( {"ok": False, "refused": "empty_profile", "error": "源库 companion 表为空:空档案/新建人格不是本工具的输入" "(旧 activate.sh 只接受空库;本工具只接续已有同一位她)"}, ensure_ascii=False)) ident = json.loads(comp[0]["identity_json"]) bazi = conn.execute("SELECT birth_input, pillars, day_master, derived, version FROM bazi_core").fetchall() if not bazi: raise SystemExit(json.dumps( {"ok": False, "refused": "missing_birth", "error": "源库 bazi_core 为空:出生底色缺失,不能证明是同一位她"}, ensure_ascii=False)) interp = conn.execute("SELECT count(*) n FROM persona_interp").fetchone()["n"] if not interp: raise SystemExit(json.dumps( {"ok": False, "refused": "missing_persona", "error": "源库 persona_interp 为空:出生诠释缺失,不能证明是同一位她"}, ensure_ascii=False)) fp = hashlib.sha256(json.dumps( [comp[0]["identity_json"], [dict(r) for r in bazi]], ensure_ascii=False, sort_keys=True).encode()).hexdigest() return { "companion_id": comp[0]["id"], "name": ident.get("name"), "identity_sha256": fp, "birth": {"pillars": json.loads(bazi[0]["pillars"]), "day_master": bazi[0]["day_master"], "version": bazi[0]["version"]}, } def _counts(conn: sqlite3.Connection, tables) -> dict: out = {} for t in tables: try: out[t] = conn.execute(f"SELECT count(*) n FROM {t}").fetchone()["n"] except sqlite3.OperationalError: out[t] = None # 表不存在:旧库未启用该能力,如实记录 return out def _accounting(conn: sqlite3.Connection) -> dict: total = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM budget_total")} return { "budget_total": total, "token_usage_rows": conn.execute("SELECT count(*) n FROM token_usage").fetchone()["n"], "request_usage_rows": conn.execute("SELECT count(*) n FROM request_usage").fetchone()["n"], "token_used_sum": conn.execute("SELECT coalesce(sum(used),0) n FROM token_usage").fetchone()["n"], "sealed": {"sealed": total.get("sealed", 0), "sealed_requests": total.get("sealed_requests"), "sealed_tokens": total.get("sealed_tokens"), "sealed_at": total.get("sealed_at")}, } def _queues(conn: sqlite3.Connection) -> dict: out = {} for name, sql in QUEUE_TABLES.items(): try: n = conn.execute(sql).fetchone()["n"] ids = [str(r[0]) for r in conn.execute(QUEUE_ID_SQL[name])] if n else [] out[name] = {"pending": n, "pending_ids": ids[:200]} # 只数量与ID,无内容 except sqlite3.OperationalError: out[name] = {"pending": None, "pending_ids": []} return out def preflight(db: Path) -> dict: conn = _ro(db) try: report = { "ok": True, "db": str(db), "db_sha256": _sha256(db), "identity": _identity(conn), "provenance": _counts(conn, SAME_HER_TABLES), "accounting": _accounting(conn), "queues": _queues(conn), } finally: conn.close() return report def _consistency_copy(src: Path, dst: Path) -> None: """SQLite backup API 一致性复制(含 WAL),不用裸文件拷贝。""" s = sqlite3.connect(f"file:{src}?mode=ro", uri=True) try: d = sqlite3.connect(str(dst)) try: s.backup(d) d.execute("PRAGMA wal_checkpoint(TRUNCATE)") finally: d.close() finally: s.close() def _dir_manifest(root: Path) -> dict: out = {} for p in sorted(root.rglob("*")): if p.is_file(): out[str(p.relative_to(root))] = _sha256(p) return out def _refuse(msg: str, **extra) -> None: raise SystemExit(json.dumps({"ok": False, **extra, "error": msg}, ensure_ascii=False)) def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict: pre = preflight(db) # 含空库/缺出生/缺诠释拒绝 src_sha = pre["db_sha256"] data = base / "data" data.mkdir(parents=True, exist_ok=True) tdb = data / "companion.db" cont = data / "continuation.json" # 活实例拒绝:迁移绝不能对运行中的实例动手。 for live in (base / "window-active", base / "logs" / "api.pid"): if live.exists(): _refuse(f"refused_live_instance:{live}", refused="live_instance") if cont.exists(): prev = json.loads(cont.read_text()) if prev.get("source", {}).get("db_sha256") == src_sha: return {"ok": True, "idempotent_noop": True, "migrated_at": prev["migrated_at"], "note": "同一源已迁移,安全 no-op"} _refuse("refused_different_source:目标已迁移自另一份档案,先 rollback 再迁移", refused="different_source", existing=prev.get("identity")) # 目标已有库(非本工具迁移产物)→ 一致性备份,供回退。 backup = None target_db_existed = tdb.exists() if target_db_existed: backups = base / "backups" backups.mkdir(parents=True, exist_ok=True) backup = backups / f"pre-migration-{int(time.time())}.db" _consistency_copy(tdb, backup) # 1) 一致性复制(源只读) _consistency_copy(db, tdb) # 2) 旧账冻结接线(只改副本):sealed* → cont_prior_sealed*;其余计数原样保留。 conn = sqlite3.connect(str(tdb)) try: conn.execute("BEGIN IMMEDIATE") for live_key, prior_key in PRIOR_KEY.items(): row = conn.execute("SELECT value FROM budget_total WHERE key=?", (live_key,)).fetchone() if row is not None: conn.execute("INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) " "DO UPDATE SET value=excluded.value", (prior_key, row[0])) conn.execute("DELETE FROM budget_total WHERE key=?", (live_key,)) now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat() # noqa: UP017 -- 本机 3.10 兼容,产品 3.11 同样支持 timezone.utc conn.execute("INSERT INTO budget_total VALUES('cont_scope',1) " "ON CONFLICT(key) DO UPDATE SET value=1") conn.execute("INSERT INTO budget_total VALUES('cont_source_sha256',?) " "ON CONFLICT(key) DO UPDATE SET value=excluded.value", (_int_or_hash(src_sha),)) conn.execute("INSERT INTO budget_total VALUES('cont_migrated_at',?) " "ON CONFLICT(key) DO UPDATE SET value=excluded.value", (int(time.time()),)) conn.commit() finally: conn.close() # 3) 向量/推导史等数据目录随实例迁移(可选;含逐文件哈希清单)。 copied_dirs = {} for src_dir, rel in data_dirs: s, d = Path(src_dir), data / rel if not s.is_dir(): _refuse(f"data_dir_missing:{s}", refused="data_dir_missing") if d.exists(): _refuse(f"data_dir_target_exists:{d}", refused="data_dir_target_exists") shutil.copytree(s, d) copied_dirs[rel] = _dir_manifest(d) record = { "ok": True, "scope": "hel919", "identity": pre["identity"], "provenance": pre["provenance"], "source": {"db": str(db), "db_sha256": src_sha, "accounting_frozen": pre["accounting"], "queues": pre["queues"]}, "target": {"base": str(base), "db": str(tdb), "target_db_existed_before": target_db_existed, "backup": str(backup) if backup else None, "data_dirs": copied_dirs}, "migrated_at": now_iso, "queue_policy": "不删队列、不静默禁用;未批准能力 cap=0 保持关闭;" "旧排队工作执行时计入新账,不执行则保留并在队列盘点中如实报告", } cont.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n") # 4) 自检:同一位她前后可核 + 旧账冻结 + 副本 live seal 已移除。 conn = _ro(tdb) try: post = {"identity": _identity(conn), "provenance": _counts(conn, SAME_HER_TABLES), "accounting": _accounting(conn), "queues": _queues(conn)} finally: conn.close() checks = { "same_her": post["identity"] == pre["identity"], "provenance_preserved": post["provenance"] == pre["provenance"], "old_counts_preserved": (post["accounting"]["token_usage_rows"] == pre["accounting"]["token_usage_rows"] and post["accounting"]["token_used_sum"] == pre["accounting"]["token_used_sum"] and post["accounting"]["request_usage_rows"] == pre["accounting"]["request_usage_rows"]), "totals_preserved": (post["accounting"]["budget_total"].get("total_requests") == pre["accounting"]["budget_total"].get("total_requests") and post["accounting"]["budget_total"].get("total_tokens") == pre["accounting"]["budget_total"].get("total_tokens")), "prior_seal_frozen": all( post["accounting"]["budget_total"].get(PRIOR_KEY[k]) == pre["accounting"]["budget_total"].get(k) for k in LIVE_SEALED_KEYS if k in pre["accounting"]["budget_total"]), "live_seal_removed": all(k not in post["accounting"]["budget_total"] for k in LIVE_SEALED_KEYS), "queues_preserved": post["queues"] == pre["queues"], } if not all(checks.values()): rollback(base) _refuse(f"selfcheck_failed:{[k for k, v in checks.items() if not v]}", refused="selfcheck") return {"ok": True, "record": record, "selfcheck": checks} def _int_or_hash(sha: str) -> int: """哈希以 63bit 整数落库(budget_total.value 是 INTEGER);全哈希留在 continuation.json。""" return int(sha[:15], 16) def rollback(base: Path) -> dict: data = base / "data" cont = data / "continuation.json" if not cont.exists(): _refuse("nothing_to_rollback: continuation.json 不存在", refused="no_continuation") rec = json.loads(cont.read_text()) tdb = data / "companion.db" existed = rec["target"].get("target_db_existed_before") backup = rec["target"].get("backup") if existed and backup: Path(backup).exists() or _refuse(f"backup_missing:{backup}", refused="backup_missing") _consistency_copy(Path(backup), tdb) note = "目标库已从迁移前一致性备份还原" else: tdb.exists() and tdb.unlink() note = "迁移前目标库不存在:迁移副本已删除(源库从未被写过)" for rel in rec["target"].get("data_dirs", {}): d = data / rel d.exists() and shutil.rmtree(d) cont.unlink() return {"ok": True, "rolled_back": note, "source_untouched": rec["source"]["db"]} def main() -> int: ap = argparse.ArgumentParser(description="HEL-919 同一位她接续迁移(离线)") sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("preflight") p.add_argument("--db", required=True, type=Path) m = sub.add_parser("migrate") m.add_argument("--db", required=True, type=Path) m.add_argument("--base", required=True, type=Path) m.add_argument("--data-dir", action="append", default=[], metavar="SRC=REL", help="随实例迁移的数据目录(如向量库/推导史),SRC=目标 data 下相对路径") r = sub.add_parser("rollback") r.add_argument("--base", required=True, type=Path) args = ap.parse_args() if args.cmd == "preflight": out = preflight(args.db) elif args.cmd == "migrate": dirs = [] for pair in args.data_dir: src, sep, rel = pair.partition("=") (src and sep and rel) or _refuse(f"bad_data_dir_spec:{pair}", refused="bad_spec") rel.startswith("/") or ".." not in Path(rel).parts or _refuse( f"bad_data_dir_rel:{rel}", refused="bad_spec") dirs.append((src, rel)) out = migrate(args.db, args.base, dirs) else: out = rollback(args.base) print(json.dumps(out, ensure_ascii=False, indent=1)) return 0 if __name__ == "__main__": raise SystemExit(main())