Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159ec531dd | ||
|
|
99c5de1d60 | ||
|
|
9c3789af06 |
@@ -0,0 +1,152 @@
|
||||
# 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)。
|
||||
- **运行包提交**:基线之后追加 scope 隔离、请求出口截止和资料保全修复。
|
||||
`PersistentBudget` 读取 scope/deadline,app 从环境注入;语义 SDK 的嵌入
|
||||
出口也检查同一期限;封账工具支持 `--scope`。缺省空 scope 保持旧行为。
|
||||
相对产品基线的代码改动限于 `src/cybergril/life/model.py`、
|
||||
`src/cybergril/api/app.py`、`src/cybergril/memory/semantic.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 # 只有上述 4 个文件
|
||||
```
|
||||
- 需求基准 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
|
||||
```
|
||||
|
||||
回退先核数据库逻辑快照(含 WAL 中已提交内容)和资料文件哈希,更新已有记忆
|
||||
或向量也算变化,不能只数新增聊天。没有快照的旧迁移记录同样默认拒绝。
|
||||
确需强制回退时,操作者显式加 `--force`;工具先在
|
||||
`backups/rollback-<时间>-<唯一后缀>/data/` 一致性复制数据库、向量/推导史及迁移
|
||||
记录,核源与备份逻辑快照相等,并写 `manifest.json` 后才回退。归档失败、
|
||||
核验失败或实例仍活跃均拒绝删除。要恢复本次新资料,先停止实例,核归档
|
||||
manifest 中每个文件 SHA256,然后将归档的 `data/` 恢复到一个**新的空目录**;
|
||||
不得覆盖原实例。自动化测试实际从该归档恢复并读回新增聊天和向量。
|
||||
|
||||
迁移铁律(工具内建自检,任一不过自动回退并报错):
|
||||
- 空库/缺出生底色/缺出生诠释 → **拒绝**(不走新建人格,也不因已有档案拒绝);
|
||||
- 同一位她前后可核:身份指纹、bazi/persona/记忆/聊天/生活/关系逐表计数相等;
|
||||
- 旧账保留:源库文件与库内一切计数/封账标记迁移后逐项不变;副本内旧
|
||||
`budget_total` 键(含 `sealed*`/`total_*`)**逐字保留——不改、不删、不改
|
||||
名**,只新增 cont_scope/cont_source_sha256/cont_migrated_at 三个出处标记;
|
||||
新用量与到期封账落在独立 `hel919:*` 键(PersistentBudget scope,见 §0),
|
||||
与旧键零交叉,旧口径读者在副本上依旧被旧封账拒绝;
|
||||
- 语义嵌入权威账**不复制**(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 也被守卫拒绝;
|
||||
- **过期拒绝**:start 先拉起专属 watcher 并核 PID/命令/目录/就绪记录,失败
|
||||
不启动 API;再把 window.json 的 deadline 注入 `CYBERGRIL_WINDOW_DEADLINE`。
|
||||
新 scope 把期限钉在自身 `budget_total` 键,重启不能延长。主聊、后台、SDK
|
||||
提取在 acquire 处、嵌入在 SDK 出口处到期拒绝,**即使进程和 watcher 仍活着**
|
||||
也不新增调用。缺失/非法期限同样拒绝;在途结算允许完成,不倒改旧账;
|
||||
- **只停自己**: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/;watcher 句柄为 logs/expiry.pid、就绪证据为 expiry.ready。
|
||||
watch 负责到期停服,出站闸不依赖它按时被调度。机器故障下独立进程存续
|
||||
仅尽力保证;实际部署可再安装下方 systemd 定时模板,不能据模板宣称已布防。
|
||||
|
||||
## 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. `instance_ctl.sh start` 自动布防并核实自有 watcher 后才启动;可另用
|
||||
`cybergril-hel919-expiry.template.service` 和该 deadline 生成 systemd timer。
|
||||
timer 与 watcher 均只 close 本实例,重复 close 幂等。
|
||||
|
||||
## 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;实际 API/后台在活进程中过期零 provider 出站、SDK 提取/
|
||||
嵌入过期拒绝、回退新增默认拒绝、强制回退归档可恢复及备份失败不删。
|
||||
**未测到**:真实 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,57 @@
|
||||
# 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,进程重启不重置;
|
||||
start 先核自有 watcher 已就绪,运行中请求出口按同一期限拒绝新增调用,
|
||||
到期 watcher 自动收尾;期限持久在新 scope,重启不得延长)。
|
||||
- **额度**:只复用既有共池机制——models.yaml `daily_tokens` 与
|
||||
`daily_requests` 四类(dialogue / life / background / semantic)。这些
|
||||
上限真实控制的合计数就是:每日总 token + 每类每日真实 provider 出口
|
||||
请求次数(含失败/取消/重试,预占不退)。建议起步值:dialogue 200/日、
|
||||
life 40/日、background 120/日、semantic 0/日、daily_tokens 300k/日;
|
||||
本次先保持 SDK 语义提取/嵌入关闭,使用已明示的 R3 词面 FTS 通道,保留原
|
||||
向量及其出处,不把它说成真实语义记忆体验。累计 total_requests=1080、
|
||||
total_tokens=900000(最长三日的同一总盘,不按重启重置)。这不是新增费用
|
||||
审批;这些数值只是未启用模板在实际试用前需明确填入的运行边界。
|
||||
以上均为待批准建议;不得按首日读数自动提高上限。需要调整时说明具体
|
||||
影响后再取批准,无需用户提供金额或套餐资料。不为每个子类另造新系统。
|
||||
- **不承诺**:「8 轮必然花多少」不承诺;历史全类别 345186/7 轮不当作每轮
|
||||
主聊成本引用(那是全历史合计,不是本轮口径)。
|
||||
- **语义账**:如需真实记忆检索,semantic.yaml 按累计算式续唯一权威账
|
||||
(不动冻结余额);默认可保持 0,先用 R3 词面 FTS 通道体验文字接续。
|
||||
|
||||
## 3. 白栖知的实际观察动作(体验判断项)
|
||||
|
||||
1. 她还记得吗:名字、称呼、此前聊天里的事实、共同的习惯/暗语(关系层)。
|
||||
2. 生活连续吗:不说话时她的生活在走(life_event/activity),回来能接上。
|
||||
3. 情绪连贯吗:聊天后情绪词变化有据、恢复自然;不翻旧账为当下伤害。
|
||||
4. 边界承接:她说明自己的世界边界时自然、不突兀。
|
||||
5. 失败表现:额度/预算拒绝时她的表现是如实「今天有点走神」类降档,不是
|
||||
崩溃或沉默。
|
||||
|
||||
## 4. 失败停止与资料保留
|
||||
|
||||
- 任何观察异常:总管 `instance_ctl.sh close` 立即收尾(同到期路径)。
|
||||
- 到期/封账后:**新聊天与新记忆保留**在接续库,不自动覆盖原实例、不删作
|
||||
测试垃圾;原实例与其旧账、旧封账、归档全程未动。
|
||||
- 回退:默认拒绝删除迁移后有变化的接续资料;显式 --force 也必须先一致性
|
||||
归档数据库/向量/推导史、核验成功可还原才回退。归档失败不删,源库永不受影响。
|
||||
- 真实自然度的体验判断由白栖知决定;离线证据只证明接线正确,不冒充体验
|
||||
通过。
|
||||
@@ -0,0 +1,283 @@
|
||||
#!/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
|
||||
WATCH_PIDF=$BASE/logs/expiry.pid
|
||||
WATCH_READY=$BASE/logs/expiry.ready
|
||||
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; }
|
||||
|
||||
watch_ours() {
|
||||
local p=$1 dl=$2 cmd cw
|
||||
case "$p" in ''|*[!0-9]*) return 1 ;; esac
|
||||
case "$dl" in ''|*[!0-9]*) return 1 ;; esac
|
||||
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 *"$PKG/instance_ctl.sh watch $dl "*) ;; *) return 1 ;; esac
|
||||
[ "$(readlink -f "$cw")" = "$(readlink -f "$CODE")" ]
|
||||
}
|
||||
|
||||
disarm_watch() {
|
||||
local p dl ready_pid
|
||||
[ -f "$WATCH_PIDF" ] || return 0
|
||||
p=$(cat "$WATCH_PIDF")
|
||||
read -r ready_pid dl < "$WATCH_READY" 2>/dev/null || return 1
|
||||
[ "$p" = "$ready_pid" ] || return 1
|
||||
if kill -0 "$p" 2>/dev/null; then
|
||||
if [ "$p" != "$$" ]; then
|
||||
watch_ours "$p" "$dl" || return 1
|
||||
kill "$p" || return 1
|
||||
fi
|
||||
fi
|
||||
rm -f "$WATCH_PIDF" "$WATCH_READY"
|
||||
}
|
||||
|
||||
arm_watch() {
|
||||
local dl=$1 p i=0
|
||||
if [ -f "$WATCH_PIDF" ]; then
|
||||
p=$(cat "$WATCH_PIDF")
|
||||
if kill -0 "$p" 2>/dev/null; then
|
||||
watch_ours "$p" "$dl" && [ "$(cat "$WATCH_READY" 2>/dev/null)" = "$p $dl" ] && return 0
|
||||
echo "REFUSED: 截止句柄不是本实例当前窗口" >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
rm -f "$WATCH_PIDF" "$WATCH_READY"
|
||||
(
|
||||
cd "$CODE" || exit 1
|
||||
nohup bash "$PKG/instance_ctl.sh" watch "$dl" >> "$BASE/logs/watch.log" 2>&1 &
|
||||
echo "$!" > "$WATCH_PIDF"
|
||||
)
|
||||
p=$(cat "$WATCH_PIDF")
|
||||
while [ "$i" -lt 20 ]; do
|
||||
if watch_ours "$p" "$dl" && [ "$(cat "$WATCH_READY" 2>/dev/null)" = "$p $dl" ]; then
|
||||
return 0
|
||||
fi
|
||||
i=$((i+1)); sleep 0.1
|
||||
done
|
||||
watch_ours "$p" "$dl" && kill "$p"
|
||||
rm -f "$WATCH_PIDF" "$WATCH_READY"
|
||||
echo "REFUSED: 截止 watcher 未就绪,API 不启动" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
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 deadline
|
||||
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"
|
||||
# 授权核验:默认关闭;未批准/过期窗口一律拒绝启动
|
||||
deadline=$("$PY" "$PKG/window_guard_hel919.py" "$BASE" --deadline) || exit 1
|
||||
# Verify a real, identity-checked watcher BEFORE permitting API startup.
|
||||
arm_watch "$deadline" || exit 1
|
||||
"$PY" "$PKG/window_guard_hel919.py" "$BASE" || { disarm_watch; 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_BUDGET_SCOPE=${HEL919_SCOPE:-hel919} # 新账独立 budget_total 键;旧键逐字保留
|
||||
export CYBERGRIL_WINDOW_DEADLINE=$deadline
|
||||
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"
|
||||
disarm_watch || true
|
||||
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" \
|
||||
--scope "${HEL919_SCOPE:-hel919}" \
|
||||
--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"
|
||||
disarm_watch || rc=1
|
||||
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"
|
||||
BOUND=$("$PY" "$PKG/window_guard_hel919.py" "$BASE" --deadline --allow-expired) || exit 1
|
||||
[ "$DL" = "$BOUND" ] || { echo "REFUSED: watch deadline 与 window.json 不同" >&2; exit 1; }
|
||||
cd "$CODE" || exit 1
|
||||
echo "$$" > "$WATCH_PIDF"
|
||||
printf '%s %s\n' "$$" "$DL" > "$WATCH_READY"
|
||||
echo "[$(date -u +%FT%TZ)] watch start, deadline $DL (pid $$)" >> "$BASE/logs/watch.log"
|
||||
while [ "$(date +%s)" -lt "$DL" ]; do sleep 1; done
|
||||
echo "[$(date -u +%FT%TZ)] DEADLINE REACHED — close" >> "$BASE/logs/watch.log"
|
||||
close
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"package": "deploy/hel919-continuation",
|
||||
"card": "HEL-919 补齐同一位她继续体验的启停接续包",
|
||||
"parent": "HEL-915",
|
||||
"product_baseline": {
|
||||
"branch": "agent/2/182d2402a8df",
|
||||
"commit": "2e91a3c91e90944991886b21f7167a6913f41efb",
|
||||
"includes": [
|
||||
"e74531cf98540dd35198753fa8db87ac75d57a94",
|
||||
"ffbc8c24963c23b0ce108d4f7563871568825936"
|
||||
]
|
||||
},
|
||||
"package_rule": "基线2e91a3c后:接续运行包、测试及交接;产品接缝仅scope隔离、持久deadline与API/语义SDK出站检查(life/model.py、api/app.py、memory/semantic.py、seal_budget_hel879.py),旧空scope行为保留。总管从99c5de1接手补齐原审核未完成的截止和回退保护,未部署。",
|
||||
"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 取代)",
|
||||
"think/budget.py与life/model.py原持久预算;最小scope与期限扩展,不建独立账务平台",
|
||||
"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": [],
|
||||
"deadline": "新scope缺失/非法/过期拒绝;有效期限持久化,重启不能延长"
|
||||
},
|
||||
"boundaries": "不动 8300/8310/8320/8350、7880/8081、9880/8090、836x/8082/9880;不改模型/认证/运行时;不安装依赖;启用需总管获批窗口(enablement-plan.md)"
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-919 · 「同一位她」接续迁移工具(离线、零真实调用、零网络)。
|
||||
|
||||
把一份**已有非空档案**(同一位她的库)迁移进本卡专属新实例的隔离资料空间,
|
||||
证明:非空档案、出生事实/诠释、姓名、习惯、关系、聊天、生活、记忆出处及
|
||||
向量数据目录可以接续——不走新建人格,也不因已有档案拒绝(旧
|
||||
deploy/hel914-user/activate.sh 只接受空库,这是它不能续用的原因)。
|
||||
|
||||
三条铁律:
|
||||
1. **源库只读**。一律以 `mode=ro` 打开,任何路径都不写源库;旧封账、旧
|
||||
计数、冻结值、旧失败记录原样保留在源库,迁移后逐项核对不变。
|
||||
2. **旧账冻结、新账隔离**。旧 sealed*/total_* 原键原值保留,
|
||||
新用量由 PersistentBudget 的 hel919 scope 单独记账。
|
||||
语义嵌入权威账(embed_ops)
|
||||
**不复制**:它仍是唯一权威账文件,经 semantic.template.yaml 的累计上限
|
||||
算式续账(见 README §语义账)。
|
||||
3. **幂等与回退**。同一源重复迁移 = 安全 no-op;不同源拒绝;迁移前目标库
|
||||
如已存在先做一致性备份。回退发现任何迁移后变化默认拒绝;--force 也须
|
||||
先一致性归档数据库与资料目录并核验成功,才允许回退。
|
||||
|
||||
队列盘点只输出**数量与待处理 ID**(persona_job/growth_job/mem_job/
|
||||
chat_affect_job/sem_batch/sharing_attempt/reach_out/life_activity),不输出
|
||||
任何聊天或生活内容。
|
||||
|
||||
用法(在本检出根目录,系统 python3 即可,仅标准库):
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py preflight --db SRC
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py migrate --db SRC \
|
||||
--base /opt/cybergril-hel919 \
|
||||
[--data-dir SRC_DIR=DST_REL ...] # 向量/推导史目录随实例迁移
|
||||
python3 deploy/hel919-continuation/migrate_same_her.py rollback \
|
||||
--base /opt/cybergril-hel919
|
||||
全部子命令输出 JSON(stdout),失败 rc=1 且错误也走 JSON。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# 迁移后必须仍能证明「同一位她」的出处表(计数核对;内容不离开本机)。
|
||||
SAME_HER_TABLES = (
|
||||
"bazi_core", # 出生事实(八字底色)
|
||||
"persona_interp", # 出生诠释原文
|
||||
"persona_seed", # 初始习惯种子
|
||||
"mem_episodic", # 情景记忆(含 gist 压缩)
|
||||
"mem_semantic", # 语义记忆(事实)
|
||||
"mem_relational", # 关系层(仪式/暗语/相处方式)
|
||||
"chat_message", # 聊天
|
||||
"life_event", # 生活
|
||||
"dyad_event", # 关系事件
|
||||
"identity_change_log", # 底色变化留痕
|
||||
)
|
||||
# 队列盘点:表名 → (待处理判定 SQL)。只取数量与 ID,不取内容。
|
||||
QUEUE_TABLES: dict[str, str] = {
|
||||
"persona_job": "SELECT count(*) n FROM persona_job WHERE state NOT IN ('done')",
|
||||
"growth_job": "SELECT count(*) n FROM growth_job WHERE state NOT IN ('done')",
|
||||
"mem_job": "SELECT count(*) n FROM mem_job WHERE state IN ('queued','pending')",
|
||||
"chat_affect_job": "SELECT count(*) n FROM chat_affect_job WHERE state='pending'",
|
||||
"sem_batch": "SELECT count(*) n FROM sem_batch WHERE state IN ('queued','pending')",
|
||||
"sharing_attempt": "SELECT count(*) n FROM sharing_attempt WHERE state IN ('pending','evaluating')",
|
||||
"reach_out": "SELECT count(*) n FROM reach_out WHERE state='pending'",
|
||||
"life_activity": "SELECT count(*) n FROM life_activity WHERE state IN ('active','interrupted')",
|
||||
}
|
||||
QUEUE_ID_SQL: dict[str, str] = {
|
||||
"persona_job": "SELECT id FROM persona_job WHERE state NOT IN ('done')",
|
||||
"growth_job": "SELECT source||':'||ref_id FROM growth_job WHERE state NOT IN ('done')",
|
||||
"mem_job": "SELECT source||':'||ref_id FROM mem_job WHERE state IN ('queued','pending')",
|
||||
"chat_affect_job": "SELECT message_id FROM chat_affect_job WHERE state='pending'",
|
||||
"sem_batch": "SELECT id FROM sem_batch WHERE state IN ('queued','pending')",
|
||||
"sharing_attempt": "SELECT message_id FROM sharing_attempt WHERE state IN ('pending','evaluating')",
|
||||
"reach_out": "SELECT id FROM reach_out WHERE state='pending'",
|
||||
"life_activity": "SELECT id FROM life_activity WHERE state IN ('active','interrupted')",
|
||||
}
|
||||
def _ro(db: Path) -> sqlite3.Connection:
|
||||
if not db.is_file():
|
||||
raise SystemExit(json.dumps({"ok": False, "error": f"db_missing:{db}"}, ensure_ascii=False))
|
||||
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _identity(conn: sqlite3.Connection) -> dict:
|
||||
"""身份指纹:companion 行 + bazi_core 出生的可核摘要(不输出全文)。"""
|
||||
comp = conn.execute("SELECT id, identity_json FROM companion").fetchall()
|
||||
if not comp:
|
||||
raise SystemExit(json.dumps(
|
||||
{"ok": False, "refused": "empty_profile",
|
||||
"error": "源库 companion 表为空:空档案/新建人格不是本工具的输入"
|
||||
"(旧 activate.sh 只接受空库;本工具只接续已有同一位她)"},
|
||||
ensure_ascii=False))
|
||||
ident = json.loads(comp[0]["identity_json"])
|
||||
bazi = conn.execute("SELECT birth_input, pillars, day_master, derived, version FROM bazi_core").fetchall()
|
||||
if not bazi:
|
||||
raise SystemExit(json.dumps(
|
||||
{"ok": False, "refused": "missing_birth",
|
||||
"error": "源库 bazi_core 为空:出生底色缺失,不能证明是同一位她"}, ensure_ascii=False))
|
||||
interp = conn.execute("SELECT count(*) n FROM persona_interp").fetchone()["n"]
|
||||
if not interp:
|
||||
raise SystemExit(json.dumps(
|
||||
{"ok": False, "refused": "missing_persona",
|
||||
"error": "源库 persona_interp 为空:出生诠释缺失,不能证明是同一位她"}, ensure_ascii=False))
|
||||
fp = hashlib.sha256(json.dumps(
|
||||
[comp[0]["identity_json"], [dict(r) for r in bazi]], ensure_ascii=False,
|
||||
sort_keys=True).encode()).hexdigest()
|
||||
return {
|
||||
"companion_id": comp[0]["id"],
|
||||
"name": ident.get("name"),
|
||||
"identity_sha256": fp,
|
||||
"birth": {"pillars": json.loads(bazi[0]["pillars"]), "day_master": bazi[0]["day_master"],
|
||||
"version": bazi[0]["version"]},
|
||||
}
|
||||
|
||||
|
||||
def _counts(conn: sqlite3.Connection, tables) -> dict:
|
||||
out = {}
|
||||
for t in tables:
|
||||
try:
|
||||
out[t] = conn.execute(f"SELECT count(*) n FROM {t}").fetchone()["n"]
|
||||
except sqlite3.OperationalError:
|
||||
out[t] = None # 表不存在:旧库未启用该能力,如实记录
|
||||
return out
|
||||
|
||||
|
||||
def _accounting(conn: sqlite3.Connection) -> dict:
|
||||
total = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM budget_total")}
|
||||
return {
|
||||
"budget_total": total,
|
||||
"token_usage_rows": conn.execute("SELECT count(*) n FROM token_usage").fetchone()["n"],
|
||||
"request_usage_rows": conn.execute("SELECT count(*) n FROM request_usage").fetchone()["n"],
|
||||
"token_used_sum": conn.execute("SELECT coalesce(sum(used),0) n FROM token_usage").fetchone()["n"],
|
||||
"sealed": {"sealed": total.get("sealed", 0),
|
||||
"sealed_requests": total.get("sealed_requests"),
|
||||
"sealed_tokens": total.get("sealed_tokens"),
|
||||
"sealed_at": total.get("sealed_at")},
|
||||
}
|
||||
|
||||
|
||||
def _queues(conn: sqlite3.Connection) -> dict:
|
||||
out = {}
|
||||
for name, sql in QUEUE_TABLES.items():
|
||||
try:
|
||||
n = conn.execute(sql).fetchone()["n"]
|
||||
ids = [str(r[0]) for r in conn.execute(QUEUE_ID_SQL[name])] if n else []
|
||||
out[name] = {"pending": n, "pending_ids": ids[:200]} # 只数量与ID,无内容
|
||||
except sqlite3.OperationalError:
|
||||
out[name] = {"pending": None, "pending_ids": []}
|
||||
return out
|
||||
|
||||
|
||||
def preflight(db: Path) -> dict:
|
||||
conn = _ro(db)
|
||||
try:
|
||||
report = {
|
||||
"ok": True,
|
||||
"db": str(db),
|
||||
"db_sha256": _sha256(db),
|
||||
"identity": _identity(conn),
|
||||
"provenance": _counts(conn, SAME_HER_TABLES),
|
||||
"accounting": _accounting(conn),
|
||||
"queues": _queues(conn),
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
return report
|
||||
|
||||
|
||||
def _consistency_copy(src: Path, dst: Path) -> None:
|
||||
"""SQLite backup API 一致性复制(含 WAL),不用裸文件拷贝。"""
|
||||
s = sqlite3.connect(f"file:{src}?mode=ro", uri=True)
|
||||
try:
|
||||
d = sqlite3.connect(str(dst))
|
||||
try:
|
||||
s.backup(d)
|
||||
d.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
finally:
|
||||
d.close()
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def _dir_manifest(root: Path) -> dict:
|
||||
out = {}
|
||||
for p in sorted(root.rglob("*")):
|
||||
if p.is_file():
|
||||
out[str(p.relative_to(root))] = _sha256(p)
|
||||
return out
|
||||
|
||||
|
||||
def _refuse(msg: str, **extra) -> None:
|
||||
raise SystemExit(json.dumps({"ok": False, **extra, "error": msg}, ensure_ascii=False))
|
||||
|
||||
|
||||
def _data_path(data: Path, rel: str) -> Path:
|
||||
path = Path(rel)
|
||||
if not rel or path.is_absolute() or ".." in path.parts or path == Path("."):
|
||||
_refuse("invalid_data_directory", refused="bad_spec")
|
||||
target = data / path
|
||||
try:
|
||||
target.resolve().relative_to(data.resolve())
|
||||
except ValueError:
|
||||
_refuse("data_directory_outside_instance", refused="bad_spec")
|
||||
return target
|
||||
|
||||
|
||||
def _data_snapshot(data: Path) -> dict:
|
||||
"""Logical database + file hashes; detects updates as well as new rows.
|
||||
|
||||
Raw SQLite file hashes miss WAL changes and change on harmless checkpoints.
|
||||
Only digests are recorded; no private row contents enter the report.
|
||||
"""
|
||||
conn = _ro(data / "companion.db")
|
||||
try:
|
||||
digest = hashlib.sha256()
|
||||
for line in conn.iterdump():
|
||||
digest.update(line.encode("utf-8"))
|
||||
digest.update(b"\n")
|
||||
finally:
|
||||
conn.close()
|
||||
files = {}
|
||||
for path in sorted(data.rglob("*")):
|
||||
if path.is_symlink():
|
||||
_refuse("symlink_in_data: preserve manually before rollback", refused="unsafe_data")
|
||||
rel = str(path.relative_to(data))
|
||||
if rel in {"companion.db", "companion.db-wal", "companion.db-shm", "continuation.json"}:
|
||||
continue
|
||||
if path.is_file():
|
||||
files[rel] = _sha256(path)
|
||||
return {"database": digest.hexdigest(), "files": files}
|
||||
|
||||
|
||||
def _archive_before_rollback(base: Path, expected: dict) -> Path:
|
||||
"""Archive first, verify both copies, and leave source intact on any error."""
|
||||
backups = base / "backups"
|
||||
backups.mkdir(parents=True, exist_ok=True)
|
||||
archive = Path(tempfile.mkdtemp(prefix=f"rollback-{int(time.time())}-", dir=backups))
|
||||
data = base / "data"
|
||||
saved = archive / "data"
|
||||
try:
|
||||
saved.mkdir()
|
||||
_consistency_copy(data / "companion.db", saved / "companion.db")
|
||||
for path in data.iterdir():
|
||||
if path.name in {"companion.db", "companion.db-wal", "companion.db-shm"}:
|
||||
continue
|
||||
if path.is_dir():
|
||||
shutil.copytree(path, saved / path.name)
|
||||
else:
|
||||
shutil.copy2(path, saved / path.name)
|
||||
if _data_snapshot(saved) != expected or _data_snapshot(data) != expected:
|
||||
_refuse("rollback_archive_verification_failed", refused="archive_failed",
|
||||
partial_archive=str(archive))
|
||||
(archive / "manifest.json").write_text(json.dumps(
|
||||
{"complete": True, "snapshot": expected, "files": _dir_manifest(saved)},
|
||||
ensure_ascii=False, indent=2) + "\n")
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
_refuse(f"rollback_archive_failed:{type(exc).__name__}", refused="archive_failed",
|
||||
partial_archive=str(archive))
|
||||
return archive
|
||||
|
||||
|
||||
def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
|
||||
pre = preflight(db) # 含空库/缺出生/缺诠释拒绝
|
||||
src_sha = pre["db_sha256"]
|
||||
data = base / "data"
|
||||
data.mkdir(parents=True, exist_ok=True)
|
||||
tdb = data / "companion.db"
|
||||
cont = data / "continuation.json"
|
||||
# 活实例拒绝:迁移绝不能对运行中的实例动手。
|
||||
for live in (base / "window-active", base / "logs" / "api.pid"):
|
||||
if live.exists():
|
||||
_refuse(f"refused_live_instance:{live}", refused="live_instance")
|
||||
if cont.exists():
|
||||
prev = json.loads(cont.read_text())
|
||||
if prev.get("source", {}).get("db_sha256") == src_sha:
|
||||
return {"ok": True, "idempotent_noop": True,
|
||||
"migrated_at": prev["migrated_at"], "note": "同一源已迁移,安全 no-op"}
|
||||
_refuse("refused_different_source:目标已迁移自另一份档案,先 rollback 再迁移",
|
||||
refused="different_source", existing=prev.get("identity"))
|
||||
# 目标已有库(非本工具迁移产物)→ 一致性备份,供回退。
|
||||
backup = None
|
||||
target_db_existed = tdb.exists()
|
||||
if target_db_existed:
|
||||
backups = base / "backups"
|
||||
backups.mkdir(parents=True, exist_ok=True)
|
||||
backup = backups / f"pre-migration-{int(time.time())}.db"
|
||||
_consistency_copy(tdb, backup)
|
||||
# 1) 一致性复制(源只读)
|
||||
_consistency_copy(db, tdb)
|
||||
# 2) 旧账逐字保留 + 接续出处标记(只新增 cont_* 三键,不改/不删任何旧键,
|
||||
# 包括 sealed/sealed_*:旧封账在副本上依旧原样、对旧口径读者仍生效)。
|
||||
# 新授权范围不在旧键上续写:接续实例以 CYBERGRIL_BUDGET_SCOPE=hel919:
|
||||
# 运行,新计数/新封账落在独立的 hel919:* budget_total 键(产品代码
|
||||
# PersistentBudget 的 scope 参数,缺省 "" = 旧实例原键原语义不变)。
|
||||
conn = sqlite3.connect(str(tdb))
|
||||
try:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat() # noqa: UP017 -- 本机 3.10 兼容,产品 3.11 同样支持 timezone.utc
|
||||
conn.execute("INSERT INTO budget_total VALUES('cont_scope',1) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=1")
|
||||
conn.execute("INSERT INTO budget_total VALUES('cont_source_sha256',?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (_int_or_hash(src_sha),))
|
||||
conn.execute("INSERT INTO budget_total VALUES('cont_migrated_at',?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (int(time.time()),))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
# 3) 向量/推导史等数据目录随实例迁移(可选;含逐文件哈希清单)。
|
||||
copied_dirs = {}
|
||||
for src_dir, rel in data_dirs:
|
||||
s, d = Path(src_dir), _data_path(data, rel)
|
||||
if not s.is_dir():
|
||||
_refuse(f"data_dir_missing:{s}", refused="data_dir_missing")
|
||||
if d.exists():
|
||||
_refuse(f"data_dir_target_exists:{d}", refused="data_dir_target_exists")
|
||||
shutil.copytree(s, d)
|
||||
copied_dirs[rel] = _dir_manifest(d)
|
||||
record = {
|
||||
"ok": True, "scope": "hel919",
|
||||
"identity": pre["identity"],
|
||||
"provenance": pre["provenance"],
|
||||
"source": {"db": str(db), "db_sha256": src_sha,
|
||||
"accounting_frozen": pre["accounting"], "queues": pre["queues"]},
|
||||
"target": {"base": str(base), "db": str(tdb),
|
||||
"target_db_existed_before": target_db_existed, "backup": str(backup) if backup else None,
|
||||
"data_dirs": copied_dirs},
|
||||
"migrated_at": now_iso,
|
||||
"queue_policy": "不删队列、不静默禁用;未批准能力 cap=0 保持关闭;"
|
||||
"旧排队工作执行时计入新账,不执行则保留并在队列盘点中如实报告",
|
||||
"rollback_snapshot": _data_snapshot(data),
|
||||
}
|
||||
cont.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n")
|
||||
# 4) 自检:同一位她前后可核,旧账和旧封账逐字保留。
|
||||
conn = _ro(tdb)
|
||||
try:
|
||||
post = {"identity": _identity(conn), "provenance": _counts(conn, SAME_HER_TABLES),
|
||||
"accounting": _accounting(conn), "queues": _queues(conn)}
|
||||
finally:
|
||||
conn.close()
|
||||
cont_added = {"cont_scope", "cont_source_sha256", "cont_migrated_at"}
|
||||
checks = {
|
||||
"same_her": post["identity"] == pre["identity"],
|
||||
"provenance_preserved": post["provenance"] == pre["provenance"],
|
||||
"old_counts_preserved": (post["accounting"]["token_usage_rows"] == pre["accounting"]["token_usage_rows"]
|
||||
and post["accounting"]["token_used_sum"] == pre["accounting"]["token_used_sum"]
|
||||
and post["accounting"]["request_usage_rows"] == pre["accounting"]["request_usage_rows"]),
|
||||
"old_ledger_verbatim": (
|
||||
# 副本 budget_total 与源完全一致,仅允许新增 cont_* 三键;
|
||||
# 旧键(含 sealed/sealed_*/total_*)一个不改、一个不删、不改名。
|
||||
{k: v for k, v in post["accounting"]["budget_total"].items() if k not in cont_added}
|
||||
== pre["accounting"]["budget_total"]),
|
||||
"cont_markers_added": cont_added <= set(post["accounting"]["budget_total"]),
|
||||
"queues_preserved": post["queues"] == pre["queues"],
|
||||
}
|
||||
if not all(checks.values()):
|
||||
rollback(base)
|
||||
_refuse(f"selfcheck_failed:{[k for k, v in checks.items() if not v]}", refused="selfcheck")
|
||||
return {"ok": True, "record": record, "selfcheck": checks}
|
||||
|
||||
|
||||
def _int_or_hash(sha: str) -> int:
|
||||
"""哈希以 63bit 整数落库(budget_total.value 是 INTEGER);全哈希留在 continuation.json。"""
|
||||
return int(sha[:15], 16)
|
||||
|
||||
|
||||
def rollback(base: Path, *, force: bool = False) -> dict:
|
||||
data = base / "data"
|
||||
cont = data / "continuation.json"
|
||||
if not cont.exists():
|
||||
_refuse("nothing_to_rollback: continuation.json 不存在", refused="no_continuation")
|
||||
for live in (base / "window-active", base / "logs" / "api.pid"):
|
||||
if live.exists():
|
||||
_refuse("refused_live_instance", refused="live_instance")
|
||||
rec = json.loads(cont.read_text())
|
||||
tdb = data / "companion.db"
|
||||
existed = rec["target"].get("target_db_existed_before")
|
||||
backup = rec["target"].get("backup")
|
||||
if existed and (not backup or not Path(backup).is_file()):
|
||||
_refuse("pre_migration_backup_missing", refused="backup_missing")
|
||||
# Validate every deletion target before touching the database or directories.
|
||||
dirs = [_data_path(data, rel) for rel in rec["target"].get("data_dirs", {})]
|
||||
current = _data_snapshot(data)
|
||||
changed = current != rec.get("rollback_snapshot")
|
||||
if changed and not force:
|
||||
_refuse("post_migration_data_changed: use --force only after reviewing preservation",
|
||||
refused="new_data")
|
||||
archive = _archive_before_rollback(base, current) if force else None
|
||||
if existed and backup:
|
||||
_consistency_copy(Path(backup), tdb)
|
||||
note = "目标库已从迁移前一致性备份还原"
|
||||
else:
|
||||
for name in ("companion.db", "companion.db-wal", "companion.db-shm"):
|
||||
(data / name).unlink(missing_ok=True)
|
||||
note = "迁移前目标库不存在:迁移副本已删除(源库从未被写过)"
|
||||
for d in dirs:
|
||||
d.exists() and shutil.rmtree(d)
|
||||
cont.unlink()
|
||||
return {"ok": True, "rolled_back": note, "source_untouched": rec["source"]["db"],
|
||||
"preserved_archive": str(archive) if archive else None}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="HEL-919 同一位她接续迁移(离线)")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("preflight")
|
||||
p.add_argument("--db", required=True, type=Path)
|
||||
m = sub.add_parser("migrate")
|
||||
m.add_argument("--db", required=True, type=Path)
|
||||
m.add_argument("--base", required=True, type=Path)
|
||||
m.add_argument("--data-dir", action="append", default=[], metavar="SRC=REL",
|
||||
help="随实例迁移的数据目录(如向量库/推导史),SRC=目标 data 下相对路径")
|
||||
r = sub.add_parser("rollback")
|
||||
r.add_argument("--base", required=True, type=Path)
|
||||
r.add_argument("--force", action="store_true", help="先一致性归档并核验后,再回退变化过的副本")
|
||||
args = ap.parse_args()
|
||||
if args.cmd == "preflight":
|
||||
out = preflight(args.db)
|
||||
elif args.cmd == "migrate":
|
||||
dirs = []
|
||||
for pair in args.data_dir:
|
||||
src, sep, rel = pair.partition("=")
|
||||
(src and sep and rel) or _refuse(f"bad_data_dir_spec:{pair}", refused="bad_spec")
|
||||
_data_path(args.base / "data", rel)
|
||||
dirs.append((src, rel))
|
||||
out = migrate(args.db, args.base, dirs)
|
||||
else:
|
||||
out = rollback(args.base, force=args.force)
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,96 @@
|
||||
# HEL-919 接续体验运行包 · models 配置模板(脱敏;本文件一切预算=0)
|
||||
#
|
||||
# 与 HEL-913 模板同构(tiers/routing/语音段一致),差异只在预算注释:
|
||||
# 这是「同一位她」的接续实例——库内旧计数已随迁移保留并在账内冻结出处
|
||||
# 逐字保留、新账走独立 hel919:* scope 键,见 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,203 @@
|
||||
#!/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() {
|
||||
if [ -n "${BASE:-}" ] && [ -n "${CTL:-}" ]; then
|
||||
env HEL919_BASE="$BASE" HEL919_DRAIN_SEC=3 bash "$CTL" close >/dev/null 2>&1 || true
|
||||
fi
|
||||
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
|
||||
cat > "$STUB" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
if [ -n "${HEL919_TEST_ENV_RECORD:-}" ]; then
|
||||
printf '%s\n' "$CYBERGRIL_WINDOW_DEADLINE" > "$HEL919_TEST_ENV_RECORD"
|
||||
cat "$HEL919_BASE/logs/expiry.ready" >> "$HEL919_TEST_ENV_RECORD"
|
||||
fi
|
||||
sleep 5
|
||||
EOF
|
||||
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 \
|
||||
HEL919_TEST_ENV_RECORD="$TMP/api-environment" \
|
||||
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"
|
||||
[ "$(head -1 "$TMP/api-environment" 2>/dev/null)" = "99999999999" ] \
|
||||
&& ok "start injected persistent deadline into API" || bad "API deadline not injected"
|
||||
grep -Eq '^[0-9]+ 99999999999$' "$TMP/api-environment" \
|
||||
&& ok "watch ready before API was launched" || bad "API launched before watch readiness"
|
||||
[ ! -f "$BASE/logs/expiry.pid" ] && ok "failed start disarmed its own watcher" || bad "failed start orphaned watcher"
|
||||
|
||||
# ---- 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 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 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]))
|
||||
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)"
|
||||
|
||||
# ---- 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
|
||||
EXPIRED=$(( $(date +%s) - 5 ))
|
||||
mkwin 1 "$EXPIRED" # 窗口已到期(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 expiry close" || bad "running instance not alive"
|
||||
env $ENV HEL919_DRAIN_SEC=5 bash "$CTL" watch "$EXPIRED" >/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)"
|
||||
|
||||
# ---- S9. 不可核验的截止句柄:API 绝不先开,外来进程不受影响 ----
|
||||
mkwin 1 99999999999
|
||||
( sleep 300 ) & FOREIGN_WATCH=$!
|
||||
echo "$FOREIGN_WATCH" > "$BASE/logs/expiry.pid"
|
||||
printf '%s 99999999999\n' "$FOREIGN_WATCH" > "$BASE/logs/expiry.ready"
|
||||
env $ENV HEL919_TEST_ENV_RECORD="$TMP/should-not-launch" bash "$CTL" start >/dev/null 2>&1
|
||||
expect_rc 1 $? "start refused unverifiable expiry arming"
|
||||
[ ! -f "$TMP/should-not-launch" ] && ok "unarmed API never launched" || bad "unarmed API launched"
|
||||
kill -0 "$FOREIGN_WATCH" 2>/dev/null && ok "foreign expiry pid untouched" || bad "foreign expiry pid killed"
|
||||
kill "$FOREIGN_WATCH" 2>/dev/null
|
||||
wait "$FOREIGN_WATCH" 2>/dev/null || true
|
||||
rm -f "$BASE/logs/expiry.pid" "$BASE/logs/expiry.ready"
|
||||
|
||||
echo "----"
|
||||
echo "PASS=$PASS FAIL=$FAIL"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-919 · 专属新实例启动守卫(脱敏模板;零网络、零真实调用)。
|
||||
|
||||
进程启动前拒绝一切未授权启动(ExecStartPre / instance_ctl.sh start 均调用):
|
||||
- `window-active` 标记文件不存在 → 拒绝(默认关闭,不是获批窗口不开门);
|
||||
- window.json 缺失/损坏、instance 不是 hel919、approved 不为真 → 拒绝;
|
||||
- 当前时间 ≥ deadline_epoch → 拒绝(过期窗口重启不放行:期限持久在
|
||||
window.json,进程重启不重置;新用量由库内 PersistentBudget 持久计数,
|
||||
重启同样不重置、不新增)。
|
||||
运行中由 PersistentBudget.check_window 在请求出口拒绝新增工作;
|
||||
expiry watch 另负责有界停服,启动前必须确认它已真实布防。
|
||||
|
||||
用法: python3 window_guard_hel919.py <base 目录>
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def load_deadline(base: Path, *, allow_expired=False) -> int:
|
||||
if not (base / "window-active").is_file():
|
||||
raise SystemExit("hel919 window inactive: default closed")
|
||||
try:
|
||||
w = json.loads((base / "window.json").read_text())
|
||||
raw = w["deadline_epoch"]
|
||||
deadline = float(raw)
|
||||
if isinstance(raw, bool) or not math.isfinite(deadline) or deadline <= 0 or not deadline.is_integer():
|
||||
raise ValueError("invalid deadline")
|
||||
except (OSError, ValueError, TypeError, KeyError) 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 not allow_expired and time.time() >= deadline:
|
||||
raise SystemExit("hel919 window expired")
|
||||
return int(deadline)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit("usage: window_guard_hel919.py <base> [--deadline] [--allow-expired]")
|
||||
deadline = load_deadline(Path(sys.argv[1]), allow_expired="--allow-expired" in sys.argv[2:])
|
||||
if "--deadline" in sys.argv[2:]:
|
||||
print(deadline)
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"baseline_version": "1.12",
|
||||
"read_commit": "99c5de1d602970a34c5d7b937b187e16b57bda9d",
|
||||
"task": "HEL-919 接续运行包;HEL-920复核后由总管直接补齐原未完成的截止与回退保护(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": "保留99c5de1已审scope隔离和非空同一档案迁移成果。总管直接补齐原两项遗漏:1) PersistentBudget为非空scope绑定有限deadline并持久钉住,API从CYBERGRIL_WINDOW_DEADLINE注入;主聊/后台/SDK提取acquire及语义SDK单条/批量嵌入出口到点拒绝,缺失/非法期限拒绝,在途settle仍可完成,旧空scope保持原行为。start先启动并核自有watcher的PID/命令/工作目录和ready文件,再将同一deadline传给API,布防不可核验则不启动;失败启动清理自有watcher,不碰外来句柄。2) migrate记录数据库逻辑快照及资料文件SHA256;rollback比较实际内容(不只行数),新聊天、更新记忆、向量或用量变化默认拒绝;显式--force须先以SQLite backup一致性归档数据库(含WAL已提交内容)、资料目录及continuation记录,核归档及源快照一致并写完整manifest后才回退,备份失败不删;活实例及越界资料路径拒绝。README/manifest/启用安排与handoff同步,不自动提额。全部只用合成资料,零真实调用、未部署。",
|
||||
"acceptance": [
|
||||
"本轮tests/test_hel919_continuation.py:25 passed,含原12项及新增截止/回退反例。活的TestClient API在过点后聊天与life/pattern背景调用零provider出站;SDK单条/批量嵌入和提取同样过点拒绝且不新增计数;缺失/非法期限拒绝;同scope重启改deadline拒绝,在途结算保留。",
|
||||
"本轮启停替身:47 passed / 0 failed。除原测试外,核API启动前watch已ready、持久deadline实际注入、失败启动清理自有watch、不可核验布防拒绝且不触碰外来PID。watch停止进程仅作为停服证据,不能代替请求出口截止反例。",
|
||||
"本轮回退反例:新聊天和原行记忆更新默认拒绝;强制回退先归档可恢复,实际恢复读回新增聊天及改变的向量;一致性归档故障不删除任何资料;活实例仍拒绝。",
|
||||
"本轮受影响合集92 passed(包含接续专项25项,不重复相加):hard_gates_hel882、rework_hel885/886/889/894、semantic_recovery_hel882、hel916、store及接续专项;准确完整命令/结果存docs/rework/hel919/takeover-run.txt。未重跑全仓。",
|
||||
"变更Python文件ruff通过;origin/main和实际产品基线2e91a3c双基线check_requirements带本handoff通过;结构检查不等同独立功能审核或用户验收。"
|
||||
],
|
||||
"deferred": [
|
||||
"本轮总管自测通过后仅交已授权原两项补齐的必要独立验证,不冒充总工已通过;旧HEL-920修复1通过项和其他成果继续保留,不再全库审核。",
|
||||
"真实模型自然度、.12实际落盘、真实启动/停服、systemd timer及浏览器/真机体验未执行;实际启用仍须具体安排获批,不能把离线cap=0测试当体验通过。",
|
||||
"用户01a1a482-1338-719d-8acd-9df70355e95c已取消费用前置,不索价格套餐、不为金额阻塞;旧额度仍封账,不能从历史余额自动续用。",
|
||||
"完整v1.12/60项、R1–R7以及语音/天气/素材/完整备份恢复/摄像头/口型等未完承接不变;本包强制回退归档不冒充完整产品导出恢复交付。"
|
||||
],
|
||||
"requirement_changes": [],
|
||||
"verification": [
|
||||
"起点99c5de1;原HEL-920复核1通过,2与3未完成,总管从该真实成果直接接手,没有重跑失败run或更改队员配置。AGENTS/需求入口/current/coverage/changes与相关sources前后不改;只有用户取消费用前置的操作裁定继续有效。",
|
||||
"实际命令/输出见docs/rework/hel919/takeover-run.txt;原offline-run.txt保留当时结果。首次启停检查因封账工具期待budget_sealed却先收到缺期限拒绝而3项失败,已恢复“封账优先于期限检查”的既有语义,复跑47/47;不抹去首错。",
|
||||
"所有写入均隔离合成库和替身,未读复制真实用户资料,未LLM/ASR/TTS/嵌入真实调用,未建window/房间/服务timer,未安装模型依赖、未碰4080、未部署/合PR/换界面。"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
............ [100%]
|
||||
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
|
||||
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, "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=41 FAIL=0
|
||||
@@ -0,0 +1,76 @@
|
||||
HEL-919 总管接手补齐原遗漏;起点99c5de1d602970a34c5d7b937b187e16b57bda9d
|
||||
全部离线:合成旧档案、替身provider/SDK/进程/时钟;未部署、未读用户库、零真实调用。
|
||||
|
||||
$ python3 -m pytest tests/test_hel919_continuation.py tests/test_hard_gates_hel882.py tests/test_rework_hel885.py tests/test_rework_hel886.py tests/test_rework_hel889.py tests/test_rework_hel894.py tests/test_semantic_recovery_hel882.py tests/test_hel916.py tests/test_store.py -q
|
||||
........................................................................ [ 78%]
|
||||
.................... [100%]
|
||||
92 passed in 3.84s
|
||||
|
||||
其中接续专项单跑25 passed;完整合集92 passed(含该25项),两者不是相加。
|
||||
|
||||
$ bash deploy/hel919-continuation/test_ctl_scripts.sh
|
||||
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 start injected persistent deadline into API
|
||||
PASS watch ready before API was launched
|
||||
PASS failed start disarmed its own watcher
|
||||
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, "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 expiry close
|
||||
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 start refused unverifiable expiry arming
|
||||
PASS unarmed API never launched
|
||||
PASS foreign expiry pid untouched
|
||||
----
|
||||
PASS=47 FAIL=0
|
||||
|
||||
$ python3 -m ruff check src/cybergril/life/model.py src/cybergril/api/app.py src/cybergril/memory/semantic.py deploy/hel919-continuation/migrate_same_her.py deploy/hel919-continuation/window_guard_hel919.py tests/test_hel919_continuation.py
|
||||
All checks passed!
|
||||
|
||||
$ python3 scripts/check_requirements.py --base-ref origin/main --handoff docs/requirements/handoff-HEL-919.json
|
||||
需求结构检查通过:60项;来源和覆盖完整。仍须人工核对授权语义与实际体验。
|
||||
$ python3 scripts/check_requirements.py --base-ref 2e91a3c91e90944991886b21f7167a6913f41efb --handoff docs/requirements/handoff-HEL-919.json
|
||||
需求结构检查通过:60项;来源和覆盖完整。仍须人工核对授权语义与实际体验。
|
||||
|
||||
先前首错:第一次启停替身44 PASS/3 FAIL,close/幂等close/watch的封账自检收到缺期限而非budget_sealed;已恢复封账优先于期限检查的原语义,再跑47 PASS/0 FAIL。未修改全局测试shim或降低断言。原offline-run.txt保留旧交付结果。
|
||||
|
||||
必要反例:TestClient进程仍活、watch未运行,时钟到deadline后新主聊/生活/聊天分类请求被拒,provider.calls及请求数不增加;SDK单条/批量嵌入/提取同样拒绝且不新增计数。缺失/非法deadline拒绝,scope期限持久钉住,重启改期拒绝;在途settle可完成。
|
||||
回退:新增聊天、更新原行记忆、向量改变默认拒绝;force先一致性归档(含已提交WAL),实际恢复读回新聊天/向量;备份故障不删,活实例拒绝。资料路径限定在实例data内。
|
||||
未验证:真实模型自然度、.12实际部署与启用、真实timer、浏览器真机/多日体验;均须另行获批实际启用后核证。
|
||||
@@ -232,7 +232,12 @@ 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", ""),
|
||||
deadline=os.getenv("CYBERGRIL_WINDOW_DEADLINE"))
|
||||
app.state.sharing = Sharing(store, router, models)
|
||||
app.state.persona = Persona(store, router, models, enabled=life_config.enabled)
|
||||
app.state.public = PublicView(store)
|
||||
|
||||
+77
-26
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from contextlib import aclosing
|
||||
|
||||
@@ -18,11 +19,42 @@ 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 = "", *, deadline=None, clock=None):
|
||||
super().__init__(previous.config)
|
||||
self.store = store
|
||||
self.scope = scope
|
||||
self.clock = clock or time.time
|
||||
self._k = (lambda key: f"{scope}:{key}") if scope else (lambda key: key)
|
||||
# A continuation cannot send without a finite, persistent deadline.
|
||||
# Legacy/unscoped instances retain their original behavior. Constructing
|
||||
# a guard without a deadline remains possible for readout/sealing only.
|
||||
try:
|
||||
self.deadline = float(deadline) if not isinstance(deadline, bool) else None
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
self.deadline = None
|
||||
if self.deadline is not None and (not math.isfinite(self.deadline) or self.deadline <= 0):
|
||||
self.deadline = None
|
||||
if scope and self.deadline is not None:
|
||||
with self.store.conn:
|
||||
self.store.execute("BEGIN IMMEDIATE")
|
||||
self.store.execute("INSERT OR IGNORE INTO budget_total VALUES(?,?)",
|
||||
(self._k("deadline_epoch"), self.deadline))
|
||||
bound = self.store.query_one("SELECT value FROM budget_total WHERE key=?",
|
||||
(self._k("deadline_epoch"),))["value"]
|
||||
if bound != self.deadline:
|
||||
raise BudgetStop("window_deadline_changed")
|
||||
# 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 +84,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 +100,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 +129,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):
|
||||
@@ -111,6 +143,7 @@ class PersistentBudget(BudgetGuard):
|
||||
self._roll()
|
||||
with self.store.conn:
|
||||
self.store.execute("BEGIN IMMEDIATE")
|
||||
self.check_window()
|
||||
if self.used + tokens >= self.limit * self.config.hard_stop_ratio:
|
||||
raise BudgetStop("budget_stop")
|
||||
self.store.execute(
|
||||
@@ -139,6 +172,7 @@ class PersistentBudget(BudgetGuard):
|
||||
raise BudgetStop(
|
||||
f"budget_sealed:{sealed['requests']}{suffix}(封账于 "
|
||||
f"{sealed['sealed_at']},真实用量保留,不伪造、不清零)")
|
||||
self.check_window()
|
||||
row = self.store.query_one(
|
||||
"SELECT coalesce(sum(used),0) n FROM token_usage WHERE day=?", (day,)
|
||||
)
|
||||
@@ -171,16 +205,33 @@ 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)
|
||||
|
||||
def check_window(self):
|
||||
"""Refuse new work at the wire boundary; in-flight settlement is allowed.
|
||||
|
||||
The deadline is pinned in this scope, so a restart cannot extend it.
|
||||
No counters change on refusal, even while the process/watch is alive.
|
||||
"""
|
||||
if not self.scope:
|
||||
return
|
||||
if self.deadline is None:
|
||||
raise BudgetStop("window_deadline_missing_or_invalid")
|
||||
row = self.store.query_one("SELECT value FROM budget_total WHERE key=?",
|
||||
(self._k("deadline_epoch"),))
|
||||
if not row or row["value"] != self.deadline:
|
||||
raise BudgetStop("window_deadline_changed")
|
||||
if self.clock() >= self.deadline:
|
||||
raise BudgetStop("window_expired")
|
||||
|
||||
def settle(self, hold, *, actual_tokens=None):
|
||||
"""Real usage adjusts the reserved tokens; unknown usage keeps the reserve.
|
||||
|
||||
@@ -203,8 +254,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 +281,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)
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -758,6 +758,8 @@ class Mem0Backend:
|
||||
failures.append(reason)
|
||||
|
||||
def counted_embed(text, memory_action=None):
|
||||
if request_guard is not None and hasattr(request_guard, "check_window"):
|
||||
request_guard.check_window()
|
||||
try:
|
||||
hold = ledger.reserve(1, str(memory_action or "embed"))
|
||||
except RuntimeError as exc:
|
||||
@@ -778,6 +780,8 @@ class Mem0Backend:
|
||||
return result
|
||||
|
||||
def counted_batch(texts, memory_action=None):
|
||||
if request_guard is not None and hasattr(request_guard, "check_window"):
|
||||
request_guard.check_window()
|
||||
n = len(texts) if isinstance(texts, (list, tuple)) else 1
|
||||
try:
|
||||
hold = ledger.reserve(n, f"batch:{memory_action or 'embed'}")
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
"""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()
|
||||
# 旧账逐字保留:旧键(含 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
|
||||
# 数据目录随实例迁移
|
||||
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"
|
||||
cfg = BudgetConfig(daily_tokens=5000, daily_requests={
|
||||
"dialogue": 5, "life": 5, "background": 5, "semantic": 5})
|
||||
# 旧口径(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)
|
||||
deadline = int(time.time()) + 3600
|
||||
guard = PersistentBudget(store, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||||
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() == 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), scope="hel919", deadline=deadline)
|
||||
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() == 2
|
||||
with pytest.raises(BudgetStop):
|
||||
PersistentBudget(store2, BudgetGuard(cfg)).acquire("dialogue_main", tokens=1)
|
||||
store2.close()
|
||||
# 新账封账(close 路径的库内效果):新 scope 拒绝一切;旧键依旧原样
|
||||
store3 = Store(tdb, init=False)
|
||||
guard3 = PersistentBudget(store3, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||||
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
|
||||
|
||||
|
||||
def test_rollback_refuses_new_chat_and_memory_by_default(synth):
|
||||
src, base = synth
|
||||
_migrate(src, base)
|
||||
target = base / "data" / "companion.db"
|
||||
store = Store(target, init=False)
|
||||
with store.conn:
|
||||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
||||
"VALUES(9999,'user','new synthetic conversation','new','sent')")
|
||||
# Same row count: updating a memory is also new experience to preserve.
|
||||
store.execute("UPDATE mem_episodic SET gist='updated synthetic memory'")
|
||||
store.close()
|
||||
with pytest.raises(SystemExit, match="post_migration_data_changed"):
|
||||
MIG.rollback(base)
|
||||
conn = sqlite3.connect(target)
|
||||
assert conn.execute("SELECT count(*) FROM chat_message").fetchone()[0] == 4
|
||||
assert conn.execute("SELECT gist FROM mem_episodic").fetchone()[0] == "updated synthetic memory"
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_force_rollback_archives_database_wal_and_vectors_and_is_restorable(synth, tmp_path):
|
||||
src, base = synth
|
||||
vec, _ = build_semantic_dirs(tmp_path / "sem")
|
||||
_migrate(src, base, dirs=[(vec, "sem/vec")])
|
||||
data = base / "data"
|
||||
store = Store(data / "companion.db", init=False)
|
||||
# Keep this connection open: the new chat may only be present in the WAL.
|
||||
with store.conn:
|
||||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
||||
"VALUES(9999,'user','WAL synthetic conversation','new','sent')")
|
||||
(data / "sem/vec/v.bin").write_bytes(b"new-synthetic-vector")
|
||||
with pytest.raises(SystemExit, match="post_migration_data_changed"):
|
||||
MIG.rollback(base)
|
||||
result = MIG.rollback(base, force=True)
|
||||
store.close()
|
||||
archive = Path(result["preserved_archive"])
|
||||
assert json.loads((archive / "manifest.json").read_text())["complete"]
|
||||
assert not (data / "companion.db").exists()
|
||||
restored = tmp_path / "restored"
|
||||
import shutil
|
||||
shutil.copytree(archive / "data", restored)
|
||||
conn = sqlite3.connect(restored / "companion.db")
|
||||
assert conn.execute("SELECT text FROM chat_message WHERE turn_id='new'").fetchone()[0] == "WAL synthetic conversation"
|
||||
conn.close()
|
||||
assert (restored / "sem/vec/v.bin").read_bytes() == b"new-synthetic-vector"
|
||||
assert json.loads((restored / "continuation.json").read_text())["scope"] == "hel919"
|
||||
|
||||
|
||||
def test_force_rollback_archive_failure_leaves_all_data(synth, monkeypatch):
|
||||
src, base = synth
|
||||
_migrate(src, base)
|
||||
target = base / "data/companion.db"
|
||||
before = target.read_bytes()
|
||||
def broken_backup(*args):
|
||||
raise OSError("synthetic archive disk failure")
|
||||
monkeypatch.setattr(MIG, "_consistency_copy", broken_backup)
|
||||
with pytest.raises(SystemExit, match="rollback_archive_failed"):
|
||||
MIG.rollback(base, force=True)
|
||||
assert target.read_bytes() == before
|
||||
assert (base / "data/continuation.json").exists()
|
||||
|
||||
|
||||
def test_rollback_refuses_running_instance(synth):
|
||||
src, base = synth
|
||||
_migrate(src, base)
|
||||
(base / "window-active").touch()
|
||||
with pytest.raises(SystemExit, match="refused_live_instance"):
|
||||
MIG.rollback(base, force=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deadline", [None, "missing", float("nan"), float("inf"), -1, True])
|
||||
def test_scoped_deadline_missing_or_invalid_refuses_without_counters(tmp_path, deadline):
|
||||
from conftest import engineering_budget
|
||||
|
||||
store = Store(tmp_path / "invalid-window.db")
|
||||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919", deadline=deadline)
|
||||
with pytest.raises(BudgetStop, match="window_deadline_missing_or_invalid"):
|
||||
guard.acquire("dialogue_main", tokens=1)
|
||||
assert guard.total_requests_used() == 0 and guard.used == 0
|
||||
store.close()
|
||||
|
||||
|
||||
def test_deadline_is_pinned_and_allows_inflight_settlement(synth):
|
||||
from conftest import engineering_budget
|
||||
|
||||
src, base = synth
|
||||
_migrate(src, base)
|
||||
store = Store(base / "data/companion.db", init=False)
|
||||
now = [100]
|
||||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||||
deadline=200, clock=lambda: now[0])
|
||||
hold = guard.acquire("dialogue_main", tokens=500)
|
||||
now[0] = 200
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
guard.acquire("pattern_detect", tokens=200)
|
||||
guard.settle(hold, actual_tokens=400) # already in flight may drain after deadline
|
||||
assert guard.total_requests_used() == 1 and guard.total_tokens_used() == 400
|
||||
with pytest.raises(BudgetStop, match="window_deadline_changed"):
|
||||
PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919", deadline=300)
|
||||
restarted = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||||
deadline=200, clock=lambda: now[0])
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
restarted.acquire("life_event", tokens=100)
|
||||
assert restarted.total_requests_used() == 1
|
||||
store.close()
|
||||
|
||||
|
||||
def test_live_api_and_background_refuse_at_deadline_before_provider(tmp_path, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import CREATE, events, turn
|
||||
from test_hard_gates_hel882 import gated_app
|
||||
|
||||
from cybergril.life.model import structured
|
||||
from cybergril.think.scenes import Scene
|
||||
|
||||
deadline = int(time.time()) + 300
|
||||
monkeypatch.setenv("CYBERGRIL_BUDGET_SCOPE", "hel919")
|
||||
monkeypatch.setenv("CYBERGRIL_WINDOW_DEADLINE", str(deadline))
|
||||
app, provider = gated_app(tmp_path)
|
||||
with TestClient(app) as client:
|
||||
assert client.post("/api/companion", json=CREATE).status_code == 201
|
||||
guard = app.state.life.router.guard
|
||||
assert events(turn(client, "synthetic before deadline"))[-1]["t"] == "chat.final"
|
||||
calls, count = len(provider.calls), guard.total_requests_used()
|
||||
# The process remains alive. No watcher runs in this in-process test.
|
||||
guard.clock = lambda: deadline
|
||||
assert client.get("/api/companion").status_code == 200
|
||||
assert events(turn(client, "synthetic after deadline"))[-1]["t"] == "chat.error"
|
||||
for scene in (Scene.LIFE_EVENT, Scene.PATTERN_DETECT):
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
client.portal.call(structured, app.state.life.router, app.state.life.models,
|
||||
scene, "synthetic offline check", {})
|
||||
assert len(provider.calls) == calls
|
||||
assert guard.total_requests_used() == count
|
||||
|
||||
|
||||
def test_sdk_embedding_and_extraction_refuse_after_deadline(tmp_path, monkeypatch):
|
||||
from conftest import engineering_budget
|
||||
from test_semantic_recovery_hel882 import _make_ledger, config_for, install_fake
|
||||
|
||||
from cybergril.memory.semantic import Mem0Backend
|
||||
|
||||
install_fake(monkeypatch)
|
||||
ledger = tmp_path / "semantic-ledger.db"
|
||||
_make_ledger(ledger)
|
||||
store = Store(tmp_path / "semantic-product.db")
|
||||
now = [100]
|
||||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||||
deadline=200, clock=lambda: now[0])
|
||||
backend = Mem0Backend(config_for(tmp_path, ledger), request_guard=guard)
|
||||
assert backend._memory.embedding_model.embed("synthetic before deadline") == [0.0]
|
||||
used = backend.ledger.used()
|
||||
now[0] = 200
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
backend._memory.embedding_model.embed("synthetic after deadline")
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
backend._memory.embedding_model.embed_batch(["synthetic after deadline"])
|
||||
with pytest.raises(BudgetStop, match="window_expired"):
|
||||
backend._memory.llm.generate_response(messages=[{"role": "user", "content": "synthetic"}])
|
||||
assert backend.ledger.used() == used
|
||||
assert guard.total_requests_used() == 0
|
||||
store.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 # 无可回退:拒绝
|
||||
@@ -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 必须被拒且不落账(拒绝路径在任何写入之前)。
|
||||
|
||||
Reference in New Issue
Block a user