import {
  base64ToBytes,
  bufferSource,
  bytesToBase64,
  canonicalize,
  constantTimeDigestEqual,
  randomUuid,
  sha256Bytes,
  sha256Json,
  signDomain,
  utf8,
} from "./crypto";
import { json, publicSummary } from "./http";
import { loadRoleSigners } from "./keys";
import {
  rfc6962NodeHash,
  witnessLeaf,
} from "./merkle";
import {
  computeCoverage,
  createRun,
  directEffect,
  dispatchDecision,
  finalizeRun,
  requestDecision,
  systemClock,
  type DecisionEvaluation,
  type DecisionObservation,
  type EffectObservation,
  type RoleSigners,
  type RunSnapshot,
  type RuntimeDependencies,
} from "./runtime";
import { verifyActionReceiptV04Bytes } from "./browser";
import { parseStrictJsonBytes } from "./strict-json";
import { HttpError, type Env, type JsonObject, type JsonValue } from "./types";
import { CAPABILITY_TOKEN_DERIVATION_VERSION } from "./constants";

type SqlState = DurableObjectState;

function internalJson(value: JsonValue, status = 200): Response {
  return json(value, status);
}

async function internalBody(request: Request): Promise<JsonObject> {
  const value = (await request.json()) as unknown;
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new HttpError(400, "INVALID_INTERNAL_REQUEST", "internal request must be an object");
  }
  return value as JsonObject;
}

function metaGet<T>(state: SqlState, key: string): T | null {
  const rows = state.storage.sql
    .exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key)
    .toArray();
  return rows.length === 0 ? null : (JSON.parse(rows[0]?.value ?? "null") as T);
}

function metaPut(state: SqlState, key: string, value: unknown): void {
  state.storage.sql.exec(
    "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
    key,
    JSON.stringify(value),
  );
}

function initializeMeta(state: SqlState): void {
  state.storage.sql.exec(
    "CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY NOT NULL,value TEXT NOT NULL)",
  );
}

function publicRunResponse(record: Awaited<ReturnType<typeof requestDecision>>): JsonObject {
  return {
    request_id: record.request_id,
    scenario: record.scenario,
    decision: record.decision,
    decision_attestation: record.decision_attestation,
    receipt: record.receipt as unknown as JsonValue,
  };
}

export class ControlPlaneRun {
  private decisionMutation: {
    keyDigest: string;
    bodyDigest: string;
    response: Promise<Response>;
  } | null = null;
  private readonly dispatchMutations = new Map<
    string,
    {
      keyDigest: string;
      bodyDigest: string;
      response: Promise<Response>;
    }
  >();
  private directMutation: {
    keyDigest: string;
    response: Promise<Response>;
  } | null = null;
  private finalization: {
    keyDigest: string;
    response: Promise<Response>;
  } | null = null;
  constructor(
    private readonly state: DurableObjectState,
    private readonly env: Env,
  ) {
    state.blockConcurrencyWhile(async () => {
      initializeMeta(state);
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS idempotency(operation TEXT NOT NULL,key_digest TEXT NOT NULL,body_digest TEXT NOT NULL,response_json TEXT NOT NULL,PRIMARY KEY(operation,key_digest))",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS decision_denominator(scenario TEXT PRIMARY KEY NOT NULL,record_json TEXT NOT NULL)",
      );
    });
  }

  private load(): RunSnapshot {
    const snapshot = metaGet<RunSnapshot>(this.state, "snapshot");
    if (snapshot === null) throw new HttpError(404, "RUN_NOT_FOUND", "run does not exist");
    return snapshot;
  }

  private save(snapshot: RunSnapshot): void {
    metaPut(this.state, "snapshot", snapshot);
  }

  private async authorize(request: Request, snapshot: RunSnapshot): Promise<void> {
    const supplied = request.headers.get("x-capability-digest") ?? "";
    if (!/^sha256:[0-9a-f]{64}$/u.test(supplied)) {
      throw new HttpError(401, "UNAUTHORIZED", "run capability is required");
    }
    if (!(await constantTimeDigestEqual(supplied, snapshot.capability_token_hash))) {
      throw new HttpError(401, "UNAUTHORIZED", "run capability is not accepted");
    }
  }

  private idempotencyReplay(request: Request, operation: string): Response {
    const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
    const bodyDigest = request.headers.get("x-body-digest") ?? "";
    if (
      !/^sha256:[0-9a-f]{64}$/u.test(keyDigest) ||
      !/^sha256:[0-9a-f]{64}$/u.test(bodyDigest)
    ) {
      throw new HttpError(400, "MISSING_IDEMPOTENCY", "idempotency digests are required");
    }
    const prior = this.state.storage.sql
      .exec<{ body_digest: string; response_json: string }>(
        "SELECT body_digest,response_json FROM idempotency WHERE operation=? AND key_digest=?",
        operation,
        keyDigest,
      )
      .toArray()[0];
    if (prior === undefined) {
      throw new HttpError(404, "IDEMPOTENCY_MISS", "idempotency key has no stored response");
    }
    if (prior.body_digest !== bodyDigest) {
      throw new HttpError(
        409,
        "IDEMPOTENCY_CONFLICT",
        "idempotency key is already bound to another request",
      );
    }
    return new Response(prior.response_json, {
      status: 200,
      headers: {
        "content-type": "application/json; charset=utf-8",
        "cache-control": "no-store",
        "x-content-type-options": "nosniff",
      },
    });
  }

  private async idempotent(
    request: Request,
    operation: string,
    execute: () => Promise<JsonObject>,
    snapshot: RunSnapshot,
  ): Promise<Response> {
    const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
    const bodyDigest = request.headers.get("x-body-digest") ?? "";
    if (
      !/^sha256:[0-9a-f]{64}$/u.test(keyDigest) ||
      !/^sha256:[0-9a-f]{64}$/u.test(bodyDigest)
    ) {
      throw new HttpError(400, "MISSING_IDEMPOTENCY", "idempotency digests are required");
    }
    const rows = this.state.storage.sql
      .exec<{ body_digest: string; response_json: string }>(
        "SELECT body_digest,response_json FROM idempotency WHERE operation=? AND key_digest=?",
        operation,
        keyDigest,
      )
      .toArray();
    const prior = rows[0];
    if (prior !== undefined) {
      if (prior.body_digest !== bodyDigest) {
        throw new HttpError(
          409,
          "IDEMPOTENCY_CONFLICT",
          "idempotency key is already bound to another request",
        );
      }
      return new Response(prior.response_json, {
        status: 200,
        headers: {
          "content-type": "application/json; charset=utf-8",
          "cache-control": "no-store",
          "x-content-type-options": "nosniff",
        },
      });
    }
    const result = await execute();
    const responseJson = `${canonicalize(result)}\n`;
    await this.state.storage.transaction(async () => {
      this.save(snapshot);
      await this.beforeMutationCommit(operation);
      this.state.storage.sql.exec(
        "INSERT INTO idempotency(operation,key_digest,body_digest,response_json) VALUES(?,?,?,?)",
        operation,
        keyDigest,
        bodyDigest,
        responseJson,
      );
    });
    return internalJson(result);
  }

  private async beforeMutationCommit(_operation: string): Promise<void> {
    await Promise.resolve();
  }

  private async beforeInitializationSave(): Promise<void> {
    await Promise.resolve();
  }

  private dependencies(): RuntimeDependencies {
    const signers = loadRoleSigners(this.env);
    const witness = this.env.RECEIPT_WITNESS.get(
      this.env.RECEIPT_WITNESS.idFromName("receipt-witness"),
    );
    return {
      signers,
      trustContextRef: `${this.env.TRUST_CONTEXT_REF}@${this.env.TRUST_CONTEXT_SHA256}`,
      recordDecisionEvaluation: async (evaluation) => {
        const prior = this.state.storage.sql
          .exec<{ record_json: string }>(
            "SELECT record_json FROM decision_denominator WHERE scenario=?",
            evaluation.scenario,
          )
          .toArray()[0];
        if (prior !== undefined) {
          return JSON.parse(prior.record_json) as DecisionEvaluation;
        }
        this.state.storage.sql.exec(
          "INSERT INTO decision_denominator(scenario,record_json) VALUES(?,?)",
          evaluation.scenario,
          JSON.stringify(evaluation),
        );
        return evaluation;
      },
      readDecisionObservations: async (runId) =>
        this.state.storage.sql
          .exec<{ record_json: string }>(
            "SELECT record_json FROM decision_denominator ORDER BY rowid",
          )
          .toArray()
          .map(
            (row) =>
              (JSON.parse(row.record_json) as DecisionEvaluation).observation,
          )
          .filter((observation) => observation.run_id === runId),
      receiveEffect: async (input) => {
        const receiver = this.env.SYNTHETIC_RECEIVER.get(
          this.env.SYNTHETIC_RECEIVER.idFromName(input.run_id),
        );
        const response = await receiver.fetch("https://internal/effect", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ...input,
            effect_key: input.mediated
              ? `permit:${input.run_id}:${input.request_id}`
              : `direct:${input.run_id}`,
          }),
        });
        if (!response.ok) throw new Error("synthetic receiver refused the fixed effect");
        return (await response.json()) as EffectObservation;
      },
      readEffects: async (runId) => {
        const receiver = this.env.SYNTHETIC_RECEIVER.get(
          this.env.SYNTHETIC_RECEIVER.idFromName(runId),
        );
        const response = await receiver.fetch("https://internal/denominator");
        if (!response.ok) throw new Error("receiver denominator is unavailable");
        const result = (await response.json()) as { effects: EffectObservation[] };
        return result.effects;
      },
      persistBeforeWitness: async (snapshot) => {
        this.save(snapshot);
      },
      witness: async (receipts) => {
        const response = await witness.fetch("https://internal/submit", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            receipts: receipts.map((receipt) => ({
              attestation: receipt.attestation,
              bytes_base64: bytesToBase64(receipt.bytes),
            })),
          }),
        });
        if (!response.ok) throw new Error("receipt witness refused verified receipt bytes");
        const result = (await response.json()) as { packet_checkpoint: JsonObject };
        return result.packet_checkpoint;
      },
    };
  }

  async fetch(request: Request): Promise<Response> {
    try {
      const url = new URL(request.url);
      if (
        request.method === "POST" &&
        request.headers.get("x-bulla-serialized-mutation") !== "1" &&
        ["/initialize", "/request", "/dispatch", "/direct", "/finalize"].includes(
          url.pathname,
        )
      ) {
        const serializedRequest = request.clone();
        return await this.state.blockConcurrencyWhile(async () => {
          const headers = new Headers(serializedRequest.headers);
          headers.set("x-bulla-serialized-mutation", "1");
          return this.fetch(new Request(serializedRequest, { headers }));
        });
      }
      if (url.pathname === "/initialize" && request.method === "POST") {
        const body = await internalBody(request);
        const existing = metaGet<RunSnapshot>(this.state, "snapshot");
        if (existing !== null) return internalJson(publicSummary(existing));
        const runId = body.run_id;
        const tokenHash = body.capability_token_hash;
        if (
          typeof runId !== "string" ||
          !/^run-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(
            runId,
          ) ||
          typeof tokenHash !== "string" ||
          !/^sha256:[0-9a-f]{64}$/u.test(tokenHash)
        ) {
          throw new HttpError(400, "INVALID_INITIALIZATION", "run initialization is malformed");
        }
        const snapshot = await createRun(
          runId,
          "redacted-capability-placeholder",
          loadRoleSigners(this.env),
          systemClock,
          `${this.env.TRUST_CONTEXT_REF}@${this.env.TRUST_CONTEXT_SHA256}`,
        );
        snapshot.capability_token_hash = tokenHash;
        await this.beforeInitializationSave();
        this.save(snapshot);
        return internalJson(publicSummary(snapshot), 201);
      }
      let snapshot = this.load();
      if (request.method === "GET" && url.pathname === "/summary") {
        return internalJson(publicSummary(snapshot));
      }
      if (request.method === "GET" && url.pathname === "/coverage") {
        if (snapshot.status !== "FINALIZED") {
          throw new HttpError(
            409,
            "COVERAGE_NOT_FINALIZED",
            "coverage remains NOT_COMPUTED until denominators freeze at finalization",
          );
        }
        return internalJson(computeCoverage(snapshot) as unknown as JsonObject);
      }
      if (request.method === "GET" && url.pathname === "/packet/manifest") {
        if (snapshot.packet === null) {
          throw new HttpError(409, "PACKET_NOT_FINALIZED", "packet is not finalized");
        }
        return internalJson(snapshot.packet.manifest as unknown as JsonObject);
      }
      if (request.method === "GET" && url.pathname.startsWith("/packet/member/")) {
        if (snapshot.packet === null) {
          throw new HttpError(409, "PACKET_NOT_FINALIZED", "packet is not finalized");
        }
        const path = decodeURIComponent(url.pathname.slice("/packet/member/".length));
        const text = snapshot.packet.members[path];
        if (text === undefined) throw new HttpError(404, "MEMBER_NOT_FOUND", "packet member not found");
        return new Response(text, {
          headers: {
            "content-type": "application/json; charset=utf-8",
            "cache-control": "public, max-age=31536000, immutable",
            "x-content-type-options": "nosniff",
          },
        });
      }
      await this.authorize(request, snapshot);
      snapshot = this.load();
      if (request.method !== "POST") throw new HttpError(405, "METHOD_NOT_ALLOWED", "method not allowed");
      const replayMatch = url.pathname.match(
        /^\/idempotency\/replay\/(request|dispatch|direct|finalize)$/u,
      );
      if (replayMatch !== null) {
        return this.idempotencyReplay(request, replayMatch[1] as string);
      }
      if (url.pathname === "/request") {
        const body = await internalBody(request);
        const scenario = body.scenario;
        if (scenario !== "mediated_append" && scenario !== "refused_append") {
          throw new HttpError(400, "INVALID_SCENARIO", "scenario is not accepted");
        }
        const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
        const bodyDigest = request.headers.get("x-body-digest") ?? "";
        const active = this.decisionMutation;
        if (active !== null) {
          if (active.keyDigest !== keyDigest) {
            throw new HttpError(
              409,
              "DECISION_IN_FLIGHT",
              "decision mutation is already in flight under another request",
            );
          }
          if (active.bodyDigest !== bodyDigest) {
            throw new HttpError(
              409,
              "IDEMPOTENCY_CONFLICT",
              "idempotency key is already bound to another request",
            );
          }
          return (await active.response).clone();
        }
        const response = this.idempotent(request, "request", async () => {
          const record = await requestDecision(snapshot, scenario, this.dependencies());
          return publicRunResponse(record);
        }, snapshot);
        this.decisionMutation = { keyDigest, bodyDigest, response };
        try {
          return (await response).clone();
        } finally {
          if (this.decisionMutation?.response === response) {
            this.decisionMutation = null;
          }
        }
      }
      if (url.pathname === "/dispatch") {
        const body = await internalBody(request);
        const attestation = body.decision_attestation;
        const argumentsHash = body.arguments_hash;
        if (
          typeof attestation !== "string" ||
          typeof argumentsHash !== "string" ||
          !/^sha256:[0-9a-f]{64}$/u.test(argumentsHash)
        ) {
          throw new HttpError(
            400,
            "INVALID_DECISION",
            "decision_attestation and arguments_hash are required",
          );
        }
        const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
        const bodyDigest = request.headers.get("x-body-digest") ?? "";
        const active = this.dispatchMutations.get(attestation);
        if (active !== undefined) {
          if (active.keyDigest !== keyDigest) {
            throw new HttpError(
              409,
              "PERMIT_IN_FLIGHT",
              "permit dispatch is already in flight under another request",
            );
          }
          if (active.bodyDigest !== bodyDigest) {
            throw new HttpError(
              409,
              "IDEMPOTENCY_CONFLICT",
              "idempotency key is already bound to another request",
            );
          }
          return (await active.response).clone();
        }
        const response = this.idempotent(request, "dispatch", async () => {
          const decision = snapshot.decisions.find(
            (record) => record.decision_attestation === attestation,
          );
          if (decision === undefined) {
            throw new HttpError(409, "DECISION_NOT_FOUND", "decision is not part of this run");
          }
          if (decision.dispatch_state === "PENDING") {
            decision.dispatch_state = "IN_FLIGHT";
            decision.observation_event_id = randomUuid();
            decision.observation_claimed_at = new Date().toISOString();
            this.save(snapshot);
          }
          const result = await dispatchDecision(
            snapshot,
            attestation,
            argumentsHash,
            this.dependencies(),
          );
          return result as unknown as JsonObject;
        }, snapshot);
        this.dispatchMutations.set(attestation, {
          keyDigest,
          bodyDigest,
          response,
        });
        try {
          return (await response).clone();
        } finally {
          if (this.dispatchMutations.get(attestation)?.response === response) {
            this.dispatchMutations.delete(attestation);
          }
        }
      }
      if (url.pathname === "/direct") {
        await internalBody(request);
        const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
        const active = this.directMutation;
        if (active !== null) {
          if (active.keyDigest !== keyDigest) {
            throw new HttpError(
              409,
              "DIRECT_EFFECT_IN_FLIGHT",
              "direct bypass mutation is already in flight under another request",
            );
          }
          return (await active.response).clone();
        }
        const response = this.idempotent(request, "direct", async () => {
          const result = await directEffect(snapshot, this.dependencies());
          return result;
        }, snapshot);
        this.directMutation = { keyDigest, response };
        try {
          return (await response).clone();
        } finally {
          if (this.directMutation?.response === response) {
            this.directMutation = null;
          }
        }
      }
      if (url.pathname === "/finalize") {
        await internalBody(request);
        const keyDigest = request.headers.get("x-idempotency-digest") ?? "";
        const active = this.finalization;
        if (active !== null) {
          if (active.keyDigest !== keyDigest) {
            throw new HttpError(
              409,
              "FINALIZATION_IN_FLIGHT",
              "run finalization is already in flight under another request",
            );
          }
          return (await active.response).clone();
        }
        const response = this.idempotent(request, "finalize", async () => {
          const result = await finalizeRun(snapshot, this.dependencies());
          return result as unknown as JsonObject;
        }, snapshot);
        this.finalization = { keyDigest, response };
        try {
          return (await response).clone();
        } finally {
          if (this.finalization?.response === response) {
            this.finalization = null;
          }
        }
      }
      throw new HttpError(404, "NOT_FOUND", "internal route not found");
    } catch (error) {
      if (error instanceof HttpError) return internalJson({ error: { code: error.code, message: error.message } }, error.status);
      return internalJson(
        {
          error: {
            code: "CONFLICT",
            message: "request could not be completed",
          },
        },
        409,
      );
    }
  }
}

export class SyntheticReceiver {
  constructor(
    private readonly state: DurableObjectState,
    _env: Env,
  ) {
    state.blockConcurrencyWhile(async () => {
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS effects(effect_key TEXT PRIMARY KEY NOT NULL,run_id TEXT NOT NULL,request_id TEXT NOT NULL,observation_id TEXT NOT NULL,record_json TEXT NOT NULL)",
      );
    });
  }

  async fetch(request: Request): Promise<Response> {
    try {
      const url = new URL(request.url);
      if (url.pathname === "/denominator" && request.method === "GET") {
        const effects = this.state.storage.sql
          .exec<{ record_json: string }>("SELECT record_json FROM effects ORDER BY rowid")
          .toArray()
          .map((row) => JSON.parse(row.record_json) as EffectObservation);
        return internalJson({ effects });
      }
      if (url.pathname !== "/effect" || request.method !== "POST") {
        throw new HttpError(404, "NOT_FOUND", "receiver route not found");
      }
      const body = await internalBody(request);
      const { effect_key: effectKey, run_id: runId, request_id: requestId, mediated, value } = body;
      if (
        typeof effectKey !== "string" ||
        typeof runId !== "string" ||
        typeof requestId !== "string" ||
        typeof mediated !== "boolean" ||
        (mediated && value !== "alpha-mediated") ||
        (!mediated && value !== "alpha-direct-bypass")
      ) {
        throw new HttpError(400, "CLOSED_SANDBOX_VIOLATION", "receiver accepts only fixed effects");
      }
      const prior = this.state.storage.sql
        .exec<{ record_json: string }>("SELECT record_json FROM effects WHERE effect_key=?", effectKey)
        .toArray()[0];
      if (prior !== undefined) return internalJson(JSON.parse(prior.record_json) as JsonObject);
      const observationId = randomUuid();
      const operationRef = await sha256Json({
        tool_name: "sandbox.append",
        value: value as string,
      });
      const record: EffectObservation = {
        anchor_id: "synthetic-receiver-effect",
        observation_id: observationId,
        run_id: runId,
        protocol: "mcp",
        operation_ref: operationRef,
        phase: "effect",
        evidence_hash: await sha256Json({
          anchor_id: "synthetic-receiver-effect",
          observation_id: observationId,
          operation_ref: operationRef,
          transport_status: "MCP_IS_ERROR_FALSE",
        }),
        request_id: requestId,
        mediated,
      };
      this.state.storage.sql.exec(
        "INSERT INTO effects(effect_key,run_id,request_id,observation_id,record_json) VALUES(?,?,?,?,?)",
        effectKey,
        runId,
        requestId,
        observationId,
        JSON.stringify(record),
      );
      return internalJson(record);
    } catch (error) {
      if (error instanceof HttpError) return internalJson({ error: { code: error.code, message: error.message } }, error.status);
      return internalJson({ error: { code: "RECEIVER_FAILURE", message: "receiver failed closed" } }, 500);
    }
  }
}

interface WitnessRow {
  leaf_index: number;
  attestation: string;
  issuer: string;
  content_hash: string;
  leaf_hash: string;
  receipt_sha256: string;
  receipt_bytes: ArrayBuffer;
  received_at: string;
}

export class ReceiptWitness {
  constructor(
    private readonly state: DurableObjectState,
    private readonly env: Env,
  ) {
    state.blockConcurrencyWhile(async () => {
      initializeMeta(state);
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS receipts(leaf_index INTEGER PRIMARY KEY,attestation TEXT UNIQUE NOT NULL,issuer TEXT NOT NULL,content_hash TEXT NOT NULL,leaf_hash TEXT NOT NULL,receipt_sha256 TEXT NOT NULL,receipt_bytes BLOB NOT NULL,received_at TEXT NOT NULL)",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS frontier(level INTEGER PRIMARY KEY,hash TEXT NOT NULL)",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS nodes(start_index INTEGER NOT NULL,tree_size INTEGER NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(start_index,tree_size))",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS checkpoints(tree_size INTEGER PRIMARY KEY,checkpoint_json TEXT NOT NULL)",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS run_allocations(idempotency_digest TEXT PRIMARY KEY,body_digest TEXT NOT NULL,capability_key_version TEXT NOT NULL,capability_token_hash TEXT NOT NULL,run_id TEXT UNIQUE NOT NULL,created_at TEXT NOT NULL)",
      );
      state.storage.sql.exec(
        "CREATE TABLE IF NOT EXISTS intake_batches(batch_hash TEXT PRIMARY KEY,response_json TEXT NOT NULL)",
      );
    });
  }

  private count(): number {
    return (
      this.state.storage.sql
        .exec<{ count: number }>("SELECT COUNT(*) AS count FROM receipts")
        .toArray()[0]?.count ?? 0
    );
  }

  private largestPowerOfTwoBelow(value: number): number {
    let power = 1;
    while (power * 2 < value) power *= 2;
    return power;
  }

  private async rangeRoot(start: number, size: number): Promise<string> {
    if (size === 0) return sha256Bytes(new Uint8Array());
    if ((size & (size - 1)) === 0) {
      const node = this.state.storage.sql
        .exec<{ hash: string }>(
          "SELECT hash FROM nodes WHERE start_index=? AND tree_size=?",
          start,
          size,
        )
        .toArray()[0]?.hash;
      if (node === undefined) throw new Error("witness node index is incomplete");
      return node;
    }
    const split = this.largestPowerOfTwoBelow(size);
    return rfc6962NodeHash(
      await this.rangeRoot(start, split),
      await this.rangeRoot(start + split, size - split),
    );
  }

  private async nodeInclusionProof(
    leafIndex: number,
    start: number,
    size: number,
  ): Promise<string[]> {
    if (size === 1) return [];
    const split = this.largestPowerOfTwoBelow(size);
    if (leafIndex < start + split) {
      return [
        ...(await this.nodeInclusionProof(leafIndex, start, split)),
        await this.rangeRoot(start + split, size - split),
      ];
    }
    return [
      ...(await this.nodeInclusionProof(leafIndex, start + split, size - split)),
      await this.rangeRoot(start, split),
    ];
  }

  private async nodeConsistencySubproof(
    oldSize: number,
    start: number,
    newSize: number,
    complete: boolean,
  ): Promise<string[]> {
    if (oldSize === newSize) {
      return complete ? [] : [await this.rangeRoot(start, newSize)];
    }
    const split = this.largestPowerOfTwoBelow(newSize);
    if (oldSize <= split) {
      return [
        ...(await this.nodeConsistencySubproof(oldSize, start, split, complete)),
        await this.rangeRoot(start + split, newSize - split),
      ];
    }
    return [
      ...(await this.nodeConsistencySubproof(
        oldSize - split,
        start + split,
        newSize - split,
        false,
      )),
      await this.rangeRoot(start, split),
    ];
  }

  private async nodeConsistencyProof(oldSize: number, newSize: number): Promise<string[]> {
    if (oldSize === 0 || oldSize === newSize) return [];
    return this.nodeConsistencySubproof(oldSize, 0, newSize, true);
  }

  private async append(
    attestation: string,
    bytes: Uint8Array,
    acceptedIssuer: string,
  ): Promise<{ row: WitnessRow; added: boolean }> {
    const receiptSha = await sha256Bytes(bytes);
    const prior = this.state.storage.sql
      .exec<WitnessRow>(
        "SELECT leaf_index,attestation,issuer,content_hash,leaf_hash,receipt_sha256,receipt_bytes,received_at FROM receipts WHERE attestation=?",
        attestation,
      )
      .toArray()[0];
    if (prior !== undefined) {
      if (prior.receipt_sha256 !== receiptSha) {
        throw new HttpError(
          409,
          "ALTERNATE_SERIALIZATION",
          "attestation is already bound to different exact receipt bytes",
        );
      }
      return { row: prior, added: false };
    }
    const document = parseStrictJsonBytes(bytes) as unknown as {
      action: { type: string; subject: { issuer_role?: string } };
      signature: { issuer: string };
      hashes: { content: string };
    };
    const verification = await verifyActionReceiptV04Bytes(bytes, {
      expected_issuers: [acceptedIssuer],
    });
    if (
      verification.structure !== "VERIFIED" ||
      verification.integrity !== "VERIFIED" ||
      verification.signatures !== "VERIFIED" ||
      verification.authority_authenticity !== "VERIFIED" ||
      verification.attestation !== attestation
    ) {
      throw new HttpError(400, "RECEIPT_REJECTED", "receipt failed witness intake verification");
    }
    const count = this.count();
    if (count >= 90_000) {
      throw new HttpError(503, "CAPACITY_LIMIT", "witness receipt capacity reached");
    }
    const leaf = await witnessLeaf({
      issuer: document.signature.issuer,
      content_hash: document.hashes.content,
      attestation_hash: attestation,
    });
    const receivedAt = new Date().toISOString();
    const row: WitnessRow = {
      leaf_index: count,
      attestation,
      issuer: document.signature.issuer,
      content_hash: document.hashes.content,
      leaf_hash: leaf,
      receipt_sha256: receiptSha,
      receipt_bytes: bufferSource(bytes),
      received_at: receivedAt,
    };
    this.state.storage.sql.exec(
      "INSERT INTO receipts(leaf_index,attestation,issuer,content_hash,leaf_hash,receipt_sha256,receipt_bytes,received_at) VALUES(?,?,?,?,?,?,?,?)",
      row.leaf_index,
      row.attestation,
      row.issuer,
      row.content_hash,
      row.leaf_hash,
      row.receipt_sha256,
      row.receipt_bytes,
      row.received_at,
    );
    this.state.storage.sql.exec(
      "INSERT INTO nodes(start_index,tree_size,hash) VALUES(?,?,?)",
      row.leaf_index,
      1,
      leaf,
    );
    let level = 0;
    let hash = leaf;
    let size = 1;
    let start = row.leaf_index;
    while (((count >> level) & 1) === 1) {
      const left = this.state.storage.sql
        .exec<{ hash: string }>("SELECT hash FROM frontier WHERE level=?", level)
        .toArray()[0]?.hash;
      if (left === undefined) throw new Error("witness frontier is inconsistent");
      hash = await rfc6962NodeHash(left, hash);
      size *= 2;
      start -= size / 2;
      this.state.storage.sql.exec("DELETE FROM frontier WHERE level=?", level);
      this.state.storage.sql.exec(
        "INSERT OR REPLACE INTO nodes(start_index,tree_size,hash) VALUES(?,?,?)",
        start,
        size,
        hash,
      );
      level += 1;
    }
    this.state.storage.sql.exec(
      "INSERT OR REPLACE INTO frontier(level,hash) VALUES(?,?)",
      level,
      hash,
    );
    return { row, added: true };
  }

  private expectedIssuer(
    document: {
      action: { type: string; subject: { issuer_role?: string } };
    },
    signers: RoleSigners,
  ): string {
    const actionType = document.action?.type;
    if (actionType === "eval.run.authorize") return signers.authorization.issuer;
    if (actionType === "capability.decide" || actionType === "capability.observe") {
      return signers.boundary.issuer;
    }
    if (actionType === "incident.handoff") return signers.incidentCommander.issuer;
    if (actionType === "incident.packet.publish") return signers.publication.issuer;
    if (actionType === "incident.statement") {
      const role = document.action.subject?.issuer_role;
      if (role === "boundary") return signers.boundary.issuer;
      if (role === "target") return signers.target.issuer;
      if (role === "incident_commander") return signers.incidentCommander.issuer;
    }
    throw new HttpError(
      400,
      "RECEIPT_ROLE_REJECTED",
      "receipt action is not accepted for its asserted issuer role",
    );
  }

  private async root(): Promise<string> {
    return this.rangeRoot(0, this.count());
  }

  private async treeCheckpoint(receivedAt: string): Promise<JsonObject> {
    const signers = loadRoleSigners(this.env);
    const treeSize = this.count();
    const previous = this.state.storage.sql
      .exec<{ checkpoint_json: string }>(
        "SELECT checkpoint_json FROM checkpoints ORDER BY tree_size DESC LIMIT 1",
      )
      .toArray()[0];
    const witnessedAt = new Date().toISOString();
    const preimage: JsonObject = {
      schema_version: 1,
      profile: "bulla.control-plane-alpha/0.1-experimental",
      witness_id: PACKET_WITNESS_ID,
      log_id: "bulla-control-plane-alpha-receipt-log",
      tree_size: treeSize,
      root_hash: await this.root(),
      previous_checkpoint_hash:
        previous === undefined
          ? null
          : ((JSON.parse(previous.checkpoint_json) as JsonObject).checkpoint_hash as string),
      received_at: receivedAt,
      witnessed_at: witnessedAt,
      anchored_before: null,
    };
    const checkpointHash = await sha256Json(preimage);
    const checkpoint: JsonObject = {
      ...preimage,
      checkpoint_hash: checkpointHash,
      proof: (await signDomain(signers.witness, "witness-checkpoint", checkpointHash)) as unknown as JsonValue,
    };
    this.state.storage.sql.exec(
      "INSERT OR REPLACE INTO checkpoints(tree_size,checkpoint_json) VALUES(?,?)",
      treeSize,
      JSON.stringify(checkpoint),
    );
    return checkpoint;
  }

  private async beforeWitnessBatchCommit(
    _batchHash: string,
    _responseJson: string,
  ): Promise<void> {
    await Promise.resolve();
  }

  private async afterWitnessBatchCommit(
    _batchHash: string,
    _responseJson: string,
  ): Promise<void> {
    await Promise.resolve();
  }

  async fetch(request: Request): Promise<Response> {
    try {
      const url = new URL(request.url);
      if (url.pathname.startsWith("/run-exists/") && request.method === "GET") {
        const runId = decodeURIComponent(url.pathname.slice("/run-exists/".length));
        const present =
          this.state.storage.sql
            .exec<{ present: number }>(
              "SELECT 1 AS present FROM run_allocations WHERE run_id=?",
              runId,
            )
            .toArray()[0] !== undefined;
        return internalJson({ exists: present });
      }
      if (url.pathname === "/lookup-allocation" && request.method === "POST") {
        const body = await internalBody(request);
        const idempotencyDigest = body.idempotency_digest;
        const bodyDigest = body.body_digest;
        const capabilityKeyVersion = body.capability_key_version;
        const capabilityTokenHash = body.capability_token_hash;
        if (
          typeof idempotencyDigest !== "string" ||
          typeof bodyDigest !== "string" ||
          capabilityKeyVersion !== CAPABILITY_TOKEN_DERIVATION_VERSION ||
          typeof capabilityTokenHash !== "string" ||
          !/^sha256:[0-9a-f]{64}$/u.test(idempotencyDigest) ||
          !/^sha256:[0-9a-f]{64}$/u.test(bodyDigest) ||
          !/^sha256:[0-9a-f]{64}$/u.test(capabilityTokenHash)
        ) {
          throw new HttpError(400, "INVALID_ALLOCATION", "allocation digests are malformed");
        }
        const prior = this.state.storage.sql
          .exec<{
            body_digest: string;
            capability_key_version: string;
            capability_token_hash: string;
            run_id: string;
          }>(
            "SELECT body_digest,capability_key_version,capability_token_hash,run_id FROM run_allocations WHERE idempotency_digest=?",
            idempotencyDigest,
          )
          .toArray()[0];
        if (prior === undefined) {
          throw new HttpError(404, "IDEMPOTENCY_MISS", "run key has no stored allocation");
        }
        if (prior.body_digest !== bodyDigest) {
          throw new HttpError(409, "IDEMPOTENCY_CONFLICT", "run key is bound to another body");
        }
        if (
          prior.capability_key_version !== capabilityKeyVersion ||
          !(await constantTimeDigestEqual(
            prior.capability_token_hash,
            capabilityTokenHash,
          ))
        ) {
          throw new HttpError(
            503,
            "CAPABILITY_KEY_ROTATED",
            "run creation replay is unavailable after capability-key rotation",
          );
        }
        return internalJson({ run_id: prior.run_id, replay: true });
      }
      if (url.pathname === "/allocate-run" && request.method === "POST") {
        const body = await internalBody(request);
        const idempotencyDigest = body.idempotency_digest;
        const bodyDigest = body.body_digest;
        const capabilityKeyVersion = body.capability_key_version;
        const capabilityTokenHash = body.capability_token_hash;
        if (
          typeof idempotencyDigest !== "string" ||
          typeof bodyDigest !== "string" ||
          capabilityKeyVersion !== CAPABILITY_TOKEN_DERIVATION_VERSION ||
          typeof capabilityTokenHash !== "string" ||
          !/^sha256:[0-9a-f]{64}$/u.test(idempotencyDigest) ||
          !/^sha256:[0-9a-f]{64}$/u.test(bodyDigest) ||
          !/^sha256:[0-9a-f]{64}$/u.test(capabilityTokenHash)
        ) {
          throw new HttpError(400, "INVALID_ALLOCATION", "allocation digests are malformed");
        }
        const prior = this.state.storage.sql
          .exec<{
            body_digest: string;
            capability_key_version: string;
            capability_token_hash: string;
            run_id: string;
          }>(
            "SELECT body_digest,capability_key_version,capability_token_hash,run_id FROM run_allocations WHERE idempotency_digest=?",
            idempotencyDigest,
          )
          .toArray()[0];
        if (prior !== undefined) {
          if (prior.body_digest !== bodyDigest) {
            throw new HttpError(409, "IDEMPOTENCY_CONFLICT", "run key is bound to another body");
          }
          if (
            prior.capability_key_version !== capabilityKeyVersion ||
            !(await constantTimeDigestEqual(
              prior.capability_token_hash,
              capabilityTokenHash,
            ))
          ) {
            throw new HttpError(
              503,
              "CAPABILITY_KEY_ROTATED",
              "run creation replay is unavailable after capability-key rotation",
            );
          }
          return internalJson({ run_id: prior.run_id, replay: true });
        }
        const count =
          this.state.storage.sql
            .exec<{ count: number }>("SELECT COUNT(*) AS count FROM run_allocations")
            .toArray()[0]?.count ?? 0;
        if (count >= 10_000) {
          throw new HttpError(503, "CAPACITY_LIMIT", "run capacity reached");
        }
        const runId = `run-${randomUuid()}`;
        this.state.storage.sql.exec(
          "INSERT INTO run_allocations(idempotency_digest,body_digest,capability_key_version,capability_token_hash,run_id,created_at) VALUES(?,?,?,?,?,?)",
          idempotencyDigest,
          bodyDigest,
          capabilityKeyVersion,
          capabilityTokenHash,
          runId,
          new Date().toISOString(),
        );
        return internalJson({ run_id: runId, replay: false }, 201);
      }
      if (url.pathname === "/submit" && request.method === "POST") {
        const body = await internalBody(request);
        if (!Array.isArray(body.receipts) || body.receipts.length === 0 || body.receipts.length > 16) {
          throw new HttpError(400, "INVALID_RECEIPT_BATCH", "witness batch must contain 1 to 16 receipts");
        }
        const signers = loadRoleSigners(this.env);
        const batchHash = await sha256Json({ receipts: body.receipts });
        const priorBatch = this.state.storage.sql
          .exec<{ response_json: string }>(
            "SELECT response_json FROM intake_batches WHERE batch_hash=?",
            batchHash,
          )
          .toArray()[0];
        if (priorBatch !== undefined) {
          return new Response(priorBatch.response_json, {
            headers: {
              "content-type": "application/json; charset=utf-8",
              "cache-control": "no-store",
            },
          });
        }
        const prepared: {
          attestation: string;
          bytes: Uint8Array;
          expectedIssuer: string;
          receiptSha256: string;
        }[] = [];
        const batchAttestations = new Set<string>();
        for (const item of body.receipts as JsonValue[]) {
          if (
            item === null ||
            typeof item !== "object" ||
            Array.isArray(item) ||
            Object.keys(item).length !== 2 ||
            !Object.hasOwn(item, "attestation") ||
            !Object.hasOwn(item, "bytes_base64")
          ) {
            throw new HttpError(
              400,
              "INVALID_RECEIPT_BATCH",
              "witness entry must contain only attestation and bytes_base64",
            );
          }
          const entry = item as JsonObject;
          if (
            typeof entry.attestation !== "string" ||
            !/^sha256:[0-9a-f]{64}$/u.test(entry.attestation) ||
            typeof entry.bytes_base64 !== "string" ||
            entry.bytes_base64.length === 0 ||
            entry.bytes_base64.length % 4 !== 0 ||
            !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(
              entry.bytes_base64,
            )
          ) {
            throw new HttpError(
              400,
              "INVALID_RECEIPT_BATCH",
              "witness entry fields are malformed",
            );
          }
          if (batchAttestations.has(entry.attestation)) {
            throw new HttpError(
              400,
              "DUPLICATE_BATCH_ATTESTATION",
              "witness batch contains a duplicate attestation",
            );
          }
          batchAttestations.add(entry.attestation);
          const bytes = base64ToBytes(entry.bytes_base64);
          if (bytesToBase64(bytes) !== entry.bytes_base64) {
            throw new HttpError(
              400,
              "INVALID_RECEIPT_BATCH",
              "receipt bytes use noncanonical base64",
            );
          }
          const document = parseStrictJsonBytes(bytes) as unknown as {
            action: { type: string; subject: { issuer_role?: string } };
          };
          const expectedIssuer = this.expectedIssuer(document, signers);
          const verification = await verifyActionReceiptV04Bytes(bytes, {
            expected_issuers: [expectedIssuer],
          });
          if (
            verification.structure !== "VERIFIED" ||
            verification.integrity !== "VERIFIED" ||
            verification.signatures !== "VERIFIED" ||
            verification.occurrence_binding !== "VERIFIED" ||
            verification.authority_authenticity !== "VERIFIED" ||
            verification.attestation !== entry.attestation
          ) {
            throw new HttpError(
              400,
              "RECEIPT_REJECTED",
              "receipt failed witness intake verification",
            );
          }
          prepared.push({
            attestation: entry.attestation,
            bytes,
            expectedIssuer,
            receiptSha256: await sha256Bytes(bytes),
          });
        }
        const responseJson = await this.state.storage.transaction(async () => {
          const concurrentPrior = this.state.storage.sql
            .exec<{ response_json: string }>(
              "SELECT response_json FROM intake_batches WHERE batch_hash=?",
              batchHash,
            )
            .toArray()[0];
          if (concurrentPrior !== undefined) return concurrentPrior.response_json;

          let newCount = 0;
          for (const entry of prepared) {
            const existing = this.state.storage.sql
              .exec<{ receipt_sha256: string }>(
                "SELECT receipt_sha256 FROM receipts WHERE attestation=?",
                entry.attestation,
              )
              .toArray()[0];
            if (existing === undefined) newCount += 1;
            else if (existing.receipt_sha256 !== entry.receiptSha256) {
              throw new HttpError(
                409,
                "ALTERNATE_SERIALIZATION",
                "attestation is already bound to different exact receipt bytes",
              );
            }
          }
          if (this.count() + newCount > 90_000) {
            throw new HttpError(503, "CAPACITY_LIMIT", "witness receipt capacity reached");
          }

          const appended: WitnessRow[] = [];
          let finalCheckpoint: JsonObject | null = null;
          for (const entry of prepared) {
            const result = await this.append(
              entry.attestation,
              entry.bytes,
              entry.expectedIssuer,
            );
            appended.push(result.row);
            if (result.added) {
              finalCheckpoint = await this.treeCheckpoint(result.row.received_at);
            }
          }
          const receivedAt = appended.reduce(
            (latest, row) => (row.received_at > latest ? row.received_at : latest),
            appended[0]?.received_at ?? new Date().toISOString(),
          );
          const treeCheckpoint =
            finalCheckpoint ??
            (() => {
              const latest = this.state.storage.sql
                .exec<{ checkpoint_json: string }>(
                  "SELECT checkpoint_json FROM checkpoints ORDER BY tree_size DESC LIMIT 1",
                )
                .toArray()[0];
              if (latest === undefined) throw new Error("witness replay checkpoint is missing");
              return JSON.parse(latest.checkpoint_json) as JsonObject;
            })();
          const packetPreimage: JsonObject = {
            witness_id: PACKET_WITNESS_ID,
            root_ref: PACKET_WITNESS_ROOT,
            received_at: receivedAt,
            witnessed_at: treeCheckpoint.witnessed_at as string,
            included_attestation_hashes: appended.map((row) => row.attestation),
          };
          const checkpointHash = await sha256Json(packetPreimage);
          const packetCheckpoint: JsonObject = {
            schema_version: 1,
            ...packetPreimage,
            anchored_before: null,
            checkpoint_hash: checkpointHash,
            proof: (await signDomain(
              signers.witness,
              "witness-checkpoint",
              checkpointHash,
            )) as unknown as JsonValue,
          };
          const atomicResponseJson = `${JSON.stringify({
            tree_checkpoint: treeCheckpoint,
            packet_checkpoint: packetCheckpoint,
          })}\n`;
          await this.beforeWitnessBatchCommit(batchHash, atomicResponseJson);
          this.state.storage.sql.exec(
            "INSERT INTO intake_batches(batch_hash,response_json) VALUES(?,?)",
            batchHash,
            atomicResponseJson,
          );
          return atomicResponseJson;
        });
        await this.afterWitnessBatchCommit(batchHash, responseJson);
        return new Response(responseJson, {
          headers: {
            "content-type": "application/json; charset=utf-8",
            "cache-control": "no-store",
          },
        });
      }
      if (url.pathname === "/checkpoints/latest" && request.method === "GET") {
        const latest = this.state.storage.sql
          .exec<{ checkpoint_json: string }>(
            "SELECT checkpoint_json FROM checkpoints ORDER BY tree_size DESC LIMIT 1",
          )
          .toArray()[0];
        if (latest === undefined) throw new HttpError(404, "NO_CHECKPOINT", "no checkpoint exists");
        return internalJson(JSON.parse(latest.checkpoint_json) as JsonObject);
      }
      if (url.pathname.startsWith("/inclusion/") && request.method === "GET") {
        const inclusionParameters = [...url.searchParams.keys()];
        if (
          inclusionParameters.some((parameter) => parameter !== "at") ||
          url.searchParams.getAll("at").length > 1
        ) {
          throw new HttpError(
            400,
            "INVALID_TREE_SIZE",
            "inclusion accepts at most one at tree size",
          );
        }
        const attestation = decodeURIComponent(url.pathname.slice("/inclusion/".length));
        const row = this.state.storage.sql
          .exec<WitnessRow>(
            "SELECT leaf_index,attestation,issuer,content_hash,leaf_hash,receipt_sha256,receipt_bytes,received_at FROM receipts WHERE attestation=?",
            attestation,
          )
          .toArray()[0];
        if (row === undefined) throw new HttpError(404, "ATTESTATION_NOT_FOUND", "attestation not found");
        const at = url.searchParams.get("at");
        const currentSize = this.count();
        const treeSize = at === null ? currentSize : Number(at);
        if (
          !Number.isSafeInteger(treeSize) ||
          treeSize < 1 ||
          treeSize > currentSize
        ) {
          throw new HttpError(
            400,
            "INVALID_TREE_SIZE",
            "at must identify an existing signed checkpoint",
          );
        }
        if (row.leaf_index >= treeSize) {
          throw new HttpError(
            404,
            "ATTESTATION_NOT_IN_CHECKPOINT",
            "attestation is not included in the selected checkpoint",
          );
        }
        if (at !== null) {
          const checkpoint = this.state.storage.sql
            .exec<{ present: number }>(
              "SELECT 1 AS present FROM checkpoints WHERE tree_size=?",
              treeSize,
            )
            .toArray()[0];
          if (checkpoint === undefined) {
            throw new HttpError(
              400,
              "INVALID_TREE_SIZE",
              "at must identify an existing signed checkpoint",
            );
          }
        }
        return internalJson({
          attestation,
          index: row.leaf_index,
          tree_size: treeSize,
          leaf: row.leaf_hash,
          root: await this.rangeRoot(0, treeSize),
          proof: await this.nodeInclusionProof(row.leaf_index, 0, treeSize),
          receipt_sha256: row.receipt_sha256,
          received_at: row.received_at,
        });
      }
      if (url.pathname === "/consistency" && request.method === "GET") {
        const consistencyParameters = [...url.searchParams.keys()];
        if (
          consistencyParameters.some(
            (parameter) => parameter !== "from" && parameter !== "to",
          ) ||
          url.searchParams.getAll("from").length !== 1 ||
          url.searchParams.getAll("to").length > 1
        ) {
          throw new HttpError(
            400,
            "INVALID_TREE_SIZE",
            "consistency requires one from and accepts at most one to tree size",
          );
        }
        const oldSize = Number(url.searchParams.get("from"));
        const to = url.searchParams.get("to");
        const currentSize = this.count();
        const newSize = to === null ? currentSize : Number(to);
        if (!Number.isSafeInteger(oldSize) || oldSize < 0 || oldSize > newSize) {
          throw new HttpError(400, "INVALID_TREE_SIZE", "from must be a prior tree size");
        }
        if (
          !Number.isSafeInteger(newSize) ||
          newSize < 0 ||
          newSize > currentSize
        ) {
          throw new HttpError(
            400,
            "INVALID_TREE_SIZE",
            "to must identify an existing signed checkpoint",
          );
        }
        if (to !== null) {
          if (newSize === 0) {
            throw new HttpError(
              400,
              "INVALID_TREE_SIZE",
              "to must identify an existing signed checkpoint",
            );
          }
          const checkpoint = this.state.storage.sql
            .exec<{ present: number }>(
              "SELECT 1 AS present FROM checkpoints WHERE tree_size=?",
              newSize,
            )
            .toArray()[0];
          if (checkpoint === undefined) {
            throw new HttpError(
              400,
              "INVALID_TREE_SIZE",
              "to must identify an existing signed checkpoint",
            );
          }
        }
        return internalJson({
          old_size: oldSize,
          new_size: newSize,
          old_root: await this.rangeRoot(0, oldSize),
          new_root: await this.rangeRoot(0, newSize),
          proof: await this.nodeConsistencyProof(oldSize, newSize),
        });
      }
      if (url.pathname.startsWith("/receipts/") && request.method === "GET") {
        const attestation = decodeURIComponent(url.pathname.slice("/receipts/".length));
        const row = this.state.storage.sql
          .exec<{ receipt_bytes: ArrayBuffer; receipt_sha256: string }>(
            "SELECT receipt_bytes,receipt_sha256 FROM receipts WHERE attestation=?",
            attestation,
          )
          .toArray()[0];
        if (row === undefined) throw new HttpError(404, "ATTESTATION_NOT_FOUND", "attestation not found");
        return new Response(row.receipt_bytes, {
          headers: {
            "content-type": "application/json; charset=utf-8",
            etag: `"${row.receipt_sha256}"`,
            "cache-control": "public, max-age=31536000, immutable",
          },
        });
      }
      throw new HttpError(404, "NOT_FOUND", "witness route not found");
    } catch (error) {
      if (error instanceof HttpError) return internalJson({ error: { code: error.code, message: error.message } }, error.status);
      return internalJson({ error: { code: "WITNESS_FAILURE", message: "witness failed closed" } }, 500);
    }
  }
}

const PACKET_WITNESS_ID = "bulla-control-plane-alpha-witness";
const PACKET_WITNESS_ROOT = "witness://bulla-control-plane-alpha/public-alpha-v1";
