HEL-914: supervise approved user trial and enforce its absolute expiry

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-30 11:33:29 +08:00
co-authored by multica-agent
parent d300d87092
commit e74531cf98
8 changed files with 210 additions and 2 deletions
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Authorized once by HEL-797 comment 01a18a81-21fd-7322-b2c7-295c3fa517aa.
# Install the deadline FIRST, then start the empty user instance. No model probe.
set -euo pipefail
[ "$#" -eq 0 ] || { echo "No deadline override: this command opens only the approved three-day window" >&2; exit 2; }
BASE=/opt/cybergril-hel913
UNIT=cybergril-hel913-user
if systemctl is-active --quiet "$UNIT.service" || [ -f "$BASE/window-active" ]; then
echo 'REFUSED: user window already active; no second activation' >&2; exit 1
fi
"$BASE/venv311/bin/python" - "$BASE" <<'PY'
import pathlib,sqlite3,sys
b=pathlib.Path(sys.argv[1]);p=b/'data/companion.db'
if p.exists():
c=sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True)
if c.execute('select count(*) from companion').fetchone()[0]:
raise SystemExit('REFUSED: an existing companion must not be reinitialized')
c.close()
PY
cp "$BASE/etc/models.yaml" "$BASE/etc/models-before-activation.yaml"
failed() {
rm -f "$BASE/window-active"
systemctl stop "$UNIT.service" "$UNIT-expiry.timer" || true
systemctl disable "$UNIT.service" "$UNIT-expiry.timer" || true
cp "$BASE/etc/models-before-activation.yaml" "$BASE/etc/models.yaml"
echo 'Activation failed; owned instance stopped, previous budget restored; logs preserved' >&2
}
trap failed ERR
"$BASE/venv311/bin/python" - "$BASE" <<'PY'
import datetime,json,pathlib,sys,zoneinfo
b=pathlib.Path(sys.argv[1]);tz=zoneinfo.ZoneInfo('Asia/Shanghai')
now=datetime.datetime.now(tz)
end=datetime.datetime.combine(now.date()+datetime.timedelta(days=3),datetime.time(),tzinfo=tz)
w={'approved':True,'authorization_comment':'01a18a81-21fd-7322-b2c7-295c3fa517aa','started_at':now.isoformat(),'deadline_at':end.isoformat(),'deadline_epoch':int(end.timestamp())}
(b/'window.json').write_text(json.dumps(w,indent=2)+'\n');(b/'window.json').chmod(0o600)
calendar=end.astimezone(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
p=pathlib.Path('/etc/systemd/system/cybergril-hel913-user-expiry.timer')
p.write_text('[Unit]\nDescription=Deadline of approved CyberGril first-use window\n\n[Timer]\nOnCalendar='+calendar+'\nPersistent=true\nUnit=cybergril-hel913-user-expiry.service\n\n[Install]\nWantedBy=timers.target\n')
PY
install -m 644 "$BASE/ops/$UNIT.service" /etc/systemd/system/
install -m 644 "$BASE/ops/$UNIT-expiry.service" /etc/systemd/system/
systemd-analyze verify "/etc/systemd/system/$UNIT.service" "/etc/systemd/system/$UNIT-expiry.service" "/etc/systemd/system/$UNIT-expiry.timer"
systemctl daemon-reload
systemctl enable --now "$UNIT-expiry.timer"
systemctl is-active --quiet "$UNIT-expiry.timer"
next=$(systemctl show "$UNIT-expiry.timer" -p NextElapseUSecRealtime --value)
[ -n "$next" ] && [ "$next" != n/a ]
install -m 600 "$BASE/etc/models-user-approved.yaml" "$BASE/etc/models.yaml.next"
mv "$BASE/etc/models.yaml.next" "$BASE/etc/models.yaml"
touch "$BASE/window-active"
systemctl enable --now "$UNIT.service"
ready=0
for attempt in $(seq 1 20); do
if curl --fail --silent --max-time 2 http://127.0.0.1:8360/api/health > "$BASE/logs/user-activation-health.json"; then ready=1; break; fi
sleep 1
done
[ "$ready" = 1 ]
"$BASE/venv311/bin/python" - "$BASE/logs/user-activation-health.json" <<'PY'
import json,sys
h=json.load(open(sys.argv[1]))
assert h['ok'] and h['llm']['ok'] and not h['companion_created']
print('PASS: empty user instance ready, model routes configured; no model probe sent')
PY
trap - ERR
cat "$BASE/window.json"
systemctl list-timers "$UNIT-expiry.timer" --no-pager
@@ -0,0 +1,9 @@
[Unit]
Description=Close CyberGril first-use window and preserve records
[Service]
Type=oneshot
ExecStart=/usr/bin/bash /opt/cybergril-hel913/ops/stop.sh
TimeoutStartSec=180
StandardOutput=append:/opt/cybergril-hel913/logs/user-expiry.log
StandardError=append:/opt/cybergril-hel913/logs/user-expiry.log
@@ -0,0 +1,36 @@
[Unit]
Description=CyberGril approved first-use instance
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=3
[Service]
Type=exec
WorkingDirectory=/opt/cybergril-hel913/current
Environment=TZ=Asia/Shanghai
Environment=PYTHONPATH=/opt/cybergril-hel913/current/src
Environment=CYBERGRIL_DB=/opt/cybergril-hel913/data/companion.db
Environment=CYBERGRIL_MODELS=/opt/cybergril-hel913/etc/models.yaml
Environment=CYBERGRIL_VOICE_CONFIG=/opt/cybergril-hel913/etc/voice.yaml
Environment=CYBERGRIL_WEB=/opt/cybergril-hel913/current/web/dist
Environment=CYBERGRIL_SEMANTIC=mem0
Environment=CYBERGRIL_SEMANTIC_CONFIG=/opt/cybergril-hel913/etc/semantic.yaml
Environment=CYBERGRIL_R2_ENABLED=1
Environment=CYBERGRIL_LIFE_TIMEZONE=Asia/Shanghai
Environment=MEM0_TELEMETRY=False
Environment=FASTEMBED_CACHE_PATH=/opt/cybergril-hel913/data/sem/fastembed-cache
Environment=HF_HUB_OFFLINE=1
Environment=TRANSFORMERS_OFFLINE=1
ExecStartPre=/opt/cybergril-hel913/venv311/bin/python /opt/cybergril-hel913/ops/window_guard.py /opt/cybergril-hel913/window.json
ExecStart=/opt/cybergril-hel913/venv311/bin/python deploy/voice/serve_dual_8360_8361.py --http-port 8360 --https-port 8361 --cert /opt/cybergril-voice-certs/cybergril-voice.pem --key /opt/cybergril-voice-certs/cybergril-voice.key
ExecStartPost=/usr/bin/bash -c 'echo "$MAINPID" > /opt/cybergril-hel913/logs/api.pid'
Restart=on-failure
RestartSec=3
TimeoutStopSec=30
KillMode=mixed
StandardOutput=append:/opt/cybergril-hel913/logs/api.log
StandardError=append:/opt/cybergril-hel913/logs/api.log
[Install]
WantedBy=multi-user.target
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Close only this window; preserve user data and all accounting history.
set -u
BASE=/opt/cybergril-hel913
UNIT=cybergril-hel913-user
rc=0
rm -f "$BASE/window-active"
HEL913_BASE="$BASE" bash "$BASE/current/deploy/hel913-unified/force_end.template.sh" now || rc=1
systemctl stop "$UNIT.service" || rc=1
systemctl disable "$UNIT.service" || rc=1
systemctl stop "$UNIT-expiry.timer" || rc=1
systemctl disable "$UNIT-expiry.timer" || rc=1
if [ -f "$BASE/data/companion.db" ]; then
"$BASE/venv311/bin/python" "$BASE/current/tools/seal_budget_hel879.py" --db "$BASE/data/companion.db" --reason 'approved first-use window closed' || rc=1
"$BASE/venv311/bin/python" "$BASE/current/tools/release_snapshot_hel896.py" snapshot --name "user-window-$(date -u +%Y%m%dT%H%M%SZ)" --db "$BASE/data/companion.db" --file "$BASE/data" --out "$BASE/archives" || rc=1
fi
"$BASE/venv311/bin/python" - "$BASE/window.json" "$rc" <<'PY'
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')
PY
exit "$rc"
+12
View File
@@ -0,0 +1,12 @@
"""Refuse startup outside the explicitly approved first-use window (no network)."""
import json
import sys
import time
from pathlib import Path
path = Path(sys.argv[1])
window = json.loads(path.read_text())
if not path.with_name('window-active').is_file():
raise SystemExit('first-use window is inactive')
if not window.get('approved') or time.time() >= int(window['deadline_epoch']):
raise SystemExit('first-use window has expired or is not approved')