- notify-feishu.sh: add a Resend email channel (key read from .env.production via a header file, never argv/stdout); both channels when configured, one acceptance counts; fixed Chinese labels on every alert line. - classify_error_log.py: per-code thresholds for low-volume signals, the [ops-signal] marker, api access-log 429/5xx counted without query strings. - ops-check.sh: container restarts/OOM, host memory, report queue wait, new feedback count (no content). - OTP sender: retry network/429/5xx once with the same idempotency key; final failure logs otp_send_failed (no address). - install-production-monitor.sh: idempotent cron install + --test-alert. - monitor-public-health.yml: off-host probe every 5 minutes on the runner. - Tests: tests/test_monitor_alerts_2348.py (on the quick list), OTP sender and ops-signal tests. Issues #350, #354. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
Production deployment and maintenance
This file is the operational source of truth for Jyotisha deployment. The production migration is governed by docs/operations/production-server-migration-2026-08.md; do not change DNS or retire the old environment outside that runbook.
Production migration state
| Item | Value |
|---|---|
| Public domain | https://jyotisha.chat |
| DNS | Spaceship nameservers (launch1.spaceship.net, launch2.spaceship.net) |
| Current public host | 83.229.126.99; production health reports the local business/identity PostgreSQL databases. The old VPS 103.117.123.53 is no longer a deployment target |
| Target host | 83.229.126.99, Ubuntu x86_64 |
| Target SSH | dedicated deploy user, confirmed variable port, public-key authentication only |
| Target capacity | 2 vCPU / 4 GB RAM; no application builds on host |
| Target app directory | /opt/jyotisha-production |
| Target environment files | .env.production and .env.production.database (0600) |
| Primary source repository | https://git.copse.top/root/Jyotisha.git |
| GitHub mirror | https://github.com/jesse-ux/Jyotisha.git (read-only mirror; no workflows, Actions disabled) |
| Migration source | Supabase project vtvnfqmonbfuxmqkqdlc + Supabase Auth |
| Migration target | private PostgreSQL 17 + Better Auth |
This migration changes both infrastructure and persistence. It is a controlled Supabase-to-private-PostgreSQL ETL, not a database-volume copy or full-dump restore. Keep the old VPS for 7–14 days and Supabase for 14–30 days after cutover.
Architecture
Spaceship DNS -> Caddy :80/:443 -> web:3000 -> api:5200
| -> local astrology engines
| -> named volume api_scratch -> /app/scratch/local
-> private PostgreSQL 17 + Better Auth
-> external model and mail providers
Only Caddy publishes host ports. Ports 3000 and 5200 must remain private.
The API image WORKDIR is /app (deploy/railway-api.Dockerfile). Runtime files written by scripts/jyotish_api_server.py resolve to /app/scratch/local (chart cache api_chart_cache, async job files or async_jobs.sqlite3, high-rigor job records). Compose mounts the named volume api_scratch at that path so those files survive container recreate. Docker creates the volume on first up; there is no data migration because the previous container overlay was ephemeral. Deploy scripts (run-staging-deploy.sh, run-production-deploy.sh) do not need extra volume flags: docker compose up creates and reattaches named volumes automatically.
The volume is not a backup domain. Chart cache is a TTL'd compute cache (default 900s) and is cheaper to rebuild than to archive. Async / high-rigor job state is short-lived (default TTL 3600s) and is not a restore unit. Restart persistence is the only reason the volume exists. Staging encrypted backups remain PostgreSQL-only via deploy/backup-staging-postgres.sh; do not add api_scratch to that helper. Project-prefixed volume names are jyotisha-staging_api_scratch and jyotisha-production_api_scratch.
The Raman house-text file read by scripts/book_citations/raman_house_texts.py (references/product_runtime_contract.md section R, BUG-1926) is committed at references/book_corpus/texts/raman_htjh_house_texts.json and ships inside the API image; no host-side provisioning is needed. JYOTISH_RAMAN_HOUSE_TEXTS_PATH can point the loader elsewhere. If the file cannot be read, the API reports the classical_texts layer as not_available_yet and nothing else changes.
Heavy rectification scans and high-rigor workflows share a process-wide concurrency gate (JYOTISH_HEAVY_COMPUTE_CONCURRENCY, default 2 to match the 2 vCPU host). A saturated request waits up to 8 seconds if fewer than 4 requests are already waiting, then returns HTTP 429 with Retry-After. Health checks and other light routes do not take a slot.
The API image installs PyJHora for one chapter only: the full-data report's last section, 「独立年度方法参考」. That chapter runs PyJHora in a child process. The API process does not import it. Chat cards, rectification scoring, and the rest of the report keep the previous no-PyJHora results. AGPL for this chapter is the product decision of 2026-10-21 (issue #93). Do not turn on the year-lord PyJHora comparison switch.
DNS and Supabase Auth
Final Spaceship resource records (apply only during the approved cutover window):
A @ 83.229.126.99
A admin 83.229.126.99
CNAME www jyotisha.chat
After cutover, verify both authoritative nameservers:
dig +short @launch1.spaceship.net A jyotisha.chat
dig +short @launch2.spaceship.net A admin.jyotisha.chat
Both user and admin hosts must return 83.229.126.99. Caddy provisions and renews HTTPS automatically after DNS resolves.
Production environment
.env.production contains runtime-only application settings. Database bootstrap, migration, and backup credentials belong only in .env.production.database.
SITE_ADDRESS=https://jyotisha.chat
APP_ENV_FILE=../.env.production
CADDYFILE_PATH=./Caddyfile.production.selfhosted
JYOTISH_API_BASE=http://api:5200
GEOAPIFY_API_KEY=<server-side Geoapify geocoding key>
AUTH_PROVIDER=self-hosted
SELF_HOSTED_IDENTITY_ENABLED=true
AUTH_USER_ORIGIN=https://jyotisha.chat
ADMIN_USER_ORIGIN=https://admin.jyotisha.chat
IDENTITY_DATABASE_URL=postgresql://identity_runtime:<encoded-secret>@postgres:5432/jyotisha
APP_DATABASE_URL=postgresql://app_runtime:<encoded-secret>@postgres:5432/jyotisha
SERVICE_DATABASE_URL=postgresql://service_runtime:<encoded-secret>@postgres:5432/jyotisha
ADMIN_DATABASE_URL=postgresql://admin_runtime:<encoded-secret>@postgres:5432/jyotisha
BETTER_AUTH_USER_SECRET=<production-only-secret>
RESEND_API_KEY=<production-only-secret>
RESEND_FROM_EMAIL=<verified-sender>
ADMIN_EMAILS=...
# Required to save/read database-backed 易支付 settings. Base64 decoding must
# produce exactly 32 random bytes. Generate independently; never reuse auth keys.
EPAY_CONFIG_ENCRYPTION_KEY=<independent-base64-encoded-32-byte-key>
# Legacy EPAY_GATEWAY_URL / EPAY_PID / EPAY_KEY / EPAY_NOTIFY_URL /
# EPAY_RETURN_URL / EPAY_SITE_NAME remain fallback-only when no database row exists.
# Online packages stay hidden by default; only explicit true enables the fallback.
EPAY_CHAT_ENABLED=false
# Fixed birth-time rectification fee shown by the account UI.
RECTIFICATION_PRICE_CREDITS=3
# Required to encrypt/decrypt model-provider API keys stored in the admin database.
# Base64 decoding must produce exactly 32 random bytes; do not reuse other keys.
MODEL_PROVIDER_CONFIG_ENCRYPTION_KEY=<independent-base64-encoded-32-byte-key>
# The admin database model catalog is the only runtime model/provider source.
# Provider API keys are entered in the admin UI and are never read from provider env vars.
# Required VedAstro server-side upstream for chart creation and rectification:
VEDASTRO_GATEWAY_MODE=official_first
VEDASTRO_API_ENDPOINT=https://api.vedastro.org/api
VEDASTRO_ENABLE_NETWORK=1
# Compatibility flag only; rectification range scans follow VEDASTRO_ENABLE_NETWORK.
VEDASTRO_RANGE_SCAN_NETWORK_ENABLED=1
VEDASTRO_TIMEOUT_SECONDS=20
VEDASTRO_API_KEY=<server-secret>
Never commit either production env file, model/payment keys, user tokens, SSH private keys, database URLs, or passwords. Do not retain Supabase runtime selectors in the target env; Supabase is migration source/rollback storage only.
After changing runtime variables, use the exact-SHA Gitea workflow to recreate services; do not rebuild or rsync a local tree on the host.
Connect and inspect
ssh -p <confirmed-port> deploy@83.229.126.99
cd /opt/jyotisha-production
COMPOSE='docker compose -p jyotisha-production --env-file .env.production -f deploy/docker-compose.server.yml -f deploy/docker-compose.postgres.yml -f deploy/docker-compose.production.yml'
$COMPOSE ps
$COMPOSE logs --tail=100 postgres api web caddy
free -h
docker stats --no-stream
UFW permits only the confirmed SSH port, HTTP, and HTTPS. PostgreSQL, Web, API, and the Docker API remain private.
Legal entity and documents gate (2026-09-30)
Since 2026-11-18 (product owner, BUG-1991) the manual release gate no longer runs this check: the invite-only beta ships with placeholder operator details and draft legal text. Before any public or paid release, run the legal-consent test with the production flag on:
cd frontend && JYOTISHA_REQUIRE_LEGAL_ENTITY=1 npx tsx --test tests/legal-consent-20260930.test.tsx
It fails while frontend/src/lib/legal-entity.ts still holds placeholder operator details or the terms / privacy text is still marked draft. From 2026-11-01 to 2026-11-18 the manual release gate .gitea/workflows/release-quality-gate.yml ran this check automatically (#119 item 9); BUG-1991 removed it for the invite-only beta. Restore that line in the workflow before the public release.
Manual production deployment with Gitea Actions
GitHub production deployment is retired. Production changes are released only by manually dispatching .gitea/workflows/deploy-production.yml. main must be a fast-forward to the current staging head H. The deployed SHA is R, the latest successful staging push of backend-quality-gate, and deploy/is-docs-only-range.sh R H must exit 0 (exit 1 or 2 both refuse). Controller artifacts and image digests come from R. Public staging health must report R. The manual release gate may record H when H is docs-only ahead of R. Rollback still requires an explicit confirmation, a gate run, and ancestry inside reviewed main history. The workflow deploys immutable registry digests and never builds application images on the production host.
The internal verification mode is for pre-DNS checks on the new host. The public mode is for the same SHA after authoritative DNS and Caddy TLS converge. Neither mode imports data, applies pending migrations, or changes DNS.
Required Gitea Actions secret:
PRODUCTION_SSH_PRIVATE_KEY = one-line base64 of the dedicated deploy private-key file
The independently verified host key is stored in PRODUCTION_KNOWN_HOSTS. See the production migration runbook for all variables, data gates, and rollback boundaries.
Staging deployment
Staging is isolated from production:
| Item | Value |
|---|---|
| URL | https://staging.jyotisha.chat |
| Admin URL | https://admin.staging.jyotisha.chat |
| Host | 118.26.111.127 |
| Path | /opt/jyotisha-staging |
| Runtime app env | /opt/jyotisha-staging/.env.staging (0600) |
| Runtime database env | /opt/jyotisha-staging/.env.staging.database (0600) |
| PostgreSQL | private Compose network; no published host port |
| Business database | local private PostgreSQL (jyotisha-staging Compose project) |
| Identity | Better Auth + Resend OTP on the same private PostgreSQL cluster |
| Actions control plane | Gitea 1.26.2 (git.copse.top) |
Gitea is the primary source repository and Actions control plane. Gitea automatically injects the per-job ${{ secrets.GITEA_TOKEN }} token; its access is limited by each workflow's permissions block and it must not be configured as a repository secret. Configure repository Actions secrets REGISTRY_USERNAME, REGISTRY_PASSWORD, and STAGING_SSH_PRIVATE_KEY, plus variables STAGING_HOST, STAGING_PORT, STAGING_USER, STAGING_PATH, STAGING_URL, and STAGING_KNOWN_HOSTS. STAGING_SSH_PRIVATE_KEY must be the private-key file encoded as one unwrapped base64 line (for example, base64 < key | tr -d '\n'), not a multiline PEM/OpenSSH value; staging workflows decode it only into a mode-0600 temporary file and validate it with ssh-keygen. Staging is an independent test line and is not required to equal or remain inside main history. A push to staging runs the exact-SHA quality gate; its publish job creates immutable API/web image digests plus an allowlisted controller bundle from that same staging SHA, then explicitly dispatches Deploy staging from refs/heads/staging. The deploy workflow validates the source gate run, consumes only that gate-attested artifact, rejects stale normal releases, and never checks out or executes an untested branch controller. The staging key, database, Resend key, and model-provider keys must not be shared with production. Staging image publishing has no Supabase build variables. GitHub is a read-only mirror with no workflow files and Actions disabled; every staging and production workflow runs only in Gitea.
Independent Staging Quality Gate runs for relevant pull_request paths, pushes to staging, and workflow_dispatch. It validates the Python/database/frontend contract; only a successful push to staging publishes the API/web images and a run-bound artifact containing their sha256 digests plus the allowlisted controller bundle. The publish job rechecks the current staging head and dispatches .gitea/workflows/deploy-staging.yml from refs/heads/staging with the exact SHA and source gate run ID. The deploy workflow waits for that gate's success, validates the artifact against the full 40-character commit, and deploys digest references rather than trusting discoverability tags.
The gate's validation runs as two jobs at once on the xiaoxin runner: validate-python (ruff/compile, quick Python gate, privacy scan, package build) and validate-frontend (frontend and PostgreSQL tests, lint, non-push production build). publish needs both. Runner-host caches, all under /root/.cache and all rebuildable:
| Path | Contents | Lifetime |
|---|---|---|
jyotisha-mirror.git |
bare Git mirror for exact-SHA checkout | kept |
jyotisha-venvs/<key> |
gate venv from deploy/ci-python-venv.sh; key = Python version + ISO week + pins + requirements*.txt |
removed after 7 days unused |
jyotisha-pip |
pip download cache | kept |
jyotisha-npm |
npm download cache mounted into the npm ci container |
kept |
The web image build also uses BuildKit cache mounts (jyotisha-web-npm, jyotisha-web-next-v2); they live in the BuildKit store and are pruned by deploy/reclaim-runner-disk.sh only when the runner is short on disk. Deleting any of these only makes the next run slower. Right after next build the image build runs frontend/scripts/check-built-css.mjs: if a class from globals.css is missing from the built style sheets (the Next cache served an old sheet, BUG-2069) the build fails. The old sheet came from Turbopack's persistent build cache (.next/cache/turbopack, on by default in Next 16); frontend/next.config.ts sets experimental.turbopackFileSystemCacheForBuild: false, so a warm build no longer reuses compiled CSS (BUG-2136, reproduced and verified locally; Turbopack compile time was 21.0 s with and without it). If the check still fires, the cause is elsewhere: renaming the cache id only resets it once.
Every Web image build must pass that same full 40-character commit as the Docker
build argument NEXT_DEPLOYMENT_ID. Next.js embeds it during next build, adds
the deployment marker to rendered documents and static asset requests, and can
replace a stale client-side navigation with a full navigation when a release
changes underneath an already-open browser tab. Never omit it, substitute a
branch name, or set it only as a runtime environment variable: doing so can
leave users on an old client runtime that fails to load the new release's
immutable chunks.
The staging env file must include these non-secret selectors so Compose cannot fall back to production paths:
APP_ENV_FILE=../.env.staging
CADDYFILE_PATH=./Caddyfile.staging
SITE_ADDRESS=https://staging.jyotisha.chat
模型供应商的 base_url 不再依赖域名白名单,任意公网 HTTPS origin 均可由管理员配置;部署环境不需要 MODEL_PROVIDER_BASE_URL_ALLOWLIST。服务端仍强制 HTTPS、禁止凭据、localhost/内网/保留地址,并在 DNS 解析、请求地址 pinning 和重定向处理上执行 SSRF 防护。
Staging is fully self-hosted: set AUTH_PROVIDER=self-hosted and SELF_HOSTED_IDENTITY_ENABLED=true. Add the four role-specific server-only database URLs, the exact AUTH_USER_ORIGIN=https://staging.jyotisha.chat and ADMIN_USER_ORIGIN=https://admin.staging.jyotisha.chat, the single BETTER_AUTH_USER_SECRET, and staging-only Resend settings listed in deploy/.env.staging.identity.example. Both hosts run the same application and Better Auth service, but cookies remain host-only; the admin host / redirects to /admin, and unauthenticated admin requests continue to /login on that host. Better Auth trusts only those two origins, while unknown identity hosts fail closed. Persisted identity.users.role=admin is the only self-hosted backend role, while viewer and ordinary users are denied. Browser code uses same-origin APIs; it receives neither database credentials nor Supabase keys. Production uses the same architecture only after the reviewed migration and cutover. See docs/operations/self-hosted-identity.md for identity validation.
The web service already loads its env file, so these server-only switches do not need a Compose change. JYOTISHA_PG_METADATA_CACHE and JYOTISHA_PG_MERGED_SESSION_SETUP default to on when unset; set either to off to restore the previous database roundtrip sequence. IDENTITY_SESSION_COOKIE_CACHE defaults to off; set it to on to cache ordinary user-session reads for 300 seconds. Names and defaults are also in deploy/.env.staging.identity.example. Do not put secrets in these three values.
After source sync and before up, the workflow validates .env.staging mode/selectors, explicitly pins the three staging selectors against ambient shell overrides, and runs docker compose --env-file .env.staging -f deploy/docker-compose.server.yml config --quiet. For later manual inspections, run the same checks only after the tracked deployment files exist on the server. Do not use a manual gate run from main as the first publishing path: publishing requires a successful push to staging, while manual Deploy staging requires a successful push gate for the exact SHA and must use the staging workflow ref.
First-deploy sequence
- Complete the server and Gitea bootstrap: create both mode-
0600env files, preload the reviewedpostgres:17-alpineimage, and configure the listed Actions variables/secrets. No repository-level Supabase variables are required. Deployment and migration workflows use--pull neverfor PostgreSQL, so database image upgrades remain an explicit operator-controlled maintenance action rather than an application-deploy side effect. - Push the reviewed test revision directly to
staging. It may advance independently ofmain; do not merge or resetmainmerely to satisfy staging release mechanics. - The
Independent Staging Quality Gateruns for that push and, when successful, publishes API/web images plus an artifact binding the exact SHA to both immutable image digests and the allowlisted staging controller bundle. - The successful publish job rechecks that
stagingstill points at the exact SHA, then dispatchesMigrate Staging Databasefor that SHA, waits for it to succeed (no-op when nothing is pending), and only then dispatchesDeploy staging. You do not click either button for a normal push. Migration failure fails the gate and does not deploy. - If environment validation fails, fix the server-side env files without committing or copying secrets, then manually rerun
Deploy stagingusing Use workflow from: staging, the same successful SHA indeploy_sha, an emptygate_run_id, andallow_rollback=false; the workflow resolves a successful exact-SHA staging push gate before mutation. - The Migrate Staging Database button remains for rollback catch-up and one-off data repairs. Leave
deploy_shaempty unless you are targeting an earlier gated SHA. A manual run does not dispatch deployment. - Confirm
https://staging.jyotisha.chat/api/healthreports the SHA from step 2.
Resetting one staging account
.gitea/workflows/reset-staging-account.yml (Reset Staging Account (manual only)) wipes the onboarding profile, chat sessions, chart profiles, and synastry reports of exactly one staging account while preserving its identity rows, credits, and ledgers. Dispatch it from Use workflow from: staging with expected_deploy_sha equal to the SHA currently reported by https://staging.jyotisha.chat/api/health, email set to the exact account address, and confirmation typed as RESET <email>. It shares the staging-mutation concurrency group and the on-host mutation.lock with deploy and migration, refuses to run unless the deployed revision matches expected_deploy_sha, and pipes deploy/reset-staging-account.sh to the staging host over the same pinned STAGING_SSH_PRIVATE_KEY / STAGING_KNOWN_HOSTS channel. It never touches production variables or hosts.
Application rollback uses the same workflow: manually dispatch Deploy staging using Use workflow from: staging with a previous known-good full SHA that has a successful Independent Staging Quality Gate push run, leave gate_run_id empty, and explicitly set allow_rollback=true. The requested SHA must be an ancestor of the current staging head. Normal deployments reject stale or divergent revisions. Rollback still consumes the selected gate run's digest and controller artifact and is supported only during that artifact's 30-day retention window; after expiry, stop and prepare a separately reviewed republish/recovery change rather than substituting a mutable tag or assuming the old run can still be rerun. Database migrations are separate and are not rolled back by an application deployment. Restore a staging database backup before running any destructive migration rehearsal.
Inspect staging without printing secrets:
ssh -i ~/.ssh/jyotisha-staging deploy@118.26.111.127
cd /opt/jyotisha-staging
docker compose --env-file .env.staging -f deploy/docker-compose.server.yml ps
docker compose --env-file .env.staging -f deploy/docker-compose.server.yml logs --tail=100 api web caddy
curl -fsS https://staging.jyotisha.chat/api/health
The normal application deployment workflow never runs database migrations. Apply migrations to the private staging PostgreSQL cluster first, verify them, and only then deploy application code that depends on them.
One-off data repairs go through the same Migrate Staging Database button, not through ad-hoc scripts on the host: ship the repair as an ordinary migration under frontend/supabase/migrations/ so the migrator applies it exactly once, and have it report how many rows it touched with RAISE NOTICE. scripts/db-migrate.mjs forwards notices, so those counts appear in the migration run log as notice <message> lines — that log is where you read the result. Write such repairs to be idempotent anyway (their where must stop matching rows they already fixed), so a manual re-run cannot double-apply. frontend/supabase/migrations/20260916020000_rectification_session_title_repair.sql is the worked example.
Staging PostgreSQL operations
This section is the server-side runbook for the disposable staging PostgreSQL volume. It does not replace the production instructions above.
Bootstrap and environment-file boundary
SSH to the staging host as the deployment user and create both environment files with a restrictive umask. The application file and the database file are separate, both are mode 0600, the database file is owned by the deployment user, and neither is committed or copied through rsync:
cd /opt/jyotisha-staging
umask 077
touch .env.staging
chmod 600 .env.staging
touch .env.staging.database
chmod 600 .env.staging.database
.env.staging contains application selectors and server-only application credentials. SCHEMA_DATABASE_URL must not appear in .env.staging; neither may any database bootstrap password, STAGING_BACKUP_ENCRYPTION_KEY, or migration-runner credential. In particular, there is no SCHEMA_DATABASE_URL or SERVICE_RUNTIME_PASSWORD in .env.staging; the schema URL and raw role password exist only in .env.staging.database, which is read by PostgreSQL and the opt-in migrator. The web/API runtime receives only the percent-encoded SERVICE_DATABASE_URL from .env.staging.
Generate every <generated> value from independently generated 32 random bytes (for example, run openssl rand -base64 32 separately for each value and place it directly into the mode-0600 file or an approved secret store). Do not reuse a password between roles, paste values into chat, commit either file, or print them in workflow logs. The schema-owner password in SCHEMA_DATABASE_URL is the same secret as SCHEMA_OWNER_PASSWORD; use a percent-encoded URL password component only, and do not encode the scheme, host, port, or database name.
The exact database keys are:
POSTGRES_DB=jyotisha
POSTGRES_USER=postgres
POSTGRES_PASSWORD=<generated>
SCHEMA_OWNER_PASSWORD=<generated>
IDENTITY_RUNTIME_PASSWORD=<generated>
APP_RUNTIME_PASSWORD=<generated>
SERVICE_RUNTIME_PASSWORD=<generated>
ADMIN_RUNTIME_PASSWORD=<generated>
MIGRATION_RUNNER_PASSWORD=<generated>
BACKUP_READER_PASSWORD=<generated>
STAGING_BACKUP_ENCRYPTION_KEY=<generated>
SCHEMA_DATABASE_URL=postgresql://schema_owner:<percent-encoded-password>@postgres:5432/jyotisha
Use the same independently generated service-role secret in exactly two host-managed locations: the raw SERVICE_RUNTIME_PASSWORD in .env.staging.database, and its percent-encoded password component in SERVICE_DATABASE_URL=postgresql://service_runtime:<percent-encoded-password>@postgres:5432/jyotisha inside .env.staging. Keep both files owned by the staging deploy user with mode 0600. The deploy controller runs both validators with shell tracing disabled before Compose changes; Gitea stores neither value and the workflow must never echo, interpolate, or pass either password as a workflow environment variable.
PostgreSQL is private: deploy/docker-compose.postgres.yml has no ports mapping, so the staging database is reachable only on the Docker app network. The CI overlay is the only host binding and is loopback-only (127.0.0.1:${POSTGRES_HOST_PORT:-55432}:5432); do not add a public database port, firewall exception, or browser-facing SQL tool. Normal web/API containers never receive SCHEMA_DATABASE_URL.
Exact deployment and migration order
Use this order for every staging revision:
- Review the test change, then push its exact commit directly to
staging;mainmay remain at a different SHA. - Wait for
Independent Staging Quality Gateto pass and publish that exact full SHA's API/web digest and controller artifact. Its publish job first dispatchesMigrate Staging Databasefor that SHA and waits for success (a no-op when nothing is pending), then dispatchesDeploy staging. Do not click either button for a normal push. Ifstagingalready advanced by a gated path, dispatch is refused. - The dispatched
Deploy stagingworkflow still validates the source gate run and checks the exact SHA in read-only migration-check mode before changing API, web, or Caddy. After the automatic migrate, that check should be clean. If it reports pending or drifted migrations, stop; do not retry the application deployment as if it were a migration. - Use Migrate Staging Database manually only for rollback catch-up or a one-off data repair. Leave
deploy_shaempty unless targeting an earlier gated SHA. A manual run does not dispatch deployment. - Confirm
https://staging.jyotisha.chat/api/healthand verify that its deployment SHA is the SHA from step 2. - After health verification, create the local encrypted backup described below.
Deploy Production and Migrate Production Database stay fully manual. They still require a hand-filled 40-character SHA. For a forward release that SHA is R (the latest gated staging push that is docs-only behind the shared main/staging head), plus allow_rollback / recovery attestation (restore_verified is a person's guarantee that the recovery point restores). Do not copy the staging automatic migrate-then-deploy shortcut onto production.
The deploy and migration workflows share the staging-mutation Actions concurrency group, and their live-tree sync plus Compose work runs under /opt/jyotisha-staging/.state/mutation.lock. The synchronized tree explicitly preserves /backups/, .env*, .state, and .incoming. The read-only checker still exits before app changes when a migration is pending. After the automatic pre-deploy migrate that should be rare. A failed automatic migration fails the quality gate and does not dispatch deployment. Application rollback restores the previously recorded digest references and SHA, falling back to validated local image IDs only when transitioning from the pre-foundation local-image deployment; it does not roll back database state.
Production recovery point before schema migration
Use Gitea Actions → Create Production Recovery Point before every production schema migration. Dispatch it from current main (the staging head H) and set deploy_sha to R. main and staging must be the same SHA, R must be a docs-only ancestor of that SHA, public staging health must report R, and the release gate must have succeeded for R or for that same head. It uses the pinned production SSH identity, shares the production-mutation lock, and runs deploy/run-production-recovery.sh with shell tracing disabled. The migration rehearsal has no Gitea button; the product runs deploy/rehearse-production-migrations.sh from the runbook.
The host script writes an AES-256-CBC/PBKDF2 encrypted custom-format PostgreSQL dump under /opt/jyotisha-production/backups, restores it into a uniquely named disposable database, validates non-sensitive row/table counts, removes only that disposable database, and writes a mode-0600 verification manifest. Before acquiring the shared host lock it validates that .state and backups are real directories, then reuses the existing passwordless Docker boundary to run the already-loaded PostgreSQL image with no network, a read-only root filesystem, all capabilities dropped except CHOWN, and only the two directories plus the verified existing lock inode bind-mounted. That helper exposes the regular mutation.lock directly at /mutation.lock, restores that inode before changing its mode-0700 parent directory, then restores the two directory mount points to the current deploy UID/GID. The direct file mount avoids depending on traversal through a parent left half-repaired by an earlier failed run, without adding DAC_OVERRIDE; it never recursively changes backup files or removes or replaces a lock inode. The workflow retrieves only the encrypted dump and verification metadata, verifies the SHA-256 digest, and uploads them as a 30-day Gitea Actions artifact with compression disabled. The artifact-backed recovery_reference, recovery_created_at, and restore_verified=true output are the inputs for Migrate Production Database. Do not use the attestation if backup, restore, retrieval, digest validation, ownership normalization, or artifact upload fails.
Never restore over jyotisha, delete the PostgreSQL volume, print .env.production.database, expose PRODUCTION_BACKUP_ENCRYPTION_KEY, or substitute a staging recovery artifact. The encrypted local archive is preserved for repair; the Actions artifact supplies the required off-host copy.
Production off-site backups (OSS)
给负责人的说明: 每天北京时间 04:45,生产主机自己把当天已经做过还原核对的加密备份上传一份到阿里云 OSS(存储桶 jyotisha-db-backup,深圳)。平时这份备份由 Gitea 的「Backup Production Daily」在 04:00 做好;如果那一次没跑(比如 runner 掉线),04:45 这一步会自己先做备份和还原核对,再上传。上传用的子账号只能往 production/ 里放文件,不能看、不能下载、不能删;旧文件靠存储桶的生命周期规则在 30 天后删除。失败时写 .state/offsite-backup-failed 并发一条飞书告警(没配飞书就记在本机 alerts.log)。这些都还没装到服务器上,装法见下面,要你点头后再装。
What runs: deploy/backup-production-offsite.sh (systemd jyotisha-production-backup.timer, daily 04:45 Asia/Shanghai, Persistent=true).
- If
.state/daily-backup-latest.envis older than 26 hours (or missing), it runsdeploy/run-production-recovery.shwithRECOVERY_BASENAME_PREFIX=production-daily, so the dump, encryption (AES-256-CBC/PBKDF2 withPRODUCTION_BACKUP_ENCRYPTION_KEY) and restore check are the same as the Gitea daily workflow. Exit 75 (host lock held) is reported ashost_locked. - It checks the recorded sha256, then PUTs
production/<UTC time>-<sha256 prefix>.dump.encand the matching-restore-verify.jsonto OSS with an OSS V1 signature (HMAC-SHA1) computed in the script,Content-MD5, three attempts, and anETagequal to the local MD5. The key and secret never appear in argv, stdout or stderr: the env file is parsed line by line, HMAC is built fromopenssl dgst -sha1over stdin, and curl reads its headers from--config -. - It writes
.state/offsite-backup-latest.env(UPLOADED_AT,OBJECT_KEY,BUCKET,SHA256,SIZE_BYTES,BACKUP_BASENAME,VERIFIED_AT,STATUS, mode0600). The same sha256 is never uploaded twice. Local copies follow the existingprune-production-daily-backups.shretention.
On failure it writes .state/offsite-backup-failed (FAILED_AT, REASON) and sends service=host route=- errorCode=offsite_backup_failed through deploy/monitor/notify-feishu.sh with /opt/jyotisha-production/.monitor.env. The next success removes the marker and sends offsite_backup_recovered. The existing disk-mode monitor still alerts backup_stale when the restore-verified daily backup is older than 36 hours.
Install (owner approves first)
Add four lines to /opt/jyotisha-production/.env.production.database without printing the file (for example sudoedit or an editor on the host; never cat, never paste into chat):
OSS_BACKUP_ACCESS_KEY_ID=<RAM user jyotisha-backup-writer>
OSS_BACKUP_ACCESS_KEY_SECRET=<its secret>
OSS_BACKUP_BUCKET=jyotisha-db-backup
OSS_BACKUP_ENDPOINT=oss-cn-shenzhen.aliyuncs.com
The RAM user's only policy:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": ["oss:PutObject"],
"Resource": ["acs:oss:*:*:jyotisha-db-backup/production/*"]
}
]
}
Bucket lifecycle (console → Bucket → 数据管理 → 生命周期): prefix production/, current versions expire after 30 days, historical (noncurrent) versions deleted after 30 days, delete markers cleaned.
After the next production sync has placed the files under /opt/jyotisha-production/deploy/:
sudo install -m 0644 /opt/jyotisha-production/deploy/systemd/jyotisha-production-backup.service /etc/systemd/system/
sudo install -m 0644 /opt/jyotisha-production/deploy/systemd/jyotisha-production-backup.timer /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now jyotisha-production-backup.timer
systemctl list-timers jyotisha-production-backup.timer
Run one backup by hand and read the result (no secrets are printed):
sudo systemctl start jyotisha-production-backup.service
systemctl status --no-pager jyotisha-production-backup.service
cat /opt/jyotisha-production/.state/offsite-backup-latest.env
Restore drill from OSS
The server key cannot read OSS. Download the object yourself from the OSS console (or with a separate read-only key on another machine), copy it to the host as /opt/jyotisha-production/backups/offsite-drill.dump.enc (mode 0600), check its sha256 against SHA256 in offsite-backup-latest.env, then follow docs/operations/production-restore-drill-20261014.md with that file: create the disposable database jyotisha_restore_check, decrypt with PRODUCTION_BACKUP_ENCRYPTION_KEY into pg_restore --exit-on-error, record only the four counts (identity.users, public.profiles, public.credit_transactions, number of public tables) and compare them with the matching -restore-verify.json, then DROP DATABASE "jyotisha_restore_check" WITH (FORCE) and delete offsite-drill.dump.enc. Never restore over jyotisha.
When the alert fires
Read REASON in /opt/jyotisha-production/.state/offsite-backup-failed:
missing_env: one of the four OSS lines is missing or malformed.upload_failed: network or OSS refused the PUT (wrong key, wrong endpoint, policy).journalctl -u jyotisha-production-backup.serviceshows the HTTP status.etag_mismatch: OSS stored something different from the local file; run the service again.daily_backup_failed/host_locked: the dump or restore check failed, or a deploy/migration held the host lock; run again after it finishes.checksum_mismatch: the local file no longer matches its record; do not upload it, take a new recovery point.
Local encrypted staging backups (three-copy limit)
After the health check, run the repository backup helper from the synchronized staging checkout:
cd /opt/jyotisha-staging
./deploy/backup-staging-postgres.sh \
.env.staging.database \
/opt/jyotisha-staging/backups/staging-db
The helper invokes pg_dump --format=custom --no-owner in the PostgreSQL container and encrypts the stream with openssl enc -aes-256-cbc -salt -pbkdf2 -pass env:STAGING_BACKUP_ENCRYPTION_KEY. It creates mode-0600 .dump.enc files in a mode-0700 directory, refuses disk usage at or above 70%, publishes atomically, and retains only the newest three encrypted local backups. The encryption passphrase is supplied through the environment, never as a command-line argument or printed value. Keep the archive directory on this staging VPS only; there is no off-site staging recovery and no off-site staging backup. These three local encrypted copies are rehearsal/rollback aids, not disaster-recovery backups.
Do not back up the API api_scratch volume. Chart cache (/app/scratch/local/api_chart_cache) is a disposable TTL cache; restoring it has no user-visible correctness value. Async job records (async_jobs / async_jobs.sqlite3 and high_rigor_jobs) expire within an hour by default and represent in-flight work, not durable product state. A staging or production restore is a PostgreSQL restore. Recreating the API container without the named volume only drops cache and in-flight jobs, which is the same loss the overlay filesystem already had before this volume existed.
Restore drill into a disposable database
Run a restore drill only against the disposable jyotisha_restore_check database. Choose one archive and use a temporary decrypted custom-format dump; the commands below match the backup helper's AES-256-CBC/PBKDF2 and pg_dump --format=custom interfaces:
set -euo pipefail
cd /opt/jyotisha-staging
export DATABASE_ENV_FILE=../.env.staging.database
BACKUP_DIR=/opt/jyotisha-staging/backups/staging-db
BACKUP_FILE="$(find "$BACKUP_DIR" -maxdepth 1 -type f -name 'jyotisha-staging-*.dump.enc' -print | LC_ALL=C sort | tail -n 1)"
test -n "$BACKUP_FILE"
test -f "$BACKUP_FILE"
test ! -L "$BACKUP_FILE"
test -s "$BACKUP_FILE"
RESTORE_DUMP="$(mktemp /tmp/jyotisha-staging-restore.XXXXXX.dump)"
chmod 600 "$RESTORE_DUMP"
trap 'rm -f -- "$RESTORE_DUMP"' EXIT
read -r -s -p 'Backup passphrase: ' STAGING_BACKUP_ENCRYPTION_KEY
printf '\n' >&2
export STAGING_BACKUP_ENCRYPTION_KEY
openssl enc -d -aes-256-cbc -pbkdf2 \
-pass env:STAGING_BACKUP_ENCRYPTION_KEY \
-in "$BACKUP_FILE" -out "$RESTORE_DUMP"
docker compose -p jyotisha-staging -f deploy/docker-compose.postgres.yml \
exec -T postgres createdb -U postgres jyotisha_restore_check
docker compose -p jyotisha-staging -f deploy/docker-compose.postgres.yml \
exec -T postgres pg_restore -U postgres --no-owner --exit-on-error \
--dbname=jyotisha_restore_check < "$RESTORE_DUMP"
# Inspect the restored disposable database, then remove only the drill target.
docker compose -p jyotisha-staging -f deploy/docker-compose.postgres.yml \
exec -T postgres dropdb -U postgres --if-exists jyotisha_restore_check
rm -f -- "$RESTORE_DUMP"
unset STAGING_BACKUP_ENCRYPTION_KEY
The passphrase is read silently into an environment variable; do not put it in argv, shell history, logs, or support messages. The cleanup scope is deliberately narrow: delete only jyotisha_restore_check and the temporary decrypted dump. Do not run docker compose down, down -v, dropdb jyotisha, volume deletion, or archive deletion as part of this drill. If restore fails, preserve the encrypted archive and PostgreSQL volume for inspection, remove only the temporary dump, and investigate before retrying.
Staging/production boundary
This disposable staging procedure does not authorize a production migration, production backup policy, production database replacement, domain switch, Supabase deletion, or production cutover. Production deployment and migration remain manual-only and require a separate reviewed approval, off-site encrypted backups, and a successful production restore drill. Keep the production .env.production and all production credentials on the production host; never copy them into staging.
Manual deployment fallback
There is no unreviewed rsync/build fallback for the new production. If Gitea Actions or the immutable artifact is unavailable, stop the release and restore the control plane; do not substitute a mutable image tag or copy a local working tree to production.
Verification
curl -fsS https://jyotisha.chat/login >/dev/null
curl -fsS -o /dev/null -w '%{http_code}\n' https://jyotisha.chat/api/account
The second command should return 401 while logged out. Verify the private Python API from inside the web container:
ssh -p <confirmed-port> deploy@83.229.126.99 \
'cd /opt/jyotisha-production && docker compose -p jyotisha-production --env-file .env.production -f deploy/docker-compose.server.yml -f deploy/docker-compose.postgres.yml -f deploy/docker-compose.production.yml exec -T web node -e "fetch(\"http://api:5200/api/health\").then(async r=>{console.log(r.status); console.log(await r.text())})"'
Expected: HTTP 200, "status": "ok", and "swisseph_available": true. Public access to 83.229.126.99:5200 and :5432 must fail. The deployment workflow also executes SELECT 1 through all four runtime database roles.
Do not treat a green app deployment as proof of database migration or data reconciliation. The production deployment refuses pending target migrations but does not apply them. Follow the schema-first ETL and verification gates in the production migration runbook. Supabase remains the read-only rollback source until the retention and reconciliation window closes.
Agentic birth-time rectification
The maintained web flow uses POST /api/rectification/agent. It has no standalone
rectification worker and no V3/V4 rollout selector. Apply all pending forward
migrations before deploying the matching web image; never delete or reverse the
historical migrations or their billing, receipt, and audit rows.
After an exact-SHA deployment, verify /api/health, then use a synthetic account
to confirm the browser calls /api/rectification/agent. Confirm retired unfinished
cases do not block the Agentic
entry, charging remains idempotent, and a previously accepted or confirmed
profile time is not changed without an explicit current acceptance. Do not record
birth data, narrative, account identifiers, tokens, or model prompts in smoke
evidence.
After a report-centre deployment, also run the authenticated list/detail/create
smoke in docs/operations/personal-report-staging.md (section “Post-deploy
report list / detail / create smoke”): GET /api/reports 200, owned
GET /api/reports/<id> 200, and one new POST /api/reports through ready.
运维与告警
这些步骤要等本分支进入 main 之后,由产品在主机上安装。仓库里没有 Webhook 地址。告警正文只允许服务名、路由、错误码、次数、requestId 和时间。
备份
- 工作流:
.gitea/workflows/backup-production-daily.yml。北京时间每天 04:00,也可手动触发。只从main运行,调用deploy/run-production-recovery.sh,不另写一套导出。 - 每日文件前缀是
production-daily-。手动恢复点仍是production-pre-migration-。清理脚本deploy/prune-production-daily-backups.sh只删超过 7 天的每日文件和对应的校验文件,不会删production-pre-migration-手动恢复点。清理排在新备份之前,所以磁盘到 70% 时过期的每日文件仍会被清掉。 - 每日备份只做存档和还原核对,不是发布用的恢复点。它不改
/opt/jyotisha-production/.state/recovery-baseline.env。核对结果另写在同目录的daily-backup-latest.env,只有文件名、sha256、核对时间和格式版本,没有数据和密钥。发布、迁移、回退都不读这个文件。上线前仍要手动点 Create production recovery。 - Gitea 产物默认保留 14 天。手动恢复点工作流仍是 30 天,没有改。
- 还原步骤:
docs/operations/production-restore-drill-20261014.md。
告警装在哪(BUG-2348)
一条命令装好主机上的全部监控,可以重复运行:
sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh
sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh --test-alert
它写 /etc/cron.d/jyotisha-production-monitor(root 运行,输出进 syslog,标签 jyotisha-monitor):
| 频率 | 脚本 | 看什么 |
|---|---|---|
| 每分钟 | healthcheck-alert.sh --mode all |
本机看到的 /api/health(连续 3 次失败告警、恢复发一次);磁盘 ≥80%;每日备份超过 36 小时没核对成功 |
| 每 5 分钟 | error-digest.sh --window |
web/api 日志里的错误码和 5xx;计算服务 429;[ops-signal] 信号(验证码发信失败、模型花费超标、切到备用模型) |
| 北京时间 09:00 | error-digest.sh --daily |
前一天的汇总 |
| 每 5 分钟 | ops-check.sh |
容器自己重启或被 OOM 杀;主机可用内存 ≥90% 已用;报告排队最久的任务超过 10 分钟没开始;有新的用户反馈(只发条数) |
服务器整台不可达时本机发不出告警,所以另有一个服务器之外的探活:Gitea 工作流 .gitea/workflows/monitor-public-health.yml,在 runner 上每 5 分钟访问三次 https://jyotisha.chat/api/health,连续三次失败告警一次,恢复发一次。它用仓库 Actions 密钥:MONITOR_FEISHU_WEBHOOK_URL、MONITOR_FEISHU_SIGN_SECRET(可空)、MONITOR_ALERT_EMAIL_TO、MONITOR_ALERT_EMAIL_FROM、MONITOR_RESEND_API_KEY。runner 关机时这一路也停,Gitea 里能看到运行记录断了。
发布窗口:版本号变化在本机和 runner 上都不再告警(JYOTISHA_COMMIT_ALERT=off),发版本身由部署工作流记录。
阈值(5 分钟窗口):一般错误码 10 次、5xx 20 次;验证码发信失败 3 次;花费超标 1 次;备用模型 3 次;供应商错误 3 次;超时、空回答 5 次;计算服务 429 合计 10 次。同一服务、路由、错误码 30 分钟内只发一次。容器、内存、排队、探活、磁盘、备份这几类是“开一次、恢复一次”。
通道写在 /opt/jyotisha-production/.monitor.env(模式 0600,不提交):
FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/<token>
FEISHU_SIGN_SECRET=<只有开了签名校验才填>
ALERT_EMAIL_TO=<收告警的邮箱,最多 5 个,用逗号隔开>
邮件用 .env.production 里已有的 RESEND_API_KEY 和 RESEND_FROM_EMAIL 发(只读这两行,不打印)。想换发件人可在 .monitor.env 里加 ALERT_EMAIL_FROM=。两个通道都配时两边都发;只要有一个接收成功就算发出,都失败时不记成已发送,下一轮再试。一个都没配时只写本机 /var/lib/jyotisha-monitor/alerts.log。
告警正文:第一行「Jyotisha 生产告警」,每条先是一句固定的中文说明(来自 notify-feishu.sh 里的对照表),再是 service=… route=… errorCode=… count=… requestId=… time=… 这一行。日志里的文字不会进告警。
应用里的信号:frontend/src/lib/ops-signal.ts 打一行 [ops-signal] {"errorCode":"…","route":"…","upstream":"…"}。只允许固定的错误码(otp_send_failed、model_spend_alert、model_fallback_used),没有邮箱、用户、正文或供应商原文。验证码发信遇到网络错误、429 或 5xx 会用同一个幂等键重试一次,仍失败才打 otp_send_failed。
验证码邮件的发信域名:在 Resend 后台 Domains 里确认发件域名的 SPF、DKIM 是 Verified,DNS 里有一条 DMARC 记录(_dmarc.<域名> TXT,至少 v=DMARC1; p=none)。上线后用一个新邮箱实收一封验证码,看是否进了垃圾箱。
日志轮转
deploy/docker-compose.server.yml 和 deploy/docker-compose.postgres.yml 的每个服务都是 json-file,单文件 20 MB,最多 10 个文件。镜像、环境变量、端口和健康检查没有改。要等生产容器按新编排重建后才生效。
看守护进程默认值:docker info --format '{{.LoggingDriver}}',以及主机上的 /etc/docker/daemon.json。编排里的 logging 会盖过守护进程对这几个服务的默认值。
按 requestId 查日志
在生产主机上,只读:
deploy/find-request-log.sh <requestId> --since 24h
<requestId> 必须是 UUID。其它写法会拒绝,避免被当成命令。--since 只接受类似 24h、30m 的形式。容器日志行前面的服务名前缀会先去掉,再按时间排序。来自 web、api、caddy。
Common operations
# Restart without rebuilding
docker compose -p jyotisha-production --env-file .env.production \
-f deploy/docker-compose.server.yml -f deploy/docker-compose.postgres.yml \
-f deploy/docker-compose.production.yml up -d
# Pull/deploy application images only through the exact-SHA Gitea workflow.
# Follow logs
docker compose -p jyotisha-production --env-file .env.production \
-f deploy/docker-compose.server.yml -f deploy/docker-compose.postgres.yml \
-f deploy/docker-compose.production.yml logs -f --tail=100 postgres api web caddy
Optional Railway deployment
Railway is not the current production target. If needed, create web and api services from the same repository using deploy/railway-web.Dockerfile and deploy/railway-api.Dockerfile; keep api private and set the web service's JYOTISH_API_BASE to Railway's private API hostname.