iterate.com / cloud

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

cloud / internal-packages / installer / test / stack-config.mjsmain at aacbc74

// stack-config.mjs — the config that the wizard writes for a first deploy (worker/stack-config.js),
// and what a run does with the sandbox image that a stored config names, and with a stored config
// that has no domain yet (container/run.sh).
// Run: node test/stack-config.mjs
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { MindConfig } from "../../../core/alchemy/src/config.ts";
import { iterateDevImage } from "../../../core/alchemy/src/sandbox-image.ts";
import { configOf } from "../worker/stack-config.js";

const asked = {
  name: "example-com",
  accountId: "0123456789abcdef0123456789abcdef",
  zone: "example.com",
  ownerEmails: ["owner@example.com"],
  trustedClients: [],
  cloudOrigin: "https://cloud.iterate.com",
  mind: { sandboxImage: "published" },
};

/** A config of the wizard as the stack reads it. The wizard names iterate's image by the older
 *  word, which the stack reads as the image at its pin and does not keep. */
const asRead = (config) => ({
  ...config,
  mind: { images: { "iterate-dev-image": iterateDevImage.image } },
});

test("the wizard's config is one that the stack takes, and names the published sandbox image", () => {
  const config = configOf(asked);
  // iterate's image has the coding CLIs and their adapters, which an agent session needs
  assert.deepEqual(MindConfig.parse(config), asRead(config));
  assert.deepEqual(config.auth.login.allow, [{ email: "owner@example.com" }]);
  // no telemetry unless the consent was the one for it
  assert.equal("telemetry" in config, false);
});

test("with the consent for it, the wizard's config turns the stack's telemetry on", () => {
  const config = configOf({ ...asked, telemetry: true });
  assert.equal(config.telemetry, true);
  assert.deepEqual(MindConfig.parse(config), asRead(config));
});

test("an update turns telemetry on in a stored config that has none, and the stack takes that config", () => {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  // the run's own jq program for it
  const program = /jq -c '(\.telemetry = true)' "\$from"/.exec(run)?.[1];
  assert.equal(program, ".telemetry = true");
  const stored = configOf(asked);
  const ran = spawnSync("jq", ["-c", program], { input: JSON.stringify(stored), encoding: "utf8" });
  const next = JSON.parse(ran.stdout);
  assert.equal(next.telemetry, true);
  assert.deepEqual(MindConfig.parse(next), asRead(next));
  // a stored config that has it is left as it is, and the run sets it only with the scopes for it
  assert.match(
    run,
    /if \[ "\$\(jq -r '\.telemetry \/\/ false' "\$STORED"\)" != true \]; then\n    if \[ "\$ITERATE_TELEMETRY" = 1 \]; then/,
  );
  assert.match(
    run,
    /Note: telemetry stays off for \$ITERATE_ZONE\. To turn it on, press \\"Turn on telemetry\\"/,
  );
});

// `deploy_stack` and its two `without_` functions of run.sh, run in bash on a folder of their own,
// with a `deploy` that fails as long as the config of the deploy asks for telemetry, or for the
// mind's Cloudflare token when Cloudflare refuses that. `config` is the one this run was given or
// wrote; with none, the deploy uses `stored`, the config that the stack keeps. `mayMakeTokens`:
// the person's consent was the one for a mind's Cloudflare connection. `failsFirst`: the first
// deploy fails in no token, whatever its config asks; `telemetryWorks`: a config that asks for
// telemetry does not fail.
function deployStack({
  telemetryOn,
  tokenRefused = true,
  failsAnyway = false,
  failsFirst = false,
  telemetryWorks = false,
  config = { name: "a", telemetry: true },
  stored,
  cloudflareOn = false,
  cloudflareRefused = false,
  mayMakeTokens = false,
}) {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const fn = (name) => new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?^\\}`, "m").exec(run)[0];
  const work = mkdtempSync(join(tmpdir(), "run-telemetry-"));
  if (config) writeFileSync(join(work, "mind.config.json"), JSON.stringify(config));
  if (stored) writeFileSync(join(work, "stored-config.json"), JSON.stringify(stored));
  if (telemetryOn) writeFileSync(join(work, "telemetry-on"), "");
  if (cloudflareOn) writeFileSync(join(work, "cloudflare-token-on"), "");
  const asks = (field) => `[ "$(jq -r '.${field} // false' "$used")" = true ]`;
  const script = `
ITERATE_ZONE=a.com
ITERATE_NAME=a
ITERATE_RETRY_SECONDS=0
STORED=/work/stored-config.json
${config ? "ITERATE_MIND_CONFIG=/work/mind.config.json" : ""}
${mayMakeTokens ? "ITERATE_CLOUDFLARE_TOKEN=1" : ""}
deploys=0
deploy() {
  local used=\${ITERATE_MIND_CONFIG:-$STORED} failed=0
  deploys=$((deploys + 1))
  rm -f /work/telemetry-token-refused /work/cloudflare-token-refused
  ${failsFirst ? '[ "$deploys" = 1 ] && return 1' : ":"}
  if ${failsAnyway ? "true" : telemetryWorks ? "false" : asks("telemetry")}; then
    ${tokenRefused ? ": > /work/telemetry-token-refused" : ":"}
    failed=1
  fi
  if ${cloudflareRefused ? asks("cloudflareToken") : "false"}; then
    : > /work/cloudflare-token-refused
    failed=1
  fi
  return $failed
}
${fn("without_telemetry")}
${fn("without_cloudflare_token")}
${fn("deploy_stack")}
deploy_stack; code=$?
used=\${ITERATE_MIND_CONFIG:-$STORED}
echo "exit=$code deploys=$deploys telemetry=$(jq -r '.telemetry // false' "$used") cloudflareToken=$(jq -r '.cloudflareToken // false' "$used")"
`.replaceAll("/work/", `${work}/`);
  const ran = spawnSync("bash", ["-c", script], { encoding: "utf8" });
  assert.equal(ran.stderr, "");
  return ran.stdout;
}

test("an update that turned telemetry on and failed deploys once more without it, and says so in one line", () => {
  const out = deployStack({ telemetryOn: true });
  assert.match(out, /exit=0 deploys=2 telemetry=false/);
  assert.match(out, /One more try, with telemetry off\./);
  assert.match(
    out,
    /^Note: telemetry not turned on: Cloudflare refused to create its token\. iterate on a\.com is deployed and works without it\. To turn it on later, /m,
  );
  // another part of telemetry failed: one more try as it was, then without it; the line says that,
  // and the deploy still ends well
  const other = deployStack({ telemetryOn: true, tokenRefused: false });
  assert.match(other, /One more try with the same config, in fifteen seconds\./);
  assert.match(
    other,
    /Note: telemetry not turned on: its part of the deploy failed[^\n]*\n.*exit=0 deploys=3/s,
  );
});

test("a deploy that turned something on and failed in no token is tried once more as it was, and keeps it", () => {
  // this run turns the mind's Cloudflare connection on, and the first try fails: the second try
  // keeps the connection
  const kept = deployStack({
    config: { name: "a", cloudflareToken: true },
    cloudflareOn: true,
    mayMakeTokens: true,
    failsFirst: true,
  });
  assert.match(kept, /exit=0 deploys=2 telemetry=false cloudflareToken=true/);
  assert.match(
    kept,
    /^The deploy failed \(exit 1\), and not in a token that this run turned on\. One more try with the same config, in fifteen seconds\.$/m,
  );
  assert.doesNotMatch(kept, /without it|no Cloudflare connection/);
  // telemetry, turned on by this run: the same
  const telemetry = deployStack({
    config: { name: "a", telemetry: true },
    telemetryOn: true,
    telemetryWorks: true,
    failsFirst: true,
  });
  assert.match(telemetry, /exit=0 deploys=2 telemetry=true/);
  // a run that turned nothing on gets no such try
  const plain = deployStack({ config: { name: "a" }, failsFirst: true });
  assert.match(plain, /exit=1 deploys=1/);
  assert.doesNotMatch(plain, /same config/);
});

test("a deploy that fails for another reason fails, and one that this run did not change is not tried twice", () => {
  // the second try, with telemetry off, fails too: the failure is the deploy's own
  const still = deployStack({ telemetryOn: true, failsAnyway: true });
  assert.match(still, /exit=1 deploys=2/);
  assert.doesNotMatch(still, /Note: telemetry not turned on/);
  // a stack whose own config asks for telemetry: this run did not turn it on, so it does not turn it off
  assert.match(deployStack({ telemetryOn: false }), /exit=1 deploys=1 telemetry=true/);
});

test("with the consent for it, the wizard's config asks for the mind's Cloudflare connection", () => {
  assert.equal("cloudflareToken" in configOf(asked), false);
  const config = configOf({ ...asked, cloudflareToken: true });
  assert.equal(config.cloudflareToken, true);
  assert.deepEqual(MindConfig.parse(config), asRead(config));
});

// `stack_updatable` of run.sh on a stack that exists and keeps `stored`: what it says, and the
// config of this deploy when it wrote one.
function updatable(stored, variables = "") {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const fn = new RegExp("^stack_updatable\\(\\) \\{\\n[\\s\\S]*?^\\}", "m").exec(run)[0];
  const work = mkdtempSync(join(tmpdir(), "run-updatable-"));
  writeFileSync(join(work, "kept.json"), JSON.stringify(stored));
  const script = `
ITERATE_ZONE=example.com
ITERATE_NAME=example-com
CLOUDFLARE_ACCOUNT_ID=${asked.accountId}
STORED=/work/stored-config.json
${variables}
cf_get() { printf '{}\\n200'; }
stored_config() { cat /work/kept.json; }
${fn}
stack_updatable; echo "exit=$?"
[ -f /work/mind.config.json ] && echo "config=$(cat /work/mind.config.json)"
[ -f /work/cloudflare-token-on ] && echo "mark=on"
`
    .replaceAll("/stack/core/alchemy", work)
    .replaceAll("/work/", `${work}/`);
  const ran = spawnSync("bash", ["-c", script], { encoding: "utf8" });
  assert.equal(ran.stderr, "");
  return ran.stdout;
}

test("an update with the consent for it sets the mind's Cloudflare connection in the config that the stack keeps", () => {
  const stored = JSON.parse(JSON.stringify(configOf(asked)));
  const out = updatable(stored, "ITERATE_CLOUDFLARE_TOKEN=1");
  assert.match(out, /^exit=0$/m);
  assert.match(out, /^mark=on$/m);
  assert.match(
    out,
    /^Note: This update gives the mind of example\.com 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-example-com-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, /m,
  );
  const next = JSON.parse(/^config=(.*)$/m.exec(out)[1]);
  assert.deepEqual(next, { ...stored, cloudflareToken: true });
  assert.deepEqual(MindConfig.parse(next), asRead(next));
  // with the consent for telemetry too, the config of the deploy has both
  const both = updatable(stored, "ITERATE_CLOUDFLARE_TOKEN=1\nITERATE_TELEMETRY=1");
  assert.deepEqual(JSON.parse(/^config=(.*)$/m.exec(both)[1]), {
    ...stored,
    telemetry: true,
    cloudflareToken: true,
  });
});

test("an update leaves the mind's Cloudflare connection as it is without the consent, on a stack that has it, and for a mind outside the stack", () => {
  const stored = configOf(asked);
  // no consent for it: no config is written, and no line names it
  const plain = updatable(stored);
  assert.match(plain, /^exit=0$/m);
  assert.doesNotMatch(plain, /config=|mark=on|Cloudflare connection/);
  // a stack that has it keeps it, with the consent or without
  for (const variables of ["", "ITERATE_CLOUDFLARE_TOKEN=1"]) {
    const has = updatable({ ...stored, cloudflareToken: true }, variables);
    assert.match(has, /^exit=0$/m);
    assert.doesNotMatch(has, /config=|mark=on|Cloudflare connection/);
  }
  // a mind that runs outside the stack takes none (core/alchemy/src/config.ts refuses the field)
  const { sandboxImage: _, ...mind } = stored.mind;
  const outside = updatable(
    { ...stored, mind: { ...mind, provided: true } },
    "ITERATE_CLOUDFLARE_TOKEN=1",
  );
  assert.match(outside, /^exit=0$/m);
  assert.match(outside, /^Note: no Cloudflare connection for example\.com: its mind runs outside/m);
  assert.doesNotMatch(outside, /config=|mark=on/);
});

test("a Cloudflare token that Cloudflare refuses: with an access that may change API tokens, one more deploy without the field", () => {
  // this run set the field
  const set = deployStack({
    config: { name: "a", cloudflareToken: true },
    cloudflareOn: true,
    cloudflareRefused: true,
    mayMakeTokens: true,
  });
  assert.match(set, /exit=0 deploys=2 telemetry=false cloudflareToken=false/);
  assert.match(set, /One more try, without it\./);
  assert.match(
    set,
    /^Note: the mind of a\.com has no Cloudflare connection: Cloudflare refused its API token\. iterate on a\.com 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"/m,
  );
  // the stack's own config has the field, and the deploy used that config: the second deploy uses
  // a config of this run, without the field
  const kept = deployStack({
    config: null,
    stored: { name: "a", cloudflareToken: true },
    cloudflareRefused: true,
    mayMakeTokens: true,
  });
  assert.match(kept, /exit=0 deploys=2 telemetry=false cloudflareToken=false/);
  // both turned on in one run, and no token from Cloudflare: the stack is deployed with neither
  const both = deployStack({
    config: { name: "a", telemetry: true, cloudflareToken: true },
    telemetryOn: true,
    cloudflareOn: true,
    cloudflareRefused: true,
    mayMakeTokens: true,
  });
  assert.match(both, /exit=0 deploys=3 telemetry=false cloudflareToken=false/);
  assert.match(both, /^Note: telemetry not turned on: /m);
});

test("a Cloudflare token that Cloudflare refuses: an access that may not change API tokens gets no second deploy, and one line says what to do", () => {
  const out = deployStack({
    config: null,
    stored: { name: "a", cloudflareToken: true },
    cloudflareRefused: true,
  });
  // the deploy without the field would have to delete the token, which this access cannot do
  assert.match(out, /exit=1 deploys=1 telemetry=false cloudflareToken=true/);
  assert.match(
    out,
    /^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.* Until then the mind uses no token of an older list, so it may have no Cloudflare connection\.$/m,
  );
  // a deploy that fails for another reason does not take the connection of a stack that has it
  const other = deployStack({
    config: null,
    stored: { name: "a", telemetry: true, cloudflareToken: true },
    mayMakeTokens: true,
  });
  assert.match(other, /exit=1 deploys=1 telemetry=true cloudflareToken=true/);
  assert.doesNotMatch(other, /Cloudflare connection|mind's API token/);
});

test("an update writes no config: the stack deploys from the one it keeps", () => {
  assert.equal(configOf({ ...asked, ownerEmails: undefined }), null);
});

// The jq program of `stack_updatable`, taken from run.sh itself, on a stored config.
const program = /said=\$\(jq -r [^']*'([^']+)' "\$STORED"/.exec(
  readFileSync(new URL("../container/run.sh", import.meta.url), "utf8"),
)?.[1];
const saidOf = (mind, more = {}) => {
  const stored = { name: "a", domain: "a.com", accountId: "1", ...(mind ? { mind } : {}), ...more };
  const ran = spawnSync(
    "jq",
    ["-r", "--arg", "n", "a", "--arg", "z", "a.com", "--arg", "a", "1", program],
    { input: JSON.stringify(stored), encoding: "utf8" },
  );
  assert.equal(ran.status, 0, ran.stderr);
  return ran.stdout.trim();
};

test("a run keeps a sandbox image that the stored config names, and stops at a built one", () => {
  assert.ok(program, "run.sh has the jq program of stack_updatable");
  assert.equal(saidOf({ images: {} }), "ok");
  assert.equal(saidOf({ images: { "iterate-dev-image": iterateDevImage.image } }), "ok");
  assert.equal(saidOf({ containers: false }), "ok");
  assert.equal(saidOf({ provided: true }), "ok");
  assert.equal(saidOf({ images: { tools: { dockerfile: "./Dockerfile" } } }), "built");
  assert.equal(
    saidOf({ images: { tools: iterateDevImage.image, built: iterateDevImage.dockerfile } }),
    "built",
  );
  // the older word, in a config stored before `mind.images`
  assert.equal(saidOf({ sandboxImage: "published" }), "ok");
  assert.equal(saidOf({ sandboxImage: "managed" }), "ok");
  assert.equal(saidOf({ sandboxImage: "later" }), "ok");
  assert.equal(saidOf({ sandboxImage: "built" }), "built");
  assert.equal(saidOf({ sandboxImage: "published" }, { atRestKey: "environment" }), "key");
});

test("a stored config from before images that names no image gets iterate's public one", () => {
  assert.equal(saidOf(undefined), "unnamed");
  assert.equal(saidOf({}), "unnamed");
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  assert.match(run, /\{sandboxImage: "published"\}\)' "\$STORED" > \/work\/mind\.config\.json/);
});

test("an update whose access may not change API tokens keeps the mind's token as it is, and one that may says this release made it", () => {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const line =
    /^ {2}if \[ "\$ITERATE_CLOUDFLARE_TOKEN" = 1 \]; then unset ITERATE_KEEP_CLOUDFLARE_TOKEN; else export ITERATE_KEEP_CLOUDFLARE_TOKEN=1; fi$/m.exec(
      run,
    )?.[0];
  assert.ok(line, "run.sh sets ITERATE_KEEP_CLOUDFLARE_TOKEN");
  for (const [given, kept] of [
    ["", "1"],
    ["1", ""],
  ]) {
    const ran = spawnSync(
      "bash",
      [
        "-c",
        `ITERATE_CLOUDFLARE_TOKEN=${given}\n${line}\necho "keep=$ITERATE_KEEP_CLOUDFLARE_TOKEN"`,
      ],
      {
        encoding: "utf8",
      },
    );
    assert.equal(ran.stdout.trim(), `keep=${kept}`);
  }
  // before `deploy_stack` in `main`, which runs the deploy that reads it
  const main = /^main\(\) \{\n[\s\S]*?^\}/m.exec(run)[0];
  assert.ok(main.includes(line));
  assert.ok(main.indexOf(line) < main.indexOf("  deploy_stack; code=$?"));
  assert.match(
    run,
    /echo "cloudflare-connection on"\n {4}\[ "\$ITERATE_CLOUDFLARE_TOKEN" = 1 \] && echo "cloudflare-token made by this release"/,
  );
});

// A chat installation's two configs (worker/installation.js `inputOf`): the stack before its
// domain (phase `early`), with no sandboxes yet, and the deploy at the domain after it, with
// no named image: its sandboxes start the Cloudflare-managed image.
const chat = { ...asked, mind: { images: {} } };
const early = (more) =>
  configOf({ ...chat, zone: undefined, mind: { containers: false }, ...more });
/** A config as the run writes it: JSON, with no undefined field. */
const written = (config) => JSON.parse(JSON.stringify(config));

test("the config before the domain is one that the stack takes: no domain, no mail, no mailed code, and the plan when the account has no Workers Paid", () => {
  for (const cloudflarePlan of ["free", undefined]) {
    const config = written(early({ cloudflarePlan }));
    assert.deepEqual(MindConfig.parse(config), config);
    assert.equal("domain" in config, false);
    assert.equal("mail" in config, false);
    assert.deepEqual(config.auth.login.methods, {});
    assert.deepEqual(config.mind, { containers: false });
    assert.equal(config.cloudflarePlan, cloudflarePlan);
    assert.equal("cloudflarePlan" in config, cloudflarePlan !== undefined);
  }
  // the deploy at the domain: its containers, with no named image
  const tail = configOf(chat);
  assert.deepEqual(MindConfig.parse(tail), tail);
  assert.deepEqual([tail.domain, tail.mail, tail.mind], ["example.com", true, { images: {} }]);
});

test("a stack deployed before its domain passes the update check, and its deploy at the domain is the one the Cloud gives a first deploy", () => {
  const stored = early({ cloudflarePlan: "free" });
  const out = updatable(stored);
  assert.match(out, /^exit=0$/m);
  assert.match(
    out,
    /^Note: The stack example-com was deployed before its domain\. This deploy gives it example\.com, 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, /m,
  );
  const next = JSON.parse(/^config=(.*)$/m.exec(out)[1]);
  assert.deepEqual(MindConfig.parse(next), next);
  assert.deepEqual(next, written(configOf(chat)));
  // a stack that an older Cloud deployed before its domain says it in the older word: the same
  const older = updatable({ ...stored, mind: { sandboxImage: "later" } });
  assert.match(older, /^exit=0$/m);
  assert.deepEqual(JSON.parse(/^config=(.*)$/m.exec(older)[1]), next);
  // with the consents for telemetry and the mind's Cloudflare connection, the same as a first
  // deploy that has both
  const both = updatable(stored, "ITERATE_TELEMETRY=1\nITERATE_CLOUDFLARE_TOKEN=1");
  assert.match(both, /^exit=0$/m);
  assert.match(both, /^mark=on$/m);
  assert.deepEqual(
    JSON.parse(/^config=(.*)$/m.exec(both)[1]),
    written(configOf({ ...chat, telemetry: true, cloudflareToken: true })),
  );
  // a stack with Workers Paid and R2 before its domain: the same
  assert.deepEqual(
    JSON.parse(/^config=(.*)$/m.exec(updatable(early()))[1]),
    written(configOf(chat)),
  );
});

test("a stack with no domain yet under another name, or of another account, still stops", () => {
  const other = updatable({ ...early(), name: "other" });
  assert.match(other, /^exit=1$/m);
  assert.match(
    other,
    /^Stopped: the config that iterate keeps under the name example-com is for no domain, under the name other, not for example\.com\. Nothing was changed\.$/m,
  );
  assert.match(updatable({ ...early(), accountId: "f".repeat(32) }), /^exit=1$/m);
  // the jq program alone: no domain is not another domain
  const ran = spawnSync(
    "jq",
    ["-r", "--arg", "n", "a", "--arg", "z", "a.com", "--arg", "a", "1", program],
    {
      input: JSON.stringify({ name: "a", accountId: "1", mind: { sandboxImage: "later" } }),
      encoding: "utf8",
    },
  );
  assert.equal(ran.stdout.trim(), "ok");
});

/** run.sh's `workers_dev_ready`, with Cloudflare's answers to GET and PUT the account's name. */
function workersDev({ get, put }) {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const fn = new RegExp("^workers_dev_ready\\(\\) \\{\\n[\\s\\S]*?^\\}", "m").exec(run)[0];
  const script = `
CLOUDFLARE_ACCOUNT_ID=a
ITERATE_NAME=ada-labs
cf_get() { printf '%s\\n%s' '${JSON.stringify(get.body)}' ${get.code}; }
cf_put() { echo "PUT $2" >&2; printf '%s\\n%s' '${JSON.stringify(put?.body ?? {})}' ${put?.code ?? 500}; }
${fn}
workers_dev_ready
`;
  const ran = spawnSync("bash", ["--norc", "-c", script], { encoding: "utf8" });
  return {
    code: ran.status,
    out: ran.stdout.trim(),
    puts: ran.stderr.trim().split("\n").filter(Boolean),
  };
}

test("a chat installation gives an account with no workers.dev name the stack's name, and keeps one it has", () => {
  const has = workersDev({ get: { code: 200, body: { result: { subdomain: "ada" } } } });
  assert.deepEqual([has.code, has.out, has.puts], [0, "workers.dev: ada.workers.dev", []]);
  const none = { code: 404, body: { errors: [{ code: 10007 }] } };
  const made = workersDev({ get: none, put: { code: 200, body: { success: true } } });
  assert.deepEqual(
    [made.code, made.out],
    [0, "workers.dev: made ada-labs.workers.dev for the account."],
  );
  assert.deepEqual(made.puts, ['PUT {"subdomain":"ada-labs"}']);
  const taken = workersDev({ get: none, put: { code: 409, body: { errors: [{ code: 10031 }] } } });
  assert.equal(taken.code, 1);
  assert.equal(taken.puts.length, 2);
  assert.match(taken.puts[1], /^PUT \{"subdomain":"ada-labs-[a-z0-9]{4}"\}$/);
  // any other answer: no guess
  assert.equal(workersDev({ get: { code: 500, body: {} } }).code, 1);
});

/** run.sh's `early`, with the store's answer (`store`: the status of its Worker, `kept`: the
 *  config it keeps, "" for none) and every other step stood in for. What it says and deploys. */
function earlyRun({ store, kept = "", config = early({ cloudflarePlan: "free" }) }) {
  const run = readFileSync(new URL("../container/run.sh", import.meta.url), "utf8");
  const fn = new RegExp("^early\\(\\) \\{\\n[\\s\\S]*?^\\}", "m").exec(run)[0];
  const work = mkdtempSync(join(tmpdir(), "run-early-"));
  writeFileSync(join(work, "COMMIT"), `${"c".repeat(40)}\n`);
  if (config) writeFileSync(join(work, "mind.config.json"), JSON.stringify(config));
  writeFileSync(join(work, "kept.json"), kept);
  const script = `
CLOUDFLARE_API_TOKEN=token
CLOUDFLARE_ACCOUNT_ID=${asked.accountId}
ITERATE_NAME=example-com
STORED=/work/stored-config.json
workers_dev_ready() { echo "workers.dev: ok"; }
not_older_stack() { :; }
not_unknown_stack() { echo "checked the commit"; }
make_store() { echo "made the store $1"; }
cf_get() { printf '{}\\n${store}'; }
stored_config() { cat /work/kept.json; }
deploy_stack() { echo "deployed with $(jq -c '{domain, cloudflarePlan, mind}' "$ITERATE_MIND_CONFIG")"; }
${fn}
early; echo "exit=$?"
`
    .replaceAll("/stack/core/alchemy", work)
    .replaceAll("/stack/", `${work}/`)
    .replaceAll("/work/", `${work}/`);
  const ran = spawnSync("bash", ["--norc", "-c", script], { encoding: "utf8" });
  assert.equal(ran.stderr, "");
  return ran.stdout;
}

test("the deploy before the domain makes the store when there is none, and deploys the config it was given", () => {
  const out = earlyRun({ store: 404 });
  assert.match(out, /^made the store iterate-example-com-state$/m);
  assert.match(out, /^checked the commit$/m);
  assert.match(
    out,
    /^The stack before its domain, on what a Free account takes, and with no sandboxes yet \(mind\.containers: false\)\.$/m,
  );
  assert.match(
    out,
    /^deployed with \{"domain":null,"cloudflarePlan":"free","mind":\{"containers":false\}\}$/m,
  );
  assert.match(out, /^exit=0$/m);
  // a store with no config in it (no deploy ever ended) is deployed into too
  assert.match(
    earlyRun({ store: 200 }),
    /^deployed with .*\nThe stack iterate-example-com is deployed before its domain/m,
  );
  // with Workers Paid and R2, the line says so
  assert.match(
    earlyRun({ store: 404, config: early() }),
    /^The stack before its domain, with Workers Paid and R2, and with no sandboxes yet/m,
  );
});

test("the deploy before the domain never deploys over a stack that keeps a config: the deploy at the domain checks that one", () => {
  const atDomain = earlyRun({ store: 200, kept: JSON.stringify(configOf(asked)) });
  assert.match(atDomain, /^exit=1$/m);
  assert.doesNotMatch(atDomain, /deployed with/);
  assert.match(
    atDomain,
    /^Stopped: iterate keeps a config under the name example-com already, for example\.com\. The deploy at the domain checks it as an update\. Nothing was changed\.$/m,
  );
  // one before its domain too: this phase deploys under a name that holds no stack alone
  const before = earlyRun({ store: 200, kept: JSON.stringify(early()) });
  assert.match(before, /^Stopped: iterate keeps a config under the name example-com already\. /m);
  assert.doesNotMatch(before, /deployed with/);
  // any other answer, and no config given: nothing is deployed
  assert.match(
    earlyRun({ store: 500 }),
    /^Cloudflare answered 500 to GET the Worker iterate-example-com-state\.\nexit=1$/m,
  );
  assert.match(
    earlyRun({ store: 404, config: null }),
    /^The phase did not get its config\.\nexit=1$/m,
  );
});