sailfork / t3code-github / .repos/ alchemy-effect/ packages/ integration-tests/ test/ Prisma/ Compute.test.ts

import { gunzipSync } from "node:zlib";
import {
  PrismaApiError,
  PrismaClient,
  type PrismaManagementClient,
} from "@alchemy.run/prisma/Client";
import {
  Compute,
  ComputeDevProvider,
  ComputeProvider,
  syncComputeEnvironment,
  waitForDeploymentUrl,
  type ComputeProps,
} from "@alchemy.run/prisma/Compute";
import type { Branch as ApiBranch } from "@alchemy.run/prisma/Types";
import { describe, expect, it } from "@alchemy.run/test";
import { fromApiToken } from "@distilled.cloud/prisma";
import { Unowned } from "alchemy/AdoptPolicy";
import { AlchemyContext } from "alchemy/AlchemyContext";
import * as Output from "alchemy/Output";
import * as Provider from "alchemy/Provider";
import type { ResourceBinding } from "alchemy/Resource";
import { Stack } from "alchemy/Stack";
import { PlatformServices } from "alchemy/Util/PlatformServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpBody from "effect/http/HttpBody";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Redacted from "effect/Redacted";
import * as Stream from "effect/Stream";
import { WebSocketServer } from "ws";
import { Credentials } from "../../../prisma/src/internal/Credentials.ts";
import {
  type Captured,
  data,
  dispatchTo,
  failure,
  FAKE_API_BASE_URL,
  makeFakeManagementApi,
  unhandled,
} from "./fixtures/FakeManagementApi.ts";
import { testStackContext } from "./fixtures/StackContext.ts";

const testBranch = (id: string, role: "production" | "preview" = "production"): ApiBranch => ({
  id,
  type: "branch",
  url: `https://api.prisma.test/v1/branches/${id}`,
  gitName: id === "branch-main" ? "main" : id,
  isDefault: role === "production" && id === "branch-main",
  role,
  createdAt: "2026-01-01T00:00:00Z",
  updatedAt: "2026-01-01T00:00:00Z",
  project: {
    id: "project-1",
    url: "https://api.prisma.test/v1/projects/project-1",
    name: "project",
  },
});

const withDefaultBranch = <T extends object>(
  client: T,
  role: "production" | "preview" = "production",
): PrismaManagementClient => {
  const mock = client as Record<string, (...args: any[]) => any>;
  return {
    ...client,
    getBranch: (id: string) => mock.getBranch?.(id) ?? Effect.succeed(testBranch(id, role)),
    listBranches: (projectId: string, query?: { gitName?: string }) =>
      mock.listBranches?.(projectId, query) ?? Effect.succeed([testBranch("branch-main", role)]),
    listApps: (query: { projectId?: string; limit?: number }) =>
      mock.listApps?.length >= 2
        ? mock.listApps(query.projectId, { limit: query.limit })
        : mock.listApps?.(query),
    createApp: (input: { projectId: string } & Record<string, unknown>) => {
      if (mock.createApp?.length < 2) return mock.createApp(input);
      const { projectId, ...body } = input;
      return mock.createApp(projectId, body);
    },
    createAppDeployment: (appId: string, input: unknown) =>
      mock.createAppDeployment?.(appId, input),
    getDeployment: (id: string) => mock.getDeployment?.(id),
    startDeployment: (id: string) => mock.startDeployment?.(id),
    stopDeployment: (id: string) => mock.stopDeployment?.(id),
    deleteDeployment: (id: string) => mock.deleteDeployment?.(id),
    listAppDeployments: (appId: string, query: unknown) => mock.listAppDeployments?.(appId, query),
    promoteApp: (appId: string, target: { deploymentId: string }) => mock.promoteApp(appId, target),
    rollbackApp: (appId: string, target: { deploymentId: string }) =>
      mock.rollbackApp?.(appId, target),
  } as unknown as PrismaManagementClient;
};

const fixtureArtifactPath = `${import.meta.dirname}/fixtures/artifact-archive.bin`;
const fixtureArtifactV1Path = `${import.meta.dirname}/fixtures/artifact-v1.bin`;
const fixtureArtifactV2Path = `${import.meta.dirname}/fixtures/artifact-v2.bin`;

const readHttpBodyBytes = Effect.fn(function* (body: HttpBody.HttpBody) {
  if (body._tag === "Uint8Array") return body.body;
  if (body._tag !== "Stream") return new Uint8Array();
  const chunks = yield* Stream.runCollect(body.stream).pipe(Effect.orDie);
  const output = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
  let offset = 0;
  for (const chunk of chunks) {
    output.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return output;
});

const readTarString = (buffer: Uint8Array, start: number, length: number) => {
  const bytes = buffer.slice(start, start + length);
  const end = bytes.indexOf(0);
  return new TextDecoder().decode(end >= 0 ? bytes.slice(0, end) : bytes);
};

const readTarFile = (buffer: Uint8Array, expectedName: string) => {
  let offset = 0;
  while (offset + 512 <= buffer.length) {
    const header = buffer.slice(offset, offset + 512);
    if (header.every((byte) => byte === 0)) break;
    const name = readTarString(header, 0, 100);
    const prefix = readTarString(header, 345, 155);
    const fullName = prefix ? `${prefix}/${name}` : name;
    const size = Number.parseInt(readTarString(header, 124, 12).trim() || "0", 8);
    const bodyStart = offset + 512;
    if (fullName === expectedName) {
      return new TextDecoder().decode(buffer.slice(bodyStart, bodyStart + size));
    }
    offset = bodyStart + size + ((512 - (size % 512)) % 512);
  }
  throw new Error(`Missing tar entry '${expectedName}'.`);
};

const httpBodyContentType = (body: HttpBody.HttpBody) =>
  body._tag === "Uint8Array" || body._tag === "Stream" ? body.contentType : undefined;

const makeHealthLifecycleFixture = (options?: {
  latestDeploymentId?: string | null;
  previewStatus?: number;
  stableStatus?: number;
  rollbackFailures?: number;
  getAppFailureCalls?: readonly number[];
  promoteUpdatesLatest?: boolean;
  rollbackUpdatesLatest?: boolean;
}) => {
  const calls: Array<[string, unknown?]> = [];
  const deployments = new Map<string, "new" | "running" | "provisioning" | "stopped" | "failed">([
    ["version-old", "running"],
  ]);
  let deploymentCounter = 0;
  let previewStatus = options?.previewStatus ?? 204;
  let stableStatus = options?.stableStatus ?? 204;
  let rollbackFailuresRemaining = options?.rollbackFailures ?? 0;
  let getAppCalls = 0;
  let latestDeploymentId =
    options?.latestDeploymentId === undefined ? "version-old" : options.latestDeploymentId;

  const app = () => ({
    id: "service-1",
    type: "app" as const,
    url: "https://api.prisma.test/v1/services/service-1",
    name: "api",
    region: { id: "us-east-1", name: "US East" },
    projectId: "project-1",
    branchId: "branch-main",
    latestDeploymentId,
    appEndpointDomain: "api.prisma.build",
    createdAt: "2026-01-01T00:00:00Z",
  });
  const client = {
    getApp: (id: string) => {
      getAppCalls += 1;
      calls.push(["getApp", id]);
      if (options?.getAppFailureCalls?.includes(getAppCalls)) {
        return Effect.fail(
          new PrismaApiError({
            method: "GET",
            path: `/v1/services/${id}`,
            // Non-transient on purpose: a 5xx would be replayed by the
            // retry policy.
            status: 400,
            message: "app observation unavailable",
          }),
        );
      }
      return Effect.succeed(app());
    },
    createAppDeployment: (appId: string, input: unknown) => {
      calls.push(["createAppDeployment", { appId, input }]);
      deploymentCounter += 1;
      const deploymentId =
        deploymentCounter === 1 ? "version-new" : `version-new-${deploymentCounter}`;
      deployments.set(deploymentId, "new");
      return Effect.succeed({
        id: deploymentId,
        type: "deployment" as const,
        url: `https://api.prisma.test/v1/deployments/${deploymentId}`,
        foundryVersionId: `foundry-${deploymentId}`,
        uploadUrl: `https://upload.prisma.test/${deploymentId}.tar.gz`,
      });
    },
    getDeployment: (id: string) => {
      calls.push(["getDeployment", id]);
      const status = deployments.get(id);
      return status
        ? Effect.succeed({
            id,
            type: "deployment" as const,
            serviceId: "service-1",
            url: `https://api.prisma.test/v1/deployments/${id}`,
            foundryVersionId: `foundry-${id}`,
            status,
            previewDomain: `${id}.preview.prisma.build`,
            createdAt: "2026-01-01T00:00:00Z",
          })
        : Effect.fail(
            new PrismaApiError({
              method: "GET",
              path: `/v1/deployments/${id}`,
              status: 404,
              message: "not found",
            }),
          );
    },
    startDeployment: (id: string) =>
      Effect.sync(() => {
        calls.push(["startDeployment", id]);
        deployments.set(id, "running");
        return { previewDomain: `${id}.preview.prisma.build` };
      }),
    promoteApp: (appId: string, target: { deploymentId: string }) =>
      Effect.sync(() => {
        calls.push(["promoteApp", { appId, ...target }]);
        if (options?.promoteUpdatesLatest !== false) {
          latestDeploymentId = target.deploymentId;
        }
        return { appEndpointDomain: "api.prisma.build", reassignedDomains: 0 };
      }),
    rollbackApp: (appId: string, target: { deploymentId: string }) =>
      Effect.gen(function* () {
        calls.push(["rollbackApp", { appId, ...target }]);
        if (rollbackFailuresRemaining > 0) {
          rollbackFailuresRemaining -= 1;
          return yield* Effect.fail(
            new PrismaApiError({
              method: "POST",
              path: `/v1/services/${appId}/rollback`,
              status: 400,
              message: "rollback unavailable",
            }),
          );
        }
        if (options?.rollbackUpdatesLatest !== false) {
          latestDeploymentId = target.deploymentId;
        }
        return { appEndpointDomain: "api.prisma.build", reassignedDomains: 0 };
      }),
    stopDeployment: (id: string) =>
      Effect.sync(() => {
        calls.push(["stopDeployment", id]);
        deployments.set(id, "stopped");
      }),
    deleteDeployment: (id: string) =>
      Effect.sync(() => {
        calls.push(["deleteDeployment", id]);
        deployments.delete(id);
      }),
  } as unknown as PrismaManagementClient;
  const http = HttpClient.make((request) => {
    if (request.url.startsWith("https://upload.prisma.test/")) {
      calls.push(["upload", request.url]);
      return readHttpBodyBytes(request.body as HttpBody.HttpBody).pipe(
        Effect.as(HttpClientResponse.fromWeb(request, new Response(null))),
      );
    }
    calls.push(["healthRequest", request.url]);
    return Effect.succeed(
      HttpClientResponse.fromWeb(
        request,
        new Response(null, {
          status: new URL(request.url).hostname.endsWith(".preview.prisma.build")
            ? previewStatus
            : stableStatus,
        }),
      ),
    );
  });

  return {
    calls,
    client,
    http,
    hasDeployment: (id: string) => deployments.has(id),
    latestDeploymentId: () => latestDeploymentId,
    setPreviewStatus: (status: number) => {
      previewStatus = status;
    },
    setStableStatus: (status: number) => {
      stableStatus = status;
    },
    setDeploymentStatus: (
      id: string,
      status: "new" | "running" | "provisioning" | "stopped" | "failed",
    ) => {
      deployments.set(id, status);
    },
  };
};

const liveProviderContext = Layer.succeed(AlchemyContext, {
  dotAlchemy: ".alchemy-test",
  dev: false,
  adopt: false,
});

const computeProviderLive = () =>
  ComputeProvider().pipe(
    Layer.provide(Layer.mergeAll(liveProviderContext, testStackContext, PlatformServices)),
  );

/**
 * Serve the Management API from the same hermetic client-shaped handlers this
 * suite declares, for the routes Compute now reaches through distilled
 * operations. `dispatchTo` maps each handler's result onto the wire (see the
 * fixture). The log tail still resolves the hand-rolled client, so the
 * `PrismaClient` layer stays provided alongside.
 */
const dispatchManagement = (client: any, request: Captured): Response => {
  const [head, id, tail] = request.pathname
    .split("/")
    .filter((segment) => segment.length > 0)
    .slice(1);
  const body = request.bodyJson as any;
  const query = Object.fromEntries(new URLSearchParams(request.search));
  const { call, callVoid, list } = dispatchTo(request);

  if (head === "services") {
    if (id === undefined) {
      return request.method === "GET"
        ? call(client.listApps, [query], list)
        : call(client.createApp, [body]);
    }
    if (tail === "deployments") {
      return request.method === "GET"
        ? call(client.listAppDeployments, [id, query], list)
        : call(client.createAppDeployment, [id, body]);
    }
    if (tail === "promote") return call(client.promoteApp, [id, body]);
    if (tail === "rollback") return call(client.rollbackApp, [id, body]);
    if (tail === undefined) {
      if (request.method === "GET") return call(client.getApp, [id]);
      if (request.method === "PATCH") return call(client.updateApp, [id, body]);
      if (request.method === "DELETE") {
        return callVoid(client.deleteApp, [id]);
      }
    }
  }
  if (head === "branches" && id !== undefined && request.method === "GET") {
    return call(client.getBranch, [id]);
  }
  if (head === "projects" && id !== undefined) {
    if (tail === "branches" && request.method === "GET") {
      return call(client.listBranches, [id, query], list);
    }
    if (tail === undefined && request.method === "DELETE") {
      return callVoid(client.deleteProject, [id]);
    }
  }
  if (head === "deployments" && id !== undefined) {
    if (tail === "start") return call(client.startDeployment, [id]);
    if (tail === "stop") {
      return callVoid(client.stopDeployment, [id]);
    }
    if (request.method === "GET") return call(client.getDeployment, [id]);
    if (request.method === "DELETE") {
      return callVoid(client.deleteDeployment, [id]);
    }
  }
  if (head === "environment-variables") {
    if (id === undefined) {
      return request.method === "GET"
        ? call(client.listEnvironmentVariables, [query], list)
        : call(client.createEnvironmentVariable, [body]);
    }
    if (request.method === "GET") {
      return call(client.getEnvironmentVariable, [id]);
    }
    if (request.method === "PATCH") {
      return call(client.updateEnvironmentVariable, [id, body]);
    }
    if (request.method === "DELETE") {
      return callVoid(client.deleteEnvironmentVariable, [id]);
    }
  }
  return unhandled(request);
};

/**
 * Ambient HTTP for a Compute test: Management API requests dispatch to the
 * client-shaped handlers; anything else (uploads, health probes) falls back
 * to the HttpClient provided beneath this layer, when there is one.
 */
const apiRoutedHttp = (client: any) =>
  Layer.mergeAll(
    Layer.effect(
      HttpClient.HttpClient,
      Effect.gen(function* () {
        const fallback = yield* Effect.serviceOption(HttpClient.HttpClient);
        return HttpClient.make((request) => {
          if (!request.url.startsWith(FAKE_API_BASE_URL)) {
            return Option.isSome(fallback)
              ? fallback.value.execute(request)
              : Effect.sync(() =>
                  HttpClientResponse.fromWeb(
                    request,
                    unhandled({
                      url: request.url,
                      method: request.method,
                      pathname: new URL(request.url).pathname,
                      search: "",
                      authorization: undefined,
                      bodyJson: undefined,
                    }),
                  ),
                );
          }
          return Effect.sync(() => {
            const url = new URL(request.url);
            const body = request.body as HttpBody.HttpBody;
            const bodyText = body._tag === "Uint8Array" ? new TextDecoder().decode(body.body) : "";
            return HttpClientResponse.fromWeb(
              request,
              dispatchManagement(client, {
                url: request.url,
                method: request.method,
                pathname: url.pathname,
                search: url.search,
                authorization: request.headers.authorization,
                bodyJson: bodyText ? JSON.parse(bodyText) : undefined,
              }),
            );
          });
        });
      }),
    ),
    fromApiToken({ apiToken: Redacted.make("fake-service-token"), apiBaseUrl: FAKE_API_BASE_URL }),
  );

describe(
  "Prisma Compute",
  { tags: ["unit", "provider:prisma", "provider:prisma:compute", "local"] },
  () => {
    it.live("accepts a streaming 200 response without consuming its body", () => {
      const body = new ReadableStream<Uint8Array>({
        pull() {
          // Deliberately never enqueue or close. Reading this body would hang.
        },
      });
      const http = HttpClient.make((request) =>
        Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body, { status: 200 }))),
      );

      return waitForDeploymentUrl("https://app.prisma.build", {
        project: "project-1",
        appName: "api",
        urlReadinessTimeoutSeconds: 0.05,
      }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)));
    });

    it.live("waits for the configured application health contract", () => {
      const requests: string[] = [];
      const http = HttpClient.make((request) => {
        requests.push(request.url);
        return Effect.succeed(
          HttpClientResponse.fromWeb(
            request,
            new Response(null, { status: requests.length === 1 ? 503 : 204 }),
          ),
        );
      });

      return Effect.gen(function* () {
        yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "/api/health" },
          pollIntervalMs: 1,
          // Wall-clock deadline (live clock). The mock succeeds on the second
          // poll, so the pass path never waits this long — it only needs to
          // not fire spuriously when a saturated event loop (full-suite run)
          // delays the second poll beyond a tight budget.
          urlReadinessTimeoutSeconds: 30,
        });

        expect(requests).toEqual([
          "https://app.prisma.build/api/health",
          "https://app.prisma.build/api/health",
        ]);
      }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)));
    });

    it.effect("rejects unsafe application health contracts", () =>
      Effect.gen(function* () {
        const pathError = yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "//attacker.example/health" },
        }).pipe(Effect.flip);
        const statusError = yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "/health", statusCodes: [] },
        }).pipe(Effect.flip);

        expect(pathError.message).toContain("healthCheck.path");
        expect(statusError.message).toContain("healthCheck.statusCodes");
      }),
    );

    it.effect("fails closed when an application health probe cannot run", () =>
      Effect.gen(function* () {
        const props = {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "/health" },
        } as const;
        const missingUrl = yield* waitForDeploymentUrl(undefined, props).pipe(Effect.flip);
        const missingRoutingUrl = yield* waitForDeploymentUrl(undefined, {
          project: "project-1",
          appName: "api",
        }).pipe(Effect.flip);
        const disabled = yield* waitForDeploymentUrl("https://app.prisma.build", {
          ...props,
          verifyUrl: false,
        }).pipe(Effect.flip);
        const missingClient = yield* waitForDeploymentUrl("https://app.prisma.build", props).pipe(
          Effect.flip,
        );

        expect(missingUrl.message).toContain("did not return");
        expect(missingRoutingUrl.message).toContain("readiness verification");
        expect(disabled.message).toContain("verifyUrl: false");
        expect(missingClient.message).toContain("HTTP client");
      }),
    );

    it.live("observes health redirects without following them", () => {
      const redirects: RequestRedirect[] = [];
      const fetch = (async (
        _input: Parameters<typeof globalThis.fetch>[0],
        init?: Parameters<typeof globalThis.fetch>[1],
      ) => {
        redirects.push(init?.redirect ?? "follow");
        return init?.redirect === "manual"
          ? new Response(null, { status: 302, headers: { location: "https://attacker.example/" } })
          : new Response(null, { status: 200 });
      }) as typeof globalThis.fetch;

      return Effect.gen(function* () {
        yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "/health", statusCodes: [302] },
          pollIntervalMs: 1,
          urlReadinessTimeoutSeconds: 0.05,
        });
        const defaultStatusError = yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          healthCheck: { path: "/health" },
          pollIntervalMs: 1,
          urlReadinessTimeoutSeconds: 0.01,
        }).pipe(Effect.flip);

        expect(redirects.length).toBeGreaterThanOrEqual(2);
        expect(redirects.every((redirect) => redirect === "manual")).toBe(true);
        expect(defaultStatusError.message).toContain("HTTP 302");
      }).pipe(
        Effect.provide(FetchHttpClient.layer),
        Effect.provideService(FetchHttpClient.Fetch, fetch),
      );
    });

    it.live("enforces one deadline for stalled requests and 404 bodies", () => {
      const stalledRequest = HttpClient.make(() => Effect.never);
      const stalledBody = HttpClient.make((request) =>
        Effect.succeed(
          HttpClientResponse.fromWeb(
            request,
            new Response(
              new ReadableStream<Uint8Array>({
                pull() {
                  // Deliberately never enqueue or close.
                },
              }),
              { status: 404 },
            ),
          ),
        ),
      );
      const props = {
        project: "project-1",
        appName: "api",
        pollIntervalMs: 1,
        urlReadinessTimeoutSeconds: 0.03,
      } as const;

      return Effect.gen(function* () {
        const requestError = yield* waitForDeploymentUrl(
          "https://request.prisma.build",
          props,
        ).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, stalledRequest)), Effect.flip);
        const bodyError = yield* waitForDeploymentUrl("https://body.prisma.build", props).pipe(
          Effect.provide(Layer.succeed(HttpClient.HttpClient, stalledBody)),
          Effect.flip,
        );

        expect(requestError.message).toContain("Timed out");
        expect(bodyError.message).toContain("Timed out");
      });
    });

    it.live("bounds the inspected prefix of a large Prisma edge 404", () => {
      let requests = 0;
      const hugeBody = `${"There is no service on this URL"}${"x".repeat(256 * 1024)}`;
      const http = HttpClient.make((request) => {
        requests += 1;
        return requests === 1
          ? Effect.succeed(
              HttpClientResponse.fromWeb(request, new Response(hugeBody, { status: 404 })),
            )
          : Effect.never;
      });

      return Effect.gen(function* () {
        const error = yield* waitForDeploymentUrl("https://missing.prisma.build", {
          project: "project-1",
          appName: "api",
          pollIntervalMs: 1,
          urlReadinessTimeoutSeconds: 0.05,
        }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)), Effect.flip);

        expect(error.message).toContain("There is no service on this URL");
        expect(requests).toBeGreaterThanOrEqual(1);
      });
    });

    it.effect("rejects invalid URL readiness timings before making a request", () => {
      const http = HttpClient.make(() => Effect.die("invalid readiness options must fail first"));

      return Effect.gen(function* () {
        const error = yield* waitForDeploymentUrl("https://app.prisma.build", {
          project: "project-1",
          appName: "api",
          pollIntervalMs: 0,
        }).pipe(Effect.provide(Layer.succeed(HttpClient.HttpClient, http)), Effect.flip);

        expect(error.message).toContain("pollIntervalMs");
      });
    });
    it.effect(
      "rejects destroyOldDeployment when promotion is skipped",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: {
                project: "project-1",
                appName: "api",
                skipPromote: true,
                destroyOldDeployment: true,
              },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain(
            "destroyOldDeployment cannot be combined with skipPromote",
          );
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect("rejects a health check when deployment start is disabled", () => {
      const client = {} as PrismaManagementClient;

      return Effect.gen(function* () {
        const provider = yield* Compute.Provider;
        const error = yield* provider
          .reconcile({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            news: {
              project: "project-1",
              appName: "api",
              start: false,
              skipPromote: true,
              healthCheck: { path: "/health" },
            },
            olds: undefined,
            output: undefined,
            session: undefined as never,
            bindings: [],
          })
          .pipe(Effect.flip);

        expect(error.message).toContain("healthCheck requires start");
      }).pipe(
        Effect.provide(computeProviderLive()),
        Effect.provide(Layer.succeed(PrismaClient, client)),
        Effect.provide(apiRoutedHttp(client)),
        Effect.provide(PlatformServices),
      );
    });

    it.effect(
      "rejects disabled start when promotion is enabled",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: { project: "project-1", appName: "api", start: false },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain("start: false requires skipPromote: true");
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects conflicting branch attachment inputs",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: {
                project: "project-1",
                appName: "api",
                branchId: "branch-1",
                branchGitName: "main",
              },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain("branchId and branchGitName are mutually exclusive");
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects invalid production and dev ports",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          for (const props of [
            { port: 0 },
            { port: 65_536 },
            { port: 1.5 },
            { dev: { port: Number.NaN } },
          ]) {
            const error = yield* provider
              .reconcile({
                id: "App",
                fqn: "App",
                instanceId: "00000000000000000000000000000000",
                news: { project: "project-1", appName: "api", ...props },
                olds: undefined,
                output: undefined,
                session: undefined as never,
                bindings: [],
              })
              .pipe(Effect.flip);
            expect(error.message).toContain("must be an integer between 1 and 65535");
          }
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects unassigned branch attachment for Compute deploys",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          for (const branchProps of [{ branchId: null }, { branchGitName: null }]) {
            const error = yield* provider
              .reconcile({
                id: "App",
                fqn: "App",
                instanceId: "00000000000000000000000000000000",
                news: {
                  project: "project-1",
                  appName: "api",
                  ...branchProps,
                } as unknown as ComputeProps,
                olds: undefined,
                output: undefined,
                session: undefined as never,
                bindings: [],
              })
              .pipe(Effect.flip);

            expect(error).toBeInstanceOf(Error);
            expect(error.message).toContain("requires an attached branch");
          }
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects skipCodeUpload without a version to fork",
      () => {
        const calls: Array<[string, unknown]> = [];
        const client = {
          getApp: (id: string) => {
            calls.push(["getApp", id]);
            return Effect.succeed({
              id,
              type: "app" as const,
              url: `https://api.prisma.test/v1/services/${id}`,
              name: "api",
              region: { id: "us-east-1", name: "US East" },
              projectId: "project-1",
              branchId: "branch-main",
              latestDeploymentId: null,
              appEndpointDomain: "api.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
        } as unknown as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: {
                project: "project-1",
                appName: "api",
                branchId: "branch-main",
                skipCodeUpload: true,
                start: false,
                skipPromote: true,
              },
              olds: undefined,
              output: {
                appId: "service-1",
                deploymentId: undefined,
                projectId: "project-1",
                appName: "api",
                regionId: "us-east-1",
                deploymentEndpointDomain: undefined,
                deploymentUrl: undefined,
                appEndpointDomain: "api.prisma.build",
                url: "https://api.prisma.build",
                promoted: false,
                previousDeploymentId: undefined,
                previousDeploymentAction: undefined,
                artifactHash: undefined,
                local: false,
              },
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain("skipCodeUpload requires an existing Prisma deployment");
          expect(calls).toEqual([["getApp", "service-1"]]);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects effect-native Compute without a main module",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: { project: "project-1", appName: "api", exports: { default: "runtime" } },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain("Effect-native Prisma Compute apps require `main`");
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects effect-native Compute with an external build",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: {
                project: "project-1",
                appName: "api",
                main: "app.ts",
                build: { command: "bun run build", outdir: "dist" },
              },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain("Effect-native Prisma Compute apps cannot use build");
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "rejects effect-native Compute with an invalid handler name",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider
            .reconcile({
              id: "App",
              fqn: "App",
              instanceId: "00000000000000000000000000000000",
              news: {
                project: "project-1",
                appName: "api",
                main: "app.ts",
                handler: "Api;console.log('nope')",
              },
              olds: undefined,
              output: undefined,
              session: undefined as never,
              bindings: [],
            })
            .pipe(Effect.flip);

          expect(error).toBeInstanceOf(Error);
          expect(error.message).toContain(
            "handler must be `default` or a valid JavaScript export identifier",
          );
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "replaces Compute when region changes even if project is unresolved",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const error = yield* provider.diff!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: { project: "project-1", appName: "api", regionId: "us-east-1" },
            news: { project: Output.asOutput("project-1"), appName: "api", regionId: "us-west-2" },
            oldBindings: [],
            newBindings: [],
            output: {
              appId: "service-1",
              deploymentId: "version-1",
              projectId: "project-1",
              appName: "api",
              regionId: "us-east-1",
              deploymentEndpointDomain: "version-1.preview.prisma.build",
              deploymentUrl: "https://version-1.preview.prisma.build",
              appEndpointDomain: "api.prisma.build",
              url: "https://api.prisma.build",
              promoted: true,
              previousDeploymentId: undefined,
              previousDeploymentAction: undefined,
              artifactHash: Redacted.make("hash-1"),
              local: false,
            },
          } as never).pipe(Effect.flip);

          expect(String(error)).toContain("cannot be changed atomically");
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "replaces Compute when project changes even if region is unresolved",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const diff = yield* provider.diff!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: { project: "project-1", appName: "api", regionId: "us-east-1" },
            news: { project: "project-2", appName: "api", regionId: Output.asOutput("us-east-1") },
            oldBindings: [],
            newBindings: [],
            output: {
              appId: "service-1",
              deploymentId: "version-1",
              projectId: "project-1",
              appName: "api",
              regionId: "us-east-1",
              deploymentEndpointDomain: "version-1.preview.prisma.build",
              deploymentUrl: "https://version-1.preview.prisma.build",
              appEndpointDomain: "api.prisma.build",
              url: "https://api.prisma.build",
              promoted: true,
              previousDeploymentId: undefined,
              previousDeploymentAction: undefined,
              artifactHash: Redacted.make("hash-1"),
              local: false,
            },
          } as never);

          expect(diff).toEqual({ action: "replace" });
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "updates Compute when props are unchanged so artifacts can rehash",
      () => {
        const client = {} as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const diff = yield* provider.diff!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: {
              project: "project-1",
              appName: "api",
              regionId: "us-east-1",
              path: ".",
              entrypoint: "server.ts",
            },
            news: {
              project: "project-1",
              appName: "api",
              regionId: "us-east-1",
              path: ".",
              entrypoint: "server.ts",
            },
            oldBindings: [],
            newBindings: [],
            output: {
              appId: "service-1",
              deploymentId: "version-1",
              projectId: "project-1",
              appName: "api",
              regionId: "us-east-1",
              deploymentEndpointDomain: "version-1.preview.prisma.build",
              deploymentUrl: "https://version-1.preview.prisma.build",
              appEndpointDomain: "api.prisma.build",
              url: "https://api.prisma.build",
              promoted: true,
              previousDeploymentId: undefined,
              previousDeploymentAction: undefined,
              artifactHash: Redacted.make("hash-1"),
              local: false,
            },
          } as never);

          expect(diff).toEqual({ action: "update" });
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect("dev provider applies the same Compute prop validation", () =>
      Effect.gen(function* () {
        const provider = yield* Compute.Provider;
        const error = yield* provider
          .reconcile({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            news: {
              project: "project-1",
              appName: "api",
              skipPromote: true,
              destroyOldDeployment: true,
              dev: { url: "http://localhost:3000" },
            },
            olds: undefined,
            output: undefined,
            session: undefined as never,
            bindings: [],
          })
          .pipe(Effect.flip);

        expect(error).toBeInstanceOf(Error);
        expect(error.message).toContain("destroyOldDeployment cannot be combined with skipPromote");
      }).pipe(
        Effect.provide(ComputeDevProvider()),
        Effect.provide(
          Layer.succeed(AlchemyContext, { dotAlchemy: ".alchemy", dev: true, adopt: false }),
        ),
        Effect.provide(PlatformServices),
      ),
    );

    it.effect(
      "adopts only the matching branch's latest deployment as Unowned",
      () => {
        const calls: Array<[string, unknown]> = [];
        const client = {
          listApps: (projectId: string, query: unknown) => {
            calls.push(["listApps", { projectId, query }]);
            return Effect.succeed([
              {
                id: "service-1",
                type: "app" as const,
                url: "https://api.prisma.test/v1/services/service-1",
                name: "api",
                region: { id: "us-east-1", name: "US East" },
                projectId,
                branchId: "branch-main",
                latestDeploymentId: "version-live",
                appEndpointDomain: "api.prisma.build",
                createdAt: "2026-01-01T00:00:00Z",
              },
              {
                id: "service-feature",
                type: "app" as const,
                url: "https://api.prisma.test/v1/services/service-feature",
                name: "api",
                region: { id: "us-east-1", name: "US East" },
                projectId,
                branchId: "branch-feature",
                latestDeploymentId: "version-feature",
                appEndpointDomain: "feature.prisma.build",
                createdAt: "2026-01-01T00:00:00Z",
              },
            ]);
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              serviceId: "service-1",
              url: `https://api.prisma.test/v1/deployments/${id}`,
              foundryVersionId: "foundry-live",
              status: "running",
              previewDomain: "version-live.preview.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          listAppDeployments: () =>
            Effect.succeed([
              {
                id: "version-old",
                type: "deployment" as const,
                serviceId: "service-1",
                url: "https://api.prisma.test/v1/deployments/version-old",
                foundryVersionId: "foundry-version-old",
                createdAt: "2026-01-01T00:00:00Z",
              },
            ]),
        } as unknown as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Provider.findProvider(Compute);
          const output = yield* provider.read!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: { project: "project-1", appName: "api" },
            output: undefined,
          });

          expect(output?.appId).toBe("service-1");
          expect(output?.deploymentId).toBe("version-live");
          expect(output?.deploymentEndpointDomain).toBe("version-live.preview.prisma.build");
          expect(output?.deploymentUrl).toBe("https://version-live.preview.prisma.build");
          expect(output?.appEndpointDomain).toBe("api.prisma.build");
          expect(output?.url).toBe("https://api.prisma.build");
          expect(output?.promoted).toBe(true);
          expect(Unowned.is(output!)).toBe(true);
          expect(calls).toEqual([
            ["listApps", { projectId: "project-1", query: { limit: "100" } }],
            ["getDeployment", "version-live"],
          ]);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
          Effect.provide(FetchHttpClient.layer),
          Effect.provide(PlatformServices),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "reads the live deployment through the canonical route",
      () => {
        const calls: Array<[string, unknown]> = [];
        const client = {
          listApps: (projectId: string, query: unknown) => {
            calls.push(["listApps", { projectId, query }]);
            return Effect.succeed([
              {
                id: "service-1",
                type: "app" as const,
                url: "https://api.prisma.test/v1/services/service-1",
                name: "api",
                region: { id: "us-east-1", name: "US East" },
                projectId,
                branchId: "branch-main",
                latestDeploymentId: "version-live",
                appEndpointDomain: "api.prisma.build",
                createdAt: "2026-01-01T00:00:00Z",
              },
            ]);
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              serviceId: "service-1",
              url: `https://api.prisma.test/v1/deployments/${id}`,
              foundryVersionId: "foundry-live",
              status: "running",
              previewDomain: "version-live.preview.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
        } as unknown as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Provider.findProvider(Compute);
          const output = yield* provider.read!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: { project: "project-1", appName: "api" },
            output: undefined,
          });

          expect(output?.deploymentId).toBe("version-live");
          expect(output?.promoted).toBe(true);
          expect(output?.deploymentUrl).toBe("https://version-live.preview.prisma.build");
          expect(calls).toEqual([
            ["listApps", { projectId: "project-1", query: { limit: "100" } }],
            ["getDeployment", "version-live"],
          ]);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
          Effect.provide(FetchHttpClient.layer),
          Effect.provide(PlatformServices),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "marks stored deployment unpromoted when live latest differs",
      () => {
        const calls: Array<[string, unknown]> = [];
        const client = {
          getApp: (id: string) => {
            calls.push(["getApp", id]);
            return Effect.succeed({
              id,
              type: "app" as const,
              url: "https://api.prisma.test/v1/services/service-1",
              name: "api",
              region: { id: "us-east-1", name: "US East" },
              projectId: "project-1",
              branchId: "branch-main",
              latestDeploymentId: "version-live",
              appEndpointDomain: "api.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              serviceId: "service-1",
              url: `https://api.prisma.test/v1/deployments/${id}`,
              foundryVersionId: `foundry-${id}`,
              status: "running",
              previewDomain: `${id}.preview.prisma.build`,
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          listAppDeployments: () =>
            Effect.succeed([
              {
                id: "version-old",
                type: "deployment" as const,
                serviceId: "service-1",
                url: "https://api.prisma.test/v1/deployments/version-old",
                foundryVersionId: "foundry-version-old",
                createdAt: "2026-01-01T00:00:00Z",
              },
            ]),
        } as unknown as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Provider.findProvider(Compute);
          const output = yield* provider.read!({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            olds: { project: "project-1", appName: "api" },
            output: {
              appId: "service-1",
              deploymentId: "version-old",
              projectId: "project-1",
              appName: "api",
              regionId: "us-east-1",
              deploymentEndpointDomain: "version-old.preview.prisma.build",
              deploymentUrl: "https://version-old.preview.prisma.build",
              appEndpointDomain: "api.prisma.build",
              url: "https://api.prisma.build",
              promoted: true,
              previousDeploymentId: undefined,
              previousDeploymentAction: undefined,
              artifactHash: Redacted.make("hash-old"),
              local: false,
            },
          });

          expect(output?.deploymentId).toBe("version-old");
          expect(output?.promoted).toBe(false);
          expect(output?.deploymentEndpointDomain).toBe("version-old.preview.prisma.build");
          expect(output?.url).toBe("https://version-old.preview.prisma.build");
          expect(calls).toEqual([
            ["getApp", "service-1"],
            ["getDeployment", "version-old"],
          ]);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
          Effect.provide(FetchHttpClient.layer),
          Effect.provide(PlatformServices),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "returns the preview URL for unpromoted Compute deploys",
      () => {
        const calls: Array<[string, unknown?]> = [];
        let status = "new";
        const client = {
          getApp: (id: string) => {
            calls.push(["getApp", id]);
            return Effect.succeed({
              id,
              type: "app" as const,
              url: "https://api.prisma.test/v1/services/service-1",
              name: "api",
              region: { id: "us-east-1", name: "US East" },
              projectId: "project-1",
              branchId: "branch-main",
              latestDeploymentId: "version-live",
              appEndpointDomain: "api.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          listEnvironmentVariables: () => Effect.succeed([]),
          createAppDeployment: (appId: string, input: unknown) => {
            calls.push(["createAppDeployment", { appId, input }]);
            return Effect.succeed({
              id: "version-new",
              type: "deployment" as const,
              url: "https://api.prisma.test/v1/deployments/version-new",
              foundryVersionId: "foundry-new",
              uploadUrl: null,
            });
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              serviceId: "service-1",
              url: `https://api.prisma.test/v1/deployments/${id}`,
              foundryVersionId: `foundry-${id}`,
              status,
              previewDomain: "version-new.preview.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          startDeployment: (id: string) =>
            Effect.sync(() => {
              calls.push(["startDeployment", id]);
              status = "running";
              return { previewDomain: "version-new.preview.prisma.build" };
            }),
        } as unknown as PrismaManagementClient;

        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const output = yield* provider.reconcile({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            news: {
              project: "project-1",
              appName: "api",
              branchId: "branch-main",
              skipCodeUpload: true,
              skipPromote: true,
              verifyUrl: false,
            },
            olds: undefined,
            output: {
              appId: "service-1",
              deploymentId: undefined,
              projectId: "project-1",
              appName: "api",
              regionId: "us-east-1",
              deploymentEndpointDomain: undefined,
              deploymentUrl: undefined,
              appEndpointDomain: "api.prisma.build",
              url: "https://api.prisma.build",
              promoted: true,
              previousDeploymentId: undefined,
              previousDeploymentAction: undefined,
              artifactHash: undefined,
              local: false,
            },
            session: undefined as never,
            bindings: [],
          });

          expect(output.promoted).toBe(false);
          expect(output.deploymentUrl).toBe("https://version-new.preview.prisma.build");
          expect(output.appEndpointDomain).toBe("api.prisma.build");
          expect(output.url).toBe("https://version-new.preview.prisma.build");
          expect(calls).toEqual([
            ["getApp", "service-1"],
            [
              "createAppDeployment",
              { appId: "service-1", input: { portMapping: { http: 8080 }, skipCodeUpload: true } },
            ],
            ["getDeployment", "version-new"],
            ["startDeployment", "version-new"],
            ["getDeployment", "version-new"],
          ]);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
          Effect.provide(FetchHttpClient.layer),
          Effect.provide(PlatformServices),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "syncs a newly created service branch before creating a version",
      () => {
        const calls: Array<[string, unknown]> = [];
        const client = {
          listApps: (projectId: string, query: unknown) => {
            calls.push(["listApps", { projectId, query }]);
            return Effect.succeed([]);
          },
          createApp: (projectId: string, input: unknown) => {
            calls.push(["createApp", { projectId, input }]);
            return Effect.succeed({
              id: "service-1",
              type: "app" as const,
              url: "https://api.prisma.test/v1/services/service-1",
              name: "api",
              region: { id: "us-east-1", name: "US East" },
              projectId,
              branchId: null,
              latestDeploymentId: null,
              appEndpointDomain: "api.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          updateApp: (id: string, input: unknown) => {
            calls.push(["updateApp", { id, input }]);
            return Effect.succeed({
              id,
              type: "app" as const,
              url: "https://api.prisma.test/v1/services/service-1",
              name: "api",
              region: { id: "us-east-1", name: "US East" },
              projectId: "project-1",
              branchId: "branch-main",
              latestDeploymentId: null,
              appEndpointDomain: "api.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
          createAppDeployment: (appId: string, input: unknown) => {
            calls.push(["createAppDeployment", { appId, input }]);
            return Effect.succeed({
              id: "version-1",
              type: "deployment" as const,
              url: "https://api.prisma.test/v1/deployments/version-1",
              foundryVersionId: "foundry-1",
              uploadUrl: "https://upload.prisma.test/version-1.tar.gz",
            });
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              serviceId: "service-1",
              url: "https://api.prisma.test/v1/deployments/version-1",
              foundryVersionId: "foundry-1",
              status: "new",
              previewDomain: "version-1.preview.prisma.build",
              createdAt: "2026-01-01T00:00:00Z",
            });
          },
        } as unknown as PrismaManagementClient;
        const http = HttpClient.make((request) =>
          Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null))),
        );
        return Effect.gen(function* () {
          const provider = yield* Compute.Provider;
          const output = yield* provider.reconcile({
            id: "App",
            fqn: "App",
            instanceId: "00000000000000000000000000000000",
            news: {
              project: "project-1",
              appName: "api",
              branchId: "branch-main",
              artifactPath: fixtureArtifactPath,
              start: false,
              skipPromote: true,
            },
            olds: undefined,
            output: undefined,
            session: undefined as never,
            bindings: [],
          });

          expect(output.appId).toBe("service-1");
          expect(output.deploymentId).toBe("version-1");
          expect(calls).toContainEqual([
            "createApp",
            {
              projectId: "project-1",
              input: {
                displayName: "api",
                regionId: undefined,
                branchId: "branch-main",
                branchGitName: undefined,
              },
            },
          ]);
          expect(calls).toContainEqual([
            "updateApp",
            {
              id: "service-1",
              input: { displayName: "api", branchId: "branch-main", branchGitName: undefined },
            },
          ]);
          const updateIndex = calls.findIndex(([name]) => name === "updateApp");
          const versionIndex = calls.findIndex(([name]) => name === "createAppDeployment");
          expect(updateIndex).toBeGreaterThan(-1);
          expect(versionIndex).toBeGreaterThan(updateIndex);
        }).pipe(
          Effect.provide(computeProviderLive()),
          Effect.provide(Layer.succeed(PrismaClient, withDefaultBranch(client))),
          Effect.provide(apiRoutedHttp(withDefaultBranch(client))),
          Effect.provide(Layer.succeed(HttpClient.HttpClient, http)),
          Effect.provide(PlatformServices),
        );
      },
      { tags: ["provider:prisma:branch"] },
    );

    it.effect(
      "creates a new version when branch attachment changes without artifact changes",
      () => {
        const calls: Array<[string, unknown]> = [];
        let branchId: string | null = "branch-main";
        let versionCounter = 0;

        const service = () => ({
          id: "service-1",
          type: "app" as const,
          url: "https://api.prisma.test/v1/services/service-1",
          name: "api",
          region: { id: "us-east-1", name: "US East" },
          projectId: "project-1",
          branchId,
          latestDeploymentId: "version-seed",
          appEndpointDomain: "api.prisma.build",
          createdAt: "2026-01-01T00:00:00Z",
        });

        const client = {
          getApp: (id: string) => {
            calls.push(["getApp", id]);
            return Effect.succeed(service());
          },
          updateApp: (id: string, input: { branchId?: string | null }) => {
            calls.push(["updateApp", { id, input }]);
            branchId = input.branchId ?? null;
            return Effect.succeed(service());
          },
          createAppDeployment: (appId: string, input: unknown) => {
            versionCounter += 1;
            const id = `version-${versionCounter}`;
            calls.push(["createAppDeployment", { appId, input, id }]);
            return Effect.succeed({
              id,
              type: "deployment" as const,
              url: `https://api.prisma.test/v1/deployments/${id}`,
              foundryVersionId: `foundry-${versionCounter}`,
              uploadUrl: null,
            });
          },
          getDeployment: (id: string) => {
            calls.push(["getDeployment", id]);
            return Effect.succeed({
              id,
              type: "deployment" as const,