Compare commits

...
2 Commits
Author SHA1 Message Date
ClaudeandClaude Opus 5.5 89efc3a7cf fix(ops): process alert ignores seconds-old processes; release flow reads production's real revision and says why it stops (BUG-2437, BUG-2438)
Independent Staging Quality Gate / validate-python (push) Successful in 5m1s
Independent Staging Quality Gate / validate-frontend (push) Failing after 4m39s
Independent Staging Quality Gate / publish (push) Skipped
- ops-check reads etimes; only processes alive >= 120 s count as CPU-hot; ps/ss/next-server allowlisted.
  Miner-name and pool-port checks unchanged.
- migrate/deploy-production print why they stop when the web container has no GITHUB_SHA.
- ship-release compares migrations against production's running SHA (unknown = migrate), so a rerun
  after a failed migration no longer skips it. README: manual container recreate must carry GITHUB_SHA.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-27 14:21:58 +08:00
ClaudeandClaude Opus 5.5 90fcbe99b6 feat(admin): BUG-2436 「内测群文案」 card in the release-notes editor
Independent Staging Quality Gate / validate-python (push) Canceled after 0s
Independent Staging Quality Gate / validate-frontend (push) Canceled after 0s
Independent Staging Quality Gate / publish (push) Canceled after 0s
Same fields as the in-app pop-up, fixed template (no model): opening line,
title, items numbered 1..n in 新功能 → 改进 → 修复 order, closing line, blank
lines between, markdown stripped for WeChat. 复制 via navigator.clipboard,
selects the text on failure, results by toast. Opening/closing lines are
editable and kept server-side in a single-row admin setting
(20261127010000_release_note_group_text.sql: admin_runtime select policy +
grant, audited write function under content.release_notes.write).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp3RzgZVEpT1PXxkwHj
2026-11-27 14:21:24 +08:00
20 changed files with 511 additions and 19 deletions
+5 -1
View File
@@ -398,7 +398,11 @@ jobs:
scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/controller/controller.tar "$remote:$incoming/controller.tar" scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/controller/controller.tar "$remote:$incoming/controller.tar"
ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'" ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'"
previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")" previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")"
[[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1 [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || {
# BUG-2438: this used to exit silently (see migrate-production-database.yml).
echo "cannot read the deployed revision from the production web container (got '${previous_sha:0:60}'); its GITHUB_SHA env is missing or malformed" >&2
exit 1
}
forward_verified=false forward_verified=false
if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" && "$ALLOW_ROLLBACK" != true ]]; then if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" && "$ALLOW_ROLLBACK" != true ]]; then
comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \ comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
@@ -319,7 +319,12 @@ jobs:
scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/staging-image/controller.tar "$remote:$incoming/controller.tar" scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/staging-image/controller.tar "$remote:$incoming/controller.tar"
ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'" ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'"
previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")" previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")"
[[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1 [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || {
# BUG-2438: this used to exit silently. An empty value means the running web container has no
# GITHUB_SHA (for example it was recreated by hand without it); recreate it with GITHUB_SHA set.
echo "cannot read the deployed revision from the production web container (got '${previous_sha:0:60}'); its GITHUB_SHA env is missing or malformed" >&2
exit 1
}
forward_verified=false forward_verified=false
if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" ]]; then if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" ]]; then
comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \ comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
+9 -2
View File
@@ -38,6 +38,7 @@ jobs:
RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }} RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }}
VERSION: ${{ inputs.version }} VERSION: ${{ inputs.version }}
STAGING_URL: ${{ vars.STAGING_URL }} STAGING_URL: ${{ vars.STAGING_URL }}
PRODUCTION_URL: ${{ vars.PRODUCTION_URL }}
steps: steps:
- name: Ship - name: Ship
run: | run: |
@@ -74,7 +75,13 @@ jobs:
git push origin "$sha:refs/heads/main" git push origin "$sha:refs/heads/main"
echo "main → $sha" echo "main → $sha"
if bash "$flow" migrations-changed "$main_before" "$sha"; then # BUG-2438: compare against what production actually runs, not main before the push. A
# rerun after a failed migration has main == sha already, and main_before..sha is empty,
# which used to skip the migration that never ran. Unknown production SHA = migrate.
production_sha="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
"${PRODUCTION_URL:-https://jyotisha.chat}/api/health" | jq -r '.deployment.gitCommit // ""' || true)"
echo "production runs ${production_sha:-unknown}"
if [[ ! "$production_sha" =~ ^[0-9a-f]{40}$ ]] || bash "$flow" migrations-changed "$production_sha" "$sha"; then
run="$(bash "$flow" dispatch create-production-recovery.yml refs/heads/main "$(jq -cn --arg s "$sha" '{deploy_sha:$s}')")" run="$(bash "$flow" dispatch create-production-recovery.yml refs/heads/main "$(jq -cn --arg s "$sha" '{deploy_sha:$s}')")"
echo "recovery point run $run" echo "recovery point run $run"
bash "$flow" wait-run "$run" 45 bash "$flow" wait-run "$run" 45
@@ -91,7 +98,7 @@ jobs:
echo "production migration run $run" echo "production migration run $run"
bash "$flow" wait-run "$run" 45 bash "$flow" wait-run "$run" 45
else else
echo "no migration changes since $main_before; skipping recovery point and migration" echo "no migration changes since production ($production_sha); skipping recovery point and migration"
fi fi
run="$(bash "$flow" dispatch deploy-production.yml refs/heads/main "$(jq -cn --arg s "$sha" \ run="$(bash "$flow" dispatch deploy-production.yml refs/heads/main "$(jq -cn --arg s "$sha" \
+3
View File
@@ -598,6 +598,9 @@ deploy/find-request-log.sh <requestId> --since 24h
- 命令行里出现常见挖矿程序名或 `stratum+tcp`:`miner_process`。 - 命令行里出现常见挖矿程序名或 `stratum+tcp`:`miner_process`。
- 有进程连到常见矿池端口(3333、4444、5555、7777、9999、14444 等):`mining_pool_connection`。我们自己的 22/80/443/3000/5200/5432 入站连接不算。 - 有进程连到常见矿池端口(3333、4444、5555、7777、9999、14444 等):`mining_pool_connection`。我们自己的 22/80/443/3000/5200/5432 入站连接不算。
- 告警只带进程名和进程号,不发命令行和环境变量。同一个进程只报一次。 - 告警只带进程名和进程号,不发命令行和环境变量。同一个进程只报一次。
- `suspicious_process` 只看已经运行满 2 分钟(`JYOTISHA_PROCESS_MIN_AGE`,默认 120 秒)的进程:`ps` 的 CPU 百分比是整个生命期的平均,刚启动几秒的进程(`ps` 自己、部署时的解压、网站刚启动)会显示接近 100%(BUG-2437)。`ps`、`ss` 和网站进程 `next-server (v…)` 在白名单里。
**手动重建生产容器(BUG-2438)**:手动 `docker compose up -d` 重建 web 或 api 时,必须同时带上 `WEB_IMAGE`、`API_IMAGE`(读当前容器的镜像摘要)和 `GITHUB_SHA`(当前容器 env 里的值),`--env-file /opt/jyotisha-production/.env.production`。漏了 `GITHUB_SHA`,健康检查的 `gitCommit` 变空,下一次生产迁移和部署会因为读不到「当前版本」而停下。
- 阈值可用 `JYOTISHA_CONTAINER_MEMORY_PERCENT_LIMIT`、`JYOTISHA_CPU_PERCENT_LIMIT`、`JYOTISHA_CONTAINER_CPU_LIMIT`、`JYOTISHA_PROCESS_CPU_LIMIT`、`JYOTISHA_CPU_SUSTAIN_RUNS` 调。 - 阈值可用 `JYOTISHA_CONTAINER_MEMORY_PERCENT_LIMIT`、`JYOTISHA_CPU_PERCENT_LIMIT`、`JYOTISHA_CONTAINER_CPU_LIMIT`、`JYOTISHA_PROCESS_CPU_LIMIT`、`JYOTISHA_CPU_SUSTAIN_RUNS` 调。
**容器(`docker-compose.server.yml`,测试和生产共用)** **容器(`docker-compose.server.yml`,测试和生产共用)**
+11 -5
View File
@@ -42,6 +42,7 @@ cpu_limit="${JYOTISHA_CPU_PERCENT_LIMIT:-85}"
container_cpu_limit="${JYOTISHA_CONTAINER_CPU_LIMIT:-90}" container_cpu_limit="${JYOTISHA_CONTAINER_CPU_LIMIT:-90}"
sustain_runs="${JYOTISHA_CPU_SUSTAIN_RUNS:-2}" sustain_runs="${JYOTISHA_CPU_SUSTAIN_RUNS:-2}"
process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}" process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}"
process_min_age="${JYOTISHA_PROCESS_MIN_AGE:-120}" # BUG-2437: seconds
[[ "$cpu_limit" =~ ^[1-9][0-9]$ ]] || exit 2 [[ "$cpu_limit" =~ ^[1-9][0-9]$ ]] || exit 2
[[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2 [[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2
[[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2 [[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2
@@ -386,10 +387,10 @@ check_container_memory() {
# Process names that may legitimately use a lot of CPU on this host. # Process names that may legitimately use a lot of CPU on this host.
allowed_process() { allowed_process() {
case "$1" in case "$1" in
node|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;; node|next-server*|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;;
caddy|dockerd|containerd|containerd-shim*|runc|docker|docker-proxy|docker-compose) return 0 ;; caddy|dockerd|containerd|containerd-shim*|runc|docker|docker-proxy|docker-compose) return 0 ;;
sshd|cron|systemd|systemd-*|journald|rsyslogd|unattended-upgr*|apt|apt-get|dpkg|http|https|gpgv) return 0 ;; sshd|cron|systemd|systemd-*|journald|rsyslogd|unattended-upgr*|apt|apt-get|dpkg|http|https|gpgv) return 0 ;;
bash|sh|awk|gzip|zstd|xz|tar|sort|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;; bash|sh|awk|gzip|zstd|xz|tar|sort|ps|ss|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;;
esac esac
return 1 return 1
} }
@@ -422,20 +423,25 @@ prune_suspects() {
done done
} }
# BUG-2437: ps reports %CPU as CPU time over lifetime, so a process seconds old (ps itself, a
# deploy step, a server warming up) reads near 100 %. Only a process running at least
# process_min_age seconds counts as hot; a miner keeps running and is still caught, and the
# name / pool checks ignore age.
check_processes() { check_processes() {
local pid pcpu comm args pct local pid etimes pcpu comm args pct
while read -r pid pcpu comm args || [ -n "${pid:-}" ]; do while read -r pid etimes pcpu comm args || [ -n "${pid:-}" ]; do
[[ "${pid:-}" =~ ^[0-9]+$ ]] || continue [[ "${pid:-}" =~ ^[0-9]+$ ]] || continue
if miner_text "$comm $args"; then if miner_text "$comm $args"; then
report_suspect "$pid" "$comm" miner_process report_suspect "$pid" "$comm" miner_process
continue continue
fi fi
[[ "${etimes:-}" =~ ^[0-9]+$ ]] && [ "$etimes" -ge "$process_min_age" ] || continue
pct="${pcpu%%.*}" pct="${pcpu%%.*}"
[[ "$pct" =~ ^[0-9]+$ ]] || continue [[ "$pct" =~ ^[0-9]+$ ]] || continue
if [ "$pct" -ge "$process_cpu_limit" ] && ! allowed_process "$comm"; then if [ "$pct" -ge "$process_cpu_limit" ] && ! allowed_process "$comm"; then
report_suspect "$pid" "$comm" suspicious_process report_suspect "$pid" "$comm" suspicious_process
fi fi
done < <(ps_cmd -eo pid=,pcpu=,comm=,args= 2>/dev/null || true) done < <(ps_cmd -eo pid=,etimes=,pcpu=,comm=,args= 2>/dev/null || true)
} }
# Established outbound connections to common mining-pool ports. # Established outbound connections to common mining-pool ports.
+44
View File
@@ -33296,3 +33296,47 @@
- 防复发:所有只要几十个 token 的小调用都必须显式关思考;本条与 BUG-2284 同类,复发原因是 BUG-2284 只修了出问题的那一处调用,没有排查同样只设上限的其它调用。 - 防复发:所有只要几十个 token 的小调用都必须显式关思考;本条与 BUG-2284 同类,复发原因是 BUG-2284 只修了出问题的那一处调用,没有排查同样只设上限的其它调用。
- 关联记录:BUG-553 / BUG-557(标题生成与写库守卫)、BUG-2284(追问建议同因)、BUG-2433。 - 关联记录:BUG-553 / BUG-557(标题生成与写库守卫)、BUG-2284(追问建议同因)、BUG-2433。
- 修复版本:`claude/chat-2433`(本地,未推送)。 - 修复版本:`claude/chat-2433`(本地,未推送)。
## BUG-2436 | 后台「更新说明」只有站内弹窗预览,发内测群还要另外手写一遍文案
- 状态:fixed-pending-verify(推到 `next`,进 1.7;待 staging 复测)。
- 首次发现 / 最近更新:2026-11-27(负责人提出,协调窗口转来,负责人已同意做)。
- 现象:每次发版负责人在后台写一遍版本、标题和条目,发内测微信群时还要再手写一份群里用的文字。
- 触发条件:每次发版。
- 根因:#331 的编辑器只做了站内弹窗这一种呈现,没有给群公告用的纯文字。
- 修复:编辑抽屉右侧在「用户看到的样子」下面加「内测群文案」卡片(`frontend/src/components/admin/release-note-group-text.tsx`):同一组字段按固定模板生成纯文字,不调用模型(`releaseNoteGroupMessage`,`frontend/src/lib/release-notes.ts`)。顺序是开头一句、标题、全部条目按 新功能 → 改进 → 修复 编号 1..n、结尾一句,块之间空一行;去掉 markdown 和列表符号,每块一行,粘到微信不走样。开头和结尾可以改,默认「大家好,Jyotisha 更新到 {版本} 啦~」「用着有任何感觉不对的地方,随时在群里说,我们都在看。」,`{版本}` 换成版本号。「复制」走 `navigator.clipboard`,失败时选中文字,结果都用 toast 提示。改过的开头结尾在复制或保存时存到服务端一行设置:新迁移 `20261127010000_release_note_group_text.sql`(单行表;admin_runtime 读要 select 策略加授权,BUG-1935 的教训;写只走带权限检查和审计的 `admin_save_release_note_group_text`,权限沿用 `content.release_notes.write`)。后台接口 GET 多返回 `groupText`,POST 多一个 `save_group_text`。
- 验证:新增 `frontend/tests/release-note-group-text-2436.test.tsx`(6 项):模板顺序、编号和空行;改过的开头结尾和 `{版本}`;粘进来的 markdown 和列表符号被去掉;默认文案和非空校验;卡片渲染(两个输入框、只读文字、复制按钮);编辑器、接口和迁移的接线。`database-release-notes-331.test.ts` 加了这张表的权限、策略、写入和审计检查(需要 Docker,本机没有,由 CI 跑)。三份迁移清单测试和公开表清单按原值/新值/原因更新。
- 防复发:群文案和弹窗用同一组字段,不再各写一份。
- 关联记录:#331(更新说明)、BUG-1935(admin_runtime 策略)、负责人「结果用 toast」规则。
- 修复版本:`next`(1.7)。
## BUG-2437 | 生产告警「有不在白名单里的进程占用大量 CPU」误报:报的是监控自己的 `ps`
- 状态:fixed-pending-verify(推到 `next`,随 1.7 上生产)。
- 首次发现 / 最近更新:2026-11-27(负责人收到飞书告警,1.6 部署期间)。
- 现象:告警 `service=host route=/proc/ps errorCode=suspicious_process`,时间正好在 1.6 生产部署(网站容器刚重建)那一分钟;上机查看时进程早已结束,负载 0.26,没有可疑进程。
- 触发条件:ops-check 每 5 分钟用 `ps -eo pcpu` 看进程;部署或其它短命令刚启动时跑到这一刻。
- 根因:`ps` 的 `%CPU` 是「CPU 时间 / 存活时间」,刚启动几秒的进程(`ps` 自己、部署时的解压、刚启动的网站)读数接近 100%;检查不看存活时间,白名单里也没有 `ps`。另外 Next.js 的进程名是 `next-server (v…)`(`comm` 带空格),不在白名单的 `node` 里,网站启动那一下同样会被报。
- 修复:`deploy/monitor/ops-check.sh` 的 `check_processes` 多读一列 `etimes`,只有存活满 `JYOTISHA_PROCESS_MIN_AGE`(默认 120 秒)的进程才按 CPU 判可疑;白名单加 `ps`、`ss`、`next-server*`。按挖矿程序名 / `stratum` 和矿池端口的两条检查不看存活时间,照旧。
- 验证:`tests/test_monitor_alerts_2348.py` 加三条假进程(刚启动的 `ps` 100%、5 秒的 `unpigz` 97%、长期运行的 `next-server (v16.0.0)` 60%)都不报;存活 30 秒的 `kdevtmpfsi` 仍按名字报 `miner_process`;原有用例照过。
- 防复发:监控按百分比判断时必须同时看存活时间;新增常驻服务时把它的 `comm` 名加进白名单。
- 关联记录:BUG-2416(防入侵告警)、BUG-2348(监控安装)。
- 修复版本:`next`(本条提交)。
## BUG-2438 | 发 1.6 时生产迁移无提示失败:网站容器缺 `GITHUB_SHA`;发版流程重跑会跳过没跑成的迁移
- 状态:fixed-pending-verify(生产已手动补好并完成 1.6 发布;流程修复推到 `next`,随 1.7 生效)。
- 首次发现 / 最近更新:2026-11-27(协调窗口,发 1.6 的 ship-release 8869 / 迁移 8871)。
- 现象:「发版」流程把 main 快进到 4155b9d22、恢复点 8870 成功后,生产迁移 8871 在「Migrate」一步以 exit 1 结束,日志里没有任何错误说明;生产健康检查的 `gitCommit` 是空字符串。
- 触发条件:1.5 上线时为加 Turnstile 密钥手动 `docker compose up -d --no-deps web`,只带了 `WEB_IMAGE` / `API_IMAGE`,没带 `GITHUB_SHA`,网站容器的 `GITHUB_SHA=` 变成空值。
- 根因:
1. 迁移和部署都从网站容器的 env 读「当前生产版本」,读到空值时 `[[ … ]] || exit 1` 直接退出,不打印原因(`migrate-production-database.yml`、`deploy-production.yml`)。
2. 运维文档没写手动重建容器必须带 `GITHUB_SHA`。
3. `ship-release.yml` 用「推送前的 main」和发版 SHA 比较迁移有没有变化;迁移失败后 main 已经等于 SHA,重跑「发版」时这段比较为空,会跳过从没跑成的迁移直接部署。
- 修复:
- 负责人同意后用原镜像摘要、原 env 文件带上 `GITHUB_SHA=87677ca9…` 重建网站容器(几秒中断),重跑迁移 8871 成功,手动派发部署 8873 成功,v1.6 自动打标签。
- 代码:两处读取失败改为打印「读不到生产网站容器的版本(GITHUB_SHA 缺失或格式不对)」再退出;`ship-release.yml` 改为和生产健康检查报告的实际运行版本比较,读不到就照样做恢复点和迁移;`deploy/README.md` 写明手动重建容器要带 `WEB_IMAGE`、`API_IMAGE`、`GITHUB_SHA` 和 env 文件。
- 验证:生产 `/api/health` = 1.6 / 4155b9d22,`/login` 200,未登录 `/api/account` 401,内部 API 健康 `swisseph_available = true`,Turnstile 两个 key 和 `.monitor.env` 仍在。`frontend/tests/branch-flow-2415.test.ts` 改为钉住新的比较方式(原值 / 新值 / 原因已注明)并通过;三个工作流 YAML 解析通过。
- 防复发:任何读生产状态的检查失败时必须打印原因;发版判断「要不要迁移」只以生产实际运行版本为准。
- 关联记录:BUG-2402(Turnstile)、BUG-2415(分支发版流程)、BUG-2425(同步删掉 `.monitor.env`,同属手动运维与发版流程的交界)。
- 修复版本:`next`(本条提交)。
+2
View File
@@ -47,6 +47,8 @@ html, body {
/* 「更新说明」 editor (issue #331): the form and a live preview side by side on wide screens. */ /* 「更新说明」 editor (issue #331): the form and a live preview side by side on wide screens. */
.admin-release-note-editor { display: grid; gap: 16px; } .admin-release-note-editor { display: grid; gap: 16px; }
/* BUG-2436: the pop-up preview and the 「内测群文案」 card stacked in the right column. */
.admin-release-note-preview { display: grid; gap: 12px; align-content: start; }
@media (min-width: 900px) { @media (min-width: 900px) {
.admin-release-note-editor { grid-template-columns: minmax(0, 1fr) 320px; align-items: start; } .admin-release-note-editor { grid-template-columns: minmax(0, 1fr) 320px; align-items: start; }
.admin-release-note-preview { position: sticky; top: 0; } .admin-release-note-preview { position: sticky; top: 0; }
@@ -4,14 +4,21 @@ import { z } from "zod";
import { requirePermission } from "@/lib/admin/auth"; import { requirePermission } from "@/lib/admin/auth";
import { queryAdminRows } from "@/lib/admin/database"; import { queryAdminRows } from "@/lib/admin/database";
import { adminErrorResponse, invalidQueryResponse, requestId, requireAdminMutation } from "@/lib/admin/http"; import { adminErrorResponse, invalidQueryResponse, requestId, requireAdminMutation } from "@/lib/admin/http";
import { releaseNoteDraftSchema, releaseNoteItemSchema } from "@/lib/release-notes"; import {
RELEASE_NOTE_GROUP_TEXT_DEFAULTS,
releaseNoteDraftSchema,
releaseNoteGroupTextSchema,
releaseNoteItemSchema,
} from "@/lib/release-notes";
export const runtime = "nodejs"; export const runtime = "nodejs";
/** /**
* 「更新说明」 in the admin console (issue #331). * 「更新说明」 in the admin console (issue #331).
* GET — every version (draft, published, withdrawn), newest edit first. * GET — every version (draft, published, withdrawn), newest edit first.
* POST — { action: "save", id?, version, title, items } | { action: "publish" | "withdraw", id }. * POST — { action: "save", id?, version, title, items } | { action: "publish" | "withdraw", id }
* | { action: "save_group_text", opening, closing } (BUG-2436 「内测群文案」 lines).
* GET also returns groupText: the saved opening/closing lines, or the defaults.
*/ */
type Row = { type Row = {
@@ -24,12 +31,14 @@ const saveSchema = releaseNoteDraftSchema.extend({
id: z.string().uuid().nullable().optional(), id: z.string().uuid().nullable().optional(),
}).strict(); }).strict();
const statusSchema = z.object({ action: z.enum(["publish", "withdraw"]), id: z.string().uuid() }).strict(); const statusSchema = z.object({ action: z.enum(["publish", "withdraw"]), id: z.string().uuid() }).strict();
const bodySchema = z.union([saveSchema, statusSchema]); const groupTextSchema = releaseNoteGroupTextSchema.extend({ action: z.literal("save_group_text") }).strict();
const bodySchema = z.union([saveSchema, statusSchema, groupTextSchema]);
const KNOWN_ERRORS: Record<string, { status: number; error: string }> = { const KNOWN_ERRORS: Record<string, { status: number; error: string }> = {
release_note_items_invalid: { status: 400, error: "条目不完整:每条要选分组并写内容" }, release_note_items_invalid: { status: 400, error: "条目不完整:每条要选分组并写内容" },
release_note_not_found: { status: 404, error: "这条更新说明不存在" }, release_note_not_found: { status: 404, error: "这条更新说明不存在" },
release_note_not_published: { status: 409, error: "只有已发布的版本可以撤回" }, release_note_not_published: { status: 409, error: "只有已发布的版本可以撤回" },
release_note_group_text_invalid: { status: 400, error: "开头和结尾都要写,每句不超过 200 字" },
}; };
export async function GET() { export async function GET() {
@@ -38,7 +47,11 @@ export async function GET() {
const rows = await queryAdminRows<Row>( const rows = await queryAdminRows<Row>(
"select id, version, title, items, status, published_at, updated_at from public.release_notes order by coalesce(published_at, updated_at) desc limit 200", "select id, version, title, items, status, published_at, updated_at from public.release_notes order by coalesce(published_at, updated_at) desc limit 200",
); );
const groupRows = await queryAdminRows<{ opening: string; closing: string }>(
"select opening, closing from public.release_note_group_text where id",
);
return NextResponse.json({ return NextResponse.json({
groupText: groupRows[0] ? { opening: groupRows[0].opening, closing: groupRows[0].closing } : RELEASE_NOTE_GROUP_TEXT_DEFAULTS,
data: rows.map((row) => { data: rows.map((row) => {
const items = z.array(releaseNoteItemSchema).safeParse(row.items); const items = z.array(releaseNoteItemSchema).safeParse(row.items);
return { return {
@@ -64,6 +77,13 @@ export async function POST(request: Request) {
const session = await requireAdminMutation(request, "content.release_notes.write"); const session = await requireAdminMutation(request, "content.release_notes.write");
const rid = requestId(request); const rid = requestId(request);
try { try {
if (body.data.action === "save_group_text") {
await queryAdminRows(
"select public.admin_save_release_note_group_text($1,$2,$3,$4) as saved",
[session.user.id, body.data.opening, body.data.closing, rid],
);
return NextResponse.json({ data: { opening: body.data.opening, closing: body.data.closing, requestId: rid } });
}
if (body.data.action === "save") { if (body.data.action === "save") {
const rows = await queryAdminRows<{ id: string }>( const rows = await queryAdminRows<{ id: string }>(
"select public.admin_save_release_note($1,$2,$3,$4,$5::jsonb,$6) as id", "select public.admin_save_release_note($1,$2,$3,$4,$5::jsonb,$6) as id",
@@ -0,0 +1,79 @@
"use client";
import { CopyOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Typography } from "antd";
import { useRef } from "react";
import type { TextAreaRef } from "antd/es/input/TextArea";
import {
RELEASE_NOTE_GROUP_TEXT_LIMIT,
releaseNoteGroupMessage,
type ReleaseNoteGroup,
type ReleaseNoteGroupText,
} from "@/lib/release-notes";
const { Text } = Typography;
type Props = Readonly<{
note: Readonly<{ version: string; title: string; items: readonly Readonly<{ group: ReleaseNoteGroup; text: string }>[] }>;
lines: ReleaseNoteGroupText;
disabled?: boolean;
onLinesChange: (lines: ReleaseNoteGroupText) => void;
/** "copied" after a clipboard write; "selected" when the clipboard refused and the text was selected instead. */
onCopy: (result: "copied" | "selected", text: string) => void;
}>;
/**
* 「内测群文案」 (BUG-2436): the note as plain text for the beta WeChat group, from the
* same fields as the in-app pop-up, with editable opening and closing lines.
*/
export function ReleaseNoteGroupTextCard({ note, lines, disabled, onLinesChange, onCopy }: Props) {
const textRef = useRef<TextAreaRef>(null);
const text = releaseNoteGroupMessage(note, lines);
async function copy() {
try {
if (!navigator.clipboard?.writeText) throw new Error("clipboard unavailable");
await navigator.clipboard.writeText(text);
onCopy("copied", text);
} catch {
const area = textRef.current?.resizableTextArea?.textArea;
area?.focus();
area?.select();
onCopy("selected", text);
}
}
return (
<Card
size="small"
title="内测群文案"
className="admin-release-note-group-text"
extra={<Button size="small" icon={<CopyOutlined />} onClick={() => void copy()}>复制</Button>}
>
<Space direction="vertical" style={{ width: "100%" }}>
<div>
<Text type="secondary">开头</Text>
<Input
value={lines.opening}
maxLength={RELEASE_NOTE_GROUP_TEXT_LIMIT}
disabled={disabled}
aria-label="群文案开头"
onChange={(event) => onLinesChange({ ...lines, opening: event.target.value })}
/>
</div>
<div>
<Text type="secondary">结尾</Text>
<Input
value={lines.closing}
maxLength={RELEASE_NOTE_GROUP_TEXT_LIMIT}
disabled={disabled}
aria-label="群文案结尾"
onChange={(event) => onLinesChange({ ...lines, closing: event.target.value })}
/>
</div>
<Input.TextArea ref={textRef} value={text} readOnly autoSize={{ minRows: 6 }} aria-label="内测群文案" />
</Space>
</Card>
);
}
@@ -8,11 +8,15 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { adminRequestJson, type AdminIdentity } from "@/lib/admin/providers"; import { adminRequestJson, type AdminIdentity } from "@/lib/admin/providers";
import { import {
RELEASE_NOTE_GROUP_TEXT_DEFAULTS,
RELEASE_NOTE_GROUPS, RELEASE_NOTE_GROUPS,
RELEASE_NOTE_LIMITS, RELEASE_NOTE_LIMITS,
releaseNoteDraftSchema, releaseNoteDraftSchema,
releaseNoteGroupTextSchema,
type ReleaseNoteGroup, type ReleaseNoteGroup,
type ReleaseNoteGroupText,
} from "@/lib/release-notes"; } from "@/lib/release-notes";
import { ReleaseNoteGroupTextCard } from "./release-note-group-text";
import { formatAdminDate } from "./resource-table"; import { formatAdminDate } from "./resource-table";
const { Text, Title } = Typography; const { Text, Title } = Typography;
@@ -70,11 +74,19 @@ export default function ReleaseNotesManagement() {
const [loadError, setLoadError] = useState<string | null>(null); const [loadError, setLoadError] = useState<string | null>(null);
const [editing, setEditing] = useState<Editing | null>(null); const [editing, setEditing] = useState<Editing | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
// BUG-2436: the 「内测群文案」 opening/closing lines, as stored and as being edited.
const [savedLines, setSavedLines] = useState<ReleaseNoteGroupText>(RELEASE_NOTE_GROUP_TEXT_DEFAULTS);
const [lines, setLines] = useState<ReleaseNoteGroupText>(RELEASE_NOTE_GROUP_TEXT_DEFAULTS);
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
const payload = await adminRequestJson<{ data: Note[] }>("/api/admin/release-notes"); const payload = await adminRequestJson<{ data: Note[]; groupText?: ReleaseNoteGroupText }>("/api/admin/release-notes");
setNotes(payload.data); setNotes(payload.data);
const stored = releaseNoteGroupTextSchema.safeParse(payload.groupText);
if (stored.success) {
setSavedLines(stored.data);
setLines(stored.data);
}
setLoadError(null); setLoadError(null);
} catch (error) { } catch (error) {
setLoadError(error instanceof Error ? error.message : "读取失败"); setLoadError(error instanceof Error ? error.message : "读取失败");
@@ -94,6 +106,31 @@ export default function ReleaseNotesManagement() {
return adminRequestJson<{ data: { id: string } }>("/api/admin/release-notes", { method: "POST", body: JSON.stringify(body) }); return adminRequestJson<{ data: { id: string } }>("/api/admin/release-notes", { method: "POST", body: JSON.stringify(body) });
} }
// Keeps the owner's edited lines for the next version; quiet when nothing changed.
async function saveLines(): Promise<boolean> {
if (!canWrite) return true;
const next = releaseNoteGroupTextSchema.safeParse(lines);
if (!next.success) {
message.error("群文案的开头和结尾都要写");
return false;
}
if (next.data.opening === savedLines.opening && next.data.closing === savedLines.closing) return true;
try {
await post({ action: "save_group_text", ...next.data });
setSavedLines(next.data);
return true;
} catch (error) {
message.error(`群文案的开头结尾没有保存:${error instanceof Error ? error.message : "请求失败"}`);
return false;
}
}
async function copied(result: "copied" | "selected") {
if (result === "copied") message.success("已复制,可以直接粘贴到群里");
else message.warning("没能自动复制,文字已经选中,请按 Ctrl+C 或长按复制");
await saveLines();
}
async function save(publish: boolean) { async function save(publish: boolean) {
if (!editing) return; if (!editing) return;
if (problem) { if (problem) {
@@ -103,6 +140,7 @@ export default function ReleaseNotesManagement() {
setBusy(true); setBusy(true);
try { try {
const saved = await post({ action: "save", id: editing.id, ...draftOf(editing) }); const saved = await post({ action: "save", id: editing.id, ...draftOf(editing) });
await saveLines();
if (publish) await post({ action: "publish", id: saved.data.id }); if (publish) await post({ action: "publish", id: saved.data.id });
await load(); await load();
setEditing(null); setEditing(null);
@@ -208,7 +246,8 @@ export default function ReleaseNotesManagement() {
))} ))}
{problem && <Text type="danger">{problem}</Text>} {problem && <Text type="danger">{problem}</Text>}
</Form> </Form>
<Card size="small" title="用户看到的样子" className="admin-release-note-preview"> <div className="admin-release-note-preview">
<Card size="small" title="用户看到的样子">
<Text type="secondary">版本 {preview?.version || "(未填)"}</Text> <Text type="secondary">版本 {preview?.version || "(未填)"}</Text>
<Title level={5} style={{ marginTop: 4 }}>{preview?.title || "(未填标题)"}</Title> <Title level={5} style={{ marginTop: 4 }}>{preview?.title || "(未填标题)"}</Title>
{RELEASE_NOTE_GROUPS.map(({ key, label }) => { {RELEASE_NOTE_GROUPS.map(({ key, label }) => {
@@ -224,6 +263,14 @@ export default function ReleaseNotesManagement() {
); );
})} })}
</Card> </Card>
<ReleaseNoteGroupTextCard
note={preview ?? { version: "", title: "", items: [] }}
lines={lines}
disabled={!canWrite || busy}
onLinesChange={setLines}
onCopy={(result) => void copied(result)}
/>
</div>
</div> </div>
)} )}
</Drawer> </Drawer>
+44
View File
@@ -67,3 +67,47 @@ export function releaseNoteFromRow(row: Readonly<{
export function unseenReleaseNote(notes: readonly ReleaseNote[]): ReleaseNote | null { export function unseenReleaseNote(notes: readonly ReleaseNote[]): ReleaseNote | null {
return notes.find((note) => !note.seen) ?? null; return notes.find((note) => !note.seen) ?? null;
} }
/**
* 「内测群文案」 (BUG-2436, owner-approved 2026-11-27): the same note as plain text for
* the beta WeChat group. A fixed template, no model: opening line, title, every item
* numbered 1..n in the order 新功能 → 改进 → 修复, closing line; a blank line between
* blocks, no markdown symbols. {版本} in the opening or closing line becomes the version.
*/
export const RELEASE_NOTE_GROUP_TEXT_DEFAULTS = {
opening: "大家好,Jyotisha 更新到 {版本} 啦~",
closing: "用着有任何感觉不对的地方,随时在群里说,我们都在看。",
} as const;
export const RELEASE_NOTE_GROUP_TEXT_LIMIT = 200;
export const RELEASE_NOTE_GROUP_ORDER: readonly ReleaseNoteGroup[] = ["feature", "improve", "fix"];
export const releaseNoteGroupTextSchema = z.object({
opening: z.string().trim().min(1).max(RELEASE_NOTE_GROUP_TEXT_LIMIT),
closing: z.string().trim().min(1).max(RELEASE_NOTE_GROUP_TEXT_LIMIT),
}).strict();
export type ReleaseNoteGroupText = z.infer<typeof releaseNoteGroupTextSchema>;
// Markdown and list marks that WeChat shows literally: leading #, >, -, *, + or "1." /
// "1、", and **bold**, __bold__, `code`.
function plainLine(text: string): string {
return text
.replace(/\r\n?/g, "\n")
.split("\n")
.map((line) => line.trim().replace(/^(?:#{1,6}\s*|>\s*|[-*+•·]\s+|\d+[.、))]\s*)+/u, "").replace(/\*\*|__|`/g, ""))
.filter((line) => line.length > 0)
.join(" ");
}
export function releaseNoteGroupMessage(
note: Readonly<{ version: string; title: string; items: readonly Readonly<{ group: ReleaseNoteGroup; text: string }>[] }>,
lines: Readonly<{ opening: string; closing: string }> = RELEASE_NOTE_GROUP_TEXT_DEFAULTS,
): string {
const version = note.version.trim();
const fill = (line: string) => plainLine(line.replaceAll("{版本}", version));
const texts = RELEASE_NOTE_GROUP_ORDER
.flatMap((group) => note.items.filter((item) => item.group === group).map((item) => plainLine(item.text)))
.filter((text) => text.length > 0);
return [fill(lines.opening), plainLine(note.title), ...texts.map((text, at) => `${at + 1}. ${text}`), fill(lines.closing)]
.filter((block) => block.length > 0)
.join("\n\n");
}
@@ -0,0 +1,89 @@
-- BUG-2436 「内测群文案」 (owner-approved 2026-11-27): the admin 「更新说明」
-- editor also shows the same note as plain text for the beta WeChat group.
-- The opening and closing lines around the items are editable, and the
-- owner's last edit is kept for the next version.
--
-- release_note_group_text: a single row (id = true) with the two lines.
-- Audit rows use a fixed target id (audit target_id is not null; there is one row).
--
-- Access:
-- * RLS on; no table privilege for app, service or authenticated roles;
-- * the admin console reads the row through an admin_runtime select policy
-- (BUG-1935: a grant without a policy reads nothing) and writes through a
-- permission-checked, audited function (content.release_notes.write).
--
-- Backward compatibility: additive only.
begin;
create table if not exists public.release_note_group_text (
id boolean primary key default true check (id),
opening text not null check (char_length(btrim(opening)) between 1 and 200),
closing text not null check (char_length(btrim(closing)) between 1 and 200),
updated_by uuid references auth.users(id) on delete set null,
updated_at timestamptz not null default clock_timestamp()
);
alter table public.release_note_group_text enable row level security;
revoke all on table public.release_note_group_text from public, anon, authenticated, service_role;
do $$
begin
if exists (select 1 from pg_roles where rolname = 'app_runtime') then
revoke all on table public.release_note_group_text from app_runtime;
end if;
if exists (select 1 from pg_roles where rolname = 'service_runtime') then
revoke all on table public.release_note_group_text from service_runtime;
end if;
end;
$$;
create or replace function public.admin_save_release_note_group_text(
p_actor_user_id uuid, p_opening text, p_closing text, p_request_id text
)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
begin
if not public.admin_has_permission(p_actor_user_id, 'content.release_notes.write') then
raise exception 'admin_permission_denied' using errcode = '42501';
end if;
if p_opening is null or p_closing is null
or char_length(btrim(p_opening)) not between 1 and 200
or char_length(btrim(p_closing)) not between 1 and 200 then
raise exception 'release_note_group_text_invalid' using errcode = '22023';
end if;
insert into public.release_note_group_text (id, opening, closing, updated_by)
values (true, btrim(p_opening), btrim(p_closing), p_actor_user_id)
on conflict (id) do update
set opening = excluded.opening, closing = excluded.closing,
updated_by = excluded.updated_by, updated_at = clock_timestamp();
insert into audit.admin_audit_logs (actor_user_id, actor_email, actor_role, action, target_type, target_id, after_value,
request_id, permission_used, reason)
select p_actor_user_id, lower(btrim(u.email)), 'admin', 'content.release_notes.group_text', 'release_note_group_text',
'00000000-0000-4000-8000-000000002436'::uuid,
jsonb_build_object('opening', btrim(p_opening), 'closing', btrim(p_closing)),
p_request_id, 'content.release_notes.write', 'admin_console_release_notes'
from identity.users u where u.id = p_actor_user_id on conflict do nothing;
return true;
end;
$$;
revoke all on function public.admin_save_release_note_group_text(uuid, text, text, text) from public, anon, authenticated;
do $$
begin
if exists (select 1 from pg_roles where rolname = 'admin_runtime') then
grant select on table public.release_note_group_text to admin_runtime;
drop policy if exists release_note_group_text_admin_read on public.release_note_group_text;
create policy release_note_group_text_admin_read on public.release_note_group_text
for select to admin_runtime using (true);
grant execute on function public.admin_save_release_note_group_text(uuid, text, text, text) to admin_runtime;
end if;
end;
$$;
commit;
@@ -339,6 +339,8 @@ test("the migration adds one column, one unique index and a guard; no settlement
"20261126030000_report_exports.sql", "20261126030000_report_exports.sql",
// 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql // 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql
"20261126040000_report_queue_per_user.sql", "20261126040000_report_queue_per_user.sql",
// 原值:最后是 BUG-2418 一份;新值:再加 BUG-2436 内测群文案(新表 release_note_group_text 和一个后台函数,不碰这里检查的表);原因:20261127010000_release_note_group_text.sql
"20261127010000_release_note_group_text.sql",
]); ]);
assert.equal(names.filter((item) => item.slice(0, 14) === name.slice(0, 14)).length, 1); assert.equal(names.filter((item) => item.slice(0, 14) === name.slice(0, 14)).length, 1);
const sql = read(`../supabase/migrations/${name}`); const sql = read(`../supabase/migrations/${name}`);
+2
View File
@@ -130,6 +130,8 @@ test("BUG-2057: the avatar table is owner-only, lives in the database, and its m
"20261126030000_report_exports.sql", "20261126030000_report_exports.sql",
// 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql // 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql
"20261126040000_report_queue_per_user.sql", "20261126040000_report_queue_per_user.sql",
// 原值:最后是 BUG-2418 一份;新值:再加 BUG-2436 内测群文案(新表 release_note_group_text 和一个后台函数,不碰这里检查的表);原因:20261127010000_release_note_group_text.sql
"20261127010000_release_note_group_text.sql",
], "the seconds migrations, the report-question column, the admin reading-log function and the coordinate-source column come after it"); ], "the seconds migrations, the report-question column, the admin reading-log function and the coordinate-source column come after it");
for (const name of after) assert.doesNotMatch(read(`supabase/migrations/${name}`), /profile_avatar_images/u); for (const name of after) assert.doesNotMatch(read(`supabase/migrations/${name}`), /profile_avatar_images/u);
// Idempotent. // Idempotent.
+5 -1
View File
@@ -56,7 +56,11 @@ test("发版 ships only a tested head: staging live on it, release checks passed
const migrate = wf.indexOf("migrate-production-database.yml"); const migrate = wf.indexOf("migrate-production-database.yml");
const deploy = wf.indexOf("deploy-production.yml"); const deploy = wf.indexOf("deploy-production.yml");
assert.ok(recovery > 0 && recovery < migrate && migrate < deploy); assert.ok(recovery > 0 && recovery < migrate && migrate < deploy);
assert.match(wf, /if bash "\$flow" migrations-changed "\$main_before" "\$sha"; then/); // 原值:migrations-changed "$main_before" "$sha";新值:比较生产实际运行的版本,读不到就照样迁移;
// 原因:BUG-2438 迁移失败后重跑时 main 已经等于 sha,main_before..sha 为空会跳过从没跑成的迁移。
assert.match(wf, /production_sha="\$\(curl [^\n]*\\\n\s*"\$\{PRODUCTION_URL:-https:\/\/jyotisha\.chat\}\/api\/health"/);
assert.match(wf, /if \[\[ ! "\$production_sha" =~ \^\[0-9a-f\]\{40\}\$ \]\] \|\| bash "\$flow" migrations-changed "\$production_sha" "\$sha"; then/);
assert.doesNotMatch(wf, /migrations-changed "\$main_before"/);
// Its own queue: the production workflows it starts hold production-mutation themselves. // Its own queue: the production workflows it starts hold production-mutation themselves.
assert.match(wf, /group: release-flow/); assert.match(wf, /group: release-flow/);
assert.doesNotMatch(wf, /group: production-mutation/); assert.doesNotMatch(wf, /group: production-mutation/);
@@ -465,6 +465,10 @@ test("local PostgreSQL applies the reviewed business schema and serves authentic
"redemption_codes", "redemption_codes",
// 新值: 加入 release_note_reads、release_notes // 新值: 加入 release_note_reads、release_notes
// 原因: 「更新说明」(issue #331,20261122130000_release_notes.sql) // 原因: 「更新说明」(issue #331,20261122130000_release_notes.sql)
// 原值: redemption_codes 之后直接是 release_note_reads
// 新值: 中间加入 release_note_group_text(按字母序 group < reads)
// 原因: BUG-2436 「内测群文案」 开头结尾一行设置(20261127010000_release_note_group_text.sql)
"release_note_group_text",
"release_note_reads", "release_note_reads",
"release_notes", "release_notes",
"reply_quality_snapshots", "reply_quality_snapshots",
@@ -33,6 +33,7 @@ test("release notes: editors publish through audited functions; each user sees e
}); });
assert.equal(migration.status, 0, `${migration.stdout}${migration.stderr}`); assert.equal(migration.status, 0, `${migration.stdout}${migration.stderr}`);
assert.match(migration.stdout, /applied 20261122130000_release_notes\.sql/); assert.match(migration.stdout, /applied 20261122130000_release_notes\.sql/);
assert.match(migration.stdout, /applied 20261127010000_release_note_group_text\.sql/);
const save = "public.admin_save_release_note(uuid, uuid, text, text, jsonb, text)"; const save = "public.admin_save_release_note(uuid, uuid, text, text, jsonb, text)";
const status = "public.admin_set_release_note_status(uuid, uuid, text, text)"; const status = "public.admin_set_release_note_status(uuid, uuid, text, text)";
@@ -110,6 +111,24 @@ test("release notes: editors publish through audited functions; each user sees e
); );
// A duplicate version is refused. // A duplicate version is refused.
assert.throws(() => fixture.psql(`select public.admin_save_release_note('${editorId}', null, '2026.11.23', '重复', '${items}'::jsonb, 'r-331-7')`)); assert.throws(() => fixture.psql(`select public.admin_save_release_note('${editorId}', null, '2026.11.23', '重复', '${items}'::jsonb, 'r-331-7')`));
// BUG-2436 「内测群文案」 lines: one stored row, read by admin_runtime through a policy,
// written only through the audited function by content.release_notes.write.
const groupSave = "public.admin_save_release_note_group_text(uuid, text, text, text)";
assert.equal(fixture.psql(`select has_function_privilege('admin_runtime', '${groupSave}', 'EXECUTE')`), "t");
assert.equal(fixture.psql(`select has_function_privilege('authenticated', '${groupSave}', 'EXECUTE')`), "f");
assert.equal(fixture.psql(`select has_function_privilege('app_runtime', '${groupSave}', 'EXECUTE')`), "f");
for (const role of ["app_runtime", "service_runtime", "authenticated", "admin_runtime"]) {
assert.equal(fixture.psql(`select has_table_privilege('${role}', 'public.release_note_group_text', 'INSERT')`), "f", role);
}
assert.equal(fixture.psql(`select has_table_privilege('admin_runtime', 'public.release_note_group_text', 'SELECT')`), "t");
assert.equal(fixture.psql(`select count(*) from pg_policies where tablename = 'release_note_group_text' and policyname = 'release_note_group_text_admin_read'`), "1");
assert.throws(() => fixture.psql(`select public.admin_save_release_note_group_text('${outsiderId}', '开头', '结尾', 'r-2436-0')`), /admin_permission_denied/);
assert.throws(() => fixture.psql(`select public.admin_save_release_note_group_text('${editorId}', ' ', '结尾', 'r-2436-1')`), /release_note_group_text_invalid/);
assert.equal(fixture.psql(`select public.admin_save_release_note_group_text('${editorId}', '大家好 {版本}', '有事说', 'r-2436-2')`), "t");
assert.equal(fixture.psql(`select public.admin_save_release_note_group_text('${editorId}', ' 各位 {版本} ', '有事群里说', 'r-2436-3')`), "t");
assert.equal(fixture.psql(`select count(*) || '|' || opening || '|' || closing from public.release_note_group_text group by opening, closing`), "1|各位 {版本}|有事群里说");
assert.equal(fixture.psql(`select count(*) from audit.admin_audit_logs where action = 'content.release_notes.group_text'`), "2");
} finally { } finally {
fixture.stop(); fixture.stop();
} }
@@ -121,6 +121,8 @@ test("the migration widens the profiles CHECK to exactly the shared list; chart_
"20261126030000_report_exports.sql", "20261126030000_report_exports.sql",
// 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql // 原值:最后是 BUG-2359 一份;新值:再加 BUG-2418 报告按人排队(换两个唯一索引、改两个领取函数和排队视图,不碰这里检查的表);原因:20261126040000_report_queue_per_user.sql
"20261126040000_report_queue_per_user.sql", "20261126040000_report_queue_per_user.sql",
// 原值:最后是 BUG-2418 一份;新值:再加 BUG-2436 内测群文案(新表 release_note_group_text 和一个后台函数,不碰这里检查的表);原因:20261127010000_release_note_group_text.sql
"20261127010000_release_note_group_text.sql",
]); ]);
assert.doesNotMatch(read("../supabase/migrations/20261122130000_release_notes.sql"), /birth_place_provider/); assert.doesNotMatch(read("../supabase/migrations/20261122130000_release_notes.sql"), /birth_place_provider/);
assert.doesNotMatch(read("../supabase/migrations/20261122140000_redemption_code_kinds.sql"), /birth_place_provider/); assert.doesNotMatch(read("../supabase/migrations/20261122140000_redemption_code_kinds.sql"), /birth_place_provider/);
@@ -0,0 +1,103 @@
// BUG-2436 「内测群文案」 (owner-approved 2026-11-27): the admin 「更新说明」 editor also shows the
// note as plain text for the beta WeChat group, from the same fields, by a fixed template (no model):
// opening line, title, every item numbered 1..n in the order 新功能 → 改进 → 修复, closing line, a blank
// line between blocks, no markdown symbols. The opening/closing lines are editable and kept server-side.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { renderToStaticMarkup } from "react-dom/server";
import { ReleaseNoteGroupTextCard } from "../src/components/admin/release-note-group-text.tsx";
import {
RELEASE_NOTE_GROUP_TEXT_DEFAULTS,
releaseNoteGroupMessage,
releaseNoteGroupTextSchema,
} from "../src/lib/release-notes.ts";
const source = (path: string) => readFileSync(new URL(`../${path}`, import.meta.url), "utf8");
const note = {
version: "1.7",
title: "报告和对话更快了",
items: [
{ group: "fix" as const, text: "打开报告不再空白" },
{ group: "feature" as const, text: "报告里可以选中一段直接提问" },
{ group: "improve" as const, text: "报告打开更快" },
{ group: "feature" as const, text: "首页新增三个常见问题" },
],
};
test("the group text is opening, title, items 1..n in 新功能 → 改进 → 修复 order, closing, blank lines between", () => {
assert.equal(
releaseNoteGroupMessage(note),
[
"大家好,Jyotisha 更新到 1.7 啦~",
"报告和对话更快了",
"1. 报告里可以选中一段直接提问",
"2. 首页新增三个常见问题",
"3. 报告打开更快",
"4. 打开报告不再空白",
"用着有任何感觉不对的地方,随时在群里说,我们都在看。",
].join("\n\n"),
);
});
test("edited opening/closing lines are used, {版本} filled in both", () => {
const text = releaseNoteGroupMessage(note, { opening: "各位,{版本} 上线了", closing: "有问题找我({版本})" });
assert.ok(text.startsWith("各位,1.7 上线了\n\n"));
assert.ok(text.endsWith("\n\n有问题找我(1.7)"));
});
test("pasted markdown or list marks are stripped so WeChat shows plain numbered lines", () => {
const text = releaseNoteGroupMessage({
version: "1.7",
title: "## **大更新**",
items: [
{ group: "feature", text: "- 新的 `报告` 页面" },
{ group: "improve", text: "1. 更快\n第二行" },
{ group: "fix", text: "> 修好了 __登录__" },
],
});
assert.doesNotMatch(text, /[#*`>_]|^- /m);
assert.deepEqual(text.split("\n\n").slice(1, 5), ["大更新", "1. 新的 报告 页面", "2. 更快 第二行", "3. 修好了 登录"]);
// No line breaks inside a block: every block is one line.
for (const block of text.split("\n\n")) assert.doesNotMatch(block, /\n/);
});
test("the defaults are the owner's wording, and both lines must be non-empty", () => {
assert.equal(RELEASE_NOTE_GROUP_TEXT_DEFAULTS.opening, "大家好,Jyotisha 更新到 {版本} 啦~");
assert.equal(RELEASE_NOTE_GROUP_TEXT_DEFAULTS.closing, "用着有任何感觉不对的地方,随时在群里说,我们都在看。");
assert.equal(releaseNoteGroupTextSchema.safeParse({ opening: " ", closing: "x" }).success, false);
assert.equal(releaseNoteGroupTextSchema.safeParse({ opening: "a", closing: "b" }).success, true);
});
test("the admin card renders the plain text, both editable lines and a 复制 button", () => {
const markup = renderToStaticMarkup(
<ReleaseNoteGroupTextCard note={note} lines={RELEASE_NOTE_GROUP_TEXT_DEFAULTS} onLinesChange={() => {}} onCopy={() => {}} />,
);
assert.match(markup, /内测群文案/);
assert.match(markup, /复制/);
assert.match(markup, /aria-label="群文案开头"[^>]*value="大家好,Jyotisha 更新到 \{版本\} 啦~"|value="大家好,Jyotisha 更新到 \{版本\} 啦~"[^>]*aria-label="群文案开头"/);
assert.match(markup, /readOnly=""|readonly=""/i);
assert.match(markup, /1\. 报告里可以选中一段直接提问/);
assert.match(markup, /4\. 打开报告不再空白/);
});
test("the editor shows both previews, copies through the clipboard with a selection fallback, and reports by toast", () => {
const editor = source("src/components/admin/release-notes-management.tsx");
assert.match(editor, /用户看到的样子/);
assert.match(editor, /<ReleaseNoteGroupTextCard/);
assert.match(editor, /message\.success\("已复制/);
assert.match(editor, /message\.warning\(/);
const card = source("src/components/admin/release-note-group-text.tsx");
assert.match(card, /navigator\.clipboard\?\.writeText/);
assert.match(card, /\.select\(\)/);
// The lines are kept server-side through the audited admin function, read back on load.
const route = source("src/app/api/admin/release-notes/route.ts");
assert.match(route, /admin_save_release_note_group_text/);
assert.match(route, /from public\.release_note_group_text/);
const migration = source("supabase/migrations/20261127010000_release_note_group_text.sql");
assert.match(migration, /create policy release_note_group_text_admin_read on public\.release_note_group_text\s+for select to admin_runtime/);
assert.match(migration, /grant select on table public\.release_note_group_text to admin_runtime/);
assert.match(migration, /content\.release_notes\.write/);
});
+10 -4
View File
@@ -419,10 +419,15 @@ def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None:
# Miner by name, an unknown hot process, a pool connection; allowlisted node stays quiet. # Miner by name, an unknown hot process, a pool connection; allowlisted node stays quiet.
ps_out = "\n".join([ ps_out = "\n".join([
" 101 99.0 node node server.js", " 101 9000 99.0 node node server.js",
" 202 80.0 kdevtmpfsi /tmp/kdevtmpfsi", " 202 30 80.0 kdevtmpfsi /tmp/kdevtmpfsi",
" 303 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443", " 303 9000 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443",
" 404 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET", " 404 9000 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET",
# BUG-2437: the monitor's own ps and a fresh deploy step read ~100 % in their first seconds;
# Next.js names its process 「next-server (v…)」.
" 505 0 100.0 ps ps -eo pid=,etimes=,pcpu=,comm=,args=",
" 606 5 97.0 unpigz unpigz -d -c",
" 707 9000 60.0 next-server (v16.0.0) next-server (v16.0.0)",
]) ])
ss_out = "\n".join([ ss_out = "\n".join([
"0 0 10.0.0.5:51234 203.0.113.9:4444 users:((\"sysupdate\",pid=303,fd=7))", "0 0 10.0.0.5:51234 203.0.113.9:4444 users:((\"sysupdate\",pid=303,fd=7))",
@@ -437,6 +442,7 @@ def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None:
assert "route=/proc/sysupdate errorCode=suspicious_process count=303" in joined assert "route=/proc/sysupdate errorCode=suspicious_process count=303" in joined
assert "route=/proc/sysupdate errorCode=mining_pool_connection" not in joined # same pid already reported assert "route=/proc/sysupdate errorCode=mining_pool_connection" not in joined # same pid already reported
assert "/proc/node" not in joined and "docker-proxy" not in joined # allowlisted / inbound assert "/proc/node" not in joined and "docker-proxy" not in joined # allowlisted / inbound
assert "/proc/ps " not in joined and "/proc/unpigz" not in joined and "/proc/next-server" not in joined # BUG-2437
assert "SECRETWALLET" not in joined and "stratum" not in joined and "pool.example" not in joined assert "SECRETWALLET" not in joined and "stratum" not in joined and "pool.example" not in joined
# Still running next time: not announced again. # Still running next time: not announced again.
before = len(alert_lines(state)) before = len(alert_lines(state))