import { appendFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { randomBytes, randomUUID } from "node:crypto";
import { Database } from "bun:sqlite";
import { z } from "zod";
import type { FetchLike } from "./adapter";
import { configuredFactoryDbPath, resolveFactoryDbPath } from "./adapters/factory";
import { HarnessApiError, type HarnessAdapter, type HarnessJson } from "./adapters/harness";
import { abandonRun, restoreRun } from "./abandoned-store";
import { loadConfig } from "./config";
import { IncidentMutationError, IncidentResolutionConflictError } from "./incidents/incident-service";
import { actionsJournalFile } from "./paths";
import { PermissionChoiceSchema, type PermissionQueue } from "./permissions";
import { writeSessionKeys } from "./sessions/screen";
import { TMUX_NAMED_KEYS } from "./sessions/tmux";
import type { CollectorState } from "./state";

/** Default-deny allowlist — exactly these verbs are permitted. */
export const ALLOWED_ACTION_VERBS = [
  "reap",
  "ci-rerun",
  "ci.rerunFailed",
  "ci.cancelRun",
  "steer",
  "snooze",
  "decision",
  "abandon",
  "restore",
  "box-drain",
  "box-restore",
  "host-quarantine",
  "host-unquarantine",
  "admission-reconcile",
  "job-retry",
  "ci-reconcile",
  "recall-spill",
  "harness.task.pause",
  "harness.task.resume",
  "harness.task.kill",
  "harness.run.pause",
  "harness.run.resume",
  "harness.run.kill",
  "harness.config.patch",
  "factory.decision.answer",
  "factory.run.stop",
  "sessions.sendKeys",
  "permission.answer",
  "permission.arm",
  "incident.resolve",
] as const;
export type AllowedActionVerb = (typeof ALLOWED_ACTION_VERBS)[number];

export const OFFLOAD_ACTION_VERBS = [
  "box-drain",
  "box-restore",
  "host-quarantine",
  "host-unquarantine",
  "admission-reconcile",
  "job-retry",
  "ci-reconcile",
  "recall-spill",
] as const;
export type OffloadActionVerb = (typeof OFFLOAD_ACTION_VERBS)[number];

export interface ActionJournalEntry {
  ts: string;
  verb: string;
  args: Record<string, string>;
  requestedBy: string;
  result: string;
  rc: number;
}

export interface SpawnResult {
  rc: number;
  stdout: string;
  stderr: string;
}

export type SpawnFn = (argv: string[]) => Promise<SpawnResult>;

export interface ActionGatewayDeps {
  state: CollectorState;
  harness?: HarnessAdapter;
  permissions?: PermissionQueue;
  journalPath?: string;
  spawn?: SpawnFn;
  now?: () => number;
  controllerUrl?: string;
  controllerToken?: string;
  fetcher?: FetchLike;
  randomUUID?: () => string;
  /** Injectable factory sssf.db path; defaults to configured/global path resolution. */
  factoryDbPath?: string;
  incidents?: IncidentsProviderLike;
}

/** The slice of IncidentsProvider the gateway needs — keeps actions decoupled from the full provider. */
export interface IncidentsProviderLike {
  resolveIncident(incidentId: string, artifact: string, summary?: string): Promise<unknown>;
}

export interface ActionGateway {
  handle(req: Request, verb: string): Promise<Response>;
}

const ReapArgsSchema = z.object({
  pid: z
    .string()
    .regex(/^\d+$/, "pid must be an integer")
    .transform((value) => Number(value))
    .refine((value) => Number.isSafeInteger(value) && value > 0, "pid must be an integer"),
});

const CiRerunArgsSchema = z.object({
  id: z
    .string()
    .regex(/^\d+$/, "id must be an integer")
    .transform((value) => Number(value))
    .refine((value) => Number.isSafeInteger(value) && value > 0, "id must be an integer"),
});

const TrainActionArgsSchema = z
  .object({
    repo: z.string().regex(
      /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?\/[A-Za-z0-9._-]{1,100}$/,
      "repo must be an owner/repository slug",
    ),
    runId: z
      .string()
      .regex(/^[1-9]\d*$/, "runId must be a positive integer")
      .transform((value) => Number(value))
      .refine((value) => Number.isSafeInteger(value), "runId must be a positive safe integer"),
  })
  .strict();

const SteerArgsSchema = z.object({
  runId: z.string().min(1),
  taskId: z.string().min(1),
  text: z.string().optional(),
  restart: z.enum(["true", "false"]).optional(),
});

const SnoozeArgsSchema = z.object({
  itemId: z.string().min(1),
  durationMs: z
    .string()
    .regex(/^\d+$/)
    .optional(),
});

const DecisionArgsSchema = z.object({
  runId: z.string().min(1),
  decisionId: z.string().min(1),
  choice: z.string().min(1),
});

const FactoryDecisionArgsSchema = z.object({
  decisionId: z.string().min(1),
  choice: z.string().min(1),
});

const PermissionAnswerArgsSchema = z.object({
  requestId: z.string().min(1),
  choice: PermissionChoiceSchema,
});

const PermissionArmArgsSchema = z.object({
  state: z.enum(["on", "off"]),
});

const FactoryStopArgsSchema = z.object({
  adwId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/, "adwId must be a session id"),
});

const SessionSendKeysArgsSchema = z.object({
  id: z.string().min(1),
  text: z.string().max(4096).optional(),
  key: z.enum(TMUX_NAMED_KEYS).optional(),
}).strict().refine(
  (args) => (args.text === undefined) !== (args.key === undefined),
  "supply exactly one of text or key",
);

const AbandonedArgsSchema = z.object({
  runId: z.string().min(1),
});

const ExpectedRevisionSchema = z
  .string()
  .regex(/^\d+$/, "expectedRevision must be an integer")
  .transform((value) => Number(value))
  .refine(
    (value) => Number.isSafeInteger(value) && value >= 0,
    "expectedRevision must be a safe integer",
  );

const BoxHostOffloadArgsSchema = z.object({
  host: z.string().min(1),
  expectedRevision: ExpectedRevisionSchema,
});

const QuarantineOffloadArgsSchema = z.object({
  host: z.string().min(1),
  command: z.string().min(1),
  expectedRevision: ExpectedRevisionSchema,
});

const AdmissionReconcileOffloadArgsSchema = z.object({
  expectedRevision: ExpectedRevisionSchema,
  reason: z.string().optional(),
});

const JobRetryOffloadArgsSchema = z.object({
  jobId: z.string().min(1),
  expectedRevision: ExpectedRevisionSchema,
});

const OptionalHostOffloadArgsSchema = z.object({
  expectedRevision: ExpectedRevisionSchema,
  host: z.string().min(1).optional(),
});

const OFFLOAD_ARG_SCHEMAS: Record<OffloadActionVerb, z.ZodTypeAny> = {
  "box-drain": BoxHostOffloadArgsSchema,
  "box-restore": BoxHostOffloadArgsSchema,
  "host-quarantine": QuarantineOffloadArgsSchema,
  "host-unquarantine": QuarantineOffloadArgsSchema,
  "admission-reconcile": AdmissionReconcileOffloadArgsSchema,
  "job-retry": JobRetryOffloadArgsSchema,
  "ci-reconcile": OptionalHostOffloadArgsSchema,
  "recall-spill": OptionalHostOffloadArgsSchema,
};

const RequestBodySchema = z.object({
  args: z.record(z.string()),
  requestedBy: z.string().optional(),
}).strict();

const IncidentResolveArgsSchema = z.object({
  incidentId: z.string().min(1, "incidentId is required"),
  artifact: z
    .string({ required_error: "artifact is required — a resolve must cite the artifact (commit, PR, doc) that proves the fix" })
    .trim()
    .min(1, "artifact is required — a resolve must cite the artifact (commit, PR, doc) that proves the fix"),
  summary: z.string().optional(),
}).strict();

const HarnessTaskArgsSchema = z.object({
  runId: z.string().min(1),
  taskId: z.string().min(1),
  attemptId: z.string().min(1),
  requestId: z.string().min(1),
}).strict();

const HarnessRunArgsSchema = z.object({
  runId: z.string().min(1),
  requestId: z.string().min(1),
}).strict();

const HarnessConfigPatchArgsSchema = z.object({
  runId: z.string().min(1),
  revision: z.string().min(1),
  patch: z.string().min(1),
}).strict();

const MAX_ACTION_BODY_BYTES = 64 * 1024;
const MAX_CONFIG_PATCH_BYTES = 32 * 1024;
const MAX_CONFIG_PATCH_KEYS = 100;
const MAX_CONFIG_PATCH_DEPTH = 8;

const HarnessJsonSchema: z.ZodType<HarnessJson> = z.lazy(() => z.union([
  z.null(),
  z.boolean(),
  z.number().finite(),
  z.string(),
  z.array(HarnessJsonSchema),
  z.record(HarnessJsonSchema),
]));

const HarnessConfigPatchSchema = z.record(HarnessJsonSchema).refine(
  (patch) => Object.keys(patch).length > 0,
  "patch must not be empty",
);

export async function readBoundedBody(request: Request, maxBytes: number): Promise<string> {
  const contentLength = request.headers.get("content-length");
  if (contentLength !== null && (!/^\d+$/.test(contentLength) || Number(contentLength) > maxBytes)) {
    throw new RangeError("request body exceeds limit");
  }
  if (!request.body) return "";
  const reader = request.body.getReader();
  const chunks: Uint8Array[] = [];
  let bytes = 0;
  try {
    while (true) {
      const chunk = await reader.read();
      if (chunk.done) break;
      bytes += chunk.value.byteLength;
      if (bytes > maxBytes) throw new RangeError("request body exceeds limit");
      chunks.push(chunk.value);
    }
  } finally {
    reader.releaseLock();
  }
  return new TextDecoder().decode(Buffer.concat(chunks));
}

function validatePatchStructure(source: string): void {
  if (Buffer.byteLength(source, "utf8") > MAX_CONFIG_PATCH_BYTES) throw new RangeError("patch exceeds limit");
  let depth = 0;
  let keys = 0;
  let inString = false;
  let escaped = false;
  for (let index = 0; index < source.length; index += 1) {
    const char = source[index]!;
    if (inString) {
      if (escaped) escaped = false;
      else if (char === "\\") escaped = true;
      else if (char === '"') inString = false;
      continue;
    }
    if (char === '"') {
      inString = true;
      let cursor = index + 1;
      let stringEscaped = false;
      while (cursor < source.length) {
        const next = source[cursor]!;
        if (stringEscaped) stringEscaped = false;
        else if (next === "\\") stringEscaped = true;
        else if (next === '"') break;
        cursor += 1;
      }
      if (cursor >= source.length) throw new SyntaxError("invalid patch JSON");
      let delimiter = cursor + 1;
      while (/\s/.test(source[delimiter] ?? "")) delimiter += 1;
      if (source[delimiter] === ":" && ++keys > MAX_CONFIG_PATCH_KEYS) throw new RangeError("patch has too many keys");
      continue;
    }
    if (char === "{" || char === "[") {
      if (++depth > MAX_CONFIG_PATCH_DEPTH) throw new RangeError("patch exceeds nesting limit");
    } else if (char === "}" || char === "]") {
      if (--depth < 0) throw new SyntaxError("invalid patch JSON");
    }
  }
  if (inString || depth !== 0) throw new SyntaxError("invalid patch JSON");
}

function journalArgs(verb: string, args: Record<string, string>): Record<string, string> {
  if (verb === "harness.config.patch") return { ...args, patch: "[REDACTED]" };
  // Keystrokes are whatever the operator typed into a live agent session — they can
  // carry secrets, so the journal records that keys were sent, never their content.
  if (verb === "sessions.sendKeys" && args.text !== undefined) return { ...args, text: "[REDACTED]" };
  return args;
}

async function defaultSpawn(argv: string[]): Promise<SpawnResult> {
  const proc = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe" });
  const [stdout, stderr, exitCode] = await Promise.all([
    new Response(proc.stdout).text(),
    new Response(proc.stderr).text(),
    proc.exited,
  ]);
  return { rc: exitCode, stdout: stdout.trim(), stderr: stderr.trim() };
}

function isAllowedVerb(verb: string): verb is AllowedActionVerb {
  return (ALLOWED_ACTION_VERBS as readonly string[]).includes(verb);
}

function isOffloadVerb(verb: string): verb is OffloadActionVerb {
  return (OFFLOAD_ACTION_VERBS as readonly string[]).includes(verb);
}

/** Reachable registry hosts present in the current non-stale fleet panel snapshot. */
export function fleetPanelHostNames(state: CollectorState): Set<string> | null {
  const panel = state.getPanels().find((entry) => entry.id === "fleet");
  if (!panel) return null;
  const data = panel.data as {
    stale?: boolean;
    registryError?: string | null;
    hosts?: Array<{ host: string; registryState?: "reachable" | "unreachable" | "bricked" | null }>;
  };
  if (data.stale || data.registryError) return null;
  return new Set((data.hosts ?? [])
    .filter((host) => host.registryState === "reachable")
    .map((host) => host.host));
}

/** Job ids present in the current non-stale remote-jobs panel snapshot. */
export function remoteJobsPanelJobIds(state: CollectorState): Set<string> | null {
  const panel = state.getPanels().find((entry) => entry.id === "remote-jobs");
  if (!panel) return null;
  const data = panel.data as { stale?: boolean; jobs?: Array<{ id: string }> };
  if (data.stale) return null;
  return new Set((data.jobs ?? []).map((job) => job.id));
}

/** Orphan candidates = items currently advertising a reap action with a pid arg. */
export function orphanCandidatePids(state: CollectorState): Set<number> {
  const pids = new Set<number>();
  for (const item of state.getItems()) {
    for (const action of item.actions) {
      if (action.verb !== "reap") continue;
      const raw = action.args.pid;
      if (!raw || !/^\d+$/.test(raw)) continue;
      pids.add(Number(raw));
    }
  }
  return pids;
}

/** Run ids present in the current ci panel snapshot. */
export function ciPanelRunIds(state: CollectorState): Set<number> {
  const panel = state.getPanels().find((entry) => entry.id === "ci");
  if (!panel) return new Set();
  const data = panel.data as {
    repos?: Array<{ runs?: Array<{ id: number }> }>;
  };
  const ids = new Set<number>();
  for (const repo of data.repos ?? []) {
    for (const run of repo.runs ?? []) {
      ids.add(run.id);
    }
  }
  return ids;
}

function authorizeTrainAction(
  state: CollectorState,
  verb: "ci.rerunFailed" | "ci.cancelRun",
  repo: string,
  runId: number,
): string | null {
  const status = state.adapterStatuses().find((entry) => entry.id === "ghci");
  if (
    !status
    || status.lastAttempt === undefined
    || status.lastSuccess === undefined
    || status.lastAttempt !== status.lastSuccess
    || status.stale
  ) {
    return "ghci snapshot is not current";
  }

  const panel = state.getPanels().find((entry) => entry.id === "ci");
  const data = panel?.data as { repos?: unknown } | undefined;
  if (!Array.isArray(data?.repos)) return "ci panel is unavailable";

  const repoPanel = data.repos.find((entry): entry is Record<string, unknown> => (
    typeof entry === "object" && entry !== null && (entry as Record<string, unknown>).repo === repo
  ));
  if (
    !repoPanel
    || repoPanel.refsComplete !== true
    || repoPanel.trainRunsComplete !== true
    || repoPanel.prsComplete !== true
    || repoPanel.trainsComplete !== true
    || !Array.isArray(repoPanel.trains)
  ) {
    return "ci train snapshot is incomplete";
  }

  const train = repoPanel.trains.find((entry): entry is Record<string, unknown> => {
    if (typeof entry !== "object" || entry === null) return false;
    const gateRun = (entry as Record<string, unknown>).gateRun;
    return typeof gateRun === "object"
      && gateRun !== null
      && (gateRun as Record<string, unknown>).id === runId;
  });
  if (!train) return "run is not current for repository";

  const gateRun = train.gateRun as Record<string, unknown>;
  if (verb === "ci.rerunFailed") {
    return train.state === "failed" ? null : "train is not failed";
  }
  return (train.state === "gating" || train.state === "rerunning")
    && (gateRun.status === "queued" || gateRun.status === "in_progress")
    ? null
    : "train run is not cancellable";
}

class ActionJournal {
  constructor(private readonly path: string) {}

  append(entry: ActionJournalEntry): void {
    mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
    appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
  }
}

interface ActionOutcome {
  httpStatus: number;
  rc: number;
  result: string;
  body: Record<string, unknown>;
}

export function createActionGateway(deps: ActionGatewayDeps): ActionGateway {
  const state = deps.state;
  const harness = deps.harness;
  const permissions = deps.permissions;
  const journal = new ActionJournal(deps.journalPath ?? actionsJournalFile());
  const spawn = deps.spawn ?? defaultSpawn;
  const now = deps.now ?? Date.now;
  const controllerUrl = deps.controllerUrl;
  const controllerToken = deps.controllerToken;
  const fetcher = deps.fetcher;
  const mintIdempotencyKey = deps.randomUUID ?? randomUUID;
  const factoryDbPath = deps.factoryDbPath ?? configuredFactoryDbPath(loadConfig());

  async function journalAndRespond(
    verb: string,
    args: Record<string, string>,
    requestedBy: string,
    outcome: ActionOutcome,
  ): Promise<Response> {
    journal.append({
      ts: new Date(now()).toISOString(),
      verb,
      args: journalArgs(verb, args),
      requestedBy,
      result: outcome.result,
      rc: outcome.rc,
    });

    if (outcome.httpStatus >= 400 && requestedBy) {
      state.annotateActionError(requestedBy, outcome.result);
    }

    return Response.json(outcome.body, { status: outcome.httpStatus });
  }

  function openFactoryDb(path: string): Database {
    const db = new Database(path);
    db.exec("PRAGMA busy_timeout = 5000");
    return db;
  }

  function mintFactoryEventId(): string {
    return `evt_${randomBytes(6).toString("hex")}`;
  }

  interface FactoryDecisionRow {
    adw_id: string;
    phase: string | null;
    options: string;
    free_text: number;
    status: string;
  }

  async function executeFactoryDecision(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = FactoryDecisionArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("factory.decision.answer", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid factory.decision.answer args" },
      });
    }

    const dbPath = resolveFactoryDbPath(factoryDbPath);
    let db: Database;
    try {
      db = openFactoryDb(dbPath);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond("factory.decision.answer", args, requestedBy, {
        httpStatus: 500,
        rc: 500,
        result: message,
        body: { ok: false, error: "factory db unavailable" },
      });
    }

    try {
      const row = db.query<FactoryDecisionRow, [string]>(
        "SELECT adw_id, phase, options, free_text, status FROM decisions WHERE decision_id=?",
      ).get(parsed.data.decisionId);
      if (!row) {
        return journalAndRespond("factory.decision.answer", args, requestedBy, {
          httpStatus: 404,
          rc: 404,
          result: `decision ${parsed.data.decisionId} not found`,
          body: { ok: false, error: "decision not found" },
        });
      }
      if (row.status !== "pending") {
        return journalAndRespond("factory.decision.answer", args, requestedBy, {
          httpStatus: 409,
          rc: 409,
          result: "decision not pending",
          body: { ok: false, error: "decision not pending" },
        });
      }

      let options: Array<{ value: string }> = [];
      try {
        const parsedOptions = JSON.parse(row.options) as unknown;
        if (Array.isArray(parsedOptions)) {
          options = parsedOptions.flatMap((entry) => {
            if (!entry || typeof entry !== "object") return [];
            const value = (entry as { value?: unknown }).value;
            return typeof value === "string" && value.length > 0 ? [{ value }] : [];
          });
        }
      } catch {
        options = [];
      }

      const freeText = row.free_text === 1;
      const choice = parsed.data.choice;
      let answerValue: string | null = null;
      let answerText: string | null = null;
      if (options.length > 0 && options.some((option) => option.value === choice)) {
        answerValue = choice;
      } else if (freeText) {
        answerText = choice;
      } else {
        return journalAndRespond("factory.decision.answer", args, requestedBy, {
          httpStatus: 400,
          rc: 400,
          result: `invalid choice: ${choice}`,
          body: { ok: false, error: "invalid choice" },
        });
      }

      const answeredAt = new Date(now()).toISOString();
      const payload = JSON.stringify({
        decision_id: parsed.data.decisionId,
        answer_value: answerValue,
        answer_text: answerText,
      });

      const answerTxn = db.transaction(() => {
        const updated = db.query(
          "UPDATE decisions SET status='answered', answer_value=?, answer_text=?, answered_by=?, answered_at=? WHERE decision_id=? AND status='pending'",
        ).run(answerValue, answerText, requestedBy, answeredAt, parsed.data.decisionId);
        if (updated.changes === 0) {
          return { conflict: true };
        }
        db.query(
          "INSERT INTO events (event_id, adw_id, phase_id, parent_id, type, name, payload_json, tokens, started_at, ended_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
        ).run(
          mintFactoryEventId(),
          row.adw_id,
          row.phase ?? "",
          "",
          "decision_answered",
          "decision",
          payload,
          null,
          answeredAt,
          null,
        );
        return { conflict: false };
      });

      let outcome: { conflict: boolean };
      try {
        outcome = answerTxn();
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return journalAndRespond("factory.decision.answer", args, requestedBy, {
          httpStatus: 500,
          rc: 500,
          result: message,
          body: { ok: false, error: "factory db unavailable" },
        });
      }

      if (outcome.conflict) {
        return journalAndRespond("factory.decision.answer", args, requestedBy, {
          httpStatus: 409,
          rc: 409,
          result: "decision not pending",
          body: { ok: false, error: "decision not pending" },
        });
      }

      return journalAndRespond("factory.decision.answer", args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: "ok",
        body: { ok: true },
      });
    } finally {
      db.close();
    }
  }

  async function executeFactoryStop(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = FactoryStopArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("factory.run.stop", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid factory.run.stop args" },
      });
    }

    const dbPath = resolveFactoryDbPath(factoryDbPath);
    let session: { status: string | null; repo: string | null } | null | undefined;
    try {
      const db = openFactoryDb(dbPath);
      try {
        session = db.query<{ status: string | null; repo: string | null }, [string]>(
          "SELECT status, repo FROM sessions WHERE adw_id=?",
        ).get(parsed.data.adwId);
      } finally {
        db.close();
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond("factory.run.stop", args, requestedBy, {
        httpStatus: 500,
        rc: 500,
        result: message,
        body: { ok: false, error: "factory db unavailable" },
      });
    }

    if (!session) {
      return journalAndRespond("factory.run.stop", args, requestedBy, {
        httpStatus: 404,
        rc: 404,
        result: `session ${parsed.data.adwId} not found`,
        body: { ok: false, error: "session not found" },
      });
    }
    if (session.status !== "running") {
      return journalAndRespond("factory.run.stop", args, requestedBy, {
        httpStatus: 409,
        rc: 409,
        result: `session not running (status=${session.status ?? "unknown"})`,
        body: { ok: false, error: "session not running" },
      });
    }

    const argv = ["factory", "stop", parsed.data.adwId];
    if (session.repo) argv.push("--repo", session.repo);
    const proc = await spawn(argv);
    const ok = proc.rc === 0;
    return journalAndRespond("factory.run.stop", args, requestedBy, {
      httpStatus: ok ? 200 : 500,
      rc: proc.rc,
      result: ok ? proc.stdout || "ok" : proc.stderr || proc.stdout || `exit ${proc.rc}`,
      body: ok
        ? { ok: true, result: proc.stdout || "ok" }
        : { ok: false, error: proc.stderr || proc.stdout || "factory stop failed" },
    });
  }

  async function executeSessionSendKeys(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = SessionSendKeysArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("sessions.sendKeys", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid sessions.sendKeys args" },
      });
    }

    const { id, text, key } = parsed.data;
    const sent = await writeSessionKeys(state, id, text !== undefined ? { text } : { key });
    const ok = sent.status === 200;
    return journalAndRespond("sessions.sendKeys", args, requestedBy, {
      httpStatus: sent.status,
      rc: sent.rc,
      result: sent.result,
      body: ok ? { ok: true, result: sent.result } : { ok: false, error: sent.result },
    });
  }

  async function executeReap(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = ReapArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("reap", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid reap args" },
      });
    }

    if (!orphanCandidatePids(state).has(parsed.data.pid)) {
      return journalAndRespond("reap", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: `pid ${parsed.data.pid} is not an orphan candidate`,
        body: { ok: false, error: "pid is not an orphan candidate" },
      });
    }

    const argv = ["reaper-ctl", "kill", String(parsed.data.pid), "--escalate"];
    const proc = await spawn(argv);
    const ok = proc.rc === 0;
    return journalAndRespond("reap", args, requestedBy, {
      httpStatus: ok ? 200 : 500,
      rc: proc.rc,
      result: ok ? proc.stdout || "ok" : proc.stderr || `exit ${proc.rc}`,
      body: ok ? { ok: true, result: proc.stdout || "ok" } : { ok: false, error: proc.stderr || "reap failed" },
    });
  }

  async function executeCiRerun(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = CiRerunArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("ci-rerun", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid ci-rerun args" },
      });
    }

    if (!ciPanelRunIds(state).has(parsed.data.id)) {
      return journalAndRespond("ci-rerun", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: `run id ${parsed.data.id} is not in the ci panel`,
        body: { ok: false, error: "run id is not in the ci panel" },
      });
    }

    const argv = ["gh", "run", "rerun", String(parsed.data.id)];
    const proc = await spawn(argv);
    const ok = proc.rc === 0;
    return journalAndRespond("ci-rerun", args, requestedBy, {
      httpStatus: ok ? 200 : 500,
      rc: proc.rc,
      result: ok ? proc.stdout || "ok" : proc.stderr || `exit ${proc.rc}`,
      body: ok ? { ok: true, result: proc.stdout || "ok" } : { ok: false, error: proc.stderr || "ci-rerun failed" },
    });
  }

  async function executeTrainAction(
    verb: "ci.rerunFailed" | "ci.cancelRun",
    args: Record<string, string>,
    requestedBy: string,
  ): Promise<Response> {
    const parsed = TrainActionArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: `invalid ${verb} args` },
      });
    }

    const denied = authorizeTrainAction(state, verb, parsed.data.repo, parsed.data.runId);
    if (denied) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: denied,
        body: { ok: false, error: denied },
      });
    }

    const runId = String(parsed.data.runId);
    const argv = verb === "ci.rerunFailed"
      ? ["gh", "run", "rerun", runId, "--failed", "-R", parsed.data.repo]
      : ["gh", "run", "cancel", runId, "-R", parsed.data.repo];
    const proc = await spawn(argv);
    const ok = proc.rc === 0;
    return journalAndRespond(verb, args, requestedBy, {
      httpStatus: ok ? 200 : 500,
      rc: proc.rc,
      result: ok ? proc.stdout || "ok" : proc.stderr || `exit ${proc.rc}`,
      body: ok
        ? { ok: true, result: proc.stdout || "ok" }
        : { ok: false, error: proc.stderr || `${verb} failed` },
    });
  }

  async function executeSteer(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = SteerArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("steer", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid steer args" },
      });
    }

    if (!harness) {
      return journalAndRespond("steer", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "harness adapter unavailable",
        body: { ok: false, error: "harness adapter unavailable" },
      });
    }

    try {
      const response = await harness.steerTask(parsed.data.runId, parsed.data.taskId, {
        text: parsed.data.text,
        restart: parsed.data.restart === "true",
      });
      return journalAndRespond("steer", args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: JSON.stringify(response),
        body: { ok: true, result: response },
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      return journalAndRespond("steer", args, requestedBy, {
        httpStatus: 500,
        rc: 500,
        result: message,
        body: { ok: false, error: message },
      });
    }
  }

  async function executeHarnessTaskControl(
    verb: "harness.task.pause" | "harness.task.resume" | "harness.task.kill",
    args: Record<string, string>,
    requestedBy: string,
  ): Promise<Response> {
    const parsed = HarnessTaskArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: `invalid ${verb} args` },
      });
    }
    if (!harness) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "harness adapter unavailable",
        body: { ok: false, error: "harness adapter unavailable" },
      });
    }

    try {
      const result = await harness.controlTask(parsed.data.runId, parsed.data.taskId, verb.slice("harness.task.".length) as "pause" | "resume" | "kill", {
        attemptId: parsed.data.attemptId,
        requestId: parsed.data.requestId,
      });
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: JSON.stringify(result),
        body: { ok: true, result },
      });
    } catch (error) {
      if (error instanceof HarnessApiError) {
        return journalAndRespond(verb, args, requestedBy, {
          httpStatus: error.status,
          rc: error.status,
          result: JSON.stringify(error.body),
          body: error.body,
        });
      }
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 502,
        rc: 502,
        result: message,
        body: { ok: false, error: "harness-unreachable" },
      });
    }
  }

  async function executeHarnessRunControl(
    verb: "harness.run.pause" | "harness.run.resume" | "harness.run.kill",
    args: Record<string, string>,
    requestedBy: string,
  ): Promise<Response> {
    const parsed = HarnessRunArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: `invalid ${verb} args` },
      });
    }
    if (!harness) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "harness adapter unavailable",
        body: { ok: false, error: "harness adapter unavailable" },
      });
    }

    try {
      const result = await harness.controlRun(parsed.data.runId, verb.slice("harness.run.".length) as "pause" | "resume" | "kill", { requestId: parsed.data.requestId });
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: JSON.stringify(result),
        body: { ok: true, result },
      });
    } catch (error) {
      if (error instanceof HarnessApiError) {
        return journalAndRespond(verb, args, requestedBy, {
          httpStatus: error.status,
          rc: error.status,
          result: JSON.stringify(error.body),
          body: error.body,
        });
      }
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 502,
        rc: 502,
        result: message,
        body: { ok: false, error: "harness-unreachable" },
      });
    }
  }

  async function executeHarnessConfigPatch(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = HarnessConfigPatchArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("harness.config.patch", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid harness.config.patch args" },
      });
    }
    let patch: Record<string, HarnessJson>;
    try {
      validatePatchStructure(parsed.data.patch);
      patch = HarnessConfigPatchSchema.parse(JSON.parse(parsed.data.patch));
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond("harness.config.patch", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: message,
        body: { ok: false, error: "invalid harness.config.patch patch" },
      });
    }
    if (!harness) {
      return journalAndRespond("harness.config.patch", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "harness adapter unavailable",
        body: { ok: false, error: "harness adapter unavailable" },
      });
    }

    try {
      const config = await harness.getRunConfig(parsed.data.runId);
      const forbiddenKey = Object.keys(patch).find((key) => {
        const field = config.fields[key];
        return !field || field.immutable !== false || field.mutationClass !== "mid-run";
      });
      if (forbiddenKey) {
        return journalAndRespond("harness.config.patch", args, requestedBy, {
          httpStatus: 403,
          rc: 403,
          result: `config patch key is not mutable mid-run: ${forbiddenKey}`,
          body: { ok: false, error: "config patch key is not mutable mid-run" },
        });
      }
      const result = await harness.patchRunConfig(parsed.data.runId, patch, parsed.data.revision);
      return journalAndRespond("harness.config.patch", args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: JSON.stringify(result),
        body: { ok: true, result },
      });
    } catch (error) {
      if (error instanceof HarnessApiError) {
        return journalAndRespond("harness.config.patch", args, requestedBy, {
          httpStatus: error.status,
          rc: error.status,
          result: JSON.stringify(error.body),
          body: error.body,
        });
      }
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond("harness.config.patch", args, requestedBy, {
        httpStatus: 502,
        rc: 502,
        result: message,
        body: { ok: false, error: "harness-unreachable" },
      });
    }
  }

  async function executeSnooze(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = SnoozeArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("snooze", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid snooze args" },
      });
    }

    const durationMs = parsed.data.durationMs ? Number(parsed.data.durationMs) : 30 * 60_000;
    const until = now() + durationMs;
    const snoozed = state.snoozeItem(parsed.data.itemId, until);
    if (!snoozed) {
      return journalAndRespond("snooze", args, requestedBy, {
        httpStatus: 404,
        rc: 404,
        result: `item ${parsed.data.itemId} not found`,
        body: { ok: false, error: "item not found" },
      });
    }

    return journalAndRespond("snooze", args, requestedBy, {
      httpStatus: 200,
      rc: 0,
      result: `snoozed until ${new Date(until).toISOString()}`,
      body: { ok: true, until },
    });
  }

  async function executeDecision(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = DecisionArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("decision", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid decision args" },
      });
    }

    if (!harness) {
      return journalAndRespond("decision", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "harness adapter unavailable",
        body: { ok: false, error: "harness adapter unavailable" },
      });
    }

    try {
      const response = await harness.answerDecision(
        parsed.data.runId,
        parsed.data.decisionId,
        parsed.data.choice,
      );
      const applied = response.applied !== false;
      return journalAndRespond("decision", args, requestedBy, {
        httpStatus: applied ? 200 : 409,
        rc: applied ? 0 : 409,
        result: JSON.stringify(response),
        body: applied
          ? { ok: true, result: response }
          : { ok: false, error: response.error ?? "decision not applied" },
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      return journalAndRespond("decision", args, requestedBy, {
        httpStatus: 500,
        rc: 500,
        result: message,
        body: { ok: false, error: message },
      });
    }
  }

  async function executePermissionAnswer(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = PermissionAnswerArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("permission.answer", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid permission.answer args" },
      });
    }
    if (!permissions) {
      return journalAndRespond("permission.answer", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "permission queue unavailable",
        body: { ok: false, error: "permission queue unavailable" },
      });
    }

    const applied = permissions.answer(parsed.data.requestId, parsed.data.choice, requestedBy);
    return journalAndRespond("permission.answer", args, requestedBy, {
      httpStatus: applied ? 200 : 409,
      rc: applied ? 0 : 409,
      result: applied ? `${parsed.data.choice} applied` : "request no longer pending",
      body: applied
        ? { ok: true, result: { requestId: parsed.data.requestId, choice: parsed.data.choice } }
        : { ok: false, error: "request no longer pending" },
    });
  }

  async function executePermissionArm(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = PermissionArmArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond("permission.arm", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: "invalid permission.arm args" },
      });
    }
    if (!permissions) {
      return journalAndRespond("permission.arm", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "permission queue unavailable",
        body: { ok: false, error: "permission queue unavailable" },
      });
    }

    const previousUntil = permissions.armedUntilMs();
    const wasArmed = previousUntil !== null && previousUntil > now();
    const armState = parsed.data.state === "on" ? permissions.arm() : permissions.disarm();
    // The browser refreshes a rolling window every few seconds; journalling each
    // keepalive would bury the arm/disarm transitions that actually matter.
    if (wasArmed && parsed.data.state === "on") {
      return Response.json({ ok: true, result: armState });
    }
    return journalAndRespond("permission.arm", args, requestedBy, {
      httpStatus: 200,
      rc: 0,
      result: armState.until === null ? "disarmed" : `armed until ${new Date(armState.until).toISOString()}`,
      body: { ok: true, result: armState },
    });
  }

  async function executeAbandonedAction(
    verb: "abandon" | "restore",
    args: Record<string, string>,
    requestedBy: string,
  ): Promise<Response> {
    const parsed = AbandonedArgsSchema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: `invalid ${verb} args` },
      });
    }

    try {
      if (verb === "abandon") abandonRun(parsed.data.runId);
      else restoreRun(parsed.data.runId);
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 200,
        rc: 0,
        result: "ok",
        body: { ok: true, result: "ok" },
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 500,
        rc: 500,
        result: message,
        body: { ok: false, error: message },
      });
    }
  }

  function validateOffloadTargets(
    verb: OffloadActionVerb,
    verbArgs: Record<string, string>,
  ): string | null {
    const hostVerbs: OffloadActionVerb[] = [
      "box-drain",
      "box-restore",
      "host-quarantine",
      "host-unquarantine",
    ];
    if (hostVerbs.includes(verb)) {
      const hosts = fleetPanelHostNames(state);
      if (!hosts) return "fleet panel is stale or unavailable";
      if (!hosts.has(verbArgs.host!)) {
        return `host ${verbArgs.host} is not in the fleet panel`;
      }
    }

    if (verb === "job-retry") {
      const jobIds = remoteJobsPanelJobIds(state);
      if (!jobIds) return "remote-jobs panel is stale or unavailable";
      if (!jobIds.has(verbArgs.jobId!)) {
        return `job ${verbArgs.jobId} is not in the remote-jobs panel`;
      }
    }

    if ((verb === "ci-reconcile" || verb === "recall-spill") && verbArgs.host) {
      const hosts = fleetPanelHostNames(state);
      if (!hosts) return "fleet panel is stale or unavailable";
      if (!hosts.has(verbArgs.host)) {
        return `host ${verbArgs.host} is not in the fleet panel`;
      }
    }

    return null;
  }

  async function executeOffloadTransition(
    verb: OffloadActionVerb,
    args: Record<string, string>,
    requestedBy: string,
  ): Promise<Response> {
    if ("idempotencyKey" in args) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: "idempotencyKey is not accepted",
        body: { ok: false, error: "idempotencyKey is not accepted" },
      });
    }

    const schema = OFFLOAD_ARG_SCHEMAS[verb];
    const parsed = schema.safeParse(args);
    if (!parsed.success) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: parsed.error.issues.map((issue) => issue.message).join("; "),
        body: { ok: false, error: `invalid ${verb} args` },
      });
    }

    const { expectedRevision, ...rest } = parsed.data as {
      expectedRevision: number;
      [key: string]: string | number | undefined;
    };
    const verbArgs: Record<string, string> = {};
    for (const [key, value] of Object.entries(rest)) {
      if (value !== undefined) verbArgs[key] = String(value);
    }

    const targetError = validateOffloadTargets(verb, verbArgs);
    if (targetError) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: targetError,
        body: { ok: false, error: targetError },
      });
    }

    if (!controllerUrl || !controllerToken || !fetcher) {
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "offload controller unavailable",
        body: { ok: false, error: "offload controller unavailable" },
      });
    }

    const idempotencyKey = mintIdempotencyKey();
    const transitionUrl = `${controllerUrl}/transition/${verb}`;
    const transitionBody = {
      expectedRevision,
      idempotencyKey,
      args: verbArgs,
    };

    try {
      const res = await fetcher(transitionUrl, {
        method: "POST",
        headers: {
          authorization: `Bearer ${controllerToken}`,
          "content-type": "application/json",
        },
        body: JSON.stringify(transitionBody),
      });

      let responseBody: Record<string, unknown>;
      try {
        responseBody = (await res.json()) as Record<string, unknown>;
      } catch {
        responseBody = {};
      }

      if (res.ok) {
        return journalAndRespond(verb, args, requestedBy, {
          httpStatus: 200,
          rc: 0,
          result: JSON.stringify(responseBody),
          body: { ok: true, result: responseBody },
        });
      }

      const errorMessage =
        typeof responseBody.error === "string" ? responseBody.error : `transition failed (${res.status})`;
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: res.status,
        rc: res.status,
        result: JSON.stringify(responseBody),
        body: { ok: false, error: errorMessage },
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      return journalAndRespond(verb, args, requestedBy, {
        httpStatus: 502,
        rc: 502,
        result: message,
        body: { ok: false, error: "controller-unreachable" },
      });
    }
  }

  async function executeIncidentResolve(args: Record<string, string>, requestedBy: string): Promise<Response> {
    const parsed = IncidentResolveArgsSchema.safeParse(args);
    if (!parsed.success) {
      const detail = parsed.error.issues.map((issue) => issue.message).join("; ");
      return journalAndRespond("incident.resolve", args, requestedBy, {
        httpStatus: 400,
        rc: 400,
        result: detail,
        body: { ok: false, error: "invalid incident.resolve args", detail },
      });
    }
    if (!deps.incidents) {
      return journalAndRespond("incident.resolve", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: "no incidents provider configured on this collector",
        body: { ok: false, error: "incidents-unavailable" },
      });
    }

    const { incidentId, artifact, summary } = parsed.data;
    try {
      await deps.incidents.resolveIncident(incidentId, artifact, summary);
    } catch (error) {
      if (error instanceof IncidentResolutionConflictError) {
        return journalAndRespond("incident.resolve", args, requestedBy, {
          httpStatus: 409,
          rc: 409,
          result: error.detail,
          body: { ok: false, error: "resolution-conflict", detail: error.detail },
        });
      }
      if (error instanceof IncidentMutationError && error.code === "not-found") {
        return journalAndRespond("incident.resolve", args, requestedBy, {
          httpStatus: 404,
          rc: 404,
          result: `incident ${incidentId} not found`,
          body: { ok: false, error: "incident not found" },
        });
      }
      const message = error instanceof Error ? error.message : String(error);
      return journalAndRespond("incident.resolve", args, requestedBy, {
        httpStatus: 503,
        rc: 503,
        result: message,
        body: { ok: false, error: "incidents-unavailable" },
      });
    }

    return journalAndRespond("incident.resolve", args, requestedBy, {
      httpStatus: 200,
      rc: 0,
      result: `incident ${incidentId} resolved — artifact: ${artifact}`,
      body: { ok: true },
    });
  }

  async function handle(req: Request, verb: string): Promise<Response> {
    if (!isAllowedVerb(verb)) {
      return new Response("not found", { status: 404 });
    }

    let body: unknown;
    try {
      body = JSON.parse(await readBoundedBody(req, MAX_ACTION_BODY_BYTES));
    } catch {
      return new Response("bad json", { status: 400 });
    }

    const parsedBody = RequestBodySchema.safeParse(body);
    if (!parsedBody.success) {
      return new Response("bad shape", { status: 400 });
    }

    const args = parsedBody.data.args;
    const requestedBy = parsedBody.data.requestedBy ?? "";

    switch (verb) {
      case "reap":
        return executeReap(args, requestedBy);
      case "ci-rerun":
        return executeCiRerun(args, requestedBy);
      case "ci.rerunFailed":
      case "ci.cancelRun":
        return executeTrainAction(verb, args, requestedBy);
      case "steer":
        return executeSteer(args, requestedBy);
      case "harness.task.pause":
      case "harness.task.resume":
      case "harness.task.kill":
        return executeHarnessTaskControl(verb, args, requestedBy);
      case "harness.run.pause":
      case "harness.run.resume":
      case "harness.run.kill":
        return executeHarnessRunControl(verb, args, requestedBy);
      case "harness.config.patch":
        return executeHarnessConfigPatch(args, requestedBy);
      case "snooze":
        return executeSnooze(args, requestedBy);
      case "decision":
        return executeDecision(args, requestedBy);
      case "factory.decision.answer":
        return executeFactoryDecision(args, requestedBy);
      case "factory.run.stop":
        return executeFactoryStop(args, requestedBy);
      case "sessions.sendKeys":
        return executeSessionSendKeys(args, requestedBy);
      case "permission.answer":
        return executePermissionAnswer(args, requestedBy);
      case "permission.arm":
        return executePermissionArm(args, requestedBy);
      case "incident.resolve":
        return executeIncidentResolve(args, requestedBy);
      case "abandon":
      case "restore":
        return executeAbandonedAction(verb, args, requestedBy);
      case "box-drain":
      case "box-restore":
      case "host-quarantine":
      case "host-unquarantine":
      case "admission-reconcile":
      case "job-retry":
      case "ci-reconcile":
      case "recall-spill":
        return executeOffloadTransition(verb, args, requestedBy);
      default:
        return new Response("not found", { status: 404 });
    }
  }

  return { handle };
}
