Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

103 KB
Raw Blame
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Ingestion control plane</title>
    <style>
      :root {
        --bg: #14161a;
        --panel: #1c1f26;
        --panel-2: #23272f;
        --border: #2c313b;
        --text: #e6e9ef;
        --muted: #8b93a1;
        --accent: #4f7cff;
        --good: #3fb950;
        --warn: #d29922;
        --error: #f85149;
        --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
      }
      * { box-sizing: border-box; }
      body {
        margin: 0;
        background: var(--bg);
        color: var(--text);
        font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      }
      .app { display: flex; min-height: 100vh; }

      /* sidebar */
      .side {
        flex: 0 0 210px; background: var(--panel); border-right: 1px solid var(--border);
        padding: 14px 10px; position: sticky; top: 0; height: 100vh;
      }
      .side .brand { font-weight: 600; font-size: 14px; padding: 4px 10px 14px; }
      .side .nav-item {
        display: block; padding: 8px 10px; border-radius: 6px; color: var(--muted);
        cursor: pointer; margin-bottom: 2px; font-size: 13px;
      }
      .side .nav-item:hover { background: var(--panel-2); color: var(--text); }
      .side .nav-item.active { background: var(--panel-2); color: var(--text); border-left: 2px solid var(--accent); }

      /* main */
      .main { flex: 1 1 auto; padding: 16px; min-width: 0; }
      .main h1 { font-size: 16px; margin: 0 0 4px; }
      .main .desc { color: var(--muted); margin: 0 0 14px; font-size: 12px; }

      .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; margin-bottom: 14px; }
      .panel > h2 {
        font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;
        color: var(--muted); margin: 0; padding: 10px 14px; border-bottom: 1px solid var(--border);
        display: flex; justify-content: space-between; align-items: center; gap: 8px;
      }
      .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 10px 14px; }

      table { width: 100%; border-collapse: collapse; }
      th, td { text-align: left; padding: 6px 14px; border-bottom: 1px solid var(--border); font-size: 12px; }
      th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
      td.mono, th.mono { font-family: var(--mono); }
      td.diff { color: var(--error); }
      td.nowrap { white-space: nowrap; }
      .scroll-x { overflow-x: auto; }
      .clip { display: inline-block; max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; }
      tr.clickable:hover td { background: rgba(79,124,255,0.06); cursor: pointer; }
      tr.selected td { background: rgba(79,124,255,0.1); }
      td .bar { height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; display: inline-block; vertical-align: middle; }
      td .bar.hot { background: var(--error); }
      td .bar.warm { background: var(--warn); }

      .pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }
      .pill.good { background: rgba(63,185,80,0.16); color: var(--good); }
      .pill.warn { background: rgba(210,153,34,0.16); color: var(--warn); }
      .pill.bad { background: rgba(248,81,73,0.16); color: var(--error); }
      .pill.muted { background: rgba(139,147,161,0.18); color: var(--muted); }
      .pill.accent { background: rgba(79,124,255,0.18); color: #a9c0ff; }

      button, select {
        background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
        border-radius: 6px; padding: 5px 10px; font-size: 12px; cursor: pointer; font-family: inherit;
      }
      button:hover { border-color: var(--accent); }
      button:disabled { opacity: 0.5; cursor: default; }
      button:disabled:hover { border-color: var(--border); }
      input.search {
        background: var(--panel-2); color: var(--text); border: 1px solid var(--border);
        border-radius: 6px; padding: 5px 10px; font-size: 12px; font-family: inherit; width: 240px;
      }
      input.search:focus { outline: none; border-color: var(--accent); }
      .toolbar { border-bottom: 1px solid var(--border); }
      .toolbar .count { margin-left: auto; }
      .pager { border-top: 1px solid var(--border); justify-content: flex-end; }
      .panel > h2.dep-head { cursor: pointer; user-select: none; }
      .panel > h2.dep-head:hover { background: var(--panel-2); }
      .dep-head .chev { color: var(--muted); flex: 0 0 auto; }
      .panel > h2 .ns { color: var(--text); font-family: var(--mono); text-transform: none; letter-spacing: 0; font-size: 12px; font-weight: 600; }
      .dep-head .dep-meta { text-transform: none; letter-spacing: 0; font-weight: 400; }
      button.small { padding: 2px 8px; font-size: 11px; }
      .muted { color: var(--muted); }
      .mono { font-family: var(--mono); }
      .empty { padding: 18px 14px; color: var(--muted); }
      .error-box { padding: 10px 14px; color: var(--error); font-family: var(--mono); font-size: 12px; white-space: pre-wrap; }

      .progress { background: var(--panel-2); border-radius: 4px; height: 8px; overflow: hidden; min-width: 160px; }
      .progress > div { background: var(--accent); height: 100%; transition: width 0.3s; }

      /* token breakdown */
      .token-block { border-bottom: 1px solid var(--border); }
      .token-head { display: flex; gap: 10px; align-items: center; padding: 9px 14px; background: var(--panel-2); flex-wrap: wrap; }
      .token-head .tok { font-family: var(--mono); cursor: pointer; }
      .token-head .tok:hover { color: #a9c0ff; }
      .token-head .share { margin-left: auto; display: flex; gap: 10px; align-items: center; }
      .token-head .bar { height: 7px; border-radius: 3px; background: var(--accent); }
      .token-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 4px 20px; padding: 8px 14px 12px; }
      .token-cols h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 4px 0; }
      .krow { display: flex; align-items: center; gap: 8px; padding: 2px 0; font-size: 12px; }
      .krow .key { font-family: var(--mono); flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
      .krow .key:hover { color: #a9c0ff; }
      .krow .cnt { color: var(--muted); font-family: var(--mono); font-size: 11px; flex: 0 0 auto; margin-left: auto; }
      .krow .kbar { height: 5px; border-radius: 3px; background: var(--accent); flex: 0 0 auto; }

      .cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; padding: 12px 14px; }
      .col h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 0 0 6px; }
      .hist-row { display: flex; align-items: center; gap: 8px; padding: 2px 0; font-size: 11px; }
      .hist-row .lbl { flex: 0 0 70px; text-align: right; color: var(--muted); font-family: var(--mono); }
      .hist-row .hbar { height: 10px; border-radius: 2px; background: var(--accent); }
      .hist-row .hcnt { color: var(--muted); font-family: var(--mono); }

      /* Height is driven by the embedded document (same-origin), so the panel
         expands to fit the debug UI instead of squeezing it into a viewport box. */
      iframe.debug { width: 100%; min-height: 480px; border: 0; background: var(--bg); display: block; }

      /* message browser */
      .overlay {
        position: fixed; inset: 0; background: rgba(8, 10, 13, 0.6); z-index: 20;
        display: flex; align-items: center; justify-content: center; padding: 24px;
      }
      .browser {
        background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
        width: min(1180px, 100%); height: min(780px, 100%);
        display: flex; flex-direction: column; overflow: hidden;
      }
      .browser-head { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }
      .browser-head .title { font-weight: 600; }
      .browser-body { display: flex; flex: 1 1 auto; min-height: 0; }
      .facets { flex: 0 0 250px; border-right: 1px solid var(--border); overflow-y: auto; padding: 8px 14px 12px; }
      .facets h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 10px 0 4px; }
      .facet-row { cursor: pointer; border-radius: 4px; margin: 0 -4px; padding: 2px 4px; }
      .facet-row:hover { background: var(--panel-2); }
      .msgs { flex: 1 1 auto; min-width: 0; overflow-y: auto; }
      .browser-foot { border-top: 1px solid var(--border); }
      .browser-foot .status { margin-right: auto; }
      .chip {
        display: inline-flex; align-items: center; gap: 4px; font-size: 11px;
        background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 1px 4px 1px 8px;
      }
      .chip .val { font-family: var(--mono); max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
      .chip .val:hover { color: #a9c0ff; }
      .chip .x { background: none; border: 0; color: var(--muted); cursor: pointer; padding: 0 4px; font-size: 12px; }
      .chip .x:hover { color: var(--error); }
      tr.msg-detail td { background: var(--panel-2); }
      .tree-row {
        display: flex; align-items: center; gap: 6px; padding: 3px 14px 3px 0;
        cursor: pointer; font-size: 12px;
      }
      .tree-row:hover { background: rgba(79,124,255,0.06); }
      .tree-row.selected { background: rgba(79,124,255,0.1); }
      .tree-row .chev { width: 14px; color: var(--muted); flex: 0 0 auto; text-align: center; }
      .tree-row .meta {
        margin-left: auto; display: flex; gap: 10px; align-items: center;
        color: var(--muted); font-family: var(--mono); font-size: 11px; padding-right: 14px;
      }
      textarea.kv-value {
        width: 100%; min-height: 180px; background: var(--bg); color: var(--text);
        border: 1px solid var(--border); border-radius: 6px; padding: 10px;
        font-family: var(--mono); font-size: 11px; box-sizing: border-box; resize: vertical;
      }
      textarea.kv-value:focus { outline: none; border-color: var(--accent); }
      pre.payload {
        margin: 0 0 8px; padding: 10px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
        font-family: var(--mono); font-size: 11px; white-space: pre-wrap; word-break: break-word;
        max-height: 340px; overflow: auto;
      }
    </style>
  </head>
  <body>
    <div class="app">
      <nav class="side">
        <div class="brand">Ingestion control plane</div>
        <div id="nav"></div>
      </nav>
      <main class="main" id="content"></main>
    </div>

    <script>
      "use strict";

      // ---------- helpers ----------
      const el = (tag, attrs = {}, ...children) => {
        const node = document.createElement(tag);
        for (const [k, v] of Object.entries(attrs)) {
          if (k === "class") node.className = v;
          else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
          else if (v === false || v === null || v === undefined) continue;
          else if (v === true) node.setAttribute(k, "");
          else node.setAttribute(k, v);
        }
        for (const child of children.flat()) {
          if (child === null || child === undefined) continue;
          node.append(child.nodeType ? child : document.createTextNode(child));
        }
        return node;
      };
      const fmtInt = (n) => (n === null || n === undefined ? "–" : Number(n).toLocaleString("en-US"));
      const fmtTarget = (t) => `${t.topic} (${fmtInt(t.partitions)})${t.cluster ? ` on ${t.cluster.name}` : ""}`;
      const fmtBytes = (n) => {
        if (n === null || n === undefined) return "–";
        const units = ["B", "KB", "MB", "GB"];
        let value = Number(n), unit = 0;
        while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
        return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`;
      };
      const fmtAgo = (iso) => {
        const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
        if (seconds < 90) return `${Math.round(seconds)}s ago`;
        if (seconds < 90 * 60) return `${Math.round(seconds / 60)}m ago`;
        if (seconds < 36 * 3600) return `${Math.round(seconds / 3600)}h ago`;
        return `${Math.round(seconds / 86400)}d ago`;
      };
      const fetchJSON = async (url, opts) => {
        const resp = await fetch(url, opts);
        const body = await resp.json().catch(() => ({}));
        if (!resp.ok) throw new Error(body.error || `${resp.status} ${resp.statusText}`);
        return body;
      };
      const copy = (text) => navigator.clipboard && navigator.clipboard.writeText(text);
      // Copy clicks must not also trigger row-level handlers (e.g. expanding
      // a message row in the browser).
      const copyable = (text, cls) =>
        el("span", { class: cls, title: `${text} (click to copy)`, onclick: (e) => { e.stopPropagation(); copy(text); } }, text);

      // Client-side search + pagination over an in-memory row list. The search
      // input is kept stable across re-renders so typing survives refreshes.
      function listView({ placeholder, pageSize, matches, renderTable, emptyText }) {
        let rows = [];
        const state = { query: "", page: 0 };
        const body = el("div", {});
        const count = el("span", { class: "muted mono count" });
        const search = el("input", {
          type: "search", class: "search", placeholder,
          oninput: () => { state.query = search.value.trim().toLowerCase(); state.page = 0; render(); },
        });
        const toolbar = el("div", { class: "row toolbar" }, search, count);

        function render() {
          const filtered = state.query ? rows.filter((row) => matches(row, state.query)) : rows;
          const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
          state.page = Math.min(state.page, pages - 1);
          const pageRows = filtered.slice(state.page * pageSize, (state.page + 1) * pageSize);
          count.textContent = state.query ? `${fmtInt(filtered.length)} of ${fmtInt(rows.length)}` : fmtInt(rows.length);
          const children = [toolbar];
          if (!pageRows.length) {
            children.push(el("div", { class: "empty" }, state.query ? "No matches." : emptyText));
          } else {
            children.push(renderTable(pageRows));
          }
          if (pages > 1) {
            children.push(el("div", { class: "row pager" },
              el("button", { class: "small", disabled: state.page === 0, onclick: () => { state.page--; render(); } }, "‹ prev"),
              el("span", { class: "muted mono" }, `page ${state.page + 1} / ${pages}`),
              el("button", { class: "small", disabled: state.page >= pages - 1, onclick: () => { state.page++; render(); } }, "next ›")));
          }
          body.replaceChildren(...children);
        }

        return {
          body,
          setRows(next) { rows = next; render(); },
          rerender: render,
          reset() { search.value = ""; state.query = ""; state.page = 0; },
        };
      }

      // Section registry: extending the tool = appending an entry here.
      const SECTIONS = [];
      let activeSection = null;

      function navigate(id) {
        const section = SECTIONS.find((s) => s.id === id) || SECTIONS[0];
        if (activeSection && activeSection.unmount) activeSection.unmount();
        activeSection = section;
        for (const item of document.querySelectorAll(".nav-item")) {
          item.classList.toggle("active", item.dataset.id === section.id);
        }
        const content = document.getElementById("content");
        content.replaceChildren(
          el("h1", {}, section.title),
          el("p", { class: "desc" }, section.description)
        );
        section.mount(content);
        location.hash = section.id;
      }

      // ---------- section: partition lag ----------
      const lagSection = {
        id: "lag",
        title: "Lagging partitions",
        description:
          "All ingestion consumer groups sorted by outstanding messages. Drill into a group, then analyze what a lagging partition contains.",
        timers: [],
        selectedTarget: null,
        currentJobId: null,
        unmount() {
          this.timers.forEach(clearInterval);
          this.timers = [];
        },
        mount(root) {
          const overviewBody = el("div", {}, el("div", { class: "empty" }, "Scanning consumer groups…"));
          const overviewFetchedAt = el("span", { class: "muted mono", style: "text-transform: none; letter-spacing: 0" });
          const partitionsTitle = el("span", {}, "Partitions");
          const partitionsBody = el("div", {}, el("div", { class: "empty" }, "Select a consumer group above."));
          const analysisTitle = el("span", {}, "Analysis");
          const analysisBody = el("div", {}, el("div", { class: "empty" }, "Start an analysis from a partition row: head reads from the group's committed offset, tail samples the newest messages."));

          this.overviewView = listView({
            placeholder: "Filter by group or topic…",
            pageSize: 25,
            matches: (row, q) => row.group.toLowerCase().includes(q) || row.topic.toLowerCase().includes(q),
            renderTable: (rows) => this.renderOverviewTable(rows),
            emptyText: "No consumer targets configured.",
          });
          this.partitionsView = listView({
            placeholder: "Filter by partition…",
            pageSize: 100,
            matches: (p, q) => String(p.partition).includes(q),
            renderTable: (rows) => this.renderPartitionsTable(rows),
            emptyText: "No partitions.",
          });

          this.ui = { overviewBody, overviewFetchedAt, partitionsTitle, partitionsBody, analysisTitle, analysisBody };

          root.append(
            el("div", { class: "panel" },
              el("h2", {}, "Consumer groups", el("span", { class: "row", style: "padding:0" }, overviewFetchedAt, el("button", { class: "small", onclick: () => this.refreshOverview() }, "Refresh"))),
              overviewBody),
            el("div", { class: "panel" },
              el("h2", {}, partitionsTitle, el("button", { class: "small", onclick: () => this.refreshPartitions() }, "Refresh")),
              partitionsBody),
            el("div", { class: "panel" }, el("h2", {}, analysisTitle), analysisBody)
          );

          this.refreshOverview();
          this.timers.push(setInterval(() => this.pollJob(), 700));
        },

        async refreshOverview() {
          const { overviewBody, overviewFetchedAt } = this.ui;
          try {
            const data = await fetchJSON("api/lag/overview");
            overviewFetchedAt.textContent = `as of ${new Date(data.fetched_at).toLocaleTimeString()}`;
            this.overviewMaxLag = Math.max(1, ...data.groups.map((r) => r.total_lag ?? 0));
            this.overviewView.setRows(data.groups);
            overviewBody.replaceChildren(this.overviewView.body);
          } catch (e) {
            overviewBody.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
        },

        // Heat bars are scaled against the full result set, not the visible page,
        // so paging/filtering does not recalibrate the colors.
        renderOverviewTable(rows) {
          const maxLag = this.overviewMaxLag;
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "group"), el("th", {}, "topic"), el("th", {}, "partitions"),
              el("th", {}, "lagging"), el("th", {}, "total lag"), el("th", {}, ""))),
            el("tbody", {}, rows.map((row) =>
              row.error
                ? el("tr", {},
                    el("td", { class: "mono" }, row.group),
                    el("td", { class: "mono" }, row.topic),
                    el("td", { colspan: "4" }, el("span", { class: "pill bad", title: row.error }, "scan failed")))
                : el("tr", { class: `clickable ${this.selectedTarget && row.group === this.selectedTarget.group && row.topic === this.selectedTarget.topic ? "selected" : ""}`, onclick: () => this.selectTarget(row) },
                    el("td", { class: "mono" }, row.group),
                    el("td", { class: "mono" }, row.topic),
                    el("td", { class: "mono" }, fmtInt(row.partitions)),
                    el("td", {}, row.lagging_partitions > 0
                      ? el("span", { class: "pill warn" }, fmtInt(row.lagging_partitions))
                      : el("span", { class: "pill good" }, "0")),
                    el("td", { class: "mono" }, fmtInt(row.total_lag)),
                    el("td", {}, row.total_lag > 0
                      ? el("span", { class: `bar ${row.total_lag > maxLag * 0.66 ? "hot" : row.total_lag > maxLag * 0.33 ? "warm" : ""}`, style: `width:${Math.max(2, (row.total_lag / maxLag) * 140)}px` })
                      : null))
            ))
          );
        },

        selectTarget(target) {
          this.selectedTarget = { group: target.group, topic: target.topic };
          this.overviewView.rerender();
          this.partitionsView.reset();
          this.refreshPartitions();
        },

        async refreshPartitions() {
          const { partitionsTitle, partitionsBody } = this.ui;
          if (!this.selectedTarget) return;
          partitionsTitle.textContent = `Partitions — ${this.selectedTarget.group} (${this.selectedTarget.topic})`;
          partitionsBody.replaceChildren(el("div", { class: "empty" }, "Scanning…"));
          try {
            const data = await fetchJSON(`api/lag?group=${encodeURIComponent(this.selectedTarget.group)}&topic=${encodeURIComponent(this.selectedTarget.topic)}`);
            this.partitionsMaxLag = Math.max(1, ...data.partitions.map((p) => p.lag));
            this.partitionsView.setRows(data.partitions);
            partitionsBody.replaceChildren(this.partitionsView.body);
          } catch (e) {
            partitionsBody.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
        },

        renderPartitionsTable(partitions) {
          const maxLag = this.partitionsMaxLag;
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "partition"), el("th", {}, "low"), el("th", {}, "high"),
              el("th", {}, "committed"), el("th", {}, "lag"), el("th", {}, ""), el("th", {}, "analyze"))),
            el("tbody", {}, partitions.map((p) => {
              const width = Math.max(2, Math.round((p.lag / maxLag) * 140));
              const heat = p.lag === 0 ? "" : p.lag > maxLag * 0.66 ? "hot" : p.lag > maxLag * 0.33 ? "warm" : "";
              return el("tr", {},
                el("td", { class: "mono" }, String(p.partition)),
                el("td", { class: "mono" }, fmtInt(p.low_watermark)),
                el("td", { class: "mono" }, fmtInt(p.high_watermark)),
                el("td", { class: "mono" }, p.committed_offset === null ? "–" : fmtInt(p.committed_offset)),
                el("td", { class: "mono" }, fmtInt(p.lag)),
                el("td", {}, p.lag > 0 ? el("span", { class: `bar ${heat}`, style: `width:${width}px` }) : null),
                el("td", {},
                  el("button", { class: "small", onclick: () => this.startAnalysis(p.partition, "committed") }, "head"),
                  " ",
                  el("button", { class: "small", onclick: () => this.startAnalysis(p.partition, "tail") }, "tail"))
              );
            }))
          );
        },

        // One analysis at a time: starting a new one cancels and replaces the current.
        async startAnalysis(partition, mode) {
          if (this.currentJobId) {
            fetchJSON(`api/analyses/${this.currentJobId}`, { method: "DELETE" }).catch(() => {});
          }
          try {
            const resp = await fetchJSON("api/analyses", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ ...this.selectedTarget, partition, mode }),
            });
            this.currentJobId = resp.job_id;
            this.pollJob();
          } catch (e) {
            this.ui.analysisBody.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
        },

        async pollJob() {
          if (!this.currentJobId) return;
          const { analysisTitle, analysisBody } = this.ui;
          let job;
          try {
            job = await fetchJSON(`api/analyses/${this.currentJobId}`);
          } catch {
            return;
          }
          analysisTitle.textContent = `Analysis — ${job.spec.group} p${job.spec.partition} (${job.spec.mode})`;
          if (job.state === "running") {
            const pctDone = job.progress.target ? (job.progress.fetched / job.progress.target) * 100 : 100;
            analysisBody.replaceChildren(
              el("div", { class: "row" },
                el("span", { class: "pill accent" }, "running"),
                el("div", { class: "progress" }, el("div", { style: `width:${pctDone.toFixed(0)}%` })),
                el("span", { class: "muted mono" },
                  `${fmtInt(job.progress.fetched)}/${fmtInt(job.progress.target)} messages · ${fmtBytes(job.progress.bytes_read)} · offset ${fmtInt(job.progress.current_offset)}`),
                el("button", { class: "small", onclick: () => fetchJSON(`api/analyses/${this.currentJobId}`, { method: "DELETE" }) }, "cancel"))
            );
          } else if (job.state === "failed") {
            analysisBody.replaceChildren(el("div", { class: "error-box" }, job.error || "analysis failed"));
            this.currentJobId = null;
          } else if (job.result) {
            analysisBody.replaceChildren(renderAnalysisResult(job));
            this.currentJobId = null;
          }
        },
      };

      function renderAnalysisResult(job) {
        const r = job.result;
        // Browsing starts where the analysis started, so the messages shown
        // line up with the aggregates that led here.
        const browseSpec = {
          group: job.spec.group,
          topic: job.spec.topic,
          partition: job.spec.partition,
          startOffset: job.spec.start_offset,
        };
        const browseKey = (text, filters) =>
          el("span", {
            class: "key",
            title: `${text} (click to browse matching messages)`,
            onclick: () => messageBrowser.open(browseSpec, filters),
          }, text);
        const chips = el(
          "div",
          { class: "row" },
          el("span", { class: "pill accent" }, `${fmtInt(r.messages_analyzed)} messages`),
          el("span", { class: "pill muted" }, `offsets ${fmtInt(job.spec.start_offset)} → ${fmtInt(r.next_offset)}`),
          el("span", { class: "pill muted" }, `${r.duration_ms} ms`),
          el("span", { class: "pill muted" }, fmtBytes(r.sizes.total_bytes)),
          r.truncated_reason ? el("span", { class: "pill warn" }, `truncated: ${r.truncated_reason}`) : null,
          r.flags.historical_migration ? el("span", { class: "pill warn" }, `historical: ${fmtInt(r.flags.historical_migration)}`) : null,
          r.flags.force_disable_person_processing ? el("span", { class: "pill muted" }, `no-person: ${fmtInt(r.flags.force_disable_person_processing)}`) : null,
          r.flags.missing_headers ? el("span", { class: "pill bad" }, `missing headers: ${fmtInt(r.flags.missing_headers)}`) : null,
          r.flags.missing_token ? el("span", { class: "pill bad" }, `missing token: ${fmtInt(r.flags.missing_token)}`) : null,
          r.token_overflow ? el("span", { class: "pill warn" }, `token overflow: ${fmtInt(r.token_overflow)}`) : null
        );

        const topList = (title, rows, makeFilter) => {
          const max = Math.max(1, ...rows.map((row) => row.count));
          return el("div", {},
            el("h3", {}, title),
            rows.length === 0 ? el("div", { class: "muted" }, "none") : null,
            rows.map((row) =>
              el("div", { class: "krow" },
                el("span", { class: "kbar", style: `width:${Math.max(3, (row.count / max) * 80)}px` }),
                browseKey(row.key, makeFilter(row.key)),
                el("span", { class: "cnt" }, `${fmtInt(row.count)} · ${row.pct.toFixed(1)}%`))
            )
          );
        };

        const maxTokenCount = Math.max(1, ...r.top_tokens.map((t) => t.count));
        const tokenBlocks = r.top_tokens.map((t) =>
          el("div", { class: "token-block" },
            el("div", { class: "token-head" },
              el("span", {
                class: t.team_id === null ? "pill muted" : "pill accent",
                style: "cursor: pointer",
                title: "Browse this team's messages",
                onclick: () => messageBrowser.open(browseSpec, { token: t.token }),
              }, t.team_id === null ? "team ?" : `team ${t.team_id}`),
              el("span", {
                class: "tok",
                title: `${t.token} (click to browse matching messages)`,
                onclick: () => messageBrowser.open(browseSpec, { token: t.token }),
              }, t.token),
              el("span", { class: "share" },
                el("span", { class: "bar", style: `width:${Math.max(3, (t.count / maxTokenCount) * 160)}px` }),
                el("span", { class: "mono muted" }, `${fmtInt(t.count)} msgs · ${t.pct.toFixed(1)}% · ${fmtBytes(t.total_bytes)}`))),
            el("div", { class: "token-cols" },
              topList("events", t.top_events, (key) => ({ token: t.token, event: key })),
              topList(
                t.distinct_id_overflow
                  ? `distinct_ids (${fmtInt(t.distinct_ids_tracked)} tracked, ${fmtInt(t.distinct_id_overflow)} overflow)`
                  : "distinct_ids",
                t.top_distinct_ids,
                (key) => ({ token: t.token, distinct_id: key })
              ))
          )
        );

        // Cumulative histogram buckets -> per-bucket counts for display.
        let previous = 0;
        const histRows = [];
        const maxBucket = Math.max(1, ...r.sizes.histogram.map((b, i, arr) => b.count - (i ? arr[i - 1].count : 0)));
        for (const bucket of r.sizes.histogram) {
          const count = bucket.count - previous;
          previous = bucket.count;
          histRows.push(
            el("div", { class: "hist-row" },
              el("span", { class: "lbl" }, `≤ ${fmtBytes(bucket.le)}`),
              el("span", { class: "hbar", style: `width:${Math.max(1, (count / maxBucket) * 160)}px` }),
              el("span", { class: "hcnt" }, fmtInt(count)))
          );
        }
        const sizes = el("div", { class: "cols" },
          el("div", { class: "col" },
            el("h3", {}, "message size"),
            el("div", { class: "muted mono", style: "margin-bottom:6px" },
              `min ${fmtBytes(r.sizes.min)} · p50 ${fmtBytes(r.sizes.p50)} · p90 ${fmtBytes(r.sizes.p90)} · p99 ${fmtBytes(r.sizes.p99)} · max ${fmtBytes(r.sizes.max)}`),
            histRows));

        return el("div", {}, chips, ...tokenBlocks, sizes);
      }

      // ---------- message browser ----------
      // Modal opened from analysis results: scans the partition for messages
      // matching header filters, 100 matches per request, with facets over
      // the loaded messages to refine further.
      const FACET_DIMS = [
        { key: "token", title: "tokens" },
        { key: "event", title: "events" },
        { key: "distinct_id", title: "distinct_ids" },
      ];
      const PAGE_LIMIT = 100;

      const messageBrowser = {
        overlay: null,
        state: null,
        epoch: 0,

        open(spec, filters) {
          this.close();
          this.state = {
            spec,
            filters: { ...filters },
            records: [],
            tokenTeams: {},
            scanned: 0,
            nextOffset: spec.startOffset,
            reachedEnd: false,
            loading: false,
            error: null,
          };

          this.listView = listView({
            placeholder: "Filter loaded messages…",
            pageSize: PAGE_LIMIT,
            matches: (record, q) =>
              ["token", "event", "distinct_id", "uuid", "session_id", "payload"].some((key) => (record[key] || "").toLowerCase().includes(q)) ||
              String(record.offset).includes(q),
            renderTable: (rows) => this.renderTable(rows),
            emptyText: "No matching messages loaded yet. Load more to scan further along the partition.",
          });

          this.ui = {
            chips: el("div", { class: "row", style: "padding: 0; flex: 1 1 auto" }),
            facets: el("div", { class: "facets" }),
            error: el("div", {}),
            status: el("span", { class: "muted mono status" }),
            loadBtn: el("button", { class: "small", onclick: () => this.fetchPage() }, "Load more"),
          };

          this.overlay = el("div", { class: "overlay", onclick: (e) => { if (e.target === this.overlay) this.close(); } },
            el("div", { class: "browser" },
              el("div", { class: "browser-head" },
                el("span", { class: "title" }, `Messages · ${spec.group} · ${spec.topic} p${spec.partition}`),
                this.ui.chips,
                el("button", { class: "small", onclick: () => this.close() }, "✕ close")),
              el("div", { class: "browser-body" },
                this.ui.facets,
                el("div", { class: "msgs" }, this.ui.error, this.listView.body)),
              el("div", { class: "row browser-foot" }, this.ui.status, this.ui.loadBtn)));
          document.body.append(this.overlay);
          this.escHandler = (e) => { if (e.key === "Escape") this.close(); };
          document.addEventListener("keydown", this.escHandler);

          this.render();
          this.fetchPage();
        },

        close() {
          this.epoch++;
          if (this.escHandler) document.removeEventListener("keydown", this.escHandler);
          if (this.overlay) this.overlay.remove();
          this.overlay = null;
          this.state = null;
          this.escHandler = null;
        },

        setFilter(key, value) {
          this.state.filters[key] = value;
          this.restart();
        },

        removeFilter(key) {
          delete this.state.filters[key];
          this.restart();
        },

        // Any filter change rescans from the original start offset so counts
        // and facets stay consistent with a single contiguous range.
        restart() {
          this.epoch++;
          const s = this.state;
          s.records = [];
          s.scanned = 0;
          s.nextOffset = s.spec.startOffset;
          s.reachedEnd = false;
          s.loading = false;
          s.error = null;
          this.listView.reset();
          this.render();
          this.fetchPage();
        },

        async fetchPage() {
          const s = this.state;
          if (!s || s.loading) return;
          const epoch = this.epoch;
          s.loading = true;
          s.error = null;
          this.render();
          const params = new URLSearchParams({
            group: s.spec.group,
            topic: s.spec.topic,
            partition: s.spec.partition,
            start_offset: s.nextOffset,
            limit: PAGE_LIMIT,
          });
          for (const dim of FACET_DIMS) {
            if (s.filters[dim.key] !== undefined) params.set(dim.key, s.filters[dim.key]);
          }
          try {
            const data = await fetchJSON(`api/messages?${params}`);
            if (epoch !== this.epoch) return;
            s.records = s.records.concat(data.messages);
            s.scanned += data.scanned;
            s.nextOffset = data.next_offset;
            s.reachedEnd = data.reached_end;
            Object.assign(s.tokenTeams, data.token_teams);
          } catch (e) {
            if (epoch !== this.epoch) return;
            s.error = String(e);
          }
          s.loading = false;
          this.render();
        },

        render() {
          const s = this.state;
          if (!s) return;

          const chips = FACET_DIMS.filter((dim) => s.filters[dim.key] !== undefined).map((dim) =>
            el("span", { class: "chip" },
              el("span", { class: "muted" }, `${dim.key}=`),
              el("span", { class: "val", title: `${s.filters[dim.key]} (click to copy)`, onclick: () => copy(s.filters[dim.key]) }, s.filters[dim.key]),
              el("button", { class: "x", title: "Remove this filter", onclick: () => this.removeFilter(dim.key) }, "×")));
          this.ui.chips.replaceChildren(
            chips.length ? el("span", { class: "muted", style: "font-size: 11px" }, "filters:") : el("span", { class: "muted", style: "font-size: 11px" }, "no filters, showing all messages"),
            ...chips);

          this.ui.error.replaceChildren(s.error ? el("div", { class: "error-box" }, s.error) : "");
          this.listView.setRows(s.records);
          this.renderFacets();

          const bits = [`${fmtInt(s.records.length)} matched`, `${fmtInt(s.scanned)} scanned`];
          if (s.loading) bits.push("scanning…");
          else if (s.reachedEnd) bits.push("caught up to the high watermark");
          else bits.push(`next offset ${fmtInt(s.nextOffset)}`);
          this.ui.status.textContent = bits.join(" · ");
          this.ui.loadBtn.disabled = s.loading;
          this.ui.loadBtn.textContent = s.loading ? "Loading…" : s.reachedEnd ? "Check for new messages" : "Load more";
        },

        teamLabel(token) {
          const team = this.state.tokenTeams[token];
          return team === null || team === undefined ? null : team;
        },

        renderFacets() {
          const s = this.state;
          const blocks = [];
          for (const dim of FACET_DIMS) {
            if (s.filters[dim.key] !== undefined) continue;
            const counts = new Map();
            for (const record of s.records) {
              const value = record[dim.key];
              if (value === undefined || value === null) continue;
              counts.set(value, (counts.get(value) || 0) + 1);
            }
            const entries = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 25);
            const max = Math.max(1, ...entries.map(([, count]) => count));
            blocks.push(el("div", {},
              el("h3", {}, dim.title),
              entries.length === 0 ? el("div", { class: "muted", style: "font-size: 11px" }, "none loaded") : null,
              entries.map(([value, count]) => {
                const team = dim.key === "token" ? this.teamLabel(value) : null;
                return el("div", { class: "krow facet-row", title: `${value} (click to filter)`, onclick: () => this.setFilter(dim.key, value) },
                  el("span", { class: "kbar", style: `width:${Math.max(3, (count / max) * 50)}px` }),
                  el("span", { class: "key" }, team === null ? value : `team ${team}`),
                  el("span", { class: "cnt" }, fmtInt(count)));
              })));
          }
          blocks.push(el("div", { class: "muted", style: "font-size: 11px; padding: 10px 0" },
            "Facets count the messages loaded so far. Click a value to filter the scan by it."));
          this.ui.facets.replaceChildren(...blocks);
        },

        renderTable(rows) {
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "offset"), el("th", {}, "time"), el("th", {}, "event"),
              el("th", {}, "distinct_id"), el("th", {}, "team"), el("th", {}, "size"), el("th", {}, "flags"))),
            el("tbody", {}, rows.map((record) => {
              const flags = [];
              if (record.missing_headers) flags.push(el("span", { class: "pill bad" }, "no headers"));
              if (record.historical_migration) flags.push(el("span", { class: "pill warn" }, "historical"));
              if (record.force_disable_person_processing) flags.push(el("span", { class: "pill muted" }, "no-person"));
              if (record.dlq_reason) flags.push(el("span", { class: "pill bad", title: record.dlq_reason }, "dlq"));
              const team = record.token ? this.teamLabel(record.token) : null;
              const row = el("tr", { class: "clickable", title: "Click to view the payload" },
                el("td", { class: "mono" }, fmtInt(record.offset)),
                el("td", { class: "muted mono" }, record.timestamp_ms ? new Date(record.timestamp_ms).toLocaleString() : "–"),
                el("td", { class: "mono" }, record.event ? copyable(record.event, "key") : el("span", { class: "muted" }, "–")),
                el("td", { class: "mono" }, record.distinct_id ? copyable(record.distinct_id, "key") : el("span", { class: "muted" }, "–")),
                el("td", {}, record.token
                  ? el("span", { class: team === null ? "pill muted" : "pill accent", title: `${record.token} (click to copy)`, style: "cursor: pointer", onclick: (e) => { e.stopPropagation(); copy(record.token); } }, team === null ? "team ?" : `team ${team}`)
                  : el("span", { class: "muted" }, "–")),
                el("td", { class: "muted mono" }, fmtBytes(record.payload_bytes)),
                el("td", {}, flags));
              row.addEventListener("click", () => this.toggleDetail(row, record));
              return row;
            })));
        },

        toggleDetail(row, record) {
          const next = row.nextElementSibling;
          if (next && next.classList.contains("msg-detail")) {
            next.remove();
            row.classList.remove("selected");
            return;
          }
          let payload = record.payload;
          try {
            payload = JSON.stringify(JSON.parse(record.payload), null, 2);
          } catch {
            // Not JSON; show the raw text.
          }
          row.classList.add("selected");
          row.after(el("tr", { class: "msg-detail" },
            el("td", { colspan: "7" },
              el("div", { class: "row", style: "padding: 8px 0 6px" },
                record.uuid ? el("span", { class: "muted mono" }, `uuid ${record.uuid}`) : null,
                record.session_id ? el("span", { class: "muted mono" }, `session ${record.session_id}`) : null,
                record.token ? el("span", { class: "muted mono" }, `token ${record.token}`) : null,
                record.payload_truncated
                  ? el("span", { class: "pill warn" }, `showing the first 64 KB of ${fmtBytes(record.payload_bytes)}`)
                  : null,
                el("button", { class: "small", style: "margin-left: auto", onclick: () => copy(record.payload) }, "copy payload")),
              el("pre", { class: "payload" }, payload || el("span", { class: "muted" }, "empty payload")))));
        },
      };

      // ---------- section: consumer debug ----------
      const debugSection = {
        id: "debug",
        title: "Consumer debug",
        description: "Ingestion consumer deployments. Expand one to list its pods; selecting a pod opens its full routing debug UI, backed by this service's per-pod proxy.",
        expanded: null,
        selectedPod: null,
        loadEpoch: 0,
        refreshSeq: 0,
        timers: [],
        // debug/load results per pod key, so re-renders show the last known
        // values instead of flashing back to placeholders while refetching.
        loads: new Map(),
        unmount() {
          this.loadEpoch++;
          this.timers.forEach(clearInterval);
          this.timers = [];
        },
        mount(root) {
          const refreshedAt = el("span", { class: "muted mono" });
          const listBody = el("div", {}, el("div", { class: "empty" }, "Loading deployments…"));
          const viewer = el("div", {});
          this.ui = { listBody, viewer, refreshedAt };
          root.append(
            el("div", { class: "row", style: "padding: 0 0 10px; justify-content: flex-end" },
              refreshedAt,
              el("button", { class: "small", onclick: () => this.refreshPods() }, "Refresh")),
            listBody,
            viewer
          );
          this.refreshPods();
          // Keep the expanded deployment's live columns current; /debug/load is
          // built to be polled cheaply. Cells repaint in place, so no flicker.
          this.timers.push(setInterval(() => {
            const group = (this.groups || []).find((g) => g.ns === this.expanded);
            if (group) this.fetchLoads(group);
          }, 5000));
        },

        async refreshPods() {
          const { listBody, refreshedAt } = this.ui;
          // Drop out-of-order responses: an older request resolving after a
          // newer one must not roll the deployment list back to stale state.
          const seq = ++this.refreshSeq;
          try {
            const data = await fetchJSON("api/pods");
            if (seq !== this.refreshSeq) return;
            refreshedAt.textContent = `as of ${new Date().toLocaleTimeString()}`;
            // One group per namespace: each ingestion lane deploys into its own.
            const byNamespace = new Map();
            for (const pod of data.pods) {
              const ns = pod.namespace || "–";
              if (!byNamespace.has(ns)) byNamespace.set(ns, []);
              byNamespace.get(ns).push(pod);
            }
            this.groups = [...byNamespace.entries()].map(([ns, pods]) => ({
              ns,
              pods,
              ready: pods.filter((p) => p.ready).length,
              restarts: pods.reduce((sum, p) => sum + (p.restarts || 0), 0),
              newestStart: pods.reduce((max, p) => (p.started_at && (!max || p.started_at > max) ? p.started_at : max), null),
            }));
            // A single deployment leaves nothing to choose between: open it.
            if (this.groups.length === 1) this.expanded = this.groups[0].ns;
            this.render();
          } catch (e) {
            if (seq !== this.refreshSeq) return;
            listBody.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
        },

        toggle(ns) {
          this.expanded = this.expanded === ns ? null : ns;
          this.render();
        },

        render() {
          const { listBody } = this.ui;
          this.loadEpoch++;
          if (!this.groups.length) {
            listBody.replaceChildren(el("div", { class: "empty" }, "No matching pods found."));
            return;
          }
          this.liveCells = new Map();
          listBody.replaceChildren(...this.groups.map((group) => this.renderGroup(group)));
          const expandedGroup = this.groups.find((group) => group.ns === this.expanded);
          if (expandedGroup) this.fetchLoads(expandedGroup);
        },

        renderGroup(group) {
          const expanded = group.ns === this.expanded;
          const total = group.pods.length;
          return el("div", { class: "panel" },
            el("h2", { class: "dep-head", onclick: () => this.toggle(group.ns) },
              el("span", { class: "row", style: "padding: 0; flex-wrap: nowrap" },
                el("span", { class: "chev" }, expanded ? "▾" : "▸"),
                el("span", { class: "ns" }, group.ns)),
              el("span", { class: "row", style: "padding: 0" },
                group.ready === total
                  ? el("span", { class: "pill good" }, `${fmtInt(total)} pod${total === 1 ? "" : "s"} ready`)
                  : el("span", { class: "pill warn" }, `${fmtInt(group.ready)}/${fmtInt(total)} pods ready`),
                group.restarts > 0
                  ? el("span", { class: "pill warn" }, `${fmtInt(group.restarts)} restart${group.restarts === 1 ? "" : "s"}`)
                  : el("span", { class: "pill muted" }, "no restarts"),
                group.newestStart ? el("span", { class: "muted mono dep-meta" }, `newest pod ${fmtAgo(group.newestStart)}`) : null)),
            expanded ? this.renderPodsTable(group) : null
          );
        },

        renderPodsTable(group) {
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "pod"), el("th", {}, "ip"), el("th", {}, "phase"), el("th", {}, "restarts"), el("th", {}, "started"),
              el("th", {}, "peer"), el("th", {}, "workers"), el("th", {}, "in flight"), el("th", {}, "pending"))),
            el("tbody", {}, group.pods.map((pod) => {
              const key = `${pod.namespace}/${pod.name}`;
              const live = {
                peer: el("td", { class: "mono muted" }, "…"),
                workers: el("td", { class: "mono muted" }, "…"),
                inFlight: el("td", { class: "mono muted" }, "…"),
                pending: el("td", { class: "mono muted" }, "…"),
              };
              this.liveCells.set(key, live);
              if (this.loads.has(key)) this.paintLoad(key);
              const row = el("tr", { class: `clickable ${key === this.selectedPod ? "selected" : ""}` },
                el("td", { class: "mono" }, pod.name),
                el("td", { class: "mono" }, pod.ip || "–"),
                el("td", {}, el("span", { class: `pill ${pod.ready ? "good" : "warn"}` }, pod.phase || "?")),
                el("td", { class: "mono" }, String(pod.restarts)),
                el("td", { class: "muted mono" }, pod.started_at ? `${new Date(pod.started_at).toLocaleString()} (${fmtAgo(pod.started_at)})` : "–"),
                live.peer, live.workers, live.inFlight, live.pending);
              row.addEventListener("click", () => this.selectPod(pod, row));
              return row;
            }))
          );
        },

        // The live columns cost one debug/load call per pod, so only the
        // expanded deployment is polled; collapsed ones cost nothing.
        fetchLoads(group) {
          const epoch = this.loadEpoch;
          for (const pod of group.pods) {
            const key = `${pod.namespace}/${pod.name}`;
            fetchJSON(`pods/${encodeURIComponent(pod.namespace)}/${encodeURIComponent(pod.name)}/debug/load`)
              .then((load) => {
                if (epoch !== this.loadEpoch) return;
                this.loads.set(key, { ok: true, load });
                this.paintLoad(key);
              })
              .catch(() => {
                if (epoch !== this.loadEpoch) return;
                this.loads.set(key, { ok: false });
                this.paintLoad(key);
              });
          }
        },

        paintLoad(key) {
          const cells = this.liveCells.get(key);
          const result = this.loads.get(key);
          if (!cells || !result) return;
          if (!result.ok) {
            cells.peer.replaceChildren(el("span", { class: "pill bad" }, "unreachable"));
            for (const cell of [cells.workers, cells.inFlight, cells.pending]) cell.replaceChildren("–");
            return;
          }
          const { load } = result;
          const set = (cell, ...children) => {
            cell.classList.remove("muted");
            cell.replaceChildren(...children);
          };
          set(cells.peer, load.peer_index != null && load.peer_count ? `${load.peer_index + 1}/${load.peer_count}` : "–");
          const routable = load.workers.filter((w) => !w.draining && (w.state === "healthy" || w.state === "degraded")).length;
          set(cells.workers, routable === load.workers.length
            ? `${routable}/${load.workers.length}`
            : el("span", { class: "pill warn" }, `${routable}/${load.workers.length}`));
          // A consumer pod from before the batcher rename still answers with
          // `dispatcher`; read whichever key the pod sends during a rollout.
          const batcher = load.batcher || load.dispatcher || {};
          set(cells.inFlight, fmtInt(batcher.total_in_flight ?? 0));
          const pending = batcher.pending_messages ?? 0;
          set(cells.pending, pending > 0 ? el("span", { class: "pill warn" }, fmtInt(pending)) : "0");
        },

        selectPod(pod, row) {
          // Pods are keyed namespace + name: identical names across lanes must
          // not both highlight. Selection repaints in place; a full re-render
          // would refetch every debug/load for one row's highlight.
          this.selectedPod = `${pod.namespace}/${pod.name}`;
          for (const selected of this.ui.listBody.querySelectorAll("tr.selected")) selected.classList.remove("selected");
          row.classList.add("selected");
          const url = `pods/${encodeURIComponent(pod.namespace)}/${encodeURIComponent(pod.name)}/`;
          this.ui.viewer.replaceChildren(
            el("div", { class: "panel" },
              el("h2", {}, el("span", {}, "Debug ", el("span", { class: "ns" }, pod.name)),
                el("a", { href: url, target: "_blank", style: "color: var(--accent); font-size: 11px; text-transform: none; letter-spacing: 0" }, "open in new tab ↗")),
              el("iframe", { class: "debug", src: url, onload: (e) => this.autosize(e.target) }))
          );
        },

        // Grow the iframe to fit the embedded debug page (same-origin via our
        // proxy) so the outer page scrolls instead of nesting a scrollbar.
        autosize(frame) {
          const doc = frame.contentDocument;
          if (!doc || !doc.body) return;
          // Measure the body, not documentElement: the latter is floored at the
          // iframe's own height, which would let the frame grow but never shrink.
          const resize = () => {
            frame.style.height = `${Math.max(480, doc.body.scrollHeight)}px`;
          };
          // Disconnect once the frame is replaced so switching pods doesn't
          // accumulate observers retaining detached iframe documents.
          const observer = new ResizeObserver(() => {
            if (!frame.isConnected) {
              observer.disconnect();
              return;
            }
            resize();
          });
          resize();
          observer.observe(doc.body);
        },
      };

      // ---------- section: etcd explorer ----------
      // Generic prefix-bounded key browser with edit/create/delete. Raw
      // writes to coordination state are protocol-dangerous, so every write
      // confirms first, with an extra warning for assignment keys.
      const etcdSection = {
        id: "etcd",
        title: "Etcd explorer",
        description: "Browse keys under a prefix, inspect values and lease state, and edit, create, or delete keys. Writes bypass every coordination protocol: use with care.",
        prefix: "/personhog/",
        rows: [],
        nextFromKey: null,
        totalCount: null,
        selectedKey: null,
        mount(root) {
          this.rows = [];
          this.nextFromKey = null;
          this.selectedKey = null;
          this.query = "";
          this.openState = new Map();

          const search = el("input", {
            type: "search", class: "search", placeholder: "Filter loaded keys…",
            oninput: () => { this.query = search.value.trim().toLowerCase(); this.renderTree(); },
          });
          this.ui = {
            prefixInput: el("input", {
              type: "text", class: "search", value: this.prefix, spellcheck: "false",
              onkeydown: (e) => { if (e.key === "Enter") this.reload(); },
            }),
            search,
            matchCount: el("span", { class: "muted mono count" }),
            status: el("span", { class: "muted mono" }),
            loadMoreBtn: el("button", { class: "small", onclick: () => this.fetchPage() }, "Load more"),
            error: el("div", {}),
            treeBody: el("div", { style: "padding: 4px 0 8px" }),
            detail: el("div", {}),
          };

          root.append(
            el("div", { class: "panel" },
              el("h2", {}, "Keys", this.ui.status),
              el("div", { class: "row toolbar" },
                el("span", { class: "muted" }, "prefix"),
                this.ui.prefixInput,
                el("button", { class: "small", onclick: () => this.reload() }, "Load"),
                el("button", { class: "small", onclick: () => this.openEditor(null) }, "New key"),
                this.ui.loadMoreBtn),
              el("div", { class: "row toolbar" }, this.ui.search, this.ui.matchCount),
              this.ui.error,
              this.ui.treeBody),
            this.ui.detail
          );
          this.reload();
        },

        reload() {
          this.prefix = this.ui.prefixInput.value.trim();
          this.rows = [];
          this.nextFromKey = null;
          this.totalCount = null;
          this.openState = new Map();
          this.renderStatus();
          this.fetchPage();
        },

        async fetchPage() {
          if (!this.prefix) return;
          const params = new URLSearchParams({ prefix: this.prefix });
          if (this.nextFromKey) params.set("from_key", this.nextFromKey);
          this.ui.loadMoreBtn.disabled = true;
          try {
            const data = await fetchJSON(`api/etcd/keys?${params}`);
            this.rows = this.rows.concat(data.keys);
            this.nextFromKey = data.next_from_key;
            this.totalCount = data.count;
            this.ui.error.replaceChildren();
            this.renderTree();
          } catch (e) {
            this.ui.error.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
          this.renderStatus();
        },

        renderStatus() {
          this.ui.status.textContent = this.totalCount === null
            ? ""
            : `${fmtInt(this.rows.length)} of ${fmtInt(this.totalCount)} keys loaded`;
          this.ui.loadMoreBtn.disabled = !this.nextFromKey;
          this.ui.loadMoreBtn.style.display = this.nextFromKey ? "" : "none";
        },

        // The loaded keys form a tree on `/`. A node can be both a value
        // and a directory (etcd allows `/a` and `/a/b` to coexist): its
        // chevron toggles the children, clicking the row opens the value.
        buildTree(rows) {
          const root = { name: "", path: "", children: new Map(), leaf: null, count: 0 };
          for (const row of rows) {
            const parts = row.key.split("/").filter((s) => s !== "");
            let node = root;
            let path = "";
            for (let i = 0; i < parts.length; i++) {
              path += "/" + parts[i];
              if (!node.children.has(parts[i])) {
                node.children.set(parts[i], { name: parts[i], path, children: new Map(), leaf: null, count: 0 });
              }
              node = node.children.get(parts[i]);
              node.count++;
              if (i === parts.length - 1) node.leaf = row;
            }
          }
          return root;
        },

        isOpen(node, depth) {
          if (this.query) return true;
          if (this.openState.has(node.path)) return this.openState.get(node.path);
          // Top-level and single-child chains open by default, so the
          // common deep prefix does not cost a click per segment.
          return depth === 0 || node.children.size === 1;
        },

        toggleDir(node, depth) {
          this.openState.set(node.path, !this.isOpen(node, depth));
          this.renderTree();
        },

        renderTree() {
          const q = this.query;
          const rows = q ? this.rows.filter((row) => row.key.toLowerCase().includes(q)) : this.rows;
          this.ui.matchCount.textContent = q ? `${fmtInt(rows.length)} of ${fmtInt(this.rows.length)}` : fmtInt(this.rows.length);
          if (!rows.length) {
            this.ui.treeBody.replaceChildren(el("div", { class: "empty" }, q ? "No matches." : "No keys loaded. Set a prefix and load."));
            return;
          }
          const byName = (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true });
          const lines = [];
          const renderNode = (node, depth) => {
            const isDir = node.children.size > 0;
            const open = isDir && this.isOpen(node, depth);
            const meta = node.leaf
              ? el("span", { class: "meta" },
                  node.leaf.lease && node.leaf.lease !== 0 ? el("span", { class: "pill accent", title: `lease ${node.leaf.lease}` }, "leased") : null,
                  el("span", {}, `v${fmtInt(node.leaf.version)}`),
                  el("span", {}, fmtBytes(node.leaf.value_bytes)))
              : el("span", { class: "meta" }, `${fmtInt(node.count)} key${node.count === 1 ? "" : "s"}`);
            lines.push(el("div", {
              class: `tree-row ${node.leaf && node.leaf.key === this.selectedKey ? "selected" : ""}`,
              style: `padding-left: ${14 + depth * 16}px`,
              title: node.leaf ? node.leaf.key : node.path,
              onclick: () => node.leaf ? this.openKey(node.leaf.key) : this.toggleDir(node, depth),
            },
              isDir
                ? el("span", { class: "chev", onclick: (e) => { e.stopPropagation(); this.toggleDir(node, depth); } }, open ? "▾" : "▸")
                : el("span", { class: "chev" }),
              el("span", { class: "mono" }, isDir && !node.leaf ? `${node.name}/` : node.name),
              meta));
            if (open) {
              for (const child of [...node.children.values()].sort(byName)) renderNode(child, depth + 1);
            }
          };
          const root = this.buildTree(rows);
          for (const node of [...root.children.values()].sort(byName)) renderNode(node, 0);
          this.ui.treeBody.replaceChildren(...lines);
        },

        async openKey(key) {
          this.selectedKey = key;
          this.renderTree();
          try {
            const detail = await fetchJSON(`api/etcd/key?key=${encodeURIComponent(key)}`);
            this.renderDetail(detail);
          } catch (e) {
            this.ui.detail.replaceChildren(el("div", { class: "panel" }, el("div", { class: "error-box" }, String(e))));
          }
        },

        confirmWrite(action, key) {
          let message = `${action} etcd key:\n\n${key}\n\nThis bypasses every coordination protocol.`;
          if (key.includes("/assignments/")) {
            message += "\n\n⚠️ This is a personhog ASSIGNMENT key. Writing it directly is forbidden by the protocol: routers only observe ownership through handoff Complete events, so a raw write leaves an unfenced old owner serving beside the new one. A force-reassignment must create a handoff record instead.";
          }
          return window.confirm(message);
        },

        renderDetail(detail) {
          let pretty = detail.value;
          try { pretty = JSON.stringify(JSON.parse(detail.value), null, 2); } catch { /* not JSON */ }
          const meta = el("div", { class: "row" },
            el("span", { class: "pill muted" }, `version ${fmtInt(detail.version)}`),
            el("span", { class: "pill muted" }, `mod rev ${fmtInt(detail.mod_revision)}`),
            el("span", { class: "pill muted" }, `create rev ${fmtInt(detail.create_revision)}`),
            detail.lease !== 0
              ? el("span", { class: "pill accent", title: `lease ${detail.lease}` },
                  detail.lease_ttl_secs === null ? "leased (ttl unknown)" : `lease ${detail.lease_ttl_secs}s / ${detail.lease_granted_ttl_secs}s`)
              : null,
            el("span", { class: "muted mono" }, fmtBytes(detail.value_bytes)),
            el("span", { class: "row", style: "padding: 0; margin-left: auto" },
              el("button", { class: "small", disabled: !detail.value_is_utf8, title: detail.value_is_utf8 ? "" : "Value is not UTF-8; editing would corrupt it", onclick: () => this.openEditor(detail) }, "Edit"),
              el("button", { class: "small", onclick: () => this.deleteKey(detail.key) }, "Delete")));
          this.ui.detail.replaceChildren(
            el("div", { class: "panel" },
              el("h2", {}, el("span", { class: "ns" }, detail.key)),
              meta,
              el("div", { style: "padding: 0 14px 12px" }, el("pre", { class: "payload" }, pretty)))
          );
        },

        // `detail === null` creates a new key; otherwise edits in place.
        openEditor(detail) {
          const keyInput = el("input", {
            type: "text", class: "search", style: "width: 100%; box-sizing: border-box",
            value: detail ? detail.key : this.prefix, spellcheck: "false",
            readonly: !!detail,
          });
          const valueInput = el("textarea", { class: "kv-value", spellcheck: "false" });
          valueInput.value = detail ? detail.value : "";
          const error = el("div", {});
          const save = async () => {
            const key = keyInput.value.trim();
            if (!key) return;
            if (detail && detail.lease !== 0 &&
                !window.confirm(`${key}\n\nThis key is lease-backed; writing it detaches it from its lease, so it will no longer expire with its owner. Continue?`)) return;
            if (!this.confirmWrite("Write", key)) return;
            try {
              await fetchJSON("api/etcd/key", {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ key, value: valueInput.value }),
              });
              this.reload();
              this.openKey(key);
            } catch (e) {
              error.replaceChildren(el("div", { class: "error-box" }, String(e)));
            }
          };
          this.ui.detail.replaceChildren(
            el("div", { class: "panel" },
              el("h2", {}, detail ? `Edit ${detail.key}` : "New key"),
              el("div", { style: "padding: 10px 14px", class: "mono" },
                detail ? null : el("div", { style: "margin-bottom: 8px" }, keyInput),
                valueInput),
              error,
              el("div", { class: "row" },
                el("button", { onclick: save }, "Save"),
                el("button", { class: "small", onclick: () => detail ? this.renderDetail(detail) : this.ui.detail.replaceChildren() }, "Cancel")))
          );
        },

        async deleteKey(key) {
          if (!this.confirmWrite("Delete", key)) return;
          try {
            await fetchJSON(`api/etcd/key?key=${encodeURIComponent(key)}`, { method: "DELETE" });
            this.selectedKey = null;
            this.ui.detail.replaceChildren();
            this.reload();
          } catch (e) {
            this.ui.detail.replaceChildren(el("div", { class: "panel" }, el("div", { class: "error-box" }, String(e))));
          }
        },
      };

      // ---------- section: personhog topology ----------
      // Protocol-aware view over the personhog coordination prefix: pods,
      // routers, assignments, and in-flight handoffs, with server-derived
      // issues (stuck handoffs, dead owners, missing acks) computed by the
      // same predicates the coordinator runs.
      const personhogSection = {
        id: "personhog",
        title: "Personhog topology",
        description: "Live view of personhog's etcd coordination state: coordinator, pods, routers, partition ownership, and in-flight handoffs, with derived issues. Refreshes every 5 seconds.",
        timers: [],
        refreshSeq: 0,
        unmount() {
          this.timers.forEach(clearInterval);
          this.timers = [];
        },
        mount(root) {
          this.ui = {
            summary: el("div", { class: "row", style: "padding: 0 0 10px" }),
            changelogStatus: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            // Rebuilt only when the action it offers changes, so a refresh keeps what is typed.
            changelogForm: el("div"),
            changelogFormKey: null,
            changelogError: el("div", { style: "padding: 0 14px" }),
            changelogDetail: el("div"),
            issuesBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            partitionsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            podsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            routersBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
          };
          this.partitionsView = listView({
            placeholder: "Filter by partition, owner, or phase…",
            pageSize: 100,
            matches: (p, q) =>
              String(p.partition).includes(q) ||
              (p.owner || "").toLowerCase().includes(q) ||
              (p.handoff ? p.handoff.phase.toLowerCase().includes(q) : false),
            renderTable: (rows) => this.renderPartitionsTable(rows),
            emptyText: "No partitions.",
          });
          root.append(
            this.ui.summary,
            el("div", { class: "panel" }, el("h2", {}, "Changelog"),
              this.ui.changelogStatus, this.ui.changelogForm, this.ui.changelogError, this.ui.changelogDetail),
            el("div", { class: "panel" }, el("h2", {}, "Issues"), this.ui.issuesBody),
            el("div", { class: "panel" }, el("h2", {}, "Partitions"), this.ui.partitionsBody),
            el("div", { class: "panel" }, el("h2", {}, "Pods"), this.ui.podsBody),
            el("div", { class: "panel" }, el("h2", {}, "Routers"), this.ui.routersBody)
          );
          this.refresh();
          this.timers.push(setInterval(() => this.refresh(), 5000));
        },

        async refresh() {
          const seq = ++this.refreshSeq;
          let data;
          try {
            data = await fetchJSON("api/personhog/topology");
          } catch (e) {
            if (seq !== this.refreshSeq) return;
            this.ui.summary.replaceChildren(el("div", { class: "error-box", style: "flex: 1 1 100%" }, String(e)));
            return;
          }
          if (seq !== this.refreshSeq) return;
          this.render(data);
          // The lag scan talks to Kafka, so it never blocks the topology render.
          this.refreshChangelog();
        },

        // One changelog view in flight at a time, always rendered: a scan slower
        // than the refresh interval would otherwise be discarded every time.
        refreshChangelog() {
          if (this.changelogInFlight) {
            this.changelogPending = true;
            return;
          }
          this.changelogInFlight = true;
          fetchJSON("api/personhog/changelog")
            .then(
              (view) => this.renderChangelog(view),
              (e) => this.ui.changelogStatus.replaceChildren(el("div", { class: "error-box" }, String(e))))
            .finally(() => {
              this.changelogInFlight = false;
              if (this.changelogPending) {
                this.changelogPending = false;
                this.refreshChangelog();
              }
            });
        },

        renderChangelog(view) {
          const formKey = this.changelogFormKeyOf(view);
          if (this.ui.changelogFormKey !== formKey) {
            this.ui.changelogFormKey = formKey;
            this.ui.changelogError.replaceChildren();
            this.ui.changelogForm.replaceChildren(...(view.config
              ? [this.migrationForm(view), this.retireGroupForm()]
              : [this.seedForm(), this.restoreForm()]));
          }
          if (!view.config) {
            this.ui.changelogStatus.replaceChildren(
              el("div", { class: "muted", style: "padding: 6px 14px 8px" }, "Not seeded. Every personhog service waits at startup until the changelog is seeded."));
            this.ui.changelogDetail.replaceChildren();
            return;
          }
          const c = view.config;
          this.ui.changelogStatus.replaceChildren(
            el("div", { class: "row", style: "padding: 6px 14px" },
              el("span", { class: "pill accent mono" }, c.topic),
              c.cluster
                ? el("span", { class: "pill muted mono" }, c.cluster.name)
                : el("span", { class: "pill warn", title: "No CHANGELOG_KAFKA_CLUSTERS entry matched PERSONHOG_KAFKA_HOSTS when the control plane started, so the changelog cannot move to another cluster." }, "cluster not recorded"),
              el("span", { class: "pill muted" }, `${fmtInt(c.partitions)} partitions`),
              el("span", { class: "pill muted" }, `epoch ${fmtInt(c.epoch)}`)));
          this.ui.changelogDetail.replaceChildren(
            this.migrationDetail(view),
            !view.writer
              ? el("div", { class: "empty" }, "No writer group.")
              : el("table", {},
                  el("thead", {}, el("tr", {},
                    el("th", {}, "consumer group"), el("th", {}, "partitions"), el("th", {}, "lagging"), el("th", {}, "total lag"),
                    el("th", { title: "A grow's restart replays about this many records per partition; a shrink by k replays about k partitions' worth. Larger replays lengthen the pause." }, "worst partition"))),
                  el("tbody", {}, [view.writer, ...view.retire_groups].map((g, i) =>
                    el("tr", {},
                      el("td", { class: "mono" }, g.group, i === 0 ? null : this.removeRetireGroupButton(g.group)),
                      el("td", { class: "mono" }, g.error ? el("span", { class: "pill bad", title: g.error }, "scan failed") : fmtInt(g.partitions)),
                      el("td", { class: "mono" }, g.error ? "–" : fmtInt(g.lagging_partitions)),
                      el("td", { class: "mono" }, g.error ? "–" : el("span", { class: `pill ${g.total_lag === 0 ? "good" : "warn"}` }, fmtInt(g.total_lag))),
                      el("td", { class: "mono" }, g.error ? "–" : fmtInt(g.max_partition_lag)))))));
        },

        changelogFormKeyOf(view) {
          if (!view.config) return "unseeded";
          const groups = (view.config.retire_groups || []).join(",");
          if (view.migration) return `migration:${view.migration.id}:${view.migration.phase}:${groups}`;
          if (view.request) return `request:${view.request.id}:${groups}`;
          return `idle:${groups}`;
        },

        removeRetireGroupButton(group) {
          const button = el("button", { style: "margin-left: 8px" }, "Remove");
          button.onclick = () => this.postChangelogAction("api/personhog/changelog/retire-groups", {
            method: "DELETE",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ group }),
          }, `Stop retire waiting on ${group}?\n\nOnly do this for a consumer that no longer runs. Retire stops waiting for it, so a generation it has not read to the end can retire and be deleted. If it still runs, it refuses to start on its next restart.`);
          return button;
        },

        retireGroupForm() {
          const groupInput = el("input", { type: "text", placeholder: "consumer group, e.g. personhog-changelog-relay", style: "width: 360px" });
          const button = el("button", {}, "Add retire group");
          button.onclick = () => {
            const group = groupInput.value.trim();
            if (!group) return;
            this.postChangelogAction("api/personhog/changelog/retire-groups", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ group }),
            }, `Add ${group} as a retire group?\n\nRetire then also waits for this group to read each generation to the end. A changelog consumer such as the relay refuses to start until its group is listed. Remove it from its row once that consumer no longer runs.`);
          };
          return el("div", { class: "row", style: "padding: 6px 14px; border-top: 1px solid var(--border)" },
            el("span", { class: "muted" }, "Other consumers retire waits on:"), groupInput, button);
        },

        async postChangelogAction(path, options, confirmText) {
          if (!window.confirm(confirmText)) return;
          try {
            await fetchJSON(path, options);
            this.ui.changelogError.replaceChildren();
            this.refresh();
          } catch (e) {
            this.ui.changelogError.replaceChildren(el("div", { class: "error-box" }, String(e)));
          }
        },

        seedForm() {
          const topicInput = el("input", { type: "text", placeholder: "changelog topic, e.g. personhog_updates_64", style: "width: 360px" });
          const groupInput = el("input", { type: "text", placeholder: "writer consumer group, e.g. personhog-writer", style: "width: 280px" });
          const error = el("div");
          const button = el("button", {}, "Seed config/changelog");
          button.onclick = async () => {
            const topic = topicInput.value.trim();
            const writer_group = groupInput.value.trim();
            if (!topic || !writer_group) {
              error.replaceChildren(el("div", { class: "error-box" }, "Enter the topic and the writer's consumer group."));
              return;
            }
            if (!window.confirm(`Seed config/changelog with topic ${topic}, with writer group ${writer_group}?\n\nThe partition count is read from the topic's metadata. Every personhog participant adopts this object; only a migration can move it afterward.`)) return;
            button.disabled = true;
            try {
              await fetchJSON("api/personhog/changelog/seed", {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ topic, writer_group }),
              });
              this.refresh();
            } catch (e) {
              error.replaceChildren(el("div", { class: "error-box" }, String(e)));
            } finally {
              button.disabled = false;
            }
          };
          return el("div", { style: "padding: 0 14px 6px" },
            el("div", { class: "row" }, topicInput, groupInput, button),
            error);
        },

        restoreForm() {
          const versions = el("select", { disabled: true }, el("option", {}, "loading backups…"));
          const error = el("div");
          const button = el("button", { disabled: true }, "Restore from backup");
          fetchJSON("api/personhog/changelog/backups")
            .then((list) => {
              if (!list.length) {
                versions.replaceChildren(el("option", {}, "no backups yet"));
                return;
              }
              versions.replaceChildren(...list.map((v) => el("option", { value: v.version_id },
                `${v.is_latest ? "current" : "earlier"}: ${v.last_modified || v.version_id}`)));
              versions.disabled = false;
              button.disabled = false;
            })
            .catch((e) => {
              versions.replaceChildren(el("option", {}, "backups unavailable"));
              error.replaceChildren(el("div", { class: "muted" }, String(e)));
            });
          button.onclick = async () => {
            const version_id = versions.value;
            const label = versions.selectedOptions[0] ? versions.selectedOptions[0].textContent : version_id;
            if (!window.confirm(`Restore config/changelog from the backup ${label}?\n\nThe config is written exactly as it was backed up, epoch and draining generations included. Restore only works while etcd holds no config. Running services ignore a config with an older epoch than they adopted, so scale personhog to zero first when rebuilding etcd.`)) return;
            button.disabled = true;
            try {
              await fetchJSON("api/personhog/changelog/restore", {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ version_id }),
              });
              this.refresh();
            } catch (e) {
              error.replaceChildren(el("div", { class: "error-box" }, String(e)));
            } finally {
              button.disabled = false;
            }
          };
          return el("div", { style: "padding: 0 14px 6px" },
            el("div", { class: "row" }, versions, button),
            error);
        },

        migrationForm(view) {
          const m = view.migration;
          const r = view.request;
          const form = el("div", { class: "row", style: "padding: 6px 14px; border-top: 1px solid var(--border)" });
          if (m) {
            const cancellable = ["Freezing", "Draining"].includes(m.phase);
            const cancel = el("button", { disabled: !cancellable }, "Cancel migration");
            cancel.onclick = () => this.postChangelogAction("api/personhog/migrations/current", {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ id: m.id }),
            },
              `Cancel the migration to ${m.to.topic}? Held partitions resume on ${m.from.topic}.`);
            form.append(
              el("span", { class: "pill warn" }, `migrating: ${m.phase}`),
              el("span", { class: "mono" }, `${fmtTarget(m.from)} → ${fmtTarget(m.to)}`),
              cancel);
          } else if (r) {
            const withdraw = el("button", {}, "Stop migration");
            withdraw.onclick = () => this.postChangelogAction("api/personhog/migrations/current", {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ id: r.id }),
            },
              `Stop the migration to ${r.to.topic}? It has not started, so nothing is held; if it starts in the meantime, it is cancelled before the flip.`);
            form.append(
              el("span", { class: "pill muted" }, "requested: waiting to start"),
              el("span", { class: "mono" }, `${fmtTarget(r.from)} → ${fmtTarget(r.to)}`),
              withdraw);
          } else {
            const topicInput = el("input", { type: "text", placeholder: "target topic, e.g. personhog_updates_128", style: "width: 360px" });
            const live = view.config.cluster ? view.config.cluster.name : null;
            const choices = view.cross_cluster_migrations ? view.clusters : view.clusters.filter((name) => name === live);
            const clusterSelect = live && choices.length > 0
              ? el("select", { title: view.cross_cluster_migrations ? null : "Another cluster needs PERSONHOG_CROSS_CLUSTER_MIGRATIONS" },
                  choices.map((name) => el("option", { value: name, selected: name === live }, name)))
              : null;
            const start = el("button", {}, "Migrate changelog");
            start.onclick = () => {
              const topic = topicInput.value.trim();
              if (!topic) return;
              const cluster = clusterSelect ? clusterSelect.value : null;
              const moving = cluster && cluster !== live
                ? `\n\nThis moves the changelog from ${live} to ${cluster}. The old topic drains and retires on ${live}.`
                : "";
              this.postChangelogAction("api/personhog/migrations", {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify(cluster ? { topic, cluster } : { topic }),
              }, `Migrate the changelog to ${topic}${cluster ? ` on ${cluster}` : ""}?${moving}\n\nThe coordinator starts it once no partition is moving and every owner is ready, then every partition pauses briefly while the fleet restarts onto the new topic. The partition count is read from the topic's metadata.`);
            };
            form.append(...[topicInput, clusterSelect, start].filter(Boolean));
          }
          return form;
        },

        migrationDetail(view) {
          const m = view.migration;
          const r = view.request;
          const body = el("div", { style: "padding: 0 14px 6px" });
          if (m) {
            body.append(m.blocking.length === 0
              ? el("div", { class: "muted" }, "Nothing blocking.")
              : el("ul", { class: "mono", style: "margin: 4px 0" }, m.blocking.slice(0, 12).map((b) => el("li", {}, b))));
          } else if (r) {
            body.append(r.waiting.length === 0
              ? el("div", { class: "muted" }, "Starting once no partition is moving and every owner is ready.")
              : el("ul", { class: "mono", style: "margin: 4px 0" }, r.waiting.slice(0, 12).map((w) => el("li", {}, w))));
          }
          for (const g of view.draining) {
            const groups = [g.writer, ...g.retire_groups];
            const isDrained = (d) => !d.error && d.partitions > 0 && d.drained_partitions === d.partitions;
            const drained = groups.every(isDrained);
            const retire = el("button", { disabled: !drained }, `Retire ${g.topic}`);
            retire.onclick = () => this.postChangelogAction("api/personhog/changelog/retire", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ topic: g.topic }),
            }, `Retire ${g.topic} now?\n\nEvery gating group has read it to the end. The coordinator retires it on its own once each group reports the drain. Retiring now skips that wait. Delete the topic in Terraform afterwards.`);
            body.append(el("div", { class: "row", style: "margin-top: 6px" },
              el("span", { class: "pill muted mono" }, `${g.topic} (${fmtInt(g.partitions)}, epoch ${fmtInt(g.epoch)})${g.cluster ? ` on ${g.cluster}` : ""} draining`),
              groups.map((d) => el("span", { class: `pill ${d.error ? "bad" : isDrained(d) ? "good" : "warn"}`, title: d.error || "" },
                `${d.group}: ${fmtInt(d.drained_partitions)}/${fmtInt(d.partitions)}${d.reported ? " · reported" : ""}`)),
              retire));
          }
          if (view.history.length > 0) {
            body.append(el("table", {},
              el("thead", {}, el("tr", {}, el("th", {}, "migration"), el("th", {}, "from"), el("th", {}, "to"), el("th", {}, "outcome"))),
              el("tbody", {}, view.history.slice(0, 5).map((h) =>
                el("tr", {},
                  el("td", { class: "mono" }, h.id),
                  el("td", { class: "mono" }, fmtTarget(h.from)),
                  el("td", { class: "mono" }, fmtTarget(h.to)),
                  el("td", {},
                    el("span", { class: `pill ${h.phase === "Complete" ? "good" : "bad"}`, title: h.blocking.join("; ") }, h.phase),
                    h.cancel_reason ? el("span", { class: "muted mono", style: "margin-left: 8px" }, h.cancel_reason)
                      : h.phase !== "Complete" && h.blocking.length > 0 ? el("span", { class: "muted mono", style: "margin-left: 8px" }, h.blocking.join("; ")) : null,
                    h.phase === "Complete" && !view.draining.some((g) => g.topic === h.from.topic) ? el("span", { class: "muted", style: "margin-left: 8px" }, `${h.from.topic} is retired; delete it in Terraform`) : null))))));
          }
          return body;
        },

        render(data) {
          const readyPods = data.pods.filter((p) => p.status === "Ready").length;
          const errors = data.issues.filter((issue) => issue.severity === "error").length;
          const warnings = data.issues.filter((issue) => issue.severity === "warning").length;
          // replaceChildren stringifies nulls instead of skipping them like
          // el() does, so absent pills must be filtered out.
          this.ui.summary.replaceChildren(...[
            data.leader
              ? el("span", { class: "pill good", title: `lease ${data.leader.lease_id}${data.leader.lease_ttl_secs !== null ? ` · ttl ${data.leader.lease_ttl_secs}s` : ""}` }, `coordinator ${data.leader.holder}`)
              : el("span", { class: "pill bad" }, "no coordinator"),
            el("span", { class: "pill muted" },
              data.total_partitions === null ? "changelog not seeded" : `${fmtInt(data.total_partitions)} partitions`),
            el("span", { class: `pill ${readyPods === data.pods.length && readyPods > 0 ? "good" : "warn"}` },
              `${fmtInt(readyPods)}/${fmtInt(data.pods.length)} pods ready`),
            el("span", { class: "pill muted" }, `${fmtInt(data.routers.length)} router${data.routers.length === 1 ? "" : "s"}`),
            errors ? el("span", { class: "pill bad" }, `${fmtInt(errors)} error${errors === 1 ? "" : "s"}`) : null,
            warnings ? el("span", { class: "pill warn" }, `${fmtInt(warnings)} warning${warnings === 1 ? "" : "s"}`) : null,
            el("span", { class: "muted mono", style: "margin-left: auto" },
              `rev ${fmtInt(data.revision)} · as of ${new Date(data.fetched_at).toLocaleTimeString()}`),
          ].filter(Boolean));

          const pillFor = { error: "bad", warning: "warn", info: "muted" };
          this.ui.issuesBody.replaceChildren(
            data.issues.length === 0
              ? el("div", { class: "empty" }, "No issues detected.")
              : el("div", { style: "padding: 6px 0" }, data.issues.map((issue) =>
                  el("div", { class: "row", style: "padding: 4px 14px" },
                    el("span", { class: `pill ${pillFor[issue.severity] || "muted"}` }, issue.severity),
                    el("span", {}, issue.summary))))
          );

          this.partitionsView.setRows(data.partitions);
          this.ui.partitionsBody.replaceChildren(this.partitionsView.body);
          this.ui.podsBody.replaceChildren(this.renderPodsTable(data.pods));
          this.ui.routersBody.replaceChildren(this.renderRoutersTable(data.routers));
        },

        renderPartitionsTable(rows) {
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "partition"), el("th", {}, "owner"), el("th", {}, "address"),
              el("th", {}, "handoff"), el("th", {}, "waiting on"))),
            el("tbody", {}, rows.map((p) => {
              const h = p.handoff;
              const phasePill = h
                ? el("span", {
                    class: `pill ${h.past_deadline ? "bad" : h.phase === "Complete" ? "good" : "accent"}`,
                    title: `${h.old_owner ? `${h.old_owner} → ` : ""}${h.new_owner} · ${h.handoff_id}`,
                  }, `${h.phase}${h.phase_age_secs !== null ? ` ${h.phase_age_secs}s` : ""}${h.past_deadline ? " ⏰" : ""}`)
                : el("span", { class: "muted" }, "–");
              return el("tr", {},
                el("td", { class: "mono" }, String(p.partition)),
                el("td", { class: "mono" }, p.owner
                  ? el("span", {}, p.owner, " ", p.owner_registered === false ? el("span", { class: "pill bad" }, "gone") : null)
                  : el("span", { class: "pill warn" }, "unassigned")),
                el("td", { class: "muted mono" }, p.advertise_address || "–"),
                el("td", {}, phasePill),
                el("td", { class: "muted" }, h && h.waiting_on ? h.waiting_on : "–"));
            }))
          );
        },

        renderPodsTable(pods) {
          if (!pods.length) return el("div", { class: "empty" }, "No pods registered.");
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "pod"), el("th", {}, "status"), el("th", {}, "address"),
              el("th", {}, "lease ttl"), el("th", {}, "heartbeat"), el("th", {}, "partitions"))),
            el("tbody", {}, pods.map((pod) =>
              el("tr", {},
                el("td", { class: "mono" }, pod.pod_name),
                el("td", {}, el("span", { class: `pill ${pod.status === "Ready" ? "good" : "warn"}` }, pod.status)),
                el("td", { class: "muted mono" }, pod.advertise_address || "–"),
                el("td", { class: "mono" }, pod.lease_ttl_secs === null ? "–" : `${pod.lease_ttl_secs}s`),
                el("td", { class: "muted mono" }, pod.last_heartbeat ? fmtAgo(pod.last_heartbeat * 1000) : "–"),
                el("td", { class: "mono", title: pod.partitions.join(", ") },
                  `${fmtInt(pod.partitions.length)}`))
            ))
          );
        },

        renderRoutersTable(routers) {
          if (!routers.length) return el("div", { class: "empty" }, "No routers registered.");
          return el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "router"), el("th", {}, "lease ttl"), el("th", {}, "heartbeat"))),
            el("tbody", {}, routers.map((router) =>
              el("tr", {},
                el("td", { class: "mono" }, router.router_name),
                el("td", { class: "mono" }, router.lease_ttl_secs === null ? "–" : `${router.lease_ttl_secs}s`),
                el("td", { class: "muted mono" }, router.last_heartbeat ? fmtAgo(router.last_heartbeat * 1000) : "–"))
            ))
          );
        },
      };

      // ---------- section: personhog parity ----------
      const paritySection = {
        id: "parity",
        title: "Personhog parity",
        description: "Recent disagreements between the Node and personhog CDC feeds, from the parity monitor's sample. Newest first. Refreshes every 30 seconds.",
        timers: [],
        refreshSeq: 0,
        unmount() {
          this.timers.forEach(clearInterval);
          this.timers = [];
        },
        mount(root) {
          this.loaded = false;
          this.ui = {
            summary: el("div", { class: "row", style: "padding: 0 0 10px" }),
            mappingsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            mergesBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
            personsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),
          };
          const matchesAny = (values, q) =>
            values.some((v) => v !== null && v !== undefined && String(v).toLowerCase().includes(q));
          this.mappingsView = listView({
            placeholder: "Filter by team, id, or outcome…",
            pageSize: 100,
            matches: (s, q) => matchesAny(
              [s.team_id, s.distinct_id, s.outcome, s.node && s.node.person_uuid, s.personhog && s.personhog.person_uuid], q),
            renderTable: (rows) => this.renderMappings(rows),
            emptyText: "No distinct id disagreements in the sample.",
          });
          this.mergesView = listView({
            placeholder: "Filter by team, person, or outcome…",
            pageSize: 100,
            matches: (s, q) => matchesAny([s.team_id, s.old_person_uuid, s.outcome, s.node, s.personhog], q),
            renderTable: (rows) => this.renderMerges(rows),
            emptyText: "No merge disagreements in the sample.",
          });
          this.personsView = listView({
            placeholder: "Filter by team, person, or outcome…",
            pageSize: 100,
            matches: (s, q) => matchesAny([s.team_id, s.person_uuid, s.outcome, ...(s.differing_properties || [])], q),
            renderTable: (rows) => this.renderPersons(rows),
            emptyText: "No person disagreements in the sample. The monitor compares persons only when both person topics are set.",
          });
          root.append(
            this.ui.summary,
            el("div", { class: "panel" }, el("h2", {}, "Distinct ids"), this.ui.mappingsBody),
            el("div", { class: "panel" }, el("h2", {}, "Merges"), this.ui.mergesBody),
            el("div", { class: "panel" }, el("h2", {}, "Persons"), this.ui.personsBody)
          );
          this.refresh();
          this.timers.push(setInterval(() => this.refresh(), 30000));
        },

        async refresh() {
          const seq = ++this.refreshSeq;
          let data;
          try {
            data = await fetchJSON("api/personhog/parity/mismatches");
          } catch (e) {
            if (seq !== this.refreshSeq) return;
            this.ui.summary.replaceChildren(el("div", { class: "error-box", style: "flex: 1 1 100%" }, String(e)));
            if (!this.loaded) {
              this.ui.mappingsBody.replaceChildren(el("div", { class: "empty" }, "No data."));
              this.ui.mergesBody.replaceChildren(el("div", { class: "empty" }, "No data."));
              this.ui.personsBody.replaceChildren(el("div", { class: "empty" }, "No data."));
            }
            return;
          }
          if (seq !== this.refreshSeq) return;
          this.loaded = true;
          this.render(data);
        },

        render(data) {
          // One sweep pushes its verdicts in hash map order, so the ring alone is not time ordered.
          const at = (s) => (typeof s.last_update_ms === "number" ? s.last_update_ms : Number.MIN_SAFE_INTEGER);
          const samples = data.samples.slice().reverse().sort((a, b) => at(b) - at(a));
          const counts = new Map();
          for (const s of samples) {
            const label = s.kind === "mapping" ? s.outcome : `${s.kind} ${s.outcome}`;
            counts.set(label, (counts.get(label) || 0) + 1);
          }
          this.ui.summary.replaceChildren(
            el("span", { class: "pill muted" }, `${fmtInt(samples.length)} in sample`),
            ...[...counts.entries()].map(([label, n]) => el("span", { class: "pill warn" }, `${label} ${fmtInt(n)}`)),
            el("span", { class: "muted" }, "The monitor keeps recent disagreements in memory, so older ones drop out and a restart clears them."),
            el("span", { class: "muted mono", style: "margin-left: auto" }, `as of ${new Date(data.fetched_at).toLocaleTimeString()}`),
            el("button", { class: "small", onclick: () => this.refresh() }, "Refresh")
          );
          this.mappingsView.setRows(samples.filter((s) => s.kind === "mapping"));
          this.ui.mappingsBody.replaceChildren(this.mappingsView.body);
          this.mergesView.setRows(samples.filter((s) => s.kind === "merge"));
          this.ui.mergesBody.replaceChildren(this.mergesView.body);
          this.personsView.setRows(samples.filter((s) => s.kind === "person"));
          this.ui.personsBody.replaceChildren(this.personsView.body);
        },

        when(sample) {
          if (sample.last_update_ms === null || sample.last_update_ms === undefined) return "–";
          const at = new Date(sample.last_update_ms);
          return el("span", { title: at.toISOString() }, `${at.toLocaleTimeString()} · ${fmtAgo(sample.last_update_ms)}`);
        },

        shortId(uuid) {
          if (!uuid) return el("span", { class: "pill bad" }, "missing");
          return el("span", { class: "mono", title: `${uuid} (click to copy)`, onclick: (e) => { e.stopPropagation(); copy(uuid); } },
            `${uuid.slice(0, 8)}…`);
        },

        renderMappings(rows) {
          const person = (row) => this.shortId(row ? row.person_uuid : null);
          return el("div", { class: "scroll-x" }, el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "time"), el("th", {}, "team"), el("th", {}, "distinct id"), el("th", {}, "outcome"),
              el("th", {}, "node person"), el("th", {}, "personhog person"), el("th", {}, "deleted"),
              el("th", { title: "Versions order rows within one feed and are not compared across feeds" }, "versions"))),
            el("tbody", {}, rows.map((s) => {
              const node = s.node, personhog = s.personhog;
              const both = node && personhog;
              const personClass = both && node.person_uuid !== personhog.person_uuid ? "mono diff" : "mono";
              const deletedClass = both && node.is_deleted !== personhog.is_deleted ? "mono diff" : "mono";
              const pair = (f) => `${node ? f(node) : "–"} / ${personhog ? f(personhog) : "–"}`;
              return el("tr", {},
                el("td", { class: "muted mono nowrap" }, this.when(s)),
                el("td", { class: "mono" }, String(s.team_id)),
                el("td", { class: "mono" }, copyable(s.distinct_id, "clip")),
                el("td", { class: "nowrap" }, el("span", { class: "pill warn" }, s.outcome)),
                el("td", { class: personClass }, person(node)),
                el("td", { class: personClass }, person(personhog)),
                el("td", { class: `${deletedClass} nowrap` }, pair((r) => (r.is_deleted ? "yes" : "no"))),
                el("td", { class: "muted mono nowrap" }, pair((r) => String(r.version))));
            }))
          ));
        },

        renderPersons(rows) {
          return el("div", { class: "scroll-x" }, el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "time"), el("th", {}, "team"), el("th", {}, "person"), el("th", {}, "outcome"),
              el("th", { title: "Top level property keys whose values differ or that one side lacks" }, "differing properties"),
              el("th", {}, "deleted"), el("th", {}, "identified"), el("th", {}, "created at"),
              el("th", { title: "Versions order rows within one feed and are not compared across feeds" }, "versions"))),
            el("tbody", {}, rows.map((s) => {
              const node = s.node, personhog = s.personhog;
              const both = node && personhog;
              const pair = (f) => `${node ? f(node) : "–"} / ${personhog ? f(personhog) : "–"}`;
              const differs = (f) => (both && f(node) !== f(personhog) ? "mono diff nowrap" : "mono nowrap");
              const keys = s.differing_properties || [];
              return el("tr", {},
                el("td", { class: "muted mono nowrap" }, this.when(s)),
                el("td", { class: "mono" }, String(s.team_id)),
                el("td", { class: "mono" }, this.shortId(s.person_uuid)),
                el("td", { class: "nowrap" }, el("span", { class: "pill warn" }, s.outcome)),
                el("td", { class: keys.length ? "mono diff" : "muted" }, keys.length ? keys.join(", ") : "–"),
                el("td", { class: differs((r) => r.is_deleted) }, pair((r) => (r.is_deleted ? "yes" : "no"))),
                el("td", { class: differs((r) => r.is_identified) }, pair((r) => (r.is_identified ? "yes" : "no"))),
                el("td", { class: differs((r) => r.created_at) }, pair((r) => r.created_at)),
                el("td", { class: "muted mono nowrap" }, pair((r) => String(r.version))));
            }))
          ));
        },

        renderMerges(rows) {
          const orDash = (v) => (v === null || v === undefined ? "–" : String(v));
          return el("div", { class: "scroll-x" }, el("table", {},
            el("thead", {}, el("tr", {},
              el("th", {}, "time"), el("th", {}, "team"), el("th", {}, "merged person"), el("th", {}, "outcome"),
              el("th", {}, "node survivor"), el("th", {}, "personhog survivor"), el("th", {}, "partitions"))),
            el("tbody", {}, rows.map((s) => {
              const survivorClass = s.node && s.personhog && s.node !== s.personhog ? "mono diff" : "mono";
              const [nodePartition, personhogPartition] = s.partitions || [null, null];
              return el("tr", {},
                el("td", { class: "muted mono nowrap" }, this.when(s)),
                el("td", { class: "mono" }, String(s.team_id)),
                el("td", { class: "mono" }, this.shortId(s.old_person_uuid)),
                el("td", { class: "nowrap" }, el("span", { class: "pill warn" }, s.outcome)),
                el("td", { class: survivorClass }, this.shortId(s.node)),
                el("td", { class: survivorClass }, this.shortId(s.personhog)),
                el("td", { class: "muted mono nowrap" }, `${orDash(nodePartition)} / ${orDash(personhogPartition)}`));
            }))
          ));
        },
      };

      // ---------- boot ----------
      SECTIONS.push(lagSection, debugSection, personhogSection, paritySection, etcdSection);
      const nav = document.getElementById("nav");
      for (const section of SECTIONS) {
        nav.append(el("span", { class: "nav-item", "data-id": section.id, onclick: () => navigate(section.id) }, section.title));
      }
      navigate(location.hash.replace("#", "") || SECTIONS[0].id);
    </script>
  </body>
</html>