Files
loki/scripts/deploy-hetzner.sh
CatoandClaude Opus 5.5 18d34dff0a fix(notify): OpenClaw jobs send only what has one tap; close the review's critical/high findings (#1542)
* fix(openclaw): every scheduled job sends only what has one tap, else NO_REPLY

On 2026-11-02 the chat still carried OpenClaw's own messages that fail the
owner's test: "Invoice / Payment Alert … if credit card is on file, no
action needed", "Gateway was not running. Restarted automatically. All good
now." The scheduled jobs' prompts live only on the box, so:

- contract.md: one short block appended (between markers, replaced on each
  install) to every enabled job except the day plan: send only what needs
  him, each item with the ONE link that does it, never status or counts, and
  reply exactly NO_REPLY when nothing passes — OpenClaw's documented silent
  token, which suppresses delivery.
- The installer lists, by path only, every file on the box that calls the
  Telegram API or says "restarted automatically", so the remaining sender is
  found from the public log without printing anything private.
- Notices carry no machine name ("orangecat-cat · …"); the source stays on
  the list row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtzUbLhg3oqt4X1NaN

* docs(telegram): register the day-plan installer (it only searches for senders)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtzUbLhg3oqt4X1NaN

* fix(notify): close the review's critical and high findings

An independent review of the messaging system found real defects; these
are the ones that lose an urgent message, send a wrong one, or wake him:

- Intrusions could be dropped: the caps held urgent notices, every SSH
  password login shared one dedupe key, and /api/notify/box answered 200
  when nothing was recorded, so the box never used its direct fallback.
  Urgent notices skip the caps, intrusion lines are keyed on the whole line,
  and the route answers 503 when an urgent line was not delivered.
- A link chosen by an email could become a trusted one-tap button. Buttons
  now open only own domains, Gmail, Google Calendar, GitHub or Hetzner.
- Long titles/labels or a fourth button dropped real notices into the list;
  they are clipped instead. Only a missing or unsafe action refuses.
- SSH login from a new address and edits to authorized_keys/sudoers/shadow/
  PAM/ld.so.preload are intrusion signs (both lists, kept equal by test);
  the button opens /today, where the notice is listed; the title names the box.
- Customers' escalations and capped goals reached the owner's chat
  (selfTelegramTarget); they now use telegramTargetFor. The gateway-down
  message went once per fleet account; it is sent once.
- The notify routes accept bearer tokens only (no browser session/CSRF).
- countDeliveries ignored rows older than a week; it no longer does.
- Night silence (22:00–07:00 Zurich) for the direct senders too: lib-alert's
  fallback, ivy-health, fleet-uptime, deploy-hetzner. ivy-health names what
  broke and offers Redeploy only when Loki's app is the failure, Box doctor
  otherwise, and reads the chat id from the box's telegram.env.
- Prompts: the day plan no longer asks for approve links it cannot get or a
  page it cannot open, never uses links found inside emails, and says when a
  source failed. The summaries he asked for (reflection, digests, scorecard,
  evening wrap) get a digest contract instead of being silenced; jobs with no
  text prompt are left untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtzUbLhg3oqt4X1NaN

* feat(day-plan): one morning message; the email scanner twice a day

Approved by the owner 2026-11-02. The day plan now carries a half-line on
each person he meets today, and the separate 07:30 "Meeting People Brief"
is switched off. The email deadline scanner runs at 08:00 and 17:00 instead
of four times a day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtzUbLhg3oqt4X1NaN

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-02 08:46:52 +01:00

648 lines
38 KiB
Bash

#!/usr/bin/env bash
# deploy-hetzner.sh — ship the production build to the bitbaum Hetzner box.
#
# The box serves Loki at https://loki.orangecat.ch (Caddy →
# 127.0.0.1:4002, systemd unit loki-app). Box-side .env, launch.sh and
# backups/ are owned by the box and never touched by a deploy.
#
# Also syncs + restarts loki-box-runner (the always-on cloud builder).
# First-time install: bash scripts/hetzner/install-box-runner.sh
#
# Usage:
# bash scripts/deploy-hetzner.sh # build + rsync + restart
# bash scripts/deploy-hetzner.sh --no-build # rsync an existing build
set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/hetzner/_box-env.sh" # SSOT: HETZNER_IP, BOX_ROOT, BOX_UBUNTU
HOST="$BOX_ROOT"
APP_DIR="/opt/loki/app"
# The box-runner's Unix owner. Defaults to ubuntu; set to fcrunner AFTER running
# migrate-box-runner-to-fcrunner.sh so the runner-code sync doesn't chown the
# dir back to ubuntu on every deploy. The app + bridge stay ubuntu-owned.
RUNNER_OWNER="${LOKI_RUNNER_OWNER:-ubuntu}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
STANDALONE="$PROJECT_DIR/.next/standalone"
# Args:
# --no-build rsync the existing $STANDALONE as-is
# --ref <sha> only build+ship if the working tree is STILL on that commit
# (used by the push-deploy hook). `npm run build` always compiles
# the floating working tree, so a hook that fires after you've
# switched branches would otherwise ship the wrong ref (it once
# shipped an off-main feature branch to the box). An isolated
# worktree would be ideal but Turbopack rejects an out-of-root
# node_modules symlink, so we guard in-place instead: build only
# when HEAD == ref, and re-check HEAD after the build so a switch
# mid-build can't ship a torn tree. On drift we skip loudly
# rather than ship wrong code.
NO_BUILD=""; REF=""
while [ $# -gt 0 ]; do
case "$1" in
--no-build) NO_BUILD=1; shift ;;
--ref) REF="${2:-}"; shift 2 ;;
*) shift ;;
esac
done
# Normalize --ref to a full SHA: git_head returns 40 chars, and the pinned-deploy
# guard compares literally, so a short ref would always "mismatch" and skip.
if [ -n "$REF" ]; then
REF="$(git -C "$PROJECT_DIR" rev-parse --verify --quiet "${REF}^{commit}")" \
|| { echo "✗ --ref does not resolve to a commit: $REF" >&2; exit 1; }
fi
# Alert the operator (Telegram) when a deploy fails AND cannot roll back — with
# one button, the Deploy workflow. A clean rollback is not paged. A silently
# broken ship + a silent rollback both left the box in an unknown state with
# nobody told; this closes that loop. Reads the box's own bot creds and sends
# from the box. Best-effort — a failed alert never affects the deploy. The
# message is base64'd so arbitrary text survives the ssh boundary unquoted.
deploy_alert() {
local b64; b64=$(printf '%s' "$1" | base64 -w0 2>/dev/null || printf '%s' "$1" | base64)
ssh "$HOST" "bash -s" <<REMOTE 2>/dev/null || true
E=/opt/loki/app/.env
T=\$(grep -oP '^TELEGRAM_BOT_TOKEN=\K.*' "\$E" 2>/dev/null | tr -d '"')
C=\$(grep -oP '^APP_TELEGRAM_CHAT_ID=\K.*' "\$E" 2>/dev/null | tr -d '"')
MSG=\$(echo '$b64' | base64 -d)
[ -n "\$T" ] && [ -n "\$C" ] && curl -s -m 10 -o /dev/null \
"https://api.telegram.org/bot\$T/sendMessage" \
--data-urlencode "chat_id=\$C" \
--data-urlencode "text=🚨 Loki deploy: \$MSG" \
--data-urlencode "disable_notification=\$(h=\$(TZ=Europe/Zurich date +%H); h=\${h#0}; [ "\${h:-0}" -ge 22 ] || [ "\${h:-0}" -lt 7 ] && echo true || echo false)" \
--data-urlencode 'reply_markup={"inline_keyboard":[[{"text":"Redeploy Loki","url":"https://github.com/bitbaum/loki/actions/workflows/deploy.yml"}]]}' || true
REMOTE
}
# ── Serialize deploys (fix: concurrent-build collision) ──────────────────────
# Two near-simultaneous pushes to main each background a deploy; without a lock
# both run `npm run build` in the shared .next tree and collide ("Another next
# build process is already running"), and the OLDER ref can win the race. A
# blocking lock serializes deploys so the NEWEST ref ships last; every step
# below is idempotent, so waiting is always safe.
LOCK_FILE="${LOKI_DEPLOY_LOCK:-/tmp/loki-deploy.lock}"
exec 9>"$LOCK_FILE"
if command -v flock >/dev/null 2>&1; then
if ! flock -w 900 9; then
echo "✗ deploy: timed out after 15m waiting for an in-flight deploy — aborting" >&2
exit 1
fi
fi
# ── Deploy-result sink (fix: exit 0 masked failed deploys) ───────────────────
# The push-deploy hook backgrounds this script and its exit code dies in a
# detached log nobody reads. Record every outcome: a final status line, a
# desktop notification (best-effort), and a row in the box debug_logs so a
# failed deploy surfaces on /system instead of being invisible until a 503.
DEPLOY_REF_SHORT="$(git -C "$PROJECT_DIR" rev-parse --short "${REF:-HEAD}" 2>/dev/null || echo unknown)"
# Which phase we are in, so a deploy killed by `set -e` on a SILENT command
# still says where it died. #289 fixed one such command; this makes the next
# one diagnosable instead of a fresh investigation. The marker read failed with
# both streams redirected to /dev/null, so the entire trace was
# "deploy FAILED (exit 1)" plus a path to a log on an ephemeral CI runner —
# which is not a diagnosis. Naming the step costs one variable.
DEPLOY_STEP="starting"
step() { DEPLOY_STEP="$1"; }
report_deploy_status() {
local code=$?
local level msg
if [ "$code" = 0 ]; then
level=info; msg="deploy OK: ${DEPLOY_REF_SHORT} to Hetzner"
else
level=error; msg="deploy FAILED (exit ${code}) during [${DEPLOY_STEP}]: ${DEPLOY_REF_SHORT} — see /tmp/push-deploy-loki.log"
fi
echo "→ ${msg}"
command -v notify-send >/dev/null 2>&1 && notify-send "Loki deploy" "$msg" >/dev/null 2>&1 || true
# Durable record in the box DB — best-effort, must never change the exit code.
# msg is fixed text + a short SHA (no single-quotes), so it is SQL-safe here.
ssh -o ConnectTimeout=10 "$HOST" "LC_ALL=C bash -s" >/dev/null 2>&1 <<REMOTE || true
DBURL=\$(grep -oP '^DATABASE_URL=\K.*' /opt/loki/app/.env 2>/dev/null | head -1 | tr -d '"')
[ -n "\$DBURL" ] && psql "\$DBURL" -q -c "insert into debug_logs (source, level, message) values ('deploy', '${level}', '${msg}')" 2>/dev/null
REMOTE
}
trap report_deploy_status EXIT
git_head() { git -C "$PROJECT_DIR" rev-parse HEAD 2>/dev/null || echo unknown; }
# Off-main gate — prod may only ever run a commit contained in origin/main.
# Runs FIRST, before the schema step mutates anything: a refused deploy must
# leave the box exactly as it found it. See the script for the two incidents
# that made this an enforced invariant rather than a remembered rule.
step "off-main gate"
bash "$SCRIPT_DIR/ci/check-deploy-ref.sh" "$PROJECT_DIR" "${REF:-HEAD}"
# Schema BEFORE build (same order as scripts/hetzner/deploy.sh): guarded,
# forward-only drizzle migrations from ./drizzle via the shared applier — the
# first run baselines the existing file set against the live loki DB. The
# applier is filename-based, so it's immune to journal/snapshot state.
# drizzle/meta now HAS a current-schema snapshot (0039) with an idx-aligned
# journal, so `npm run db:generate` diffs and emits the next 0040+ migration
# automatically — no more hand-written DDL (that reflex caused the box-DDL
# ownership rollbacks; see scripts/db/apply-box.sh).
step "schema migration"
bash "$SCRIPT_DIR/hetzner/apply-schema.sh" loki "$PROJECT_DIR" loki "." \
|| { echo "✗ schema step failed — deploy aborted (no code shipped)" >&2; exit 1; }
# Ownership self-heal: apply-schema.sh (shared infra) runs DDL as the postgres
# superuser, so a freshly-migrated table would be owned by postgres and thus
# INVISIBLE to the loki app role (privilege-filtered information_schema) —
# the exact class that rolled back deploys. Idempotent reassignment: on a healthy
# box this touches zero tables; when a new migration created a postgres-owned
# object, it hands ownership to the app role before the drift-check runs.
DBURL_OWN=$(ssh "$HOST" "grep -oP '^DATABASE_URL=\K.*' /opt/loki/app/.env 2>/dev/null | head -1 | tr -d '\"'")
if [ -n "$DBURL_OWN" ]; then
APP_ROLE=$(printf '%s' "$DBURL_OWN" | sed -E 's#^[^/]*//([^:]+):.*#\1#')
ssh "$HOST" "sudo -u postgres psql -d loki -v ON_ERROR_STOP=1 -q -c \"DO \\\$\\\$ DECLARE r record; n int := 0; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname='public' AND tableowner <> '${APP_ROLE}' LOOP EXECUTE format('ALTER TABLE public.%I OWNER TO ${APP_ROLE}', r.tablename); n := n + 1; END LOOP; IF n > 0 THEN RAISE NOTICE 'reassigned % table(s) to ${APP_ROLE}', n; END IF; END \\\$\\\$;\"" \
&& echo " ✓ table ownership reconciled to ${APP_ROLE}" \
|| echo " ⚠ ownership reconcile skipped (non-fatal)"
fi
if [ -n "$NO_BUILD" ]; then
: # reuse the existing $STANDALONE
elif [ -n "$REF" ]; then
CURRENT="$(git_head)"
if [ "$CURRENT" != "$REF" ]; then
echo "✗ pinned deploy SKIPPED — working tree is on ${CURRENT:0:12}, not the pushed ref ${REF:0:12}."
echo " A backgrounded push-deploy must not build whatever branch you've since switched to."
echo " Deploy it explicitly: git checkout ${REF:0:12} && bash scripts/deploy-hetzner.sh (or push from main again)"
exit 1
fi
# Pass the pinned ref into the build env so the postbuild (deploy-local.sh)
# gates the LOCAL systemd restart on it too. Without this, a HEAD switch
# mid-build is caught here (box rsync aborts) but the postbuild has already
# restarted the local prod service with the torn build — the box was protected
# but local was not. Now a drifted pinned build restarts nothing, anywhere.
(cd "$PROJECT_DIR" && LOKI_DEPLOY_REF="$REF" pnpm run build)
AFTER="$(git_head)"
if [ "$AFTER" != "$REF" ]; then
echo "✗ pinned deploy ABORTED — HEAD moved to ${AFTER:0:12} during the build; not shipping a torn tree (local restart was skipped too)." >&2
exit 1
fi
else
(cd "$PROJECT_DIR" && pnpm run build)
fi
if [ -z "$NO_BUILD" ]; then
(cd "$PROJECT_DIR" && pnpm -C bridge run build)
fi
if [ ! -d "$STANDALONE/.next/static" ]; then
echo "✗ $STANDALONE missing static assets — run pnpm run build first" >&2
exit 1
fi
# ── Regression guard: never ship a commit that is BEHIND what is already live ──
#
# This script ships whatever the working tree is on, and the box accepts it
# without question — so a deploy run from a stale checkout silently rolls
# production back. It has done so repeatedly (see the comment in
# src/app/api/health/route.ts). Most recently on 2026-08-15: CI shipped and
# verified main at 09:48, and ten minutes later a hand-run deploy replaced it
# with a tree ~25 commits old. The build-ref marker made that *visible* — it is
# how this was found — but visibility after the fact is not prevention.
#
# The box's marker is the SSOT for what is running. If that commit is an
# ancestor of what we are about to ship, this is a fast-forward and safe.
# Anything else moves production backwards, or sideways onto an unrelated
# branch, and is refused. ALLOW_ROLLBACK=1 is the deliberate override for a
# genuine rollback.
# Every command here must be non-fatal under `set -euo pipefail`. Reading the
# marker is a QUESTION, not a step of the deploy: if the box has no .build-ref
# then `cat` exits 1, `pipefail` makes the whole substitution non-zero, and
# `set -e` kills the deploy — with no message at all, because the guard that
# would have explained itself never ran. That is exactly what happened: two
# deploys died silently between "table ownership reconciled" and the snapshot.
# `|| true` on BOTH sides (remote command and local substitution) keeps an
# unanswerable question from becoming a failed deploy; check-not-behind.sh
# already treats an empty marker as "cannot tell — ship anyway".
step "reading the live build marker"
SHIPPING_SHA="$(git -C "$PROJECT_DIR" rev-parse "${REF:-HEAD}" 2>/dev/null || echo "")"
LIVE_REF_NOW="$(ssh "$HOST" "cat '$APP_DIR/.build-ref' 2>/dev/null || true" 2>/dev/null | tr -d '[:space:]' || true)"
bash "$PROJECT_DIR/scripts/ci/check-not-behind.sh" "$LIVE_REF_NOW" "$SHIPPING_SHA" "$PROJECT_DIR" || exit 1
# Snapshot the current box build for one-command rollback (fix: in-place rsync
# left no way back from a broken restart). Excludes backups/ so we don't copy
# the dump store every deploy; .env + launch.sh ARE snapshotted so a rollback
# restores a coherent tree.
echo "→ snapshot current box build → $APP_DIR.prev"
ssh "$HOST" "test -d '$APP_DIR' && rsync -a --delete --exclude backups '$APP_DIR/' '$APP_DIR.prev/'" \
|| echo " (no prior build to snapshot)"
# Restore the previous build if a ship fails its restart/verification, so a
# broken deploy doesn't strand the box. --delete but --exclude backups, so the
# dump store is never touched; .env/launch.sh come from the snapshot.
rollback_box() {
local why="${1:-deploy failed}"
echo "↩ deploy failed after ship — rolling box back to previous build" >&2
if ssh "$HOST" "test -d '$APP_DIR.prev' \
&& rsync -a --delete --exclude backups '$APP_DIR.prev/' '$APP_DIR/' \
&& chown -R ubuntu:ubuntu '$APP_DIR' \
&& systemctl restart loki-app && sleep 3 \
&& systemctl is-active loki-app >/dev/null"; then
echo " ✓ rolled back to previous build" >&2
# Rolled back cleanly: the box serves the last-good build and CI already
# shows the failed ship. Nothing for the owner to do, so nothing on his phone.
echo " (not paged: rolled back cleanly — $why)" >&2
else
echo " ✗ ROLLBACK FAILED — box needs manual attention" >&2
deploy_alert "$why, and the rollback failed too. Loki may be half-installed. Redeploying puts a whole build back."
fi
}
# Keepalive on the rsync transport: without it a dead TCP connection wedges the
# transfer indefinitely (observed a 15-min stall at 0 bytes/s with the box fully
# reachable). ServerAlive drops the channel after ~90s of silence so the deploy
# fails fast and can be rerun, rather than hanging past every timeout below.
RSYNC_SSH="ssh -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=6"
step "rsync to box"
echo "→ rsync standalone → $HOST:$APP_DIR"
rsync -az --delete -e "$RSYNC_SSH" \
--exclude '.env' \
--exclude 'launch.sh' \
--exclude 'backups' \
"$STANDALONE/" "$HOST:$APP_DIR/"
echo "→ restart loki-app on box"
# timeout: this ssh once hung for 47 minutes AFTER the restart completed on
# the box (channel never closed), freezing the deploy before verification and
# the runner sync — the push looked deployed but the runner kept old code.
# Every step below this one is idempotent, so a killed-and-rerun deploy is
# always safe; a silently hung one is not.
if ! timeout 180 ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=6 "$HOST" \
"chown -R ubuntu:ubuntu $APP_DIR \
&& systemctl restart loki-app \
&& sleep 3 \
&& systemctl is-active loki-app >/dev/null"; then
echo "✗ restart failed on box" >&2; rollback_box "loki-app failed to restart"; exit 1
fi
# Post-deploy verification — fails the deploy LOUDLY instead of shipping a
# silently-broken auth/email config, and rolls back. Catches the X-saga
# failure mode: a provider silently un-mounting when its env keys go missing.
#
# The /sign-in check POLLS for readiness (up to ~20s) rather than curling once:
# a slow-to-stop old Next process pushes the new one's first-accept past the
# restart's `sleep 3`, and a single immediate curl then failed the deploy and
# rolled back a build that was actually fine. Poll until the server accepts, and
# only then run the (one-shot) health/provider assertions.
echo "→ post-deploy verification"
# Paused providers (PAUSED_PROVIDERS in src/lib/auth-providers.ts) are
# deliberately unmounted, so they are not expected here. Computing the list
# fails the deploy rather than falling back to a guess.
# Which runtime the box answers sign-in with decides which providers are
# mounted (AUTH_RUNTIME=accountkit unmounts GitHub, Google and X), so read it
# from the box's env. A mode name, not a secret; anything that is not a plain
# word is treated as unset.
BOX_AUTH_RUNTIME=$(ssh "$HOST" "grep -oE '^(export[[:space:]]+)?AUTH_RUNTIME=[a-z]+' $APP_DIR/.env 2>/dev/null | tail -1 | sed 's/.*=//'" || true)
[[ "$BOX_AUTH_RUNTIME" =~ ^[a-z]+$ ]] || BOX_AUTH_RUNTIME=""
echo " box auth runtime: ${BOX_AUTH_RUNTIME:-authjs (unset)}"
# The OIDC clients AccountKit mounts come from the box's env too: the issuer
# and client id are not secrets and are read as they are; a client secret is
# reported only as "set" (its value never leaves the box). /opt/fleet/env
# first, then the app's .env, where a non-empty line wins (launch.sh's order).
BOX_OIDC_ENV=$({ ssh "$HOST" "for f in /opt/fleet/env $APP_DIR/.env; do [ -r \$f ] && cat \$f; done 2>/dev/null" || true; } | awk '
match($0, /^[[:space:]]*(export[[:space:]]+)?(ORANGECAT_OAUTH_ISSUER|ORANGECAT_OAUTH_CLIENT_ID|ORANGECAT_OAUTH_CLIENT_SECRET|SIGNIN_ISSUER|SIGNIN_CLIENT_ID|SIGNIN_CLIENT_SECRET)=/) {
line = substr($0, RSTART, RLENGTH); sub(/^[[:space:]]*(export[[:space:]]+)?/, "", line); name = substr(line, 1, length(line) - 1)
value = substr($0, RSTART + RLENGTH); gsub(/^["\047]|["\047][[:space:]]*$/, "", value)
if (value == "") next
if (name ~ /SECRET$/) value = "set"
seen[name] = value
}
END { for (n in seen) if (seen[n] ~ /^[A-Za-z0-9_.:\/-]+$/) printf "%s=%s\n", n, seen[n] }')
echo " box OIDC clients: $(grep -oE '^(ORANGECAT_OAUTH_CLIENT_ID|SIGNIN_CLIENT_ID)=' <<<"$BOX_OIDC_ENV" | tr -d = | tr '\n' ' ')"
EXPECTED_PROVIDERS=$(cd "$PROJECT_DIR" && env -u ORANGECAT_OAUTH_ISSUER -u ORANGECAT_OAUTH_CLIENT_ID -u ORANGECAT_OAUTH_CLIENT_SECRET -u SIGNIN_ISSUER -u SIGNIN_CLIENT_ID -u SIGNIN_CLIENT_SECRET $BOX_OIDC_ENV AUTH_RUNTIME="$BOX_AUTH_RUNTIME" npx tsx scripts/expected-auth-providers.ts) || {
echo "✗ could not compute expected auth providers" >&2; rollback_box "expected auth providers unknown"; exit 1
}
if ! ssh "$HOST" 'set -e
base=http://127.0.0.1:4002
code=000
for i in $(seq 1 20); do
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "$base/sign-in") || true; code=${code:0:3}
[ "$code" = 200 ] && break
sleep 1
done
echo " /sign-in: $code"; [ "$code" = 200 ] || { echo " ✗ sign-in not 200 after 20s"; exit 1; }
# /api/health returns 503 when env.ts finds a fatal/error config issue
hcode=$(curl -s -o /dev/null -w "%{http_code}" "$base/api/health")
echo " /api/health: $hcode"; [ "$hcode" = 200 ] || { echo " ✗ env health degraded — see debug_logs source=instrumentation/env"; exit 1; }
# Expected auth providers must actually be mounted (not just env-gated in the UI)
prov=$(curl -s "$base/api/auth/providers")
for p in '"$EXPECTED_PROVIDERS"'; do
grep -q "\"$p\"" <<<"$prov" || { echo " ✗ auth provider missing: $p"; exit 1; }
done
echo " ✓ providers mounted: '"$EXPECTED_PROVIDERS"'"'; then
echo "✗ post-deploy verification failed" >&2; rollback_box "post-deploy verification failed (sign-in / health / providers)"; exit 1
fi
# Schema-drift guard against the BOX database. The pre-push check (scripts/
# check-schema-drift.ts) runs against the laptop DB; the box has its own
# Postgres, so a table/column added in code but never pushed there silently
# 500s the first feature that queries it. Print the schema-declared tables and
# columns here, fetch the box's tables/columns over ssh, and diff — fail LOUDLY
# instead of trusting a half-broken deploy.
echo "→ schema-drift check (box DB)"
# LC_ALL=C on EVERY sort and comm below: `comm` requires its inputs sorted in
# the same collation it verifies with, and glibc UTF-8 locales (e.g. de_CH.UTF-8)
# order some `table.column` strings inconsistently — `sort` produces output that
# `comm` then rejects as "not in sorted order", exit 1. Under set -euo pipefail
# that aborted the whole deploy (skipping the bridge sync) even though the box
# schema was fine. Byte-order collation is deterministic and self-consistent.
DECLARED=$(cd "$PROJECT_DIR" && npx tsx scripts/check-schema-drift.ts --print 2>/dev/null | LC_ALL=C sort)
DECLARED_COLUMNS=$(cd "$PROJECT_DIR" && npx tsx scripts/check-schema-drift.ts --print-columns 2>/dev/null | LC_ALL=C sort)
BOX_TABLES=$(ssh "$HOST" 'LC_ALL=C bash -s' <<'REMOTE' | LC_ALL=C sort
DBURL=$(grep -oP '^DATABASE_URL=\K.*' /opt/loki/app/.env 2>/dev/null | head -1 | tr -d '"')
psql "$DBURL" -t -A -c "select table_name from information_schema.tables where table_schema = 'public'" 2>/dev/null
REMOTE
)
BOX_COLUMNS=$(ssh "$HOST" 'LC_ALL=C bash -s' <<'REMOTE' | LC_ALL=C sort
DBURL=$(grep -oP '^DATABASE_URL=\K.*' /opt/loki/app/.env 2>/dev/null | head -1 | tr -d '"')
psql "$DBURL" -t -A -c "select table_name || '.' || column_name from information_schema.columns where table_schema = 'public'" 2>/dev/null
REMOTE
)
MISSING=$(LC_ALL=C comm -23 <(printf '%s\n' "$DECLARED") <(printf '%s\n' "$BOX_TABLES"))
MISSING_COLUMNS=$(LC_ALL=C comm -23 <(printf '%s\n' "$DECLARED_COLUMNS") <(printf '%s\n' "$BOX_COLUMNS"))
if [ -n "$MISSING" ] || [ -n "$MISSING_COLUMNS" ]; then
echo " ✗ box DB is missing declared tables:"
[ -n "$MISSING" ] && printf '%s\n' "$MISSING" | sed 's/^/ - /' || echo " - none"
echo " ✗ box DB is missing declared columns:"
[ -n "$MISSING_COLUMNS" ] && printf '%s\n' "$MISSING_COLUMNS" | sed 's/^/ - /' || echo " - none"
echo " → run 'DATABASE_URL=<box> npx drizzle-kit push' before trusting this deploy"
# The app is already live at this point but is missing tables/columns the new
# code needs — it will 500 on those features. Roll back to the last-good build
# (whose schema matched the box) and alert, rather than serve a half-broken app.
# Schema application stays a deliberate manual step: auto-applying DDL to prod
# (drops included) is not worth the blast radius; the gate + rollback is safe.
rollback_box "box DB is missing declared tables/columns — schema not pushed"
exit 1
fi
echo " ✓ schema: all $(printf '%s\n' "$DECLARED" | grep -c .) declared tables and $(printf '%s\n' "$DECLARED_COLUMNS" | grep -c .) declared columns present on box"
# Does the LIVE box report the commit we just shipped? Everything above proves
# the box is healthy; nothing above proves it is running THIS build. A stale
# rsync, a rotated-back app dir, or a second deploy landing behind this one all
# leave a green verification and the wrong code serving — which is exactly how
# the same build got rolled back three times without anyone noticing. The
# marker comes from scripts/record-build-ref.sh via /api/health.
SHIPPED_SHA="$(git -C "$PROJECT_DIR" rev-parse "${REF:-HEAD}" 2>/dev/null || echo "")"
LIVE_SHA="$(ssh "$HOST" "curl -s --max-time 5 http://127.0.0.1:4002/api/health" 2>/dev/null \
| sed -n 's/.*"commit":"\([0-9a-f]*\)".*/\1/p')"
if [ -z "$LIVE_SHA" ]; then
# Pre-marker builds report no commit. Warn, never block: a deploy that is
# otherwise verified must not fail because the PREVIOUS build lacked a stamp.
echo " ⚠ live build reports no commit — build-ref marker absent (pre-#279 build?)"
elif [ "$LIVE_SHA" != "$SHIPPED_SHA" ]; then
# Loud, but NOT a rollback. The realistic cause is another deploy landing
# behind this one — and reverting to app.prev would then throw away the newer
# build, turning a benign race into the exact incident this check exists to
# catch. The app is up and healthy; what was missing before was ever being
# TOLD that the box is serving something else. Now it says so, and
# /api/health answers it afterwards without an ssh session.
echo " ⚠ live build is ${LIVE_SHA:0:12}, but this deploy shipped ${SHIPPED_SHA:0:12}" >&2
echo " The box is not serving what was just built — another deploy raced this one," >&2
echo " or the rsync did not take. Confirm before trusting prod:" >&2
echo " curl -s https://loki.orangecat.ch/api/health" >&2
echo " git log --oneline -1 ${LIVE_SHA:0:12}" >&2
else
echo " ✓ live build is ${LIVE_SHA:0:12} — the commit this deploy shipped"
fi
echo "✓ deployed $(git -C "$PROJECT_DIR" rev-parse --short "${REF:-HEAD}") to Hetzner — verified"
# Event bridge — separate from the Next app and runner, but part of the same
# control-plane protocol. Sync it here so SSE/rawkey/presence contracts cannot
# drift between deploys.
BRIDGE_DIR="/opt/loki/bridge"
echo "→ sync event bridge → $HOST:$BRIDGE_DIR"
rsync -az --delete --no-perms --omit-dir-times -e "$RSYNC_SSH" \
--exclude '.env' \
--exclude 'node_modules' \
"$PROJECT_DIR/bridge/" "$HOST:$BRIDGE_DIR/"
ssh "$HOST" "chown -R ubuntu:ubuntu $BRIDGE_DIR \
&& systemctl restart loki-bridge \
&& sleep 2 \
&& systemctl is-active loki-bridge >/dev/null"
echo " ✓ loki-bridge active"
# The agents' standing instructions (~/.claude/CLAUDE.md for the runner user)
# come from scripts/hetzner/box-agent-claude.md. They used to be written only by
# install-box-runner.sh, so every later edit to the contract stayed in the repo
# and never reached the agents. Merge-only and idempotent; read at each session
# start, so no runner restart. Never fails the deploy.
LOKI_RUNNER_OWNER="$RUNNER_OWNER" timeout 60 bash "$SCRIPT_DIR/hetzner/apply-box-agent-contract.sh" "$HOST" \
|| echo " ⚠ box agent contract not applied (the deploy continues)"
# Cloud builder (box-runner) — separate systemd unit from loki-app so app
# deploys never kill running agent PTYs. Still sync runner code on every ship
# so poller/pty-runtime fixes reach the always-on executor.
RUNNER_DIR="/opt/loki/runner"
echo "→ sync box-runner code → $HOST:$RUNNER_DIR"
# Track whether runner code actually changed. A systemd restart of the runner
# kills its whole cgroup — including any claude/hermes the runner launched for a
# live dispatch (a review run died this way, and every app-only deploy used to
# restart the runner for nothing). So: only restart when runner code moved, and
# drain in-flight agents first when it did.
#
# --checksum (-c): compare CONTENT, not size+mtime. The deploy runs from a
# fresh checkout, so every file's mtime is the checkout's; with the default
# quick check every file was re-sent and itemized, RUNNER_CHANGED was 1 on
# every deploy, docs-only included, and each restart ended every idle
# session (owner, 2026-10-19: five restarts in an afternoon, sessions gone).
RUNNER_CHANGED=0
sync_runner() {
local out
out=$(rsync -azci --no-perms --omit-dir-times -e "$RSYNC_SSH" "$@" 2>/dev/null) || return 0
grep -qE '^[<>ch]f' <<<"$out" && RUNNER_CHANGED=1
return 0
}
sync_runner "$PROJECT_DIR/src/" "$HOST:$RUNNER_DIR/src/"
sync_runner "$PROJECT_DIR/desktop/src/" "$HOST:$RUNNER_DIR/desktop/src/"
# box-runner reads its version from desktop/package.json — ship it alongside.
sync_runner "$PROJECT_DIR/desktop/package.json" "$HOST:$RUNNER_DIR/desktop/"
sync_runner "$PROJECT_DIR/home/" "$HOST:$RUNNER_DIR/home/"
sync_runner "$PROJECT_DIR/scripts/box-runner.ts" \
"$PROJECT_DIR/scripts/mint-box-runner-token.ts" \
"$PROJECT_DIR/scripts/write-tenant-engines.ts" \
"$PROJECT_DIR/scripts/hetzner/new-tenant.sh" \
"$PROJECT_DIR/scripts/hetzner/reconcile-tenants.sh" \
"$PROJECT_DIR/scripts/hetzner/loki-box-runner@.service" \
"$PROJECT_DIR/scripts/hetzner/box-agent-claude.md" \
"$PROJECT_DIR/scripts/reindex-knowledge.ts" \
"$PROJECT_DIR/scripts/hosted-runner.ts" \
"$PROJECT_DIR/scripts/hermes-dispatch.ts" \
"$PROJECT_DIR/scripts/new-site-dispatch.ts" \
"$HOST:$RUNNER_DIR/scripts/"
# The deferred-restart script must reach the box BEFORE it is invoked below.
sync_runner "$PROJECT_DIR/scripts/hetzner/drain-and-restart-runner.sh" \
"$HOST:$RUNNER_DIR/scripts/"
# The sealed-build image recipe, built on the box by install-sealed-builds.sh.
sync_runner "$PROJECT_DIR/scripts/hetzner/agent-image/" "$HOST:$RUNNER_DIR/scripts/agent-image/"
sync_runner "$PROJECT_DIR/tsconfig.json" "$HOST:$RUNNER_DIR/tsconfig.json"
# Dependencies ship WITH the code that imports them. Until now the runner's
# src/ was re-synced every deploy while its package.json was whatever the
# original provisioning installed — so the moment a file under src/ gained a
# new import, the runner broke at its next run and said nothing. Observed
# 2026-08-24: loki-reindex had been dying nightly at 03:30 on
# `Cannot find module 'bip-kit'`, imported via src/lib/thoughts-content.ts,
# because the box manifest still listed 31 deps and never learned about it.
RUNNER_MANIFEST_CHANGED=0
# Content compare for the same reason as sync_runner. package.json alone: this
# is a pnpm repo and the box installs with npm, so there is no package-lock to
# ship — listing one made rsync exit 23 and blanked this output, which hid
# every real manifest change.
manifest_out=$(rsync -azci --no-perms --omit-dir-times -e "$RSYNC_SSH" \
"$PROJECT_DIR/package.json" \
"$HOST:$RUNNER_DIR/" 2>/dev/null) || manifest_out=""
grep -qE '^[<>ch]f' <<<"$manifest_out" && RUNNER_MANIFEST_CHANGED=1
# package.json carries `"@orangecat/sdk": "file:vendor/…tgz"`, so the tarball is
# part of the manifest: bump its version without shipping the file and the
# install fails on the box for a path that exists only here.
vendor_out=$(rsync -azci --no-perms --omit-dir-times -e "$RSYNC_SSH" \
"$PROJECT_DIR/vendor/" "$HOST:$RUNNER_DIR/vendor/" 2>/dev/null) || vendor_out=""
grep -qE '^[<>ch]f' <<<"$vendor_out" && RUNNER_MANIFEST_CHANGED=1
ssh "$HOST" "chown -R $RUNNER_OWNER:$RUNNER_OWNER $RUNNER_DIR/src $RUNNER_DIR/desktop $RUNNER_DIR/home $RUNNER_DIR/scripts $RUNNER_DIR/tsconfig.json"
if [ "$RUNNER_MANIFEST_CHANGED" = "1" ]; then
echo "→ runner manifest changed — installing dependencies"
# `npm install`, deliberately NOT `npm ci`: ci deletes node_modules wholesale,
# and for the window that takes, node_modules/.bin/tsx does not exist — which
# is the runner's own ExecStart. Incremental install keeps the always-on
# executor runnable throughout.
#
# And NOT --omit=dev: tsx is a devDependency here, so pruning dev deps would
# delete the very binary that starts the runner and the reindex timer.
step "runner dependencies"
# Fail the deploy rather than ship a runner whose imports it may not have.
# The alternative — warn and continue — is how this bug stayed invisible for
# weeks in the first place: the runner was broken and the deploy said green.
# HUSKY=0 is required, not cosmetic: package.json's `prepare` script runs
# husky, the runner dir is not a git repo, and without the opt-out the
# install exits 127 — which (correctly) would fail every deploy from here on.
ssh "$HOST" "cd $RUNNER_DIR && HUSKY=0 npm install --no-audit --no-fund --silent" \
|| { echo " ✗ runner dependency install FAILED — refusing to report a green deploy over a runner missing its imports" >&2; exit 1; }
ssh "$HOST" "chown -R $RUNNER_OWNER:$RUNNER_OWNER $RUNNER_DIR/node_modules $RUNNER_DIR/package.json $RUNNER_DIR/package-lock.json" || true
echo " ✓ runner dependencies installed"
RUNNER_CHANGED=1 # new deps only take effect in a fresh process
else
echo " ✓ runner manifest unchanged — dependency install skipped"
fi
# The runner restart waits for in-flight agents — but it waits ON THE BOX, in a
# detached transient unit, not here.
#
# This loop used to run inside the deploy: 480 of the ship step's 570 seconds
# were spent watching one agent that never finished, after which it restarted
# anyway. The web app had been live and verified for eight minutes by then. Two
# separate systems with opposite needs were sharing one job's wall-clock: the
# app wants to be live now, the runner wants to not kill anyone's work.
#
# Decoupled, both get what they want. The deploy ends when the app is verified;
# the box waits as long as it needs (up to 6h, and never kills a working agent) and restarts when the
# runner is genuinely idle. While the runner's heartbeat version is behind
# this deploy, the app hands it no work-starting commands
# (src/lib/runner-update-hold.ts), so that idle moment comes even with
# autopilot on. `systemd-run` detaches it into its own cgroup, so it
# survives this ssh closing and cannot be killed by the restart it performs.
# What the always-on builder is doing BEFORE this deploy touches it — in the
# CI log, where a person without an ssh session can read it. On 2026-10-11 the
# deploy scheduled a drain-then-restart and the runner was offline the next
# morning; the only record was the box journal. Warn-only: a dead runner is a
# fact to print, not a reason to fail a verified app deploy.
step "box-runner state"
ssh "$HOST" "
printf ' box-runner: %s (restart unit: %s)\n' \
\"\$(systemctl is-active loki-box-runner 2>/dev/null)\" \
\"\$(systemctl is-active loki-runner-restart.service 2>/dev/null || true)\"
journalctl -u loki-box-runner -n 6 --no-pager -o cat 2>/dev/null | sed 's/^/ │ /'
journalctl -t loki-drain -n 3 --no-pager -o cat 2>/dev/null | sed 's/^/ │ drain: /'
" 2>/dev/null || echo " ⚠ could not read box-runner state"
step "scheduling runner restart"
if [ "$RUNNER_CHANGED" = 1 ]; then
echo "→ runner code changed — scheduling a drain-then-restart on the box"
# Newest intent wins: a previous deploy's pending restart is superseded by
# this one, which is already syncing newer code. One drain per unit: the
# owner's legacy unit and every private builder's instance, each in its
# own transient unit so one tenant's long task never holds another's
# restart (docs/architecture/private-builders.md).
ssh "$HOST" "
units=\"loki-box-runner \$(systemctl list-units 'loki-box-runner@*' --no-legend --plain 2>/dev/null | awk '{print \$1}' | sed 's/\.service\$//')\"
for u in \$units; do
r=\"loki-runner-restart-\${u//@/-}\"
systemctl stop \"\$r.service\" 2>/dev/null || true
systemctl reset-failed \"\$r.service\" 2>/dev/null || true
systemd-run --unit=\"\$r\" --collect --quiet \
--description=\"Loki: restart \$u once its agents drain\" \
/bin/bash $RUNNER_DIR/scripts/drain-and-restart-runner.sh \"\$u\"
done
" && echo " ✓ restart scheduled for each runner unit — runs when it goes idle (journal: -t loki-drain)" \
|| echo " ⚠ could not schedule the runner restart — runner keeps old code until the next deploy" >&2
else
echo " ✓ runner code unchanged — restart skipped (in-flight agents undisturbed)"
fi
# ── Box state the code depends on, kept in step with the code ────────────────
# Both of these used to be a command someone had to remember to run on the box
# after a merge. Neither happened on its own, so a feature could be live and
# verified while the thing it needs did not exist: the 19:00 evening proposal
# had no timer, and the fix check had no browser to take its picture with.
# Each is idempotent and warn-only — the app above is already live and
# verified, and nothing here may turn that into a failed deploy.
# 1. Scheduled jobs: SCHED in install-hetzner-crons.sh is the SSOT; a job added
# there gets its timer from the deploy of the merge that adds it.
step "cron timers"
if timeout 120 bash "$PROJECT_DIR/scripts/install-hetzner-crons.sh" >/dev/null 2>&1; then
echo " ✓ cron timers match scripts/install-hetzner-crons.sh"
else
echo " ⚠ could not refresh the cron timers — run scripts/install-hetzner-crons.sh by hand" >&2
fi
# 1b. Private builders: the unit template and the root timer that reconciles
# users.private_builder into tenant units (new-tenant.sh). The template is
# refreshed here so a change to it reaches every tenant's next restart.
step "private builders"
if timeout 60 ssh "$HOST" "install -m 0644 $RUNNER_DIR/scripts/loki-box-runner@.service /etc/systemd/system/loki-box-runner@.service && systemctl daemon-reload" >/dev/null 2>&1 \
&& timeout 120 bash "$PROJECT_DIR/scripts/hetzner/install-tenant-reconcile.sh" "$HOST" >/dev/null 2>&1; then
echo " ✓ tenant unit template and loki-tenants.timer in place"
else
echo " ⚠ could not install the tenant template or timer — run scripts/hetzner/install-tenant-reconcile.sh by hand" >&2
fi
# Sealed builds: podman, runsc and the agent image, as readings. Switching a
# tenant to them is the operator's one file (new-tenant.sh, step 8), never
# this step's. The first run builds the image, which takes a few minutes.
if sealed_out=$(timeout 900 bash "$PROJECT_DIR/scripts/hetzner/install-sealed-builds.sh" "$HOST" 2>&1); then
printf '%s\n' "$sealed_out" | sed 's/^/ /'
else
echo " ⚠ sealed-build readings unavailable this deploy" >&2
printf '%s\n' "$sealed_out" | tail -5 | sed 's/^/ /' >&2
fi
# 2. A browser for the app user. The fix check (src/lib/feedback/page-picture.ts)
# and a preview's before-and-after tour take phone-sized pictures of live
# pages. Playwright looks for ITS OWN Chromium revision in the app user's
# cache, so the install must be run by the Playwright the app ships — the
# one in the standalone's node_modules — never by the runner's: the runner
# is installed by npm from package.json's ranges while the app is built from
# pnpm's lockfile, and the two resolved different Playwright versions, so
# the revision installed here was never the one the app asked for, and
# /api/health said nothing (2026-10-17: every picture "no-browser"). The
# health line's `pictures` field now says whether it worked; the output of
# a failed install is kept in the deploy log.
step "browser for pictures"
APP_USER="${LOKI_APP_USER:-ubuntu}"
PW_CLI="$APP_DIR/node_modules/playwright/cli.js"
if ! ssh "$HOST" "test -f $PW_CLI"; then
echo " ⚠ the app ships no Playwright ($PW_CLI missing) — pictures are off until it does" >&2
elif pw_out=$(timeout 300 ssh "$HOST" "sudo -u $APP_USER -H bash -c 'cd $APP_DIR && /usr/bin/node $PW_CLI install chromium'" 2>&1); then
echo " ✓ Chromium present for $APP_USER at the app's own Playwright revision"
else
echo " ⚠ could not install Chromium for $APP_USER — /api/health will say pictures.ok=false" >&2
printf '%s\n' "$pw_out" | tail -15 | sed 's/^/ /' >&2
fi