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 ]
+23 -8
View File
@@ -3,17 +3,32 @@
"read_commit": "2e91a3c91e90944991886b21f7167a6913f41efb",
"task": "HEL-919 补齐同一位她继续体验的启停接续包(HEL-915 工程收口)",
"requirement_ids": [
"CG-006", "CG-008", "CG-009", "CG-011", "CG-013", "CG-014", "CG-015", "CG-016", "CG-021",
"AM-001", "AM-002", "AM-003",
"GOV-001", "GOV-002", "GOV-003", "GOV-004", "GOV-005", "GOV-006",
"CG-006",
"CG-008",
"CG-009",
"CG-011",
"CG-013",
"CG-014",
"CG-015",
"CG-016",
"CG-021",
"AM-001",
"AM-002",
"AM-003",
"GOV-001",
"GOV-002",
"GOV-003",
"GOV-004",
"GOV-005",
"GOV-006",
"DEL-001"
],
"deliverable": "deploy/hel919-continuation/ 接续运行包(基线 2e91a3c 之后仅新增本目录 + tests/test_hel919_continuation.py + 本 handoff,src/web/config/tools 零改动):1) migrate_same_her.py 同一位她迁移(preflight/migrate/rollback)——源库只读(mode=ro + SQLite backup API),拒绝空档案/缺出生/缺诠释,不因已有档案拒绝;身份指纹(companion+bazi_core+persona_interp)与逐表出处计数(bazi/persona/记忆/聊天/生活/关系)前后核对相等;向量/推导史目录 --data-dir 随实例复制含逐文件哈希;同一源幂等 no-op、不同源拒绝、迁移前目标库一致性备份、rollback 精确还原、自检不过自动回退;对活实例(window-active/api.pid)拒绝迁移。2) 旧账保留+新账隔离:源库逐字节不变;副本内旧 sealed* 移入冻结出处键 cont_prior_sealed*(源库旧封账仍生效),token_usage/request_usage 历史行与 total_requests/total_tokens 计数原样保留,新用量由既有 PersistentBudget 零改动在同一副本继续累计(新旧可分、重启不重置);close 用既有 tools/seal_budget_hel879.py 只封本实例新账;语义嵌入权威账不复制,semantic.template.yaml 按既有累计算式续唯一权威账(冻结余额/authority 前缀保留,42提取/111嵌入类历史余额不可借)。3) queue_policy.md 背景工作盘点(原文压缩/聊天情绪分类/分享判断/生活/成长/persona/mem_job/SDK提取嵌入/主动联系 → 实际表与预算类别)与接续政策:不删队列、不静默禁用,未批准 cap=0 显式关闭,执行计入新账,不执行保留说明,chat_affect_cutoff 历史切断点不重算;盘点只含 pending 数量与 ID。4) instance_ctl.sh 唯一入口 check/start/stop/close/status/watch + window_guard_hel919.py:默认关闭(无 window-active 或预算全 0 一律 fail-closed,check 拒绝未批非零预算);启动需 approved window.json,过期拒绝、到期 watch/timer 只 close 本实例;stop 只杀身份核验(cmdline+cwd 双验,PID 复用不动手)的本实例 pid,有界排空 HEL919_DRAIN_SEC(默认30s),绝不调用旧 force_end/worker/bridge/tts,不触碰 8300/8310/8320/8350、7880/8081、9880/8090;重复 start 拒绝;close 幂等并记 closed_at/close.log。5) enablement-plan.md 给总管的启用安排:文字/生活/情绪小范围,谁准备(施工员2号离线)/谁操作(总管唯一入口)/白栖知何时参与(体验阶段)与观察点(记得吗/生活连续/情绪连贯/边界承接/失败表现)、≤72h 窗口 + 原有共池上限直接复用(daily_tokens + 四类 daily_requests 合计口径,建议起步值列明、总管可按首日读数调整)、失败停止与资料保留(新聊天记忆保留、不自动覆盖原实例、rollback 只回退副本);无人民币金额、不承诺固定每轮成本、不把历史全类别合计当每轮口径。本轮取消费用前置依据:白栖知 HEL-915 评论 01a1a482-1338-719d-8acd-9df70355e95c 原话,属操作裁定、非需求变更。",
"deliverable": "deploy/hel919-continuation/ 接续运行包(基线 2e91a3c 之后新增本目录 + tests/test_hel919_continuation.py + 本 handoff;产品代码仅极小 scope 扩展:PersistentBudget 可选 scope 参数(缺省 \"\"=旧键旧语义,旧实例零影响)、app 读 CYBERGRIL_BUDGET_SCOPE、seal_budget_hel879.py --scope,共 3 文件,其余零改动):1) migrate_same_her.py 同一位她迁移(preflight/migrate/rollback)——源库只读(mode=ro + SQLite backup API),拒绝空档案/缺出生/缺诠释,不因已有档案拒绝;身份指纹(companion+bazi_core+persona_interp)与逐表出处计数(bazi/persona/记忆/聊天/生活/关系)前后核对相等;向量/推导史目录 --data-dir 随实例复制含逐文件哈希;同一源幂等 no-op、不同源拒绝、迁移前目标库一致性备份、rollback 精确还原、自检不过自动回退;对活实例(window-active/api.pid)拒绝迁移。2) 旧账保留+新账隔离(总管复核返工后口径):源库逐字节不变;副本内旧 budget_total 键(含 sealed*/total_*)逐字保留——不改、不删、不改名,只新增 cont_scope/cont_source_sha256/cont_migrated_at 三个出处标记;接续实例以 CYBERGRIL_BUDGET_SCOPE=hel919 运行,新用量计数与到期封账全部落在独立 hel919:* budget_total 键(PersistentBudget scope 扩展),与旧键零交叉,旧口径读者在源库与副本上都依旧被旧封账拒绝;重启不重置(scope 计数持久在库);close 用 tools/seal_budget_hel879.py --scope hel919 只封新账;语义嵌入权威账不复制,semantic.template.yaml 按既有累计算式续唯一权威账(冻结余额/authority 前缀保留,42提取/111嵌入类历史余额不可借)。3) queue_policy.md 背景工作盘点(原文压缩/聊天情绪分类/分享判断/生活/成长/persona/mem_job/SDK提取嵌入/主动联系 → 实际表与预算类别)与接续政策:不删队列、不静默禁用,未批准 cap=0 显式关闭,执行计入新账,不执行保留说明,chat_affect_cutoff 历史切断点不重算;盘点只含 pending 数量与 ID。4) instance_ctl.sh 唯一入口 check/start/stop/close/status/watch + window_guard_hel919.py:默认关闭(无 window-active 或预算全 0 一律 fail-closed,check 拒绝未批非零预算);启动需 approved window.json,过期拒绝、到期 watch/timer 只 close 本实例;stop 只杀身份核验(cmdline+cwd 双验,PID 复用不动手)的本实例 pid,有界排空 HEL919_DRAIN_SEC(默认30s),绝不调用旧 force_end/worker/bridge/tts,不触碰 8300/8310/8320/8350、7880/8081、9880/8090;重复 start 拒绝;close 幂等并记 closed_at/close.log。5) enablement-plan.md 给总管的启用安排:文字/生活/情绪小范围,谁准备(施工员2号离线)/谁操作(总管唯一入口)/白栖知何时参与(体验阶段)与观察点(记得吗/生活连续/情绪连贯/边界承接/失败表现)、≤72h 窗口 + 原有共池上限直接复用(daily_tokens + 四类 daily_requests 合计口径,建议起步值列明、总管可按首日读数调整)、失败停止与资料保留(新聊天记忆保留、不自动覆盖原实例、rollback 只回退副本);无人民币金额、不承诺固定每轮成本、不把历史全类别合计当每轮口径。本轮取消费用前置依据:白栖知 HEL-915 评论 01a1a482-1338-719d-8acd-9df70355e95c 原话,属操作裁定、非需求变更。",
"acceptance": [
"tests/test_hel919_continuation.py 12/12 通过(隔离合成旧档案+替身,零真实调用/零网络):空档案/缺出生/缺诠释拒绝;同一位她身份指纹与逐表计数前后相等;源库逐字节不变、副本 live seal 移入 cont_prior_sealed*、旧计数与新计数(1→2→3,含 settle 修正)同库可分;进程重开(重启等价)计数不重置;源库旧 seal 仍拒绝一切 acquire;幂等 no-op/不同源拒绝/回退精确还原(含迁移前已存在目标库的备份还原与目标不存在时删副本);window_guard 默认关闭/过期/未批准/错实例/损坏 JSON 全拒绝、有效窗口放行;队列盘点 JSON 不含任何聊天/生活/诠释文本;CLI 通路 preflight/migrate/rollback rc 与 JSON 输出正确",
"bash deploy/hel919-continuation/test_ctl_scripts.sh 34/34 通过(stub 替身,零真实服务/端口/出站):包文件齐全与语法;未批非零预算 check 拒绝、显式 HEL919_ALLOW_BUDGET=1 放行;非法子命令 rc=2;无窗口/过期窗口 start 拒绝且不留 pid;失败启动只清自己留日志;stop 杀身份核验过的自有 pid、外来活 pid 拒绝动手且不受影响;close 只封本实例库(sealed=1 且 cont_prior_sealed 保留)、window.json 记 closed_at、幂等、封窗后 start 拒绝",
"tests/test_hel919_continuation.py 12/12 通过(隔离合成旧档案+替身,零真实调用/零网络):空档案/缺出生/缺诠释拒绝;同一位她身份指纹与逐表计数前后相等;源库逐字节不变、副本 budget_total 与源逐键相等仅新增 cont_* 三键(旧封账 sealed=1 原样保留)、token/request 历史行原样;旧口径(scope=\"\")在源库与迁移副本上都仍被旧封账拒绝(旧账未被绕过);新 scope 计数独立(hel919:total_* 键)、settle 修正、进程重开不重置;新账封账只写 hel919:sealed* 且旧键 untouched;幂等 no-op/不同源拒绝/回退精确还原(含迁移前已存在目标库的备份还原与目标不存在时删副本);window_guard 默认关闭/过期/未批准/错实例/损坏 JSON 全拒绝、有效窗口放行;队列盘点 JSON 不含任何聊天/生活/诠释文本;CLI 通路 preflight/migrate/rollback rc 与 JSON 输出正确",
"bash deploy/hel919-continuation/test_ctl_scripts.sh 41/41 通过(stub 替身,零真实服务/端口/出站):包文件齐全与语法;未批非零预算 check 拒绝、显式 HEL919_ALLOW_BUDGET=1 放行;非法子命令 rc=2;无窗口/过期窗口 start 拒绝且不留 pid;失败启动只清自己留日志;stop 杀身份核验过的自有 pid、外来活 pid 拒绝动手且不受影响;close 只封本实例新 scope(hel919:sealed=1,旧 sealed 原样)、window.json 记 closed_at、幂等、封窗后 start 拒绝;S8 运行中到期直接证据:活的自有句柄进程在 watch 到点后被 close 停止(进程确认死亡=不再可能有新出站)、pid/window-active 移除、新 scope 封账、重启被拒",
"python3 -m ruff check deploy/hel919-continuation tests/test_hel919_continuation.py 通过(0 错误)",
"受影响面核对:产品代码零改动(git diff 2e91a3c..HEAD -- src web config tools 为空);tests/test_hel916.py 16/16、tests/test_store.py 8/8 复测通过;实跑记录 docs/rework/hel919/offline-run.txt",
"受影响面核对:产品代码改动仅 scope 扩展 3 文件(life/model.py、api/app.py、seal_budget_hel879.py,缺省语义与旧完全一致);tests/test_hel916.py 16/16、test_hard_gates_hel882 + test_rework_hel885/886/889/894 + test_store 共 70/70 复测通过;实跑记录 docs/rework/hel919/offline-run.txt",
"双基线需求检查通过:--base-ref origin/main 与 --base-ref 2e91a3c91e90944991886b21f7167a6913f41efb 各含本 handoff"
],
"deferred": [
@@ -24,7 +39,7 @@
],
"requirement_changes": [],
"verification": [
"离线证据:docs/rework/hel919/offline-run.txt(pytest 12/12 + 启停替身 34/34 实跑输出);ruff 0 错误;双基线 check_requirements 通过",
"离线证据:docs/rework/hel919/offline-run.txt(pytest 12/12 + 启停替身 41/41 实跑输出,含 S8 运行中到期收尾直接证据);ruff 0 错误;双基线 check_requirements 通过",
"迁移自检内建:同一份 JSON 里给出 same_her/provenance_preserved/old_counts_preserved/totals_preserved/prior_seal_frozen/live_seal_removed/queues_preserved 七项布尔,任一 False 自动回退并拒绝",
"边界:全部测试用隔离合成档案('测试她/替身她'),未读、未复制、未写任何真实用户资料;未调用 LLM/ASR/TTS/嵌入;未建 window/房间;未恢复任何停机服务;未安装依赖",
"未测到:真实部署布局在 .12 上的实际落盘、systemd timer 实际触发、真实 provider 出站、浏览器端到端、Safari/手机、多日运行;均如实未验证,留待获批启用窗口由总管执行并记录"
+15 -4
View File
@@ -1,5 +1,8 @@
............ [100%]
12 passed in 0.41s
12 passed in 0.45s
---- budget-affected suites ----
.......................................................... [100%]
58 passed in 3.24s
---- ctl drill ----
PASS syntax instance_ctl.sh
PASS package file README.md
@@ -31,10 +34,18 @@ PASS own pid stopped
PASS stop refuses non-own live pid
PASS foreign pid untouched
PASS close ok (no running api)
{"ok": true, "sealed": 1, "prior": 1}
PASS close sealed THIS instance db (prior seal frozen intact)
{"ok": true, "old_sealed": 1, "new_scope_sealed": 1}
PASS close sealed NEW scope only; old ledger verbatim
PASS window.json records closed_at
PASS close idempotent
PASS start refused after close (window-active removed)
PASS running instance alive before deadline
PASS watch closed expired running instance
PASS expired running instance stopped (no further egress possible)
PASS watch removed pid file
PASS watch removed window-active
{"ok": true}
PASS expiry sealed NEW scope only; old keys verbatim (no rename)
PASS restart after expiry refused (deadline persisted)
----
PASS=34 FAIL=0
PASS=41 FAIL=0
+5 -1
View File
@@ -232,7 +232,11 @@ def create_app(
app.state.chat_lock = asyncio.Lock()
app.state.health_cache = (0, False)
app.state.health_lock = asyncio.Lock()
router.guard = PersistentBudget(store, router.guard)
# HEL-919 continuation instances count (and later seal) their new
# authorization under a separate budget_total scope; "" keeps the
# exact legacy keys for every existing instance.
router.guard = PersistentBudget(
store, router.guard, scope=os.getenv("CYBERGRIL_BUDGET_SCOPE", ""))
app.state.sharing = Sharing(store, router, models)
app.state.persona = Persona(store, router, models, enabled=life_config.enabled)
app.state.public = PublicView(store)
+37 -26
View File
@@ -18,11 +18,22 @@ class PersistentBudget(BudgetGuard):
reservations persist beside token_usage in the product store — every real
provider exit reserves atomically before the call, restart never resets,
concurrency never overshoots (single ``BEGIN IMMEDIATE``).
HEL-919 scope: ``scope="<name>:"`` moves ONLY the ``budget_total`` keys
(sealed/sealed_*/total_requests/total_tokens) to ``<name>:…``. Default ""
keeps the exact legacy keys, so every existing instance is untouched. A
continuation instance runs with its own scope: the migrated copy keeps the
old ledger verbatim (old seal still enforced for legacy readers) while the
new authorization counts — and is later sealed — under its own keys.
Daily token_usage/request_usage rows stay shared history; on the migration
day itself old same-day rows count toward the new caps (conservative, never
more generous).
"""
def __init__(self, store, previous):
def __init__(self, store, previous, scope: str = ""):
super().__init__(previous.config)
self.store = store
self._k = (lambda key: f"{scope}:{key}") if scope else (lambda key: key)
# Persisted rows already include previous usage when reusing an injected router.
if not isinstance(previous, PersistentBudget):
for scene, used in previous.state.by_scene.items():
@@ -52,13 +63,15 @@ class PersistentBudget(BudgetGuard):
def total_requests_used(self):
row = self.store.query_one(
"SELECT coalesce((SELECT value FROM budget_total WHERE key='total_requests'),0) v"
"SELECT coalesce((SELECT value FROM budget_total WHERE key=?),0) v",
(self._k("total_requests"),),
)
return row["v"] if row else 0
def total_tokens_used(self):
row = self.store.query_one(
"SELECT coalesce((SELECT value FROM budget_total WHERE key='total_tokens'),0) v"
"SELECT coalesce((SELECT value FROM budget_total WHERE key=?),0) v",
(self._k("total_tokens"),),
)
return row["v"] if row else 0
@@ -66,11 +79,13 @@ class PersistentBudget(BudgetGuard):
def sealed(self):
"""封账标记(None=未封)。体验链提前走完时的可执行关闭,跨重启/归档不失效。"""
row = self.store.query_one("SELECT value v FROM budget_total WHERE key='sealed'")
row = self.store.query_one(
"SELECT value v FROM budget_total WHERE key=?", (self._k("sealed"),))
if not row or row["v"] != 1:
return None
def _val(key, default=0):
r = self.store.query_one(f"SELECT value v FROM budget_total WHERE key='{key}'")
r = self.store.query_one(
"SELECT value v FROM budget_total WHERE key=?", (self._k(key),))
return r["v"] if r else default
return {"requests": _val("sealed_requests"), "tokens": _val("sealed_tokens"),
"sealed_at": _val("sealed_at")}
@@ -93,17 +108,13 @@ class PersistentBudget(BudgetGuard):
marker = {"requests": self.total_requests_used(),
"tokens": self.total_tokens_used(),
"sealed_at": int(time.time())}
self.store.execute("INSERT INTO budget_total VALUES('sealed',1) "
"ON CONFLICT(key) DO UPDATE SET value=1")
self.store.execute("INSERT INTO budget_total VALUES('sealed_requests',?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(marker["requests"],))
self.store.execute("INSERT INTO budget_total VALUES('sealed_tokens',?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(marker["tokens"],))
self.store.execute("INSERT INTO budget_total VALUES('sealed_at',?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(marker["sealed_at"],))
for key, value in (("sealed", 1), ("sealed_requests", marker["requests"]),
("sealed_tokens", marker["tokens"]),
("sealed_at", marker["sealed_at"])):
self.store.execute(
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(self._k(key), value),
)
return marker
def reserve(self, tokens, scene):
@@ -171,12 +182,12 @@ class PersistentBudget(BudgetGuard):
(day, category, requests),
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_requests',?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (requests,)
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (self._k("total_requests"), requests)
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_tokens',?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (tokens,)
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (self._k("total_tokens"), tokens)
)
return BudgetHold(scene=scene, category=category,
reserved_tokens=tokens, requests=requests, day=day)
@@ -203,8 +214,8 @@ class PersistentBudget(BudgetGuard):
(hold.day, hold.scene, delta),
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_tokens',?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (delta,)
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (self._k("total_tokens"), delta)
)
def release(self, hold):
@@ -230,12 +241,12 @@ class PersistentBudget(BudgetGuard):
(hold.day, hold.category, -hold.requests),
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_requests',?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (-hold.requests,)
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (self._k("total_requests"), -hold.requests)
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_tokens',?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (-hold.reserved_tokens,)
"INSERT INTO budget_total VALUES(?,?) ON CONFLICT(key) DO UPDATE "
"SET value=value+excluded.value", (self._k("total_tokens"), -hold.reserved_tokens)
)
+37 -24
View File
@@ -165,10 +165,16 @@ def test_migrate_preserves_same_her_and_freezes_old_ledger(synth, tmp_path):
assert conn.execute("SELECT count(*) n FROM mem_episodic").fetchone()["n"] == 1
total = {r["key"]: r["value"] for r in conn.execute("SELECT * FROM budget_total")}
conn.close()
# 旧账冻结:live seal 移入 cont_prior_*,历史用量与总量保留
assert "sealed" not in total and "cont_prior_sealed" in total
assert total["cont_prior_sealed"] == 1
assert total["cont_prior_sealed_requests"] == 1 # 迁移前真实用量 1 次
# 旧账逐字保留:旧键(含 sealed/sealed_*)一个不改、不删、不改名,
# 只新增 cont_scope/cont_source_sha256/cont_migrated_at 三个出处标记
cont_added = {"cont_scope", "cont_source_sha256", "cont_migrated_at"}
sconn = sqlite3.connect(f"file:{src}?mode=ro", uri=True)
sconn.row_factory = sqlite3.Row
src_total = MIG._accounting(sconn)["budget_total"]
sconn.close()
assert {k: v for k, v in total.items() if k not in cont_added} == src_total
assert cont_added <= set(total)
assert total["sealed"] == 1 and total["sealed_requests"] == 1 # 旧封账原样(迁移前真实用量 1 次)
assert total["total_requests"] == 1 and total["total_tokens"] == 1000
# 源库逐字节不变
assert src.read_bytes() == before_bytes
@@ -230,39 +236,46 @@ def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
src, base = synth
assert _migrate(src, base)["ok"]
tdb = base / "data" / "companion.db"
# 旧库(源)封账依旧拒绝一切
sconn = Store(src, init=False)
old = PersistentBudget(sconn, BudgetGuard(BudgetConfig()))
with pytest.raises(BudgetStop):
old.acquire("dialogue_main", tokens=1)
sconn.close()
# 副本:新授权范围生效,可继续体验;新计数在旧账之上单独可核
store = Store(tdb, init=False)
cfg = BudgetConfig(daily_tokens=5000, daily_requests={
"dialogue": 5, "life": 5, "background": 5, "semantic": 5})
guard = PersistentBudget(store, BudgetGuard(cfg))
assert guard.total_requests_used() == 1 # 旧计数保留
# 旧口径(scope="")在源库与副本上都被旧封账拒绝:旧账没被改写、没被绕过
for db in (src, tdb):
legacy = Store(db, init=False)
with pytest.raises(BudgetStop):
PersistentBudget(legacy, BudgetGuard(cfg)).acquire("dialogue_main", tokens=1)
legacy.close()
# 接续实例(scope="hel919"):新授权范围生效,新计数落在独立 hel919:* 键
store = Store(tdb, init=False)
guard = PersistentBudget(store, BudgetGuard(cfg), scope="hel919")
assert guard.total_requests_used() == 0 # 新 scope 从零起,不借旧计数也不清旧键
hold = guard.acquire("dialogue_main", tokens=500)
guard.settle(hold, actual_tokens=400)
assert guard.total_requests_used() == 2
assert guard.total_tokens_used() == 1400
assert guard.total_requests_used() == 1 and guard.total_tokens_used() == 400
t = {r["key"]: r["value"] for r in store.query("SELECT key,value FROM budget_total")}
assert t["total_requests"] == 1 and t["total_tokens"] == 1000 # 旧键未动
assert t["hel919:total_requests"] == 1 and t["hel919:total_tokens"] == 400
store.close()
# 进程"重启":重开库,计数与期限类状态不重置
# 进程"重启":重开库,新 scope 计数不重置;旧口径读者依旧被旧封账拒绝
store2 = Store(tdb, init=False)
guard2 = PersistentBudget(store2, BudgetGuard(cfg))
assert guard2.total_requests_used() == 2
assert guard2.total_tokens_used() == 1400
guard2 = PersistentBudget(store2, BudgetGuard(cfg), scope="hel919")
assert guard2.total_requests_used() == 1 and guard2.total_tokens_used() == 400
hold = guard2.acquire("life_event", tokens=100)
guard2.settle(hold, actual_tokens=100)
assert guard2.total_requests_used() == 3
assert guard2.total_requests_used() == 2
with pytest.raises(BudgetStop):
PersistentBudget(store2, BudgetGuard(cfg)).acquire("dialogue_main", tokens=1)
store2.close()
# 新账封账后同样拒绝(close 路径的库内效果)
# 新账封账(close 路径的库内效果):新 scope 拒绝一切;旧键依旧原样
store3 = Store(tdb, init=False)
guard3 = PersistentBudget(store3, BudgetGuard(cfg))
guard3.seal()
guard3 = PersistentBudget(store3, BudgetGuard(cfg), scope="hel919")
marker = guard3.seal()
with pytest.raises(BudgetStop):
guard3.acquire("dialogue_main", tokens=1)
t = {r["key"]: r["value"] for r in store3.query("SELECT key,value FROM budget_total")}
assert t["sealed"] == 1 and t["sealed_requests"] == 1 # 旧封账未被触碰
assert t["hel919:sealed"] == 1 and t["hel919:sealed_requests"] == 2
store3.close()
assert marker["requests"] == 2
# ---------------------------------------------------------------- window guard
+2 -1
View File
@@ -38,12 +38,13 @@ def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--db", required=True, type=Path, help="团队实例产品库路径")
ap.add_argument("--reason", default="", help="封账原因(记录在交付评论,不写入库)")
ap.add_argument("--scope", default="", help="budget_total 键 scope(如 hel919:);缺省=旧账原键")
args = ap.parse_args()
if not args.db.is_file():
print(json.dumps({"ok": False, "error": f"库不存在:{args.db}"}, ensure_ascii=False))
return 1
store = Store(args.db, init=False)
guard = PersistentBudget(store, BudgetGuard(BudgetConfig()))
guard = PersistentBudget(store, BudgetGuard(BudgetConfig()), scope=args.scope)
before = guard.total_requests_used()
marker = guard.seal()
# 自检:封账后 acquire 必须被拒且不落账(拒绝路径在任何写入之前)。