447 lines
21 KiB
Python
447 lines
21 KiB
Python
#!/usr/bin/env python3
|
||
"""HEL-919 · 「同一位她」接续迁移工具(离线、零真实调用、零网络)。
|
||
|
||
把一份**已有非空档案**(同一位她的库)迁移进本卡专属新实例的隔离资料空间,
|
||
证明:非空档案、出生事实/诠释、姓名、习惯、关系、聊天、生活、记忆出处及
|
||
向量数据目录可以接续——不走新建人格,也不因已有档案拒绝(旧
|
||
deploy/hel914-user/activate.sh 只接受空库,这是它不能续用的原因)。
|
||
|
||
三条铁律:
|
||
1. **源库只读**。一律以 `mode=ro` 打开,任何路径都不写源库;旧封账、旧
|
||
计数、冻结值、旧失败记录原样保留在源库,迁移后逐项核对不变。
|
||
2. **旧账冻结、新账隔离**。旧 sealed*/total_* 原键原值保留,
|
||
新用量由 PersistentBudget 的 hel919 scope 单独记账。
|
||
语义嵌入权威账(embed_ops)
|
||
**不复制**:它仍是唯一权威账文件,经 semantic.template.yaml 的累计上限
|
||
算式续账(见 README §语义账)。
|
||
3. **幂等与回退**。同一源重复迁移 = 安全 no-op;不同源拒绝;迁移前目标库
|
||
如已存在先做一致性备份。回退发现任何迁移后变化默认拒绝;--force 也须
|
||
先一致性归档数据库与资料目录并核验成功,才允许回退。
|
||
|
||
队列盘点只输出**数量与待处理 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 tempfile
|
||
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')",
|
||
}
|
||
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 _data_path(data: Path, rel: str) -> Path:
|
||
path = Path(rel)
|
||
if not rel or path.is_absolute() or ".." in path.parts or path == Path("."):
|
||
_refuse("invalid_data_directory", refused="bad_spec")
|
||
target = data / path
|
||
try:
|
||
target.resolve().relative_to(data.resolve())
|
||
except ValueError:
|
||
_refuse("data_directory_outside_instance", refused="bad_spec")
|
||
return target
|
||
|
||
|
||
def _data_snapshot(data: Path) -> dict:
|
||
"""Logical database + file hashes; detects updates as well as new rows.
|
||
|
||
Raw SQLite file hashes miss WAL changes and change on harmless checkpoints.
|
||
Only digests are recorded; no private row contents enter the report.
|
||
"""
|
||
conn = _ro(data / "companion.db")
|
||
try:
|
||
digest = hashlib.sha256()
|
||
for line in conn.iterdump():
|
||
digest.update(line.encode("utf-8"))
|
||
digest.update(b"\n")
|
||
finally:
|
||
conn.close()
|
||
files = {}
|
||
for path in sorted(data.rglob("*")):
|
||
if path.is_symlink():
|
||
_refuse("symlink_in_data: preserve manually before rollback", refused="unsafe_data")
|
||
rel = str(path.relative_to(data))
|
||
if rel in {"companion.db", "companion.db-wal", "companion.db-shm", "continuation.json"}:
|
||
continue
|
||
if path.is_file():
|
||
files[rel] = _sha256(path)
|
||
return {"database": digest.hexdigest(), "files": files}
|
||
|
||
|
||
def _archive_before_rollback(base: Path, expected: dict) -> Path:
|
||
"""Archive first, verify both copies, and leave source intact on any error."""
|
||
backups = base / "backups"
|
||
backups.mkdir(parents=True, exist_ok=True)
|
||
archive = Path(tempfile.mkdtemp(prefix=f"rollback-{int(time.time())}-", dir=backups))
|
||
data = base / "data"
|
||
saved = archive / "data"
|
||
try:
|
||
saved.mkdir()
|
||
_consistency_copy(data / "companion.db", saved / "companion.db")
|
||
for path in data.iterdir():
|
||
if path.name in {"companion.db", "companion.db-wal", "companion.db-shm"}:
|
||
continue
|
||
if path.is_dir():
|
||
shutil.copytree(path, saved / path.name)
|
||
else:
|
||
shutil.copy2(path, saved / path.name)
|
||
if _data_snapshot(saved) != expected or _data_snapshot(data) != expected:
|
||
_refuse("rollback_archive_verification_failed", refused="archive_failed",
|
||
partial_archive=str(archive))
|
||
(archive / "manifest.json").write_text(json.dumps(
|
||
{"complete": True, "snapshot": expected, "files": _dir_manifest(saved)},
|
||
ensure_ascii=False, indent=2) + "\n")
|
||
except (OSError, sqlite3.Error) as exc:
|
||
_refuse(f"rollback_archive_failed:{type(exc).__name__}", refused="archive_failed",
|
||
partial_archive=str(archive))
|
||
return archive
|
||
|
||
|
||
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) 旧账逐字保留 + 接续出处标记(只新增 cont_* 三键,不改/不删任何旧键,
|
||
# 包括 sealed/sealed_*:旧封账在副本上依旧原样、对旧口径读者仍生效)。
|
||
# 新授权范围不在旧键上续写:接续实例以 CYBERGRIL_BUDGET_SCOPE=hel919:
|
||
# 运行,新计数/新封账落在独立的 hel919:* budget_total 键(产品代码
|
||
# PersistentBudget 的 scope 参数,缺省 "" = 旧实例原键原语义不变)。
|
||
conn = sqlite3.connect(str(tdb))
|
||
try:
|
||
conn.execute("BEGIN IMMEDIATE")
|
||
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_path(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 保持关闭;"
|
||
"旧排队工作执行时计入新账,不执行则保留并在队列盘点中如实报告",
|
||
"rollback_snapshot": _data_snapshot(data),
|
||
}
|
||
cont.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n")
|
||
# 4) 自检:同一位她前后可核,旧账和旧封账逐字保留。
|
||
conn = _ro(tdb)
|
||
try:
|
||
post = {"identity": _identity(conn), "provenance": _counts(conn, SAME_HER_TABLES),
|
||
"accounting": _accounting(conn), "queues": _queues(conn)}
|
||
finally:
|
||
conn.close()
|
||
cont_added = {"cont_scope", "cont_source_sha256", "cont_migrated_at"}
|
||
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"]),
|
||
"old_ledger_verbatim": (
|
||
# 副本 budget_total 与源完全一致,仅允许新增 cont_* 三键;
|
||
# 旧键(含 sealed/sealed_*/total_*)一个不改、一个不删、不改名。
|
||
{k: v for k, v in post["accounting"]["budget_total"].items() if k not in cont_added}
|
||
== pre["accounting"]["budget_total"]),
|
||
"cont_markers_added": cont_added <= set(post["accounting"]["budget_total"]),
|
||
"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, *, force: bool = False) -> dict:
|
||
data = base / "data"
|
||
cont = data / "continuation.json"
|
||
if not cont.exists():
|
||
_refuse("nothing_to_rollback: continuation.json 不存在", refused="no_continuation")
|
||
for live in (base / "window-active", base / "logs" / "api.pid"):
|
||
if live.exists():
|
||
_refuse("refused_live_instance", refused="live_instance")
|
||
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 (not backup or not Path(backup).is_file()):
|
||
_refuse("pre_migration_backup_missing", refused="backup_missing")
|
||
# Validate every deletion target before touching the database or directories.
|
||
dirs = [_data_path(data, rel) for rel in rec["target"].get("data_dirs", {})]
|
||
current = _data_snapshot(data)
|
||
changed = current != rec.get("rollback_snapshot")
|
||
if changed and not force:
|
||
_refuse("post_migration_data_changed: use --force only after reviewing preservation",
|
||
refused="new_data")
|
||
archive = _archive_before_rollback(base, current) if force else None
|
||
if existed and backup:
|
||
_consistency_copy(Path(backup), tdb)
|
||
note = "目标库已从迁移前一致性备份还原"
|
||
else:
|
||
for name in ("companion.db", "companion.db-wal", "companion.db-shm"):
|
||
(data / name).unlink(missing_ok=True)
|
||
note = "迁移前目标库不存在:迁移副本已删除(源库从未被写过)"
|
||
for d in dirs:
|
||
d.exists() and shutil.rmtree(d)
|
||
cont.unlink()
|
||
return {"ok": True, "rolled_back": note, "source_untouched": rec["source"]["db"],
|
||
"preserved_archive": str(archive) if archive else None}
|
||
|
||
|
||
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)
|
||
r.add_argument("--force", action="store_true", help="先一致性归档并核验后,再回退变化过的副本")
|
||
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")
|
||
_data_path(args.base / "data", rel)
|
||
dirs.append((src, rel))
|
||
out = migrate(args.db, args.base, dirs)
|
||
else:
|
||
out = rollback(args.base, force=args.force)
|
||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|