iterate.com / cloud

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

cloud / internal-packages / installer / container / check-result.shmain at aacbc74

#!/bin/bash
# check-result.sh — WHAT A DEPLOY LEFT BEHIND, looked at from outside: the parts a person relies on.
# run.sh calls it. A deploy can end with a part missing (its tool reports one resource's failure and
# keeps the others), and a stack with a part missing still answers: so the run looks, and says
# which part is missing in plain words, before anybody is told that iterate is live.
#
#   check-result.sh            after a deploy that ended well: exit 1 when a part is missing
#   check-result.sh --report   after a deploy that failed: says what is there, exit 0 always
#
# One line per part: "Works: …", "Missing: …" (the person's page shows these), or "Not checked: …"
# when Cloudflare gave no answer to go by, which fails nothing.
#
# Then the mind itself (part 7): a deployment whose mind was not made has no site and no app, so
# that fails the run. Then the pages that the person's page links to (part 8). A page that does
# not answer fails nothing: the deployment works without it. It is said as "Not there: …", and the run records
# "page <id> works" or "page <id> missing" for each: the person's page shows a button only for a
# page that the run saw answer (src/deploy-steps.ts `pagesOf`), so no button leads to a dead page.
#
# The parts: iterate answers as an issuer; mail to the domain comes to iterate (Email Routing is on
# and its catch-all goes to a Worker); the apex and wildcard DNS records; the MX records; Email
# Sending with its DNS records; the state store (a plan finds nothing to create; said, fails nothing); the page for the
# first passkey, when this run made the owner's ticket. The ticket's hash cannot be seen from outside.
#
# Mail is a part of a first deploy, whose config (/work/mind.config.json) asks for it. An update
# deploys from the config the stack keeps, where its owner may have turned mail off: there, mail
# that is off is said and fails nothing.
#
# Inputs, from the run's environment: CLOUDFLARE_API_TOKEN, ITERATE_ZONE, ITERATE_ZONE_ID, ITERATE_NAME,
# CLOUDFLARE_ACCOUNT_ID (for the telemetry part alone), and
# ITERATE_FIRST_OWNER_TICKET when the run made a ticket. The token is never an argument of a
# command: curl reads its header from standard input.
API=${CLOUDFLARE_API:-https://api.cloudflare.com/client/v4}
# the config that the deploy used: run.sh names it, and names none for a deploy from the config
# that the stack keeps
CONFIG=${ITERATE_MIND_CONFIG:-}
report=0
[ "$1" = "--report" ] && report=1
missing=0

# 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"
}
# GET an address `tries` times, five seconds apart, until it answers 200: the last status.
status_of() {
  local url=$1 tries=$2 code=000 i
  for i in $(seq 1 "$tries"); do
    code=$(curl -s -o /dev/null -m 10 -w '%{http_code}' "$url")
    [ "$code" = 200 ] && break
    [ "$i" != "$tries" ] && sleep 5
  done
  echo "$code"
}
works() { echo "Works: $1"; }
lacks() { echo "Missing: $1"; missing=1; }

site="https://iterate.$ITERATE_ZONE"

# 1. iterate answers. After a deploy that ended well, run.sh waited for this already.
code=$(status_of "$site/.well-known/oauth-authorization-server" "$([ "$report" = 1 ] && echo 6 || echo 3)")
if [ "$code" = 200 ]; then
  works "iterate answers at $site."
else
  lacks "iterate does not answer at $site (it answered $code)."
fi

# 2. Mail to the domain comes to iterate. One word for what Cloudflare says now: "works <worker>",
# "off", "elsewhere" (the catch-all does not go to a Worker), or "unknown <status> <path>".
mail_now() {
  local out code body worker path="/zones/$ITERATE_ZONE_ID/email/routing"
  out=$(cf_get "$path"); code=${out##*$'\n'}; body=${out%$'\n'*}
  [ "$code" != 200 ] && { echo "unknown $code $path"; return; }
  [ "$(jq -r '.result.enabled' <<<"$body" 2>/dev/null)" != true ] && { echo off; return; }
  path="$path/rules/catch_all"
  out=$(cf_get "$path"); code=${out##*$'\n'}; body=${out%$'\n'*}
  [ "$code" != 200 ] && { echo "unknown $code $path"; return; }
  worker=$(jq -r 'select(.result.enabled == true) | .result.actions[]? | select(.type == "worker") | .value[0]' <<<"$body" 2>/dev/null | head -1)
  [ -n "$worker" ] && echo "works $worker" || echo elsewhere
}
wanted=unknown
[ -n "$CONFIG" ] && [ -f "$CONFIG" ] && wanted=$(jq -r 'if .mail then "yes" else "no" end' "$CONFIG" 2>/dev/null || echo unknown)
if [ "$wanted" != no ]; then
  # a deploy that ended well turned mail on seconds ago: give Cloudflare half a minute to say so
  tries=1
  [ "$report" = 0 ] && [ "$wanted" = yes ] && tries=6
  for i in $(seq 1 "$tries"); do
    mail=$(mail_now)
    case $mail in works*) break ;; esac
    [ "$i" != "$tries" ] && sleep 5
  done
  case $mail in
    works*) works "mail to $ITERATE_ZONE comes to iterate (Email Routing is on, and its catch-all goes to the Worker ${mail#works })." ;;
    unknown*) set -- $mail; echo "Not checked: mail to $ITERATE_ZONE (Cloudflare answered $2 to GET $3)." ;;
    off)
      if [ "$wanted" = yes ]; then
        lacks "mail to $ITERATE_ZONE. Email Routing is off for the domain, so iterate receives no mail."
      else
        echo "Email Routing is off for $ITERATE_ZONE: iterate receives no mail there."
      fi ;;
    *)
      if [ "$wanted" = yes ]; then
        lacks "mail to $ITERATE_ZONE. Email Routing is on, but its catch-all rule does not go to iterate."
      else
        echo "Email Routing's catch-all rule for $ITERATE_ZONE does not go to iterate: iterate receives no mail there."
      fi ;;
  esac
fi

# 3. The two DNS records that bring the domain and every name under it to iterate.
for name in "$ITERATE_ZONE" "*.$ITERATE_ZONE"; do
  out=$(cf_get "/zones/$ITERATE_ZONE_ID/dns_records?type=AAAA&name=$(jq -rn --arg n "$name" '$n|@uri')"); code=${out##*$'\n'}; body=${out%$'\n'*}
  if [ "$code" != 200 ]; then
    echo "Not checked: the DNS record for $name (Cloudflare answered $code)."
  elif jq -e '.result[] | select(.content == "100::" and .proxied == true)' >/dev/null 2>&1 <<<"$body"; then
    works "the DNS record for $name leads to iterate."
  else
    lacks "the DNS record for $name (AAAA 100::, proxied). Without it, $name does not reach iterate."
  fi
done

# 4. Mail: the MX records at the apex, and the Email Sending domain with its records.
if [ "$wanted" = yes ]; then
  # Email Routing adds its MX records when it is turned on: seconds ago, after a first deploy
  for i in $(seq 1 "$tries"); do
    out=$(cf_get "/zones/$ITERATE_ZONE_ID/dns_records?type=MX&name=$ITERATE_ZONE"); code=${out##*$'\n'}; body=${out%$'\n'*}
    [ "$code" != 200 ] || [ "$(jq '[.result[]] | length' <<<"$body" 2>/dev/null)" != 0 ] && break
    [ "$i" != "$tries" ] && sleep 5
  done
  other=$(jq -r '[.result[] | select(.content | test("^route[0-9]+\\.mx\\.cloudflare\\.net\\.?$") | not) | .content] | join(", ")' <<<"$body" 2>/dev/null)
  if [ "$code" != 200 ]; then
    echo "Not checked: the MX records of $ITERATE_ZONE (Cloudflare answered $code)."
  elif [ -n "$other" ]; then
    lacks "mail to $ITERATE_ZONE goes elsewhere too: MX records point at $other. Delete them in Cloudflare's DNS page, then deploy again."
  elif [ "$(jq '[.result[]] | length' <<<"$body")" -gt 0 ]; then
    works "the MX records of $ITERATE_ZONE point at Cloudflare's Email Routing."
  else
    lacks "the MX records of $ITERATE_ZONE. Email Routing adds them when it is on; deploy again."
  fi
  out=$(cf_get "/zones/$ITERATE_ZONE_ID/email/sending/subdomains"); code=${out##*$'\n'}; body=${out%$'\n'*}
  sending=$(jq -r --arg z "$ITERATE_ZONE" '.result[]? | select(.name == $z and .enabled == true) | .id' <<<"$body" 2>/dev/null | head -1)
  if [ "$code" != 200 ]; then
    echo "Not checked: mail from $ITERATE_ZONE (Cloudflare answered $code to GET /zones/$ITERATE_ZONE_ID/email/sending/subdomains)."
  elif [ -z "$sending" ]; then
    lacks "mail from $ITERATE_ZONE. Email Sending is not set up for the domain, so iterate cannot send sign-in codes."
  else
    want=$(cf_get "/zones/$ITERATE_ZONE_ID/email/sending/subdomains/$sending/dns"); want=${want%$'\n'*}
    have=$(cf_get "/zones/$ITERATE_ZONE_ID/dns_records?per_page=500"); have=${have%$'\n'*}
    absent=$(jq -rn --argjson want "$want" --argjson have "$have" '[$want.result[]? | . as $w | select([$have.result[]? | select(.name == $w.name and .type == $w.type)] | length == 0) | "\(.type) \(.name)"] | unique | join(", ")' 2>/dev/null)
    if [ -n "$absent" ]; then
      lacks "mail from $ITERATE_ZONE: Email Sending waits for these DNS records: $absent."
    else
      works "mail from $ITERATE_ZONE: Email Sending is on, with its DNS records."
    fi
  fi
fi

# 5. The state store holds every resource: a plan of the same stack finds nothing to create.
if [ -d /stack/core/alchemy ] && [ "$report" = 0 ]; then
  # This part fails nothing yet: it was never seen after a real first deploy, and a wrong "Missing"
  # would call a good deploy failed. It says what the plan names, as "Not checked".
  plan=$(cd /stack/core/alchemy && timeout 120 node node_modules/alchemy/bin/cli.js plan --stage "$ITERATE_NAME" 2>&1); code=$?
  # a plan line is `[<resource>] <action>`, after the logger's clock
  todo=$(grep -oE '\[[A-Za-z0-9_./-]+\] (create|replace)\b' <<<"$plan" | sed -E 's/^\[([^]]+)\].*/\1/' | sort -u | paste -sd, - | sed 's/,/, /g')
  if [ "$code" != 0 ]; then
    echo "Not checked: the state store (a plan of the stack ended with exit $code)."
  elif [ -n "$todo" ]; then
    echo "Not checked: the state store (a plan names parts that a new deploy would make: $todo)."
  else
    works "the state store holds every part of the stack."
  fi
fi

# 5b. The stack's own telemetry: its Worker is there. A deploy from the config that the stack keeps
# has no config here to read, so Cloudflare is asked either way; a Worker that is not there is said
# only when this deploy's config asked for telemetry. This part fails nothing: a deployment works
# without its telemetry, and the mind then says that it has none.
if [ -n "$CLOUDFLARE_ACCOUNT_ID" ]; then
  out=$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/iterate-$ITERATE_NAME-telemetry/script-settings"); code=${out##*$'\n'}
  if [ "$code" = 200 ]; then
    works "your stack's telemetry: the Worker iterate-$ITERATE_NAME-telemetry is there, with two API tokens of its own that stay in your account."
  elif [ -n "$CONFIG" ] && [ -f "$CONFIG" ] && [ "$(jq -r '.telemetry // false' "$CONFIG" 2>/dev/null)" = true ]; then
    echo "Not there: your stack's telemetry (Cloudflare answered $code to GET the Worker iterate-$ITERATE_NAME-telemetry)."
  fi
fi

# 6. The page that takes the owner's ticket, when this run made one.
if [ -n "$ITERATE_FIRST_OWNER_TICKET" ]; then
  code=$(status_of "$site/keys/first" 3)
  if [ "$code" = 200 ]; then
    works "the page for your first passkey answers at $site/keys/first."
  else
    lacks "the page for your first passkey ($site/keys/first answered $code)."
  fi
fi

# 7. The mind itself, after a deploy whose parts are all there. The first request to the domain
# bears it: it then makes its config repo and publishes it, which takes seconds. Until that is done,
# every name of the domain but iterate.<domain> answers the platform's own page (core/itx
# src/serve-host.ts, "This mind has no site yet"), and no app of the mind answers. A mind that
# stays so was not made (on 11 November 2026 a deploy left one with no Artifacts namespace, so its
# config repo could not be made, and the run said that iterate was live). Asked every three
# seconds, for ninety at most. An answer that is not that page, or no answer, fails nothing here.
#
# A mind that runs on a machine of the person's (the config's `mind.provided`) is not a part of
# the deploy. While no machine is connected, the boundary answers 503 for the mind's names with a
# page of its own (core/boundary-worker src/provided-mind.ts, "This mind runs elsewhere and is not
# connected right now"). That is not a mind that answers, and it is not a deploy with a part
# missing: the run says "Not checked", and asks none of the mind's apps (part 8), which answer
# the same page. run.sh says what to do about it (its Note "Start it there").
away=0
if [ "$report" != 1 ] && [ "$missing" = 0 ]; then
  for i in $(seq 1 30); do
    body=$(curl -s -m 10 "https://$ITERATE_ZONE/")
    case $body in *"This mind has no site yet"*) ;; *) break ;; esac
    [ "$i" != 30 ] && sleep 3
  done
  case $body in
    *"This mind has no site yet"*)
      lacks "your mind's own site. iterate answers at $site, but the mind was not made: https://$ITERATE_ZONE/ still says that it has no site, so none of its apps answers. Press Try again. If it happens again, send us the deploy log." ;;
    *"This mind runs elsewhere and is not connected right now"*)
      away=1
      echo "Not checked: your mind and its apps. The mind runs on a machine of yours, and no machine is connected just now: https://$ITERATE_ZONE/ says so. They answer when the machine is connected." ;;
    *) works "your mind answers at https://$ITERATE_ZONE/." ;;
  esac
fi

# 8. The pages that the buttons and commands of the person's page lead to, asked as a browser that
# is signed out asks them, redirects not followed. After a deploy whose parts are all there only:
# a run that failed has no page to show buttons on.
# `answer_of <url>`: the status, a space, and where the answer sends the browser.
answer_of() { curl -s -o /dev/null -m 10 -H 'accept: text/html' -w '%{http_code} %{redirect_url}' "$1"; }
# `page <id> <works|missing> <words>`: one line for the person, one for their page.
page() {
  if [ "$2" = works ]; then echo "Works: $3"; else echo "Not there: $3"; fi
  echo "page $1 $2"
}
if [ "$report" != 1 ] && [ "$missing" = 0 ]; then
  # Pages of iterate.<domain> that ask for a sign-in first: a redirect to its sign-in page.
  for pair in "keys:the page for your passkeys" "members:the page where you add people" "self-test:the self-test page"; do
    id=${pair%%:*}; what=${pair#*:}
    answer=$(answer_of "$site/$id"); code=${answer%% *}; to=${answer#* }
    case "$code $to" in
      30[23]\ "$site/sign-in"*) page "$id" works "$what answers at $site/$id." ;;
      *) page "$id" missing "$what ($site/$id answered $code)." ;;
    esac
  done
  # The address that Claude Code connects to: a refusal that says where to sign in.
  head=$(curl -s -o /dev/null -m 10 -D - "$site/mcp" | tr -d '\r')
  code=$(awk 'NR == 1 { print $2 }' <<<"$head")
  if [ "$code" = 401 ] && grep -qi '^www-authenticate: *Bearer' <<<"$head"; then
    page mcp works "the address for Claude Code answers at $site/mcp."
  else
    page mcp missing "the address for Claude Code ($site/mcp answered ${code:-nothing})."
  fi
  # The apps of the config repo, each on its own name: a redirect to iterate.<domain>'s sign-in.
  # The first request to the domain wakes it. A stack that an update just reached then brings its
  # config repo up to the template it bundles and publishes that, which takes seconds: the Dash,
  # where every agent is and the onboarding chat, is asked every three seconds, for ninety at most.
  # An app that answers so can still be a blank page: it has no build, and its page loads
  # iterate's components from addresses that its index.html pins (check-imports.mjs). So each of
  # those addresses is asked too, as the default config in this image names them: a signed-out
  # run cannot read the app's files through the mind.
  # A mind on the person's machine that is not connected (part 7) serves no app just now: the
  # run records each as missing, so the person's page shows no button for it, and says no more.
  if [ "$away" = 1 ]; then
    echo "page dash missing"
  else
    curl -s -o /dev/null -m 10 "https://$ITERATE_ZONE/"
    imports=
    [ -f /stack/check-imports.mjs ] && imports=$(timeout 120 node /stack/check-imports.mjs /stack/core/configs/default/apps dash 2>/dev/null)
    # the run's log keeps what the check saw: `imports <app> works <count>`
    [ -n "$imports" ] && echo "$imports"
    app_answers() {
      answer=$(answer_of "$1"); code=${answer%% *}; to=${answer#* }
      case "$code $to" in 302\ "$site/oauth2/auth"*) return 0 ;; esac
      return 1
    }
    # `app_page <id> <words> <address>`
    app_page() {
      local absent
      absent=$(sed -n "s/^imports $1 missing //p" <<<"$imports")
      if ! app_answers "$3"; then
        page "$1" missing "$2 ($3 answered $code)."
      elif [ -n "$absent" ]; then
        page "$1" missing "$2 answers at $3, but its page loads a module that does not answer: $absent."
      else
        page "$1" works "$2 answers at $3"
      fi
    }
    app="https://dash.$ITERATE_ZONE/"
    # On an update the older Dash answers until the newer template is published. The newer one is
    # live when its manifest, which answers anyone, is the template's own.
    manifest=/stack/core/configs/default/apps/dash/public/manifest.webmanifest
    newer_dash() {
      [ ! -f "$manifest" ] || [ "$(curl -s -m 10 "${app}manifest.webmanifest")" = "$(cat "$manifest")" ]
    }
    for i in $(seq 1 30); do
      app_answers "$app" && newer_dash && break
      [ "$i" != 30 ] && sleep 3
    done
    app_page dash "the Dash" "$app"
  fi
fi

[ "$report" = 1 ] && exit 0
exit "$missing"