#!/usr/bin/env bash # Thin v1 production upgrade for equipo: from the staged version production # serves to the next staged version, on the same database, runners first # (the staging release order, scripts/staging-thin.py release). # # scripts/upgrade-thin.sh # print the plan only (default) # scripts/upgrade-thin.sh --execute # run it, step by step # scripts/upgrade-thin.sh rollback [--execute] # restore the recorded prior state # # is a `make release` version staging passed on exactly these # bytes (`make staged-check`), read from $EQUIPO_RELEASE_REPO/releases # (default: this checkout). It changes production. An agent may run # --execute when the version's staging run is green with no waiver # (Paul, 2026-11-20); a waived version needs Paul's approval of the waiver, # then an agent runs it too (Paul, 2026-11-22). Each step asks first and stops on the first failure. The run # is resumable: steps done are recorded in $BACKUPS/upgrade.state and # skipped. When the next upgrade starts, a finished or rolled-back one's # state is kept as upgrade--.state. # # Upgrade: # 1 preflight staged-check, artifacts, CARLOS sign-in; the cutover (or the # last upgrade) finished and production serves its version, # which descends from; the runner unit and roots are # production's, not staging's; the replica reads clean (PRAGMA # integrity_check) and nothing is in flight; records the prior # state (served version, runner service.env and unit) # 2 backup carlos db pull, integrity-checked, counted, hashed, read-only. # The upgrade changes no configuration: the same database. # 3 runner the staged runner, tool proxy, gitleaks (the preview # scanner) and page renderer (install-renderer) beside the # current one, checked by verify-installed, which renders a # fixture page; service.env and unit written from the # preflight's record (scripts/runner-config.py); nothing in # flight on a reading just before the restart (a short window, # not a drain: Equipo has no maintenance mode); the restart # keeps the runner's state and enrolment # 4 instance the staged instance with --swap hold, until /api/version # reports it. Its migrations run when it starts. # 5 verify the version; in this boot and unit invocation, the staged # runner's process welcomed by the instance and not dropped # since, on two readings # # Rollback restores the previous runner (service.env and unit) and promotes # the previously served version. It does not roll back the database: once # step 4 has started, the new version's migrations may have run, and the # backup from step 2 is the only copy from before them. set -euo pipefail APP=equipo ACCOUNT=oficina CONSOLE=https://console.carloku.com HOST=equipo.bds.oncarlos.com ORIGIN=https://$HOST PUBLIC_ORIGIN=${EQUIPO_PUBLIC_ORIGIN:-https://equipo.oficina.works} 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 CUTOVER_STATE=$BACKUPS/cutover.state STATE=$BACKUPS/upgrade.state REPO=$(cd "$(dirname "$0")/.." && pwd) RELEASE_REPO=${EQUIPO_RELEASE_REPO:-$REPO} RELEASES=$RELEASE_REPO/releases PROC=${UPGRADE_PROC:-/proc} carlos_app=(--app "$APP" --account "$ACCOUNT" --console "$CONSOLE") # Open tasks holding the work of an Engineering step that ran out of time # (done, step_timeout; protocol 32): a release before it takes that work # for finished, so a rollback refuses while any is open. UNFINISHED="SELECT count(DISTINCT k.id) FROM chat_tasks k JOIN chat_steps s ON s.task_id=k.id WHERE s.specialist='engineering' AND s.state='done' AND s.reason='step_timeout' AND k.stage NOT IN ('done','cancelled')" UNFINISHED_REFUSAL="open tasks hold unfinished work a release before protocol 32 takes for finished: finish or cancel them, or set UPGRADE_ALLOW_UNFINISHED=1 to roll back anyway" IN_FLIGHT="SELECT (SELECT count(*) FROM chat_steps WHERE state IN ('queued','running'))||'/'||(SELECT count(*) FROM chat_steps WHERE specialist='merge' AND state IN ('queued','running'))||'/'||(SELECT count(*) FROM chat_turns WHERE dispatched=1 AND state NOT IN ('replied','failed','cancelled'))" mode=upgrade version=${1:-} [[ $version == rollback ]] && mode=rollback execute=0 [[ ${2:-} == --execute ]] && execute=1 if [[ $mode == upgrade && ! $version =~ ^[0-9a-f]{7,12}$ ]]; then sed -n '2,44p' "$0" exit 2 fi die() { echo "refused: $*" >&2; exit 1; } # A refusal read from the records stops --execute; the plan notes it and goes on. refuse() { if ((execute)); then die "$*"; fi echo " ! would refuse: $*" } step() { printf '\n== %s\n' "$1" if ((execute)) && [[ ${UPGRADE_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_in() { [[ -f $1 ]] && sed -n "s/^$2=//p" "$1" | tail -1 || true; } get() { get_in "$STATE" "$1"; } put() { ((execute)) || return 0 printf '%s=%s\n' "$1" "$2" >>"$STATE" || die "could not record $1=$2 in $STATE" } # A finished or rolled-back upgrade's record is history: its steps are not this run's. history=0 done_step() { ((!history)) && [[ $(get "done_$1") == 1 ]]; } finish() { put "done_$1" 1; } file_value() { sed -n "s/^$1=\"\{0,1\}\([^\"]*\)\"\{0,1\}$/\1/p" "$2"; } overlaps() { case "$1/" in "$2"/*) return 0 ;; esac; case "$2/" in "$1"/*) return 0 ;; esac; return 1; } wait_serving() { run bash -c "for i in \$(seq 60); do [ \"\$(curl -fsS $ORIGIN/api/version)\" = $1 ] && exit 0; sleep 2; done; exit 1"; } # Steps queued or running, merges among them, and dispatched turns not yet # ended: a runner restart fails a running step or turn, and a merge needs # the runner it started with. One reading of the replica: a short window, # not a drain. idle() { local out out=$(carlos db query "${carlos_app[@]}" --sql "$IN_FLIGHT" | tail -1) || die "could not read the work in flight. $REPLICA" [[ $out =~ ^[0-9]+/[0-9]+/[0-9]+$ ]] || die "could not read the work in flight. $REPLICA" [[ $out == 0/0/0 ]] || die "in flight (steps/merges/turns): $out; run again when nothing runs" } # No open task holds unfinished work (UNFINISHED), on one reading of the # replica, unless the operator said to go on. unfinished_none() { local n [[ ${UPGRADE_ALLOW_UNFINISHED:-} == 1 ]] && return 0 n=$(carlos db query "${carlos_app[@]}" --sql "$UNFINISHED" | tail -1) || die "could not read the open tasks. $REPLICA" [[ $n =~ ^[0-9]+$ ]] || die "could not read the open tasks. $REPLICA" echo " open tasks with unfinished work: $n" [[ $n == 0 ]] } # 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 } # The unit's main process runs the binary with sha256 $1. runs() { local pid pid=$(systemctl --user show -p MainPID --value "$UNIT") [[ $pid =~ ^[1-9][0-9]*$ && $(sha256sum "$PROC/$pid/exe" 2>/dev/null | cut -d ' ' -f 1) == "$1" ]] } # Connected now: in this boot and the unit's current invocation, the # process running the binary with sha256 $1 logged the instance's welcome, # and no stream drop after it, on two readings in a row of the same # invocation and process. $2 names that binary. connected() { local seen= inv pid last for _ in $(seq "${UPGRADE_TRIES:-30}"); do inv=$(systemctl --user show -p InvocationID --value "$UNIT") pid=$(systemctl --user show -p MainPID --value "$UNIT") last= if [[ $inv =~ ^[0-9a-f]{32}$ && $pid =~ ^[1-9][0-9]*$ ]]; then [[ $(sha256sum "$PROC/$pid/exe" | cut -d ' ' -f 1) == "$1" ]] || die "the running runner is not $2" last=$(journalctl --user -b _SYSTEMD_INVOCATION_ID="$inv" _PID="$pid" -o cat --no-pager | grep -E 'msg=welcome|msg="runner stream' | tail -1 || true) fi if [[ $last == *msg=welcome* ]]; then [[ $seen == "$inv $pid" ]] && return 0 seen="$inv $pid" else seen= fi sleep "${UPGRADE_WAIT:-5}" done return 1 } # The in-flight check and the backup both read the platform's replica of # the database (carlos db restores a copy); an unreadable one stops here. REPLICA="Check the platform's replica with: carlos db query ${carlos_app[*]} --sql 'PRAGMA integrity_check' (it must print ok)" replica() { local said said=$(carlos db query "${carlos_app[@]}" --sql 'PRAGMA integrity_check' 2>/dev/null | tail -1) || said= [[ $said == ok ]] || die "the platform's replica of $APP's database cannot be read, and the in-flight check and the backup both need it. $REPLICA" } database_note() { echo " The database is not rolled back. If $(get version) started, its migrations may have run," echo " and $(get prev_version) now runs on the migrated database. The copy from before the upgrade:" echo " $(get backup) (sha256 $(get backup_sha256))" echo " No carlos verb writes a database back to an instance (carlos db only reads a copy)." echo " To restore it, a platform operator replaces the database of $HOST (the file the activator" echo " passes as --db) with that file, with the instance stopped. Check it first:" echo " python3 -c \"import sqlite3; print(sqlite3.connect('file:$(get backup)?mode=ro', uri=True).execute('pragma integrity_check').fetchone()[0])\"" } if [[ $mode == rollback ]]; then [[ -f $STATE ]] || die "no upgrade was recorded ($STATE)" [[ $(get rolled_back) != 1 ]] || die "already rolled back" snap=$BACKUPS/upgrade-$(get stamp) [[ -n $(get stamp) && -f $snap/service.env && -f $snap/equipo-runner.service ]] || die "the prior state was not recorded" prev_exec=$(sed -n 's/^ExecStart=\(.*\) run$/\1/p' "$snap/equipo-runner.service") [[ -f $prev_exec ]] || die "the previous runner $prev_exec is missing" prev_sha=$(sha256sum "$prev_exec" | cut -d ' ' -f 1) step "rollback 0 no open task holds unfinished work" echo " open tasks whose Engineering ran out of time and kept its work: 0 (a release before" echo " protocol 32 takes that work for finished), read now and again on two readings once" echo " the runner is stopped (only it reports steps); finish or cancel them first, or set" echo " UPGRADE_ALLOW_UNFINISHED=1 to roll back anyway" if ((execute)); then unfinished_none || die "$UNFINISHED_REFUSAL"; fi step "rollback 1 stop the runner" # A retry after the previous runner started again does not stop it a second time. if ((execute)) && runs "$prev_sha"; then echo " $UNIT already runs $prev_exec"; else run systemctl --user stop "$UNIT" # Nothing reports a step now: two readings, a wait apart, so the # replica has caught up with the last report the runner sent. if ((execute)); then for reading in 1 2; do ((reading == 1)) || sleep "${UPGRADE_WAIT:-5}" unfinished_none || { run systemctl --user start "$UNIT"; die "$UNFINISHED_REFUSAL (the runner was started again; nothing else changed)"; } done fi fi step "rollback 2 the previous runner's service.env and unit" 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 the previous instance version" run carlos promote "${carlos_app[@]}" "$(get prev_version)" edge wait_serving "$(get prev_version)" step "rollback 4 start the previous runner, and see it connected" run systemctl --user start "$UNIT" echo " $UNIT runs $prev_exec, welcomed by the instance in this invocation, on two readings" if ((execute)); then connected "$prev_sha" "the previous runner $prev_exec" || die "the previous runner is not connected; nothing recorded as rolled back" fi put rolled_back 1 if ((!execute)) || [[ $(get instance_started) == 1 ]]; then database_note; fi ((execute)) || echo $'\nPlan only. Run it with --execute.' exit 0 fi instance=$RELEASES/equipo-linux-arm64-$version runner_release=$RELEASES/equipo-runner-linux-amd64-$version staged=$RELEASES/staged/$version.json # The version production should serve: an unfinished upgrade to this # version resumes from its record; otherwise the last upgrade (finished, or # rolled back to its previous version) names it, or else the cutover. if [[ -f $STATE && $(get rolled_back) == 1 ]]; then base=$(get prev_version) history=1 elif [[ -f $STATE ]] && done_step verify; then base=$(get version) history=1 elif [[ -f $STATE ]]; then [[ $(get version) == "$version" ]] || die "an upgrade to $(get version) is unfinished; finish it or roll it back" base=$(get prev_version) else [[ -f $CUTOVER_STATE ]] || refuse "no cutover was recorded ($CUTOVER_STATE)" [[ $(get_in "$CUTOVER_STATE" done_verify) == 1 && $(get_in "$CUTOVER_STATE" rolled_back) != 1 ]] || refuse "the cutover has not finished ($CUTOVER_STATE has no done_verify)" base=$(get_in "$CUTOVER_STATE" version) fi [[ $base != "$version" ]] || die "production is already on $version" echo "Upgrade production from ${base:--unknown-} to $version." step "1 preflight" run make -C "$RELEASE_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" echo " production serves ${base:--unknown-} ($ORIGIN/api/version), and $version descends from it (git merge-base)" echo " $UNIT is $RUNNER_ROOT/equipo-runner.service, enrolled, talking to $PUBLIC_ORIGIN, roots not shared with $STAGING_ROOT" echo " the replica reads clean (the in-flight check and the backup need it):" printf ' $ carlos db query %s --sql "PRAGMA integrity_check" # must be ok\n' "${carlos_app[*]}" echo " nothing in flight (steps/merges/turns):" printf ' $ carlos db query %s --sql "%s" # must be 0/0/0\n' "${carlos_app[*]}" "$IN_FLIGHT" if ((execute)) && ! done_step preflight; then served=$(curl -fsS "$ORIGIN/api/version") || die "could not read the served version" [[ $served == "$base" ]] || die "production serves $served, but the records say $base" git -C "$RELEASE_REPO" merge-base --is-ancestor "$base" "$version" || die "$version does not descend from $base" unit_file=$(systemctl --user show -p FragmentPath --value "$UNIT") || die "could not read $UNIT" [[ $(readlink -f "$unit_file") == "$RUNNER_ROOT/equipo-runner.service" ]] || die "$UNIT is not the production runner unit" grep -qx "EnvironmentFile=$RUNNER_ROOT/service.env" "$RUNNER_ROOT/equipo-runner.service" || die "$UNIT does not read $RUNNER_ROOT/service.env" [[ $(file_value EQUIPO_RUNNER_STATE_DIR "$RUNNER_ROOT/service.env") == "$RUNNER_ROOT/state" ]] || die "the runner state is not $RUNNER_ROOT/state" [[ -f $RUNNER_ROOT/state/credentials.json ]] || die "the runner is not enrolled" [[ $(file_value EQUIPO_ORIGIN "$RUNNER_ROOT/service.env") == "$PUBLIC_ORIGIN" ]] || die "the runner does not talk to $PUBLIC_ORIGIN: finish the cutover first" if [[ -f $STAGING_ROOT/service.env ]]; then for key in EQUIPO_RUNNER_STATE_DIR EQUIPO_WORKSPACE_ROOT EQUIPO_SCRATCH_ROOT; do mine=$(file_value "$key" "$RUNNER_ROOT/service.env") theirs=$(file_value "$key" "$STAGING_ROOT/service.env") if [[ -n $mine && -n $theirs ]] && overlaps "$mine" "$theirs"; then die "$key is shared with the staging runner" fi done fi replica idle install -d -m 0700 "$BACKUPS" if ((history)); then mv "$STATE" "$BACKUPS/upgrade-$(get version)-$(get stamp).state"; history=0; fi stamp=$(date -u +%Y%m%dT%H%M%SZ) install -d -m 0700 "$BACKUPS/upgrade-$stamp" cp -p "$RUNNER_ROOT/service.env" "$RUNNER_ROOT/equipo-runner.service" "$BACKUPS/upgrade-$stamp/" put version "$version" put stamp "$stamp" put prev_version "$served" finish preflight fi stamp=PLAN ((history)) || stamp=$(get stamp) stamp=${stamp:-PLAN} step "2 backup: the current database (the upgrade keeps it: no configuration changes)" if ! done_step backup; then if ((execute)); then replica; fi backup=$BACKUPS/equipo-upgrade-$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 ('teams','chat_tasks','chat_steps','chat_turns','runners')]; sys.exit(r!='ok')" run sha256sum "$backup" run chmod 0400 "$backup" if ((execute)); then put backup "$backup" put backup_sha256 "$(sha256sum "$backup" | cut -d ' ' -f 1)" fi finish backup fi step "3 runner: the staged runner beside the current one, then the unit switches" new=$RUNNER_ROOT/releases/$version config=(--exec "$new/equipo-runner" "EQUIPO_TOOL_PROXY_PATH=$new/equipo-tool-proxy") if ! done_step runner; then run install -d -m 0700 "$new" run install -m 0700 "$runner_release/equipo-runner" "$runner_release/equipo-tool-proxy" "$runner_release/gitleaks" "$new/" # 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 "$new/equipo-runner" install-renderer "$runner_release/renderer.tar.gz" # The staged runner holds every program its configuration names, its # own tool proxy, the gitleaks and the renderer beside it, to its # release's digests before anything switches. run bash -c "set -a; . '$RUNNER_ROOT/service.env'; set +a; EQUIPO_TOOL_PROXY_PATH='$new/equipo-tool-proxy' '$new/equipo-runner' verify-installed" # Written from the preflight's record, never the live files, so a retry # gives the same files; each key, ExecStart and RestartSec exactly once. run python3 "$REPO/scripts/runner-config.py" render "$BACKUPS/upgrade-$stamp" "$RUNNER_ROOT" "${config[@]}" run systemctl --user daemon-reload echo " the loaded unit starts $new/equipo-runner (systemctl show -p ExecStart)" if ((execute)); then [[ $(systemctl --user show -p ExecStart --value "$UNIT") == *"path=$new/equipo-runner ;"* ]] || die "the loaded $UNIT does not start $new/equipo-runner" fi finish runner fi want=$( [[ -f $staged ]] && python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["sha256"]["runner"])' "$staged" || echo "the runner hash in $staged") echo " nothing in flight, read again right before the restart. This is a short window, not a drain:" echo " work dispatched after the reading, or not yet in the replica, can still be cut by the restart." if ! done_step restart; then # A retry after the restart happened finds the staged runner running and # does not restart it again. if ((execute)) && runs "$want"; then echo " $UNIT already runs the staged runner"; else if ((execute)); then idle; fi run systemctl --user restart "$UNIT" fi finish restart fi step "4 instance: the staged instance with --swap hold; its migrations run on start" echo " From here a rollback restores the previous version but not the database: that needs the step 2 backup." if ! done_step instance; then put instance_started 1 run carlos deploy "${carlos_app[@]}" --channel edge --target linux-arm64 --swap hold --version "$version" --timeout 5m --no-prompt "$instance" wait_serving "$version" finish instance fi step "5 verify" run curl -fsS "$ORIGIN/api/version" echo " sha256 of $PROC//exe must be $want" echo " $ journalctl --user -b _SYSTEMD_INVOCATION_ID= _PID= -o cat --no-pager" echo " the last stream line is msg=welcome (no later \"runner stream\" drop), on two readings of the same process" if ((execute)) && ! done_step verify; then [[ $(curl -fsS "$ORIGIN/api/version") == "$version" ]] || die "production does not report $version" connected "$want" "the staged $version runner" || die "the runner is not connected to the instance now; to undo: scripts/upgrade-thin.sh rollback --execute" finish verify fi echo " Then, as the owner: sign in at $PUBLIC_ORIGIN/conversation, check the offline line is" echo " gone, say hello and see the reply stream." echo " To undo: scripts/upgrade-thin.sh rollback --execute" ((execute)) || echo $'\nPlan only. Run it with --execute.'