HEL-919: same-her continuation package — migration isolation, frozen old ledger, scoped start/stop, offline evidence
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
# HEL-919 · 同一位她继续体验的启停接续运行包(离线可执行准备;未部署,cap=0)
|
||||
|
||||
> 本目录是 HEL-915 既有体验接续的**工程收口**:把「同一位她继续体验」装成
|
||||
> 可交接的启停接续包——同一位她迁移(拒绝空档案、不因已有档案拒绝)、
|
||||
> 旧账保留 + 新消耗隔离可核、背景工作不漏项、专属实例唯一启停入口(默认
|
||||
> 一切真实出口关闭)、给总管的启用安排。**本卡未部署任何现网服务、未监听
|
||||
> 任何端口、未改任何现有实例(8300/8310/8320/8350、7880/8081 及全部用户
|
||||
> 资料/旧账/归档原样);实际启用与新用量由总管按 enablement-plan.md 获批
|
||||
> 后执行。**
|
||||
|
||||
## 0. 精确版本
|
||||
|
||||
- **产品基线(本卡起点,不回退、不合并、不改 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)零改动:
|
||||
```bash
|
||||
git merge-base --is-ancestor 2e91a3c91e90944991886b21f7167a6913f41efb HEAD && echo ok
|
||||
git diff --stat 2e91a3c91e90944991886b21f7167a6913f41efb HEAD -- src web config tools # 必须为空
|
||||
```
|
||||
- 需求基准 v1.12(`docs/requirements/`),检查见 `handoff-HEL-919.json`。
|
||||
|
||||
## 1. 交付物清单
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `README.md` | 本说明(唯一照抄入口) |
|
||||
| `manifest.json` | 机器可读清单:基线、文件、边界 |
|
||||
| `migrate_same_her.py` | 同一位她接续迁移:preflight / migrate / rollback(源库只读、幂等、自检、一致性备份) |
|
||||
| `instance_ctl.sh` | 专属实例唯一启停入口:check / start / stop / close / status / watch |
|
||||
| `window_guard_hel919.py` | 启动授权守卫:默认关闭、未批准/过期拒绝、重启不重置期限 |
|
||||
| `models.template.yaml` | 预算全 0 的脱敏配置模板(新授权范围落点) |
|
||||
| `semantic.template.yaml` | 语义权威账续账模板(全 0;唯一权威账不复制) |
|
||||
| `cybergril-hel919-expiry.template.service` | 到期收尾 systemd 模板(只 close 本实例) |
|
||||
| `queue_policy.md` | 背景工作盘点与旧队列接续政策 |
|
||||
| `enablement-plan.md` | 给总管的启用安排(可直接交用户体验) |
|
||||
| `test_ctl_scripts.sh` | 启停脚本离线替身检查(零真实服务/端口/出站) |
|
||||
|
||||
离线测试证据:`tests/test_hel919_continuation.py`(合成旧档案 + 替身
|
||||
provider/进程/时钟);`docs/rework/hel919/` 下为实跑记录。
|
||||
|
||||
## 2. 目标实例布局(唯一布局)
|
||||
|
||||
```
|
||||
/opt/cybergril-hel919/ # 实例根(名字可换;结构固定)
|
||||
current/ # git checkout <运行包提交>(§0 校验两条都要过)
|
||||
etc/models.yaml # 由 models.template.yaml 复制(预算默认全 0)
|
||||
etc/semantic.yaml # 由 semantic.template.yaml 复制(cap 默认全 0)
|
||||
etc/voice.yaml # 由 config/voice.example.yaml 复制(语音维持关闭)
|
||||
data/companion.db # 迁移产物(同一位她的隔离副本)
|
||||
data/continuation.json # 迁移记录(身份指纹/出处计数/冻结账/队列盘点)
|
||||
data/<向量库、推导史等> # 迁移时 --data-dir 随实例复制
|
||||
backups/ # 迁移前目标库一致性备份(回退用)
|
||||
logs/
|
||||
window.json / window-active # 获批窗口才存在(enablement-plan.md §1)
|
||||
```
|
||||
|
||||
本实例端口默认 8370/8371(`HEL919_HTTP/HTTPS`),不属于旧统一实例
|
||||
8360/8361,也不触碰任何共享服务。
|
||||
|
||||
## 3. 同一位她迁移(获批部署窗口内执行一次;全程离线)
|
||||
|
||||
```bash
|
||||
# 1) 预检源档案(只读):非空档案/出生/诠释齐全才放行;输出身份指纹与队列盘点
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py preflight --db <源实例库>
|
||||
|
||||
# 2) 迁移到隔离副本(源库只读;目标已有库先做一致性备份;幂等)
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py migrate \
|
||||
--db <源实例库> --base /opt/cybergril-hel919 \
|
||||
--data-dir <源向量库目录>=sem/vec --data-dir <源推导史目录>=sem/hist
|
||||
|
||||
# 3) 回退(只动副本,源库永不回退)
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py rollback --base /opt/cybergril-hel919
|
||||
```
|
||||
|
||||
迁移铁律(工具内建自检,任一不过自动回退并报错):
|
||||
- 空库/缺出生底色/缺出生诠释 → **拒绝**(不走新建人格,也不因已有档案拒绝);
|
||||
- 同一位她前后可核:身份指纹、bazi/persona/记忆/聊天/生活/关系逐表计数相等;
|
||||
- 旧账保留:源库文件与库内一切计数/封账标记迁移后逐项不变;副本内旧
|
||||
`sealed*` 移入冻结出处键 `cont_prior_sealed*`(旧实例上的封账依旧生效——
|
||||
那份库从未被写);token/request 历史行与总量计数原样保留,新用量在同一
|
||||
副本继续累计,新旧天然可分;
|
||||
- 语义嵌入权威账**不复制**(queue_policy.md §3);
|
||||
- 重复运行:同一源 = 安全 no-op;不同源 = 拒绝;`rollback` 精确还原。
|
||||
|
||||
## 4. 就绪检查与启停(唯一操作入口)
|
||||
|
||||
```bash
|
||||
bash deploy/hel919-continuation/instance_ctl.sh check # 布局/迁移/默认关闭核验
|
||||
bash deploy/hel919-continuation/instance_ctl.sh start # 需 window.json + window-active
|
||||
bash deploy/hel919-continuation/instance_ctl.sh status
|
||||
bash deploy/hel919-continuation/instance_ctl.sh stop # 只停本实例自有 pid 句柄,有界排空
|
||||
bash deploy/hel919-continuation/instance_ctl.sh close # 窗口收尾:stop + 封本实例新账 + 记 closed_at
|
||||
bash deploy/hel919-continuation/instance_ctl.sh watch <epoch> # 到点自动 close
|
||||
```
|
||||
|
||||
安全属性(替身演练 + 单测证明,见 §6):
|
||||
- **默认关闭**:无 `window-active` 标记 / 预算全 0 → 一切真实出口在发送前
|
||||
拒绝(fail-closed),start 也被守卫拒绝;
|
||||
- **过期拒绝**:deadline 持久在 window.json,到期 watch 自动 close,此后
|
||||
重启被守卫拒绝;进程重启不重置期限、不新增用量(账在库内);
|
||||
- **只停自己**:stop/close 只操作身份核验过的本实例 pid(cmdline+cwd 双验,
|
||||
PID 复用不动手);不调用旧 force_end / worker / bridge / tts 脚本,不触碰
|
||||
8300/8310/8320/8350、7880、8081、9880、8090 等共享服务;
|
||||
- **有界收尾**:在途排空上限 HEL919_DRAIN_SEC(默认 30s);
|
||||
- **收尾可核**:close 写 close.log / window.json closed_at / 封账标记,
|
||||
运行日志在 logs/。
|
||||
|
||||
## 5. 获批启用(总管操作;enablement-plan.md 是完整安排)
|
||||
|
||||
1. `check` 通过后,按批准写 etc/models.yaml 预算值(新授权范围);
|
||||
2. 生成 window.json(approved/started_at/deadline_at/deadline_epoch/
|
||||
authorization_comment)+ `touch window-active`;
|
||||
3. 生成 expiry timer(`cybergril-hel919-expiry.template.service` + 由
|
||||
deadline 换算的 OnCalendar)→ `instance_ctl.sh start`。
|
||||
|
||||
## 6. 离线验证(零真实调用)
|
||||
|
||||
```bash
|
||||
python3 -m pytest tests/test_hel919_continuation.py -q # 合成档案 + 替身
|
||||
bash deploy/hel919-continuation/test_ctl_scripts.sh # 启停替身检查
|
||||
python3 scripts/check_requirements.py --base-ref origin/main --handoff docs/requirements/handoff-HEL-919.json
|
||||
python3 scripts/check_requirements.py --base-ref 2e91a3c91e90944991886b21f7167a6913f41efb --handoff docs/requirements/handoff-HEL-919.json
|
||||
```
|
||||
|
||||
覆盖:空档案拒绝、同一位她前后保留、旧账冻结与源库不变、幂等/冲突/回退、
|
||||
新用量隔离且重启不重置、默认关闭零出站、过期拒绝、stop 只操作自有句柄、
|
||||
队列只盘数量与 ID。**未测到**:真实 LLM/ASR/TTS 行为、真实部署、浏览器
|
||||
端到端、Safari/手机;真实自然度由用户体验判断,离线证据不冒充。
|
||||
@@ -0,0 +1,22 @@
|
||||
# HEL-919 接续体验运行包 · 到期收尾 systemd 模板(脱敏待批件;默认不布防)
|
||||
#
|
||||
# 获批启用时由总管按 window.json 的 deadline 生成 timer(比 watch 前台等待
|
||||
# 更可靠);OnCalendar 必须填 UTC 时间(由 deadline_epoch 换算)。到期动作
|
||||
# 只调本包 instance_ctl.sh close:只停本实例自有句柄 + 只封本实例新账,
|
||||
# 不调用旧 force_end,不触碰任何共享服务(8300/8310/8320/8350、7880、8081、
|
||||
# 9880、8090)。
|
||||
#
|
||||
# 生成示例(部署说明 §6):
|
||||
# printf '[Unit]\nDescription=HEL-919 window deadline\n\n[Timer]\nOnCalendar=<UTC>\nPersistent=true\nUnit=cybergril-hel919-expiry.service\n\n[Install]\nWantedBy=timers.target\n' \
|
||||
# > /etc/systemd/system/cybergril-hel919-expiry.timer
|
||||
|
||||
[Unit]
|
||||
Description=Close HEL-919 continuation window (this instance only)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
Environment=HEL919_BASE=/opt/cybergril-hel919
|
||||
ExecStart=/usr/bin/bash /opt/cybergril-hel919/current/deploy/hel919-continuation/instance_ctl.sh close
|
||||
TimeoutStartSec=180
|
||||
StandardOutput=append:/opt/cybergril-hel919/logs/expiry.log
|
||||
StandardError=append:/opt/cybergril-hel919/logs/expiry.log
|
||||
@@ -0,0 +1,52 @@
|
||||
# HEL-919 · 给总管的接续体验启用安排(可直接交用户体验;非用量优化研究)
|
||||
|
||||
范围收敛为**文字 / 生活 / 情绪**小范围接续体验:同一位她(既有档案、出生
|
||||
底色、名字、习惯、关系、聊天、生活、记忆全部保留),不含语音、天气素材、
|
||||
完整备份恢复、摄像头与口型(未完项承接不变)。用户已明确免除费用考虑
|
||||
(HEL-915 评论 01a1a482-1338-719d-8acd-9df70355e95c:「我觉得你不用考虑
|
||||
消耗费用,只需要确保项目推进」),本安排不出现人民币金额、不再索要计费
|
||||
资料;边界用工程自选的**原有共池与有限运行窗口**表达,并证明可达性。
|
||||
|
||||
## 1. 谁准备、谁操作、白栖知何时参与
|
||||
|
||||
| 阶段 | 负责人 | 动作 |
|
||||
| --- | --- | --- |
|
||||
| 准备(离线,零调用) | 施工员2号 | 按本包 README 完成隔离副本迁移演练证据;本卡交付物即准备完成态 |
|
||||
| 启用(一次窗口) | 总管 | 在接续实例上写获批 models.yaml/semantic.yaml 数值、生成 window.json + expiry timer、`instance_ctl.sh check && start`;全程唯一操作入口 |
|
||||
| 体验 | 白栖知 | 打开接续实例页面,与同一位她文字交流;观察点见 §3 |
|
||||
| 收尾 | 总管(到期自动+人工复核) | expiry timer 自动 `close`(停本实例、封本实例新账);核对日志与账目后向用户报告 |
|
||||
|
||||
## 2. 运行边界(工程自选,原有共池直接复用)
|
||||
|
||||
- **窗口**:单次 ≤ 72 小时(deadline 写入 window.json,进程重启不重置;
|
||||
到期 expiry 自动收尾,重启被 window_guard 拒绝)。
|
||||
- **额度**:只复用既有共池机制——models.yaml `daily_tokens` 与
|
||||
`daily_requests` 四类(dialogue / life / background / semantic)。这些
|
||||
上限真实控制的合计数就是:每日总 token + 每类每日真实 provider 出口
|
||||
请求次数(含失败/取消/重试,预占不退)。建议起步值:dialogue 200/日、
|
||||
life 40/日、background 120/日、semantic 40/日、daily_tokens 300k/日;
|
||||
总管可按首日实际 `budget_total`/`request_usage` 读数调整,不需要用户
|
||||
拍板金额。不为每个子类另造新系统。
|
||||
- **不承诺**:「8 轮必然花多少」不承诺;历史全类别 345186/747 不当作每轮
|
||||
主聊成本引用(那是全历史合计,不是本轮口径)。
|
||||
- **语义账**:如需真实记忆检索,semantic.yaml 按累计算式续唯一权威账
|
||||
(不动冻结余额);默认可保持 0,先用 R3 词面 FTS 通道体验文字接续。
|
||||
|
||||
## 3. 白栖知的实际观察动作(体验判断项)
|
||||
|
||||
1. 她还记得吗:名字、称呼、此前聊天里的事实、共同的习惯/暗语(关系层)。
|
||||
2. 生活连续吗:不说话时她的生活在走(life_event/activity),回来能接上。
|
||||
3. 情绪连贯吗:聊天后情绪词变化有据、恢复自然;不翻旧账为当下伤害。
|
||||
4. 边界承接:她说明自己的世界边界时自然、不突兀。
|
||||
5. 失败表现:额度/预算拒绝时她的表现是如实「今天有点走神」类降档,不是
|
||||
崩溃或沉默。
|
||||
|
||||
## 4. 失败停止与资料保留
|
||||
|
||||
- 任何观察异常:总管 `instance_ctl.sh close` 立即收尾(同到期路径)。
|
||||
- 到期/封账后:**新聊天与新记忆保留**在接续库,不自动覆盖原实例、不删作
|
||||
测试垃圾;原实例与其旧账、旧封账、归档全程未动。
|
||||
- 回退:`migrate_same_her.py rollback` 只回退接续副本到迁移前状态,源库
|
||||
永不受影响。
|
||||
- 真实自然度的体验判断由白栖知决定;离线证据只证明接线正确,不冒充体验
|
||||
通过。
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-919 接续体验运行包 · 专属新实例唯一启停入口(模板;默认一切真实出口关闭)
|
||||
#
|
||||
# 子命令(只认这些,其他一律 rc=2 拒绝,绝不静默当 start):
|
||||
# check 离线就绪检查:布局/配置/迁移记录/默认关闭(预算全 0)核验,零启动
|
||||
# start 经 window_guard_hel919.py 授权核验后启动本实例 API(身份核验、
|
||||
# 健康检查失败只清自己刚起的进程);重复 start 拒绝
|
||||
# stop 只停本实例自己持有的精确 pid 句柄(身份核验;PID 复用不动手),
|
||||
# 有界排空(HEL919_DRAIN_SEC,默认 30s)。绝不调用旧 force_end/
|
||||
# worker/bridge/tts 控制脚本,绝不触碰 8300/8310/8320/8350、7880、
|
||||
# 8081、9880、8090 等共享服务
|
||||
# close 窗口收尾 = stop + 本实例新账显式封账(tools/seal_budget_hel879.py,
|
||||
# 只封本实例库)+ window.json 记 closed_at;幂等
|
||||
# watch <epoch> 到点自动 close(受监督前台等待;更可靠等价物=获批后装
|
||||
# systemd timer 调本脚本 close,模板见 cybergril-hel919-expiry.template)
|
||||
# status pid 句柄 + 健康状态
|
||||
#
|
||||
# 环境变量(默认值按部署说明的实例布局,全部可用 ENV 覆盖做替身演练):
|
||||
# HEL919_BASE 实例根目录(默认 /opt/cybergril-hel919;含 current/ etc/ data/ logs/)
|
||||
# HEL919_HTTP / HEL919_HTTPS 本实例端口(默认 8370/8371;旧统一实例 8360/8361 不属于本实例)
|
||||
# HEL919_VENV 产品 3.11 venv python(默认 /opt/cybergril-hel879/current/.venv311/bin/python)
|
||||
# HEL919_CERT / HEL919_KEY 证书(默认复用既有自签)
|
||||
# HEL919_DRAIN_SEC stop 有界排空秒数(默认 30)
|
||||
set -u
|
||||
BASE=${HEL919_BASE:-/opt/cybergril-hel919}
|
||||
CODE=${HEL919_CODE:-$BASE/current}
|
||||
HTTP=${HEL919_HTTP:-8370}
|
||||
HTTPS=${HEL919_HTTPS:-8371}
|
||||
VENV=${HEL919_VENV:-/opt/cybergril-hel879/current/.venv311/bin/python}
|
||||
CERT=${HEL919_CERT:-/opt/cybergril-voice-certs/cybergril-voice.pem}
|
||||
KEY=${HEL919_KEY:-/opt/cybergril-voice-certs/cybergril-voice.key}
|
||||
DRAIN=${HEL919_DRAIN_SEC:-30}
|
||||
PKG=$CODE/deploy/hel919-continuation
|
||||
LOG=$BASE/logs/api.log
|
||||
PIDF=$BASE/logs/api.pid
|
||||
MARKER="serve_dual_8360_8361.py"
|
||||
PY=${HEL919_PY:-python3} # 守卫/检查用系统 python(仅标准库)
|
||||
|
||||
usage() { echo "usage: [ENV=..] bash $0 check|start|stop|close|status|watch <epoch>" >&2; exit 2; }
|
||||
|
||||
# 进程身份核验:pid 存活 + cmdline 含本启动器 + cwd 是本实例代码目录。
|
||||
# 任一不满足(含 PID 被系统复用)一律不动它。
|
||||
ours() {
|
||||
local p=$1 cmd cw
|
||||
case "$p" in ''|*[!0-9]*) return 1 ;; esac
|
||||
[ "$p" != "$$" ] || return 1
|
||||
kill -0 "$p" 2>/dev/null || return 1
|
||||
cmd=$(tr '\0' ' ' < "/proc/$p/cmdline" 2>/dev/null) || return 1
|
||||
cw=$(readlink "/proc/$p/cwd" 2>/dev/null) || return 1
|
||||
case "$cmd" in *"$MARKER"*) ;; *) return 1 ;; esac
|
||||
[ "$(readlink -f "$cw")" = "$(readlink -f "$CODE")" ] || return 1
|
||||
return 0
|
||||
}
|
||||
pidfile_pid() { [ -f "$PIDF" ] && cat "$PIDF" 2>/dev/null; }
|
||||
|
||||
check() {
|
||||
local rc=0
|
||||
for d in "$BASE" "$CODE" "$BASE/etc" "$BASE/data" "$BASE/logs"; do
|
||||
[ -d "$d" ] && echo "ok dir $d" || { echo "MISSING dir $d" >&2; rc=1; }
|
||||
done
|
||||
for f in "$BASE/etc/models.yaml" "$BASE/data/companion.db" "$BASE/data/continuation.json"; do
|
||||
[ -f "$f" ] && echo "ok file $f" || { echo "MISSING file $f(先完成迁移,见 README §3)" >&2; rc=1; }
|
||||
done
|
||||
if [ -f "$BASE/etc/models.yaml" ]; then
|
||||
# 默认关闭核验:models.yaml budget 段任何非 0 值都必须有获批 window.json 支撑
|
||||
"$PY" - "$BASE/etc/models.yaml" "${HEL919_ALLOW_BUDGET:-0}" <<'EOF'
|
||||
import re, sys
|
||||
text = open(sys.argv[1], encoding="utf-8").read()
|
||||
m = re.search(r"^budget:.*?(?=^\S)", text, re.S | re.M)
|
||||
allow = sys.argv[2] == "1"
|
||||
bad = []
|
||||
if m:
|
||||
for line in m.group(0).splitlines():
|
||||
if re.match(r"\s*(daily_tokens|dialogue|life|background|semantic|total_requests|total_tokens|warn_ratio|hard_stop_ratio)\s*:", line):
|
||||
k, _, v = line.strip().partition(":")
|
||||
if k in ("warn_ratio", "hard_stop_ratio"):
|
||||
continue
|
||||
nums = re.findall(r"\d+", v)
|
||||
if nums and any(int(n) > 0 for n in nums) and not allow:
|
||||
bad.append(line.strip())
|
||||
if bad and not allow:
|
||||
print("REFUSED: budget 非零而未获批准(window-active 授权 + HEL919_ALLOW_BUDGET=1 才放行):", bad, file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print("ok default-off budgets (or approved)")
|
||||
EOF
|
||||
[ $? -eq 0 ] || rc=1
|
||||
fi
|
||||
[ $rc -eq 0 ] && echo "CHECK OK(就绪;默认关闭)" || echo "CHECK FAILED" >&2
|
||||
return $rc
|
||||
}
|
||||
|
||||
start() {
|
||||
local p
|
||||
p=$(pidfile_pid)
|
||||
if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then
|
||||
if ours "$p"; then echo "REFUSED: 本实例已在运行 (pid $p) — 先 stop" >&2
|
||||
else echo "REFUSED: pid 文件里的活 pid $p 不是本实例(PID 复用?)— 人工处理 $PIDF" >&2; fi
|
||||
exit 1
|
||||
fi
|
||||
rm -f "$PIDF"
|
||||
[ -x "$VENV" ] || { echo "REFUSED: venv python 不可执行: $VENV" >&2; exit 1; }
|
||||
mkdir -p "$BASE/logs" "$BASE/data"
|
||||
# 授权核验:默认关闭;未批准/过期窗口一律拒绝启动
|
||||
"$PY" "$PKG/window_guard_hel919.py" "$BASE" || exit 1
|
||||
cd "$CODE" || exit 1
|
||||
set -a
|
||||
export CYBERGRIL_DB=$BASE/data/companion.db
|
||||
export CYBERGRIL_SEMANTIC=${HEL919_SEMANTIC:-stub}
|
||||
export CYBERGRIL_R2_ENABLED=1
|
||||
export TZ=Asia/Shanghai
|
||||
export CYBERGRIL_SEMANTIC_CONFIG=$BASE/etc/semantic.yaml
|
||||
export MEM0_TELEMETRY=False
|
||||
export FASTEMBED_CACHE_PATH=$BASE/data/sem/fastembed-cache
|
||||
export HF_HUB_OFFLINE=1
|
||||
export TRANSFORMERS_OFFLINE=1
|
||||
export CYBERGRIL_MODELS=$BASE/etc/models.yaml
|
||||
export CYBERGRIL_VOICE_CONFIG=$BASE/etc/voice.yaml
|
||||
export CYBERGRIL_WEB=$CODE/web/dist
|
||||
export PYTHONPATH=$CODE/src
|
||||
set +a
|
||||
nohup "$VENV" deploy/voice/serve_dual_8360_8361.py \
|
||||
--http-port "$HTTP" --https-port "$HTTPS" --cert "$CERT" --key "$KEY" \
|
||||
> "$LOG" 2>&1 &
|
||||
p=$!
|
||||
echo "$p" > "$PIDF"
|
||||
echo "hel919 api starting (pid $p) http=$HTTP https=$HTTPS"
|
||||
sleep 6
|
||||
if curl -s --max-time 3 "http://127.0.0.1:$HTTP/api/health" >/dev/null; then
|
||||
echo "OK: $HTTP healthy"; return 0
|
||||
fi
|
||||
echo "FAIL: 健康检查未过 — 日志保留在 $LOG;tail:" >&2
|
||||
tail -20 "$LOG" >&2
|
||||
if ours "$p"; then kill "$p"; sleep 2; ours "$p" && kill -9 "$p"; fi
|
||||
rm -f "$PIDF"
|
||||
echo "已清理自己刚起的进程(日志保留)" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
stop() {
|
||||
local p rc=0
|
||||
p=$(pidfile_pid)
|
||||
if [ -z "$p" ]; then echo "hel919 api not running (no pid file)"; return 0; fi
|
||||
if kill -0 "$p" 2>/dev/null && ! ours "$p"; then
|
||||
echo "REFUSED: pid $p 存活但不是本实例 api(PID 复用?)— 不动手,人工处理 $PIDF" >&2
|
||||
return 1
|
||||
fi
|
||||
if ours "$p"; then
|
||||
kill "$p" # SIGTERM:应用有界收尾在途请求
|
||||
local i=0
|
||||
while [ $i -lt "$DRAIN" ] && ours "$p"; do sleep 1; i=$((i+1)); done
|
||||
if ours "$p"; then
|
||||
echo "有界排空 ${DRAIN}s 到期仍在运行 — 对已身份核验的本实例进程 SIGKILL" >&2
|
||||
kill -9 "$p"; sleep 1
|
||||
fi
|
||||
ours "$p" && rc=1
|
||||
fi
|
||||
rm -f "$PIDF"
|
||||
[ $rc -eq 0 ] && echo "hel919 api stopped(只操作了本实例自有句柄 pid $p)"
|
||||
return $rc
|
||||
}
|
||||
|
||||
close() {
|
||||
local rc=0
|
||||
stop || rc=1
|
||||
if [ -f "$BASE/data/companion.db" ]; then
|
||||
"$PY" "$CODE/tools/seal_budget_hel879.py" --db "$BASE/data/companion.db" \
|
||||
--reason "hel919 continuation window closed" >> "$BASE/logs/close.log" 2>&1 || rc=1
|
||||
fi
|
||||
"$PY" - "$BASE/window.json" "$rc" <<'EOF'
|
||||
import datetime, json, pathlib, sys
|
||||
p = pathlib.Path(sys.argv[1])
|
||||
if p.exists():
|
||||
w = json.loads(p.read_text())
|
||||
w["closed_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
w["close_exit_code"] = int(sys.argv[2])
|
||||
p.write_text(json.dumps(w, indent=2) + "\n")
|
||||
EOF
|
||||
[ -f "$BASE/window-active" ] && rm -f "$BASE/window-active"
|
||||
echo "hel919 window closed(本实例新账已显式封账;资料与全部账目保留)"
|
||||
return $rc
|
||||
}
|
||||
|
||||
status() {
|
||||
local p
|
||||
p=$(pidfile_pid)
|
||||
if [ -n "$p" ]; then
|
||||
if ours "$p"; then echo "running pid $p (identity verified)"
|
||||
elif kill -0 "$p" 2>/dev/null; then echo "pid $p alive but NOT ours (stale pid file?)"
|
||||
else echo "pid $p not alive (stale pid file)"; fi
|
||||
else
|
||||
echo "no pid file"
|
||||
fi
|
||||
curl -s --max-time 3 "http://127.0.0.1:$HTTP/api/health" && echo " <- health" \
|
||||
|| echo "health not answering"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
check) check ;;
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
close) close ;;
|
||||
status) status ;;
|
||||
watch)
|
||||
DL=${2:?deadline epoch seconds required}
|
||||
case "$DL" in *[!0-9]*|'') usage ;; esac
|
||||
mkdir -p "$BASE/logs"
|
||||
echo "[$(date -u +%FT%TZ)] watch start, deadline $DL (pid $$)" >> "$BASE/logs/watch.log"
|
||||
while [ "$(date +%s)" -lt "$DL" ]; do sleep 30; done
|
||||
echo "[$(date -u +%FT%TZ)] DEADLINE REACHED — close" >> "$BASE/logs/watch.log"
|
||||
close
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"package": "deploy/hel919-continuation",
|
||||
"card": "HEL-919 补齐同一位她继续体验的启停接续包",
|
||||
"parent": "HEL-915",
|
||||
"product_baseline": {
|
||||
"branch": "agent/2/182d2402a8df",
|
||||
"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 零改动",
|
||||
"files": [
|
||||
"README.md", "manifest.json", "migrate_same_her.py", "instance_ctl.sh",
|
||||
"window_guard_hel919.py", "models.template.yaml", "semantic.template.yaml",
|
||||
"cybergril-hel919-expiry.template.service", "queue_policy.md",
|
||||
"enablement-plan.md", "test_ctl_scripts.sh"
|
||||
],
|
||||
"reuse": [
|
||||
"deploy/hel913-unified(启停/身份核验/模板口径)",
|
||||
"deploy/hel914-user(窗口守卫形态;空档案限制由 migrate_same_her.py 取代)",
|
||||
"src/cybergril/think/budget.py + life/model.py PersistentBudget(持久预算,零改动复用)",
|
||||
"tools/seal_budget_hel879.py(显式封账,close 复用)",
|
||||
"config/semantic.example.yaml(权威账续账算式)"
|
||||
],
|
||||
"defaults": {
|
||||
"deployed": false, "listening_ports": [], "real_calls": 0,
|
||||
"budgets": "models/semantic 模板全 0(fail-closed)",
|
||||
"shared_services_touched": []
|
||||
},
|
||||
"boundaries": "不动 8300/8310/8320/8350、7880/8081、9880/8090、836x/8082/9880;不改模型/认证/运行时;不安装依赖;启用需总管获批窗口(enablement-plan.md)"
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,96 @@
|
||||
# HEL-919 接续体验运行包 · models 配置模板(脱敏;本文件一切预算=0)
|
||||
#
|
||||
# 与 HEL-913 模板同构(tiers/routing/语音段一致),差异只在预算注释:
|
||||
# 这是「同一位她」的接续实例——库内旧计数已随迁移保留并在账内冻结出处
|
||||
# (cont_prior_*,见 migrate_same_her.py),本文件的预算值就是**新授权范围**:
|
||||
# 未批准一律 0(发送前拒绝,fail-closed);获批后由总管按 enablement-plan.md
|
||||
# 写入,进程重启不重置(PersistentBudget 库内持久计数)。
|
||||
#
|
||||
# 用法:复制到 <实例>/etc/models.yaml,只改 base_url 指向获批网关、按批准
|
||||
# 包写入预算值。未经批准一律保持 0(发送前拒绝,fail-closed)。instance_ctl.sh
|
||||
# check 会在无获批窗口时拒绝任何非 0 预算(默认关闭核验)。
|
||||
# 候选分支 config/models.yaml 的 tiers/routing 与本模板一致;本模板把
|
||||
# base_url 换成占位符并保留 HEL-908 reasoning: buffer_turn 与 HEL-911/912
|
||||
# 审核通过的调度修正(turn_detection=None 在代码侧,见 src/cybergril/voice/worker.py)。
|
||||
tiers:
|
||||
high:
|
||||
provider: openai_compat
|
||||
model: <获批模型名>
|
||||
base_url: <http://内网网关:端口/v1>
|
||||
api_key_env: null
|
||||
timeout: 60.0
|
||||
temperature: 0.85
|
||||
reasoning: buffer_turn
|
||||
standard:
|
||||
provider: openai_compat
|
||||
model: <获批模型名>
|
||||
base_url: <http://内网网关:端口/v1>
|
||||
api_key_env: null
|
||||
timeout: 40.0
|
||||
temperature: 0.7
|
||||
reasoning: buffer_turn
|
||||
low:
|
||||
provider: openai_compat
|
||||
model: <获批模型名>
|
||||
base_url: <http://内网网关:端口/v1>
|
||||
api_key_env: null
|
||||
timeout: 20.0
|
||||
temperature: 0.4
|
||||
reasoning: buffer_turn
|
||||
routing:
|
||||
dialogue_main: high
|
||||
dialogue_followup: standard
|
||||
proactive_message: high
|
||||
crisis: high
|
||||
life_event: low
|
||||
memory_gist: low
|
||||
fact_extract: low
|
||||
output_guard: low
|
||||
pattern_detect: low
|
||||
filler: none
|
||||
tick: none
|
||||
reach_out: none
|
||||
avatar_drive: none
|
||||
budget:
|
||||
daily_tokens: 0
|
||||
warn_ratio: 0.7
|
||||
hard_stop_ratio: 0.95
|
||||
daily_requests:
|
||||
dialogue: 0
|
||||
life: 0
|
||||
background: 0
|
||||
semantic: 0
|
||||
# 用户实例永不配置一次性总量(total_requests/total_tokens 保持缺省):
|
||||
# 一次性总量只属于独立团队测试实例,见 docs/budget-package-hel895.md §6。
|
||||
asr:
|
||||
provider: scripted
|
||||
model: qwen3-asr-1.7b
|
||||
language: zh
|
||||
paralinguistic:
|
||||
provider: scripted
|
||||
model: sensevoice-small
|
||||
window_ms: 1500
|
||||
enabled: true
|
||||
tts:
|
||||
provider: silence
|
||||
model: fun-cosyvoice3-0.5b
|
||||
voice_ref: null
|
||||
sample_rate: 16000
|
||||
vad:
|
||||
provider: energy
|
||||
model: silero-v6
|
||||
sample_rate: 16000
|
||||
turn:
|
||||
provider: heuristic
|
||||
silence_min_ms: 150
|
||||
silence_hard_end_ms: 800
|
||||
embedding:
|
||||
provider: openai_compat
|
||||
model: qwen3-embedding-0.6b
|
||||
base_url: null
|
||||
api_key_env: null
|
||||
dim: 1024
|
||||
avatar:
|
||||
route: vrm
|
||||
renderer: three.js
|
||||
lipsync: envelope
|
||||
@@ -0,0 +1,43 @@
|
||||
# HEL-919 · 背景工作盘点与旧队列接续政策(只盘点数量与 ID,不含任何内容)
|
||||
|
||||
本文件是「背景工作不漏项、不人为关成假体验」的落地清单:列出接续实例里
|
||||
真实存在的背景工作路径、它们排队的地方、以及旧排队工作的接续政策。盘点
|
||||
工具:`migrate_same_her.py preflight/migrate` 的 `queues` 段(pending 数量 +
|
||||
pending ID,绝不导出聊天/生活文本)。
|
||||
|
||||
## 1. 实际路径盘点(表 → 工作)
|
||||
|
||||
| 卡片点名的工作 | 实际路径 | 预算类别(models.yaml daily_requests) |
|
||||
| --- | --- | --- |
|
||||
| 原文压缩(记忆 gist) | `mem_episodic.gist`(`set_gist`,scene `memory_gist`) | background |
|
||||
| 聊天情绪分类 | `chat_affect_job`(+ `life_control.chat_affect_cutoff` 一次性历史切断点,HEL-916) | background |
|
||||
| 分享判断 | `sharing_attempt`(judge_attempts 恰好一次重排,HEL-916) | background |
|
||||
| 生活 | `life_run` / `life_event` / `life_activity`(继续/打断/恢复) | life |
|
||||
| 成长 | `growth_job` / `growth_event` | background |
|
||||
| 出生诠释任务 | `persona_job` / `persona_interp` / `persona_seed` | background |
|
||||
| 记忆入账 | `mem_job`(chat → mem_episodic) | background |
|
||||
| SDK 提取/嵌入 | `sem_batch` / `sem_covered` / `sem_row_done` + 语义嵌入权威账(embed_ops/llm_ops,独立 cap) | semantic(+语义账独立累计上限) |
|
||||
| 主动联系 | `reach_out` | dialogue |
|
||||
|
||||
## 2. 接续政策
|
||||
|
||||
1. **不删队列、不静默禁用**:迁移把全部表原样带到接续副本;正常生活/记忆
|
||||
不会为省额度被悄悄关掉。
|
||||
2. **未批准的能力维持关闭**:daily_requests 未写批准值的类别 cap=0,真实
|
||||
provider 出口在发送前拒绝(fail-closed);语义层 embed/llm cap=0 同理。
|
||||
关闭是显式配置(models.yaml / semantic.yaml),不是暗中切断。
|
||||
3. **旧排队工作执行时计入新账**:任何真实出口先 `PersistentBudget.acquire`
|
||||
预占(失败/取消/重试不退款,保守保留预占——已发送的成本不当未发生);
|
||||
HEL-886 语义批次「预算拒绝不烧尝试次数、预算回来后重排」的既有语义不变。
|
||||
4. **不执行的必须保留并说明**:窗口到期 close 后仍在 pending 的队列行原样
|
||||
留在库里(封账只拒绝新预占,不改队列状态);下次获批窗口接续处理。
|
||||
5. **历史切断点不重算**:`chat_affect_cutoff` 固化在迁移库中,旧聊天永不
|
||||
被补算为当下伤害(HEL-916 返工结论,历史回溯未获授权不做)。
|
||||
|
||||
## 3. 语义嵌入权威账(不复制、不另起新账)
|
||||
|
||||
权威账文件**只有一个**(`semantic.yaml ledger_path` 指向的 embed_ops 库)。
|
||||
接续实例**不复制**该文件:复制会造成两份权威账并发消费。续账走既有累计
|
||||
算式(semantic.template.yaml 注释):新 cap = 原批上限 + 获批增量,冻结
|
||||
余额与 authority 前缀校验保留;`min_used` 保证动到冻结前缀(含 42 提取/
|
||||
111 嵌入类历史余额)会被拒绝。默认全 0 = 真实提取/嵌入全部关闭。
|
||||
@@ -0,0 +1,63 @@
|
||||
# CyberGril 语义记忆层(Mem0 固定源)脱敏配置示例
|
||||
#
|
||||
# 复制为 config/semantic.yaml 并由总管在获批准的预算数值内填写。
|
||||
# embed_cap=0 / llm_cap=0 是安全默认:真实嵌入与 SDK 内部提取 LLM 全部关闭
|
||||
# (fail-closed,任何真实工作前拒绝),不会碰 498/500 的冻结余额。只有白栖知
|
||||
# 批准的新预算经总管核定后才可调高。硬闸与执行表见 docs/budget-plan-hel874.md。
|
||||
#
|
||||
# 后端选择(环境变量 CYBERGRIL_SEMANTIC):
|
||||
# off —— 关闭(默认;对话记忆检索回落到 R3 词面 FTS 通道)
|
||||
# stub —— 编排接通的自测后端(确定性子串匹配,非语义,不冒充语义能力)
|
||||
# mem0 —— 真实固定源 Mem0(2c81af3bbe27d9bccb09c772d583df9e9be72ee5,mem0ai 2.2.1,
|
||||
# 需发布 venv 已离线并入固定栈 wheel,见 deploy/hel874-release.md §4)
|
||||
# HEL-874/882 已对固定安装实测:search 必须带 user_id 过滤、payload 直读走
|
||||
# SDK 自带 client、内部 LLM 过独立 llm_ops 闸(证据 docs/rework/hel874/)。
|
||||
|
||||
# 嵌入账本:沿用 HEL-857 系列唯一权威账(embed_ops 表)续账,绝不另起新账;
|
||||
# SDK 内部提取 LLM 记同库 llm_ops 新表(独立 cap,互不挪用)
|
||||
#
|
||||
# ── 累计上限算式(HEL-885,写入前照此换算,禁止直接填增量)───────────────
|
||||
# 权威账现状:已用 498 条 / 原批上限 500(其中冻结不动 2 条余额)。
|
||||
# 白栖知批准的 B 部分新增嵌入额度(例如 180 条)并入同一累计账:
|
||||
# embed_cap = 500 + 180 = 680 # 原上限 + 新批增量(不是 180!)
|
||||
# embed_reserve = 2 # 原冻结余额 2 条继续保留不动
|
||||
# 可用余量 = 680 − 498 − 2 = 180
|
||||
# 错误示例:embed_cap: 180(对已用 498 的账等于瞬间耗尽并掩盖历史);
|
||||
# 动到旧冻结 2 条(min_used: 498 会拒绝)。
|
||||
ledger_path: /absolute/path/to/embed_ledger.sqlite3
|
||||
embed_cap: 0 # 本产品环境允许使用的嵌入条数累计上限;0=未批准=全部拒绝
|
||||
embed_daily: 0 # 嵌入条数日顶(执行表 C:建议 60/日,待批);0=未批准=拒绝
|
||||
embed_reserve: 0 # 预留不动的余量(例如为复测保留 40;冻结口径见上方算式)
|
||||
llm_cap: 0 # Mem0 内部提取 LLM 调用累计上限(执行表 B:建议 60,待批)
|
||||
llm_daily: 0 # Mem0 内部提取 LLM 日顶(执行表 C:建议 40/日,待批)
|
||||
|
||||
# 冻结前缀(HEL-885 起为必填,不可注释掉):只要 embed_cap / llm_cap 任一 >0,
|
||||
# 缺少、留空或填错的 authority 块都会让 mem0 模式在构造前直接拒绝
|
||||
# (ledger_authority_required / ledger_authority_*,fail-closed,不降级)。
|
||||
# ledger_path 必须仍是含冻结前缀的权威账——指向新空文件重开余额同样被拒。
|
||||
# 数值由总管按权威账现状填写(前 N 行逐行 SHA256 与最少已用条数):
|
||||
authority:
|
||||
prefix_rows: 181
|
||||
prefix_sha256: "<权威账前 N 行逐行摘要,总管填写>"
|
||||
min_used: 498
|
||||
|
||||
# 记录作用域:add(user_id=) 与 search(filters={"user_id":…}) 必须一致;
|
||||
# mem0 2.2.1 拒绝无过滤 search,此键一般不需要改
|
||||
user_scope: cybergril
|
||||
|
||||
# 网关(现有配置同源,config/models.yaml 的 halogen 网关)
|
||||
gateway_base_url: http://192.168.200.11:8731/v1
|
||||
gateway_model: halogen-qwen3.8-flash-next
|
||||
gateway_key: cybergril-local-test
|
||||
# 每次网关调用的硬超时(秒,HEL-889):关闭排空阶段因此有界——已被接受但
|
||||
# 长期不答的请求不会把 worker 与进程关闭无限挂住。默认 60,一般不改。
|
||||
gateway_timeout: 60
|
||||
|
||||
# 统一请求闸:产品进程会把 router 的 PersistentBudget 传给后端,SDK 内部提取
|
||||
# LLM 每次发送前在 "semantic" 类别 + 日 token 池里原子预占(models.yaml 的
|
||||
# daily_requests.semantic 与 daily_tokens 批准值生效),无需在此重复配置。
|
||||
|
||||
# 本地向量库与推导史目录(独立数据目录,随实例一起备份/回滚)
|
||||
vector_root: /absolute/path/to/sem/vec
|
||||
history_root: /absolute/path/to/sem/hist
|
||||
collection: cg_public
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-919 接续运行包 · 启停脚本离线替身检查(零真实服务、零真实端口、零出站)
|
||||
#
|
||||
# 用替身解释器(只休眠的脚本)与隔离合成档案验证 instance_ctl.sh / 守卫 /
|
||||
# 迁移工具的启停安全:非法子命令拒绝、默认关闭 start 拒绝、过期窗口拒绝、
|
||||
# 失败启动只清自己、stop 只杀身份核验过的自有句柄(外来 pid 不动手)、
|
||||
# close 只封本实例库。不启动真实 API,不监听端口,不触任何共享服务。
|
||||
#
|
||||
# 用法: bash deploy/hel919-continuation/test_ctl_scripts.sh (在检出根目录)
|
||||
set -u
|
||||
PKG=$(cd "$(dirname "$0")" && pwd)
|
||||
ROOT=$(cd "$PKG/../.." && pwd)
|
||||
TMP=$(mktemp -d /tmp/hel919-ctl-test.XXXXXX)
|
||||
PASS=0; FAIL=0
|
||||
cleanup() { rm -rf "$TMP"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
ok() { PASS=$((PASS+1)); echo "PASS $1"; }
|
||||
bad() { FAIL=$((FAIL+1)); echo "FAIL $1"; }
|
||||
expect_rc() { [ "$2" = "$1" ] && ok "$3" || bad "$3 (want rc=$1 got rc=$2)"; }
|
||||
|
||||
# ---- S1. 静态:语法 + 包文件齐全 ----
|
||||
bash -n "$PKG/instance_ctl.sh" 2>/dev/null && ok "syntax instance_ctl.sh" || bad "syntax instance_ctl.sh"
|
||||
for f in README.md manifest.json migrate_same_her.py window_guard_hel919.py \
|
||||
models.template.yaml semantic.template.yaml queue_policy.md \
|
||||
enablement-plan.md cybergril-hel919-expiry.template.service test_ctl_scripts.sh; do
|
||||
[ -f "$PKG/$f" ] && ok "package file $f" || bad "package file $f missing"
|
||||
done
|
||||
python3 -c "import sys; [compile(open(f, encoding='utf-8').read(), f, 'exec') for f in sys.argv[1:]]" \
|
||||
"$PKG/migrate_same_her.py" "$PKG/window_guard_hel919.py" \
|
||||
&& ok "compile tools" || bad "compile tools"
|
||||
|
||||
# ---- 沙盒实例布局(镜像 README §2;current 为最小代码副本) ----
|
||||
BASE=$TMP/inst; CODE=$BASE/current
|
||||
mkdir -p "$BASE/etc" "$BASE/data" "$BASE/logs" "$CODE"
|
||||
cp -a "$ROOT/deploy" "$ROOT/tools" "$ROOT/src" "$CODE/"
|
||||
CTL="$PKG/instance_ctl.sh"
|
||||
STUB=$TMP/stub-python
|
||||
printf '#!/usr/bin/env bash\nsleep 5\n' > "$STUB"; chmod +x "$STUB"
|
||||
printf 'dummy cert\n' > "$TMP/c.pem"; printf 'dummy key\n' > "$TMP/c.key"
|
||||
ENV="HEL919_BASE=$BASE HEL919_VENV=$STUB HEL919_CERT=$TMP/c.pem HEL919_KEY=$TMP/c.key HEL919_PY=python3"
|
||||
|
||||
# 合成同一位她档案 → 迁移进沙盒实例(隔离数据,零真实资料)
|
||||
python3 "$PKG/migrate_same_her.py" migrate --db "$TMP/nonexistent.db" --base "$BASE" >/dev/null 2>&1
|
||||
[ $? -ne 0 ] && ok "migrate refuses missing db" || bad "migrate missing db not refused"
|
||||
python3 - "$TMP/src.db" <<'EOF'
|
||||
import json, sqlite3, sys
|
||||
sys.path.insert(0, "src")
|
||||
from cybergril.memory.store import Store
|
||||
from cybergril.life.model import PersistentBudget
|
||||
from cybergril.think.budget import BudgetConfig, BudgetGuard
|
||||
s = Store(sys.argv[1])
|
||||
with s.conn:
|
||||
s.execute("INSERT INTO companion VALUES(1,?)", (json.dumps({"name": "替身她"}, ensure_ascii=False),))
|
||||
s.execute("INSERT INTO bazi_core VALUES(1,'{}','{}','辛','金','{}','{}',0.5,'[]',1,1)")
|
||||
s.execute("INSERT INTO persona_interp VALUES(1,'替身诠释','h','stub',1,'synthetic')")
|
||||
PersistentBudget(s, BudgetGuard(BudgetConfig())).seal()
|
||||
s.close()
|
||||
EOF
|
||||
python3 "$PKG/migrate_same_her.py" migrate --db "$TMP/src.db" --base "$BASE" >/dev/null \
|
||||
&& ok "synthetic migrate ok" || bad "synthetic migrate failed"
|
||||
cp "$PKG/models.template.yaml" "$BASE/etc/models.yaml"
|
||||
|
||||
# ---- S2. check:默认关闭核验 ----
|
||||
env $ENV bash "$CTL" check >/dev/null 2>&1; expect_rc 0 $? "check ok (all budgets 0)"
|
||||
sed -i 's/^ dialogue: 0/ dialogue: 9/' "$BASE/etc/models.yaml"
|
||||
env $ENV bash "$CTL" check >/dev/null 2>&1; expect_rc 1 $? "check refuses unapproved nonzero budget"
|
||||
env HEL919_ALLOW_BUDGET=1 $ENV bash "$CTL" check >/dev/null 2>&1; expect_rc 0 $? "check passes nonzero with explicit allow"
|
||||
cp "$PKG/models.template.yaml" "$BASE/etc/models.yaml"
|
||||
|
||||
# ---- S3. start:默认关闭 / 过期窗口拒绝(零启动) ----
|
||||
env $ENV bash "$CTL" frobnicate >/dev/null 2>&1; expect_rc 2 $? "invalid subcommand refused (rc=2)"
|
||||
[ ! -f "$BASE/logs/api.pid" ] && ok "invalid subcommand started nothing" || bad "invalid subcommand left pid file"
|
||||
env $ENV bash "$CTL" start >/dev/null 2>&1; expect_rc 1 $? "start refused without window (default closed)"
|
||||
[ ! -f "$BASE/logs/api.pid" ] && ok "refused start left no pid" || bad "refused start left pid file"
|
||||
mkwin() { # mkwin <approved 0|1> <deadline_epoch>
|
||||
printf '{"instance":"hel919","approved":%s,"deadline_epoch":%s,"authorization_comment":"synthetic"}\n' "$1" "$2" > "$BASE/window.json"
|
||||
touch "$BASE/window-active"
|
||||
}
|
||||
mkwin 1 1 # 早已过期
|
||||
env $ENV bash "$CTL" start >/dev/null 2>&1; expect_rc 1 $? "start refused with expired window"
|
||||
[ ! -f "$BASE/logs/api.pid" ] && ok "expired start left no pid" || bad "expired start left pid file"
|
||||
rm -f "$BASE/window-active" "$BASE/window.json"
|
||||
|
||||
# ---- S4. 失败启动收尾:健康不过 → 只清自己、留日志 ----
|
||||
mkwin 1 99999999999
|
||||
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 $? "failed start (no health) exits 1"
|
||||
[ ! -f "$BASE/logs/api.pid" ] && ok "failed start removed pid file" || bad "failed start left pid file"
|
||||
|
||||
# ---- S5. stop 只操作身份核验过的自有句柄 ----
|
||||
# 自有句柄:stub 以 marker 参数启动、cwd 在本实例代码目录
|
||||
pushd "$CODE" >/dev/null
|
||||
"$STUB" serve_dual_8360_8361.py --http-port 1 >/dev/null 2>&1 &
|
||||
OWN=$!
|
||||
popd >/dev/null
|
||||
sleep 0.3
|
||||
echo "$OWN" > "$BASE/logs/api.pid"
|
||||
env $ENV HEL919_DRAIN_SEC=3 bash "$CTL" stop >/dev/null 2>&1; expect_rc 0 $? "stop own verified pid"
|
||||
kill -0 "$OWN" 2>/dev/null && bad "own pid still alive" || ok "own pid stopped"
|
||||
# 外来 pid:活着但不匹配身份 → 拒绝动手,进程不受影响
|
||||
FOREIGN=$!
|
||||
( sleep 300 ) & FOREIGN=$!
|
||||
sleep 0.2
|
||||
echo "$FOREIGN" > "$BASE/logs/api.pid"
|
||||
env $ENV bash "$CTL" stop >/dev/null 2>&1; expect_rc 1 $? "stop refuses non-own live pid"
|
||||
kill -0 "$FOREIGN" 2>/dev/null && ok "foreign pid untouched" || bad "foreign pid was killed!"
|
||||
kill "$FOREIGN" 2>/dev/null
|
||||
rm -f "$BASE/logs/api.pid" "$BASE/window-active"
|
||||
|
||||
# ---- S6. close:只封本实例库;封账可核、窗口记录、幂等 ----
|
||||
env $ENV bash "$CTL" close >/dev/null 2>&1; expect_rc 0 $? "close ok (no running api)"
|
||||
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"]}))
|
||||
EOF
|
||||
[ $? -eq 0 ] && ok "close sealed THIS instance db (prior seal frozen intact)" || bad "close seal state wrong"
|
||||
python3 - "$BASE/window.json" <<'EOF'
|
||||
import json, sys
|
||||
w = json.load(open(sys.argv[1]))
|
||||
assert w.get("closed_at"), w
|
||||
EOF
|
||||
[ $? -eq 0 ] && ok "window.json records closed_at" || bad "window.json missing closed_at"
|
||||
env $ENV bash "$CTL" close >/dev/null 2>&1; expect_rc 0 $? "close idempotent"
|
||||
|
||||
# ---- S7. close 之后 start 被拒(封窗不再开门) ----
|
||||
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)"
|
||||
|
||||
echo "----"
|
||||
echo "PASS=$PASS FAIL=$FAIL"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-919 · 专属新实例启动守卫(脱敏模板;零网络、零真实调用)。
|
||||
|
||||
进程启动前拒绝一切未授权启动(ExecStartPre / instance_ctl.sh start 均调用):
|
||||
- `window-active` 标记文件不存在 → 拒绝(默认关闭,不是获批窗口不开门);
|
||||
- window.json 缺失/损坏、instance 不是 hel919、approved 不为真 → 拒绝;
|
||||
- 当前时间 ≥ deadline_epoch → 拒绝(过期窗口重启不放行:期限持久在
|
||||
window.json,进程重启不重置;新用量由库内 PersistentBudget 持久计数,
|
||||
重启同样不重置、不新增)。
|
||||
运行中到达截止由 expiry watch(instance_ctl.sh watch)有界收尾:停本实例
|
||||
进程后不存在可出站进程,满足「到期拒绝新出站」;本守卫保证此后无法重启。
|
||||
|
||||
用法: python3 window_guard_hel919.py <base 目录>
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
base = Path(sys.argv[1]) if len(sys.argv) > 1 else None
|
||||
if base is None:
|
||||
raise SystemExit("usage: window_guard_hel919.py <base>")
|
||||
if not (base / "window-active").is_file():
|
||||
raise SystemExit("hel919 window inactive: default closed")
|
||||
wp = base / "window.json"
|
||||
try:
|
||||
w = json.loads(wp.read_text())
|
||||
except Exception as exc:
|
||||
raise SystemExit(f"hel919 window unreadable: {exc}") from exc
|
||||
if w.get("instance") != "hel919":
|
||||
raise SystemExit("hel919 window: wrong instance")
|
||||
if not w.get("approved"):
|
||||
raise SystemExit("hel919 window not approved")
|
||||
if time.time() >= int(w["deadline_epoch"]):
|
||||
raise SystemExit(f"hel919 window expired at {w.get('deadline_at')}")
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"baseline_version": "1.12",
|
||||
"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",
|
||||
"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 原话,属操作裁定、非需求变更。",
|
||||
"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 拒绝",
|
||||
"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",
|
||||
"双基线需求检查通过:--base-ref origin/main 与 --base-ref 2e91a3c91e90944991886b21f7167a6913f41efb 各含本 handoff"
|
||||
],
|
||||
"deferred": [
|
||||
"实际启用(部署、写获批预算、开窗口、真实体验)归总管按 enablement-plan.md 获批后执行;本卡只交离线可执行准备,cap=0、未部署、未监听端口、未动任何现有实例与用户资料",
|
||||
"真实模型下的接续自然度(她是否'还是她')由白栖知实际体验判断;离线证据只证明接线与账目正确,不冒充体验通过",
|
||||
"语音、天气/素材、完整备份恢复、摄像头、口型等未完功能承接不变(HEL-915 正文清单继续有效);本包不做用量优化研究",
|
||||
"语义真实提取/嵌入(semantic cap>0)默认关闭;如需启用由总管按权威账现状填累计算式数值,min_used 保证冻结余额不可动"
|
||||
],
|
||||
"requirement_changes": [],
|
||||
"verification": [
|
||||
"离线证据:docs/rework/hel919/offline-run.txt(pytest 12/12 + 启停替身 34/34 实跑输出);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/手机、多日运行;均如实未验证,留待获批启用窗口由总管执行并记录"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
............ [100%]
|
||||
12 passed in 0.41s
|
||||
---- ctl drill ----
|
||||
PASS syntax instance_ctl.sh
|
||||
PASS package file README.md
|
||||
PASS package file manifest.json
|
||||
PASS package file migrate_same_her.py
|
||||
PASS package file window_guard_hel919.py
|
||||
PASS package file models.template.yaml
|
||||
PASS package file semantic.template.yaml
|
||||
PASS package file queue_policy.md
|
||||
PASS package file enablement-plan.md
|
||||
PASS package file cybergril-hel919-expiry.template.service
|
||||
PASS package file test_ctl_scripts.sh
|
||||
PASS compile tools
|
||||
PASS migrate refuses missing db
|
||||
PASS synthetic migrate ok
|
||||
PASS check ok (all budgets 0)
|
||||
PASS check refuses unapproved nonzero budget
|
||||
PASS check passes nonzero with explicit allow
|
||||
PASS invalid subcommand refused (rc=2)
|
||||
PASS invalid subcommand started nothing
|
||||
PASS start refused without window (default closed)
|
||||
PASS refused start left no pid
|
||||
PASS start refused with expired window
|
||||
PASS expired start left no pid
|
||||
PASS failed start (no health) exits 1
|
||||
PASS failed start removed pid file
|
||||
PASS stop own verified pid
|
||||
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)
|
||||
PASS window.json records closed_at
|
||||
PASS close idempotent
|
||||
PASS start refused after close (window-active removed)
|
||||
----
|
||||
PASS=34 FAIL=0
|
||||
@@ -0,0 +1,323 @@
|
||||
"""HEL-919 · 同一位她接续包离线测试(合成旧档案 + 替身,零真实调用/零网络)。
|
||||
|
||||
覆盖验收清单:
|
||||
- 空档案拒绝(不冒充同一位她接续成功);缺出生/缺诠释拒绝;
|
||||
- 非空同一档案前后保留(身份指纹、出生、记忆、聊天、生活逐表计数相等);
|
||||
- 旧 seal 与旧账不变(源库逐项核对;副本冻结为 cont_prior_*,live seal 移除),
|
||||
新计数单独可核(PersistentBudget 在副本上继续累计,重启不重置);
|
||||
- 数据目录(向量库/推导史)随实例迁移;
|
||||
- 幂等(同源 no-op)/ 不同源拒绝 / 回退精确还原;
|
||||
- window_guard:默认关闭、未批准、过期、错误实例全部拒绝,有效窗口放行;
|
||||
- 队列盘点只含数量与 ID,不含任何内容文本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cybergril.life.model import PersistentBudget
|
||||
from cybergril.memory.store import Store
|
||||
from cybergril.think.budget import BudgetConfig, BudgetGuard, BudgetStop
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PKG = ROOT / "deploy" / "hel919-continuation"
|
||||
|
||||
|
||||
def _load_migrator():
|
||||
spec = importlib.util.spec_from_file_location("migrate_same_her", PKG / "migrate_same_her.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
MIG = _load_migrator()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 合成旧档案
|
||||
|
||||
def build_synthetic_archive(path: Path, *, sealed: bool = True, seed: int = 1) -> None:
|
||||
"""隔离合成库:非空同一位她 + 旧用量 + 旧封账 + 待处理队列(无任何真实数据)。"""
|
||||
store = Store(path)
|
||||
with store.conn:
|
||||
store.execute("INSERT INTO companion VALUES(1, ?)", (json.dumps(
|
||||
{"name": f"测试她{seed}", "birth": "2001-02-03 04:05"}, ensure_ascii=False),))
|
||||
store.execute(
|
||||
"INSERT INTO bazi_core VALUES(1,'{\"y\":2001}',?,'辛','金','{}','{}',0.6,'[]',1,?)",
|
||||
(json.dumps({"year": "辛巳", "month": "庚寅", "day": "辛卯", "time": "庚寅"}), seed))
|
||||
store.execute("INSERT INTO persona_interp VALUES(1,?,?,'stub-model',1,'synthetic')",
|
||||
(f"诠释原文{seed}", f"pillars-hash-{seed}"))
|
||||
store.execute("INSERT INTO persona_seed VALUES(1,?,1,'synthetic',1)", (f"初始习惯{seed}",))
|
||||
# chat_message: id, ts, role, text, turn_id, status
|
||||
for i in range(3):
|
||||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(?,?,?,?,?)",
|
||||
(1000 + i, "user" if i % 2 == 0 else "companion",
|
||||
f"synthetic turn {seed}-{i}", f"t{seed}-{i}", "sent"))
|
||||
store.execute("INSERT INTO mem_episodic(ts,role,raw,gist,salience,accessibility) "
|
||||
"VALUES(1000,'user','合成原文','合成要点',0.5,1.0)")
|
||||
store.execute("INSERT INTO mem_relational(kind,content,first_seen,last_used,strength) "
|
||||
"VALUES('ritual','合成暗语',1,2,0.8)")
|
||||
store.execute("INSERT INTO life_event(ts,kind,content,salience,source,day_key) "
|
||||
"VALUES(1000,'scene','合成生活',0.4,'generated','2026-11-01')")
|
||||
store.execute("INSERT INTO dyad_event(id,ts,kind,summary,severity) VALUES(1,1000,'repair','合成事件',0.1)")
|
||||
# 待处理队列(只证明盘点,不含真实内容)
|
||||
store.execute("INSERT INTO chat_affect_job VALUES(3,'pending','synthetic',0,1,NULL)")
|
||||
store.execute("INSERT INTO growth_job VALUES('chat',1,'pending','synthetic',0)")
|
||||
# 旧用量 + 旧封账:走真实 PersistentBudget 路径
|
||||
cfg = BudgetConfig(daily_tokens=1_000_000,
|
||||
daily_requests={"dialogue": 10, "life": 10, "background": 10, "semantic": 10},
|
||||
total_requests=55)
|
||||
guard = PersistentBudget(store, BudgetGuard(cfg))
|
||||
hold = guard.acquire("dialogue_main", requests=1, tokens=1234)
|
||||
guard.settle(hold, actual_tokens=1000)
|
||||
if sealed:
|
||||
guard.seal()
|
||||
store.close()
|
||||
|
||||
|
||||
def build_semantic_dirs(base: Path) -> tuple[Path, Path]:
|
||||
vec, hist = base / "vec", base / "hist"
|
||||
vec.mkdir(parents=True), hist.mkdir(parents=True)
|
||||
(vec / "v.bin").write_bytes(b"synthetic-vector")
|
||||
(hist / "h.json").write_text("{}")
|
||||
return vec, hist
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def synth(tmp_path):
|
||||
src = tmp_path / "old" / "companion.db"
|
||||
build_synthetic_archive(src)
|
||||
base = tmp_path / "hel919"
|
||||
(base / "data").mkdir(parents=True)
|
||||
return src, base
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- preflight
|
||||
|
||||
def test_preflight_refuses_empty_archive(tmp_path):
|
||||
empty = tmp_path / "empty.db"
|
||||
Store(empty).close() # 全新空库:companion 表为空
|
||||
with pytest.raises(SystemExit):
|
||||
MIG.preflight(empty)
|
||||
|
||||
|
||||
def test_preflight_refuses_missing_birth(tmp_path):
|
||||
src, _ = build_partial(tmp_path, drop="bazi_core")
|
||||
with pytest.raises(SystemExit):
|
||||
MIG.preflight(src)
|
||||
|
||||
|
||||
def test_preflight_refuses_missing_persona(tmp_path):
|
||||
src, _ = build_partial(tmp_path, drop="persona_interp")
|
||||
with pytest.raises(SystemExit):
|
||||
MIG.preflight(src)
|
||||
|
||||
|
||||
def build_partial(tmp_path, *, drop: str):
|
||||
src = tmp_path / "partial.db"
|
||||
build_synthetic_archive(src, seed=2)
|
||||
conn = sqlite3.connect(src)
|
||||
with conn:
|
||||
conn.execute(f"DELETE FROM {drop}")
|
||||
conn.close()
|
||||
return src, tmp_path
|
||||
|
||||
|
||||
def test_preflection_reports_counts_and_ids_only(synth):
|
||||
src, _ = synth
|
||||
report = MIG.preflight(src)
|
||||
assert report["ok"] and report["identity"]["name"] == "测试她1"
|
||||
assert report["provenance"]["chat_message"] == 3
|
||||
assert report["queues"]["chat_affect_job"]["pending"] == 1
|
||||
assert report["queues"]["chat_affect_job"]["pending_ids"] == ["3"]
|
||||
assert report["accounting"]["sealed"]["sealed"] == 1
|
||||
# 内容不出现在任何 JSON 输出里
|
||||
blob = json.dumps(report, ensure_ascii=False)
|
||||
for secret in ("合成原文", "合成暗语", "合成生活", "诠释原文1"):
|
||||
assert secret not in blob
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- migrate
|
||||
|
||||
def _migrate(src, base, dirs=()):
|
||||
return MIG.migrate(src, base, [(str(s), rel) for s, rel in dirs])
|
||||
|
||||
|
||||
def test_migrate_preserves_same_her_and_freezes_old_ledger(synth, tmp_path):
|
||||
src, base = synth
|
||||
vec, hist = build_semantic_dirs(tmp_path / "sem")
|
||||
before_bytes = src.read_bytes()
|
||||
out = _migrate(src, base, dirs=[(vec, "sem/vec"), (hist, "sem/hist")])
|
||||
rec = out["record"]
|
||||
# 同一位她:身份指纹一致、出处逐表计数一致(自检已断言,这里独立复核)
|
||||
assert out["selfcheck"]["same_her"] and out["selfcheck"]["provenance_preserved"]
|
||||
conn = sqlite3.connect(f"file:{base/'data'/'companion.db'}?mode=ro", uri=True)
|
||||
conn.row_factory = sqlite3.Row
|
||||
assert conn.execute("SELECT count(*) n FROM companion").fetchone()["n"] == 1
|
||||
assert conn.execute("SELECT count(*) n FROM chat_message").fetchone()["n"] == 3
|
||||
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 次
|
||||
assert total["total_requests"] == 1 and total["total_tokens"] == 1000
|
||||
# 源库逐字节不变
|
||||
assert src.read_bytes() == before_bytes
|
||||
# 数据目录随实例迁移
|
||||
assert (base / "data" / "sem" / "vec" / "v.bin").read_bytes() == b"synthetic-vector"
|
||||
assert (base / "data" / "sem" / "hist" / "h.json").exists()
|
||||
assert set(rec["target"]["data_dirs"]) == {"sem/vec", "sem/hist"}
|
||||
# 迁移记录内容不含聊天/生活文本
|
||||
blob = json.dumps(rec, ensure_ascii=False)
|
||||
for secret in ("合成原文", "合成暗语", "合成生活"):
|
||||
assert secret not in blob
|
||||
|
||||
|
||||
def test_migrate_idempotent_same_source_and_refuses_different(synth, tmp_path):
|
||||
src, base = synth
|
||||
assert _migrate(src, base)["ok"]
|
||||
again = _migrate(src, base)
|
||||
assert again.get("idempotent_noop") is True
|
||||
other = tmp_path / "other.db"
|
||||
build_synthetic_archive(other, seed=9)
|
||||
with pytest.raises(SystemExit):
|
||||
_migrate(other, base)
|
||||
|
||||
|
||||
def test_rollback_restores_pre_migration_state(synth):
|
||||
src, base = synth
|
||||
# 目标已有旧库(非本工具产物)→ 备份 → 迁移 → 回退还原
|
||||
pre = base / "data" / "companion.db"
|
||||
Store(pre).close()
|
||||
assert _migrate(src, base)["ok"]
|
||||
out = MIG.rollback(base)
|
||||
assert out["ok"]
|
||||
conn = sqlite3.connect(f"file:{pre}?mode=ro", uri=True)
|
||||
assert conn.execute("SELECT count(*) n FROM companion").fetchone()[0] == 0 # 还原为迁移前的空库
|
||||
conn.close()
|
||||
assert not (base / "data" / "continuation.json").exists()
|
||||
|
||||
|
||||
def test_rollback_removes_copy_when_target_was_absent(tmp_path):
|
||||
src = tmp_path / "fresh.db"
|
||||
build_synthetic_archive(src)
|
||||
base = tmp_path / "inst"
|
||||
(base / "data").mkdir(parents=True)
|
||||
assert _migrate(src, base)["ok"]
|
||||
out = MIG.rollback(base)
|
||||
assert out["ok"] and not (base / "data" / "companion.db").exists()
|
||||
|
||||
|
||||
def test_refuse_migrate_onto_live_instance(synth):
|
||||
src, base = synth
|
||||
(base / "window-active").write_text("")
|
||||
with pytest.raises(SystemExit):
|
||||
_migrate(src, base)
|
||||
|
||||
|
||||
# ------------------------------------------------------- 新账隔离 + 重启不重置
|
||||
|
||||
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 # 旧计数保留
|
||||
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
|
||||
store.close()
|
||||
# 进程"重启":重开库,计数与期限类状态不重置
|
||||
store2 = Store(tdb, init=False)
|
||||
guard2 = PersistentBudget(store2, BudgetGuard(cfg))
|
||||
assert guard2.total_requests_used() == 2
|
||||
assert guard2.total_tokens_used() == 1400
|
||||
hold = guard2.acquire("life_event", tokens=100)
|
||||
guard2.settle(hold, actual_tokens=100)
|
||||
assert guard2.total_requests_used() == 3
|
||||
store2.close()
|
||||
# 新账封账后同样拒绝(close 路径的库内效果)
|
||||
store3 = Store(tdb, init=False)
|
||||
guard3 = PersistentBudget(store3, BudgetGuard(cfg))
|
||||
guard3.seal()
|
||||
with pytest.raises(BudgetStop):
|
||||
guard3.acquire("dialogue_main", tokens=1)
|
||||
store3.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- window guard
|
||||
|
||||
def _guard(base: Path):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(PKG / "window_guard_hel919.py"), str(base)],
|
||||
capture_output=True, text=True)
|
||||
|
||||
|
||||
def _make_window(base: Path, *, approved=True, deadline_in=3600, instance="hel919"):
|
||||
w = {"instance": instance, "approved": approved,
|
||||
"started_at": 1, "deadline_at": 2,
|
||||
"deadline_epoch": int(time.time()) + deadline_in,
|
||||
"authorization_comment": "synthetic"}
|
||||
(base / "window.json").write_text(json.dumps(w))
|
||||
(base / "window-active").write_text("")
|
||||
|
||||
|
||||
def test_window_guard_default_closed_and_expiry(synth):
|
||||
_, base = synth
|
||||
assert _guard(base).returncode != 0 # 无标记:默认关闭
|
||||
_make_window(base)
|
||||
assert _guard(base).returncode == 0 # 有效窗口放行
|
||||
_make_window(base, deadline_in=-10)
|
||||
assert _guard(base).returncode != 0 # 过期拒绝(重启不放行)
|
||||
_make_window(base, approved=False)
|
||||
assert _guard(base).returncode != 0 # 未批准拒绝
|
||||
_make_window(base, instance="other")
|
||||
assert _guard(base).returncode != 0 # 非本实例拒绝
|
||||
(base / "window.json").write_text("{broken")
|
||||
assert _guard(base).returncode != 0 # 损坏拒绝
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- CLI 通路
|
||||
|
||||
def test_cli_preflight_migrate_rollback(synth):
|
||||
src, base = synth
|
||||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||||
"preflight", "--db", str(src)],
|
||||
capture_output=True, text=True)
|
||||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||||
"migrate", "--db", str(src), "--base", str(base)],
|
||||
capture_output=True, text=True)
|
||||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||||
"migrate", "--db", str(src), "--base", str(base)],
|
||||
capture_output=True, text=True)
|
||||
assert r.returncode == 0 and json.loads(r.stdout).get("idempotent_noop")
|
||||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||||
"rollback", "--base", str(base)],
|
||||
capture_output=True, text=True)
|
||||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||||
"rollback", "--base", str(base)],
|
||||
capture_output=True, text=True)
|
||||
assert r.returncode != 0 # 无可回退:拒绝
|
||||
Reference in New Issue
Block a user