iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / container / run.shmain at aacbc74

#!/bin/bash
# run.sh — ONE DEPLOY OF A MIND'S STACK, run by the installer's Deployer (worker/deploy-run.js) in
# its container: check the access, erase the domain when the person asked for that (erase.mjs),
# deploy, wait for iterate to answer, check what the deploy made (check-result.sh). Each step
# starts with a line
# `== step <id>` (the ids of STEPS), and the last line is `__EXIT__:<code>`, on every path.
#
# Inputs, from the environment the Deployer gives this process alone: CLOUDFLARE_API_TOKEN,
# CLOUDFLARE_ACCOUNT_ID, ITERATE_ZONE, ITERATE_ZONE_ID, ITERATE_NAME, and for "Erase and replace"
# ITERATE_ERASE, the name of the list the person agreed to. For an update, optionally
# ITERATE_RECORD_COMMIT (the commit that this Cloud's last run deployed there) and
# ITERATE_UPDATE_ANYWAY (`not_unknown_stack`). The stack's config is
# /work/mind.config.json for a first deploy; with no such file the stack deploys from the config
# it keeps beside its own state, which is how an update runs. The token is never an argument of a
# command (curl reads its header from standard input), and every line of output passes `redact`,
# which writes `[token]` in its place.
#
# A stack keeps its state in a store of its own: a Worker with Durable Objects, which the first
# deploy makes. A store that is seconds old can refuse every write. Cloudflare runs the new Worker
# at once, but one of its objects may not start for a quarter of a minute more, and Alchemy waits
# only for the Worker. That fails a first deploy with nothing made. So `make_store` makes a missing
# store before the deploy and waits until it answers, and a deploy that the store refused all the
# same runs once more.
export CI=1 DO_NOT_TRACK=1 FORCE_COLOR=0 NO_COLOR=1
API=https://api.cloudflare.com/client/v4

# Every line, as it comes, with the token's text replaced by [token]. A bash loop, not awk: the
# image's awk (mawk) reads a pipe in blocks, so the log would arrive all at once at the end.
redact() {
  local line
  while IFS= read -r line || [ -n "$line" ]; do
    [ -n "$CLOUDFLARE_API_TOKEN" ] && line=${line//"$CLOUDFLARE_API_TOKEN"/[token]}
    printf '%s\n' "$line"
  done
}

# GET a path of Cloudflare's API with the token: the body, then a line with the HTTP status.
cf_get() {
  printf 'Authorization: Bearer %s\n' "$CLOUDFLARE_API_TOKEN" | curl -s -m 30 -H @- -w '\n%{http_code}' "$API$1"
}

# DELETE a path of Cloudflare's API with the token: the body, then a line with the HTTP status.
cf_delete() {
  printf 'Authorization: Bearer %s\n' "$CLOUDFLARE_API_TOKEN" | curl -s -m 30 -H @- -X DELETE -w '\n%{http_code}' "$API$1"
}

# PUT a path of Cloudflare's API with the token and a JSON body: the body, then a line with the HTTP status.
cf_put() {
  printf 'Authorization: Bearer %s\n' "$CLOUDFLARE_API_TOKEN" | curl -s -m 30 -H @- -H 'content-type: application/json' -X PUT --data "$2" -w '\n%{http_code}' "$API$1"
}

# The account's workers.dev name: a new account has none (10007), and the wizard gives it one. A
# chat installation gives it the names in ITERATE_WORKERS_DEV_NAMES (from the person's email,
# worker/account-name.js), then the stack's name, then that name with four random letters, until
# one is not someone else's (10031).
workers_dev_ready() {
  local out code body name
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/subdomain"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" = 200 ] && [ -n "$(jq -r '.result.subdomain // empty' <<<"$body")" ]; then
    echo "workers.dev: $(jq -r '.result.subdomain' <<<"$body").workers.dev"
    return 0
  fi
  if ! grep -q 10007 <<<"$body"; then
    echo "Cloudflare answered $code to GET the account's workers.dev name."
    return 1
  fi
  # shellcheck disable=SC2086 # the names are split at spaces
  for name in $ITERATE_WORKERS_DEV_NAMES "$ITERATE_NAME" "$ITERATE_NAME-$(tr -dc 'a-z0-9' </dev/urandom | head -c 4)"; do
    # a derived name is checked first, as wrangler does: 10031 taken (next name), 10032 free
    if [[ " $ITERATE_WORKERS_DEV_NAMES " == *" $name "* ]] &&
      grep -q 10031 <<<"$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/subdomains/$name")"; then
      echo "workers.dev: $name is taken."
      continue
    fi
    out=$(cf_put "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/subdomain" "{\"subdomain\":\"$name\"}"); code=${out##*$'\n'}
    if [ "$code" = 200 ]; then
      echo "workers.dev: made $name.workers.dev for the account."
      return 0
    fi
  done
  echo "Cloudflare refused a workers.dev name for the account ($code)."
  return 1
}

# Make the stack's state store, then wait until it lists its stacks: that answer comes from the
# store's index object, which can refuse while the Worker itself answers. Five minutes at most.
make_store() {
  local alchemy="node node_modules/alchemy/bin/cli.js" i
  # five minutes at most: a bootstrap can wait without end, and then leave a store that answers
  # 404. `--force` makes such a store again; this path runs only when there was no store, so there
  # is no state to lose.
  if ! timeout 300 $alchemy state bootstrap --backend cloudflare --name "$1" --no-input; then
    echo "The state store $1 was not made. One more try."
    if ! timeout 300 $alchemy state bootstrap --backend cloudflare --name "$1" --no-input --force; then
      echo "The state store $1 was not made."
      return 1
    fi
  fi
  for i in $(seq 1 20); do
    if $alchemy state list --backend cloudflare --name "$1" --no-input >/dev/null 2>&1; then
      echo "The state store answers."
      return 0
    fi
    echo "The state store does not answer yet, waiting"
    sleep 5
  done
  echo "The state store did not answer within five minutes."
  return 1
}

# The config that the stack keeps beside its state, as one line of JSON; nothing when it keeps
# none. A store with no deploy that ended keeps none: it has no stack at all (the read says
# "null"), or parts of one and no output yet (the read fails with "path does not exist"). Any
# other read returns 1, a failed one and one whose answer is not an output: the run must not take
# "I could not read it" for "there is none".
stored_config() {
  local out json
  if ! out=$(CI=true timeout 120 node node_modules/alchemy/bin/cli.js state read "mind/$ITERATE_NAME/output" \
    --backend cloudflare --name "$1" 2>/work/stored-config.err); then
    grep -q "path does not exist" /work/stored-config.err && return 0
    return 1
  fi
  json=$(sed -n '/^{$/,$p' <<<"$out")
  if [ -z "$json" ]; then
    grep -Eq '^null[[:space:]]*$' <<<"$out" && return 0
    return 1
  fi
  jq -ce 'if type == "object" then .config // empty else error("not an output") end' <<<"$json" 2>/dev/null
  local said=$?
  # jq -e says 4 when it printed nothing: an output with no config in it
  [ $said -eq 0 ] || [ $said -eq 4 ]
}

# A STACK THAT EXISTS DEPLOYS FROM ITS OWN CONFIG, whatever the run was given. The page gives a
# config when it thinks this is a first deploy, and it thinks so after an update that failed
# ("Try again"): that config names the owner alone, so it would drop every other member that the
# stack's config names. The owner's ticket stays when the stack's config names its address as an
# owner (the stack refuses any other, and the deploy would fail).
keep_stored_config() {
  [ -n "$ITERATE_MIND_CONFIG" ] || return 0
  local stored email
  if [ -s "$STORED" ]; then
    stored=$(cat "$STORED")
  elif ! stored=$(stored_config "$1"); then
    echo "Stopped: the run could not read the config that iterate keeps for $ITERATE_ZONE, so it cannot tell a first deploy from an update. Nothing was changed. Press Try again."
    return 1
  fi
  [ -n "$stored" ] || return 0
  if [ -f /work/config-published ]; then
    # the config of this deploy is the one that the stack keeps, with the fields `stack_updatable` set
    echo "iterate is on $ITERATE_ZONE already: this deploy uses the config that the stack keeps, with its members, and with what the notes above say it sets in it."
  else
    # check-result.sh reads the same variable: a config that the deploy did not use says nothing
    # about what the deploy must have made
    unset ITERATE_MIND_CONFIG
    echo "iterate is on $ITERATE_ZONE already: this deploy uses the config that the stack keeps, with its members, not a new one."
  fi
  [ -n "$ITERATE_FIRST_OWNER_TICKET" ] || return 0
  email=$(jq -r '.email // "" | ascii_downcase' <<<"$ITERATE_FIRST_OWNER_TICKET")
  if ! jq -e --arg e "$email" 'any(.auth.login.allow[]?; .email == $e)' >/dev/null <<<"$stored"; then
    unset ITERATE_FIRST_OWNER_TICKET
    echo "No first-passkey link: $email is not an owner in the config that the stack keeps. Sign in at https://iterate.$ITERATE_ZONE with an address that is."
  fi
}

# AN UPDATE MUST BE ONE THAT THIS RUN CAN MAKE, asked in the first step, before anything changes.
# A stack that exists was deployed by this page or from a computer (the four first minds were), so
# its config can ask for what this container does not have. The run reads the config that the stack
# keeps (to $STORED, which `keep_stored_config` and check-result.sh read too) and stops when:
#   - the store keeps no config and the run was given none: no deploy of the stack ever ended;
#   - the config is of another name, domain or account (a config with no domain is not of another
#     domain: see below);
#   - the vault's key is kept outside Cloudflare (`atRestKey: "environment"`): the deploy needs
#     the key, which this run never has. The first sentence of that stop is what the Cloud knows it
#     by (worker/deploy-run.js KEY_OUTSIDE), and "Your deployments" then shows no Update button;
#   - the config asks for a sandbox image built with Docker: a named image with a `dockerfile`
#     (`mind.images`), or the older word for iterate's (`mind.sandboxImage: "built"`).
# A config from before `mind.images` that says no word about its image means a built one too
# (core/alchemy/src/config.ts `withImageOfBefore`; every config stored since says `images` or
# `containers`). The run does not stop there: it deploys from the stack's config with
# `mind.sandboxImage: "published"` set, the older word that the stack still reads, and says so in
# a note. The published image is the built one, built by iterate and pushed to the account's
# registry by the deploy (core/alchemy/scripts/sandbox-image.ts), which needs no Docker.
#
# A STACK DEPLOYED BEFORE ITS DOMAIN (a chat installation's phase `early`, or a deploy from a
# computer; its config has no `domain`) takes this run's domain: the config of this deploy is the
# one that the stack keeps, with `domain`, with mail and the mailed sign-in code as every first
# deploy of the Cloud has them (a stack with no domain can have neither), and without
# `cloudflarePlan`. Every run that gets here waited for Workers Paid and R2 (the wizard before the
# consent, a chat installation before its deploy). One note says so.
#
# THE STACK'S OWN TELEMETRY (`telemetry: true`: its warehouse, and two narrow API tokens for its
# telemetry Worker alone, which stay in the account) is on only when this run's access may make
# it: the person pressed "Turn on telemetry", their consent then gave the scope that makes API
# tokens, and the Cloud sets ITERATE_TELEMETRY=1 (worker/scopes.js `telemetryGranted`). A first deploy's config says it then. An update of a stack
# whose config has none sets it in the config that the stack keeps, with a note. Without the
# scope, an update runs as it always did and a note says how to turn telemetry on. A stack that
# has telemetry keeps it at every update: its tokens are there, and no deploy makes them again.
#
# A TELEMETRY PART THAT FAILS DOES NOT FAIL THE DEPLOY. When this run turned telemetry on and the
# deploy then failed, the run deploys once more with telemetry off (`without_telemetry`,
# `deploy_stack`): the stack is updated, and one line says that telemetry was not turned on and
# what the person does next.
#
# THE MIND'S CLOUDFLARE CONNECTION (`cloudflareToken: true`: one API token of the account for the
# mind itself, with which its agents read the account and query its logs and traces, and change
# nothing; core/alchemy README, "The mind's Cloudflare token") is the person's choice on the deployment's card: "Give
# this mind a Cloudflare connection". Their consent then gave the scope that makes API tokens, and
# the Cloud sets ITERATE_CLOUDFLARE_TOKEN=1. A first deploy's config says it then; an update sets
# it in the config that the stack keeps, with a note. A mind that runs outside the stack
# (`mind.provided`) takes none. A stack that has the token keeps it at every update. Without
# ITERATE_CLOUDFLARE_TOKEN=1 the deploy keeps the token as it is (ITERATE_KEEP_CLOUDFLARE_TOKEN),
# also when this release changes what the token may do, and the mind then keeps no token of the
# older list: the card offers the consent again (worker/scopes.js `CLOUDFLARE_TOKEN_EDITION`).
# With it, the deploy makes the token this release's, and says so: `cloudflare-token made by this
# release`.
#
# A TOKEN THAT CLOUDFLARE REFUSES DOES NOT FAIL THE DEPLOY when this run's access may change API
# tokens: the run deploys once more without the field (`without_cloudflare_token`,
# `deploy_stack`), which removes a token the stack had, and one line says so. With an access that
# may not change API tokens there is no second try (the deploy without the field would have to
# delete the token, which the same access cannot do): one line says what the person does.
STORED=/work/stored-config.json
export ITERATE_MIND_PROVIDED=
stack_updatable() {
  local store="iterate-$ITERATE_NAME-state" out code stored said
  rm -f "$STORED" /work/config-published
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$store/script-settings"); code=${out##*$'\n'}
  [ "$code" = 404 ] && return 0
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET the Worker $store."
    return 1
  fi
  if ! stored=$(cd /stack/core/alchemy && stored_config "$store"); then
    echo "Stopped: the run could not read the config that iterate keeps for $ITERATE_ZONE, so it cannot tell a first deploy from an update. Nothing was changed. Press Try again."
    return 1
  fi
  if [ -z "$stored" ]; then
    [ -f /work/mind.config.json ] && return 0
    echo "Stopped: iterate keeps no config for $ITERATE_ZONE under the name $ITERATE_NAME: no deploy of it ever ended, so there is nothing to update. Nothing was changed. Erase and replace it, or deploy it once from a computer that has its config."
    return 1
  fi
  printf '%s\n' "$stored" > "$STORED"
  said=$(jq -r --arg n "$ITERATE_NAME" --arg z "$ITERATE_ZONE" --arg a "$CLOUDFLARE_ACCOUNT_ID" '
    if .name != $n or (.domain != null and .domain != $z) then "other"
    elif .accountId != $a then "account"
    elif .atRestKey == "environment" then "key"
    elif .mind.sandboxImage == "built" or any(.mind.images[]?; has("dockerfile")) then "built"
    elif .mind.provided == true or .mind.containers == false or .mind.images != null or .mind.sandboxImage != null then "ok"
    else "unnamed" end' "$STORED" 2>/dev/null)
  case $said in
    ok) ;;
    other)
      echo "Stopped: the config that iterate keeps under the name $ITERATE_NAME is for $(jq -r '"\(.domain // "no domain"), under the name \(.name)"' "$STORED"), not for $ITERATE_ZONE. Nothing was changed."
      return 1 ;;
    account)
      echo "Stopped: the config that iterate keeps for $ITERATE_ZONE names another Cloudflare account. Nothing was changed."
      return 1 ;;
    key)
      echo "Stopped: This deployment keeps its vault key outside Cloudflare. Update it from a computer that holds the key. Nothing was changed."
      return 1 ;;
    built)
      echo "Stopped: This deployment builds its sandbox image with Docker (its config names a Dockerfile), and iterate Cloud has no Docker. Update it from a computer that has Docker, or name a pushed image in mind.images there. Nothing was changed."
      return 1 ;;
    unnamed)
      if ! jq -c '.mind = ((.mind // {}) + {sandboxImage: "published"})' "$STORED" > /work/mind.config.json; then
        echo "Stopped: the run could not write the config of this deploy. Nothing was changed."
        return 1
      fi
      : > /work/config-published
      echo "Note: The config of this deployment named no sandbox image, which means an image built with Docker. iterate Cloud has no Docker: this update set mind.sandboxImage to \"published\" in the config that the stack keeps, so its sandboxes start the image that iterate builds and publishes, copied into this account's registry." ;;
    *)
      echo "Stopped: the run could not understand the config that iterate keeps for $ITERATE_ZONE. Nothing was changed."
      return 1 ;;
  esac
  if [ "$(jq -r '.domain // ""' "$STORED")" = "" ]; then
    # on top of the sandbox image's change above, when this run made one
    local before=$STORED
    [ -f /work/config-published ] && before=/work/mind.config.json
    # with Workers Paid the account has Containers: a stack with no sandboxes yet gets them, with no
    # named image, so its sandboxes start the Cloudflare-managed image cloudflare/debian-trixie
    if ! jq -c --arg z "$ITERATE_ZONE" '.domain = $z | .mail = true | .auth.login.methods.email //= {} | del(.cloudflarePlan) | if .mind.sandboxImage == "later" or .mind.containers == false then .mind |= (del(.sandboxImage, .containers) + {images: {}}) else . end' "$before" > /work/mind.config.next.json || ! mv /work/mind.config.next.json /work/mind.config.json; then
      echo "Stopped: the run could not write the config of this deploy. Nothing was changed."
      return 1
    fi
    : > /work/config-published
    echo "Note: The stack $ITERATE_NAME was deployed before its domain. This deploy gives it $ITERATE_ZONE, with mail and sign-in with a mailed code, and the parts that need Workers Paid and R2 (domain, mail: true and auth.login.methods.email, no cloudflarePlan, and its containers with no named image for one that had none yet, in the config that the stack keeps)."
  fi
  if [ "$(jq -r '.telemetry // false' "$STORED")" != true ]; then
    if [ "$ITERATE_TELEMETRY" = 1 ]; then
      # on top of the sandbox image's change above, when this run made one
      local from=$STORED
      [ -f /work/config-published ] && from=/work/mind.config.json
      if ! jq -c '.telemetry = true' "$from" > /work/mind.config.next.json || ! mv /work/mind.config.next.json /work/mind.config.json; then
        echo "Stopped: the run could not write the config of this deploy. Nothing was changed."
        return 1
      fi
      : > /work/config-published
      : > /work/telemetry-on
      echo "Note: This update turns on telemetry for $ITERATE_ZONE (telemetry: true in the config that the stack keeps): its events, logs and traces go to a warehouse in your own account, which your mind and its Dash read. The deploy makes two narrow API tokens for that, named iterate-$ITERATE_NAME-telemetry-catalog and iterate-$ITERATE_NAME-telemetry-analytics. They stay in your account; iterate Cloud keeps neither."
    else
      echo "Note: telemetry stays off for $ITERATE_ZONE. To turn it on, press \"Turn on telemetry\" on its card in iterate Cloud: Cloudflare then asks for one more permission."
    fi
  fi
  if [ "$ITERATE_CLOUDFLARE_TOKEN" = 1 ] && [ "$(jq -r '.cloudflareToken // false' "$STORED")" != true ]; then
    if [ "$(jq -r '.mind.provided // false' "$STORED")" = true ]; then
      echo "Note: no Cloudflare connection for $ITERATE_ZONE: its mind runs outside this deployment (mind.provided in its config), and such a deployment takes none."
    else
      # the config of this deploy: the one this run wrote, else the one the stack keeps
      local with=$STORED
      [ -f /work/config-published ] && with=/work/mind.config.json
      if ! jq -c '.cloudflareToken = true' "$with" > /work/mind.config.next.json || ! mv /work/mind.config.next.json /work/mind.config.json; then
        echo "Stopped: the run could not write the config of this deploy. Nothing was changed."
        return 1
      fi
      : > /work/config-published
      : > /work/cloudflare-token-on
      echo "Note: This update gives the mind of $ITERATE_ZONE a Cloudflare connection (cloudflareToken: true in the config that the stack keeps). The deploy makes one API token in your account for it, whose name begins iterate-$ITERATE_NAME-cloudflare: it reads the account and its zones, and queries the logs and traces of its Workers, so that the mind's agents can see what the account runs. It changes nothing in the account, and it reaches nothing beyond the account. It stays in your account; iterate Cloud does not keep it."
    fi
  fi
  [ "$(jq -r '.mind.provided // false' "$STORED")" = true ] && ITERATE_MIND_PROVIDED=1
  return 0
}

# The config of this deploy with telemetry off again, when this run turned it on: 0 when the config
# was rewritten. For a stack that exists it is then the config that the stack keeps (with the
# sandbox image's change, when the run made one).
without_telemetry() {
  [ -f /work/telemetry-on ] && [ -f /work/mind.config.json ] || return 1
  jq -c 'del(.telemetry)' /work/mind.config.json > /work/mind.config.next.json || return 1
  mv /work/mind.config.next.json /work/mind.config.json || return 1
  rm -f /work/telemetry-on
}

# The config of this deploy without the mind's Cloudflare token: 0 when the config was rewritten.
# Only with an access that may change API tokens (ITERATE_CLOUDFLARE_TOKEN): when this run set the
# field, and when Cloudflare refused the token of a stack whose config has the field already (the
# deploy without the field then deletes that token).
without_cloudflare_token() {
  [ "$ITERATE_CLOUDFLARE_TOKEN" = 1 ] || return 1
  [ -f /work/cloudflare-token-on ] || [ -f /work/cloudflare-token-refused ] || return 1
  local from=/work/mind.config.json
  [ -f "$from" ] || from=$STORED
  [ "$(jq -r '.cloudflareToken // false' "$from" 2>/dev/null)" = true ] || return 1
  jq -c 'del(.cloudflareToken)' "$from" > /work/mind.config.next.json || return 1
  mv /work/mind.config.next.json /work/mind.config.json || return 1
  rm -f /work/cloudflare-token-on
  # the next deploy reads this config, also for a stack that deploys from the config it keeps
  export ITERATE_MIND_CONFIG=/work/mind.config.json
}

# The deploy, with its second tries: once more when the state store refused it; once more as it
# was when this run turned the mind's Cloudflare token or telemetry on and the deploy failed in
# neither token; once more without the mind's Cloudflare token when Cloudflare refused it or this
# run set it and the deploy failed; and once more with telemetry off when this run turned
# telemetry on and the deploy failed. Returns the last deploy's exit code.
deploy_stack() {
  local code
  deploy; code=$?
  if [ "$code" != 0 ] && [ -f /work/store-refused ]; then
    echo "The state store refused the deploy. One more try, in fifteen seconds."
    sleep "${ITERATE_RETRY_SECONDS:-15}"
    deploy; code=$?
  fi
  # A failure elsewhere can end by itself: on a new zone, Cloudflare refuses the mail events
  # subscription until the zone's Email Sending is on ("domain is not an enabled sending
  # subdomain"). The tries below drop what this run turned on, so the same config goes first.
  if [ "$code" != 0 ] && { [ -f /work/cloudflare-token-on ] || [ -f /work/telemetry-on ]; } \
    && [ ! -f /work/cloudflare-token-refused ] && [ ! -f /work/telemetry-token-refused ]; then
    echo "The deploy failed (exit $code), and not in a token that this run turned on. One more try with the same config, in fifteen seconds."
    sleep "${ITERATE_RETRY_SECONDS:-15}"
    deploy; code=$?
  fi
  if [ "$code" != 0 ]; then
    # read now: the next deploy removes the mark
    local refused=
    [ -f /work/cloudflare-token-refused ] && refused=1
    if without_cloudflare_token; then
      local cause="its part of the deploy failed (the lines above say where)"
      [ -n "$refused" ] && cause="Cloudflare refused its API token"
      echo "The deploy failed with the mind's Cloudflare connection in its config (exit $code). One more try, without it."
      deploy; code=$?
      [ "$code" = 0 ] && echo "Note: the mind of $ITERATE_ZONE has no Cloudflare connection: $cause. iterate on $ITERATE_ZONE is deployed and works without it, and the mind has no API token in your account. To try again, press \"Give this mind a Cloudflare connection\" on its card in iterate Cloud."
    elif [ -n "$refused" ]; then
      echo "Note: Cloudflare refused a change to the mind's API token, and this access to Cloudflare may not change API tokens. Press \"Give this mind a Cloudflare connection\" on its card in iterate Cloud (Cloudflare then asks for one more permission), then update again. Until then the mind uses no token of an older list, so it may have no Cloudflare connection."
    fi
  fi
  if [ "$code" != 0 ] && without_telemetry; then
    local why="its part of the deploy failed (the lines above say where)"
    [ -f /work/telemetry-token-refused ] && why="Cloudflare refused to create its token"
    echo "The deploy failed with telemetry turned on (exit $code). One more try, with telemetry off."
    deploy; code=$?
    [ "$code" = 0 ] && echo "Note: telemetry not turned on: $why. iterate on $ITERATE_ZONE is deployed and works without it. To turn it on later, press \"Turn on telemetry\" on its card in iterate Cloud, or deploy once from a computer with an API token that may create API tokens (core/alchemy README, \"Telemetry\")."
  fi
  return "$code"
}

# One line per Worker of the stack that exists: `version <before|after> <worker> <version id>`, the
# version that Cloudflare serves now. The Deployer keeps them in the run's record
# (worker/deploy-run.js): the proof of what an update changed.
versions_now() {
  local worker out code body id
  for worker in boundary auth secrets mind; do
    worker="iterate-$ITERATE_NAME-$worker"
    out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$worker/deployments"); code=${out##*$'\n'}; body=${out%$'\n'*}
    [ "$code" = 200 ] || continue
    id=$(jq -r '.result.deployments[0].versions | max_by(.percentage) | .version_id // empty' <<<"$body" 2>/dev/null)
    [ -n "$id" ] && echo "version $1 $worker $id"
  done
  return 0
}

# ITERATE_PROTOTYPE_TOKEN is a stand-in credential that a deploy from a computer can give the
# stack's auth Worker. A deploy from here never has it, so the binding goes: right for a real
# mind (the coordinator's call, 11 November 2026). `had_stand_in before` notes that it was there;
# `had_stand_in after` says so in the log when it was there and no longer is.
had_stand_in() {
  local out code body
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/iterate-$ITERATE_NAME-auth/settings"); code=${out##*$'\n'}; body=${out%$'\n'*}
  [ "$code" = 200 ] || return 0
  if jq -e 'any(.result.bindings[]?; .name == "ITERATE_PROTOTYPE_TOKEN")' >/dev/null 2>&1 <<<"$body"; then
    [ "$1" = before ] && : > /work/had-stand-in
  elif [ "$1" = after ] && [ -f /work/had-stand-in ]; then
    echo "Note: This deployment's sign-in had a stand-in credential (ITERATE_PROTOTYPE_TOKEN), given by a deploy from a computer. An update from iterate Cloud does not carry it: the deployment no longer has it."
  fi
  return 0
}

# The stack's whole deploy. Every line passes on as it comes; a line that says the state store
# failed leaves a note, /work/store-refused. Twenty minutes at most: a deploy takes a few, and the
# token ends within the hour.
deploy() {
  rm -f /work/store-refused /work/telemetry-token-refused /work/cloudflare-token-refused
  # --adopt: the deploy takes up what an earlier run of iterate left when that run's state is gone
  # (a store that refused its writes, or a store made again). Without it Alchemy refuses each such
  # part ("OwnedBySomeoneElse") and nothing is deployed.
  # `records_free` runs first, so a record that the deploy takes up is one the stack makes itself.
  # ITERATE_COMMIT: the packed stack has no git, and the deploy writes its commit on the boundary
  # Worker (`not_unknown_stack` reads it at the next update)
  ITERATE_COMMIT=$(cat /stack/COMMIT) timeout 1200 pnpm run deploy --stage "$ITERATE_NAME" --yes --adopt 2>&1 | {
    local line
    while IFS= read -r line || [ -n "$line" ]; do
      case $line in
        *"State store "*failed*) : > /work/store-refused ;;
        # a telemetry token that Cloudflare did not make: `deploy_stack` says so
        *"[TelemetryCatalogToken] fail"*|*"[TelemetryAnalyticsToken] fail"*) : > /work/telemetry-token-refused ;;
        # the mind's own Cloudflare token (core/alchemy/src/stack.ts `cloudflareTokenPart`)
        *"[MindCloudflareToken] fail"*) : > /work/cloudflare-token-refused ;;
      esac
      printf '%s\n' "$line"
    done
  }
  return "${PIPESTATUS[0]}"
}

# The names the stack needs must be free, or hold the stack's own record (AAAA 100::, proxied): the
# domain itself and '*' (the stack makes these two), and 'iterate' and '*.iterate' (a record there
# wins over '*', so iterate.<domain> would go elsewhere). A record that points somewhere else is
# the person's: the run never replaces it. It stops, names each record and changes nothing.
# One more is the stack's own: a PROXIED placeholder, an A in 192.0.2.0/24, on a name
# whose route `<name>/*` the stack's own Worker holds. Proxied, it reaches no origin: the route
# serves the name. A routes read that does not answer 200 leaves the stop as it was.
# A line "Stopped: …" is for the person's page (src/deploy-steps.ts).
records_free() {
  local out code body name found= held=
  local names=("$ITERATE_ZONE" "*.$ITERATE_ZONE" "iterate.$ITERATE_ZONE" "*.iterate.$ITERATE_ZONE")
  out=$(cf_get "/zones/$ITERATE_ZONE_ID/workers/routes"); code=${out##*$'\n'}; body=${out%$'\n'*}
  # the names whose route the stack's own Worker holds, one per line
  [ "$code" = 200 ] && held=$(jq -r --arg mine "iterate-$ITERATE_NAME-boundary" \
    '.result[] | select(.script == $mine) | .pattern | select(endswith("/*")) | .[:-2]' <<<"$body")
  for name in "${names[@]}"; do
    out=$(cf_get "/zones/$ITERATE_ZONE_ID/dns_records?per_page=100&name=$name"); code=${out##*$'\n'}; body=${out%$'\n'*}
    if [ "$code" != 200 ]; then
      echo "Cloudflare answered $code to GET the DNS records of $name."
      return 1
    fi
    found+=$(jq -r --arg held "$held" '($held | split("\n")) as $held | .result[]
      | select(.type == "A" or .type == "AAAA" or .type == "CNAME")
      | select((.type == "AAAA" and .content == "100::") | not)
      | select((.proxied == true and (.name as $n | $held | index($n))
          and .type == "A" and (.content | startswith("192.0.2."))) | not)
      | "\(.type) \(.name) → \(.content)"' <<<"$body")$'\n'
  done
  found=$(grep -v '^$' <<<"$found" | paste -sd';' - | sed 's/;/; /g')
  [ -z "$found" ] && return 0
  echo "Stopped: $ITERATE_ZONE already has DNS records that point somewhere else: $found. iterate needs these names. Delete these records in Cloudflare (your domain, DNS, Records) and press Try again, or choose another domain. Nothing was changed."
  return 1
}

# Workers that are iterate's own and not the stack's: a deployment made as one Worker, under the
# wizard's default name for it, and the boundary Worker under its name from before 11 November
# 2026. Such a Worker holds the routes of the domain, and a route has one Worker, so the stack's
# deploy cannot attach them.
OLD_WORKERS="iterate iterate-$ITERATE_NAME-ingress"

# A stack from before 11 November 2026 has its Workers under other names (`-project`, `-ingress`)
# and keeps its state, config and data under them. This version's deploy would make a new, empty
# iterate beside it. So a run that is not "Erase and replace" stops here, before it writes a
# config, makes a store or removes a route. The stack's own deploy refuses the same
# (core/alchemy/scripts/refuse-older-stack.ts). The first sentence of the stop is what the page
# knows it by (src/deploy-steps.ts `olderStackOf`).
not_older_stack() {
  local out code worker found=
  for worker in "iterate-$ITERATE_NAME-project" "iterate-$ITERATE_NAME-ingress"; do
    out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$worker/script-settings"); code=${out##*$'\n'}
    case $code in
      404) ;;
      200) found+="${found:+ and }$worker" ;;
      *)
        echo "Cloudflare answered $code to GET the Worker $worker."
        return 1
        ;;
    esac
  done
  [ -z "$found" ] && return 0
  echo "Stopped: This iterate is from before a large change. It cannot be updated in place. Erase and replace it: its members, files and config repo are not kept. Your Cloudflare account has $found, which the earlier iterate made. Nothing was changed."
  return 1
}

# AN UPDATE NEVER REPLACES A STACK WITH AN OLDER ITERATE WITHOUT A WORD. A deploy writes the commit
# it is made from on the stack's boundary Worker, as the tag `iterate-commit:<40 hex>`
# (core/alchemy/src/stack.ts), and /stack/COMMITS lists every commit that this image's iterate has
# behind it (pack-stack.sh). The stack's commit is the tag, else what this Cloud's last run
# deployed there (ITERATE_RECORD_COMMIT). When it is not in the list, the stack is newer than
# this Cloud or from another branch, and this deploy would put something that is not its
# successor in its place: its state and config may have a shape this iterate does not know.
# The run then stops, before it changes anything. The one way past is the person's own word for
# exactly this replacement: ITERATE_UPDATE_ANYWAY holds the commit they saw on the card ("Update
# anyway"), and it must be the commit the stack runs now. A stack with no tag and no record is
# from before the tag: it is updated, and one line says so.
# The line `replaces <commit>` is for the run's record (worker/deploy-run.js `finish`).
COMMIT_TAG="iterate-commit:"
not_unknown_stack() {
  local worker="iterate-$ITERATE_NAME-boundary" out code body theirs mine
  mine=$(cat /stack/COMMIT)
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$worker/script-settings"); code=${out##*$'\n'}; body=${out%$'\n'*}
  [ "$code" = 404 ] && return 0
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET the Worker $worker."
    return 1
  fi
  if ! theirs=$(jq -er --arg t "$COMMIT_TAG" 'if (.result | type) != "object" then error("no result") else [(.result.tags // [])[] | select(startswith($t)) | ltrimstr($t)] end | if length > 1 then error("more than one") else (.[0] // "none") end' <<<"$body" 2>/dev/null); then
    echo "Stopped: the run could not read which iterate ${ITERATE_ZONE:-the stack $ITERATE_NAME} runs from its Worker $worker. Nothing was changed. Press Try again."
    return 1
  fi
  if [ "$theirs" = none ]; then
    theirs=${ITERATE_RECORD_COMMIT:-}
    if [ -z "$theirs" ]; then
      echo "Note: Nothing records which iterate ${ITERATE_ZONE:-the stack $ITERATE_NAME} runs (a deploy from before 12 November 2026 wrote none), so this update cannot check that it is not newer than iterate Cloud's. From this update on, its Worker $worker says which."
      return 0
    fi
  fi
  if ! [[ $theirs =~ ^[0-9a-f]{40}$ ]]; then
    echo "Stopped: the Worker $worker says which iterate ${ITERATE_ZONE:-the stack $ITERATE_NAME} runs in a way this run does not understand. Nothing was changed."
    return 1
  fi
  if [ ! -s /stack/COMMITS ]; then
    echo "Stopped: this iterate Cloud does not know which versions of iterate it can update. Nothing was changed."
    return 1
  fi
  grep -qxF "$theirs" /stack/COMMITS && return 0
  if [ "${ITERATE_UPDATE_ANYWAY:-}" = "$theirs" ]; then
    echo "Note: Update anyway: this deployment ran iterate at ${theirs:0:9}, which iterate Cloud does not have. You asked to replace it with ${mine:0:9}."
    echo "replaces $theirs"
    return 0
  fi
  echo "Stopped: This deployment runs iterate at ${theirs:0:9}, which this Cloud does not have: it is newer than the Cloud, or from another branch. Nothing was changed. Update it from a computer, wait until iterate Cloud is updated, or press “Update anyway” on its card in your deployments."
  return 1
}

# The routes the stack needs must be free, held by the stack's own Worker, or held by one of
# OLD_WORKERS: <domain>/* and *.<domain>/* (the stack attaches these two), and iterate.<domain>/*
# and *.iterate.<domain>/* (a route there wins over the wildcard, so iterate.<domain> would go
# elsewhere). A route of any other Worker is the person's: the run stops, names the Worker and
# changes nothing. A route of an older iterate Worker is iterate's own: this check writes it to
# /work/old-routes and removes nothing; `old_routes_removed` removes it right before the deploy.
routes_free() {
  local out code body mine="iterate-$ITERATE_NAME-boundary" foreign old line id pattern script
  out=$(cf_get "/zones/$ITERATE_ZONE_ID/workers/routes"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET the Workers routes of $ITERATE_ZONE."
    return 1
  fi
  body=$(jq -c --arg z "$ITERATE_ZONE" --arg mine "$mine" '[.result[]
    | select(.pattern == "\($z)/*" or .pattern == "*.\($z)/*" or .pattern == "iterate.\($z)/*" or .pattern == "*.iterate.\($z)/*")
    | select(.script != $mine) | {id, pattern, script: (.script // "")}]' <<<"$body")
  foreign=$(jq -r --arg old "$OLD_WORKERS" '[.[] | select(.script as $s | ($old | split(" ") | index($s)) | not)
    | if .script == "" then "\(.pattern) is a route that turns Workers off"
      else "\(.pattern) is served by your Worker “\(.script)”" end] | join("; ")' <<<"$body")
  if [ -n "$foreign" ]; then
    echo "Stopped: $foreign. iterate needs these addresses. In Cloudflare, open your domain, Workers Routes, and delete each of these routes, then press Try again. Or choose another domain. Nothing was changed."
    return 1
  fi
  jq -r '.[] | [.id, .pattern, .script] | @tsv' <<<"$body" > /work/old-routes
  return 0
}

# Remove the routes that `routes_free` found on an older iterate Worker. THE LAST THING BEFORE THE
# DEPLOY, after every stop that changes nothing: from here until the deploy attaches the routes to
# the stack's Worker, the domain is served by nobody.
old_routes_removed() {
  local out code id pattern script
  # the names of the older Workers it took routes from, for `old_workers_left`
  : > /work/old-workers
  while IFS=$'\t' read -r id pattern script; do
    [ -z "$id" ] && continue
    out=$(cf_delete "/zones/$ITERATE_ZONE_ID/workers/routes/$id"); code=${out##*$'\n'}
    if [ "$code" != 200 ]; then
      echo "Cloudflare answered $code to DELETE the route $pattern of the Worker $script."
      return 1
    fi
    echo "Removed the route $pattern from the Worker “$script”, which an earlier iterate made: this deploy serves $ITERATE_ZONE in its place."
    printf '%s\t%s\n' "$script" "$pattern" >> /work/old-workers
  done < /work/old-routes
  return 0
}

# After a deploy that works, one line for the person's page ("Note: …", src/deploy-steps.ts) per
# older Worker that the run took routes from: what the deploy took over, and that the Worker can be
# deleted when no route of the domain is left on it. The run deletes no Worker: the person may
# want what it kept.
old_workers_left() {
  [ -s /work/old-workers ] || return 0
  local out code body name took left
  out=$(cf_get "/zones/$ITERATE_ZONE_ID/workers/routes"); code=${out##*$'\n'}; body=${out%$'\n'*}
  for name in $(cut -f1 /work/old-workers | sort -u); do
    took=$(awk -F'\t' -v n="$name" '$1 == n { print $2 }' /work/old-workers | paste -sd'|' - | sed 's/|/ and /g')
    left=
    if [ "$code" = 200 ] && ! jq -e --arg s "$name" 'any(.result[]; .script == $s)' >/dev/null <<<"$body"; then
      left=" That Worker serves nothing on $ITERATE_ZONE now: if you do not need what it kept, you can delete it in Cloudflare (Workers & Pages)."
    fi
    echo "Note: An earlier iterate served $ITERATE_ZONE from its Worker “$name”. This deploy took over $took.$left"
  done
}

# The phases of a chat installation, each its own process with ITERATE_PHASE: see
# ../worker/installation.js for when each runs and why.

# prep: the account is reachable, has its workers.dev name, holds no stack from before the rename,
# and has the stack's state store (made where Cloudflare allows it on the account's plan; else the
# deploy makes it); the mind's Worker is built.
prep() {
  echo "stack $(cat /stack/COMMIT)"
  echo "== step prep"
  if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ -z "$ITERATE_NAME" ]; then
    echo "The phase did not get its inputs: the token, the account and the name."
    return 1
  fi
  local out code body store="iterate-$ITERATE_NAME-state"
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET /accounts/$CLOUDFLARE_ACCOUNT_ID."
    return 1
  fi
  echo "account: $(jq -r '.result.name' <<<"$body")"
  workers_dev_ready || return 1
  not_older_stack || return 1
  cd /stack/core/alchemy || return 1
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$store/script-settings"); code=${out##*$'\n'}
  if [ "$code" = 404 ]; then
    make_store "$store" || echo "Note: the state store $store was not made now. The deploy makes it."
  else
    echo "The state store $store is there."
  fi
  if ! timeout 600 pnpm --filter core-mind-worker build >/work/prep-build.log 2>&1; then
    tail -n 20 /work/prep-build.log
    echo "The build of the mind's Worker failed."
    return 1
  fi
  echo "Built the mind's Worker."
}

# early: the stack before its domain, from the config of installation.js `inputOf`
# (/work/mind.config.json; its fields: worker/stack-config.js `configOf`). The deploy at the domain
# gives the same stack the rest (`stack_updatable`). This phase deploys only under a name whose
# store keeps no config: a stack that exists is left to the deploy, which checks it as an update.
early() {
  echo "stack $(cat /stack/COMMIT)"
  echo "== step early"
  if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ -z "$ITERATE_NAME" ]; then
    echo "The phase did not get its inputs: the token, the account and the name."
    return 1
  fi
  [ -f /work/mind.config.json ] || { echo "The phase did not get its config."; return 1; }
  rm -f "$STORED" /work/config-published /work/telemetry-on /work/cloudflare-token-on /work/cloudflare-token-refused
  local out code stored store="iterate-$ITERATE_NAME-state"
  workers_dev_ready || return 1
  not_older_stack || return 1
  cd /stack/core/alchemy || return 1
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$store/script-settings"); code=${out##*$'\n'}
  case $code in
    404) make_store "$store" || return 1 ;;
    200)
      if ! stored=$(stored_config "$store"); then
        echo "Stopped: the run could not read the config that iterate keeps under the name $ITERATE_NAME. Nothing was changed."
        return 1
      fi
      if [ -n "$stored" ]; then
        echo "Stopped: iterate keeps a config under the name $ITERATE_NAME already$(jq -r '.domain // empty | ", for \(.)"' <<<"$stored" 2>/dev/null). The deploy at the domain checks it as an update. Nothing was changed."
        return 1
      fi ;;
    *)
      echo "Cloudflare answered $code to GET the Worker $store."
      return 1 ;;
  esac
  not_unknown_stack || return 1
  echo "$(jq -r 'if .cloudflarePlan == "free" then "The stack before its domain, on what a Free account takes" else "The stack before its domain, with Workers Paid and R2" end' /work/mind.config.json), and with no sandboxes yet (mind.containers: false)."
  export ITERATE_MIND_CONFIG=/work/mind.config.json
  deploy_stack; code=$?
  if [ "$code" != 0 ]; then
    echo "The deploy before the domain failed (exit $code)."
    return 1
  fi
  echo "The stack iterate-$ITERATE_NAME is deployed before its domain: the deploy at the domain gives it the rest."
}

main() {
  echo "stack $(cat /stack/COMMIT)"
  rm -f "$STORED" /work/config-published /work/mind.config.next.json /work/telemetry-on /work/had-stand-in
  rm -f /work/cloudflare-token-on /work/cloudflare-token-refused

  echo "== step check"
  if [ -z "$CLOUDFLARE_API_TOKEN" ] || [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ -z "$ITERATE_ZONE" ] || [ -z "$ITERATE_ZONE_ID" ] || [ -z "$ITERATE_NAME" ]; then
    echo "The run did not get its inputs: the token, the account, the zone and the name."
    return 1
  fi
  local out code body
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET /accounts/$CLOUDFLARE_ACCOUNT_ID."
    return 1
  fi
  echo "account: $(jq -r '.result.name' <<<"$body")"
  out=$(cf_get "/zones/$ITERATE_ZONE_ID"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" != 200 ]; then
    echo "Cloudflare answered $code to GET /zones/$ITERATE_ZONE_ID."
    return 1
  fi
  local zone
  zone=$(jq -r '.result.name' <<<"$body")
  echo "zone: $zone"
  if [ "$zone" != "$ITERATE_ZONE" ]; then
    echo "The zone $ITERATE_ZONE_ID is $zone, not $ITERATE_ZONE."
    return 1
  fi
  # "Erase and replace": the person agreed to lose everything on the domain and the earlier
  # iterate. After it the store is gone, so what follows is a first deploy.
  if [ -n "$ITERATE_ERASE" ]; then
    echo "== step erase"
    node /stack/erase.mjs || return 1
  else
    not_older_stack || return 1
    not_unknown_stack || return 1
    stack_updatable || return 1
    versions_now before
    had_stand_in before
  fi
  records_free || return 1
  routes_free || return 1
  # a chat installation's deploy: the account may still have no workers.dev name
  if [ "$ITERATE_WORKERS_DEV" = 1 ]; then workers_dev_ready || return 1; fi

  echo "== step deploy"
  cd /stack/core/alchemy || return 1
  if [ -f /work/mind.config.json ]; then
    export ITERATE_MIND_CONFIG=/work/mind.config.json
  else
    echo "No config was given: the stack deploys from the config it keeps beside its state."
  fi
  # 404 says the store is not there yet; Alchemy asks the same question the same way
  local store="iterate-$ITERATE_NAME-state"
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$store/script-settings"); code=${out##*$'\n'}
  if [ "$code" = 404 ]; then
    make_store "$store" || return 1
  else
    keep_stored_config "$store" || return 1
  fi
  old_routes_removed || return 1
  # a first deploy whose config asks for telemetry: this run turned it on too
  [ ! -s "$STORED" ] && [ "$(jq -r '.telemetry // false' /work/mind.config.json 2>/dev/null)" = true ] && : > /work/telemetry-on
  # and one whose config asks for the mind's Cloudflare connection: this run set it too
  [ ! -s "$STORED" ] && [ "$(jq -r '.cloudflareToken // false' /work/mind.config.json 2>/dev/null)" = true ] && : > /work/cloudflare-token-on
  # an access that may not change API tokens leaves the mind's token as it is
  if [ "$ITERATE_CLOUDFLARE_TOKEN" = 1 ]; then unset ITERATE_KEEP_CLOUDFLARE_TOKEN; else export ITERATE_KEEP_CLOUDFLARE_TOKEN=1; fi
  deploy_stack; code=$?
  if [ "$code" != 0 ]; then
    echo "The deploy failed (exit $code)."
    # a failed deploy can leave most of the stack made: say what is there and what is missing
    bash /stack/check-result.sh --report
    return 1
  fi
  versions_now after
  had_stand_in after
  # for the Cloud's record of this run (worker/deploy-run.js): whether the config of this deploy
  # asks for the mind's Cloudflare connection, and so whether the stack has its token
  if [ "$(jq -r '.cloudflareToken // false' "${ITERATE_MIND_CONFIG:-$STORED}" 2>/dev/null)" = true ]; then
    echo "cloudflare-connection on"
    [ "$ITERATE_CLOUDFLARE_TOKEN" = 1 ] && echo "cloudflare-token made by this release"
  else
    echo "cloudflare-connection off"
  fi

  echo "== step answer"
  local url="https://iterate.$ITERATE_ZONE/.well-known/oauth-authorization-server"
  # every five seconds for ten minutes: a new zone's certificate can take minutes
  # The mind is asked too, with no token, at an address under /api/ that the mind alone answers
  # (the boundary answers /api itself): the mind's own 401 says that the boundary reaches it. A
  # newborn stack answered 500 and 522 there for its first seconds. A provided mind runs on the
  # person's own machine, which can be off: the run says what it answered and does not wait.
  local answered= api head mind="https://iterate.$ITERATE_ZONE/api/_skeleton"
  for i in $(seq 1 120); do
    out=$(curl -s -m 10 -w '\n%{http_code}' "$url"); code=${out##*$'\n'}; body=${out%$'\n'*}
    if [ "$code" = 200 ] && jq -e . >/dev/null 2>&1 <<<"$body"; then
      head=$(curl -s -o /dev/null -m 10 -D - "$mind" | tr -d '\r')
      api=$(awk 'NR == 1 { print $2 }' <<<"$head")
      if [ "$api" = 401 ] && grep -qi '^www-authenticate: *Bearer realm="iterate"' <<<"$head"; then
        echo "iterate.$ITERATE_ZONE answers: its issuer is $(jq -r '.issuer' <<<"$body")"
        echo "The mind answers at $mind."
        answered=1
        break
      fi
      if [ "$ITERATE_MIND_PROVIDED" = 1 ]; then
        echo "iterate.$ITERATE_ZONE answers: its issuer is $(jq -r '.issuer' <<<"$body")"
        echo "Note: The mind of this deployment runs on a machine of yours, and it did not answer just now ($mind answered ${api:-nothing}). Start it there."
        answered=1
        break
      fi
      [ $((i % 12)) = 1 ] && echo "The mind's API answered ${api:-nothing} so far, waiting"
    else
      [ $((i % 12)) = 1 ] && echo "iterate.$ITERATE_ZONE answered ${code:-nothing} so far, waiting"
    fi
    sleep 5
  done
  if [ -z "$answered" ]; then
    echo "iterate.$ITERATE_ZONE did not answer within ten minutes (sign-in: ${code:-nothing}, the mind: ${api:-not asked})."
    return 1
  fi

  # The deploy's exit code is not the last word: check each part that a person will rely on.
  echo "== step verify"
  if ! bash /stack/check-result.sh; then
    echo "The deploy ended, but a part is missing. iterate is not ready on $ITERATE_ZONE."
    return 1
  fi
  old_workers_left
}

case ${ITERATE_PHASE:-} in
  prep) prep 2>&1 | redact ;;
  early) early 2>&1 | redact ;;
  *) main 2>&1 | redact ;;
esac
echo "__EXIT__:${PIPESTATUS[0]}"