import type { Server } from "bun";
import { z } from "zod";
import { Buffer } from "node:buffer";
import { open, realpath, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { isAbsolute, join, relative, resolve } from "node:path";
import { readBoundedBody, type ActionGateway } from "./actions";
import { defaultConfig, persistProjectColors, ProjectColorsPersistenceError, ProjectColorsSchema, type CollectorConfig } from "./config";
import { configFile } from "./paths";
import type { FetchLike } from "./adapter";
import {
  loadBuildboxRegistry,
  RegistryUnavailableError,
  type BuildboxRegistry,
} from "./buildbox-registry";
import { HarnessApiError, type HarnessAdapter } from "./adapters/harness";
import { buildDigest, type DigestResponse } from "./alerter";
import { CREDENTIAL_KEY, redactBrowserValue } from "./redact";
import {
  ClaudeCodeHookInputSchema,
  DEFAULT_WAIT_MS,
  PermissionRequestSchema,
  claudeCodeHookOutput,
  claudeCodeRequest,
  type PermissionQueue,
} from "./permissions";
import { readActivityCached } from "./activity/read";
import { ACTIVITY_ENTRIES_MAX_LIMIT, readActivitySourceEntries } from "./activity/entries";
import { ACTIVITY_SOURCE_IDS } from "./activity/registry";
import { type ActivityActor, type ActivityCategory, type ActivityReadOptions, type ActivitySeverity, type ActivitySourceEntriesOptions, ACTIVITY_SEVERITY_ORDER } from "./activity/types";
import { readSessionScreen } from "./sessions/screen";
import type { Panel } from "./schema";
import { FACTORY_PANEL_ID, type FactoryPanelData, type FactoryRunView } from "./adapters/factory";
import type { CollectorState, Delta } from "./state";
import { CollectorFatalError } from "./errors";
import { IncidentsUnavailableError, type IncidentsProvider } from "./incidents/provider";
import { IncidentIdempotencyConflictError, IncidentMutationError, IncidentResolutionConflictError } from "./incidents/incident-service";
import { assembleDispatchBrief, BriefAssemblyError, parseTaxonomy, type BriefDeps } from "./incidents/dispatch-brief";
import { createDeployAssetDeps, readDeployProvenance } from "./incidents/brief-assets";
import { IncidentOptionsError, InvalidIncidentDispatchError, InvalidIncidentTypeError, validateIncidentDispatchSelection, validateIncidentType, type LoadedIncidentOptions } from "./incidents/dispatch-options";
import { atomicWriteRoutingConfig, defaultRoutingRuntimeDir, readRoutingConfig, RoutingProviderSchema } from "./routing-config";
import { inventoryHooks, type HookInventoryOptions } from "./hooks-inventory";
import { CLUSTER_PANEL_ID, type ClusterSnapshot } from "./adapters/kubernetes";
import { HookControlsError, isRegisteredHookControl, readHookControls, repairHookControls, setHookControl } from "./hook-controls";

export type FactoryDetailWorkerResult =
  | { status: "ok"; body: string }
  | { status: "missing" }
  | { status: "too-large" };

export interface ServerOptions {
  host: string;
  port: number;
  token: string;
  state: CollectorState;
  actionGateway?: ActionGateway;
  permissions?: PermissionQueue;
  harness?: HarnessAdapter;
  incidents?: IncidentsProvider;
  digestTimeZone?: string;
  controllerUrl?: string;
  controllerToken?: string;
  fetcher?: FetchLike;
  /** Registry gate for controller-backed host requests. Injectable for tests. */
  loadBuildboxRegistry?: () => Promise<BuildboxRegistry>;
  /** Loads and serializes one Factory run outside the server event loop. */
  loadFactoryRunDetail?: (adwId: string, signal: AbortSignal) => Promise<FactoryDetailWorkerResult>;
  factoryDataDir?: string;
  routingRuntimeDir?: string;
  hookInventoryOptions?: HookInventoryOptions;
  /** Hook-control configuration root. Injectable for isolated tests. */
  hookControlsConfigDirectory?: string;
  /** Deployed incident-brief assets. Injectable for tests. */
  incidentBriefAssets?: BriefDeps;
  incidentBriefProvenance?: () => string;
  loadIncidentOptions?: () => Promise<LoadedIncidentOptions>;
  /** Running configuration and its backing file, injectable for isolated tests. */
  config?: CollectorConfig;
  configPath?: string;
}

const MAX_FACTORY_ARTIFACT_BYTES = 1024 * 1024;
const MAX_FACTORY_RUN_DETAIL_BYTES = 8 * 1024 * 1024;
const MAX_INCIDENT_BODY_BYTES = 64 * 1024;

const FileIncidentRequestSchema = z.object({
  requestId: z.string().uuid(),
  title: z.string().trim().min(1).max(160),
  description: z.string().trim().min(1).max(20_000),
  cli: z.string().trim().min(1).max(80),
  model: z.string().trim().min(1).max(160),
  reasoningEffort: z.string().trim().min(1).max(80),
  account: z.string().trim().min(1).max(160),
  unsafe: z.boolean(),
  priority: z.enum(["P0", "P1", "P2", "P3"]),
  incidentType: z.string().trim().min(1).max(80).optional(),
}).strict();
const DispatchIncidentBodySchema = z.object({
  withoutBrief: z.boolean().optional(),
}).strict();
const ResolveIncidentBodySchema = z.object({
  artifact: z.string().trim().min(1).max(2000),
  summary: z.string().trim().max(2000).optional(),
}).strict();
const ProjectColorsRequestSchema = z.object({ projects: ProjectColorsSchema }).strict();
const DEFAULT_FACTORY_DATA_DIR = process.env.OVERDECK_FACTORY_DATA_DIR
  ?? join(homedir(), ".local", "state", "overdeck", "factory", "data");

export function summarizeFactoryPanel(panel: Panel): Panel {
  if (panel.id !== FACTORY_PANEL_ID) return panel;
  const data = panel.data as FactoryPanelData;
  return {
    ...panel,
    data: {
      ...data,
      runs: data.runs.map((run) => ({
        ...run,
        detailAvailable: true,
        phases: [],
        events: [],
        attempts: [],
        gates: [],
        diffs: [],
        processes: [],
      })),
    } satisfies FactoryPanelData,
  };
}

export function publicCollectorDelta(delta: Delta): Delta {
  return delta.type === "panel" ? { ...delta, panel: summarizeFactoryPanel(delta.panel) } : delta;
}

export function factoryRunDetailResponse(run: FactoryRunView): Response {
  const body = JSON.stringify(run);
  if (Buffer.byteLength(body) > MAX_FACTORY_RUN_DETAIL_BYTES) {
    return Response.json({ error: "factory-run-detail-too-large" }, { status: 413 });
  }
  return new Response(body, { headers: { "content-type": "application/json" } });
}

export function factoryRunDetail(panel: Panel | undefined, adwId: string): FactoryRunView | undefined {
  if (panel?.id !== FACTORY_PANEL_ID) return undefined;
  const data = panel.data as FactoryPanelData;
  return data.runs.find((run) => run.adwId === adwId);
}

function artifactRange(rangeHeader: string | null, size: number): { start: number; end: number } | null | "invalid" {
  if (rangeHeader === null) return null;
  const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
  if (!match || (match[1] === "" && match[2] === "")) return "invalid";
  if (match[1] === "") {
    const suffixLength = Number(match[2]);
    if (!Number.isSafeInteger(suffixLength) || suffixLength <= 0 || size === 0) return "invalid";
    return { start: Math.max(0, size - suffixLength), end: size - 1 };
  }
  const start = Number(match[1]);
  const requestedEnd = match[2] === "" ? size - 1 : Number(match[2]);
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(requestedEnd) || start >= size || requestedEnd < start) return "invalid";
  return { start, end: Math.min(requestedEnd, size - 1) };
}

export async function readFactoryArtifact(dataDir: string, requestedPath: string, rangeHeader: string | null = null): Promise<Response> {
  if (!requestedPath.trim() || requestedPath.includes("\0")) {
    return Response.json({ error: "invalid-artifact-path" }, { status: 400 });
  }
  try {
    const root = await realpath(dataDir);
    const candidate = await realpath(isAbsolute(requestedPath) ? requestedPath : resolve(root, requestedPath));
    const fromRoot = relative(root, candidate);
    if (!fromRoot || fromRoot === ".." || fromRoot.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(fromRoot)) {
      return Response.json({ error: "artifact-path-outside-data-dir" }, { status: 403 });
    }
    const info = await stat(candidate);
    if (!info.isFile()) return Response.json({ error: "artifact-not-a-file" }, { status: 400 });
    const range = artifactRange(rangeHeader, info.size);
    const commonHeaders = {
      "accept-ranges": "bytes",
      "x-overdeck-artifact-size": String(info.size),
    };
    if (range === "invalid") {
      return Response.json({ error: "invalid-artifact-range" }, {
        status: 416,
        headers: { ...commonHeaders, "content-range": `bytes */${info.size}` },
      });
    }
    const isTail = range === null && info.size > MAX_FACTORY_ARTIFACT_BYTES;
    const position = range?.start ?? (isTail ? info.size - MAX_FACTORY_ARTIFACT_BYTES : 0);
    const end = range?.end ?? info.size - 1;
    const length = info.size === 0 ? 0 : end - position + 1;
    const handle = await open(candidate, "r");
    try {
      const buffer = Buffer.alloc(length);
      const { bytesRead } = await handle.read(buffer, 0, length, position);
      return new Response(buffer.subarray(0, bytesRead), {
        headers: {
          ...commonHeaders,
          "content-type": "text/plain; charset=utf-8",
          "content-length": String(bytesRead),
          ...(range ? { "content-range": `bytes ${position}-${position + bytesRead - 1}/${info.size}` } : {}),
          "x-overdeck-artifact-tail": isTail ? "true" : "false",
          "x-overdeck-artifact-truncated": isTail ? "true" : "false",
        },
        status: range ? 206 : 200,
      });
    } finally {
      await handle.close();
    }
  } catch (error) {
    const code = (error as NodeJS.ErrnoException).code;
    return Response.json({ error: code === "ENOENT" ? "artifact-not-found" : "artifact-unavailable" }, { status: code === "ENOENT" ? 404 : 400 });
  }
}

function unauthorized(): Response {
  return Response.json({ error: "unauthorized" }, { status: 401 });
}

function isAuthorized(req: Request, token: string): boolean {
  const header = req.headers.get("authorization");
  if (!header) return false;
  const match = /^Bearer (.+)$/.exec(header);
  if (!match) return false;
  return match[1] === token;
}

function harnessErrorResponse(error: unknown): Response {
  if (error instanceof HarnessApiError) {
    return Response.json(error.body, { status: error.status });
  }
  return Response.json({ error: "harness-unreachable" }, { status: 502 });
}

function incidentsErrorResponse(error: unknown): Response {
  if (error instanceof IncidentIdempotencyConflictError) {
    return Response.json({ error: "idempotency-conflict" }, { status: 409 });
  }
  if (error instanceof IncidentMutationError) {
    const status = error.code === "not-found" ? 404 : error.code === "invalid-request" ? 400 : 409;
    return Response.json({ error: error.code }, { status });
  }
  if (error instanceof IncidentResolutionConflictError) {
    return Response.json({ error: "resolution-conflict", detail: error.detail }, { status: 409 });
  }
  if (error instanceof BriefAssemblyError) {
    return Response.json({ error: "brief-assembly-failed", detail: `dispatch blocked: brief assembly failed — ${error.reason}` }, { status: 422 });
  }
  if (error instanceof IncidentOptionsError) {
    console.error(`[incident-options] kind=${error.kind} detail=${error.detail}`);
    return Response.json({ error: error.kind === "accounts" ? "incident-accounts-unavailable" : "incident-assets-unavailable" }, { status: 503 });
  }
  if (error instanceof IncidentsUnavailableError) {
    return Response.json({ error: "incidents-store-unavailable" }, { status: 503 });
  }
  throw error;
}

const MAX_SSE_FRAME_BYTES = 64 * 1024;
const MAX_PERMISSION_BODY_BYTES = 256 * 1024;
const FRAME_BOUNDARY = /\r\n\r\n|\r\n\n|\r\r\n|\r\r|\n\r\n|\n\r|\n\n/g;

function redactSseFrame(frame: string): string | null {
  const lines = frame.split(/\r\n|[\r\n]/);
  const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, ""));
  if (data.length === 0) return frame;
  try {
    const safe = JSON.stringify(redactBrowserValue(JSON.parse(data.join("\n"))));
    return [...lines.filter((line) => !line.startsWith("data:")), `data: ${safe}`].join("\n");
  } catch {
    return null;
  }
}

function redactConfigValue(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(redactConfigValue);
  if (!value || typeof value !== "object") return value;
  return Object.fromEntries(Object.entries(value).map(([key, nested]) => [
    key,
    CREDENTIAL_KEY.test(key) ? { isSecret: true, redacted: true } : redactConfigValue(nested),
  ]));
}

function redactConfigResponse(config: Awaited<ReturnType<HarnessAdapter["getRunConfig"]>>): unknown {
  return {
    revision: config.revision,
    fields: Object.fromEntries(Object.entries(config.fields).map(([key, field]) => [
      key,
      CREDENTIAL_KEY.test(key)
        ? { source: field.source, immutable: field.immutable, mutationClass: field.mutationClass, isSecret: true, redacted: true }
        : { ...field, value: redactConfigValue(field.value) },
    ])),
  };
}

function parseArrayParam(url: URL, key: string): string[] {
  return url.searchParams
    .getAll(key)
    .flatMap((entry) => entry.split(","))
    .map((entry) => entry.trim())
    .filter((entry) => entry.length > 0);
}

function parseCategory(value: string): ActivityCategory | undefined {
  return ([
    "land",
    "gate",
    "deploy",
    "run",
    "agent",
    "buildbox",
    "guard",
    "notification",
    "git",
    "service",
    "ci",
  ] as const).includes(value as ActivityCategory)
    ? (value as ActivityCategory)
    : undefined;
}

function parseActor(value: string): ActivityActor | undefined {
  return value === "agent" || value === "human" || value === "timer" || value === "system"
    ? (value as ActivityActor)
    : undefined;
}

function parseSeverity(value: string | null): ActivitySeverity | undefined {
  if (!value || !(value in ACTIVITY_SEVERITY_ORDER)) return undefined;
  return value as ActivitySeverity;
}

interface ActivityRouteParseResult {
  ok: boolean;
  error?: string;
  options?: ActivityReadOptions;
}

function parseReadActivityOptions(url: URL): ActivityRouteParseResult {
  const from = url.searchParams.get("from") ?? undefined;
  const to = url.searchParams.get("to") ?? undefined;
  const q = url.searchParams.get("q")?.trim() ?? undefined;

  if (from !== undefined && Number.isNaN(Date.parse(from))) {
    return { ok: false, error: `invalid from: ${from}` };
  }
  if (to !== undefined && Number.isNaN(Date.parse(to))) {
    return { ok: false, error: `invalid to: ${to}` };
  }

  const parsedCategories = parseArrayParam(url, "category").map((entry) => {
    const parsed = parseCategory(entry);
    if (parsed === undefined) {
      return undefined;
    }
    return parsed;
  });
  if (parsedCategories.some((entry) => entry === undefined)) {
    return { ok: false, error: "invalid category filter" };
  }
  const parsedActors = parseArrayParam(url, "actor").map((entry) => {
    const parsed = parseActor(entry);
    if (parsed === undefined) return undefined;
    return parsed;
  });
  if (parsedActors.some((entry) => entry === undefined)) {
    return { ok: false, error: "invalid actor filter" };
  }

  const severityParam = url.searchParams.get("severity>=") ?? url.searchParams.get("severity");
  const severityFloor = severityParam === null ? undefined : parseSeverity(severityParam);
  if (severityParam !== null && severityFloor === undefined) {
    return { ok: false, error: `invalid severity: ${severityParam}` };
  }

  const limitParam = url.searchParams.get("limit") ?? undefined;
  let limit: number | undefined;
  if (limitParam !== undefined) {
    const parsed = Number(limitParam);
    if (!Number.isInteger(parsed) || parsed < 1 || parsed > 2000) {
      return { ok: false, error: `invalid limit: ${limitParam}` };
    }
    limit = parsed;
  }

  const categories = parsedCategories.filter((entry): entry is ActivityCategory => entry !== undefined);
  const actors = parsedActors.filter((entry): entry is ActivityActor => entry !== undefined);
  const projects = parseArrayParam(url, "project");
  const runtimes = parseArrayParam(url, "runtime");
  const hosts = parseArrayParam(url, "host");
  const workloads = parseArrayParam(url, "workload");
  const builds = parseArrayParam(url, "build");

  return {
    ok: true,
    options: {
      from,
      to,
      categories: categories.length > 0 ? categories : undefined,
      projects: projects.length > 0 ? projects : undefined,
      runtimes: runtimes.length > 0 ? runtimes : undefined,
      hosts: hosts.length > 0 ? hosts : undefined,
      workloads: workloads.length > 0 ? workloads : undefined,
      builds: builds.length > 0 ? builds : undefined,
      actors: actors.length > 0 ? actors : undefined,
      severityFloor,
      limit,
      q: q?.length ? q : undefined,
    },
  };
}

function errorResponse(error: string): Response {
  return Response.json({ error }, { status: 400 });
}

interface ActivityEntriesParseResult {
  ok: boolean;
  error?: string;
  options?: ActivitySourceEntriesOptions;
}

function parseActivityEntriesOptions(sourceId: string, url: URL): ActivityEntriesParseResult {
  const from = url.searchParams.get("from") ?? undefined;
  const to = url.searchParams.get("to") ?? undefined;
  const q = url.searchParams.get("q")?.trim() ?? undefined;
  const recordId = url.searchParams.get("recordId")?.trim() ?? undefined;

  if (from !== undefined && Number.isNaN(Date.parse(from))) return { ok: false, error: `invalid from: ${from}` };
  if (to !== undefined && Number.isNaN(Date.parse(to))) return { ok: false, error: `invalid to: ${to}` };

  const severityParam = url.searchParams.get("severity");
  const severityFloor = severityParam === null ? undefined : parseSeverity(severityParam);
  if (severityParam !== null && severityFloor === undefined) {
    return { ok: false, error: `invalid severity: ${severityParam}` };
  }

  const limitParam = url.searchParams.get("limit");
  let limit: number | undefined;
  if (limitParam !== null) {
    const parsed = Number(limitParam);
    if (!Number.isInteger(parsed) || parsed < 1 || parsed > ACTIVITY_ENTRIES_MAX_LIMIT) {
      return { ok: false, error: `invalid limit: ${limitParam}` };
    }
    limit = parsed;
  }

  const offsetParam = url.searchParams.get("offset");
  let offset: number | undefined;
  if (offsetParam !== null) {
    const parsed = Number(offsetParam);
    if (!Number.isInteger(parsed) || parsed < 0) {
      return { ok: false, error: `invalid offset: ${offsetParam}` };
    }
    offset = parsed;
  }

  return {
    ok: true,
    options: {
      sourceId,
      ...(from === undefined ? {} : { from }),
      ...(to === undefined ? {} : { to }),
      ...(q === undefined || q.length === 0 ? {} : { q }),
      ...(recordId === undefined || recordId.length === 0 ? {} : { recordId }),
      ...(severityFloor === undefined ? {} : { severityFloor }),
      ...(limit === undefined ? {} : { limit }),
      ...(offset === undefined ? {} : { offset }),
    },
  };
}


function relayStream(request: Request, upstream: Response, abort: AbortController): Response {
  if (!upstream.body) return new Response(null, { status: upstream.status, headers: upstream.headers });

  const reader = upstream.body.getReader();
  const decoder = new TextDecoder();
  const encoder = new TextEncoder();
  let pending = "";
  let closed = false;
  const close = (reason?: unknown) => {
    if (closed) return;
    closed = true;
    abort.abort(reason);
    void reader.cancel(reason).catch(() => undefined);
  };
  request.signal.addEventListener("abort", () => close(request.signal.reason), { once: true });

  const body = new ReadableStream<Uint8Array>({
    async pull(controller) {
      try {
        const chunk = await reader.read();
        if (chunk.done) {
          closed = true;
          controller.close();
          return;
        }
        pending += decoder.decode(chunk.value, { stream: true });
        let boundary: RegExpExecArray | null;
        const boundaries = new RegExp(FRAME_BOUNDARY);
        let start = 0;
        while ((boundary = boundaries.exec(pending)) !== null) {
          const frame = pending.slice(start, boundary.index);
          if (encoder.encode(frame).byteLength > MAX_SSE_FRAME_BYTES) {
            close("SSE frame exceeds maximum size");
            controller.close();
            return;
          }
          const safeFrame = redactSseFrame(frame);
          if (safeFrame === null) {
            close("SSE frame contains malformed JSON data");
            controller.close();
            return;
          }
          controller.enqueue(encoder.encode(`${safeFrame}\n\n`));
          start = boundary.index + boundary[0].length;
        }
        pending = pending.slice(start);
        if (encoder.encode(pending).byteLength > MAX_SSE_FRAME_BYTES) {
          close("SSE frame exceeds maximum size");
          controller.close();
          return;
        }
      } catch (error) {
        if (!closed) {
          closed = true;
          controller.error(error);
        }
      }
    },
    cancel(reason) {
      close(reason);
    },
  });

  return new Response(body, {
    status: upstream.status,
    headers: { "content-type": upstream.headers.get("content-type") ?? "application/octet-stream" },
  });
}

// Bun types `port` optional because a Server may bind a unix socket; this one
// always binds host + port.
export type CollectorServer = Server<undefined> & { port: number };

export function startServer(opts: ServerOptions): CollectorServer {
  const {
    host,
    port,
    token,
    state,
    actionGateway,
    permissions,
    harness,
    incidents,
    digestTimeZone,
    controllerUrl,
    controllerToken,
    fetcher = fetch,
    loadBuildboxRegistry: readBuildboxRegistry = loadBuildboxRegistry,
    loadFactoryRunDetail: readFactoryRunDetail,
    factoryDataDir = DEFAULT_FACTORY_DATA_DIR,
    routingRuntimeDir = defaultRoutingRuntimeDir(),
    hookInventoryOptions,
    hookControlsConfigDirectory,
    incidentBriefAssets = createDeployAssetDeps(),
    incidentBriefProvenance = readDeployProvenance,
    loadIncidentOptions,
    config = defaultConfig(),
    configPath = configFile(),

  } = opts;

  let factoryRunDetailInFlight = false;
  let server: Server<undefined>;
  try {
    server = Bun.serve({
      hostname: host,
      port,
      // /events holds an open SSE stream that is idle whenever no delta arrives;
      // Bun's 10s default idleTimeout would tear it down mid-stream every time.
      idleTimeout: 0,
      async fetch(req) {
        if (!isAuthorized(req, token)) {
          return unauthorized();
        }

        const url = new URL(req.url);

        if (url.pathname === "/health" && req.method === "GET") {
          return Response.json({ ok: true });
        }

        if (url.pathname === "/state" && req.method === "GET") {
          return Response.json({
            panels: state.getPanels().map(summarizeFactoryPanel),
            adapters: state.adapterStatuses(),
          });
        }

        const factoryRunMatch = /^\/factory\/runs\/([^/]+)$/.exec(url.pathname);
        if (factoryRunMatch && req.method === "GET") {
          if (!readFactoryRunDetail) {
            return Response.json({ error: "factory-run-detail-unavailable" }, { status: 503 });
          }
          if (factoryRunDetailInFlight) {
            return Response.json({ error: "factory-run-detail-busy" }, { status: 429 });
          }
          let adwId: string;
          try { adwId = decodeURIComponent(factoryRunMatch[1]!); }
          catch { return Response.json({ error: "factory-run-not-found" }, { status: 404 }); }

          factoryRunDetailInFlight = true;
          try {
            const result = await readFactoryRunDetail(adwId, req.signal);
            if (result.status === "missing") return Response.json({ error: "factory-run-not-found" }, { status: 404 });
            if (result.status === "too-large") return Response.json({ error: "factory-run-detail-too-large" }, { status: 413 });
            if (Buffer.byteLength(result.body) > MAX_FACTORY_RUN_DETAIL_BYTES) {
              return Response.json({ error: "factory-run-detail-too-large" }, { status: 413 });
            }
            return new Response(result.body, { headers: { "content-type": "application/json" } });
          } finally {
            factoryRunDetailInFlight = false;
          }
        }

        if (url.pathname === "/items" && req.method === "GET") {
          const kind = url.searchParams.get("kind") ?? undefined;
          return Response.json({ items: state.getItems(kind) });
        }

        if (url.pathname === "/cluster" && req.method === "GET") {
          const panel = state.getPanel(CLUSTER_PANEL_ID);
          return panel
            ? Response.json(panel.data)
            : Response.json({ error: "cluster-snapshot-unavailable" }, { status: 503 });
        }

        const clusterNodeMatch = /^\/cluster\/nodes\/([^/]+)$/.exec(url.pathname);
        if (clusterNodeMatch && req.method === "GET") {
          const panel = state.getPanel(CLUSTER_PANEL_ID);
          if (!panel) return Response.json({ error: "cluster-snapshot-unavailable" }, { status: 503 });
          let name: string;
          try { name = decodeURIComponent(clusterNodeMatch[1]!); } catch { return Response.json({ error: "unknown-node" }, { status: 404 }); }
          const snapshot = panel.data as ClusterSnapshot;
          const node = snapshot.nodes.find((entry) => entry.name === name);
          return node ? Response.json({ observedAt: snapshot.observedAt, sources: snapshot.sources, node }) : Response.json({ error: "unknown-node" }, { status: 404 });
        }

        const clusterWorkloadMatch = /^\/cluster\/workloads\/([^/]+)$/.exec(url.pathname);
        if (clusterWorkloadMatch && req.method === "GET") {
          const panel = state.getPanel(CLUSTER_PANEL_ID);
          if (!panel) return Response.json({ error: "cluster-snapshot-unavailable" }, { status: 503 });
          let uid: string;
          try { uid = decodeURIComponent(clusterWorkloadMatch[1]!); } catch { return Response.json({ error: "unknown-workload" }, { status: 404 }); }
          const snapshot = panel.data as ClusterSnapshot;
          const workload = snapshot.nodes.flatMap((node) => node.workloads).find((entry) => entry.uid === uid)
            ?? snapshot.unmatchedWorkloads.find((entry) => entry.uid === uid);
          if (!workload) return Response.json({ error: "unknown-workload" }, { status: 404 });
          const sessions = [...snapshot.nodes.flatMap((node) => node.sessions), ...snapshot.unplacedSessions].filter((entry) => entry.workloadUid === uid);
          const builds = [...snapshot.nodes.flatMap((node) => node.builds), ...snapshot.unplacedBuilds].filter((entry) => entry.workloadUid === uid);
          return Response.json({ observedAt: snapshot.observedAt, sources: snapshot.sources, workload, sessions, builds });
        }

        if (url.pathname === "/config/projects") {
          if (req.method === "GET") return Response.json({ projects: config.projectColors ?? {} });
          if (req.method === "POST") {
            return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES)
              .then((raw) => ProjectColorsRequestSchema.safeParse(JSON.parse(raw)))
              .then((parsed) => {
                if (!parsed.success) return Response.json({ error: "invalid-project-colors" }, { status: 400 });
                return persistProjectColors(configPath, parsed.data.projects)
                  .then(({ projects, durability }) => {
                    // An indeterminate durability result is still post-rename committed.
                    config.projectColors = projects;
                    return Response.json({ projects, durability });
                  })
                  .catch((error) => {
                    if (error instanceof ProjectColorsPersistenceError) {
                      return Response.json(
                        { error: error.code === "lock-busy" ? "project-colors-write-busy" : "project-colors-write-conflict" },
                        { status: error.code === "lock-busy" ? 503 : 409 },
                      );
                    }
                    return Response.json({ error: "project-colors-write-failed" }, { status: 500 });
                  });
              })
              .catch((error) => Response.json(
                { error: error instanceof RangeError ? "payload-too-large" : "invalid-project-colors" },
                { status: error instanceof RangeError ? 413 : 400 },
              ));
          }
        }

        const routingMatch = /^\/config\/routing\/(codex|claude)$/.exec(url.pathname);
        if (routingMatch) {
          const provider = RoutingProviderSchema.parse(routingMatch[1]);
          if (req.method === "GET") {
            return readRoutingConfig(routingRuntimeDir, provider)
              .then((body) => Response.json(body))
              .catch((error) => Response.json({ error: "routing-config-unavailable", detail: String(error) }, { status: 500 }));
          }
          if (req.method === "POST") {
            return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES)
              .then((raw) => atomicWriteRoutingConfig(routingRuntimeDir, provider, JSON.parse(raw)))
              .then((rules) => Response.json({ provider, rules }))
              .catch((error) => Response.json({ error: "invalid-routing-config", detail: String(error) }, { status: 400 }));
          }
        }

        if (url.pathname === "/hooks" && req.method === "GET") {
          return inventoryHooks(hookInventoryOptions).then((body) => Response.json(body));
        }

        const hookControlError = (error: unknown): Response => {
          if (error instanceof HookControlsError) {
            const status = error.code === 'invalid' ? 409 : error.code === 'locked' ? 503 : error.code === 'unknown' ? 404 : 500;
            const code = error.code === 'invalid' ? 'hook-controls-invalid' : error.code === 'locked' ? 'hook-controls-locked' : error.code === 'unknown' ? 'unknown-hook-control' : 'hook-controls-write-failed';
            return Response.json({ error: code, detail: error.message }, { status });
          }
          return Response.json({ error: 'hook-controls-write-failed' }, { status: 500 });
        };
        if (url.pathname === '/config/hooks') {
          if (req.method === 'GET') return readHookControls(hookControlsConfigDirectory).then((body) => Response.json(body)).catch(hookControlError);
          return Response.json({ error: 'method-not-allowed' }, { status: 405 });
        }
        if (url.pathname === '/config/hooks/repair') {
          if (req.method !== 'POST') return Response.json({ error: 'method-not-allowed' }, { status: 405 });
          if (req.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') return Response.json({ error: 'unsupported-media-type' }, { status: 415 });
          return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES).then((raw) => {
            const value: unknown = JSON.parse(raw);
            if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value as object).length !== 1 || (value as { confirm?: unknown }).confirm !== 'replace-invalid-config') throw new SyntaxError();
            return repairHookControls(hookControlsConfigDirectory);
          }).then((body) => Response.json(body)).catch((error) => error instanceof RangeError ? Response.json({ error: 'payload-too-large' }, { status: 413 }) : error instanceof SyntaxError ? Response.json({ error: 'invalid-hook-control-request' }, { status: 400 }) : hookControlError(error));
        }
        const hookControlMatch = /^\/config\/hooks\/([^/]+)$/.exec(url.pathname);
        if (hookControlMatch) {
          if (req.method !== 'POST') return Response.json({ error: 'method-not-allowed' }, { status: 405 });
          let id: string;
          try { id = decodeURIComponent(hookControlMatch[1]!); } catch { return Response.json({ error: 'unknown-hook-control' }, { status: 404 }); }
          if (!isRegisteredHookControl(id)) return Response.json({ error: 'unknown-hook-control' }, { status: 404 });
          if (req.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') return Response.json({ error: 'unsupported-media-type' }, { status: 415 });
          return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES).then((raw) => {
            const value: unknown = JSON.parse(raw);
            if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value as object).length !== 1 || typeof (value as { enabled?: unknown }).enabled !== 'boolean') throw new SyntaxError();
            return setHookControl(id as Parameters<typeof setHookControl>[0], (value as { enabled: boolean }).enabled, hookControlsConfigDirectory);
          }).then((body) => Response.json(body)).catch((error) => error instanceof RangeError ? Response.json({ error: 'payload-too-large' }, { status: 413 }) : error instanceof SyntaxError ? Response.json({ error: 'invalid-hook-control-request' }, { status: 400 }) : hookControlError(error));
        }

        if (url.pathname === "/incidents" && req.method === "GET") {
          if (!incidents) {
            return new Response("not found", { status: 404 });
          }

          const scopeParam = url.searchParams.get("scope");
          if (scopeParam !== null && scopeParam !== "active" && scopeParam !== "resolved" && scopeParam !== "all") {
            return Response.json({ error: "invalid-query" }, { status: 400 });
          }

          const priorityParam = url.searchParams.get("priority");
          if (priorityParam !== null && priorityParam !== "P0" && priorityParam !== "P1" && priorityParam !== "P2" && priorityParam !== "P3") {
            return Response.json({ error: "invalid-query" }, { status: 400 });
          }

          const query = url.searchParams.get("query") ?? undefined;
          const limitParam = url.searchParams.get("limit");
          const cursorParam = url.searchParams.get("cursor");
          const highWaterParam = url.searchParams.get("highWater");
          const limit = limitParam === null ? 50 : Number(limitParam);
          const cursor = cursorParam === null ? undefined : Number(cursorParam);
          const highWater = highWaterParam === null ? undefined : Number(highWaterParam);
          if ((query?.length ?? 0) > 256 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100 || (cursor !== undefined && (!Number.isSafeInteger(cursor) || cursor < 1)) || (highWater !== undefined && (!Number.isSafeInteger(highWater) || highWater < 0))) {
            return Response.json({ error: "invalid-query" }, { status: 400 });
          }

          return incidents.listIncidents({
            scope: scopeParam ?? "active",
            limit,
            ...(cursor === undefined ? {} : { cursor }),
            ...(highWater === undefined ? {} : { highWater }),
            ...(query === undefined ? {} : { query }),
            ...(priorityParam === null ? {} : { priority: priorityParam }),
          }).then((body) => Response.json(body)).catch(incidentsErrorResponse);
        }

        if (url.pathname === "/incidents" && req.method === "POST") {
          if (!incidents) return new Response("not found", { status: 404 });
          if (!loadIncidentOptions) return Response.json({ error: "incident-assets-unavailable" }, { status: 503 });
          return readBoundedBody(req, MAX_INCIDENT_BODY_BYTES)
            .then((raw) => FileIncidentRequestSchema.safeParse(JSON.parse(raw)))
            .then(async (parsed) => {
              if (!parsed.success) return Response.json({ error: "invalid-incident" }, { status: 400 });
              const request = parsed.data;
              try {
                const options = await loadIncidentOptions();
                validateIncidentType(request.incidentType, options);
                const selection = validateIncidentDispatchSelection(request, options);
                return incidents.fileIncident({ ...request, wrapperModel: selection.wrapperModel })
                  .then((incident) => Response.json({ incident }, { status: 201 }))
                  .catch(incidentsErrorResponse);
              } catch (error) {
                if (error instanceof InvalidIncidentDispatchError) return Response.json({ error: "invalid-incident-dispatch" }, { status: 400 });
                if (error instanceof InvalidIncidentTypeError) return Response.json({ error: "invalid-incident" }, { status: 400 });
                return incidentsErrorResponse(error);
              }
            })
            .catch((error) => Response.json({ error: error instanceof RangeError ? "payload-too-large" : "invalid-incident" }, { status: error instanceof RangeError ? 413 : 400 }));
        }

        if (url.pathname === "/digest" && req.method === "GET") {
          const digest: DigestResponse = buildDigest(state, Date.now, digestTimeZone);
          return Response.json(digest);
        }

        if (url.pathname === "/activity" && req.method === "GET") {
          const parsed = parseReadActivityOptions(url);
          if (!parsed.ok || !parsed.options) {
            return errorResponse(parsed.error ?? "invalid activity request");
          }
          return Response.json(readActivityCached(parsed.options));
        }

        const activityEntriesMatch = /^\/activity\/sources\/([^/]+)\/entries$/.exec(url.pathname);
        if (activityEntriesMatch && req.method === "GET") {
          let sourceId: string;
          try {
            sourceId = decodeURIComponent(activityEntriesMatch[1]!);
          } catch {
            return Response.json({ error: "unknown-source" }, { status: 404 });
          }
          const parsed = parseActivityEntriesOptions(sourceId, url);
          if (!parsed.ok || !parsed.options) {
            return errorResponse(parsed.error ?? "invalid activity entries request");
          }
          const entries = readActivitySourceEntries(parsed.options);
          if (entries === undefined) {
            return Response.json({ error: "unknown-source", sources: ACTIVITY_SOURCE_IDS }, { status: 404 });
          }
          return Response.json(entries);
        }

        if (url.pathname === "/factory/artifact" && req.method === "GET") {
          return readFactoryArtifact(factoryDataDir, url.searchParams.get("path") ?? "", req.headers.get("range"));
        }

        if (url.pathname === "/incidents/options" && req.method === "GET") {
          if (!incidents) return new Response("not found", { status: 404 });
          if (incidents.getOptions) return incidents.getOptions().then((options) => Response.json(options)).catch(incidentsErrorResponse);
          const raw = incidentBriefAssets.readAsset("taxonomy.json");
          if (raw === null) return Response.json({ error: "incident-assets-unavailable" }, { status: 503 });
          try { return Response.json({ types: parseTaxonomy(raw).map(({ id, title, keywords }) => ({ id, title, keywords })) }); }
          catch (error) { return incidentsErrorResponse(error); }
        }

        const incidentMatch = /^\/incidents\/([^/]+)$/.exec(url.pathname);
        if (incidentMatch && req.method === "GET") {
          if (!incidents) {
            return new Response("not found", { status: 404 });
          }

          let incidentId: string;
          try {
            incidentId = decodeURIComponent(incidentMatch[1]!);
          } catch {
            return Response.json({ error: "not-found" }, { status: 404 });
          }

          return incidents.getIncident(incidentId)
            .then((incident) => incident === null
              ? Response.json({ error: "not-found" }, { status: 404 })
              : Response.json(incident))
            .catch(incidentsErrorResponse);
        }

        const lifecycleMatch = /^\/incidents\/([^/]+)\/(stop|delete)$/.exec(url.pathname);
        if (lifecycleMatch && req.method === "POST") {
          if (!incidents) return new Response("not found", { status: 404 });
          let incidentId: string;
          try { incidentId = decodeURIComponent(lifecycleMatch[1]!); }
          catch { return Response.json({ error: "not-found" }, { status: 404 }); }
          if (lifecycleMatch[2] === "stop" && !incidents.stopIncident) return new Response("not found", { status: 404 });
          if (lifecycleMatch[2] === "delete" && !incidents.deleteIncident) return new Response("not found", { status: 404 });
          return (lifecycleMatch[2] === "stop"
            ? incidents.stopIncident!(incidentId).then((incident) => Response.json({ incident }))
            : incidents.deleteIncident!(incidentId).then(() => new Response(null, { status: 204 })))
            .catch(incidentsErrorResponse);
        }

        const dispatchMatch = /^\/incidents\/([^/]+)\/dispatch$/.exec(url.pathname);
        if (dispatchMatch && req.method === "POST") {
          if (!incidents) return new Response("not found", { status: 404 });
          if (!loadIncidentOptions) return Response.json({ error: "incident-assets-unavailable" }, { status: 503 });
          let incidentId: string;
          try { incidentId = decodeURIComponent(dispatchMatch[1]!); }
          catch { return Response.json({ error: "not-found" }, { status: 404 }); }
          return readBoundedBody(req, MAX_INCIDENT_BODY_BYTES)
            .then((raw) => DispatchIncidentBodySchema.safeParse(raw.trim().length === 0 ? {} : JSON.parse(raw)))
            .then((parsed) => parsed.success
              ? incidents.dispatchIncident(incidentId, { withoutBrief: parsed.data.withoutBrief === true })
                  .then((incident) => Response.json({ incident })).catch(incidentsErrorResponse)
              : Response.json({ error: "invalid-request" }, { status: 400 }))
            .catch((error) => error instanceof RangeError
              ? Response.json({ error: "payload-too-large" }, { status: 413 })
              : error instanceof SyntaxError
                ? Response.json({ error: "invalid-request" }, { status: 400 })
                : incidentsErrorResponse(error));
        }

        const briefMatch = /^\/incidents\/([^/]+)\/brief$/.exec(url.pathname);
        if (briefMatch && req.method === "GET") {
          if (!incidents) return new Response("not found", { status: 404 });
          let incidentId: string;
          try { incidentId = decodeURIComponent(briefMatch[1]!); }
          catch { return Response.json({ error: "not-found" }, { status: 404 }); }
          return incidents.getIncident(incidentId)
            .then((incident) => {
              if (incident === null) return Response.json({ error: "not-found" }, { status: 404 });
              if (incident.dispatchBrief !== null) {
                return Response.json({
                  brief: { text: incident.dispatchBrief, sections: [] },
                  provenance: incident.dispatchBriefProvenance,
                  persisted: true,
                });
              }
              const assembled = assembleDispatchBrief(incident, incidentBriefAssets);
              return Response.json({ brief: assembled, provenance: incidentBriefProvenance(), persisted: false });
            })
            .catch(incidentsErrorResponse);
        }

        const resolveMatch = /^\/incidents\/([^/]+)\/resolve$/.exec(url.pathname);
        if (resolveMatch && req.method === "POST") {
          if (!incidents) return new Response("not found", { status: 404 });
          let incidentId: string;
          try { incidentId = decodeURIComponent(resolveMatch[1]!); }
          catch { return Response.json({ error: "not-found" }, { status: 404 }); }
          return req.text()
            .then((raw) => {
              const parsed = ResolveIncidentBodySchema.safeParse(raw.trim().length === 0 ? {} : JSON.parse(raw));
              if (!parsed.success) return Response.json({ error: "invalid-resolve-request" }, { status: 400 });
              return incidents.resolveIncident(incidentId!, parsed.data.artifact, parsed.data.summary)
                .then((incident) => Response.json(incident))
                .catch(incidentsErrorResponse);
            })
            .catch((error) => error instanceof SyntaxError
              ? Response.json({ error: "invalid-request" }, { status: 400 })
              : incidentsErrorResponse(error));
        }

        const harnessEventsMatch = /^\/harness\/runs\/([^/]+)\/events$/.exec(url.pathname);
        if (harnessEventsMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          return harness.getRunEvents(decodeURIComponent(harnessEventsMatch[1]!), {
            raw: url.search,
            lastEventId: req.headers.get("last-event-id") ?? undefined,
          }).then((body) => Response.json(body)).catch(harnessErrorResponse);
        }

        const harnessStreamMatch = /^\/harness\/runs\/([^/]+)\/tasks\/([^/]+)\/stream$/.exec(url.pathname);
        if (harnessStreamMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          const [runId, taskId] = harnessStreamMatch.slice(1).map(decodeURIComponent);
          const abort = new AbortController();
          req.signal.addEventListener("abort", () => abort.abort(req.signal.reason), { once: true });
          return harness.openTaskStream(runId!, taskId!, {
            raw: url.search,
            lastEventId: req.headers.get("last-event-id") ?? undefined,
            signal: abort.signal,
          }).then((upstream) => relayStream(req, upstream, abort)).catch(harnessErrorResponse);
        }

        const harnessConfigMatch = /^\/harness\/runs\/([^/]+)\/config$/.exec(url.pathname);
        if (harnessConfigMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          return harness.getRunConfig(decodeURIComponent(harnessConfigMatch[1]!))
            .then((body) => Response.json(redactConfigResponse(body))).catch(harnessErrorResponse);
        }

        const harnessPlanMatch = /^\/harness\/runs\/([^/]+)\/plan$/.exec(url.pathname);
        if (harnessPlanMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          return harness.getEffectivePlan(decodeURIComponent(harnessPlanMatch[1]!))
            .then((body) => Response.json(body)).catch(harnessErrorResponse);
        }

        const harnessDecisionsMatch = /^\/harness\/runs\/([^/]+)\/decisions$/.exec(url.pathname);
        if (harnessDecisionsMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          return harness.getDecisions(decodeURIComponent(harnessDecisionsMatch[1]!))
            .then((body) => Response.json(body)).catch(harnessErrorResponse);
        }

        const harnessRunMatch = /^\/harness\/runs\/([^/]+)$/.exec(url.pathname);
        if (harnessRunMatch && req.method === "GET") {
          if (!harness) return new Response("not found", { status: 404 });
          return harness.getRunDetail(decodeURIComponent(harnessRunMatch[1]!))
            .then((body) => Response.json(body)).catch(harnessErrorResponse);
        }

        const sessionScreenMatch = /^\/sessions\/([^/]+)\/screen$/.exec(url.pathname);
        if (sessionScreenMatch && req.method === "GET") {
          const sessionId = decodeURIComponent(sessionScreenMatch[1]!);
          return readSessionScreen(state, sessionId)
            .then(({ status, body }) => Response.json(body, { status }));
        }

        const hostLogsMatch = /^\/hosts\/([^/]+)\/logs$/.exec(url.pathname);
        if (hostLogsMatch && req.method === "GET") {
          if (!controllerUrl || !controllerToken) {
            return Response.json({ error: "offload controller unavailable" }, { status: 503 });
          }
          const hostname = decodeURIComponent(hostLogsMatch[1] ?? "");
          // Registry read failures alone answer 503; a controller failure inside the proxy
          // chain keeps its own 502 rather than being relabelled a registry fault.
          return readBuildboxRegistry().catch((error) => {
            const detail = error instanceof RegistryUnavailableError ? error.message : String(error);
            return Response.json({ error: "buildbox-registry-unavailable", detail }, { status: 503 });
          }).then((registry) => {
            if (registry instanceof Response) return registry;
            const declared = registry.hosts.find((host) => host.name === hostname);
            if (!declared) {
              return Response.json({ error: "host-not-in-buildbox-registry" }, { status: 404 });
            }
            if (declared.state !== "reachable") {
              return Response.json({ error: `host-declared-${declared.state}` }, { status: 409 });
            }
            return fetcher(`${controllerUrl}/hosts/${encodeURIComponent(hostname)}/logs`, {
              headers: { authorization: `Bearer ${controllerToken}` },
            }).then(async (res) => {
              const body = await res.text();
              return new Response(body, {
                status: res.status,
                headers: { "content-type": res.headers.get("content-type") ?? "application/json" },
              });
            }).catch(() => Response.json({ error: "controller-unreachable" }, { status: 502 }));
          });
        }

        // Feeder seam: a permission request parks here — the connection stays open
        // until a browser verdict arrives or the queue's bound lapses. No polling
        // on either side; the agent blocks on a socket read.
        if (url.pathname === "/permissions/request" && req.method === "POST") {
          if (!permissions) return new Response("not found", { status: 404 });
          return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES)
            .then((raw) => {
              const parsed = PermissionRequestSchema.safeParse(JSON.parse(raw));
              if (!parsed.success) {
                return Response.json({ decision: "ask", reason: "invalid permission request" }, { status: 400 });
              }
              return permissions.request(parsed.data, req.signal).then((verdict) => Response.json(verdict));
            })
            .catch(() => Response.json({ decision: "ask", reason: "unreadable permission request" }, { status: 400 }));
        }

        // Claude Code feeder: takes the raw PreToolUse envelope and answers with the
        // hook's own output contract, so the shell hook never parses JSON.
        if (url.pathname === "/permissions/request/claude-code" && req.method === "POST") {
          if (!permissions) return new Response("not found", { status: 404 });
          return readBoundedBody(req, MAX_PERMISSION_BODY_BYTES)
            .then((raw) => {
              const parsed = ClaudeCodeHookInputSchema.safeParse(JSON.parse(raw));
              if (!parsed.success) return Response.json({}, { status: 400 });
              return permissions
                .request(claudeCodeRequest(parsed.data, DEFAULT_WAIT_MS), req.signal)
                .then((verdict) => Response.json(claudeCodeHookOutput(verdict)));
            })
            .catch(() => Response.json({}, { status: 400 }));
        }

        if (req.method === "POST") {
          const actionMatch = /^\/actions\/([^/]+)$/.exec(url.pathname);
          if (actionMatch) {
            if (!actionGateway) {
              return new Response("not found", { status: 404 });
            }
            return actionGateway.handle(req, actionMatch[1]!);
          }
        }

        if (url.pathname === "/events" && req.method === "GET") {
          let unsubscribe: () => void = () => {};
          const stream = new ReadableStream<Uint8Array>({
            start(controller) {
              const encoder = new TextEncoder();
              // an initial comment forces headers to flush immediately (Bun buffers until the first chunk)
              controller.enqueue(encoder.encode(": connected\n\n"));
              unsubscribe = state.subscribe((delta: Delta) => {
                controller.enqueue(encoder.encode(`data: ${JSON.stringify(publicCollectorDelta(delta))}\n\n`));
              });
            },
            cancel() {
              unsubscribe();
            },
          });
          return new Response(stream, {
            headers: {
              "content-type": "text/event-stream",
              "cache-control": "no-cache",
              connection: "keep-alive",
            },
          });
        }

        return new Response("not found", { status: 404 });
      },
    });
  } catch (err) {
    const code = (err as { code?: string }).code;
    const message = (err as Error).message ?? String(err);
    if (code === "EADDRINUSE" || message.includes("EADDRINUSE") || message.includes("address already in use")) {
      throw new CollectorFatalError(
        "PORT_BUSY",
        `port ${port} on ${host} is already in use — refusing to auto-increment`,
      );
    }
    throw err;
  }

  return server as CollectorServer;
}
