import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { FetchLike } from "../adapter";
import { abandonRun } from "../abandoned-store";
import { createHarnessAdapter, computeRunStalenessMs, isAttemptAlarmed, isRunAlarmedByStaleness, newestJournalEventMs } from "./harness";

const FIXTURE_DIR = join(import.meta.dir, "..", "..", "test", "fixtures", "harness");
const TOKEN = "test-token-abc123";
const BASE_URL = "http://127.0.0.1:4981";

function fixture<T>(name: string): T {
  return JSON.parse(readFileSync(join(FIXTURE_DIR, name), "utf8")) as T;
}

interface MockCall {
  url: string;
  method: string;
  authorization: string | null;
  ifMatch?: string | null;
  body: unknown;
}

function createMockFetch() {
  const calls: MockCall[] = [];

  const routes: Record<string, unknown> = {
    "GET /runs": fixture("runs.json"),
    "GET /queue": { queue: [] },
    "GET /runs/05c65e0ba11a--opt-data-integrity/timeline": fixture("timeline-opt-data-integrity.json"),
    "GET /runs/4b4a6e1d17d2--grok-account-parity/timeline": fixture("timeline-grok-account-parity.json"),
    "GET /runs/4b4a6e1d17d2--grok-account-parity/decisions": fixture("decisions-grok-account-parity.json"),
    "GET /runs/05c65e0ba11a--opt-data-integrity/attempts": { attempts: [] },
    "GET /runs/4b4a6e1d17d2--grok-account-parity/attempts": { attempts: [] },
    "GET /runs/05c65e0ba11a--opt-data-integrity/events": { events: [], nextSince: "0", capabilities: {} },
    "GET /runs/4b4a6e1d17d2--grok-account-parity/events": { events: [], nextSince: "0", capabilities: {} },
  };

  const fetchImpl = async (input: string | URL | Request, init?: RequestInit) => {
    const url = typeof input === "string" ? input : input.toString();
    const method = init?.method ?? "GET";
    const path = url.replace(BASE_URL, "");
    const headers = new Headers(init?.headers);
    const bodyRaw = init?.body;
    calls.push({
      url: path,
      method,
        authorization: headers.get("authorization"),
        ifMatch: headers.get("if-match"),
      body: typeof bodyRaw === "string" ? JSON.parse(bodyRaw) : null,
    });

    const key = `${method} ${path}`;
    if (key in routes) {
      return new Response(JSON.stringify(routes[key]), { status: 200 });
    }
    if (method === "POST" && path.match(/^\/runs\/[^/]+\/decisions\/[^/]+$/)) {
      return new Response(JSON.stringify({ statusCode: 200, applied: true }), { status: 200 });
    }
    if (method === "POST" && path.match(/^\/runs\/[^/]+\/tasks\/[^/]+\/steer$/)) {
      return new Response(JSON.stringify({ ok: true, id: "steer-1", queued: true, restart: false }), { status: 200 });
    }
    return new Response(JSON.stringify({ error: "not-found" }), { status: 404 });
  };

  return { fetchImpl, calls };
}

function makeAdapter(fetchImpl: FetchLike) {
  return createHarnessAdapter({ fetchImpl, baseUrl: BASE_URL, token: TOKEN, interval: 5000, harnessHome: join(configDir, "harness"), ensureImpl: async () => {} });
}

function writeHarnessConnection(harnessHome: string, port: number, token = TOKEN) {
  writeFileSync(join(harnessHome, "control-api.port"), String(port));
  writeFileSync(join(harnessHome, "token"), token);
}

function makeDiscoveryAdapter(fetchImpl: FetchLike, harnessHome = configDir, opts: { ensureImpl?: () => Promise<void> } = {}) {
  return createHarnessAdapter({ fetchImpl, harnessHome, interval: 5000, ensureImpl: async () => {}, ...opts });
}

function emptyRuns() {
  return Response.json({ runs: [] });
}

function emptyQueue() {
  return Response.json({ queue: [] });
}

let configDir: string;
let previousConfigDir: string | undefined;

beforeEach(() => {
  previousConfigDir = process.env.OVERDECK_CONFIG_DIR;
  configDir = mkdtempSync(join(tmpdir(), "overdeck-harness-config-"));
  process.env.OVERDECK_CONFIG_DIR = configDir;
});

afterEach(() => {
  if (previousConfigDir === undefined) delete process.env.OVERDECK_CONFIG_DIR;
  else process.env.OVERDECK_CONFIG_DIR = previousConfigDir;
  rmSync(configDir, { recursive: true, force: true });
});

// src/timeline.js builds every segment t0 from its run's own start/end, so a segment
// outside its run window is unreachable in real data — a fixture that does it is wrong,
// and the forensics widgets consume these timestamps to place lanes.
describe("timeline fixtures match the generator's invariants", () => {
  const timelineFixtures = ["timeline-opt-data-integrity.json", "timeline-grok-account-parity.json"];

  for (const name of timelineFixtures) {
    it(`${name}: every segment falls inside a run window`, () => {
      const data = fixture<{
        runs: { startTs: string; endTs: string }[];
        segments: { t0: number; durMs: number; cat: string }[];
      }>(name);

      expect(data.runs.length).toBeGreaterThan(0);
      expect(data.segments.length).toBeGreaterThan(0);

      const windows = data.runs.map((run) => ({
        start: new Date(run.startTs).getTime(),
        end: new Date(run.endTs).getTime(),
      }));

      for (const segment of data.segments) {
        const covering = windows.find(
          (w) => segment.t0 >= w.start && segment.t0 + segment.durMs <= w.end,
        );
        expect(covering).toBeDefined();
      }
    });
  }
});

describe("createHarnessAdapter", () => {
  it("projects ordered queue entries losslessly without fabricated run fields", async () => {
    const queue = [
      {
        id: "pending-window",
        repo: "/workspace/queued",
        slug: "queued-work",
        preset: null,
        account: null,
        addedAt: "2026-07-30T00:00:00.000Z",
        status: "window-held",
        attempt: 0,
        runId: null,
        window: { source: "night", start: "22:00", end: "06:00", time_zone: "UTC" },
        nextEligibleAt: "2026-07-30T22:00:00.000Z",
        bypassRequestedAt: null,
        terminalAt: null,
        failure: null,
      },
      {
        id: "running",
        repo: "/workspace/running",
        slug: "active-work",
        preset: "fast",
        account: "team-a",
        addedAt: "2026-07-30T00:01:00.000Z",
        status: "running",
        attempt: 2,
        runId: "run-active",
        window: null,
        nextEligibleAt: null,
        bypassRequestedAt: "2026-07-30T00:01:30.000Z",
        terminalAt: null,
        failure: { message: "gate failed" },
      },
    ];
    const { fetchImpl: baseFetch } = createMockFetch();
    const adapter = makeAdapter(async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.endsWith("/queue")) return Response.json({ queue });
      return baseFetch(input, init);
    });

    const result = await adapter.poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!;
    const data = plans.data as { runs: unknown[]; queue: unknown[] };

    expect(data.queue).toEqual(queue);
    expect(data.queue).toHaveLength(2);
    expect(data.runs.some((run) => JSON.stringify(run).includes("pending-window"))).toBe(false);
    expect(JSON.stringify(data.queue)).not.toContain("tasksTotal");
  });

  it("rejects failed or invalid queue reads so collector retains prior plans state", async () => {
    let queueState: "valid" | "failed" | "malformed" = "valid";
    const { fetchImpl: baseFetch } = createMockFetch();
    const adapter = makeAdapter(async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.endsWith("/queue")) {
        if (queueState === "failed") return Response.json({ queue: "unavailable" }, { status: 503 });
        if (queueState === "malformed") return Response.json({ queue: [{ id: "pending" }] });
        return Response.json({ queue: [{ id: "pending", repo: "/workspace", slug: "queued", preset: null, account: null, addedAt: "2026-07-30T00:00:00.000Z", status: "pending", attempt: 0, runId: null, window: null, nextEligibleAt: null, bypassRequestedAt: null, terminalAt: null, failure: null }] });
      }
      return baseFetch(input, init);
    });

    const prior = await adapter.poll();
    queueState = "failed";

    await expect(adapter.poll()).rejects.toThrow();
    queueState = "malformed";
    await expect(adapter.poll()).rejects.toThrow(/invalid harness response/i);
    expect(prior.panels.find((panel) => panel.id === "plans")!.data).toMatchObject({
      queue: [{ id: "pending", runId: null }],
    });
  });

  it("keeps legacy plans output free of every observability field", async () => {
    const { fetchImpl } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const result = await adapter.poll();

    const serialized = JSON.stringify(result.panels.find((panel) => panel.id === "plans")!.data);
    for (const field of ["capabilities", "attemptId", "acceptance", "ratelimits", "duration", "findings"]) {
      expect(serialized).not.toContain(field);
    }
  });

  it("projects enriched observability reads losslessly without defaults", async () => {
    const responses: Record<string, unknown> = {
      "GET /runs/enriched/events?since=opaque-cursor&task=t-1": fixture("events-enriched.json"),
      "GET /runs/enriched/config": fixture("config-enriched.json"),
      "GET /runs/enriched/plan": fixture("plan-enriched.json"),
      "GET /runs/enriched/decisions": fixture("decisions-enriched.json"),
      "GET /runs/enriched": fixture("run-enriched.json"),
    };
    const fetchImpl: FetchLike = async (input, init) => {
      const raw = typeof input === "string" ? input : input.toString();
      const url = new URL(raw);
      const key = `${init?.method ?? "GET"} ${url.pathname}${url.search}`;
      return key in responses ? Response.json(responses[key]) : Response.json({ error: "not-found" }, { status: 404 });
    };
    const adapter = makeAdapter(fetchImpl);

    await expect(adapter.getRunEvents("enriched", { since: "opaque-cursor", taskId: "t-1" })).resolves.toEqual(
      fixture("events-enriched.json"),
    );
    await expect(adapter.getRunConfig("enriched")).resolves.toEqual({
      revision: "cfg-1",
      fields: {
        "watchdog.idleTimeoutMs": { value: 50, source: "run-override", immutable: false, mutationClass: "mid-run" },
        "notify.ntfy.token": { source: "unknown", immutable: false, mutationClass: "global", isSecret: true, redacted: true },
      },
    });
    await expect(adapter.getEffectivePlan("enriched")).resolves.toEqual(fixture("plan-enriched.json"));
    await expect(adapter.getDecisions("enriched")).resolves.toEqual(fixture("decisions-enriched.json"));
    await expect(adapter.getRunDetail("enriched")).resolves.toEqual(fixture("run-enriched.json"));
  });

  it("redacts credential-like config values while retaining field metadata", async () => {
    const adapter = makeAdapter(async () => Response.json({
      revision: "r1",
      fields: {
        apiKey: { value: "must-not-reach-json", source: "env", immutable: true, mutationClass: "global" },
        watchdog: { value: { authorization: "nested-secret", idleTimeoutMs: 50 }, source: "run-override", immutable: false, mutationClass: "mid-run" },
      },
    }));
    const config = await adapter.getRunConfig("run-1");
    expect(JSON.stringify(config)).not.toContain("must-not-reach-json");
    expect(JSON.stringify(config)).not.toContain("nested-secret");
    expect(config).toMatchObject({
      fields: {
        apiKey: { source: "env", immutable: true, mutationClass: "global", isSecret: true, redacted: true },
        watchdog: { value: { authorization: { isSecret: true, redacted: true }, idleTimeoutMs: 50 }, source: "run-override", immutable: false, mutationClass: "mid-run" },
      },
    });
  });

  it("redacts nested credentials from every JSON browser egress surface", async () => {
    const responses: Record<string, unknown> = {
      "GET /runs/run/events": { events: [{ id: "e1", source: "runlog", kind: "activity", ts: "2026-07-22T00:00:00.000Z", payload: { nested: { authorization: "event-secret" } } }], nextSince: "e1", capabilities: {} },
      "GET /runs/run/plan": { runId: "run", revision: "r1", planHash: "h1", tasks: [], meta: { nested: { token: "plan-secret" } } },
      "GET /runs/run/decisions": { decisions: [{ id: "d1", task: null, summary: null, options: [], requestedAt: null, needs: { secret: "decision-secret" } }], capabilities: {} },
      "GET /runs/run": { run: { nested: { apiKey: "detail-secret" } } },
      "POST /runs/run/pause": { nested: { cookie: "response-secret" } },
    };
    const adapter = makeAdapter(async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      const key = `${init?.method ?? "GET"} ${url.replace(BASE_URL, "")}`;
      return Response.json(responses[key]);
    });

    const values = await Promise.all([
      adapter.getRunEvents("run"), adapter.getEffectivePlan("run"), adapter.getDecisions("run"), adapter.getRunDetail("run"), adapter.controlRun("run", "pause"),
    ]);
    const serialized = JSON.stringify(values);
    for (const secret of ["event-secret", "plan-secret", "decision-secret", "detail-secret", "response-secret"]) expect(serialized).not.toContain(secret);
    expect(serialized).toContain("[REDACTED]");
  });

  it("streams task SSE without applying request timeout and preserves opaque cursors", async () => {
    let received: RequestInit | undefined;
    const fetchImpl: FetchLike = async (_input, init) => {
      received = init;
      return new Response("id: l:opaque:42\nevent: transcript\ndata: {}\n\n", {
        headers: { "content-type": "text/event-stream" },
      });
    };
    const adapter = createHarnessAdapter({ fetchImpl, baseUrl: BASE_URL, token: TOKEN, requestTimeoutMs: 1 });

    const response = await adapter.openTaskStream("enriched", "t-1", { since: "opaque-cursor", lastEventId: "l:opaque:41" });

    expect(response.headers.get("content-type")).toContain("text/event-stream");
    expect(received?.signal).toBeUndefined();
    expect(new Headers(received?.headers).get("last-event-id")).toBe("l:opaque:41");
  });

  it("sends task, run, and config controls with observed IDs and revisions", async () => {
    const calls: MockCall[] = [];
    const fetchImpl: FetchLike = async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      calls.push({
        url: url.replace(BASE_URL, ""),
        method: init?.method ?? "GET",
        authorization: new Headers(init?.headers).get("authorization"),
        ifMatch: new Headers(init?.headers).get("if-match"),
        body: typeof init?.body === "string" ? JSON.parse(init.body) : null,
      });
      return init?.method === "PATCH" ? Response.json(fixture("config-enriched.json")) : Response.json({ ok: true });
    };
    const adapter = makeAdapter(fetchImpl);

    await adapter.controlTask("run id", "task/id", "pause", { attemptId: "attempt-1", requestId: "request-1" });
    await adapter.controlRun("run id", "kill", { requestId: "request-2" });
    await adapter.patchRunConfig("run id", { watchdog: { idleTimeoutMs: 50 } }, "cfg-revision");

    expect(calls.map(({ method, url, body }) => ({ method, url, body }))).toEqual([
      { method: "POST", url: "/runs/run%20id/tasks/task%2Fid/pause", body: { attemptId: "attempt-1", requestId: "request-1" } },
      { method: "POST", url: "/runs/run%20id/kill", body: { requestId: "request-2" } },
      { method: "PATCH", url: "/runs/run%20id/config", body: { watchdog: { idleTimeoutMs: 50 } } },
    ]);
    expect(calls).toHaveLength(3);
    expect(calls[2]?.ifMatch).toBe("cfg-revision");
  });

  it("rejects malformed wire payloads and retains upstream status plus redacted body", async () => {
    const malformed: FetchLike = async () => Response.json({ events: "not-an-array" });
    const upstream: FetchLike = async () => Response.json({ error: "bad", token: "secret" }, { status: 409 });

    await expect(makeAdapter(malformed).getRunEvents("run")).rejects.toThrow(/invalid harness response/i);
    await expect(makeAdapter(upstream).getRunConfig("run")).rejects.toMatchObject({ status: 409, body: { error: "bad", token: "[REDACTED]" } });
  });

  it("accepts run-scoped events and rejects unchecked enriched wire values", async () => {
    const validRunEvent: FetchLike = async () => Response.json({
      events: [{ id: "run:1", source: "harness", kind: "run-started", ts: "2026-07-22T00:00:00.000Z", payload: {} }],
      nextSince: "run:1",
      capabilities: { events: true },
    });
    const malformedEvents: FetchLike = async () => Response.json({
      events: [], nextSince: "next", capabilities: { events: "yes" }, hasMore: "false",
    });
    const malformedConfig: FetchLike = async () => Response.json({
      revision: "r1", fields: { watchdog: { value: () => undefined, source: "run", immutable: false, mutationClass: "mid-run" } },
    });
    const malformedDecisions: FetchLike = async () => Response.json({
      decisions: [{ id: "d1", task: null, summary: null, requestedAt: null, options: [], why: 1 }], capabilities: {},
    });
    const malformedLimits: FetchLike = async () => Response.json({ run: { ratelimits: { provider: { provider: "x", state: "ok", waitMs: "1" } } } });

    await expect(makeAdapter(validRunEvent).getRunEvents("run")).resolves.toMatchObject({ events: [{ id: "run:1" }] });
    await expect(makeAdapter(malformedEvents).getRunEvents("run")).rejects.toThrow(/invalid harness response/i);
    await expect(makeAdapter(malformedConfig).getRunConfig("run")).rejects.toThrow(/invalid harness response/i);
    await expect(makeAdapter(malformedDecisions).getDecisions("run")).rejects.toThrow(/invalid harness response/i);
    await expect(makeAdapter(malformedLimits).getRunDetail("run")).rejects.toThrow(/invalid harness response/i);
  });
  it("builds a plans panel from /runs with waves grouped from the DAG", async () => {
    const { fetchImpl } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const result = await adapter.poll();

    const plans = result.panels.find((panel) => panel.id === "plans");
    expect(plans).toBeDefined();
    const data = plans!.data as {
      runs: Array<{
        runId: string;
        seq: number;
        repoRoot: string;
        registry?: { slug?: string; created?: string; projectName?: string; topic?: string };
        failClass?: string;
        updatedAt: string | null;
        attempts: number;
        abandoned: boolean;
        waves: Array<{
          wave: number;
          tasks: Array<{
            id: string;
            status: string;
            state?: string;
            seat?: string;
            deps?: string[];
            attempt?: number;
            branch?: string;
            failClass?: string;
          }>;
        }>;
      }>;
    };
    expect(data.runs).toHaveLength(2);

    const optData = data.runs.find((run) => run.runId === "05c65e0ba11a--opt-data-integrity")!;
    expect(optData.seq).toBe(12);
    expect(optData.attempts).toBe(3);
    expect(optData.repoRoot).toBe("/home/user/Projects/opt-data-integrity");
    expect(optData.registry).toEqual({
      slug: "opt-data-integrity",
      created: "2026-07-08",
      projectName: "opt-data-integrity",
      topic: "Data integrity hardening",
    });
    expect(optData.waves).toEqual([
      {
        wave: 1,
        tasks: [
          {
            id: "t1",
            status: "succeeded",
            state: "committed",
            seat: "coder",
            deps: [],
            attempt: 0,
            branch: "",
          },
        ],
      },
      {
        wave: 2,
        tasks: [
          {
            id: "t5",
            status: "running",
            state: "gated",
            seat: "coder",
            deps: ["t1"],
            attempt: 0,
            branch: "",
          },
        ],
      },
    ]);

    const failed = data.runs.find((run) => run.runId === "4b4a6e1d17d2--grok-account-parity")!;
    expect(failed.attempts).toBe(1);
    expect(failed.updatedAt).toBeNull();
    expect(failed.failClass).toBe("gate-failed");
    expect(failed.waves[0]?.tasks[0]?.failClass).toBe("gate-failed");
    expect(data.runs.every((run) => run.abandoned === false)).toBe(true);
  });

  it("forwards honest defaults when repo metadata is absent", async () => {
    const { fetchImpl: baseFetch } = createMockFetch();
    const fetchImpl: FetchLike = async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.endsWith("/runs")) {
        const source = fixture<{ runs: Array<Record<string, unknown>> }>("runs.json").runs[0]!;
        const { repoRoot: _repoRoot, registry: _registry, ...run } = source;
        return Response.json({ runs: [run] });
      }
      return baseFetch(input, init);
    };

    const result = await makeAdapter(fetchImpl).poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!;
    const run = (plans.data as { runs: Array<{ repoRoot: string; registry?: unknown }> }).runs[0]!;

    expect(run.repoRoot).toBe("");
    expect(run.registry).toBeUndefined();
  });

  it("forwards the persisted abandoned timestamp without fabrication", async () => {
    abandonRun("05c65e0ba11a--opt-data-integrity", () => "2026-07-19T12:00:00.000Z");
    const { fetchImpl } = createMockFetch();
    const result = await makeAdapter(fetchImpl).poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!;
    const run = (plans.data as {
      runs: Array<{ runId: string; abandoned: boolean; abandonedAt: string | null }>;
    }).runs.find((entry) => entry.runId === "05c65e0ba11a--opt-data-integrity")!;

    expect(run.abandoned).toBe(true);
    expect(run.abandonedAt).toBe("2026-07-19T12:00:00.000Z");
  });

  it("emits a halt item for a run whose status requires human intervention", async () => {
    const { fetchImpl } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const result = await adapter.poll();

    const halts = result.items.filter((item) => item.kind === "halt");
    expect(halts).toHaveLength(1);
    expect(halts[0]).toMatchObject({
      id: "halt-4b4a6e1d17d2--grok-account-parity",
      severity: "act",
      kind: "halt",
      title: "grok-account-parity halted",
      detail: "runner-not-live",
    });
    // the gated (non-halt) run must not produce a halt item.
    expect(halts.some((item) => item.id.includes("opt-data-integrity"))).toBe(false);
  });

  it("does not emit harness decision inbox items", async () => {
    const { fetchImpl } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const result = await adapter.poll();

    expect(result.items.filter((item) => item.kind === "decision")).toEqual([]);
  });

  const LIVENESS_NOW_MS = Date.parse("2026-08-04T03:00:00.000Z");

  function activeRun(overrides: Record<string, unknown> = {}) {
    return {
      runId: "run-liveness",
      seq: 1,
      title: "liveness-plan",
      status: "running",
      degradedReason: "",
      state: "running",
      currentTask: "t1",
      owner: "runner",
      tasksTotal: 2,
      tasksCompleted: 0,
      pendingDecisions: 0,
      updatedAt: "2026-08-04T02:59:30.000Z",
      dag: { nodes: [], edges: [] },
      ...overrides,
    };
  }

  function makeLivenessAdapter(
    attempts: unknown[],
    runOverrides: Record<string, unknown> = {},
    fetchExtras?: FetchLike,
    events?: unknown[] | "unavailable",
  ) {
    const run = activeRun(runOverrides);
    const defaultEvents = [{
      id: "e-live",
      source: "run",
      kind: "activity",
      ts: "2026-08-04T02:59:30.000Z",
      payload: {},
    }];
    return createHarnessAdapter({
      fetchImpl: async (input, init) => {
        const url = typeof input === "string" ? input : input.toString();
        const path = url.replace(BASE_URL, "");
        if (path === "/runs") return Response.json({ runs: [run] });
        if (path === "/queue") return emptyQueue();
        if (path === `/runs/${encodeURIComponent(run.runId)}/attempts`) return Response.json({ attempts });
        if (path === `/runs/${encodeURIComponent(run.runId)}/events`) {
          if (events === "unavailable") throw new Error("connect ECONNREFUSED");
          return Response.json({
            events: events ?? defaultEvents,
            nextSince: "e-live",
            capabilities: {},
          });
        }
        if (path.endsWith("/timeline")) return Response.json(fixture("timeline-opt-data-integrity.json"));
        if (fetchExtras) return fetchExtras(input, init);
        return new Response(JSON.stringify({ error: "not-found" }), { status: 404 });
      },
      baseUrl: BASE_URL,
      token: TOKEN,
      interval: 5000,
      harnessHome: join(configDir, "harness"),
      ensureImpl: async () => {},
      now: () => LIVENESS_NOW_MS,
    });
  }

  it("does not emit a liveness alert when an attempt is within budget with recent heartbeats", async () => {
    const adapter = makeLivenessAdapter([
      {
        attemptId: "attempt-live",
        task: "t1",
        timeoutSecs: 120,
        liveness: { elapsedSecs: 30, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:59:30.000Z" },
      },
    ], {
      dag: {
        nodes: [{ id: "t1", kind: "task", label: "t1", status: "running", meta: { wave: 1, state: "running", deps: [], attempt: 0, seat: "coder", branch: "" } }],
        edges: [],
      },
    });

    const result = await adapter.poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!.data as {
      runs: Array<{ alarmed?: boolean; waves: Array<{ tasks: Array<{ id: string; alarmed?: boolean }> }> }>;
    };

    expect(result.items.filter((item) => item.kind === "alert")).toHaveLength(0);
    expect(plans.runs[0]?.alarmed).toBeUndefined();
    expect(plans.runs[0]?.waves[0]?.tasks[0]?.alarmed).toBeUndefined();
    expect(isAttemptAlarmed(
      { attemptId: "attempt-live", task: "t1", timeoutSecs: 120, liveness: { elapsedSecs: 30, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:59:30.000Z" } },
      LIVENESS_NOW_MS,
    )).toBe(false);
  });

  it("emits a liveness alert when attempt elapsed exceeds 2x timeoutSecs", async () => {
    const adapter = makeLivenessAdapter([
      {
        attemptId: "attempt-stale",
        task: "t1",
        timeoutSecs: 100,
        liveness: { elapsedSecs: 250, lastActivity: "tool_call:bash", lastSignalAt: "2026-08-04T02:59:30.000Z" },
      },
    ], {
      dag: {
        nodes: [{ id: "t1", kind: "task", label: "t1", status: "running", meta: { wave: 1, state: "running", deps: [], attempt: 0, seat: "coder", branch: "" } }],
        edges: [],
      },
    });

    const result = await adapter.poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!.data as {
      runs: Array<{ runId: string; alarmed?: boolean; waves: Array<{ tasks: Array<{ id: string; alarmed?: boolean }> }> }>;
    };

    const alerts = result.items.filter((item) => item.kind === "alert");
    expect(alerts).toHaveLength(1);
    expect(alerts[0]).toMatchObject({
      id: "liveness-run-liveness-attempt-stale",
      severity: "warn",
      kind: "alert",
      title: "liveness-plan attempt stalled",
      detail: "task t1: elapsed 250s exceeds 2× timeout (100s)",
      actions: [],
    });
    expect(plans.runs.find((run) => run.runId === "run-liveness")?.alarmed).toBe(true);
    expect(plans.runs[0]?.waves[0]?.tasks.find((task) => task.id === "t1")?.alarmed).toBe(true);
  });

  it("emits an alert when active-run attempt coverage is unavailable", async () => {
    const { fetchImpl: baseFetch } = createMockFetch();
    const adapter = makeAdapter(async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.endsWith("/attempts")) throw new Error("connect ECONNREFUSED");
      return baseFetch(input, init);
    });

    const result = await adapter.poll();

    expect(result.items).toContainEqual(expect.objectContaining({
      id: "attempts-unavailable-05c65e0ba11a--opt-data-integrity",
      severity: "warn",
      kind: "alert",
    }));
  });

  it("emits a liveness alert when heartbeat gap exceeds 180s while still in progress", async () => {
    const adapter = makeLivenessAdapter(
      [{
        attemptId: "attempt-gap",
        task: "t1",
        timeoutSecs: 120,
        liveness: { elapsedSecs: 60, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:56:00.000Z" },
      }],
      { updatedAt: "2026-08-04T03:00:00.000Z" },
    );

    const result = await adapter.poll();

    const alerts = result.items.filter((item) => item.kind === "alert");
    expect(alerts).toHaveLength(1);
    expect(alerts[0]).toMatchObject({
      id: "liveness-run-liveness-attempt-gap",
      severity: "warn",
      kind: "alert",
      detail: "task t1: no heartbeat for 240s",
    });
  });

  it("never emits a liveness alert for a completed attempt regardless of elapsed time", async () => {
    const adapter = makeLivenessAdapter(
      [{
        attemptId: "attempt-done",
        task: "t1",
        timeoutSecs: 60,
        liveness: null,
      }],
      { updatedAt: "2026-08-04T02:50:00.000Z" },
    );

    const result = await adapter.poll();

    expect(result.items.filter((item) => item.kind === "alert")).toHaveLength(0);
    expect(isAttemptAlarmed(
      { attemptId: "attempt-done", task: "t1", timeoutSecs: 60, liveness: null },
      LIVENESS_NOW_MS,
    )).toBe(false);
  });

  it("alarms only the stale attempt when concurrent in-progress attempts share a fresh run.updatedAt", async () => {
    const adapter = makeLivenessAdapter(
      [
        {
          attemptId: "attempt-fresh",
          task: "t1",
          timeoutSecs: 120,
          liveness: { elapsedSecs: 30, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:59:30.000Z" },
        },
        {
          attemptId: "attempt-wedged",
          task: "t2",
          timeoutSecs: 120,
          liveness: { elapsedSecs: 60, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:56:00.000Z" },
        },
      ],
      { updatedAt: "2026-08-04T03:00:00.000Z" },
    );

    const result = await adapter.poll();

    const alerts = result.items.filter((item) => item.kind === "alert");
    expect(alerts).toHaveLength(1);
    expect(alerts[0]).toMatchObject({
      id: "liveness-run-liveness-attempt-wedged",
      detail: "task t2: no heartbeat for 240s",
    });
  });

  it("computes per-run staleness from the newest journal and heartbeat timestamps", () => {
    const journalMs = Date.parse("2026-08-04T02:56:00.000Z");
    const heartbeatMs = Date.parse("2026-08-04T02:59:00.000Z");
    expect(newestJournalEventMs([
      { id: "e1", source: "run", kind: "activity", ts: "2026-08-04T02:56:00.000Z", payload: {} },
      { id: "e2", source: "run", kind: "activity", ts: "2026-08-04T02:50:00.000Z", payload: {} },
    ])).toBe(journalMs);
    const stalenessMs = computeRunStalenessMs(LIVENESS_NOW_MS, journalMs, heartbeatMs);
    expect(stalenessMs).toBe(LIVENESS_NOW_MS - heartbeatMs);
    expect(isRunAlarmedByStaleness(stalenessMs)).toBe(false);
    expect(isRunAlarmedByStaleness(computeRunStalenessMs(LIVENESS_NOW_MS, journalMs, Date.parse("2026-08-04T02:56:00.000Z")))).toBe(true);
    expect(computeRunStalenessMs(LIVENESS_NOW_MS, null, null)).toBeNull();
    expect(isRunAlarmedByStaleness(null)).toBe(false);
  });

  it("flags a run alarmed by run-level staleness when journal and heartbeat are both stale", async () => {
    const adapter = makeLivenessAdapter(
      [{
        attemptId: "attempt-quiet",
        task: "t1",
        timeoutSecs: 120,
        liveness: null,
      }],
      {
        dag: {
          nodes: [{ id: "t1", kind: "task", label: "t1", status: "running", meta: { wave: 1, state: "running", deps: [], attempt: 0, seat: "coder", branch: "" } }],
          edges: [],
        },
      },
      undefined,
      [{
        id: "e-stale",
        source: "run",
        kind: "activity",
        ts: "2026-08-04T02:55:00.000Z",
        payload: {},
      }],
    );

    const result = await adapter.poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!.data as {
      runs: Array<{ alarmed?: boolean; waves: Array<{ tasks: Array<{ id: string; alarmed?: boolean }> }> }> };
    expect(result.items.filter((item) => item.kind === "alert")).toHaveLength(0);
    expect(plans.runs[0]?.alarmed).toBe(true);
    expect(plans.runs[0]?.waves[0]?.tasks[0]?.alarmed).toBe(true);
  });

  it("does not flag run-level staleness when journal coverage is unavailable", async () => {
    const adapter = makeLivenessAdapter(
      [{
        attemptId: "attempt-live",
        task: "t1",
        timeoutSecs: 120,
        liveness: { elapsedSecs: 30, lastActivity: "thinking", lastSignalAt: "2026-08-04T02:59:30.000Z" },
      }],
      {
        dag: {
          nodes: [{ id: "t1", kind: "task", label: "t1", status: "running", meta: { wave: 1, state: "running", deps: [], attempt: 0, seat: "coder", branch: "" } }],
          edges: [],
        },
      },
      undefined,
      "unavailable",
    );

    const result = await adapter.poll();
    const plans = result.panels.find((panel) => panel.id === "plans")!.data as {
      runs: Array<{ alarmed?: boolean }> };
    expect(plans.runs[0]?.alarmed).toBeUndefined();
  });

  it("computes exact bucket sums for the forensics panel from the fixture timeline", async () => {
    const { fetchImpl } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const result = await adapter.poll();

    const forensics = result.panels.find((panel) => panel.id === "forensics:05c65e0ba11a--opt-data-integrity");
    expect(forensics).toBeDefined();
    const data = forensics!.data as { attribution: Array<{ cat: string; totalMs: number }> };

    const byCat = Object.fromEntries(data.attribution.map((row) => [row.cat, row.totalMs]));
    expect(byCat).toEqual({
      "llm-implement": 420000,
      "llm-fixer": 180000,
      "llm-review": 150000,
      gate0: 300000,
      "idle-restart": 60000,
      other: 30000,
    });
    const total = data.attribution.reduce((sum, row) => sum + row.totalMs, 0);
    expect(total).toBe(1140000);
  });

  it("poll rejects when the harness control-api is unreachable, so the reconciler retains all prior state", async () => {
    const downFetch: FetchLike = async () => {
      throw new Error("connect ECONNREFUSED");
    };
    const adapter = makeAdapter(downFetch);

    await expect(adapter.poll()).rejects.toThrow();
  });

  it("aborts a hung control-api request after the configured timeout", async () => {
    const hungFetch: FetchLike = async (_input, init) => {
      const signal = init?.signal;
      if (!signal) throw new Error("missing timeout signal");
      return new Promise<Response>((_resolve, reject) => {
        signal.addEventListener("abort", () => reject(signal.reason), { once: true });
      });
    };
    const adapter = createHarnessAdapter({
      fetchImpl: hungFetch,
      baseUrl: BASE_URL,
      token: TOKEN,
      requestTimeoutMs: 10,
      harnessHome: join(configDir, "harness"),
      ensureImpl: async () => {},
    });

    await expect(adapter.poll()).rejects.toThrow(/timed out/i);
  });

  it("caps concurrent decisions and timeline requests", async () => {
    const source = fixture<{ runs: Array<Record<string, unknown>> }>("runs.json").runs[0]!;
    const runs = Array.from({ length: 18 }, (_, index) => ({
      ...structuredClone(source),
      runId: `run-${index}`,
      pendingDecisions: 1,
    }));
    let active = 0;
    let maxActive = 0;
    const fetchImpl: FetchLike = async (input) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.endsWith("/runs")) return Response.json({ runs });
      if (url.endsWith("/queue")) return emptyQueue();
      active += 1;
      maxActive = Math.max(maxActive, active);
      await new Promise((resolve) => setTimeout(resolve, 5));
      active -= 1;
      if (url.endsWith("/decisions")) return Response.json({ decisions: [] });
      return Response.json(fixture("timeline-opt-data-integrity.json"));
    };
    const adapter = createHarnessAdapter({
      fetchImpl,
      baseUrl: BASE_URL,
      token: TOKEN,
      requestConcurrency: 4,
    });

    await adapter.poll();

    expect(maxActive).toBe(4);
  });

  it("poll succeeds when a run's decisions endpoint would fail because decisions are not polled for inbox items", async () => {
    const { fetchImpl: baseFetch } = createMockFetch();
    const flakyFetch: FetchLike = async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.includes("/decisions")) {
        throw new Error("connect ECONNREFUSED");
      }
      return baseFetch(input, init);
    };
    const adapter = makeAdapter(flakyFetch);

    const result = await adapter.poll();
    expect(result.items.filter((item) => item.kind === "decision")).toEqual([]);
  });

  it("stays zero-throw when only the timeline endpoint fails — the forensics panel just stays stale", async () => {
    const { fetchImpl: baseFetch } = createMockFetch();
    const flakyFetch: FetchLike = async (input, init) => {
      const url = typeof input === "string" ? input : input.toString();
      if (url.includes("/timeline")) {
        throw new Error("connect ECONNREFUSED");
      }
      return baseFetch(input, init);
    };
    const adapter = makeAdapter(flakyFetch);

    const result = await adapter.poll();

    expect(result.panels.some((panel) => panel.id === "plans")).toBe(true);
    expect(result.panels.some((panel) => panel.id.startsWith("forensics:"))).toBe(false);
    expect(result.items.some((item) => item.kind === "decision")).toBe(false);
    expect(result.items.some((item) => item.kind === "halt")).toBe(true);
  });

  it("proxies decision answers with the bearer token and JSON body", async () => {
    const { fetchImpl, calls } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const response = await adapter.answerDecision("4b4a6e1d17d2--grok-account-parity", "d-42", "accept-quarantine-continue");

    expect(response).toEqual({ statusCode: 200, applied: true });
    const call = calls.find((c) => c.method === "POST" && c.url.endsWith("/decisions/d-42"));
    expect(call).toBeDefined();
    expect(call!.authorization).toBe(`Bearer ${TOKEN}`);
    expect(call!.body).toEqual({ choice: "accept-quarantine-continue" });
  });

  it("redacts nested credentials from decision answer responses", async () => {
    const adapter = makeAdapter(async () => Response.json({
      applied: true,
      result: { callback: { authorization: "decision-response-secret" } },
    }));

    const response = await adapter.answerDecision("run", "decision", "proceed");

    expect(JSON.stringify(response)).not.toContain("decision-response-secret");
    expect(response).toEqual({ applied: true, result: { callback: { authorization: "[REDACTED]" } } });
  });

  it("proxies steer requests with the bearer token and JSON body", async () => {
    const { fetchImpl, calls } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    const response = await adapter.steerTask("4b4a6e1d17d2--grok-account-parity", "t1", { text: "focus on the migration" });

    expect(response).toEqual({ ok: true, id: "steer-1", queued: true, restart: false });
    const call = calls.find((c) => c.method === "POST" && c.url.endsWith("/tasks/t1/steer"));
    expect(call).toBeDefined();
    expect(call!.authorization).toBe(`Bearer ${TOKEN}`);
    expect(call!.body).toEqual({ text: "focus on the migration" });
  });

  it("discards nested credentials from closed steer responses", async () => {
    const adapter = makeAdapter(async () => Response.json({
      ok: true,
      id: "steer-1",
      queued: true,
      restart: false,
      acknowledgement: { nested: { token: "steer-response-secret" } },
    }));

    const response = await adapter.steerTask("run", "task", { text: "continue" });

    expect(JSON.stringify(response)).not.toContain("steer-response-secret");
    expect(response).toEqual({
      ok: true,
      id: "steer-1",
      queued: true,
      restart: false,
    });
  });

  it("attaches the bearer token to every GET call during poll()", async () => {
    const { fetchImpl, calls } = createMockFetch();
    const adapter = makeAdapter(fetchImpl);

    await adapter.poll();

    expect(calls.length).toBeGreaterThan(0);
    for (const call of calls) {
      expect(call.authorization).toBe(`Bearer ${TOKEN}`);
    }
  });

  it("re-reads the control-api pointer for each poll", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    const adapter = makeDiscoveryAdapter(async (input) => {
      const url = new URL(input.toString());
      ports.push(Number(url.port));
      return url.pathname === "/queue" ? emptyQueue() : emptyRuns();
    });

    await adapter.poll();
    writeHarnessConnection(configDir, 5102);
    await adapter.poll();

    expect(ports).toEqual([5101, 5101, 5101, 5102, 5102, 5102]);
  });

  it("invalidates discovered connections on network failures and timeouts", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    const failures = [new Error("ECONNREFUSED"), new Error("request timed out")];
    const adapter = makeDiscoveryAdapter(async (input) => {
      ports.push(Number(new URL(input.toString()).port));
      const failure = failures.shift();
      if (failure) throw failure;
      return Response.json({ events: [], nextSince: "next", capabilities: {} });
    });

    await expect(adapter.getRunEvents("run")).rejects.toThrow(/ECONNREFUSED/);
    writeHarnessConnection(configDir, 5102);
    await expect(adapter.getRunEvents("run")).rejects.toThrow(/timed out/);
    writeHarnessConnection(configDir, 5103);
    await adapter.getRunEvents("run");

    expect(ports).toEqual([5101, 5102, 5103]);
  });

  it("classifies 401 separately from other status and JSON failures", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    const responses = [
      new Response("not json", { status: 401 }),
      Response.json({ error: "missing" }, { status: 404 }),
      Response.json({ error: "conflict" }, { status: 409 }),
      Response.json({ error: "failed" }, { status: 500 }),
      new Response("not json"),
    ];
    const adapter = makeDiscoveryAdapter(async (input) => {
      ports.push(Number(new URL(input.toString()).port));
      return responses.shift()!;
    });

    await expect(adapter.controlRun("run", "pause")).rejects.toThrow();
    writeHarnessConnection(configDir, 5102);
    for (let index = 0; index < 4; index += 1) await expect(adapter.controlRun("run", "pause")).rejects.toThrow();

    expect(ports).toEqual([5101, 5102, 5102, 5102, 5102]);
  });

  it("invalidates discovered connections when reading a response body fails", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    let unreadable = true;
    const adapter = makeDiscoveryAdapter(async (input) => {
      ports.push(Number(new URL(input.toString()).port));
      if (unreadable) {
        unreadable = false;
        return { status: 200, ok: true, text: async () => { throw new Error("body closed"); } } as unknown as Response;
      }
      return Response.json({ events: [], nextSince: "next", capabilities: {} });
    });

    await expect(adapter.getRunEvents("run")).rejects.toThrow(/unable to read harness response/);
    writeHarnessConnection(configDir, 5102);
    await adapter.getRunEvents("run");

    expect(ports).toEqual([5101, 5102]);
  });

  it("keeps a newer generation when an older in-flight request fails", async () => {
    writeHarnessConnection(configDir, 5101);
    let rejectOld!: (error: Error) => void;
    const ports: number[] = [];
    const adapter = makeDiscoveryAdapter((input) => {
      const url = new URL(input.toString());
      const port = Number(url.port);
      ports.push(port);
      if (port === 5101) return new Promise<Response>((_resolve, reject) => { rejectOld = reject; });
      return Promise.resolve(url.pathname === "/queue" ? emptyQueue() : emptyRuns());
    });

    const stale = adapter.getRunEvents("run");
    writeHarnessConnection(configDir, 5102);
    await adapter.poll();
    rejectOld(new Error("old connection failed"));
    await expect(stale).rejects.toThrow(/old connection failed/);
    await adapter.poll();

    expect(ports).toEqual([5101, 5102, 5102, 5102, 5102, 5102, 5102]);
  });

  it("pins a poll and established SSE stream to their starting connection", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    let failStream = () => {};
    const run = { ...fixture<{ runs: Array<Record<string, unknown>> }>("runs.json").runs[0]!, pendingDecisions: 1 };
    const adapter = makeDiscoveryAdapter(async (input) => {
      const url = new URL(input.toString());
      ports.push(Number(url.port));
      if (url.pathname === "/health") return Response.json({});
      if (url.pathname === "/runs") {
        writeHarnessConnection(configDir, 5102);
        return Response.json({ runs: [run] });
      }
      if (url.pathname === "/queue") return emptyQueue();
      if (url.pathname.endsWith("/decisions")) return Response.json({ decisions: [] });
      if (url.pathname.endsWith("/timeline")) return Response.json(fixture("timeline-opt-data-integrity.json"));
      if (url.pathname.endsWith("/attempts")) return Response.json({ attempts: [] });
      if (url.pathname.endsWith("/events")) return Response.json({ events: [], nextSince: "next", capabilities: {} });
      return new Response(new ReadableStream({ start(controller) { failStream = () => controller.error(new Error("stream closed")); } }), {
        headers: { "content-type": "text/event-stream" },
      });
    });

    await adapter.poll();
    expect(ports).toEqual([5101, 5101, 5101, 5101, 5101, 5101]);
    const stream = await adapter.openTaskStream("run", "task");
    failStream();
    await expect(stream.body!.getReader().read()).rejects.toThrow(/stream closed/);
    writeHarnessConnection(configDir, 5103);
    await adapter.getRunEvents("run");

    expect(ports.slice(-2)).toEqual([5101, 5101]);
  });

  it("invalidates SSE handshakes, rotates tokens, and never reads fixed-endpoint pointers", async () => {
    writeHarnessConnection(configDir, 5101, "old-token");
    const calls: Array<{ port: number; token: string | null }> = [];
    let handshake = true;
    const adapter = makeDiscoveryAdapter(async (input, init) => {
      calls.push({ port: Number(new URL(input.toString()).port), token: new Headers(init?.headers).get("authorization") });
      if (handshake) {
        handshake = false;
        return new Response("unauthorized", { status: 401 });
      }
      return Response.json({ events: [], nextSince: "next", capabilities: {} });
    });

    await expect(adapter.openTaskStream("run", "task")).rejects.toThrow();
    writeHarnessConnection(configDir, 5102, "new-token");
    await adapter.getRunEvents("run");
    expect(calls).toEqual([{ port: 5101, token: "Bearer old-token" }, { port: 5102, token: "Bearer new-token" }]);

    const fixedCalls: string[] = [];
    const fixed = createHarnessAdapter({
      baseUrl: BASE_URL,
      token: TOKEN,
      harnessHome: join(configDir, "missing"),
      fetchImpl: async (input) => {
        const url = input.toString();
        fixedCalls.push(url);
        if (url.endsWith("/queue")) return emptyQueue();
        if (fixedCalls.length === 1) throw new Error("fixed endpoint unavailable");
        if (fixedCalls.length === 2) return Response.json({ error: "unauthorized" }, { status: 401 });
        return emptyRuns();
      },
    });
    await expect(fixed.getRunEvents("run")).rejects.toThrow(/fixed endpoint unavailable/);
    await expect(fixed.controlRun("run", "pause")).rejects.toThrow();
    await fixed.poll();
    expect(fixedCalls).toEqual([`${BASE_URL}/runs/run/events`, `${BASE_URL}/runs/run/pause`, `${BASE_URL}/health`, `${BASE_URL}/runs`, `${BASE_URL}/queue`]);
  });

  it("rejects failed /runs reads rather than mixing stale runs with queue state", async () => {
    writeHarnessConnection(configDir, 5101);
    const ports: number[] = [];
    const adapter = makeDiscoveryAdapter(async (input) => {
      const url = new URL(input.toString());
      ports.push(Number(url.port));
      if (url.pathname === "/health") return Response.json({});
      throw new Error(`connection refused: ${url.pathname}`);
    });

    await expect(adapter.poll()).rejects.toThrow(/connection refused: \/runs/);
    expect(ports).toEqual([5101, 5101]);
  });

  it("self-heals a dead control-api by running ensure and retrying the poll", async () => {
    writeHarnessConnection(configDir, 5101);
    let healed = false;
    let ensured = 0;
    const adapter = makeDiscoveryAdapter(async (input) => {
      const url = new URL(input.toString());
      if (!healed) throw new Error("connect ECONNREFUSED");
      return url.pathname === "/queue" ? emptyQueue() : emptyRuns();
    }, configDir, { ensureImpl: async () => { ensured += 1; healed = true; } });

    await adapter.poll();
    expect(ensured).toBe(1);
  });

  it("re-runs ensure when the control-api serves a superseded engine version", async () => {
    writeHarnessConnection(configDir, 5101);
    mkdirSync(join(configDir, "engine"), { recursive: true });
    writeFileSync(join(configDir, "engine", "CURRENT"), "0.2.0\n");
    let version = "0.1.0";
    let ensured = 0;
    const adapter = makeDiscoveryAdapter(async (input) => {
      const url = new URL(input.toString());
      if (url.pathname === "/health") return Response.json({ version });
      return url.pathname === "/queue" ? emptyQueue() : emptyRuns();
    }, configDir, { ensureImpl: async () => { ensured += 1; version = "0.2.0"; } });

    await adapter.poll();
    expect(ensured).toBe(1);
  });
});
