#!/usr/bin/env bash # Thin v1 production cutover for equipo (spec section 8): a drained move to # the thin instance and runner, on a fresh database, with a verified export # of the old one kept, and a complete rollback. # # scripts/cutover-thin.sh # print the plan only (default) # scripts/cutover-thin.sh --execute # a person runs it, step by step # scripts/cutover-thin.sh rollback [--execute] # restore the recorded prior state # # is a `make release` version staging passed on exactly these # bytes (`make staged-check`). Agents must not run --execute: it changes # production. Each step asks first and stops on the first failure. The run # is resumable: steps done are recorded in $BACKUPS/cutover.state and skipped. # # Cutover: # 1 preflight staged-check, artifacts, CARLOS sign-in, runner unit, roots # not shared with the staging runner; records the prior # configuration (served version, EQUIPO_ALWAYS_ON and # EQUIPO_DATABASE, runner service.env and unit, instance id) # 2 drain stop the old runner # 3 export carlos db pull, integrity-checked, counted, hashed, read-only # 4 config EQUIPO_DATABASE=equipo-v1.db (fresh; equipo.db untouched), # EQUIPO_ALWAYS_ON removed # 5 deploy the staged instance, --swap hold, until /api/version reports it # 6 identity read the new instance id from the new database through the # platform replica; it must exist and differ from the old one. # Nothing on the runner has changed yet, so a failure here # still rolls back cleanly. # 7 runner install the staged runner, tool proxy, gitleaks (the # preview scanner) and page renderer beside the old one, new service.env # (tool proxy path, new instance id) and unit # (RestartPreventExitStatus=3), old state moved aside # 8 enrol the runner enrols with the new instance, the owner approves # 9 verify runner active, version, replica reads the new tables # # Rollback restores the recorded prior configuration exactly: stops the # runner, moves the new state aside under a timestamped name, restores the # old state, service.env and unit, restores EQUIPO_ALWAYS_ON and # EQUIPO_DATABASE, promotes the previously served version, starts the runner. set -euo pipefail APP=equipo ACCOUNT=oficina CONSOLE=https://console.carloku.com HOST=equipo.bds.oncarlos.com # ORIGIN is the platform route, where the served version is read. PUBLIC_ORIGIN # is the address people use (EQUIPO_ORIGIN); the cutover moves both the # instance and the runner to it. ORIGIN=https://$HOST PUBLIC_ORIGIN=${EQUIPO_PUBLIC_ORIGIN:-https://equipo.oficina.works} NEW_DB=equipo-v1.db UNIT=equipo-runner.service RUNNER_ROOT=$HOME/.local/share/equipo-runner STAGING_ROOT=$HOME/.local/share/equipo-runner-staging BACKUPS=$HOME/.local/share/equipo-cutover STATE=$BACKUPS/cutover.state SNAP=$BACKUPS/prior REPO=$(cd "$(dirname "$0")/.." && pwd) carlos_app=(--app "$APP" --account "$ACCOUNT" --console "$CONSOLE") mode=cutover version=${1:-} [[ $version == rollback ]] && mode=rollback execute=0 [[ ${2:-} == --execute ]] && execute=1 if [[ $mode == cutover && ! $version =~ ^[0-9a-f]{7,12}$ ]]; then sed -n '2,41p' "$0" exit 2 fi die() { echo "refused: $*" >&2; exit 1; } step() { printf '\n== %s\n' "$1" if ((execute)) && [[ ${CUTOVER_YES:-} != 1 ]]; then read -r -p "Run this step? Type yes: " answer [[ $answer == yes ]] || { echo "stopped before: $1"; exit 1; } fi } run() { printf ' $ %s\n' "$*" if ((execute)); then "$@"; fi } # Recorded facts and finished steps, one KEY=value per line. get() { [[ -f $STATE ]] && sed -n "s/^$1=//p" "$STATE" | tail -1 || true; } put() { ((execute)) || return 0 printf '%s=%s\n' "$1" "$2" >>"$STATE" || die "could not record $1=$2 in $STATE" } done_step() { [[ $(get "done_$1") == 1 ]]; } finish() { put "done_$1" 1; } # env_value reads one key from a `carlos env list` listing on stdin. env_value() { awk -v k="$1" '$1 == k { print $2; found = 1 } END { if (!found) print "-unset-" }'; } # The runner scans every preview with the gitleaks beside its own # executable, held to the hash linked into the runner; without it every # preview fails (preview_scanner). $1 is a runner release directory: its # gitleaks runs, and its sha256 is the one linked into its equipo-runner. scanner_linked() { local sum [[ -f $1/gitleaks && ! -L $1/gitleaks && -x $1/gitleaks ]] || return 1 sum=$(sha256sum "$1/gitleaks" | cut -d ' ' -f 1) || return 1 grep -qaF "$sum" "$1/equipo-runner" } scanner() { echo " $1/gitleaks: executable, and its sha256 is linked into $1/equipo-runner" if ((execute)) && ! scanner_linked "$1"; then die "$1/gitleaks is missing, cannot run, or is not the scanner equipo-runner was built with" fi } # The runner renders pages with the renderer tree beside its own # executable, held to the pin linked into the runner (the sha256 of the # tree's MANIFEST). $1 is a runner release directory: the MANIFEST of its # renderer.tar.gz has the sha256 linked into its equipo-runner. renderer_linked() { local sum [[ -f $1/renderer.tar.gz && ! -L $1/renderer.tar.gz ]] || return 1 sum=$(tar -xzOf "$1/renderer.tar.gz" MANIFEST | sha256sum | cut -d ' ' -f 1) || return 1 grep -qaF "$sum" "$1/equipo-runner" } renderer() { echo " $1/renderer.tar.gz: its MANIFEST's sha256 is linked into $1/equipo-runner" if ((execute)) && ! renderer_linked "$1"; then die "$1/renderer.tar.gz is missing, or is not the renderer equipo-runner was built with" fi } overlaps() { case "$1/" in "$2"/*) return 0 ;; esac; case "$2/" in "$1"/*) return 0 ;; esac; return 1; } if [[ $mode == rollback ]]; then [[ -f $STATE ]] || die "no cutover was recorded ($STATE)" [[ $(get rolled_back) != 1 ]] || die "already rolled back" # On CARLOS the activator passes the app an absolute --db, so EQUIPO_DATABASE # chose no fresh file: a deploy that began may have migrated the old # database in place. It may have begun when the record says it started or # finished, or when a record from before deploy_started existed passed # step 4 without saying. if [[ $(get deploy_started) == 1 ]] || done_step deploy || { done_step config && [[ -z $(get deploy_started) ]]; }; then die "a deploy of $(get version) may have begun, and it migrates the production database in place (EQUIPO_DATABASE is ignored on CARLOS); $(get prev_version) cannot read it. Finish on the kept database: scripts/cutover-finish-thin.sh" fi stamp=$(get stamp) [[ -n $stamp && -f $SNAP/service.env && -f $SNAP/equipo-runner.service ]] || die "the prior configuration was not recorded" step "rollback 1 stop the runner" run systemctl --user stop "$UNIT" step "rollback 2 runner state, service.env and unit" if [[ -e $RUNNER_ROOT/state.pre-thin-$stamp ]]; then if [[ -e $RUNNER_ROOT/state ]]; then run mv "$RUNNER_ROOT/state" "$RUNNER_ROOT/state.thin-rolled-back-$(date -u +%Y%m%dT%H%M%SZ)" fi run mv "$RUNNER_ROOT/state.pre-thin-$stamp" "$RUNNER_ROOT/state" fi run cp -p "$SNAP/service.env" "$RUNNER_ROOT/service.env" run cp -p "$SNAP/equipo-runner.service" "$RUNNER_ROOT/equipo-runner.service" run systemctl --user daemon-reload step "rollback 3 instance configuration and the previous release" prev_db=$(get prev_database) prev_always=$(get prev_always_on) if [[ $prev_db == -unset- ]]; then run carlos env unset "${carlos_app[@]}" EQUIPO_DATABASE; else run carlos env set "${carlos_app[@]}" --no-prompt "EQUIPO_DATABASE=$prev_db"; fi if [[ $prev_always != -unset- ]]; then run carlos env set "${carlos_app[@]}" --no-prompt "EQUIPO_ALWAYS_ON=$prev_always"; fi prev_origin=$(get prev_origin) if [[ -n $prev_origin ]]; then run carlos env set "${carlos_app[@]}" --no-prompt "EQUIPO_ORIGIN=$prev_origin"; fi run carlos promote "${carlos_app[@]}" "$(get prev_version)" edge run bash -c "for i in \$(seq 60); do [ \"\$(curl -fsS $ORIGIN/api/version)\" = $(get prev_version) ] && exit 0; sleep 2; done; exit 1" step "rollback 4 start the previous runner" run systemctl --user start "$UNIT" put rolled_back 1 ((execute)) || echo $'\nPlan only. A person runs it with --execute.' exit 0 fi instance=$REPO/releases/equipo-linux-arm64-$version runner_release=$REPO/releases/equipo-runner-linux-amd64-$version if [[ -f $STATE ]]; then [[ $(get version) == "$version" ]] || die "a cutover to $(get version) is recorded; roll it back first" [[ $(get rolled_back) != 1 ]] || die "this cutover was rolled back; move $STATE aside to start again" if done_step verify; then die "the cutover to $version is complete"; fi fi step "1 preflight" run make -C "$REPO" staged-check RELEASE_VERSION="$version" run test -f "$instance" run test -x "$runner_release/equipo-runner" run test -x "$runner_release/equipo-tool-proxy" scanner "$runner_release" renderer "$runner_release" run test -f "$RUNNER_ROOT/equipo-runner.service" run test -f "$RUNNER_ROOT/service.env" run carlos apps list --account "$ACCOUNT" --console "$CONSOLE" if ((execute)) && ! done_step preflight; then if ls -d "$RUNNER_ROOT"/state.pre-thin-* >/dev/null 2>&1; then die "an unrecorded earlier attempt left state.pre-thin-*" fi [[ -d $RUNNER_ROOT/state ]] || die "no runner state to keep" if [[ -f $STAGING_ROOT/service.env ]]; then for key in EQUIPO_RUNNER_STATE_DIR EQUIPO_WORKSPACE_ROOT EQUIPO_SCRATCH_ROOT; do mine=$(sed -n "s/^$key=\"\{0,1\}\([^\"]*\)\"\{0,1\}$/\1/p" "$RUNNER_ROOT/service.env") theirs=$(sed -n "s/^$key=\"\{0,1\}\([^\"]*\)\"\{0,1\}$/\1/p" "$STAGING_ROOT/service.env") if [[ -n $mine && -n $theirs ]] && overlaps "$mine" "$theirs"; then die "$key is shared with the staging runner" fi done fi # Read every fact rollback needs before changing anything; a read that # fails or looks wrong stops the cutover here, with nothing changed. prev_version=$(curl -fsS "$ORIGIN/api/version") || die "could not read the served version" [[ $prev_version =~ ^[A-Za-z0-9._-]{1,64}$ ]] || die "unexpected served version" listing=$(carlos env list "${carlos_app[@]}") || die "could not read the instance configuration" grep -q '^KEY' <<<"$listing" || die "unexpected configuration listing" prev_always_on=$(env_value EQUIPO_ALWAYS_ON <<<"$listing") prev_database=$(env_value EQUIPO_DATABASE <<<"$listing") prev_origin=$(env_value EQUIPO_ORIGIN <<<"$listing") [[ $prev_origin =~ ^https://[a-z0-9.-]+$ ]] || die "unexpected EQUIPO_ORIGIN" [[ $PUBLIC_ORIGIN =~ ^https://[a-z0-9.-]+$ ]] || die "unexpected public origin" curl -fsS -o /dev/null "$PUBLIC_ORIGIN/api/version" || die "$PUBLIC_ORIGIN does not serve this app yet: attach the domain first" for value in "$prev_always_on" "$prev_database"; do [[ $value =~ ^[A-Za-z0-9._-]{1,128}$ ]] || die "unexpected configuration value" done old_instance_id=$(sed -n 's/^EQUIPO_INSTANCE_ID="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' "$RUNNER_ROOT/service.env") [[ $old_instance_id =~ ^[A-Z0-9]{26}$ ]] || die "the runner config has no instance id" install -d -m 0700 "$BACKUPS" "$SNAP" stamp=$(date -u +%Y%m%dT%H%M%SZ) cp -p "$RUNNER_ROOT/service.env" "$SNAP/service.env" cp -p "$RUNNER_ROOT/equipo-runner.service" "$SNAP/equipo-runner.service" put version "$version" put stamp "$stamp" put prev_version "$prev_version" put prev_always_on "$prev_always_on" put prev_database "$prev_database" put prev_origin "$prev_origin" put old_instance_id "$old_instance_id" finish preflight fi stamp=$(get stamp) stamp=${stamp:-PLAN} step "2 drain: stop the old runner (it finishes or releases in-flight work on SIGTERM)" run systemctl --user stop "$UNIT" step "3 export and verify the current database" if ! done_step export; then backup=$BACKUPS/equipo-$stamp.db run carlos db pull "${carlos_app[@]}" --out "$backup" run python3 -c "import sqlite3,sys; c=sqlite3.connect('file:$backup?mode=ro', uri=True); r=c.execute('pragma integrity_check').fetchone()[0]; print('integrity', r); [print(t, c.execute('select count(*) from '+t).fetchone()[0]) for t in ('members','tasks','conversation_messages','runners')]; sys.exit(r!='ok')" run sha256sum "$backup" run chmod 0400 "$backup" finish export fi step "4 configuration: fresh database file, no always-on" if ! done_step config; then run carlos env set "${carlos_app[@]}" --no-prompt "EQUIPO_DATABASE=$NEW_DB" "EQUIPO_ORIGIN=$PUBLIC_ORIGIN" [[ $(get prev_always_on) == -unset- ]] || run carlos env unset "${carlos_app[@]}" EQUIPO_ALWAYS_ON put deploy_started 0 finish config fi step "5 deploy the staged instance with --swap hold" if ! done_step deploy; then # Recorded before CARLOS is asked: from here rollback refuses the old version. put deploy_started 1 run carlos deploy "${carlos_app[@]}" --channel edge --target linux-arm64 --swap hold --version "$version" --timeout 5m --no-prompt "$instance" run bash -c "for i in \$(seq 60); do [ \"\$(curl -fsS $ORIGIN/api/version)\" = $version ] && exit 0; sleep 2; done; exit 1" finish deploy fi step "6 identity: the new instance id, from the new database" printf ' $ carlos db query %s --sql "select id from teams"\n' "${carlos_app[*]}" if ((execute)) && ! done_step identity; then new_id= for _ in $(seq "${CUTOVER_ID_TRIES:-30}"); do new_id=$(carlos db query "${carlos_app[@]}" --sql "select id from teams" 2>/dev/null | sed -n 2p || true) [[ $new_id =~ ^[A-Z0-9]{26}$ && $new_id != "$(get old_instance_id)" ]] && break new_id= sleep "${CUTOVER_ID_WAIT:-5}" done [[ -n $new_id ]] || die "the replica shows no new instance id; roll back (scripts/cutover-thin.sh rollback --execute)" put new_instance_id "$new_id" finish identity fi new_id=$(get new_instance_id) step "7 install the staged runner beside the old one" if ! done_step runner; then run install -d -m 0700 "$RUNNER_ROOT/releases/$version" run install -m 0700 "$runner_release/equipo-runner" "$runner_release/equipo-tool-proxy" "$runner_release/gitleaks" "$RUNNER_ROOT/releases/$version/" # The page renderer beside it, unpacked by the staged runner itself and # held to the pin linked into it; verify-installed then renders a page. run "$RUNNER_ROOT/releases/$version/equipo-runner" install-renderer "$runner_release/renderer.tar.gz" run sed -i -e "s|^EQUIPO_TOOL_PROXY_PATH=.*|EQUIPO_TOOL_PROXY_PATH=\"$RUNNER_ROOT/releases/$version/equipo-tool-proxy\"|" -e "s|^EQUIPO_INSTANCE_ID=.*|EQUIPO_INSTANCE_ID=\"${new_id:-NEW_INSTANCE_ID}\"|" -e "s|^EQUIPO_ORIGIN=.*|EQUIPO_ORIGIN=\"$PUBLIC_ORIGIN\"|" "$RUNNER_ROOT/service.env" run sed -i -e "s|^ExecStart=.*|ExecStart=$RUNNER_ROOT/releases/$version/equipo-runner run|" -e '/^RestartPreventExitStatus=/d' -e '/^RestartSec=/a RestartPreventExitStatus=3' "$RUNNER_ROOT/equipo-runner.service" if ((execute)); then [[ -e $RUNNER_ROOT/state.pre-thin-$stamp ]] && die "state.pre-thin-$stamp already exists" fi # The old credential belongs to the old database; keep the old state for rollback. run mv "$RUNNER_ROOT/state" "$RUNNER_ROOT/state.pre-thin-$stamp" run install -d -m 0700 "$RUNNER_ROOT/state" run systemctl --user daemon-reload finish runner fi step "8 enrol the runner with the new instance: open the printed link as the owner and enter the code" if ! done_step enrol; then # Before anything of the new runner starts, it holds every program in # its new configuration (bubblewrap, claude, codex and its code mode # host, the staged tool proxy) and the gitleaks and renderer beside it # to the digests of its release, and renders a fixture page. run bash -c "set -a; . '$RUNNER_ROOT/service.env'; set +a; '$RUNNER_ROOT/releases/$version/equipo-runner' verify-installed" run bash -c "set -a; . '$RUNNER_ROOT/service.env'; set +a; '$RUNNER_ROOT/releases/$version/equipo-runner' enrol" run systemctl --user start "$UNIT" finish enrol fi step "9 verify" run curl -fsS "$ORIGIN/api/version" run systemctl --user is-active "$UNIT" run carlos db query "${carlos_app[@]}" --sql "select count(*) from chat_turns" finish verify echo " Then, as the owner: sign in at $PUBLIC_ORIGIN/conversation, check the offline line" echo " is gone, say hello and see the reply stream. Sign native devices in again." echo " To undo: scripts/cutover-thin.sh rollback --execute" ((execute)) || echo $'\nPlan only. A person runs it with --execute.'