iterate.com / cloud

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

cloud / scripts / zone-enrollment / zone-enrollment.test.tsmain at aacbc74

// zone-enrollment.test.ts — WHAT A MIND'S STACK DOES TO A ZONE THAT JOINS ITS CONFIG, STAYS IN
// IT, AND LEAVES IT, proven with no account: Alchemy's own CLI plans and deploys the stack's
// per-zone resources (./zone-resources.ts) against a fake Cloudflare on 127.0.0.1
// (./fake-cloudflare.ts) that starts as iterate2.com was inventoried on 25 Nov 2026 (the card
// tasks/decide-iterate2-com-mail-routing-without-web-changes.md of the iterate.com mind). The
// fixture's one way out is the fake (./only-the-fake.ts): no credential, no Doppler, no state
// store of an account. The ids here are made up: the card holds the real ones.
//
// The fake answers as Cloudflare's docs say, not as a live account was seen to: what this proves
// is which calls Alchemy sends and in which order, never what Cloudflare then does.
import { spawn } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fromApiToken } from "@distilled.cloud/cloudflare/Credentials";
import { StackContext } from "alchemy/StackContext";
import * as Effect from "effect/Effect";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as Redacted from "effect/Redacted";
import { expect, test } from "vitest";
import { MindConfig } from "../../core/alchemy/src/config.ts";
import { mindStack } from "../../core/alchemy/src/stack.ts";
import { type FakeZone, receivingRecordsOf, startFake, type World } from "./fake-cloudflare.ts";
import { type ZoneInput, zoneResources } from "./zone-resources.ts";

// ── a zone joins ──

/** A test that runs Alchemy's CLI two or more times: each run takes 1 to 3 s on beelink, and more
 *  on a CI runner. */
const CLI = { timeout: 60_000 };

test(
  "a zone joins by seven writes, and none removes, remakes or repeats a thing that was there: its Email Sending domain is taken over by reads alone",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    const plan = await at.run("plan");
    expect(plan).toMatchObject({
      status: 0,
      writes: [],
      // the zone's one catch-all rule is always there, so Alchemy words it as taken over
      summary: "6 to create, 2 to adopted",
      lines: [
        `ApexRecord-${ZONE} create`,
        `ApexRoute-${ZONE} create`,
        `EmailCatchAll-${ZONE} adopted`,
        `EmailRouting-${ZONE} create`,
        `EmailSending-${ZONE} adopted`,
        `MailEvents-${ZONE} create`,
        `WildcardRecord-${ZONE} create`,
        `WildcardRoute-${ZONE} create`,
      ],
    });

    expect(await at.run("deploy")).toMatchObject({
      status: 0,
      sortedWrites: [
        // HTTP: the apex and the wildcard, each a proxied record and a route to the boundary
        "POST /dns_records",
        "POST /dns_records",
        // receiving: Email Routing on, and the zone's one catch-all rule changed in place
        "POST /email/routing/enable",
        // outbound: the events of sent mail, to the stack's queue. Email Sending itself: no write
        "POST /event_subscriptions/subscriptions",
        "POST /workers/routes",
        "POST /workers/routes",
        "PUT /email/routing/rules/catch_all",
      ],
    });
    expect(at.seen()).toEqual({
      // what was there is as it was: the six records, and the sending domain with its id
      recordsFromBefore: baselineRecords(),
      sending: [sendingDomain()],
      // the catch-all is the same rule, now at the boundary
      catchAll: {
        id: "catch-all",
        name: "",
        enabled: true,
        actions: [{ type: "worker", value: [BOUNDARY] }],
      },
      routingEnabled: true,
      // HTTP: two records and two routes, and no other
      httpRecords: [`*.${ZONE} AAAA 100:: proxied`, `${ZONE} AAAA 100:: proxied`],
      routes: [`*.${ZONE}/* ${BOUNDARY}`, `${ZONE}/* ${BOUNDARY}`],
      subscriptions: [`email.sending ${ZONE} to events-queue`],
      onlyTheFake: true,
    });
  },
);

test(
  "a zone that stays is left alone: a second plan and a second deploy change nothing",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    expect(await at.run("plan")).toMatchObject({ status: 0, summary: "no changes", writes: [] });
    expect(await at.run("deploy")).toMatchObject({ status: 0, writes: [] });
  },
);

// Cloudflare publishes the zone's MX records when Email Routing is turned on. It takes a
// catch-all rule while routing is off (measured on a dev zone, 25 Nov 2026).
test(
  "the catch-all is the boundary's before Email Routing is turned on, and when the zone leaves, routing is off before the catch-all goes back",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    const ofRouting = (writes: string[]) =>
      writes.filter((write) => write.includes("/email/routing"));
    expect(ofRouting((await at.run("deploy")).writes)).toEqual([
      "PUT /email/routing/rules/catch_all",
      "POST /email/routing/enable",
    ]);
    expect(ofRouting((await at.run("deploy", { zoneInConfig: false })).writes)).toEqual([
      "POST /email/routing/disable",
      "PUT /email/routing/rules/catch_all",
    ]);
  },
);

// Until 25 Nov 2026 the stack turned routing on first. A mind that was deployed that way holds
// the same two resources in its state, and the new order plans nothing for them.
test(
  "a zone that the earlier order deployed (routing on, then the catch-all) plans no change with the new order",
  CLI,
  async () => {
    await using at = await fixture(inventoried(), { routingFirst: true });
    expect(
      (await at.run("deploy")).writes.filter((write) => write.includes("/email/routing")),
    ).toEqual(["POST /email/routing/enable", "PUT /email/routing/rules/catch_all"]);
    expect(await at.run("plan", { routingFirst: false })).toMatchObject({
      status: 0,
      summary: "no changes",
      writes: [],
    });
    expect(await at.run("deploy", { routingFirst: false })).toMatchObject({
      status: 0,
      writes: [],
    });
  },
);

test(
  "a zone that receives already (Email Routing on, the catch-all at the boundary) joins with no change to its receiving: no record, no rule",
  CLI,
  async () => {
    await using at = await fixture(receiving());
    // the enable call is sent again, and Cloudflare has nothing to do; the catch-all gets no call
    expect(await at.run("deploy")).toMatchObject({
      status: 0,
      sortedWrites: [
        "POST /dns_records",
        "POST /dns_records",
        "POST /email/routing/enable",
        "POST /event_subscriptions/subscriptions",
        "POST /workers/routes",
        "POST /workers/routes",
      ],
    });
    expect(at.seen()).toMatchObject({
      recordsFromBefore: receiving().records,
      catchAll: receiving().catchAll,
      routingEnabled: true,
      sending: [sendingDomain()],
      onlyTheFake: true,
    });
  },
);

// Until 25 Nov 2026 the stack declared the sending domain with no `adopt`.
test(
  "without the take-over, the plan stops at a zone whose Email Sending domain is there already, and nothing changes",
  CLI,
  async () => {
    await using at = await fixture(inventoried(), { takeOverSending: false });
    const plan = await at.run("plan");
    expect(plan).toMatchObject({ status: 1, writes: [] });
    expect(plan.output).toContain(
      `OwnedBySomeoneElse: Cannot adopt resource 'EmailSending-${ZONE}' (Cloudflare.Email.SendingSubdomain)`,
    );
    // a deploy makes its own plan first, and stops the same way before its first write
    expect(await at.run("deploy")).toMatchObject({ status: 1, writes: [] });
    expect(at.zone()).toEqual(inventoried());
  },
);

// ── a zone leaves: Alchemy deletes what its state holds for the zone ──

test(
  "a zone that leaves the config is planned as eight deletes: the deploy removes what the stack made, deletes the sending domain that it took over, gives the catch-all back as it found it, and turns Email Routing off",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    expect(await at.run("plan", { zoneInConfig: false })).toMatchObject({
      status: 0,
      writes: [],
      summary: "8 to delete",
      lines: [
        `ApexRecord-${ZONE} delete`,
        `ApexRoute-${ZONE} delete`,
        `EmailCatchAll-${ZONE} delete`,
        `EmailRouting-${ZONE} delete`,
        `EmailSending-${ZONE} delete`,
        `MailEvents-${ZONE} delete`,
        `WildcardRecord-${ZONE} delete`,
        `WildcardRoute-${ZONE} delete`,
      ],
    });
    expect(await at.run("deploy", { zoneInConfig: false })).toMatchObject({
      status: 0,
      sortedWrites: [
        "DELETE /dns_records/<made>",
        "DELETE /dns_records/<made>",
        "DELETE /email/sending/subdomains/sending-domain",
        "DELETE /event_subscriptions/subscriptions/<made>",
        "DELETE /workers/routes/<made>",
        "DELETE /workers/routes/<made>",
        "POST /email/routing/disable",
        "PUT /email/routing/rules/catch_all",
      ],
    });
    expect(at.seen()).toEqual({
      // no call names one of the six records: what Cloudflare does with the sending domain's own
      // records when the domain is deleted is Cloudflare's, and the fake leaves them
      recordsFromBefore: baselineRecords(),
      sending: [],
      catchAll: inventoried().catchAll,
      routingEnabled: false,
      httpRecords: [],
      routes: [],
      subscriptions: [],
      onlyTheFake: true,
    });
    // and once more: nothing is left to do
    expect(await at.run("plan", { zoneInConfig: false })).toMatchObject({
      summary: "no resources",
    });
  },
);

// WHAT PREDATES THE STACK AND IS NOT GIVEN BACK: Alchemy's Email Routing resource does not record
// whether routing was on before it. A zone that received mail before it joined stops receiving
// when it leaves: the catch-all is the boundary's again, and routing is off.
test(
  "a zone that received mail before it joined has its Email Routing turned off when it leaves",
  CLI,
  async () => {
    await using at = await fixture(receiving());
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    const removal = await at.run("deploy", { zoneInConfig: false });
    expect(removal).toMatchObject({ status: 0 });
    expect(removal.writes).toContain("POST /email/routing/disable");
    expect(at.seen()).toMatchObject({ routingEnabled: false, catchAll: receiving().catchAll });
  },
);

// ── a deploy that fails midway, and the way back ──
// Alchemy has no undo: what a failed deploy made stays, in the account and in the state. The way
// back is a second deploy with the zone list from before, and the way on is the same deploy again.

test(
  "a join that fails midway leaves what it made, and the same deploy again finishes it by the one call that was refused",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    at.refuse(/POST .*\/event_subscriptions/);
    expect(await at.run("deploy")).toMatchObject({ status: 1 });
    // nothing was undone: the zone takes requests and mail, and no events of sent mail arrive
    expect(at.seen()).toMatchObject({
      routingEnabled: true,
      catchAll: { enabled: true, actions: [{ type: "worker", value: [BOUNDARY] }] },
      routes: [`*.${ZONE}/* ${BOUNDARY}`, `${ZONE}/* ${BOUNDARY}`],
      sending: [sendingDomain()],
      subscriptions: [],
    });
    at.refuse();
    expect(await at.run("plan")).toMatchObject({ status: 0, summary: "1 to create", writes: [] });
    expect(await at.run("deploy")).toMatchObject({
      status: 0,
      writes: ["POST /event_subscriptions/subscriptions"],
    });
  },
);

// THE WAY BACK IS NO RESTORE: the zone list from before deletes all that the state holds for the
// zone, and the state holds the sending domain that the join took over.
test(
  "the way back from a join that failed is the zone list from before: it removes what was made, and deletes the sending domain that was there before the join",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    at.refuse(/POST .*\/event_subscriptions/);
    expect(await at.run("deploy")).toMatchObject({ status: 1 });
    at.refuse();
    expect(await at.run("plan", { zoneInConfig: false })).toMatchObject({ summary: "8 to delete" });
    expect(await at.run("deploy", { zoneInConfig: false })).toMatchObject({ status: 0 });
    expect(at.seen()).toEqual({
      recordsFromBefore: baselineRecords(),
      // what the zone had before the join, and has no more
      sending: [],
      catchAll: inventoried().catchAll,
      routingEnabled: false,
      httpRecords: [],
      routes: [],
      subscriptions: [],
      onlyTheFake: true,
    });
  },
);

test(
  "a leave that fails midway goes on with the same deploy again; the way back makes the zone's resources anew, with a new sending domain",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    at.refuse(/DELETE .*\/workers\/routes/);
    expect(await at.run("deploy", { zoneInConfig: false })).toMatchObject({ status: 1 });
    // the routes stay, and the rest of the zone is gone: its hostnames reach the boundary, with
    // no record that makes them resolve, and its mail is off
    expect(at.seen()).toMatchObject({
      routes: [`*.${ZONE}/* ${BOUNDARY}`, `${ZONE}/* ${BOUNDARY}`],
      httpRecords: [],
      routingEnabled: false,
      sending: [],
    });
    at.refuse();
    // the way back: the zone in the list again
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    expect(at.seen()).toMatchObject({
      routingEnabled: true,
      httpRecords: [`*.${ZONE} AAAA 100:: proxied`, `${ZONE} AAAA 100:: proxied`],
      // not the domain that was deleted: Cloudflare makes one, with an id of its own
      sending: [{ tag: expect.stringMatching(/^made-/), name: ZONE }],
      subscriptions: [`email.sending ${ZONE} to events-queue`],
    });
    // the way on: the leave again, which now ends
    expect(await at.run("deploy", { zoneInConfig: false })).toMatchObject({ status: 0 });
    expect(at.seen()).toMatchObject({ routes: [], sending: [], routingEnabled: false });
  },
);

// A FAILURE THAT NO EXIT CODE SHOWS: Alchemy's Email Routing provider drops every error of its
// delete (alchemy 2.0.0-beta.87, Email/Routing.ts). The zone then keeps its MX records with a
// catch-all that is `drop`, disabled: mail to it is lost. Only a read of the zone shows it.
test(
  "a leave whose turning-off of Email Routing is refused ends as a success, with routing still on and no handler",
  CLI,
  async () => {
    await using at = await fixture(inventoried());
    expect(await at.run("deploy")).toMatchObject({ status: 0 });
    at.refuse(/POST .*\/email\/routing\/disable/);
    expect(await at.run("deploy", { zoneInConfig: false })).toMatchObject({ status: 0 });
    expect(at.seen()).toMatchObject({ routingEnabled: true, catchAll: inventoried().catchAll });
    // and the state has forgotten the zone: no later plan turns it off
    at.refuse();
    expect(await at.run("plan", { zoneInConfig: false })).toMatchObject({
      summary: "no resources",
    });
  },
);

// ── the fixture against the stack's own declaration (core/alchemy/src/stack.ts) ──

test("the fixture declares for a zone what the stack declares for it: the same ids and types, and the same plain props", async () => {
  const stack = await declaredBy(mindStack(config(["example.com", "second.example"])));
  const ofTheZone = Object.keys(stack).filter((id) => id.endsWith("-second.example"));
  const fixtureResources = await declaredBy(
    zoneResources({
      zoneId: "zone-id",
      zoneName: "second.example",
      boundaryWorkerName: "iterate-example-boundary",
      cloudflareEventsQueueId: "events-queue",
    }),
  );
  const shapeOf = (resources: Record<string, any>) =>
    Object.fromEntries(
      ofTheZone.sort().map((id) => {
        // the boundary's name and the queue's id are Outputs in the stack, and given in the fixture
        const {
          script: _script,
          queueId: _queueId,
          actions: _actions,
          ...props
        } = plainProps(resources[id]);
        return [id, { type: resources[id]?.Type, props }];
      }),
    );
  expect(Object.keys(fixtureResources).sort()).toEqual(ofTheZone.sort());
  expect(shapeOf(fixtureResources)).toEqual(shapeOf(stack));
});

test("a second zone adds eight resources of its own, and changes three things of the stack's Workers: each Worker's config, the boundary's kept config, and the addresses that the auth Worker may send from", async () => {
  const one = await declaredBy(mindStack(config(["example.com"])));
  const two = await declaredBy(mindStack(config(["example.com", "second.example"])));
  // What changes in a resource that both have: a Worker's plain-text variables and the auth
  // Worker's binding to send mail, and no other prop. The auth Worker's own `ITERATE` holds the
  // zones too, and is no plain text here: the stack computes it from the Access team's outputs.
  const changed: string[] = [];
  const senders = (value: any) => JSON.stringify(value?.allowedSenderAddresses);
  for (const id of Object.keys(one)) {
    if (one[id].Type === "Cloudflare.Worker") {
      for (const name of Object.keys(one[id].Props.env)) {
        const [before, after] = [one[id].Props.env[name], two[id].Props.env[name]];
        if (typeof before === "string" ? before !== after : senders(before) !== senders(after))
          changed.push(`${id}/${name}`);
      }
    } else if (JSON.stringify(plainProps(one[id])) !== JSON.stringify(plainProps(two[id])))
      changed.push(id);
  }
  expect({
    gone: Object.keys(one).filter((id) => !(id in two)),
    came: Object.keys(two)
      .filter((id) => !(id in one))
      .map((id) => `${id} ${two[id].Type}`)
      .sort(),
    changed: changed.sort(),
    authSenders: two.Auth.Props.env.SEND_EMAIL.allowedSenderAddresses,
  }).toEqual({
    gone: [],
    came: [
      // HTTP: every hostname of the zone reaches the boundary
      "ApexRecord-second.example Cloudflare.DNS.Record",
      "ApexRoute-second.example Cloudflare.Workers.Route",
      // receiving
      "EmailCatchAll-second.example Cloudflare.Email.CatchAll",
      "EmailRouting-second.example Cloudflare.Email.Routing",
      // outbound
      "EmailSending-second.example Cloudflare.Email.SendingSubdomain",
      "MailEvents-second.example Cloudflare.Queues.Subscription",
      "WildcardRecord-second.example Cloudflare.DNS.Record",
      "WildcardRoute-second.example Cloudflare.Workers.Route",
    ],
    changed: [
      "Auth/SEND_EMAIL",
      "Boundary/DEPLOY_CONFIG",
      "Boundary/ITERATE",
      "Mind/ITERATE",
      "Secrets/ITERATE",
      "Telemetry/ITERATE",
    ],
    // auth senders: sign-in@second.example joins the two that were there
    authSenders: ["sign-in@example.com", "sign-in@second.example", "self-test@example.com"],
  });
});

// ── the zone, the fixture and the stack's declaration ──

const ZONE = "iterate2.com";
const BOUNDARY = "iterate-iterate-boundary";
const ACCOUNT = "a".repeat(32);
const BOUNCE = `cf-bounce.${ZONE}`;
const MX = { type: "MX", ttl: 1 };
const TXT = { type: "TXT", ttl: 1 };

/** The zone's six DNS records of the inventory: Email Sending's return path, its DKIM key and
 *  the DMARC policy. None is a receiving record, and none is at the apex. */
function baselineRecords() {
  return [
    { id: "bounce-mx-1", name: BOUNCE, ...MX, content: "route1.mx.cloudflare.net", priority: 77 },
    { id: "bounce-mx-2", name: BOUNCE, ...MX, content: "route2.mx.cloudflare.net", priority: 8 },
    { id: "bounce-mx-3", name: BOUNCE, ...MX, content: "route3.mx.cloudflare.net", priority: 70 },
    {
      id: "bounce-spf",
      name: BOUNCE,
      ...TXT,
      content: '"v=spf1 include:_spf.mx.cloudflare.net ~all"',
    },
    { id: "bounce-dkim", name: `cf-bounce._domainkey.${ZONE}`, ...TXT, content: '"the live key"' },
    { id: "dmarc", name: `_dmarc.${ZONE}`, ...TXT, content: '"v=DMARC1; p=reject;"' },
  ];
}

function sendingDomain() {
  return {
    tag: "sending-domain",
    name: ZONE,
    enabled: true,
    dkim_selector: "cf-bounce",
    return_path_domain: BOUNCE,
    preview_enabled: true,
  };
}

/** iterate2.com as inventoried: Email Sending on, Email Routing off, the catch-all `drop` and
 *  disabled, no route, no apex record. */
function inventoried(): FakeZone {
  return {
    id: "b".repeat(32),
    name: ZONE,
    records: baselineRecords(),
    routes: [],
    routing: { id: "routing", enabled: false, status: "unconfigured" },
    catchAll: { id: "catch-all", name: "", enabled: false, actions: [{ type: "drop" }] },
    sending: [sendingDomain()],
  };
}

/** The same zone after the receive-only step of the linked card: Email Routing on, with the
 *  records Cloudflare adds for it, and the catch-all at the boundary Worker. */
function receiving(): FakeZone {
  const zone = inventoried();
  return {
    ...zone,
    records: [
      ...zone.records,
      ...receivingRecordsOf(ZONE).map((record, at) => ({ id: `receiving-${at}`, ...record })),
    ],
    routing: { id: "routing", enabled: true, status: "ready" },
    catchAll: { ...zone.catchAll, enabled: true, actions: [{ type: "worker", value: [BOUNDARY] }] },
  };
}

/** A fake that holds `zone`, and Alchemy's CLI over the fixture's stack with it: `run("plan")`
 *  and `run("deploy")`, each with the calls that it sent. The state is a folder that goes with
 *  the fixture. */
async function fixture(
  zone: FakeZone,
  options: { takeOverSending?: boolean; routingFirst?: boolean } = {},
) {
  const world: World = { accountId: ACCOUNT, zones: [zone], subscriptions: [] };
  const fake = await startFake(world);
  const folder = mkdtempSync(join(tmpdir(), "zone-enrollment-"));
  const refusedFile = join(folder, "refused.log");
  const input: ZoneInput = {
    zoneId: zone.id,
    zoneName: zone.name,
    boundaryWorkerName: BOUNDARY,
    cloudflareEventsQueueId: "events-queue",
    takeOverSending: options.takeOverSending,
    routingFirst: options.routingFirst,
  };
  /** `zoneInConfig: false`: the stack after the zone left its config. `routingFirst`: the order
   *  of this run, when it is not the fixture's. */
  const run = async (
    command: "plan" | "deploy",
    { zoneInConfig = true, routingFirst = input.routingFirst } = {},
  ) => {
    const from = fake.calls.length;
    // not spawnSync: the fake answers from this process while the CLI runs
    const child = spawn(
      join(import.meta.dirname, "../node_modules/.bin/alchemy"),
      [
        command,
        join(import.meta.dirname, "fixture.run.ts"),
        "--stage",
        "iterate",
        "--no-input",
        ...(command === "plan" ? [] : ["--yes"]),
      ],
      {
        cwd: folder,
        stdio: ["ignore", "pipe", "pipe"],
        // nothing of this computer's environment: no token, no sign-in, no profile
        env: {
          PATH: process.env.PATH,
          HOME: join(folder, "home"),
          DO_NOT_TRACK: "1",
          NODE_OPTIONS: `--import ${join(import.meta.dirname, "only-the-fake.ts")}`,
          FAKE_CLOUDFLARE: fake.url,
          REFUSED_CALLS: refusedFile,
          CLOUDFLARE_API_TOKEN: "no-token",
          CLOUDFLARE_ACCOUNT_ID: ACCOUNT,
          ZONE_ENROLLMENT_FIXTURE: JSON.stringify(zoneInConfig ? [{ ...input, routingFirst }] : []),
        },
      },
    );
    let output = "";
    child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
    child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
    const status = await new Promise<number | null>((resolve) => child.on("close", resolve));
    /** every call that changes something, as `METHOD path` with the zone's or account's id cut,
     *  and an id that the fake made as `<made>` */
    const writes = fake.calls
      .slice(from)
      .filter((call) => call.method !== "GET")
      .map(
        (call) =>
          `${call.method} ${call.path.replace(/^\/(zones|accounts)\/[^/]+/, "").replace(/made-\d+$/, "<made>")}`,
      );
    return {
      status,
      output,
      /** the plan's lines, as scripts/lib/own-minds-gate.ts reads them, sorted */
      lines: [...output.matchAll(/INFO: \[([^\]]+)\] (\S+)\s*$/gm)]
        .map((said) => `${said[1]} ${said[2]}`)
        .sort(),
      summary: /INFO: Plan: (.+?)\s*$/m.exec(output)?.[1],
      writes,
      sortedWrites: [...writes].sort(),
    };
  };
  return {
    run,
    /** Cloudflare refuses each call that `call` matches (`METHOD path`), until `refuse()`. */
    refuse: (...calls: RegExp[]) => void fake.refuses.splice(0, fake.refuses.length, ...calls),
    zone: () => world.zones[0]!,
    /** The zone and the account as they are now, in the words of the tests. `onlyTheFake`: the
     *  fake served every call, and the one call that the CLI tried elsewhere, its look for a
     *  newer version of itself, was refused. */
    seen: () => {
      const now = world.zones[0]!;
      return {
        recordsFromBefore: now.records.filter((record) => !record.id.startsWith("made-")),
        sending: now.sending,
        catchAll: now.catchAll,
        routingEnabled: now.routing.enabled,
        httpRecords: now.records
          .filter((record) => record.type === "AAAA")
          .map(
            (record) => `${record.name} AAAA ${record.content}${record.proxied ? " proxied" : ""}`,
          )
          .sort(),
        routes: now.routes.map((route) => `${route.pattern} ${route.script}`).sort(),
        subscriptions: world.subscriptions.map(
          (each: any) =>
            `${each.source.type} ${each.source.domain} to ${each.destination.queue_id}`,
        ),
        onlyTheFake:
          fake.unserved.length === 0 &&
          (existsSync(refusedFile)
            ? readFileSync(refusedFile, "utf8").trim().split("\n")
            : []
          ).every((line) => line === "GET https://registry.npmjs.org/-/package/alchemy/dist-tags"),
      };
    },
    async [Symbol.asyncDispose]() {
      await fake.close();
      rmSync(folder, { recursive: true, force: true });
    },
  };
}

function config(zones: string[]) {
  return MindConfig.parse({
    mindId: "a".repeat(64),
    controlPlaneHostname: "iterate.example.com",
    ownerEmails: ["owner@owner.example"],
    topology: "full-cloudflare",
    alchemy: { stageName: "example" },
    cloudflare: { accountId: ACCOUNT, zones },
  });
}

/** Each resource that a program declares, by its logical id: Alchemy records it as it is declared,
 *  with no provider, no credential and no state (as core/alchemy/src/stack-bindings.test.ts).
 *  The one call of a declaration, the stack's lookup of a zone by its name, is answered here. */
async function declaredBy(program: Effect.Effect<unknown, unknown, any>) {
  const stack = {
    name: "mind",
    stage: "example",
    resources: {} as Record<string, any>,
    bindings: {},
    actions: {},
  };
  const zoneLookup = HttpClient.make((request) =>
    Effect.succeed(
      HttpClientResponse.fromWeb(
        request,
        Response.json({
          success: true,
          errors: [],
          messages: [],
          result: [
            {
              id: "zone-id",
              name: new URL(request.url).searchParams.get("name"),
              account: { id: ACCOUNT },
            },
          ],
        }),
      ),
    ),
  );
  await Effect.runPromise(
    program.pipe(
      Effect.provideService(StackContext, stack),
      Effect.provideService(HttpClient.HttpClient, zoneLookup),
      Effect.provide(fromApiToken({ apiToken: Redacted.make("none") })),
    ) as Effect.Effect<unknown>,
  );
  return Object.fromEntries(
    Object.values(stack.resources).map((resource) => [resource.LogicalId as string, resource]),
  );
}

/** A resource's props that are plain values: an Output of another resource is left out. */
function plainProps(resource: any) {
  return JSON.parse(
    JSON.stringify(resource?.Props ?? {}, (_key, value) =>
      typeof value === "function" ||
      (value && typeof value === "object" && "kind" in value && "~alchemy/Output" in value)
        ? undefined
        : value,
    ),
  );
}