HEL-919 rework: old ledger verbatim in copy (no seal rename) + scoped budget keys; running-expiry drill evidence

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
施工员2号
2026-11-04 11:56:00 +08:00
co-authored by multica-agent
parent 9c3789af06
commit 99c5de1d60
12 changed files with 185 additions and 101 deletions
+11 -7
View File
@@ -13,12 +13,15 @@
- **产品基线(本卡起点,不回退、不合并、不改 PR 目标)**:
`agent/2/182d2402a8df` @ `2e91a3c91e90944991886b21f7167a6913f41efb`
(含 HEL-916 两轮返工 e74531c/2e91a3c、HEL-914 ffbc8c2)。
- **运行包提交**:基线之后只新增/修改 `deploy/hel919-continuation/`、
`tests/test_hel919_continuation.py`、`docs/requirements/handoff-HEL-919.json`
的追加提交;产品代码(src/web/config/tools)零改动:
- **运行包提交**:基线之后的追加提交。除本包文件外,产品代码只含**极小
scope 扩展**(`PersistentBudget` 可选 `scope` 参数 + app 读
`CYBERGRIL_BUDGET_SCOPE` + 封账工具 `--scope`;缺省 "" 时键名与语义与旧
完全一致,旧实例零影响),改动仅限:
`src/cybergril/life/model.py`、`src/cybergril/api/app.py`、
`tools/seal_budget_hel879.py`:
```bash
git merge-base --is-ancestor 2e91a3c91e90944991886b21f7167a6913f41efb HEAD && echo ok
git diff --stat 2e91a3c91e90944991886b21f7167a6913f41efb HEAD -- src web config tools # 必须为空
git diff --stat 2e91a3c91e90944991886b21f7167a6913f41efb HEAD -- src web config tools # 只有上述 3 个文件
```
- 需求基准 v1.12(`docs/requirements/`),检查见 `handoff-HEL-919.json`。
@@ -79,9 +82,10 @@ python3 deploy/hel919-continuation/migrate_same_her.py rollback --base /opt/cybe
- 空库/缺出生底色/缺出生诠释 → **拒绝**(不走新建人格,也不因已有档案拒绝);
- 同一位她前后可核:身份指纹、bazi/persona/记忆/聊天/生活/关系逐表计数相等;
- 旧账保留:源库文件与库内一切计数/封账标记迁移后逐项不变;副本内旧
`sealed*` 移入冻结出处键 `cont_prior_sealed*`(旧实例上的封账依旧生效——
那份库从未被写);token/request 历史行与总量计数原样保留,新用量在同一
副本继续累计,新旧天然可分;
`budget_total` 键(含 `sealed*`/`total_*`)**逐字保留——不改、不删、不改
名**,只新增 cont_scope/cont_source_sha256/cont_migrated_at 三个出处标记;
新用量与到期封账落在独立 `hel919:*` 键(PersistentBudget scope,见 §0),
与旧键零交叉,旧口径读者在副本上依旧被旧封账拒绝;
- 语义嵌入权威账**不复制**(queue_policy.md §3);
- 重复运行:同一源 = 安全 no-op;不同源 = 拒绝;`rollback` 精确还原。
@@ -114,6 +114,7 @@ start() {
export HF_HUB_OFFLINE=1
export TRANSFORMERS_OFFLINE=1
export CYBERGRIL_MODELS=$BASE/etc/models.yaml
export CYBERGRIL_BUDGET_SCOPE=${HEL919_SCOPE:-hel919} # 新账独立 budget_total 键;旧键逐字保留
export CYBERGRIL_VOICE_CONFIG=$BASE/etc/voice.yaml
export CYBERGRIL_WEB=$CODE/web/dist
export PYTHONPATH=$CODE/src
@@ -164,6 +165,7 @@ close() {
stop || rc=1
if [ -f "$BASE/data/companion.db" ]; then
"$PY" "$CODE/tools/seal_budget_hel879.py" --db "$BASE/data/companion.db" \
--scope "${HEL919_SCOPE:-hel919}" \
--reason "hel919 continuation window closed" >> "$BASE/logs/close.log" 2>&1 || rc=1
fi
"$PY" - "$BASE/window.json" "$rc" <<'EOF'
+1 -1
View File
@@ -7,7 +7,7 @@
"commit": "2e91a3c91e90944991886b21f7167a6913f41efb",
"includes": ["e74531cf98540dd35198753fa8db87ac75d57a94", "ffbc8c24963c23b0ce108d4f7563871568825936"]
},
"package_rule": "基线之后只新增 deploy/hel919-continuation/、tests/test_hel919_continuation.py、docs/requirements/handoff-HEL-919.json;src/web/config/tools 零改动",
"package_rule": "基线之后新增 deploy/hel919-continuation/、tests/test_hel919_continuation.py、docs/requirements/handoff-HEL-919.json;产品代码仅极小 scope 扩展:src/cybergril/life/model.py(PersistentBudget 可选 scope,缺省 ''=旧键旧语义)、src/cybergril/api/app.py(读 CYBERGRIL_BUDGET_SCOPE)、tools/seal_budget_hel879.py(--scope);其余 src/web/config/tools 零改动",
"files": [
"README.md", "manifest.json", "migrate_same_her.py", "instance_ctl.sh",
"window_guard_hel919.py", "models.template.yaml", "semantic.template.yaml",
+12 -24
View File
@@ -79,15 +79,6 @@ QUEUE_ID_SQL: dict[str, str] = {
"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))
@@ -243,16 +234,14 @@ def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
_consistency_copy(tdb, backup)
# 1) 一致性复制(源只读)
_consistency_copy(db, tdb)
# 2) 旧账冻结接线(只改副本):sealed* → cont_prior_sealed*;其余计数原样保留。
# 2) 旧账逐字保留 + 接续出处标记(只新增 cont_* 三键,不改/不删任何旧键,
# 包括 sealed/sealed_*:旧封账在副本上依旧原样、对旧口径读者仍生效)。
# 新授权范围不在旧键上续写:接续实例以 CYBERGRIL_BUDGET_SCOPE=hel919:
# 运行,新计数/新封账落在独立的 hel919:* budget_total 键(产品代码
# PersistentBudget 的 scope 参数,缺省 "" = 旧实例原键原语义不变)。
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")
@@ -294,20 +283,19 @@ def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
"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"]),
"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),
"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()):
@@ -2,7 +2,7 @@
#
# 与 HEL-913 模板同构(tiers/routing/语音段一致),差异只在预算注释:
# 这是「同一位她」的接续实例——库内旧计数已随迁移保留并在账内冻结出处
# (cont_prior_*,见 migrate_same_her.py),本文件的预算值就是**新授权范围**:
# 逐字保留、新账走独立 hel919:* scope 键,见 migrate_same_her.py),本文件的预算值就是**新授权范围**:
# 未批准一律 0(发送前拒绝,fail-closed);获批后由总管按 enablement-plan.md
# 写入,进程重启不重置(PersistentBudget 库内持久计数)。
#
+39 -4
View File
@@ -114,11 +114,11 @@ python3 - "$BASE/data/companion.db" <<'EOF'
import sqlite3, sys, json
c = sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True)
t = {r[0]: r[1] for r in c.execute("SELECT key,value FROM budget_total")}
assert t.get("sealed") == 1, t
assert "cont_prior_sealed" in t, t
print(json.dumps({"ok": True, "sealed": t["sealed"], "prior": t["cont_prior_sealed"]}))
assert t.get("sealed") == 1, t # 旧键逐字保留(源库封账原样)
assert t.get("hel919:sealed") == 1, t # close 只封新 scope
print(json.dumps({"ok": True, "old_sealed": t["sealed"], "new_scope_sealed": t["hel919:sealed"]}))
EOF
[ $? -eq 0 ] && ok "close sealed THIS instance db (prior seal frozen intact)" || bad "close seal state wrong"
[ $? -eq 0 ] && ok "close sealed NEW scope only; old ledger verbatim" || bad "close seal state wrong"
python3 - "$BASE/window.json" <<'EOF'
import json, sys
w = json.load(open(sys.argv[1]))
@@ -131,6 +131,41 @@ env $ENV bash "$CTL" close >/dev/null 2>&1; expect_rc 0 $? "close idempotent"
env $ENV HEL919_VENV=$STUB HEL919_CERT=$TMP/c.pem HEL919_KEY=$TMP/c.key \
bash "$CTL" start >/dev/null 2>&1; expect_rc 1 $? "start refused after close (window-active removed)"
# ---- S8. 运行中到期:watch 到点对活实例收尾(直接证据) ----
# 重建有效窗口并启动一个"自有句柄"活进程,watch 一个已到/将至的 deadline
python3 - "$BASE/data/companion.db" <<'EOF'
import sqlite3, sys
c = sqlite3.connect(sys.argv[1])
with c:
for k in ("hel919:sealed", "hel919:sealed_requests", "hel919:sealed_tokens", "hel919:sealed_at"):
c.execute("DELETE FROM budget_total WHERE key=?", (k,)) # 重置 S6 的新账封账,模拟窗口内运行
c.close()
EOF
mkwin 1 $(( $(date +%s) - 5 )) # 窗口已到期(deadline 持久在 window.json)
pushd "$CODE" >/dev/null
"$STUB" serve_dual_8360_8361.py --http-port 1 >/dev/null 2>&1 &
RUN=$!
popd >/dev/null
sleep 0.3
echo "$RUN" > "$BASE/logs/api.pid"
kill -0 "$RUN" 2>/dev/null && ok "running instance alive before deadline" || bad "running instance not alive"
NOW=$(date +%s)
env $ENV HEL919_DRAIN_SEC=5 bash "$CTL" watch $NOW >/dev/null 2>&1; expect_rc 0 $? "watch closed expired running instance"
kill -0 "$RUN" 2>/dev/null && bad "expired running instance still alive (new egress not stopped)" || ok "expired running instance stopped (no further egress possible)"
[ ! -f "$BASE/logs/api.pid" ] && ok "watch removed pid file" || bad "watch left pid file"
[ ! -f "$BASE/window-active" ] && ok "watch removed window-active" || bad "watch left window-active"
python3 - "$BASE/data/companion.db" <<'EOF'
import json, sqlite3, sys
c = sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True)
t = {r[0]: r[1] for r in c.execute("SELECT key,value FROM budget_total")}
c.close()
assert t.get("hel919:sealed") == 1, t
assert t.get("sealed") == 1 and t.get("cont_prior_sealed") is None, t # 旧键原样;无改名残留
print(json.dumps({"ok": True}))
EOF
[ $? -eq 0 ] && ok "expiry sealed NEW scope only; old keys verbatim (no rename)" || bad "expiry seal state wrong"
env $ENV bash "$CTL" start >/dev/null 2>&1; expect_rc 1 $? "restart after expiry refused (deadline persisted)"
echo "----"
echo "PASS=$PASS FAIL=$FAIL"
[ "$FAIL" -eq 0 ]