Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

196 KB
Raw Blame
// Generated by packages/claude-mod (npm run build:mod). Do not edit.
// ../api-client/src/client.ts
var config = { baseUrl: "" };
function configureApiClient(next) {
  config = next;
  BASE_URL = next.baseUrl;
}
var BASE_URL = "";
function resolveToken() {
  const { token } = config;
  if (typeof token === "function") return token();
  return token ?? null;
}
function requestHeaders(extra) {
  const headers = {
    "Content-Type": "application/json",
    ...extra
  };
  const token = resolveToken();
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  return headers;
}
var ApiClientError = class extends Error {
  constructor(status, detail) {
    super(`API error ${status}: ${detail}`);
    this.status = status;
    this.detail = detail;
    this.name = "ApiClientError";
  }
  status;
  detail;
};
function stringifyDetail(detail) {
  if (typeof detail === "string") return detail;
  if (Array.isArray(detail)) {
    const msgs = detail.map(
      (d) => d && typeof d === "object" && "msg" in d ? String(d.msg) : null
    ).filter((m) => !!m).map((m) => m.replace(/^Value error, /, ""));
    if (msgs.length > 0) return msgs.join("; ");
  }
  return null;
}
async function handleResponse(res) {
  if (!res.ok) {
    let detail = res.statusText;
    try {
      const json = await res.json();
      detail = stringifyDetail(json.detail) ?? detail;
    } catch {
    }
    throw new ApiClientError(res.status, detail);
  }
  if (res.status === 204) return void 0;
  return res.json();
}
function doFetch(url, init) {
  return (config.fetch ?? fetch)(url, init);
}
function headersToRecord(headers) {
  const out = {};
  if (!headers) return out;
  if (Array.isArray(headers)) {
    for (const [name, value] of headers) out[name] = value;
  } else if (typeof headers.forEach === "function") {
    headers.forEach((value, name) => {
      out[name] = value;
    });
  } else {
    Object.assign(out, headers);
  }
  return out;
}
function createAdapterFetch(minimal) {
  const adapted = async (input2, init) => {
    const url = typeof input2 === "string" ? input2 : "href" in input2 ? input2.href : input2.url;
    const body = init?.body;
    if (body != null && typeof body !== "string") {
      throw new TypeError("createAdapterFetch only sends string bodies");
    }
    const request = { headers: headersToRecord(init?.headers) };
    if (init?.method) request.method = init.method;
    if (body != null) request.body = body;
    if (init?.signal) request.signal = init.signal;
    const res = await minimal(url, request);
    return {
      ok: res.ok,
      status: res.status,
      statusText: `HTTP ${res.status}`,
      json: async () => JSON.parse(res.text),
      text: async () => res.text
    };
  };
  return adapted;
}
async function apiGet(path, params, fetchOptions) {
  const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      if (v !== void 0 && v !== null) {
        url.searchParams.set(k, String(v));
      }
    }
  }
  const res = await doFetch(url.toString(), {
    method: "GET",
    headers: requestHeaders(),
    ...fetchOptions
  });
  return handleResponse(res);
}
async function apiPost(path, body, fetchOptions, params) {
  const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      if (v !== void 0 && v !== null) {
        url.searchParams.set(k, String(v));
      }
    }
  }
  const res = await doFetch(url.toString(), {
    method: "POST",
    headers: requestHeaders(),
    ...body !== void 0 ? { body: JSON.stringify(body) } : {},
    ...fetchOptions
  });
  return handleResponse(res);
}

// ../api-client/src/costs.ts
async function getSavings(repoId, opts = {}) {
  return apiGet(`/api/repos/${repoId}/savings`, {
    days: opts.days
  });
}

// ../api-client/src/health.ts
async function getHealth() {
  return apiGet("/health");
}

// ../api-client/src/repos.ts
async function listRepos() {
  return apiGet("/api/repos");
}

// ../types/src/repos.ts
function normalizeRepoPath(p, isWindows) {
  const slashed = isWindows ? p.replace(/\\/g, "/") : p;
  const trimmed = slashed.replace(/\/+$/, "");
  return isWindows ? trimmed.toLowerCase() : trimmed;
}

// ../types/src/serve-lock.ts
function isServeLock(value) {
  if (typeof value !== "object" || value === null) return false;
  const v = value;
  return typeof v.pid === "number" && typeof v.host === "string" && typeof v.port === "number" && typeof v.url === "string" && (typeof v.ui_port === "number" || v.ui_port === null) && typeof v.server_version === "string" && typeof v.started_at === "string";
}
var LOOPBACK_V4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
function isLoopbackUrl(url) {
  try {
    const u = new URL(url);
    if (u.protocol !== "http:" && u.protocol !== "https:") return false;
    return u.hostname === "localhost" || u.hostname === "[::1]" || LOOPBACK_V4.test(u.hostname);
  } catch {
    return false;
  }
}

// src/data/transport.ts
function connectApiClient(host, baseUrl) {
  configureApiClient({ baseUrl, fetch: createAdapterFetch(host.http) });
}
var TimeoutError = class extends Error {
  constructor(label, ms) {
    super(`${label} timed out after ${ms} ms`);
    this.name = "TimeoutError";
  }
};
function withTimeout(work, ms, label) {
  let timer;
  const timeout = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new TimeoutError(label, ms)), ms);
  });
  return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
}

// src/data/discovery.ts
var HEALTH_TIMEOUT_MS = 800;
var LIST_TIMEOUT_MS = 3e3;
var CONNECT_TIMEOUT_MS = 35e3;
var GIT_TIMEOUT_MS = 5e3;
var MAX_WALK = 20;
var SHA = /^[0-9a-f]{7,64}$/i;
function isWindowsPath(p) {
  return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
}
function join(dir, rel2) {
  return `${dir.replace(/[\\/]+$/, "")}/${rel2}`;
}
function parentDir(p) {
  const trimmed = p.replace(/[\\/]+$/, "");
  const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
  if (cut < 0) return null;
  if (cut === 0) return trimmed === "" ? null : "/";
  return trimmed.slice(0, cut);
}
async function findIndexedRoot(host, cwd2) {
  let dir = cwd2;
  for (let i = 0; dir !== null && i < MAX_WALK; i++) {
    if (await host.fs.exists(join(dir, ".repowise/state.json"))) return dir;
    dir = parentDir(dir);
  }
  return null;
}
async function readJson(host, path) {
  try {
    return JSON.parse(await host.fs.read(path));
  } catch {
    return null;
  }
}
async function readServeLock(host, repoRoot) {
  const parsed = await readJson(host, join(repoRoot, ".repowise/serve.lock.json"));
  return isServeLock(parsed) ? parsed : null;
}
async function isPidAlive(host, pid, cwd2) {
  try {
    if (isWindowsPath(cwd2)) {
      const out2 = await host.process.run(["tasklist", "/FI", `PID eq ${pid}`, "/NH", "/FO", "CSV"], cwd2);
      return out2.exitCode === 0 && out2.stdout.includes(`"${pid}"`);
    }
    const out = await host.process.run(["ps", "-p", String(pid), "-o", "pid="], cwd2);
    return out.exitCode === 0 && out.stdout.trim() === String(pid);
  } catch {
    return null;
  }
}
async function probeServer(host, lock, repoRoot) {
  connectApiClient(host, lock.url);
  try {
    await withTimeout(getHealth(), HEALTH_TIMEOUT_MS, "health");
  } catch {
    return { kind: "down" };
  }
  try {
    const repos = await withTimeout(listRepos(), LIST_TIMEOUT_MS, "listRepos");
    const win = isWindowsPath(repoRoot);
    const target = normalizeRepoPath(repoRoot, win);
    const match = repos.find((r) => r.local_path && normalizeRepoPath(r.local_path, win) === target);
    return match ? { kind: "ok", repoId: match.id, updatedAt: match.updated_at ?? null } : { kind: "unlisted" };
  } catch (err) {
    if (err instanceof ApiClientError && (err.status === 401 || err.status === 403)) return { kind: "auth" };
    return { kind: "down" };
  }
}
async function mcpReachable(host) {
  try {
    return await withTimeout(host.mcp.connect(), CONNECT_TIMEOUT_MS, "mcp connect");
  } catch {
    return false;
  }
}
async function unindexedMode(host, cwd2) {
  const inWorkTree = (await git(host, cwd2, ["rev-parse", "--is-inside-work-tree"]))?.trim() === "true";
  if (!inWorkTree) return "no-repo";
  return await mcpReachable(host) ? "no-index" : "no-cli";
}
async function serverState(host, repoRoot) {
  const lock = await readServeLock(host, repoRoot);
  if (!lock || !isLoopbackUrl(lock.url)) return { kind: "down" };
  if (await isPidAlive(host, lock.pid, repoRoot) === false) return { kind: "down" };
  return probeServer(host, lock, repoRoot);
}
async function discover(host) {
  const cwd2 = await host.session.cwd();
  const repoRoot = await findIndexedRoot(host, cwd2);
  if (repoRoot === null) return { mode: await unindexedMode(host, cwd2), repoRoot };
  const server = await serverState(host, repoRoot);
  if (server.kind === "ok") return { mode: "full", repoRoot, repo: { id: server.repoId, updatedAt: server.updatedAt } };
  if (!await mcpReachable(host)) return { mode: "no-cli", repoRoot };
  const liteReason = server.kind === "down" ? "no-server" : server.kind;
  return { mode: "lite", liteReason, repoRoot };
}
async function git(host, cwd2, args) {
  try {
    const out = await withTimeout(host.process.run(["git", ...args], cwd2), GIT_TIMEOUT_MS, "git");
    return out.exitCode === 0 ? out.stdout : null;
  } catch {
    return null;
  }
}
async function updateRunning(host, repoRoot) {
  const lock = await readJson(host, join(repoRoot, ".repowise/.update.lock"));
  const pid = lock?.pid;
  return typeof pid === "number" && await isPidAlive(host, pid, repoRoot) === true;
}
async function readFreshness(host, repoRoot) {
  const state2 = await readJson(host, join(repoRoot, ".repowise/state.json"));
  const indexed = state2?.last_sync_commit;
  if (typeof indexed !== "string" || !SHA.test(indexed)) return null;
  const head = (await git(host, repoRoot, ["rev-parse", "HEAD"]))?.trim();
  if (!head || !SHA.test(head) || head === indexed) return null;
  if (await updateRunning(host, repoRoot)) return null;
  const diff = await git(host, repoRoot, ["diff", "--name-only", indexed, head, "--"]);
  const changedFiles = diff === null ? null : diff.split("\n").filter((l) => l.trim() !== "").length;
  return { changedFiles };
}

// src/data/mcp.ts
var PLUGIN_SERVER_FORMS = ["plugin:repowise:repowise", "plugin_repowise_repowise"];
var DEFAULT_TIMEOUT_MS = 1e4;
var resolvedServer = null;
var resolving = null;
function resetMcp() {
  resolvedServer = null;
  resolving = null;
}
function warmMcp(host) {
  if (resolvedServer !== null || resolving !== null) return;
  const asked = host.mcp.server().then((name) => {
    if (name !== null && PLUGIN_SERVER_FORMS.includes(name)) resolvedServer = name;
  }).catch(() => void 0).finally(() => {
    if (resolving === asked) resolving = null;
  });
  resolving = asked;
}
async function mcpReady(host, timeoutMs = DEFAULT_TIMEOUT_MS) {
  warmMcp(host);
  const pending = resolving;
  if (resolvedServer === null && pending !== null) await withTimeout(pending, timeoutMs, "MCP connect").catch(() => void 0);
  return resolvedServer !== null;
}
function parse(result, tool) {
  const text2 = result.content[0]?.text;
  if (result.isError) throw new Error(`${tool} failed: ${String(text2).slice(0, 200)}`);
  if (typeof text2 !== "string") throw new Error(`${tool} returned no text`);
  const parsed = JSON.parse(text2);
  return parsed !== null && typeof parsed === "object" && "result" in parsed ? parsed.result : parsed;
}
function callTool(host, tool, args, opts = {}) {
  if (resolvedServer === null) {
    warmMcp(host);
    return Promise.reject(new Error("repowise MCP server name not resolved yet"));
  }
  const call = host.mcp.call(resolvedServer, tool, args).then((r) => parse(r, tool));
  return withTimeout(call, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, tool);
}
function recentOwner(o) {
  const name = o?.recent_owner;
  const share = o?.recent_owner_pct;
  return typeof name === "string" && name !== "" && typeof share === "number" ? { name, share } : null;
}
async function fetchFileContext(host, path) {
  const result = await callTool(host, "get_context", {
    targets: [path],
    include: ["callers", "ownership"]
  });
  const target = result.targets?.[path];
  if (target === void 0 || target.error !== void 0) return null;
  const callers = target.callers_total ?? target.callers?.length;
  const contributors = target.ownership?.contributor_count;
  return {
    callerFiles: typeof callers === "number" ? callers : null,
    contributors: typeof contributors === "number" ? contributors : null,
    hotspot: typeof target.hotspot === "boolean" ? target.hotspot : null,
    recentOwner: recentOwner(target.ownership)
  };
}

// ../ui/src/lib/format.ts
function parseDate(date) {
  if (date instanceof Date) return date;
  if (!/[zZ]|[+-]\d\d?:\d\d$/.test(date.trim())) {
    return /* @__PURE__ */ new Date(`${date.trim()}Z`);
  }
  return new Date(date);
}
var NUMBER_FORMAT = new Intl.NumberFormat("en-US");
function formatNumber(n) {
  return NUMBER_FORMAT.format(n);
}
function relativeTimeParts(date) {
  const d = parseDate(date);
  const now = Date.now();
  const diff = now - d.getTime();
  const seconds = Math.floor(diff / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const weeks = Math.floor(days / 7);
  const months = Math.floor(days / 30);
  if (seconds < 10) return { unit: "now", value: 0 };
  if (seconds < 60) return { unit: "s", value: seconds };
  if (minutes < 60) return { unit: "m", value: minutes };
  if (hours < 24) return { unit: "h", value: hours };
  if (days < 7) return { unit: "d", value: days };
  if (weeks < 5) return { unit: "w", value: weeks };
  if (months < 12) return { unit: "mo", value: months };
  return { unit: "y", value: Math.floor(months / 12) };
}
function formatRelativeTime(date) {
  const { unit, value } = relativeTimeParts(date);
  return unit === "now" ? "just now" : `${value}${unit} ago`;
}
function formatRelativeTimeOrNull(iso, fallback = "—") {
  if (!iso) return fallback;
  const d = parseDate(iso);
  if (Number.isNaN(d.getTime()) || d.getTime() > Date.now()) return fallback;
  return formatRelativeTime(d);
}

// src/format.ts
function countOf(n, singular, plural) {
  return `${formatNumber(n)} ${n === 1 ? singular : plural}`;
}
function fit(text2, columns) {
  if (columns <= 0) return "";
  if (text2.length <= columns) return text2;
  return `${text2.slice(0, columns - 1).trimEnd()}…`;
}
var NOT_ONE_CELL = /[\u0000-\u001f\u007f-\u009f\ud800-\udfffᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/;
function cellSafe(text2) {
  return Array.from(text2, (ch) => ch.length === 1 && !NOT_ONE_CELL.test(ch) ? ch : "?").join("");
}

// ../../node_modules/d3-hierarchy/src/hierarchy/count.js
function count(node) {
  var sum = 0, children = node.children, i = children && children.length;
  if (!i) sum = 1;
  else while (--i >= 0) sum += children[i].value;
  node.value = sum;
}
function count_default() {
  return this.eachAfter(count);
}

// ../../node_modules/d3-hierarchy/src/hierarchy/each.js
function each_default(callback, that) {
  let index = -1;
  for (const node of this) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
function eachBefore_default(callback, that) {
  var node = this, nodes = [node], children, i, index = -1;
  while (node = nodes.pop()) {
    callback.call(that, node, ++index, this);
    if (children = node.children) {
      for (i = children.length - 1; i >= 0; --i) {
        nodes.push(children[i]);
      }
    }
  }
  return this;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
function eachAfter_default(callback, that) {
  var node = this, nodes = [node], next = [], children, i, n, index = -1;
  while (node = nodes.pop()) {
    next.push(node);
    if (children = node.children) {
      for (i = 0, n = children.length; i < n; ++i) {
        nodes.push(children[i]);
      }
    }
  }
  while (node = next.pop()) {
    callback.call(that, node, ++index, this);
  }
  return this;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/find.js
function find_default(callback, that) {
  let index = -1;
  for (const node of this) {
    if (callback.call(that, node, ++index, this)) {
      return node;
    }
  }
}

// ../../node_modules/d3-hierarchy/src/hierarchy/sum.js
function sum_default(value) {
  return this.eachAfter(function(node) {
    var sum = +value(node.data) || 0, children = node.children, i = children && children.length;
    while (--i >= 0) sum += children[i].value;
    node.value = sum;
  });
}

// ../../node_modules/d3-hierarchy/src/hierarchy/sort.js
function sort_default(compare) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare);
    }
  });
}

// ../../node_modules/d3-hierarchy/src/hierarchy/path.js
function path_default(end) {
  var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
  while (start !== ancestor) {
    start = start.parent;
    nodes.push(start);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}
function leastCommonAncestor(a, b) {
  if (a === b) return a;
  var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.js
function ancestors_default() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.js
function descendants_default() {
  return Array.from(this);
}

// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.js
function leaves_default() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/links.js
function links_default() {
  var root = this, links = [];
  root.each(function(node) {
    if (node !== root) {
      links.push({ source: node.parent, target: node });
    }
  });
  return links;
}

// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.js
function* iterator_default() {
  var node = this, current, next = [node], children, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      yield node;
      if (children = node.children) {
        for (i = 0, n = children.length; i < n; ++i) {
          next.push(children[i]);
        }
      }
    }
  } while (next.length);
}

// ../../node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy(data, children) {
  if (data instanceof Map) {
    data = [void 0, data];
    if (children === void 0) children = mapChildren;
  } else if (children === void 0) {
    children = objectChildren;
  }
  var root = new Node(data), node, nodes = [root], child, childs, i, n;
  while (node = nodes.pop()) {
    if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = childs[i] = new Node(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }
  return root.eachBefore(computeHeight);
}
function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}
function objectChildren(d) {
  return d.children;
}
function mapChildren(d) {
  return Array.isArray(d) ? d[1] : null;
}
function copyData(node) {
  if (node.data.value !== void 0) node.value = node.data.value;
  node.data = node.data.data;
}
function computeHeight(node) {
  var height = 0;
  do
    node.height = height;
  while ((node = node.parent) && node.height < ++height);
}
function Node(data) {
  this.data = data;
  this.depth = this.height = 0;
  this.parent = null;
}
Node.prototype = hierarchy.prototype = {
  constructor: Node,
  count: count_default,
  each: each_default,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default,
  path: path_default,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default
};

// ../../node_modules/d3-hierarchy/src/accessors.js
function required(f) {
  if (typeof f !== "function") throw new Error();
  return f;
}

// ../../node_modules/d3-hierarchy/src/constant.js
function constantZero() {
  return 0;
}
function constant_default(x) {
  return function() {
    return x;
  };
}

// ../../node_modules/d3-hierarchy/src/treemap/round.js
function round_default(node) {
  node.x0 = Math.round(node.x0);
  node.y0 = Math.round(node.y0);
  node.x1 = Math.round(node.x1);
  node.y1 = Math.round(node.y1);
}

// ../../node_modules/d3-hierarchy/src/treemap/dice.js
function dice_default(parent, x0, y0, x1, y1) {
  var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;
  while (++i < n) {
    node = nodes[i], node.y0 = y0, node.y1 = y1;
    node.x0 = x0, node.x1 = x0 += node.value * k;
  }
}

// ../../node_modules/d3-hierarchy/src/treemap/slice.js
function slice_default(parent, x0, y0, x1, y1) {
  var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;
  while (++i < n) {
    node = nodes[i], node.x0 = x0, node.x1 = x1;
    node.y0 = y0, node.y1 = y0 += node.value * k;
  }
}

// ../../node_modules/d3-hierarchy/src/treemap/squarify.js
var phi = (1 + Math.sqrt(5)) / 2;
function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
  var rows = [], nodes = parent.children, row2, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
  while (i0 < n) {
    dx = x1 - x0, dy = y1 - y0;
    do
      sumValue = nodes[i1++].value;
    while (!sumValue && i1 < n);
    minValue = maxValue = sumValue;
    alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
    beta = sumValue * sumValue * alpha;
    minRatio = Math.max(maxValue / beta, beta / minValue);
    for (; i1 < n; ++i1) {
      sumValue += nodeValue = nodes[i1].value;
      if (nodeValue < minValue) minValue = nodeValue;
      if (nodeValue > maxValue) maxValue = nodeValue;
      beta = sumValue * sumValue * alpha;
      newRatio = Math.max(maxValue / beta, beta / minValue);
      if (newRatio > minRatio) {
        sumValue -= nodeValue;
        break;
      }
      minRatio = newRatio;
    }
    rows.push(row2 = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
    if (row2.dice) dice_default(row2, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
    else slice_default(row2, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
    value -= sumValue, i0 = i1;
  }
  return rows;
}
var squarify_default = (function custom(ratio) {
  function squarify(parent, x0, y0, x1, y1) {
    squarifyRatio(ratio, parent, x0, y0, x1, y1);
  }
  squarify.ratio = function(x) {
    return custom((x = +x) > 1 ? x : 1);
  };
  return squarify;
})(phi);

// ../../node_modules/d3-hierarchy/src/treemap/index.js
function treemap_default() {
  var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
  function treemap(root) {
    root.x0 = root.y0 = 0;
    root.x1 = dx;
    root.y1 = dy;
    root.eachBefore(positionNode);
    paddingStack = [0];
    if (round) root.eachBefore(round_default);
    return root;
  }
  function positionNode(node) {
    var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
    if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
    if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
    node.x0 = x0;
    node.y0 = y0;
    node.x1 = x1;
    node.y1 = y1;
    if (node.children) {
      p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
      x0 += paddingLeft(node) - p;
      y0 += paddingTop(node) - p;
      x1 -= paddingRight(node) - p;
      y1 -= paddingBottom(node) - p;
      if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
      if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
      tile(node, x0, y0, x1, y1);
    }
  }
  treemap.round = function(x) {
    return arguments.length ? (round = !!x, treemap) : round;
  };
  treemap.size = function(x) {
    return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
  };
  treemap.tile = function(x) {
    return arguments.length ? (tile = required(x), treemap) : tile;
  };
  treemap.padding = function(x) {
    return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
  };
  treemap.paddingInner = function(x) {
    return arguments.length ? (paddingInner = typeof x === "function" ? x : constant_default(+x), treemap) : paddingInner;
  };
  treemap.paddingOuter = function(x) {
    return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
  };
  treemap.paddingTop = function(x) {
    return arguments.length ? (paddingTop = typeof x === "function" ? x : constant_default(+x), treemap) : paddingTop;
  };
  treemap.paddingRight = function(x) {
    return arguments.length ? (paddingRight = typeof x === "function" ? x : constant_default(+x), treemap) : paddingRight;
  };
  treemap.paddingBottom = function(x) {
    return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant_default(+x), treemap) : paddingBottom;
  };
  treemap.paddingLeft = function(x) {
    return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant_default(+x), treemap) : paddingLeft;
  };
  return treemap;
}

// ../types/src/health.ts
var EXCELLENT_MIN = 8.5;
var GOOD_MIN = 7;
var FAIR_MIN = 5.5;
var NEEDS_WORK_MIN = 4;
var HEALTH_BAND_ORDER = [
  "at_risk",
  "needs_work",
  "fair",
  "good",
  "excellent"
];
var HEALTH_BAND_LABEL = {
  excellent: "Excellent",
  good: "Good",
  fair: "Fair",
  needs_work: "Needs work",
  at_risk: "At risk"
};
function bandForScore(score) {
  if (score >= EXCELLENT_MIN) return "excellent";
  if (score >= GOOD_MIN) return "good";
  if (score >= FAIR_MIN) return "fair";
  if (score >= NEEDS_WORK_MIN) return "needs_work";
  return "at_risk";
}

// ../ui/src/brand.ts
var BRAND = {
  /** Accent orange — the brand fill (CTAs, owl eyes, highlights). */
  accent: "#f59520",
  /** Accent text on light surfaces (darkened for 4.5:1 contrast). */
  accentTextLight: "#a16215",
  /** Brand plum — logo strokes on light surfaces, secondary accent. */
  plum: "#473659",
  /** Plum near-black — primary ink on warm paper. */
  ink: "#241b2c",
  /** Warm paper — the light-mode page background. */
  paper: "#fbf6f1",
  /** Cream — the logo stroke color on dark surfaces. */
  cream: "#fce9dd"
};
var LIGHT = {
  bgRoot: "#fbf6f1",
  bgSurface: "#ffffff",
  bgElevated: "#f7f4f1",
  bgInset: "#f0ebe6",
  textPrimary: "#241b2c",
  textSecondary: "#5e5360",
  textTertiary: "#8c7f88",
  accentPrimary: "#a16215",
  accentFill: "#f59520",
  accentSecondary: "#58436c",
  success: "#1d8155",
  warning: "#856700",
  error: "#b23a2e"
};
var DARK = {
  bgRoot: "#0e0e0f",
  bgSurface: "#141416",
  bgElevated: "#191a1c",
  bgInset: "#0a0a0b",
  textPrimary: "#f2f2f3",
  textSecondary: "#b4b4b9",
  textTertiary: "#7c7c82",
  accentPrimary: "#f59520",
  accentFill: "#f59520",
  accentSecondary: "#a98fc4",
  success: "#34d399",
  warning: "#e8b339",
  error: "#e06a5a"
};
var DARK_CANVAS = {
  nodeAtRisk: "#b0544b",
  nodeNeedsWork: "#bd7c42",
  nodeFair: "#a89453",
  nodeGood: "#42906f",
  nodeExcellent: "#5cb389",
  nodeNeutral: "#333336",
  caution: "#d9b04a"
};
var DARK_CANVAS_BAND = {
  excellent: DARK_CANVAS.nodeExcellent,
  good: DARK_CANVAS.nodeGood,
  fair: DARK_CANVAS.nodeFair,
  needs_work: DARK_CANVAS.nodeNeedsWork,
  at_risk: DARK_CANVAS.nodeAtRisk
};

// src/views/map.ts
var UPPER_HALF = 9600;
var LOWER_HALF = 9604;
var SPACE = 32;
var hex = (s) => parseInt(s.slice(1), 16);
var GROUND = hex(DARK.bgRoot);
var TERMINAL_DEFAULT = 16777216;
var LABEL_FG = hex(DARK.textSecondary);
var NEUTRAL = hex(DARK_CANVAS.nodeNeutral);
var BLACK = 0;
var MAP_PALETTES = {
  dark: {
    tileA: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.12),
    tileB: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.22),
    folder: hex(DARK.textTertiary),
    hit: mix(hex(DARK.bgElevated), hex(DARK.textSecondary), 0.32),
    read: hex(DARK.textSecondary),
    named: mix(hex(DARK.accentSecondary), hex(DARK.bgRoot), 0.45),
    importer: hex(DARK.accentSecondary),
    edit: hex(BRAND.accent),
    ring: hex(BRAND.cream)
  },
  light: {
    tileA: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.08),
    tileB: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.16),
    folder: hex(LIGHT.textTertiary),
    hit: mix(hex(LIGHT.bgInset), hex(LIGHT.textSecondary), 0.3),
    read: hex(LIGHT.textSecondary),
    named: mix(hex(LIGHT.accentSecondary), hex(LIGHT.bgRoot), 0.55),
    importer: hex(LIGHT.accentSecondary),
    edit: hex(BRAND.accentTextLight),
    ring: hex(LIGHT.textPrimary)
  }
};
var DEFAULT_STYLE = { theme: "dark", health: false };
var DENSE_SHARE = 0.6;
var SPLIT_SHARE = 0.25;
var MAX_SPLITS = 8;
var GUTTER_MIN = 6;
var EDGE_MIN = 3;
function colorForScore(score) {
  return score === null ? NEUTRAL : hex(DARK_CANVAS_BAND[bandForScore(score)]);
}
function mix(a, b, amount) {
  const ch = (shift) => {
    const x = a >> shift & 255;
    const y = b >> shift & 255;
    return Math.round(x + (y - x) * amount) << shift;
  };
  return (ch(16) | ch(8) | ch(0)) >>> 0;
}
var byName = (a, b) => a < b ? -1 : a > b ? 1 : 0;
function dirsOf(path) {
  return path.split("/").slice(0, -1);
}
function keyOf(path, split) {
  const dirs = dirsOf(path);
  let depth = Math.min(1, dirs.length);
  while (depth < dirs.length && split.has(dirs.slice(0, depth).join("/"))) depth++;
  return dirs.slice(0, depth).join("/");
}
function nextSplit(files, split, limit) {
  const weight = /* @__PURE__ */ new Map();
  for (const f of files) {
    const key2 = keyOf(f.file_path, split);
    weight.set(key2, (weight.get(key2) ?? 0) + f.nloc);
  }
  const heavy = [...weight].filter(([key2, w]) => key2 !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));
  for (const [key2] of heavy) {
    const deeper = /* @__PURE__ */ new Set([...split, key2]);
    const parts = new Set(files.filter((f) => keyOf(f.file_path, split) === key2).map((f) => keyOf(f.file_path, deeper)));
    if (parts.size > 1) return key2;
  }
  return null;
}
function groupKeys(files) {
  const split = /* @__PURE__ */ new Set();
  const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;
  for (let i = 0; i < MAX_SPLITS; i++) {
    const key2 = nextSplit(files, split, limit);
    if (key2 === null) break;
    split.add(key2);
  }
  return files.map((f) => keyOf(f.file_path, split));
}
var folderDatum = (name) => ({ name, children: [], kids: /* @__PURE__ */ new Map() });
function insertFile(group, key2, file) {
  const rel2 = key2 === "" ? file.file_path : file.file_path.slice(key2.length + 1);
  let node = group;
  for (const dir of rel2.split("/").slice(0, -1)) {
    let next = node.kids?.get(dir);
    if (next === void 0) {
      next = folderDatum(dir);
      node.kids?.set(dir, next);
      node.children?.push(next);
    }
    node = next;
  }
  node.children?.push({ name: file.file_path, file });
}
function treemapOf(files, width2, height) {
  const keys = groupKeys(files);
  const groups = /* @__PURE__ */ new Map();
  files.forEach((file, i) => {
    const key2 = keys[i] ?? "";
    const group = groups.get(key2) ?? folderDatum(key2);
    groups.set(key2, group);
    insertFile(group, key2, file);
  });
  const data = { name: "", children: [...groups.values()] };
  const root = hierarchy(data).sum((d) => d.file?.nloc ?? 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));
  return treemap_default().tile(squarify_default).size([width2, height])(root);
}
var rectOf = (n) => ({ x: n.x0, y: n.y0, w: n.x1 - n.x0, h: n.y1 - n.y0 });
function pixelSpan(from, to) {
  return [Math.ceil(from - 0.5), Math.ceil(to - 0.5)];
}
function groupInterior(rect, width2, height) {
  const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);
  const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);
  const gutter = x1 - x0 >= GUTTER_MIN && y1 - y0 >= GUTTER_MIN;
  return { x0, y0, x1: gutter && x1 < width2 ? x1 - 1 : x1, y1: gutter && y1 < height ? y1 - 1 : y1 };
}
function placeFile(leaf, group, inner) {
  const file = leaf.data.file;
  const rect = rectOf(leaf);
  const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);
  const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);
  return {
    path: file.file_path,
    score: file.score,
    nloc: file.nloc,
    group,
    rect,
    px0: Math.max(x0, inner.x0),
    py0: Math.max(y0, inner.y0),
    px1: Math.min(x1, inner.x1),
    py1: Math.min(y1, inner.y1)
  };
}
function tileFor(f, i, style) {
  const pal = MAP_PALETTES[style.theme];
  if (style.health) return colorForScore(f.score);
  return i % 2 === 0 ? pal.tileA : pal.tileB;
}
function paintBox(base, width2, box2, fill) {
  for (let y = box2.y0; y < box2.y1; y++) base.fill(fill, y * width2 + box2.x0, y * width2 + box2.x1);
}
function folderPath(group, node) {
  const below2 = node.ancestors().reverse().slice(2).map((n) => n.data.name);
  return [group.data.name, ...below2].filter((part) => part !== "").join("/");
}
function folderTiles(group, inner) {
  const out = [];
  for (const node of group.descendants()) {
    if (node === group || node.children === void 0) continue;
    const tone = (node.parent?.children ?? []).indexOf(node) % 2;
    const [x0, x1] = pixelSpan(node.x0, node.x1);
    const [y0, y1] = pixelSpan(node.y0, node.y1);
    const box2 = { x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1) };
    out.push({ path: folderPath(group, node), ...box2, tone });
  }
  return out;
}
var within = (f, x, y) => x >= f.x0 && x < f.x1 && y >= f.y0 && y < f.y1;
function folderAt(layout, x, y) {
  const tile = layout.folders.filter((f) => within(f, x, y)).at(-1);
  if (tile !== void 0) return tile.path;
  const group = layout.groups.find((g) => within({ x0: g.rect.x, y0: g.rect.y, x1: g.rect.x + g.rect.w, y1: g.rect.y + g.rect.h }, x, y));
  return group === void 0 || group.key === "" ? null : group.key;
}
function paintFile(base, width2, f, fill) {
  const edge = mix(fill, BLACK, 0.3);
  const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;
  const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;
  for (let y = f.py0; y < f.py1; y++) {
    base.fill(y === edgeY ? edge : fill, y * width2 + f.px0, y * width2 + f.px1);
    if (edgeX >= 0) base[y * width2 + edgeX] = edge;
  }
}
function labelText(key2, width2) {
  const parts = key2.split("/");
  const rungs = [key2, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];
  const text2 = rungs.find((r) => r.length > 0 && r.length <= width2);
  return text2 !== void 0 && /^[\x20-\x7e]+$/.test(text2) ? text2 : null;
}
var LABEL_MIN_COLS = 12;
var LABEL_MIN_ROWS = 3;
var MAX_LABELS = 8;
function labelFor(g, columns, rows, root) {
  const col = Math.ceil(g.rect.x);
  const row2 = Math.ceil(g.rect.y / 2);
  const width2 = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;
  const height = Math.floor((g.rect.y + g.rect.h) / 2) - row2;
  const small = height < LABEL_MIN_ROWS || width2 < LABEL_MIN_COLS;
  const key2 = root === null ? g.key : g.key.slice(root.length + 1);
  if (key2 === "" || small || row2 >= rows) return null;
  const text2 = labelText(key2, width2);
  return text2 === null ? null : { row: row2, col, text: text2 };
}
function labelsFor(groups, columns, rows, root = null) {
  return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows, root)).filter((l) => l !== null).slice(0, MAX_LABELS);
}
function fileLabel(f, rows) {
  const text2 = cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1));
  const row2 = Math.ceil(f.py0 / 2);
  const roomy = f.px1 - f.px0 >= text2.length + 2 && Math.floor(f.py1 / 2) > row2;
  return roomy && row2 < rows ? { row: row2, col: f.px0 + 1, text: text2 } : null;
}
function fileLabels(files, rows, taken) {
  const used = new Set(taken.flatMap((l) => [...l.text].map((_, k) => `${l.row}:${l.col + k}`)));
  const out = [];
  for (const label of files.map((f) => fileLabel(f, rows))) {
    if (label === null) continue;
    const cells = [...label.text].map((_, k) => `${label.row}:${label.col + k}`);
    if (cells.some((c) => used.has(c))) continue;
    cells.forEach((c) => used.add(c));
    out.push(label);
  }
  return out;
}
function paintBase(map2, style, dense) {
  const { width: width2, height } = map2;
  const base = new Uint32Array(width2 * height).fill(GROUND);
  const pal = MAP_PALETTES[style.theme];
  const tone = (t) => t === 0 ? pal.tileB : pal.tileA;
  if (!style.health) map2.groups.forEach((g, i) => paintBox(base, width2, groupInterior(g.rect, width2, height), tone(i % 2)));
  if (!style.health) for (const f of map2.folders) paintBox(base, width2, f, tone(1 - f.tone));
  if (dense && !style.health) return base;
  for (const i of map2.drawn) paintFile(base, width2, map2.files[i], tileFor(map2.files[i], i, style));
  return base;
}
function filesUnder(feed, root) {
  const lines = feed.filter((f) => f.nloc > 0);
  return root === null ? lines : lines.filter((f) => f.file_path.startsWith(`${root}/`));
}
function layoutMap(feed, canvas) {
  const { columns, rows, caseInsensitive } = canvas;
  const style = canvas.style ?? DEFAULT_STYLE;
  const width2 = columns;
  const height = rows * 2;
  const zoom = canvas.root ?? null;
  const root = treemapOf(filesUnder(feed, zoom), width2, height);
  const groups = [];
  const files = [];
  const folders = [];
  for (const node of root.children ?? []) {
    const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;
    const inner = groupInterior(rectOf(node), width2, height);
    for (const leaf of node.leaves()) files.push(placeFile(leaf, group, inner));
    folders.push(...folderTiles(node, inner));
  }
  const drawn = [];
  const index = /* @__PURE__ */ new Map();
  const lower = /* @__PURE__ */ new Map();
  files.forEach((f, i) => {
    index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);
    lower.set(f.path.toLowerCase(), i);
    if (f.px1 > f.px0 && f.py1 > f.py0) drawn.push(i);
  });
  const dense = drawn.length < files.length * DENSE_SHARE;
  const base = paintBase({ width: width2, height, groups, folders, files, drawn }, style, dense);
  const folderNames = labelsFor(groups, columns, rows, zoom);
  const labels = zoom === null || dense ? folderNames : [...folderNames, ...fileLabels(files, rows, folderNames)];
  return { columns, rows, width: width2, height, groups, files, drawn, index, caseInsensitive, labels, base, style, dense, lower, folders, root: zoom };
}
function halfCell(top, bottom) {
  if (top === GROUND && bottom === GROUND) return [SPACE, TERMINAL_DEFAULT, TERMINAL_DEFAULT];
  if (top === GROUND) return [LOWER_HALF, bottom, TERMINAL_DEFAULT];
  return [UPPER_HALF, top, bottom === GROUND ? TERMINAL_DEFAULT : bottom];
}
function labelCovered(label, marked, width2) {
  if (marked === void 0) return false;
  for (let c = label.col; c < label.col + label.text.length; c++) {
    if (marked[2 * label.row * width2 + c] || marked[(2 * label.row + 1) * width2 + c]) return true;
  }
  return false;
}
var cellGround = (pixel) => pixel === void 0 || pixel === GROUND ? TERMINAL_DEFAULT : pixel;
function writeText(words, layout, label, colors) {
  if (label.row < 0 || label.row >= layout.rows) return;
  for (let k = Math.max(0, -label.col); k < label.text.length && label.col + k < layout.columns; k++) {
    const col = label.col + k;
    words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);
  }
}
function writeFolderLabels(words, layout, pixels, marked) {
  const fg = layout.style.health ? LABEL_FG : MAP_PALETTES[layout.style.theme].folder;
  for (const label of layout.labels) {
    if (labelCovered(label, marked, layout.width)) continue;
    writeText(words, layout, label, (col) => [fg, cellGround(pixels[2 * label.row * layout.width + col])]);
  }
}
function encodeCells(layout, pixels, marked, names2 = []) {
  const { columns, rows, width: width2 } = layout;
  const words = new Uint32Array(columns * rows * 3);
  for (let i = 0; i < columns * rows; i++) {
    const r = Math.floor(i / columns);
    const c = i % columns;
    words.set(halfCell(pixels[2 * r * width2 + c] ?? GROUND, pixels[(2 * r + 1) * width2 + c] ?? GROUND), i * 3);
  }
  writeFolderLabels(words, layout, pixels, marked);
  for (const name of names2) writeText(words, layout, name, () => [name.color, TERMINAL_DEFAULT]);
  return new Uint8Array(words.buffer).toBase64();
}

// src/views/overlay.ts
var NO_LIT = { hits: [], reads: [], named: [], importers: [], edits: [], edit: null, current: null };
var FRAME_MS = 40;
var FLASH_MS = 600;
var RIPPLE_MS = 1200;
var NAME_MAX = 18;
var FLASH_LIFT = 0.6;
var keyOf2 = (layout, path) => layout.caseInsensitive ? path.toLowerCase() : path;
function indices(layout, paths, lowered = false) {
  const out = [];
  for (const p of paths) {
    const i = lowered ? layout.lower.get(p) : layout.index.get(keyOf2(layout, p));
    if (i !== void 0) out.push(i);
  }
  return out;
}
var one = (layout, path) => path === null ? null : layout.index.get(keyOf2(layout, path)) ?? null;
function notOnMap(layout, lit) {
  const all = new Set([...lit.hits, ...lit.reads, ...lit.importers, ...lit.edit === null ? [] : [lit.edit]].map((p) => keyOf2(layout, p)));
  return [...all].filter((p) => !layout.index.has(p)).length;
}
function litPixels(layout, f) {
  if (f.px1 > f.px0 && f.py1 > f.py0) return { x0: f.px0, y0: f.py0, x1: f.px1, y1: f.py1 };
  const x = Math.min(layout.width - 1, Math.max(0, Math.floor(f.rect.x + f.rect.w / 2)));
  const row2 = Math.min(layout.rows - 1, Math.max(0, Math.floor((f.rect.y + f.rect.h / 2) / 2)));
  return { x0: x, y0: row2 * 2, x1: x + 1, y1: row2 * 2 + 2 };
}
var ROW_TRIES = [0, 1, -1, 2, -2];
var rowIn = (layout, row2) => row2 >= 0 && row2 < layout.rows;
var spanIn = (layout, col, len) => col >= 0 && col + len <= layout.columns;
var inside = (layout, row2, col, len) => rowIn(layout, row2) && spanIn(layout, col, len);
function freeSpan(taken, layout, at, len) {
  if (!inside(layout, at.row, at.col, len)) return false;
  for (let c = at.col - 1; c <= at.col + len; c++) if (taken.has(at.row * layout.columns + c)) return false;
  return true;
}
function placeName(layout, taken, f, color2) {
  const text2 = fit(cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1)), NAME_MAX);
  const box2 = litPixels(layout, f);
  const mid = Math.floor((box2.y0 + box2.y1 - 1) / 4);
  const tries = ROW_TRIES.flatMap((dr) => [box2.x1 + 1, box2.x0 - text2.length - 1].map((col) => ({ row: mid + dr, col })));
  const at = tries.find((t) => freeSpan(taken, layout, t, text2.length));
  if (at === void 0) return null;
  for (let c = at.col; c < at.col + text2.length; c++) taken.add(at.row * layout.columns + c);
  return { ...at, text: text2, color: color2 };
}
function namesFor(layout, o) {
  const pal = MAP_PALETTES[layout.style.theme];
  const order = [...new Set([o.edit, o.current, ...[...o.reads].reverse()].filter((i) => i !== null))];
  const taken = /* @__PURE__ */ new Set();
  const hot = /* @__PURE__ */ new Set([o.edit, o.current]);
  return order.map((i) => placeName(layout, taken, layout.files[i], hot.has(i) ? pal.edit : TERMINAL_DEFAULT)).filter((n) => n !== null);
}
function resolveLit(layout, lit, selected = null) {
  const o = {
    hits: indices(layout, lit.hits),
    reads: indices(layout, lit.reads),
    // Flow keeps the files a reply named lowercased.
    named: indices(layout, lit.named, true),
    importers: indices(layout, lit.importers),
    edit: one(layout, lit.edit),
    current: one(layout, lit.current)
  };
  return { ...o, names: namesFor(layout, o), selected: one(layout, selected) };
}
function center(layout, f) {
  const b = litPixels(layout, f);
  return [Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2)];
}
function distance(layout, a, b) {
  const [ax, ay] = center(layout, a);
  const [bx, by] = center(layout, b);
  return Math.hypot(ax - bx, ay - by);
}
function rippleRadius(layout, overlay) {
  const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];
  if (!origin || overlay.importers.length === 0) return 0;
  return Math.max(...overlay.importers.map((i) => distance(layout, origin, layout.files[i]))) + 3;
}
function fillFile(p, f, color2) {
  const { width: width2 } = p.layout;
  const b = litPixels(p.layout, f);
  for (let y = b.y0; y < b.y1; y++) {
    p.px.fill(color2, y * width2 + b.x0, y * width2 + b.x1);
    p.marked.fill(1, y * width2 + b.x0, y * width2 + b.x1);
  }
}
function fillAll(p, files, color2) {
  for (const i of files) fillFile(p, p.layout.files[i], color2);
}
function paintRing(p, origin, reach, color2) {
  const [ox, oy] = center(p.layout, origin);
  const { width: width2, height } = p.layout;
  for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {
    for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width2 - 1, ox + reach); x++) {
      const d = Math.hypot(x - ox, y - oy);
      if (d <= reach && d > reach - 2) p.px[y * width2 + x] = mix(p.px[y * width2 + x], color2, 0.5);
    }
  }
}
function hitColor(pal, anim) {
  return anim?.kind === "flash" ? mix(pal.hit, pal.read, FLASH_LIFT * (1 - anim.t)) : pal.hit;
}
function reached(layout, overlay, reach) {
  const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];
  if (origin === void 0 || reach === Infinity) return overlay.importers;
  return overlay.importers.filter((i) => distance(layout, origin, layout.files[i]) <= reach);
}
function rippleReach(layout, overlay, anim) {
  return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;
}
var inRange = (v, n) => v >= 0 && v < n;
function set(p, x, y, color2) {
  if (!inRange(x, p.layout.width) || !inRange(y, p.layout.height)) return;
  p.px[y * p.layout.width + x] = color2;
  p.marked[y * p.layout.width + x] = 1;
}
function around(box2) {
  const out = [];
  for (let x = box2.x0 - 1; x <= box2.x1; x++) out.push([x, box2.y0 - 1], [x, box2.y1]);
  for (let y = box2.y0; y < box2.y1; y++) out.push([box2.x0 - 1, y], [box2.x1, y]);
  return out;
}
function paintSelection(p, f, color2) {
  for (const [x, y] of around(litPixels(p.layout, f))) set(p, x, y, color2);
}
function framePixels(layout, overlay, anim) {
  const p = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };
  const pal = MAP_PALETTES[layout.style.theme];
  const reach = rippleReach(layout, overlay, anim);
  fillAll(p, overlay.hits, hitColor(pal, anim));
  fillAll(p, overlay.named, pal.named);
  fillAll(p, reached(layout, overlay, reach), pal.importer);
  fillAll(p, overlay.reads, pal.read);
  fillAll(p, [overlay.edit, overlay.current].filter((i) => i !== null), pal.edit);
  const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];
  if (origin !== void 0 && reach < Infinity) paintRing(p, origin, reach, pal.importer);
  const selected = overlay.selected === null ? void 0 : layout.files[overlay.selected];
  if (selected !== void 0) paintSelection(p, selected, pal.ring);
  return { pixels: p.px, marked: p.marked };
}
function frameCells(layout, overlay, anim) {
  const { pixels, marked } = framePixels(layout, overlay, anim);
  return encodeCells(layout, pixels, marked, overlay.names);
}

// src/animator.ts
var Animator = class {
  anim = null;
  timer;
  blitting = false;
  stopped = false;
  io = null;
  /** The closures of the hook running now; the timer's next frame goes through them. */
  use(io) {
    this.io = io;
  }
  progress(now) {
    const a = this.anim;
    return a === null ? void 0 : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };
  }
  /**
   * Plays `kind` for `duration` ms, replacing whatever played. `redraw` false
   * when called from a render, which already draws the first step.
   */
  play(io, kind, duration, screen, redraw = true) {
    this.stop();
    if (this.stopped) return;
    this.io = io;
    this.anim = { kind, start: Date.now(), duration };
    if (redraw) io.redraw();
    this.timer = setInterval(() => this.tick(screen), FRAME_MS);
  }
  stop() {
    clearInterval(this.timer);
    this.timer = void 0;
    this.anim = null;
  }
  /** For good: a disposed session plays nothing more. */
  end() {
    this.stopped = true;
    this.stop();
  }
  /** A timer's frame: never throws out of the timer; a failure stops the animation. */
  tick(screen) {
    try {
      this.frame(screen);
    } catch (err) {
      this.failed(err);
    }
  }
  /** A failed frame: the animation stops and the failure goes to the debug log. */
  failed(err) {
    this.stop();
    this.io?.debug(`animation failed: ${String(err)}`);
  }
  frame(screen) {
    const step2 = this.progress(Date.now());
    const frame = step2 === void 0 ? null : screen(step2);
    const io = this.io;
    if (step2 === void 0 || frame === null || io === null) return this.stop();
    if (this.blitting) return;
    if (step2.t >= 1) this.stop();
    this.blitting = true;
    io.blit(frame.key, frame.cells, frame.columns, frame.rows).then((r) => r.deny === void 0 || this.refused(io, r.deny)).catch((err) => this.refused(io, String(err))).finally(() => {
      this.blitting = false;
    });
  }
  /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */
  refused(io, why) {
    io.debug(`blit refused: ${why}`);
    this.stop();
    if (!this.stopped) io.redraw();
  }
};

// src/model/replies.ts
var PARSE_CHARS = 64 * 1024;
var EXCERPT_CHARS = 2 * 1024;
var MAX_PATHS = 200;
var MAX_DEPTH = 6;
var isRec = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
var rec = (v) => isRec(v) ? v : {};
var str = (v) => typeof v === "string" && v !== "" ? v : null;
var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
var bool = (v) => typeof v === "boolean" ? v : null;
var count2 = (v) => Array.isArray(v) ? v.length : num(v);
function fact(what, n, of = null) {
  if (n === null) return [];
  return of !== null && of > n ? [{ what, n, of }] : [{ what, n }];
}
function sumOver(targets, read) {
  const found = targets.map(read).filter((n) => n !== null);
  return found.length === 0 ? null : found.reduce((a, b) => a + b, 0);
}
var targetsOf = (r) => Object.values(rec(r["targets"])).filter(isRec);
var flagged = (targets, key2) => targets.some((t) => key2 in t) ? targets.filter((t) => t[key2] === true).length : null;
function contextFacts(r) {
  const targets = targetsOf(r);
  const docs = targets.map((t) => rec(t["docs"]));
  const symbols = sumOver(docs, (d) => count2(d["symbols"]));
  const symbolTotal = sumOver(docs, (d) => num(rec(d["symbols_truncated"])["total"]) ?? count2(d["symbols"]));
  return [
    ...fact("targets", targets.length),
    ...fact("docs", docs.filter((d) => str(d["title"]) !== null).length || null),
    ...fact("symbols", symbols, symbolTotal),
    ...fact("callers", sumOver(targets, (t) => count2(t["callers"]))),
    ...fact("callees", sumOver(targets, (t) => count2(t["callees"]))),
    ...fact("decisions", sumOver(targets, (t) => count2(t["decisions"]))),
    ...fact("hotspots", flagged(targets, "hotspot") || null)
  ];
}
function riskFacts(r) {
  const targets = targetsOf(r);
  return [
    ...fact("targets", targets.length),
    ...fact("dependents", sumOver(targets, (t) => num(t["dependents_count"]))),
    ...fact("coChange", sumOver(targets, (t) => num(t["co_change_partners_total"]) ?? count2(t["co_change_partners"]))),
    ...fact("hotspots", flagged(targets, "is_hotspot") || null)
  ];
}
function answerFacts(r) {
  return [
    ...fact("citations", count2(r["citations"])),
    ...fact("bodies", count2(r["symbol_bodies"])),
    ...fact("rationale", count2(r["code_rationale"]), num(r["code_rationale_total"])),
    ...fact("guesses", count2(r["best_guesses"]))
  ];
}
function whyFacts(r) {
  const git2 = rec(r["git_archaeology"]);
  return [
    ...fact("decisions", count2(r["decisions"])),
    ...fact("rationale", count2(r["code_rationale"]), num(r["code_rationale_total"])),
    ...fact("commits", count2(git2["git_log"] ?? git2["file_commits"]))
  ];
}
function searchFacts(r) {
  return fact("results", count2(r["results"]));
}
function symbolFacts(r) {
  const start = num(r["start_line"]);
  const end = num(r["end_line"]);
  return [
    ...fact("lines", start !== null && end !== null && end >= start ? end - start + 1 : null),
    ...fact("callers", count2(r["callers"])),
    ...fact("callees", count2(r["callees"]))
  ];
}
function listFacts(r) {
  return Object.entries(r).filter(([key2, v]) => Array.isArray(v) && v.length > 0 && !key2.startsWith("_")).slice(0, 3).map(([key2, v]) => ({ what: key2, n: v.length }));
}
var READERS = {
  get_context: contextFacts,
  get_risk: riskFacts,
  get_answer: answerFacts,
  get_why: whyFacts,
  search_codebase: searchFacts,
  get_symbol: symbolFacts
};
function insideOf(tool, r) {
  const known = READERS[tool]?.(r) ?? [];
  return known.length > 0 ? known : listFacts(r);
}
function behindOf(r, meta) {
  const budget = rec(meta["response_budget"]);
  const used = num(budget["serialized_chars"]);
  const limit = num(budget["limit_chars"]);
  const completeness = rec(meta["completeness"]);
  const capped = bool(completeness["capped"]);
  return {
    commit: str(meta["indexed_commit"]),
    ageDays: num(meta["index_age_days"]),
    indexBehind: bool(meta["index_behind"]),
    verified: bool(r["verified"]),
    complete: bool(meta["complete"]) ?? (capped === null ? null : !capped),
    confidence: str(r["confidence"]),
    grounding: str(r["grounding"]),
    retrieval: str(r["retrieval_quality"]),
    budget: used !== null && limit !== null ? { used, limit } : null,
    omittedTokens: num(rec(meta["omitted"])["tokens"]),
    degraded: str(r["degraded"]) ?? str(meta["degraded"]),
    semantic: bool(meta["semantic_search"])
  };
}
var PATH_READERS = {
  path: (v, add) => add(v),
  file: (v, add) => add(v),
  file_path: (v, add) => add(v),
  citations: (v, add) => Array.isArray(v) ? v.forEach(add) : void 0,
  targets: (v, add) => isRec(v) ? Object.keys(v).forEach(add) : void 0
};
function walkPaths(v, depth, add) {
  if (depth > MAX_DEPTH) return;
  if (Array.isArray(v)) return v.forEach((item) => walkPaths(item, depth + 1, add));
  for (const [key2, value] of Object.entries(rec(v))) {
    if (key2 === "_meta") continue;
    PATH_READERS[key2]?.(value, add);
    walkPaths(value, depth + 1, add);
  }
}
function pathsOf(r) {
  const found = /* @__PURE__ */ new Set();
  walkPaths(r, 0, (p) => {
    if (typeof p === "string" && p !== "" && found.size < MAX_PATHS) found.add(p.replace(/\\/g, "/"));
  });
  return [...found];
}
var EMPTY_BEHIND = behindOf({}, {});
function utf8Bytes(text2) {
  return new TextEncoder().encode(text2).length;
}
function errorOf(body) {
  const err = body["error"];
  if (typeof err === "string") return err.split("\n")[0] ?? err;
  return str(rec(err)["message"]);
}
function summarizeBody(tool, body, bytes, excerpt = "") {
  const r = rec(body);
  const meta = rec(r["_meta"]);
  return {
    tool,
    bytes,
    parsed: true,
    inside: insideOf(tool, r),
    behind: behindOf(r, meta),
    paths: pathsOf(r),
    excerpt,
    error: errorOf(r)
  };
}
function summarizeReply(tool, text2) {
  const bytes = utf8Bytes(text2);
  const excerpt = text2.slice(0, EXCERPT_CHARS);
  const parsed = text2.length <= PARSE_CHARS ? parseObject(text2) : null;
  if (parsed === null) return unparsed(tool, text2, bytes, excerpt);
  const summary = summarizeBody(tool, resultOf(parsed), bytes, excerpt);
  return summary.error === null ? { ...summary, error: errorOf(parsed) } : summary;
}
function parseObject(text2) {
  try {
    const v = JSON.parse(text2);
    return isRec(v) ? v : null;
  } catch {
    return null;
  }
}
function resultOf(parsed) {
  const result = isRec(parsed["result"]) ? parsed["result"] : parsed;
  return isRec(parsed["_meta"]) && !isRec(result["_meta"]) ? { ...result, _meta: parsed["_meta"] } : result;
}
function unparsed(tool, text2, bytes, excerpt) {
  const first = text2.trim().split("\n")[0] ?? "";
  const error = text2.length <= PARSE_CHARS && first !== "" ? first : null;
  return { tool, bytes, parsed: false, inside: [], behind: EMPTY_BEHIND, paths: [], excerpt, error };
}

// src/model/flow.ts
var MAX_TURNS = 6;
var MAX_ACTIVITIES = 60;
var PROMPT_CHARS = 160;
var MAX_NAMED = 2e3;
var MAX_ARGS = 4;
var ARG_CHARS = 160;
var COMMAND_CHARS = 2e3;
var MAX_HIT_PATHS = 200;
var REPOWISE_TOOL = /^mcp__(?:repowise|plugin_repowise_repowise|claude_ai_repowise)__(\w+)$/i;
var OWN_CALL_PREFIX = "toolu_plugin_";
var initialFlow = {
  turns: [],
  earlier: { turns: 0, repowise: 0, reads: 0, edits: 0 },
  named: {},
  blast: {},
  open: null
};
var END_OF = { answer: "answer", aborted: "stopped", refusal: "failed", error: "failed" };
function turnEnd(reason, isAborted) {
  return END_OF[reason ?? ""] ?? (isAborted === true ? "stopped" : "answer");
}
function repowiseTool(name) {
  return REPOWISE_TOOL.exec(name)?.[1] ?? null;
}
var KIND_OF = {
  Read: "read",
  Edit: "edit",
  MultiEdit: "edit",
  Write: "edit",
  NotebookEdit: "edit",
  Grep: "search",
  Glob: "search",
  Bash: "shell"
};
var ARG_KEYS = ["targets", "query", "question", "id", "file_path", "notebook_path", "pattern", "path", "command", "url", "description"];
var PATH_ARGS = /* @__PURE__ */ new Set(["file_path", "notebook_path", "path"]);
function shortPath(path, root) {
  const slashed = path.replace(/\\/g, "/");
  if (root === null) return slashed;
  const base = root.replace(/\\/g, "/").replace(/\/+$/, "");
  const inside2 = slashed.toLowerCase().startsWith(`${base.toLowerCase()}/`);
  return inside2 ? slashed.slice(base.length + 1) : slashed;
}
function argValue(key2, v, root) {
  if (typeof v === "string") return (PATH_ARGS.has(key2) ? shortPath(v, root) : v.replace(/\s+/g, " ")).slice(0, ARG_CHARS);
  if (Array.isArray(v)) return v.map((x) => typeof x === "string" ? x : JSON.stringify(x)).join(", ").slice(0, ARG_CHARS);
  if (v === void 0 || v === null) return null;
  return JSON.stringify(v).slice(0, ARG_CHARS);
}
function compactArgs(e, root) {
  const out = [];
  for (const key2 of ARG_KEYS) {
    const value = argValue(key2, e[key2], root);
    if (value !== null && out.length < MAX_ARGS) out.push([key2, value]);
  }
  return out;
}
var lineCount = (s) => typeof s === "string" ? s.split("\n").length : null;
function editLines(e) {
  const written = e.tool === "Write" ? lineCount(e["content"]) : null;
  if (written !== null) return { written };
  const before = lineCount(e["old_string"]);
  const after = lineCount(e["new_string"]);
  return before !== null && after !== null ? { delta: after - before } : null;
}
function askedFiles(e, root) {
  const targets = e["targets"];
  const list2 = Array.isArray(targets) ? targets : [];
  return list2.filter((t) => typeof t === "string" && !t.includes("::")).map((t) => shortPath(t, root));
}
function isClaudeCall(e) {
  return typeof e.tool_use_id === "string" && typeof e.tool === "string" && !e.tool_use_id.startsWith(OWN_CALL_PREFIX);
}
function activityOf(e, at, root) {
  if (!isClaudeCall(e)) return null;
  const rw = repowiseTool(e.tool);
  const kind = rw !== null ? "repowise" : KIND_OF[e.tool] ?? "other";
  return { ...BLANK, id: e.tool_use_id, kind, tool: rw ?? e.tool, agentId: agentOf(e), startedAt: at, args: compactArgs(e, root), ...BY_KIND[kind](e, root) };
}
var BLANK = {
  endedAt: null,
  paths: [],
  asked: [],
  command: null,
  isError: false,
  bytes: null,
  reply: null,
  namedBy: null,
  lines: null,
  hits: null,
  hitPaths: []
};
var agentOf = (e) => typeof e.agentId === "string" ? e.agentId : null;
function fileOf(e, root) {
  const file = e["file_path"] ?? e["notebook_path"];
  return { paths: typeof file === "string" ? [shortPath(file, root)] : [] };
}
function commandOf(e) {
  const command = e["command"];
  return { command: typeof command === "string" ? command.slice(0, COMMAND_CHARS) : null };
}
var BY_KIND = {
  repowise: (e, root) => ({ ...fileOf(e, root), asked: askedFiles(e, root) }),
  read: fileOf,
  edit: (e, root) => ({ ...fileOf(e, root), lines: editLines(e) }),
  search: fileOf,
  shell: (e) => commandOf(e),
  other: fileOf
};
function searchHits(outcome, root) {
  const result = outcome?.result;
  if (typeof result !== "object" || result === null) return { hits: null, hitPaths: [] };
  if (!Array.isArray(result.filenames)) return { hits: typeof result.numFiles === "number" ? result.numFiles : null, hitPaths: [] };
  const names2 = result.filenames.filter((f) => typeof f === "string");
  return { hits: names2.length, hitPaths: names2.slice(0, MAX_HIT_PATHS).map((f) => shortPath(f, root)) };
}
function outcomeText(outcome) {
  const text2 = outcome?.text;
  return typeof text2 === "string" ? text2 : null;
}
function toolEnded(e, outcome, at, root) {
  if (!isClaudeCall(e)) return null;
  const rw = repowiseTool(e.tool);
  const text2 = outcomeText(outcome);
  const isError = outcome === null || outcome?.isError === true;
  const summary = rw === null || text2 === null ? null : summarizeReply(rw, text2);
  const reply = summary === null ? null : { ...summary, paths: summary.paths.map((p) => shortPath(p, root)) };
  const bytes = summary?.bytes ?? (text2 === null ? null : new TextEncoder().encode(text2).length);
  return { type: "toolEnded", id: e.tool_use_id, at, isError, bytes, reply, ...searchHits(outcome, root) };
}
function pathKey(path) {
  return path.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();
}
function namingOf(named2, path) {
  return named2[pathKey(path)] ?? null;
}
function withNamed(named2, paths, naming) {
  let out = named2;
  let size = Object.keys(named2).length;
  for (const p of paths) {
    const key2 = pathKey(p);
    if (out[key2] !== void 0 || size >= MAX_NAMED) continue;
    if (out === named2) out = { ...named2 };
    out[key2] = naming;
    size++;
  }
  return out;
}
var isFile = (a) => a.kind === "read" || a.kind === "edit";
var isAnswered = (a) => a.kind === "repowise" && a.endedAt !== null && !a.isError;
function turnTotals(turn) {
  const files = turn.activities.filter(isFile);
  const keys = (list2) => new Set(list2.map((a) => pathKey(a.paths[0] ?? "")));
  const answered = turn.activities.filter(isAnswered);
  const edits = files.filter((a) => a.kind === "edit");
  return {
    repowise: turn.activities.filter((a) => a.kind === "repowise").length,
    answered: answered.length,
    answeredMs: answered.reduce((ms, a) => ms + a.endedAt - a.startedAt, 0),
    reads: keys(files.filter((a) => a.kind === "read")).size,
    edits: keys(edits).size,
    opened: keys(files).size,
    named: keys(files.filter((a) => a.namedBy !== null)).size,
    editNamed: edits.some((a) => a.namedBy !== null)
  };
}
function fold(earlier, turn) {
  const t = turnTotals(turn);
  return { turns: earlier.turns + 1, repowise: earlier.repowise + t.repowise, reads: earlier.reads + t.reads, edits: earlier.edits + t.edits };
}
function withTurn(state2, turn) {
  const turns = [...state2.turns, turn];
  if (turns.length <= MAX_TURNS) return { ...state2, turns };
  const gone = turns.shift();
  return { ...state2, turns, earlier: fold(state2.earlier, gone) };
}
var INJECTED = /\s*<\\?((?:agent-message|system-reminder|task-notification|local-command-[\w-]+|command-[\w-]+))\b[^>]*>[\s\S]*?(?:<\/\1>|$)\s*/g;
function userWords(text2) {
  return text2.replace(INJECTED, " ").trim();
}
function newTurn(state2, turnId, prompt, at) {
  const seq = (state2.turns.at(-1)?.seq ?? state2.earlier.turns) + 1;
  return { seq, turnId, prompt: userWords(prompt).slice(0, PROMPT_CHARS), startedAt: at, endedAt: null, durationMs: null, end: null, activities: [], dropped: 0 };
}
function openTurn(state2, at) {
  const last = state2.turns.at(-1);
  return last !== void 0 && last.endedAt === null ? state2 : withTurn(state2, newTurn(state2, null, "", at));
}
function mapLast(state2, f) {
  const last = state2.turns.at(-1);
  const next = last === void 0 ? last : f(last);
  return next === last ? state2 : { ...state2, turns: [...state2.turns.slice(0, -1), next] };
}
function mapActivity(state2, id, f) {
  const i = state2.turns.findIndex((t) => t.activities.some((a) => a.id === id));
  if (i < 0) return state2;
  const turn = state2.turns[i];
  const activities = turn.activities.map((a) => a.id === id ? f(a) : a);
  const turns = state2.turns.map((t, j) => j === i ? { ...turn, activities } : t);
  return { ...state2, turns };
}
function pushActivity(t, activity) {
  const all = [...t.activities, activity];
  const over = all.length - MAX_ACTIVITIES;
  return over > 0 ? { ...t, activities: all.slice(over), dropped: t.dropped + over } : { ...t, activities: all };
}
function append(state2, activity) {
  return mapLast(openTurn(state2, activity.startedAt), (t) => pushActivity(t, activity));
}
function closeTurn(state2, at, durationMs, end) {
  return mapLast(state2, (t) => t.endedAt !== null ? t : { ...t, endedAt: at, durationMs: durationMs ?? at - t.startedAt, end });
}
function started(state2, activity) {
  const namedBy = isFile(activity) && activity.paths[0] !== void 0 ? namingOf(state2.named, activity.paths[0]) : null;
  return append(state2, { ...activity, namedBy });
}
function ended(state2, action) {
  const { id, at, isError, bytes, reply, hits, hitPaths } = action;
  const next = mapActivity(state2, id, (a) => ({ ...a, endedAt: at, isError, bytes, reply, hits, hitPaths }));
  if (next === state2 || reply === null || isError) return next;
  const turn = next.turns.find((t) => t.activities.some((a) => a.id === id));
  return { ...next, named: withNamed(next.named, reply.paths, { id, tool: reply.tool, at, turn: turn.seq }) };
}
function openable(state2) {
  return state2.turns.flatMap((t) => t.activities.filter((a) => a.kind === "repowise").map((a) => a.id));
}
function stepped(state2, by) {
  const ids2 = openable(state2);
  if (ids2.length === 0) return state2;
  const at = state2.open === null ? -1 : ids2.indexOf(state2.open);
  const i = at < 0 ? by === 1 ? 0 : ids2.length - 1 : Math.min(ids2.length - 1, Math.max(0, at + by));
  return ids2[i] === state2.open ? state2 : { ...state2, open: ids2[i] };
}
function reduceFlow(state2, action) {
  switch (action.type) {
    case "turnStarted": {
      const closed = closeTurn(state2, action.at, null, "stopped");
      return withTurn(closed, newTurn(closed, action.turnId, action.prompt, action.at));
    }
    case "turnEnded":
      return closeTurn(state2, action.at, action.durationMs, action.end);
    case "toolStarted":
      return started(state2, action.activity);
    case "toolEnded":
      return ended(state2, action);
    case "blastLanded":
      return { ...state2, blast: { ...state2.blast, [pathKey(action.path)]: action.facts } };
    case "toggle":
      return { ...state2, open: state2.open === action.id ? null : action.id };
    case "step":
      return stepped(state2, action.by);
  }
}
function visits(state2) {
  const out = [];
  let order = 0;
  const steps = state2.turns.flatMap((t) => t.activities.map((a) => [a, t.seq]));
  for (const [a, turn] of steps) {
    const found = visitsOf(a, turn, order + 1);
    if (found.length > 0) order++;
    out.push(...found);
  }
  return out;
}
function visitsOf(a, turn, order) {
  if (a.isError) return [];
  if (a.kind === "search") return a.hitPaths.map((path2) => ({ path: path2, kind: "search-hit", order, at: a.endedAt ?? a.startedAt, turn }));
  const path = a.paths[0];
  return (a.kind === "read" || a.kind === "edit") && path !== void 0 ? [{ path, kind: a.kind, order, at: a.startedAt, turn }] : [];
}
function isWorking(state2) {
  const last = state2.turns.at(-1);
  return last !== void 0 && last.endedAt === null;
}
function inFlight(state2) {
  return state2.turns.at(-1)?.activities.find((a) => a.kind === "repowise" && a.endedAt === null) ?? null;
}

// src/model/turnFacts.ts
var COCHANGE_SHOWN = 2;
var GENERIC = /* @__PURE__ */ new Set(["test", "tests", "spec", "specs", "__init__"]);
var TEST_RUNNER = /\b(?:pytest|py\.test|manage\.py test|runtests|npm (?:run )?test|vitest|jest|go test|cargo test)\b/;
function testsOf(file) {
  if (file === void 0) return null;
  const measured = file.measured_tests_total ?? 0;
  if (measured > 0) return { total: measured, files: file.measured_tests ?? [], basis: "measured" };
  const inferred = file.inferred_tests_total ?? 0;
  return inferred > 0 ? { total: inferred, files: file.inferred_tests ?? [], basis: "inferred" } : null;
}
function blastFacts(path, r) {
  const key2 = pathKey(path);
  const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key2);
  const cochange = (r.cochange_warnings ?? []).filter((w) => pathKey(w.changed) === key2).map((w) => ({ path: w.missing_partner, score: w.score })).sort((a, b) => b.score - a.score);
  const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key2));
  return { importers, cochange, tests };
}
var allActivities = (state2) => state2.turns.flatMap((t) => t.activities);
function openedKeys(state2) {
  return new Set(allActivities(state2).filter(isFile).map((a) => pathKey(a.paths[0] ?? "")));
}
function testCommands(state2) {
  return allActivities(state2).map((a) => a.command).filter((c) => c !== null && TEST_RUNNER.test(c));
}
var asWord = (command, word) => !GENERIC.has(word) && new RegExp(`(^|[^\\w])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^\\w])`).test(command);
function names(command, test) {
  const slashed = test.replace(/\\/g, "/");
  const parts = slashed.split("/");
  const stem = (parts.at(-1) ?? "").replace(/\.[^.]+$/, "");
  const folder = parts.at(-2) ?? "";
  const cmd = command.replace(/\\/g, "/");
  return cmd.includes(slashed) || asWord(cmd, stem) || asWord(cmd, folder);
}
function testsRun(state2, tests) {
  const commands = testCommands(state2);
  return tests.filter((t) => commands.some((c) => names(c, t))).length;
}
function gapsOf(state2, path, facts, opened) {
  const seen = facts.importers.filter((p) => opened.has(pathKey(p))).length;
  const t = facts.tests;
  const run = t === null ? 0 : testsRun(state2, t.files);
  return {
    path,
    importers: facts.importers.length > seen ? { total: facts.importers.length, opened: seen } : null,
    cochange: facts.cochange.filter((c) => !opened.has(pathKey(c.path))).slice(0, COCHANGE_SHOWN),
    tests: t !== null && run < t.total ? { total: t.total, run, basis: t.basis } : null
  };
}
var hasGap = (g) => g.importers !== null || g.cochange.length > 0 || g.tests !== null;
function editedFiles(turn) {
  const out = /* @__PURE__ */ new Map();
  for (const a of turn.activities) {
    const path = a.kind === "edit" && !a.isError ? a.paths[0] : void 0;
    if (path !== void 0 && !out.has(pathKey(path))) out.set(pathKey(path), path);
  }
  return [...out.values()];
}
function beforeAccept(state2, turn) {
  const opened = openedKeys(state2);
  return editedFiles(turn).map((path) => [path, state2.blast[pathKey(path)]]).filter((pair) => pair[1] !== void 0).map(([path, facts]) => gapsOf(state2, path, facts, opened)).filter(hasGap);
}
function searchedBefore(state2, key2, at) {
  return allActivities(state2).some((a) => a.kind === "search" && a.startedAt < at && a.hitPaths.some((p) => pathKey(p) === key2));
}
function viaOf(state2, first) {
  if (first.namedBy !== null) return { kind: "repowise", tool: first.namedBy.tool };
  return searchedBefore(state2, pathKey(first.paths[0] ?? ""), first.startedAt) ? { kind: "search" } : { kind: "direct" };
}
function workingSet(state2, turn) {
  const first = /* @__PURE__ */ new Map();
  const edited = /* @__PURE__ */ new Set();
  for (const a of turn.activities.filter((x) => isFile(x) && !x.isError && x.paths[0] !== void 0)) {
    const key2 = pathKey(a.paths[0]);
    if (!first.has(key2)) first.set(key2, a);
    if (a.kind === "edit") edited.add(key2);
  }
  const rows = [...first].map(([key2, a]) => ({ path: a.paths[0], kind: edited.has(key2) ? "edited" : "read", via: viaOf(state2, a) }));
  return [...rows.filter((r) => r.kind === "edited"), ...rows.filter((r) => r.kind === "read")];
}
var CONTEXT_KINDS = ["repowise", "read", "search", "shell", "other"];
var CONTEXT_OF = {
  repowise: "repowise",
  read: "read",
  search: "search",
  shell: "shell",
  edit: "other",
  other: "other"
};
function contextBytes(turn) {
  const out = { repowise: 0, read: 0, search: 0, shell: 0, other: 0 };
  for (const a of turn.activities) {
    const kind = CONTEXT_OF[a.kind];
    if (kind !== null && a.bytes !== null) out[kind] += a.bytes;
  }
  return out;
}
function firstEditMs(turn) {
  const edit = turn.activities.find((a) => a.kind === "edit");
  return edit === void 0 ? null : edit.startedAt - turn.startedAt;
}
function firstEdits(state2) {
  const out = /* @__PURE__ */ new Map();
  for (const a of allActivities(state2)) {
    const key2 = a.kind === "edit" && a.paths[0] !== void 0 ? pathKey(a.paths[0]) : null;
    if (key2 !== null && !out.has(key2)) out.set(key2, a.startedAt);
  }
  return out;
}
function answeredBeforeEdit(state2) {
  const edits = firstEdits(state2);
  const before = (a) => a.asked.some((p) => (edits.get(pathKey(p)) ?? Number.POSITIVE_INFINITY) < a.startedAt);
  return new Set(allActivities(state2).filter((a) => a.kind === "repowise" && before(a)).map((a) => a.id));
}

// src/views/copy.ts
var HINTS = {
  "no-server": "Lens map needs the local server: repowise serve --no-ui",
  auth: "local server needs an API key; Lens does not read keys",
  unlisted: "Lens map needs a local server for this repo: repowise serve --no-ui",
  "no-index": "index this repo for Lens: repowise init --no-prose --yes",
  "no-cli": "Lens needs the Repowise CLI: pip install repowise"
};
function freshnessLine(f) {
  const changed = f.changedFiles === null ? "" : ` (${countOf(f.changedFiles, "file", "files")} changed)`;
  return `index behind HEAD${changed} · repowise update`;
}
function spinnerLine(file, ctx) {
  const parts = [file.slice(file.lastIndexOf("/") + 1)];
  if (ctx.callerFiles) parts.push(countOf(ctx.callerFiles, "caller file", "caller files"));
  if (ctx.contributors) parts.push(countOf(ctx.contributors, "contributor", "contributors"));
  return parts.join(" · ");
}
function squeezeLine(s) {
  const parts = [`${countOf(s.originalLines, "line", "lines")} → ${s.keptLines.toLocaleString("en-US")}`];
  if (s.omittedTokens > 0) parts.push(`~${countOf(s.omittedTokens, "token", "tokens")} omitted`);
  const failures = [s.failed > 0 ? `${s.failed.toLocaleString("en-US")} failed` : "", s.errors > 0 ? countOf(s.errors, "error", "errors") : ""];
  if (s.failed + s.errors > 0) parts.push(failures.filter((f) => f !== "").join(", "));
  const more = s.refs.length > 1 ? ` (+${s.refs.length - 1} more)` : "";
  parts.push(`repowise expand ${s.refs[0]}${more}`);
  return parts.join(" · ");
}
function marginLine(note) {
  if (note.kind === "decision") {
    return note.reviewed ? `a standing decision covers this file: ${note.title}` : `a decision found in this file, not yet reviewed: ${note.title}`;
  }
  const where = note.symbol === null ? "" : `, mostly in ${note.symbol}`;
  return `fixed ${countOf(note.count, "time", "times")} in 6 months, most recently ${note.age}${where}`;
}
function savingsLine(d, columns) {
  const inferred = d.inferredTokens > 0 ? ` (${d.inferredTokens.toLocaleString("en-US")} inferred)` : "";
  const usd = d.usd >= 5e-3 ? ` · $${d.usd.toFixed(2)}` : "";
  const head = `${countOf(d.tokens, "token", "tokens")}${inferred}${usd} saved`;
  const full = `${head} since this session started · all agents on this repo`;
  return full.length <= columns ? full : `${head} this session · all agents`;
}
var REVIEWING = "Reviewing the change...";
var REVIEW_TIMEOUT_S = 20;
var REVIEW_TIMED_OUT = `Change review timed out after ${REVIEW_TIMEOUT_S} s`;
var RUN_TESTS = "Run tests";
var WHY = "Why";
var DETAILS = "Details";
var OVERLAP_MARK = "◦";
function reviewFailed(message) {
  return `Change review could not run: ${message}`;
}
function reviewScope(ref, workingTree, changed) {
  const where = workingTree ? ref : `${ref} (no uncommitted changes)`;
  return changed === null ? where : `${where}, ${countOf(changed, "changed file", "changed files")}`;
}
function noNewFindings(analyzed) {
  return `no new findings in ${analyzed === 1 ? "the 1 changed file" : `all ${analyzed.toLocaleString("en-US")} changed files`}`;
}
function healthImproved(resolved) {
  return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;
}
var HEALTH_NOT_REPORTED = "not reported";
var NO_NEW_FINDINGS = "no new findings";
var PARTLY_COMPARED = "partly compared, no new findings";
function notCompared(why) {
  return why === "" ? "not compared" : `not compared: ${why}`;
}
function improvedShort(resolved) {
  return `improved, ${resolved.toLocaleString("en-US")} resolved`;
}
function newFindings(total2, required2) {
  return `${countOf(total2, "new finding", "new findings")}, ${required2 ? "review required" : "low severity"}`;
}
function resolvedToo(resolved) {
  return `${countOf(resolved, "finding", "findings")} resolved`;
}
function findingLine(f) {
  const at = f.lines === void 0 ? f.path : `${f.path}:${f.lines[0]}`;
  return `${f.severity} ${f.biomarker}: ${f.reason} (${at})`;
}
function moreFindings(more) {
  return `and ${more.toLocaleString("en-US")} more (Details)`;
}
function partialScope(analyzed, changed, reasons) {
  const why = Object.entries(reasons).map(([reason, n]) => `${n.toLocaleString("en-US")} ${reason.replace(/_/g, " ")}`).join(", ");
  const skipped = changed - analyzed;
  return `Scope: compared ${analyzed.toLocaleString("en-US")} of ${countOf(changed, "changed file", "changed files")}; ${skipped.toLocaleString("en-US")} not analysed${why ? ` (${why})` : ""}, so this is not a clean bill`;
}
function diffShape(percentile) {
  const where = percentile === null || percentile === void 0 ? "not ranked (no recent commits to compare)" : `bigger than ${Math.round(percentile)}% of this repo's recent commits`;
  return `Diff shape: ${where}; size, not danger`;
}
function testsBasis(measured) {
  return measured ? "measured by stored coverage" : "inferred from the dependency graph, not measured";
}
function runAllLine(reason) {
  return reason ? `Run every test: ${reason}` : "Run every test";
}
function testsLine(t) {
  if (t.runAll != null) {
    const first = t.tests.length ? `; first: ${t.tests.join(", ")}` : "";
    return `${runAllLine(t.runAll)}${first}`;
  }
  const count3 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");
  const shown = t.truncated ? ` (first ${t.tests.length.toLocaleString("en-US")} shown)` : "";
  return `Tests to run: ${count3}, ${testsBasis(t.measured)}${shown}: ${t.tests.join(", ")}`;
}
function overlapLine(branches, files, more) {
  const who = countOf(branches.length, "other branch", "other branches") + (more ? " or more" : "");
  const what = files.length === 1 ? files[0] : countOf(files.length, "changed file", "changed files");
  const verb = branches.length === 1 && !more ? "edits" : "edit";
  return `${OVERLAP_MARK} ${who} also ${verb} ${what} (${branches.join(", ")})`;
}
function overlapShort(branches) {
  return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;
}
function directiveLines(d) {
  const out = [`Change review: ${d.status.replace(/_/g, " ")}`, d.headline];
  if (d.reasons?.length) out.push("Reasons:", ...d.reasons.map((r) => `  ${r}`));
  if (d.next_actions?.length) out.push("Next actions:", ...d.next_actions.map((a) => `  ${a}`));
  return out;
}
function runTestsPrompt(t) {
  if (t.runAll != null) {
    const first = t.tests.length ? `, starting with ${t.tests.join(" ")}` : "";
    return `Run the whole test suite for this change${first}. Repowise cannot vouch for a smaller set: ${t.runAll}`;
  }
  const rest = t.truncated ? ` (the first ${t.tests.length} of ${t.total})` : "";
  return `Run the tests Repowise names for this change${rest}, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
}
var MAP_COPY = {
  title: "Lens",
  looking: "Lens map: looking for the local server",
  loading: "Lens map: loading the map",
  failed: "Lens map could not load; it tries again on /lens",
  desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",
  tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",
  noScore: "Not scored",
  waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens",
  healthOn: "Health colours: on",
  healthOff: "Health colours: off",
  quiet: "Nothing lit yet this turn. Files Claude searches, opens and edits light up here."
};
var STORY_COPY = {
  searched: "SEARCHED",
  opened: "OPENED",
  edited: "EDITED",
  reaches: "REACHES"
};
function mapAlt(drawn) {
  return `Map of the repo: ${countOf(drawn, "file", "files")} drawn as tiles, with the files Claude searched, opened and edited this turn lit, and the files that import its edit`;
}
function notPlacedLine(reason) {
  return `Lens map needs a wider terminal: ${reason}`;
}
var SCOPE_REST = "rest too small to draw";
function indexedPart(age) {
  return `indexed ${age}`;
}
function cappedPart(s) {
  const largest = `${formatNumber(s.shown)} largest of ${countOf(s.repositoryTotal, "file", "files")}`;
  if (s.dense) return [`${largest}; drawn as folders at this size`];
  if (s.drawn >= s.shown) return [`${largest} drawn`];
  return [`${formatNumber(s.drawn)} of the ${formatNumber(s.shown)} largest (of ${countOf(s.repositoryTotal, "file", "files")}) drawn at this size`, SCOPE_REST];
}
function drawnPart(s) {
  if (s.beyondCap > 0) return cappedPart(s);
  if (s.dense) return [`${countOf(s.repositoryTotal, "file", "files")}, drawn as folders at this size`];
  if (s.drawn >= s.repositoryTotal) return [`${countOf(s.repositoryTotal, "file", "files")}, all drawn`];
  return [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];
}
function scopeParts(s) {
  const parts = drawnPart(s);
  if (s.indexed !== null) parts.push(indexedPart(s.indexed));
  if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} ${s.zoom === null ? "not on the map" : "outside this folder"}`);
  return parts;
}
function searchedPart(pattern, hits) {
  const count3 = hits === null ? "matches not counted" : countOf(hits, "file", "files");
  return pattern === "" ? `last search matched ${count3}` : `${pattern}: ${count3}`;
}
function linesPart(lines) {
  if (lines === null) return "";
  if ("written" in lines) return ` ${countOf(lines.written, "line", "lines")} written`;
  const sign = lines.delta > 0 ? "+" : lines.delta < 0 ? "-" : "";
  return ` ${sign}${countOf(Math.abs(lines.delta), "line", "lines")}`;
}
function namedByPart(name, tool) {
  return `◆ ${name} named by ${tool}`;
}
function reachesPart(total2, names2) {
  const shown = names2.map((n) => n.opened ? `${n.name} (opened)` : n.name);
  const more = total2 - names2.length;
  return `${countOf(total2, "importer", "importers")}: ${[...shown, ...more > 0 ? [`+${formatNumber(more)}`] : []].join(", ")}`;
}
function reachesPending(edit) {
  return `finding the files that import ${edit}`;
}
var REACHES_FAILED = "import graph unavailable";
var MAP_KEYS_COPY = {
  next: "next",
  previous: "previous",
  zoom: "zoom in",
  up: "up",
  clear: "clear"
};
function crumbLine(root) {
  return root.split("/").join(" / ");
}
function whyParts(why) {
  const parts = [];
  if (why.edited !== null) parts.push(`Claude edited it${why.edited.lines === null ? "" : `,${linesPart(why.edited.lines)}`}`);
  if (why.opened) parts.push("Claude opened it");
  if (why.imports !== null) parts.push(`imports ${why.imports}`);
  if (why.namedBy !== null) parts.push(`named by ${why.namedBy}`);
  return parts;
}
function detailLine(path, why, knows) {
  const facts = knows.context === null ? [] : knowsParts(knows.context);
  const tests = knows.tests === null ? [] : [testsReach(knows.tests)];
  return [path, ...whyParts(why), ...facts, ...tests].join(" · ");
}
function testsReach(t) {
  return `${countOf(t.total, "test reaches it", "tests reach it")} (${t.basis})`;
}
var PANE_COPY = {
  command: "Open Lens: Claude's steps with Repowise, the map of its turn, ask the index, and the session recap",
  argumentHint: "[flow | map | ask <question> | recap]",
  tabs: { flow: "Flow", map: "Map", ask: "Ask", recap: "Recap" },
  askLabel: "ask ",
  askPlaceholder: "why ...? asks the decision records; anything else asks the index",
  askSubmit: "ask",
  askIdle: "Ask about this repo. Answers cite the evidence they used.",
  askBusy: "still answering the last question; ask again when it lands",
  noEvidence: "no evidence cited",
  fromIndex: "Built from the index",
  fromModel: "Written by this repo's configured model, from the index",
  bodyFailed: "Lens could not draw this tab; details in the debug log"
};
var ASK_CHARS = 4e3;
function askingLine(tool) {
  return tool === "get_why" ? "asking the decision records..." : "asking the index...";
}
function askFailedLine(message) {
  return `Could not answer: ${message}`;
}
function askCut(chars) {
  return `reply cut at ${formatNumber(chars)} characters`;
}
function moreRows(more) {
  return `and ${formatNumber(more)} more`;
}
var RECAP_COPY = {
  files: "Files",
  fromReview: "from the last change review",
  review: "Change review",
  health: "Code health",
  findings: "Findings",
  tests: "Tests to run",
  overlap: "Branches overlapping",
  saved: "Saved",
  decisions: "Decisions surfaced",
  noReview: "none this session",
  notCompared: "not compared",
  noTests: "none named",
  noOverlap: "none found",
  notReported: "not reported",
  noSavings: "nothing yet since this session started",
  savingsNeedServer: "needs the local server: repowise serve --no-ui",
  noDecisions: "none",
  noModel: "Lens made no model calls.",
  fromIndex: "Every figure here is read from the local index."
};
function filesTouched(edited, touched) {
  const all = touched.capped ? `${formatNumber(touched.count)}+` : formatNumber(touched.count);
  return `${formatNumber(edited)} edited of ${all} ${touched.count === 1 && !touched.capped ? "file" : "files"} touched`;
}
function findingsCounts(resolved, total2) {
  return `${formatNumber(resolved)} resolved · ${countOf(total2, "new finding", "new findings")}`;
}
function testsToRunCount(t) {
  if (t.runAll != null) return "every test";
  const count3 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");
  return `${count3}, ${t.measured ? "measured" : "inferred"}`;
}
function decisionsSurfaced(titles) {
  return `${formatNumber(titles.length)}: ${titles.join("; ")}`;
}
function recapFooter(modelAsks) {
  if (modelAsks === 0) return `${RECAP_COPY.noModel} ${RECAP_COPY.fromIndex}`;
  const asks = countOf(modelAsks, "Ask reply", "Ask replies");
  return `${RECAP_COPY.noModel} ${asks} from get_answer may have been written by this repo's configured model.`;
}
var BRIEF_COPY = {
  compacted: "context compacted",
  button: "Brief Claude",
  intro: "The context was compacted. This brief is built from the Repowise index and this session's edits:",
  files: "Files edited:",
  decisions: "Decisions in play:",
  review: "Open review items:"
};
var BRIEF_CHARS = 1200;
function briefDecision(title, reviewed) {
  return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;
}
function briefTests(t) {
  if (t.runAll != null) return runAllLine(t.runAll).replace(/^Run/, "run");
  return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
}
var FLOW_COPY = {
  waiting: "Waiting for Claude",
  empty: "Lens is listening. Send a prompt and this tab shows what only Lens sees: what an edit reaches, where Claude's context came from, and what Repowise answered.",
  notConnected: "Repowise is not connected in this repo, so only Claude's own steps show here.",
  beforeAccept: "BEFORE YOU ACCEPT",
  workingSet: "WORKING SET",
  context: "CONTEXT",
  calls: "REPOWISE CALLS",
  asOfIndex: "as of the last index",
  edited: "edited",
  read: "read",
  search: "search",
  direct: "direct",
  hotspot: "hotspot",
  subagent: "subagent",
  asking: "asking...",
  error: "error",
  beforeEdit: "from the index before this edit",
  howAnswered: "how it was answered",
  excerpt: "reply begins",
  thenOpened: "Claude then opened",
  nothingOpened: "nothing yet",
  noRepowise: "No Repowise calls",
  editNamed: "edit landed in a file Repowise named",
  next: "Next call",
  previous: "Previous call"
};
function clockText(ms) {
  const s = Math.max(0, Math.floor(ms / 1e3));
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}
function durationText(ms) {
  if (ms < 1e3) return `${Math.max(0, Math.round(ms))} ms`;
  if (ms < 1e4) return `${(ms / 1e3).toFixed(1)} s`;
  const s = Math.round(ms / 1e3);
  return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;
}
function sizeText(bytes) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
var END_WORD = { answer: "Done", stopped: "Stopped", failed: "Did not finish" };
function statusLine(end, ms, edited) {
  const head = end === null ? `Working · ${clockText(ms)}` : `${END_WORD[end]} · ${durationText(ms)}`;
  return edited === 0 ? head : `${head} · edited ${countOf(edited, "file", "files")}`;
}
function answerLine(t) {
  const parts = [t.repowise === 0 ? FLOW_COPY.noRepowise : `Repowise ${countOf(t.repowise, "call", "calls")}`];
  const named2 = t.named > 0 ? `, ${formatNumber(t.named)} named by Repowise first` : "";
  if (t.opened > 0) parts.push(`Claude opened ${countOf(t.opened, "file", "files")}${named2}`);
  if (t.editNamed) parts.push(FLOW_COPY.editNamed);
  return parts.join(" · ");
}
function importersLine(total2, opened) {
  return `${countOf(total2, "direct importer", "direct importers")}; Claude opened ${opened === 0 ? "none" : formatNumber(opened)}`;
}
function cochangeLine(partners) {
  return `not opened, usually changes with it (co-change score): ${partners.map((p) => `${p.path} ${p.score.toFixed(2)}`).join(", ")}`;
}
function testsReachLine(total2, basis, run, file) {
  return `${countOf(total2, "test file", "test files")} reach ${file} (${basis}); ${run === 0 ? "none" : formatNumber(run)} run`;
}
function introducedLine(n, first) {
  const what = first === null ? "" : `: ${first.biomarker.replace(/_/g, " ")} in ${first.path.split("/").at(-1)}`;
  return `this turn introduced ${countOf(n, "finding", "findings")}${what}`;
}
var HEALTH_PARTLY = "health compared in part only; no new findings in the part compared";
function knowsParts(k) {
  const parts = [];
  if (k.hotspot === true) parts.push(FLOW_COPY.hotspot);
  if (k.callerFiles !== null && k.callerFiles > 0) parts.push(countOf(k.callerFiles, "file uses it", "files use it"));
  if (k.recentOwner !== null) parts.push(`recent owner ${k.recentOwner.name} ${Math.round(k.recentOwner.share * 100)} %`);
  return parts;
}
function moreFiles(n) {
  return `+${formatNumber(n)} more`;
}
var CONTEXT_LABEL = { repowise: "Repowise", read: "file reads", search: "search", shell: "shell", other: "other" };
function contextPart(kind, bytes) {
  return `${CONTEXT_LABEL[kind]} ${sizeText(bytes)}`;
}
function firstEditText(ms) {
  return `first edit after ${durationText(ms)}`;
}
function turnFooter(turn, ms, t, end = "answer") {
  const how = end === null || end === "answer" ? "" : ` · ${END_WORD[end].toLowerCase()}`;
  const took = ms === null ? "" : ` · ${durationText(ms)}`;
  return `Turn ${turn}${how}${took} · ${countOf(t.repowise, "Repowise call", "Repowise calls")} · ${countOf(t.reads, "file read", "files read")} · ${formatNumber(t.edits)} edited`;
}
function earlierLine(t) {
  return `Earlier: ${countOf(t.turns, "turn", "turns")} · ${countOf(t.repowise, "Repowise call", "Repowise calls")} · ${countOf(t.reads, "file read", "files read")} · ${formatNumber(t.edits)} edited`;
}
function hiddenSteps(n) {
  return `${countOf(n, "earlier call", "earlier calls")} hidden · j / k step through calls`;
}
function laterSteps(n) {
  return `${countOf(n, "later call", "later calls")} below · j / k step through calls`;
}
function droppedSteps(n) {
  return `${countOf(n, "earlier step", "earlier steps")} of this turn not kept`;
}
var INSIDE_UNITS = {
  targets: ["target", "targets"],
  docs: ["documentation page", "documentation pages"],
  symbols: ["symbol", "symbols"],
  callers: ["caller", "callers"],
  callees: ["callee", "callees"],
  decisions: ["decision", "decisions"],
  hotspots: ["hotspot", "hotspots"],
  dependents: ["direct dependent", "direct dependents"],
  coChange: ["co-change partner", "co-change partners"],
  contributors: ["contributor", "contributors"],
  citations: ["cited file", "cited files"],
  bodies: ["symbol body", "symbol bodies"],
  rationale: ["rationale comment", "rationale comments"],
  guesses: ["best guess", "best guesses"],
  commits: ["commit", "commits"],
  results: ["result", "results"],
  lines: ["line", "lines"]
};
function insideFact(f) {
  const [one2, many] = INSIDE_UNITS[f.what] ?? [f.what.replace(/_/g, " "), f.what.replace(/_/g, " ")];
  return f.of === void 0 ? countOf(f.n, one2, many) : `${formatNumber(f.n)} of ${countOf(f.of, one2, many)}`;
}
function freshnessText(b) {
  if (b.indexBehind !== null) return b.indexBehind ? "index behind HEAD" : "index current";
  return b.ageDays === null ? null : `index ${countOf(b.ageDays, "day", "days")} old`;
}
var ageText = (days) => `index ${countOf(days, "day", "days")} old`;
var when = (shown, text2) => shown ? text2 : null;
var named = (v, text2) => v === null ? null : text2(v);
var BEHIND = [
  (b) => named(b.commit, (c) => `indexed at ${c}`),
  (b) => named(b.ageDays, ageText),
  (b) => named(b.verified, (v) => v ? "verified against the code" : "not verified"),
  (b) => when(b.complete === false, "partial: the server capped it"),
  (b) => named(b.confidence, (c) => `confidence ${c}`),
  (b) => named(b.grounding, (g) => `grounding ${g.replace(/_/g, " ")}`),
  (b) => named(b.retrieval, (r) => `retrieval ${r}`),
  (b, bytes) => named(b.budget, (budget) => `reply ${bytes === null ? countOf(budget.used, "character", "characters") : sizeText(bytes)} (cap ${countOf(budget.limit, "character", "characters")})`),
  (b) => named(b.omittedTokens, (t) => `${countOf(t, "token", "tokens")} left out, restorable`),
  (b) => named(b.degraded, (d) => `degraded: ${d}`),
  (b) => when(b.semantic === false, "semantic search off")
];
function behindParts(b, bytes = null) {
  return BEHIND.map((part) => part(b, bytes)).filter((p) => p !== null);
}

// src/views/elements.ts
function text(value, props = {}) {
  return { type: "Text", props, children: [value] };
}
function box(props, children) {
  return { type: "Box", props, children };
}
function button(key2, hotkey, label, dimColor = false) {
  return { type: "Button", props: { key: key2, label, hotkey, plain: true, ...dimColor ? { dimColor } : {} } };
}
function raster(props) {
  return { type: "Raster", props };
}
function input(props) {
  return { type: "Input", props };
}
function markdown(text2) {
  return { type: "Markdown", props: { text: text2 } };
}
function svg(source, alt) {
  return { type: "Svg", props: { source, alt } };
}
var SUBMIT_IN_HOOK = () => void 0;
function pressFor(key2, presses) {
  const onPress = presses[key2];
  if (!onPress) throw new Error(`button ${key2} has no action`);
  return onPress;
}
var PROPS = {
  Text: (n) => ({ ...n.props, children: n.children }),
  Box: (n, table, presses) => ({ ...n.props, children: n.children.map((child) => materialize(child, table, presses)) }),
  Button: (n, _table, presses) => ({ ...n.props, onPress: pressFor(n.props.key, presses) }),
  Input: (n) => ({ ...n.props, onSubmit: SUBMIT_IN_HOOK }),
  Raster: (n) => ({ ...n.props }),
  Markdown: (n) => ({ ...n.props }),
  Svg: (n) => ({ ...n.props })
};
function materialize(node, table, presses = {}) {
  const build = table[node.type];
  if (!build) throw new Error(`element ${node.type} is not on this surface`);
  return build(PROPS[node.type](node, table, presses));
}

// src/views/mapPane.ts
var MAP_KEY = "lens-map";
var HEALTH_KEY = "lens-map-health";
var MAP_KEYS = {
  next: { key: "lens-map-next", hotkey: "j" },
  previous: { key: "lens-map-previous", hotkey: "k" },
  zoom: { key: "lens-map-zoom", hotkey: "z" },
  up: { key: "lens-map-up", hotkey: "u" },
  clear: { key: "lens-map-clear", hotkey: "x" }
};
var MAP_PRESSES = [...Object.values(MAP_KEYS).map((k) => k.key), HEALTH_KEY];
var MAX_COLUMNS = 512;
var MAX_ROWS = 256;
var MIN_ROWS = 4;
var GAP = 2;
var SEP = " · ";
var CRUMB_ROWS = 1;
var STORY_ROWS = 4;
var DETAIL_ROWS = 1;
var SCOPE_ROWS = 2;
var KEY_ROWS = 1;
var HEAD = 10;
var REACH_NAMES = 3;
var INLINE_ROWS_PER_COLUMN = 1 / 6;
var INLINE_MAX_ROWS = 20;
var hexOf = (n) => `#${n.toString(16).padStart(6, "0")}`;
var BAND_SWATCHES = [
  ...HEALTH_BAND_ORDER.map((band) => ({ glyph: "■", color: DARK_CANVAS_BAND[band], label: HEALTH_BAND_LABEL[band] })),
  { glyph: "■", color: DARK_CANVAS.nodeNeutral, label: MAP_COPY.noScore }
];
function packRows(items, width2, columns, gap) {
  const rows = [];
  let used = Infinity;
  for (const item of items) {
    const w = width2(item);
    const last = rows[rows.length - 1];
    if (last === void 0 || used + gap + w > columns) {
      rows.push([item]);
      used = w;
    } else {
      last.push(item);
      used += gap + w;
    }
  }
  return rows;
}
var swatchWidth = (s) => s.label.length + 2;
function legendRows(columns, health2 = false) {
  const bands = health2 ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;
  return CRUMB_ROWS + STORY_ROWS + DETAIL_ROWS + bands + SCOPE_ROWS + KEY_ROWS;
}
function mapSize(pane, health2 = false) {
  const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));
  const wanted = pane.placement === "dock" ? pane.bodyRows - legendRows(columns, health2) : Math.min(INLINE_MAX_ROWS, Math.round(columns * INLINE_ROWS_PER_COLUMN));
  return { columns, rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, wanted)) };
}
function swatchRows(items, columns) {
  return packRows(items, swatchWidth, columns, GAP).map(
    (row2) => box(
      { flexDirection: "row", columnGap: GAP },
      row2.map((s) => box({ flexDirection: "row" }, [text(s.glyph, { color: s.color }), text(` ${s.label}`, { dimColor: true })]))
    )
  );
}
function scopeRows(scope, columns) {
  const rows = (parts2) => packRows(parts2, (p) => p.length, columns, SEP.length);
  let parts = scopeParts(scope);
  for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {
    if (rows(parts).length <= 2) break;
    parts = parts.filter((p) => p !== optional);
  }
  return rows(parts).slice(0, 2).map((row2) => row2.join(SEP));
}
function storyRow(head, segs, columns) {
  let room = Math.max(0, columns - HEAD);
  const parts = [text(head.padEnd(HEAD), { dimColor: true })];
  for (const s of segs) {
    if (room <= 0) break;
    const shown = fit(s.text, room);
    room -= shown.length;
    parts.push(text(shown, s.color === void 0 ? {} : { color: s.color }));
  }
  return box({ flexDirection: "row" }, parts);
}
function reachSegs(reach, plum) {
  if (reach.callers.status === "loading") return [{ text: reachesPending(reach.edit.slice(reach.edit.lastIndexOf("/") + 1)) }];
  if (reach.callers.status === "failed") return [{ text: REACHES_FAILED }];
  const paths = [...reach.callers.paths].sort((a, b) => Number(reach.opened.has(b.toLowerCase())) - Number(reach.opened.has(a.toLowerCase())));
  const names2 = paths.slice(0, REACH_NAMES).map((p) => ({ name: p.slice(p.lastIndexOf("/") + 1), opened: reach.opened.has(p.toLowerCase()) }));
  return [{ text: reachesPart(paths.length, names2), color: plum }];
}
function searchedSegs(story) {
  return story.searched.length === 0 ? [] : [{ text: story.searched.map((s) => searchedPart(s.pattern, s.hits)).join(SEP) }];
}
function openedSegs(story, plum) {
  if (story.opened.length === 0) return [];
  const named2 = story.opened.find((o) => o.namedBy !== null);
  const names2 = { text: story.opened.map((o) => o.name).join(SEP) };
  return named2 === void 0 ? [names2] : [names2, { text: `  ${namedByPart(named2.name, named2.namedBy)}`, color: plum }];
}
function editedSegs(story, amber) {
  return story.edited.map((e, i) => ({ text: `${i === 0 ? "" : SEP}◉ ${e.name}${linesPart(e.lines)}`, color: amber }));
}
function storyView(story, reach, style, columns) {
  const pal = MAP_PALETTES[style.theme];
  const rows = [
    [STORY_COPY.searched, searchedSegs(story)],
    [STORY_COPY.opened, openedSegs(story, hexOf(pal.importer))],
    [STORY_COPY.edited, editedSegs(story, hexOf(pal.edit))],
    [STORY_COPY.reaches, reach === null ? [] : reachSegs(reach, hexOf(pal.importer))]
  ];
  return rows.filter(([, segs]) => segs.length > 0).map(([head, segs]) => storyRow(head, segs, columns));
}
var NO_KEYS = { items: false, selected: false, zoomable: false, zoomed: false };
var KEY_PRIORITY = ["health", "next", "zoom", "previous", "up", "clear"];
var keyCells = (label) => label.length + 3;
var MORE = "…";
function keyRow(keys, style, columns) {
  const offered = [
    ["next", keys.items],
    ["previous", keys.items],
    ["zoom", keys.zoomable],
    ["up", keys.zoomed],
    ["clear", keys.selected]
  ];
  const all = [...offered.filter(([, shown2]) => shown2).map(([name]) => ({ name, label: MAP_KEYS_COPY[name] })), { name: "health", label: style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff }];
  const ranked = [...all].sort((a, b) => KEY_PRIORITY.indexOf(a.name) - KEY_PRIORITY.indexOf(b.name));
  const cells = (n) => ranked.slice(0, n).reduce((w, k) => w + keyCells(k.label) + GAP, 0) + (n < all.length ? MORE.length : -GAP);
  let kept = all.length;
  while (kept > 0 && cells(kept) > columns) kept--;
  const shown = new Set(ranked.slice(0, kept).map((k) => k.name));
  const nodes = all.filter((k) => shown.has(k.name)).map((k) => k.name === "health" ? button(HEALTH_KEY, "h", k.label, true) : button(MAP_KEYS[k.name].key, MAP_KEYS[k.name].hotkey, k.label, true));
  return box({ flexDirection: "row", columnGap: GAP }, kept < all.length ? [...nodes, text(MORE, { dimColor: true })] : nodes);
}
var dimLine = (line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" });
function legendView(parts, style, columns) {
  const story = storyView(parts.story, parts.reach, style, columns);
  const quiet = story.length === 0 ? [dimLine(MAP_COPY.quiet, columns)] : story;
  const detail = parts.detail ?? null;
  return [
    ...quiet,
    ...detail === null ? [] : [text(fit(detail, columns), { wrap: "truncate-end" })],
    ...style.health ? swatchRows(BAND_SWATCHES, columns) : [],
    ...scopeRows(parts.scope, columns).map((f) => dimLine(f, columns)),
    keyRow(parts.keys ?? NO_KEYS, style, columns)
  ];
}
function crumbs(layout) {
  return layout.root === null ? [] : [dimLine(crumbLine(layout.root), layout.columns)];
}
function mapPaneView(layout, cells, parts) {
  return box({ key: "lens-map-pane", flexDirection: "column" }, [
    ...crumbs(layout),
    raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),
    ...legendView(parts, layout.style, layout.columns)
  ]);
}
function noticeView(line2, columns) {
  return box({ key: "lens-map-pane", flexDirection: "column" }, [text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" })]);
}

// src/views/owl.ts
var EYES = { open: "◉", shut: "─", side: "◐", happy: "^", still: "•" };
var BLINK = [...Array(9).fill(EYES.open), EYES.shut];
var BLINK_MS = 250;
var EYES_OF = {
  asleep: EYES.shut,
  asking: EYES.side,
  happy: EYES.happy,
  stopped: EYES.still
};
function owlEyes(state2, now, still) {
  if (state2 !== "watching") return EYES_OF[state2];
  return still ? EYES.open : BLINK[Math.floor(now / BLINK_MS) % BLINK.length];
}
var OWL_WIDTH = 5;
function owl(state2, eyes, amber) {
  if (state2 === "asleep") return [text(`{${eyes},${eyes}}`, { dimColor: true })];
  const eye = () => eyes === EYES.shut || eyes === EYES.still ? text(eyes) : text(eyes, { color: amber });
  return [text("{"), eye(), text(","), eye(), text("}")];
}

// src/views/theme.ts
var DARK_THEME = { plum: DARK.accentSecondary, amber: BRAND.accent };
var LIGHT_THEME = { plum: LIGHT.accentSecondary, amber: BRAND.accentTextLight };
function flowTheme(light) {
  return light ? LIGHT_THEME : DARK_THEME;
}
function themeOf(value) {
  return typeof value === "string" && value.startsWith("light") ? "light" : "dark";
}
var HILLS = "▁▂▃▅▃▂▁▁▂▃▂▁▁▁▂▃▄▃▂▁";
var MIRROR = { "▁": " ", "▂": "▔", "▃": "▔", "▄": "▀", "▅": "▀" };
var THISTLE = "⚘";
function repeat(pattern, columns) {
  return pattern.repeat(Math.ceil(Math.max(0, columns) / pattern.length)).slice(0, Math.max(0, columns));
}
function hills(columns) {
  return repeat(HILLS, columns);
}
function loch(columns) {
  return [...hills(columns)].map((c) => MIRROR[c] ?? " ").join("");
}

// src/views/flow.ts
var FLOW_BOX_ID = "lens-flow";
var FLOW_NEXT = "lens-flow-next";
var FLOW_PREV = "lens-flow-prev";
var HAPPY_MS = 3e3;
var NARROW = 80;
var MIN_BODY = 3;
var ACTIVE_MARK = "▸";
var GUTTER = 2;
var CLOCK_W = 6;
var DETAIL_W = 20;
var DETAIL_INDENT = GUTTER + CLOCK_W;
var EMPTY_W = 70;
var WORKING_ROWS = 6;
var FILE_W = 44;
var KIND_W = 8;
var VIA_W = 13;
var BAR_W = 60;
var BUILT_FROM = 2;
var TARGET_MIN = 28;
var SEP2 = " · ";
var EXCERPT_LINE = 160;
var rowKey = (id) => `${FLOW_BOX_ID}-${id}`;
function flowPresses(state2) {
  return [[FLOW_NEXT, null], [FLOW_PREV, null], ...openable(state2).map((id) => [rowKey(id), id])];
}
var width = (segs) => segs.reduce((n, s) => n + s.t.length, 0);
function segNode(s) {
  if (s.press !== void 0) return { type: "Button", props: { key: s.press, label: s.t, plain: true } };
  const props = {};
  if (s.color !== void 0) props.color = s.color;
  if (s.dim === true) props.dimColor = true;
  return text(s.t, props);
}
function row(segs, columns, right = []) {
  const fixed = width(segs.filter((s) => s.flex !== true)) + width(right) + (right.length > 0 ? 2 : 0);
  const fitted = segs.map((s) => s.flex === true ? { ...s, t: fit(s.t, Math.max(1, columns - fixed)) } : s);
  const gap = right.length > 0 ? Math.max(2, columns - width(fitted) - width(right)) : 0;
  const all = gap > 0 ? [...fitted, { t: " ".repeat(gap) }, ...right] : fitted;
  return box({ flexDirection: "row" }, all.filter((s) => s.t !== "").map(segNode));
}
var dimLine2 = (t, columns) => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" });
var pad = (n) => ({ t: " ".repeat(n) });
function wrapWords(words, columns) {
  return packRows(words.split(" "), (w) => w.length, Math.max(1, columns), 1).map((r) => r.join(" "));
}
function section(caption, lines) {
  return lines.length === 0 ? [] : [text(caption, { dimColor: true }), ...lines];
}
function owlState(state2, now) {
  const last = state2.turns.at(-1);
  if (last === void 0) return "asleep";
  if (isWorking(state2)) return inFlight(state2) === null ? "watching" : "asking";
  if (last.end === "stopped" || last.end === "failed") return "stopped";
  return last.endedAt !== null && now - last.endedAt < HAPPY_MS ? "happy" : "asleep";
}
function statusSegs(turn, now, theme2) {
  const edited = turnTotals(turn).edits;
  if (turn.endedAt === null) return [{ t: statusLine(null, now - turn.startedAt, edited) }];
  const end = turn.end ?? "answer";
  const line2 = { t: statusLine(end, turn.durationMs ?? 0, edited) };
  return end === "answer" ? [line2, { t: `  ${THISTLE}`, color: theme2.plum }] : [line2];
}
function notice(mode) {
  return mode === "no-index" || mode === "no-cli" ? FLOW_COPY.notConnected : null;
}
function header(state2, v, theme2) {
  const turn = state2.turns.at(-1);
  const st = owlState(state2, v.now);
  const face = box({ flexDirection: "row" }, owl(st, owlEyes(st, v.now, v.still), theme2.amber));
  const room = v.columns - OWL_WIDTH - 1;
  const said = notice(v.mode);
  const tail = said === null ? [] : [dimLine2(said, v.columns)];
  if (turn === void 0) {
    const [first = "", ...rest] = wrapWords(FLOW_COPY.empty, Math.min(EMPTY_W, room));
    return [box({ flexDirection: "row", columnGap: 1 }, [face, text(first)]), ...rest.map((l) => text(`${" ".repeat(OWL_WIDTH + 1)}${l}`)), ...tail];
  }
  const prompt = turn.prompt.replace(/\s+/g, " ").trim();
  return [
    box({ flexDirection: "row", columnGap: 1 }, [face, row(statusSegs(turn, v.now, theme2), room)]),
    text(fit(answerLine(turnTotals(turn)), v.columns), { wrap: "truncate-end" }),
    ...prompt === "" ? [] : [dimLine2(`"${prompt}"`, v.columns)],
    ...tail
  ];
}
var fileName = (path) => path.split("/").at(-1) ?? path;
function gapLines(g) {
  const out = [];
  if (g.importers !== null) out.push(importersLine(g.importers.total, g.importers.opened));
  if (g.cochange.length > 0) out.push(cochangeLine(g.cochange));
  if (g.tests !== null) out.push(testsReachLine(g.tests.total, g.tests.basis, g.tests.run, fileName(g.path)));
  return out;
}
function healthLines(risk) {
  const hd = risk?.health_delta;
  if (hd === void 0) return [];
  if (hd.introduced > 0) return [introducedLine(hd.introduced, hd.top_findings.find((f) => f.change === "introduced") ?? null)];
  return hd.status === "partial" ? [HEALTH_PARTLY] : [];
}
function beforeAcceptLines(state2, turn, v) {
  const files = beforeAccept(state2, turn).flatMap((g) => [
    row([pad(2), { t: g.path, flex: true }, { t: `  ${FLOW_COPY.asOfIndex}`, dim: true }], v.columns),
    ...gapLines(g).map((l) => dimLine2(`    ${l}`, v.columns))
  ]);
  const health2 = healthLines(v.review).map((l) => text(fit(`  ${l}`, v.columns)));
  return section(FLOW_COPY.beforeAccept, [...files, ...health2]);
}
function viaSeg(via, theme2) {
  if (via.kind === "repowise") return { t: via.tool.padEnd(VIA_W), color: theme2.plum };
  return { t: (via.kind === "search" ? FLOW_COPY.search : FLOW_COPY.direct).padEnd(VIA_W), dim: true };
}
function workingRow(f, t) {
  const card = t.cards.get(pathKey(f.path));
  const knows = t.columns < NARROW || card === void 0 ? "" : knowsParts(card).join(SEP2);
  const kind = { t: (f.kind === "edited" ? FLOW_COPY.edited : FLOW_COPY.read).padEnd(KIND_W), dim: f.kind === "read" };
  return row([pad(2), { t: fit(f.path, t.fileW).padEnd(t.fileW + 2) }, kind, viaSeg(f.via, t.theme), { t: knows, dim: true, flex: true }], t.columns);
}
function workingLines(state2, turn, v, theme2) {
  const files = workingSet(state2, turn);
  const longest = Math.max(0, ...files.map((f) => f.path.length));
  const t = {
    cards: new Map(Object.entries(v.contexts).map(([p, c]) => [pathKey(p), c])),
    columns: v.columns,
    fileW: Math.min(FILE_W, longest, Math.max(8, v.columns - 2 - KIND_W - VIA_W - 4)),
    theme: theme2
  };
  const rows = files.slice(0, WORKING_ROWS).map((f) => workingRow(f, t));
  const more = files.length > WORKING_ROWS ? [dimLine2(`  ${moreFiles(files.length - WORKING_ROWS)}`, v.columns)] : [];
  return section(`${FLOW_COPY.workingSet} · ${FLOW_COPY.asOfIndex}`, [...rows, ...more]);
}
var SHADE = { repowise: "█", read: "▓", search: "▒", shell: "░", other: "·" };
function cellsOf(bytes, total2, cells) {
  return CONTEXT_KINDS.filter((k) => bytes[k] > 0).map((k) => [k, Math.max(1, Math.round(bytes[k] / total2 * cells))]);
}
function shadeSeg(kind, n, theme2) {
  const t = SHADE[kind].repeat(n);
  return kind === "repowise" ? { t, color: theme2.plum } : { t };
}
function contextLines(turn, columns, theme2) {
  const bytes = contextBytes(turn);
  const total2 = CONTEXT_KINDS.reduce((n, k) => n + bytes[k], 0);
  if (total2 === 0) return [];
  const cells = cellsOf(bytes, total2, Math.min(BAR_W, columns - 4));
  const bar = row([pad(2), ...cells.map(([k, n]) => shadeSeg(k, n, theme2))], columns);
  const legend = cells.map(([k]) => `${SHADE[k]} ${contextPart(k, bytes[k])}`);
  const first = firstEditMs(turn);
  const parts = first === null ? legend : [...legend, firstEditText(first)];
  const lines = packRows(parts, (p) => p.length, Math.max(10, columns - 2), 2).map((r) => dimLine2(`  ${r.join("  ")}`, columns));
  return section(FLOW_COPY.context, [bar, ...lines]);
}
function lead(a, ctx) {
  const mark = a.id === ctx.active ? { t: `${ACTIVE_MARK} `, color: ctx.theme.amber } : pad(GUTTER);
  return [mark, { t: clockText(a.startedAt - ctx.turn.startedAt).padEnd(CLOCK_W), dim: true }];
}
function builtFrom(a, ctx) {
  const reply = a.reply;
  const facts = reply === null ? [] : reply.inside.slice(0, BUILT_FROM).map(insideFact);
  const fresh = reply === null ? null : freshnessText(reply.behind);
  return [...ctx.beforeEdit.has(a.id) ? [FLOW_COPY.beforeEdit] : [], ...facts, ...fresh === null ? [] : [fresh]];
}
function rightOf(a, ctx) {
  if (a.isError) return FLOW_COPY.error;
  if (a.endedAt === null) return FLOW_COPY.asking;
  return [durationText(a.endedAt - a.startedAt), ...builtFrom(a, ctx)].join(SEP2);
}
function callLine(a, ctx) {
  const what = a.args[0]?.[1] ?? "";
  const sub = a.agentId === null ? [] : [{ t: `  ${FLOW_COPY.subagent}`, dim: true }];
  const segs = [...lead(a, ctx), { t: a.tool, press: rowKey(a.id) }, pad(2), { t: what, flex: true }, ...sub];
  const room = ctx.columns - width(segs.filter((s) => s.flex !== true)) - Math.min(what.length, TARGET_MIN) - 2;
  return { node: row(segs, ctx.columns, [{ t: fit(rightOf(a, ctx), Math.max(1, room)), dim: true }]), id: a.id };
}
function labeled(label, body, ctx, id) {
  return { node: row([pad(DETAIL_INDENT), { t: label.padEnd(DETAIL_W), dim: true }, { t: body, flex: true }], ctx.columns), id };
}
function wrapped(label, parts, ctx, id) {
  const room = Math.max(10, ctx.columns - DETAIL_INDENT - DETAIL_W);
  return packRows(parts, (p) => p.length, room, SEP2.length).map((r, i) => labeled(i === 0 ? label : "", r.join(SEP2), ctx, id));
}
function replyDetail(a, ctx) {
  const reply = a.reply;
  if (reply === null) return [];
  const excerpt = reply.excerpt === "" ? [] : [labeled(FLOW_COPY.excerpt, reply.excerpt.replace(/\s+/g, " ").slice(0, EXCERPT_LINE), ctx, a.id)];
  const note = ctx.beforeEdit.has(a.id) ? [FLOW_COPY.beforeEdit] : [];
  return [...wrapped(FLOW_COPY.howAnswered, [...note, ...behindParts(reply.behind, reply.bytes)], ctx, a.id), ...excerpt];
}
function detailLines(a, ctx) {
  if (a.id !== ctx.open) return [];
  const opened = ctx.opened.get(a.id) ?? [];
  return [...replyDetail(a, ctx), labeled(FLOW_COPY.thenOpened, opened.length === 0 ? FLOW_COPY.nothingOpened : opened.join(", "), ctx, a.id)];
}
function openedAfter(state2) {
  const out = /* @__PURE__ */ new Map();
  for (const a of state2.turns.flatMap((t) => t.activities)) {
    const by = a.namedBy?.id;
    const path = a.paths[0];
    if (by === void 0 || path === void 0) continue;
    const list2 = out.get(by) ?? [];
    if (!list2.includes(path)) list2.push(path);
    out.set(by, list2);
  }
  return out;
}
var isCall = (a) => a.kind === "repowise";
function callLines(state2, turn, v, theme2) {
  const ctx = {
    turn,
    columns: v.columns,
    active: isWorking(state2) ? inFlight(state2)?.id ?? null : null,
    open: state2.open,
    theme: theme2,
    beforeEdit: answeredBeforeEdit(state2),
    opened: openedAfter(state2)
  };
  const calls = turn.activities.filter(isCall).flatMap((a) => [callLine(a, ctx), ...detailLines(a, ctx)]);
  const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine2(`  ${droppedSteps(turn.dropped)}`, v.columns) }] : [];
  return [...dropped, ...calls];
}
var heightOf = (l) => l.height ?? 1;
var total = (lines) => lines.reduce((n, l) => n + heightOf(l), 0);
function windowStart(lines, room, open) {
  const at = open === null ? -1 : lines.findIndex((l) => l.id === open);
  const floor = at < 0 ? lines.length - 1 : Math.max(0, at - 1);
  let start = 0;
  while (start < floor && total(lines.slice(start)) > room) start++;
  return start;
}
function stepsOutside(lines, shown) {
  return new Set(lines.map((l) => l.id).filter((id) => !shown.has(id))).size;
}
function windowed(lines, room, open) {
  if (total(lines) <= room) return lines;
  const start = windowStart(lines, room - 2, open);
  let end = lines.length;
  while (end > start + 1 && total(lines.slice(start, end)) > room - 2) end--;
  const shown = new Set(lines.slice(start, end).map((l) => l.id));
  const above = stepsOutside(lines.slice(0, start), shown);
  const below2 = stepsOutside(lines.slice(end), shown);
  const note = (n, say) => n === 0 ? [] : [{ node: dimLine2(say(n), Number.POSITIVE_INFINITY) }];
  return [...note(above, hiddenSteps), ...lines.slice(start, end), ...note(below2, laterSteps)];
}
function earlierTurns(state2, columns) {
  const out = state2.turns.slice(0, -1).reverse().map((t) => dimLine2(`  ${turnFooter(t.seq, t.durationMs, turnTotals(t), t.end)}`, columns));
  if (state2.earlier.turns > 0) out.push(dimLine2(`  ${earlierLine(state2.earlier)}`, columns));
  return out;
}
function navRow(state2) {
  if (openable(state2).length === 0) return [];
  return [box({ flexDirection: "row", columnGap: 2 }, [button(FLOW_NEXT, "j", FLOW_COPY.next, true), button(FLOW_PREV, "k", FLOW_COPY.previous, true)])];
}
function dashboard(state2, turn, v, theme2) {
  return [...beforeAcceptLines(state2, turn, v), ...workingLines(state2, turn, v, theme2), ...contextLines(turn, v.columns, theme2)];
}
function closing(turn, columns) {
  return turn !== void 0 && turn.end === "answer" ? [text(loch(columns), { dimColor: true })] : [];
}
function flowView(state2, v) {
  const theme2 = flowTheme(v.light === true);
  const head = [text(hills(v.columns), { color: theme2.plum }), ...header(state2, v, theme2)];
  const turn = state2.turns.at(-1);
  const fixed = turn === void 0 ? [] : dashboard(state2, turn, v, theme2);
  const after = [...closing(turn, v.columns), ...earlierTurns(state2, v.columns), ...navRow(state2)];
  const room = Math.max(MIN_BODY, v.rows - head.length - fixed.length - after.length - 1);
  const calls = turn === void 0 ? [] : windowed(callLines(state2, turn, v, theme2), room, state2.open);
  const callNodes = section(FLOW_COPY.calls, calls.map((l) => l.node));
  return box({ key: FLOW_BOX_ID, flexDirection: "column" }, [...head, ...fixed, ...callNodes, ...after]);
}

// src/flow-controller.ts
var REDRAW_MS = 125;
var STILL_TICK_MS = 1e3;
var GONE_MS = 1e3;
var LensFlow = class {
  state = initialFlow;
  /** Flow is on screen: set by its render; cleared by another tab, or by a redraw no render answered. */
  shown = false;
  still = false;
  io = null;
  lastDraw = Number.NEGATIVE_INFINITY;
  /** When the first redraw no Flow render has answered was asked for; null once one did. */
  unansweredSince = null;
  pending;
  ticker;
  happy;
  setReducedMotion(reduced) {
    this.still = reduced;
  }
  /** Another tab is shown, or the pane is gone: nothing of Flow is on screen. */
  hide() {
    this.shown = false;
    this.stopTick();
  }
  dispatch(io, action) {
    this.io = io;
    const next = reduceFlow(this.state, action);
    if (next === this.state) return;
    this.state = next;
    if (action.type === "turnEnded") this.afterTurn();
    this.request();
  }
  /** The tab's tree at `now`; a render marks Flow on screen and keeps the owl's clock going while Claude works. */
  paneTree(io, pane, now) {
    this.io = io;
    this.shown = true;
    this.unansweredSince = null;
    this.ensureTick();
    return flowView(this.state, { ...pane, now, still: this.still });
  }
  dispose() {
    this.hide();
    clearTimeout(this.pending);
    clearTimeout(this.happy);
    this.pending = void 0;
    this.happy = void 0;
    this.io = null;
  }
  /** A redraw now, or once the throttle allows; nothing while Flow is not on screen. */
  request() {
    if (!this.shown || this.pending !== void 0) return;
    const wait = this.lastDraw + REDRAW_MS - Date.now();
    if (wait <= 0) return this.draw();
    this.pending = setTimeout(() => this.timer(() => (this.pending = void 0, true)), wait);
  }
  /** A timer's body: its step says whether to redraw; a failure is logged, never thrown into the runtime. */
  timer(step2) {
    try {
      if (step2()) this.draw();
    } catch (err) {
      this.io?.debug(`flow timer failed: ${String(err)}`);
    }
  }
  /** Redraws, unless redraws have gone unanswered for a while: then the pane is gone and Flow stops asking. */
  draw() {
    const now = Date.now();
    if (this.unansweredSince !== null && now - this.unansweredSince >= GONE_MS) return this.hide();
    if (!this.shown || this.io === null) return;
    this.lastDraw = now;
    this.unansweredSince ??= now;
    this.io.redraw();
  }
  /** The owl is happy for a moment, then sleeps: one redraw when that moment ends. */
  afterTurn() {
    this.stopTick();
    clearTimeout(this.happy);
    this.happy = setTimeout(() => this.timer(() => (this.happy = void 0, true)), HAPPY_MS);
  }
  ensureTick() {
    if (this.ticker !== void 0 || !this.shown || !isWorking(this.state)) return;
    this.ticker = setInterval(() => this.timer(() => this.tick()), this.still ? STILL_TICK_MS : BLINK_MS);
  }
  /** Redraw while Claude works; stop once it is done. Off screen, `draw` stops it. */
  tick() {
    if (isWorking(this.state)) return true;
    this.stopTick();
    return false;
  }
  stopTick() {
    clearInterval(this.ticker);
    this.ticker = void 0;
  }
};

// src/model/events.ts
function fromTurnComplete(e) {
  return e.agentId === void 0 ? { type: "turnCompleted" } : null;
}
var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write"]);
function fileTarget(e, repoRoot) {
  if (!FILE_TOOLS.has(e.tool) || repoRoot === null || typeof e.file_path !== "string") return null;
  const windows = /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(repoRoot);
  return relativeTo(e.file_path, repoRoot, windows);
}
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write"]);
var STANDING = /^\[repowise\] .+? is governed by a standing decision: (.+?)(?: because .*)?\.$/;
var MINED = /^\[repowise\] .+? has a decision recorded in it, mined but not reviewed: (.+?)(?: because .*)?\.$/;
var FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, last (.+?)(?: \(bug magnet\))?(?:; mostly in (.+?))?\.$/;
function stripConfirmed(line2) {
  return line2.replace(/ \((?:seen in|confirmed across) \d+ sessions\)\.$/, ".");
}
function notesFromAugment(additionalContext) {
  if (!Array.isArray(additionalContext)) return [];
  const notes = [];
  const lines = additionalContext.filter((c) => typeof c === "string").flatMap((c) => c.split(/\r?\n/));
  for (const raw of lines) {
    const line2 = stripConfirmed(raw.trim());
    const standing = STANDING.exec(line2);
    const decision = standing ?? MINED.exec(line2);
    const fixes = FIXES.exec(line2);
    if (decision !== null && !notes.some((n) => n.kind === "decision")) {
      notes.push({ kind: "decision", reviewed: standing !== null, title: decision[1] });
    } else if (fixes !== null && !notes.some((n) => n.kind === "fixes")) {
      notes.push({ kind: "fixes", count: Number(fixes[1]), age: fixes[2], symbol: fixes[3] ?? null });
    }
  }
  return notes;
}
function savingsTotals(s) {
  return {
    tokens: s.saved_input_tokens,
    inferredTokens: Math.min(s.inferred_saved_input_tokens, s.saved_input_tokens),
    usd: s.priced_input_savings_usd
  };
}
function savingsSince(now, base) {
  const tokens = now.tokens - base.tokens;
  const inferredTokens = now.inferredTokens - base.inferredTokens;
  const usd = now.usd - base.usd;
  if (tokens < 0 || inferredTokens < 0 || usd < 0) return null;
  return { tokens, inferredTokens: Math.min(inferredTokens, tokens), usd };
}
var OBSERVED_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write", "Grep", "Glob"]);
var OWN_CALL_PREFIX2 = "toolu_plugin_";
function absolutePath(raw, ctx) {
  const absolute = ctx.isWindows ? /^[A-Za-z]:[\\/]|^\\\\/.test(raw) : raw.startsWith("/");
  const joined = absolute ? raw : `${ctx.cwd.replace(/[\\/]+$/, "")}/${raw.replace(/^\.[\\/]/, "")}`;
  return ctx.isWindows ? joined.replace(/\\/g, "/") : joined;
}
function absoluteKey(raw, ctx) {
  return normalizeRepoPath(absolutePath(raw, ctx), ctx.isWindows);
}
function relativeTo(absolute, root, isWindows) {
  const rootKey = normalizeRepoPath(root, isWindows);
  const slashed = isWindows ? absolute.replace(/\\/g, "/") : absolute;
  if (!normalizeRepoPath(slashed, isWindows).startsWith(`${rootKey}/`)) return null;
  return slashed.slice(rootKey.length + 1);
}
function filenamesOf(out) {
  const names2 = typeof out.result === "object" ? out.result.filenames : void 0;
  return Array.isArray(names2) ? names2.filter((v) => typeof v === "string") : [];
}
function isContentGrep(tool, out) {
  return tool === "Grep" && typeof out.result === "object" && out.result.mode === "content";
}
function searchAction(out, ctx) {
  return { type: "search", paths: filenamesOf(out).map((f) => absoluteKey(f, ctx)) };
}
function fileAction(e, ctx) {
  const raw = e["file_path"];
  if (typeof raw !== "string") return null;
  const path = absoluteKey(raw, ctx);
  return e.tool === "Read" ? { type: "read", path } : { type: "edit", path };
}
function fromToolCall(e, outcome, ctx) {
  if (!OBSERVED_TOOLS.has(e.tool) || e.tool_use_id?.startsWith(OWN_CALL_PREFIX2)) return null;
  const out = outcome ?? {};
  if (out.isError === true || isContentGrep(e.tool, out)) return null;
  return e.tool === "Grep" || e.tool === "Glob" ? searchAction(out, ctx) : fileAction(e, ctx);
}
function touchedPath(e, cwd2, repoRoot) {
  const raw = typeof e.file_path === "string" ? e.file_path : e["notebook_path"];
  if (typeof raw !== "string") return null;
  const base = cwd2 ?? repoRoot;
  if (base === null) return raw;
  const isWindows = /^[A-Za-z]:[\/]|^[\/]{2}/.test(base);
  const abs = absolutePath(raw, { cwd: base, isWindows });
  return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;
}

// src/model/story.ts
var NO_STORY = { searched: [], opened: [], edited: [] };
var nameOf = (path) => path.slice(path.lastIndexOf("/") + 1);
var FILE_KINDS = /* @__PURE__ */ new Set(["read", "edit", "search"]);
var isFileStep = (a) => !a.isError && FILE_KINDS.has(a.kind);
var isOpen = (a) => a.kind === "read" || a.kind === "edit";
function storyTurn(state2) {
  for (let i = state2.turns.length - 1; i >= 0; i--) {
    const t = state2.turns[i];
    if (t.activities.some(isFileStep)) return t;
  }
  return null;
}
function argOf(a, keys) {
  return a.args.find(([k]) => keys.includes(k))?.[1] ?? "";
}
function openedOf(steps) {
  const seen = /* @__PURE__ */ new Map();
  for (const a of steps) {
    const path = a.paths[0];
    if (!isOpen(a) || path === void 0 || seen.has(path)) continue;
    seen.set(path, { name: nameOf(path), namedBy: a.namedBy?.tool ?? null });
  }
  return [...seen.values()];
}
function storyFromFlow(state2) {
  const turn = storyTurn(state2);
  if (turn === null) return NO_STORY;
  const steps = turn.activities.filter(isFileStep);
  return {
    searched: steps.filter((a) => a.kind === "search").map((a) => ({ pattern: argOf(a, ["pattern", "query"]), hits: a.hits })),
    opened: openedOf(steps),
    edited: steps.filter((a) => a.kind === "edit" && a.paths[0] !== void 0).map((a) => ({ name: nameOf(a.paths[0]), lines: a.lines }))
  };
}
function litFromFlow(state2) {
  const turn = storyTurn(state2);
  if (turn === null) return NO_LIT;
  const mine = visits(state2).filter((v) => v.turn === turn.seq);
  const opened = mine.filter((v) => v.kind !== "search-hit");
  const edits = opened.filter((v) => v.kind === "edit");
  return {
    hits: mine.filter((v) => v.kind === "search-hit").map((v) => v.path),
    reads: [...new Set(opened.map((v) => v.path))],
    named: Object.entries(state2.named).filter(([, n]) => n.turn === turn.seq).map(([key2]) => key2),
    importers: [],
    edits: [...new Set(edits.map((v) => v.path))],
    edit: edits.at(-1)?.path ?? null,
    current: opened.at(-1)?.path ?? null
  };
}
var rel = (abs, root, ci) => relativeTo(abs, root, ci);
function litFromTrail(trail, root, caseInsensitive) {
  const all = (paths) => paths.map((p) => rel(p, root, caseInsensitive)).filter((p) => p !== null);
  const reads = all(trail.reads);
  const edit = trail.edit === null ? null : rel(trail.edit, root, caseInsensitive);
  return { hits: all(trail.hits), reads, named: [], importers: [], edits: edit === null ? [] : [edit], edit, current: reads.at(-1) ?? null };
}
function storyFromTrail(trail) {
  return {
    searched: trail.searches === 0 ? [] : [{ pattern: "", hits: trail.hits.length }],
    opened: trail.reads.map((p) => ({ name: nameOf(p), namedBy: null })),
    edited: trail.edit === null ? [] : [{ name: nameOf(trail.edit), lines: null }]
  };
}
function combineCallers(answers, edited) {
  const ready = answers.filter((c) => c.status === "ready");
  if (ready.length > 0) return { status: "ready", paths: [...new Set(ready.flatMap((c) => c.paths))].filter((p) => !edited.has(p.toLowerCase())) };
  if (answers.some((c) => c.status === "loading")) return { status: "loading" };
  return answers.length > 0 ? { status: "failed" } : null;
}
function withImporters(lit, importersOf) {
  if (lit.edit === null) return { lit, reach: null };
  const answers = lit.edits.map(importersOf).filter((c) => c !== null);
  const callers = combineCallers(answers, new Set(lit.edits.map((p) => p.toLowerCase())));
  if (callers === null) return { lit, reach: null };
  const importers = callers.status === "ready" ? callers.paths : [];
  return { lit: { ...lit, importers }, reach: { edit: lit.edit, callers, opened: new Set(lit.reads.map((p) => p.toLowerCase())) } };
}

// src/model/inspect.ts
var KNOWS_NOTHING = { context: null, tests: null, namedBy: null };
var key = (p) => p.toLowerCase();
function litPaths(lit) {
  const edits = [...lit.edits].reverse();
  const order = [...edits, ...lit.reads, ...lit.importers, ...lit.named];
  const seen = /* @__PURE__ */ new Set();
  return order.filter((p) => {
    if (seen.has(key(p))) return false;
    seen.add(key(p));
    return true;
  });
}
function step(paths, current, by) {
  if (paths.length === 0) return null;
  const at = current === null ? -1 : paths.findIndex((p) => key(p) === key(current));
  if (at === -1) return (by === 1 ? paths[0] : paths.at(-1)) ?? null;
  return paths[(at + by + paths.length) % paths.length] ?? null;
}
var nameOf2 = (p) => p.slice(p.lastIndexOf("/") + 1);
var has = (paths, p) => paths.some((x) => key(x) === key(p));
function whyLit(path, lit, story, knows) {
  const edit = has(lit.edits, path) ? story.edited.find((e) => e.name === nameOf2(path)) ?? { lines: null } : null;
  return {
    edited: edit === null ? null : { lines: edit.lines },
    opened: edit === null && has(lit.reads, path),
    imports: has(lit.importers, path) && lit.edit !== null ? nameOf2(lit.edit) : null,
    namedBy: knows.namedBy
  };
}
function contextOf(contexts, path) {
  const exact = contexts[path];
  if (exact !== void 0) return exact;
  const lower = key(path);
  const found = Object.keys(contexts).find((k) => key(k) === lower);
  return found === void 0 ? null : contexts[found] ?? null;
}
function knowsOf(path, contexts, flow2) {
  const facts = flow2 === null ? void 0 : flow2.blast[pathKey(path)];
  const tests = facts?.tests ?? null;
  return {
    context: contextOf(contexts, path),
    tests: tests === null ? null : { total: tests.total, basis: tests.basis },
    namedBy: flow2 === null ? null : flow2.named[pathKey(path)]?.tool ?? null
  };
}

// ../api-client/src/blast-radius.ts
async function analyzeBlastRadius(repoId, body) {
  return apiPost(
    `/api/repos/${repoId}/blast-radius`,
    body
  );
}

// ../api-client/src/areas.ts
function holdParams(opts = {}) {
  if (opts.hold !== "map") return {};
  return { hold: "map", include: opts.include?.length ? [...opts.include].sort().join(",") : void 0 };
}

// ../api-client/src/code-health.ts
async function getHealthMap(repoId, opts = {}) {
  return apiGet(`/api/repos/${repoId}/health/map`, {
    cap: opts.cap,
    active: opts.active?.length ? opts.active.join(",") : void 0,
    scope: opts.scope,
    counts: opts.counts,
    include_held: opts.include_held || void 0,
    q: opts.q?.trim() || void 0,
    area: opts.area || void 0,
    ...holdParams(opts)
  });
}

// src/model/trail.ts
var MAX_READS = 200;
var initialTrail = {
  reads: [],
  readsCapped: false,
  hits: [],
  searches: 0,
  edit: null,
  edits: 0,
  callers: null
};
function withRead(state2, path) {
  if (state2.reads.includes(path)) return state2;
  const reads = [...state2.reads, path];
  if (reads.length <= MAX_READS) return { ...state2, reads };
  return { ...state2, reads: reads.slice(reads.length - MAX_READS), readsCapped: true };
}
function reduceTrail(state2, action) {
  switch (action.type) {
    case "read":
      return withRead(state2, action.path);
    case "search":
      return { ...state2, hits: action.paths, searches: state2.searches + 1 };
    case "edit":
      return {
        ...withRead(state2, action.path),
        edit: action.path,
        edits: state2.edits + 1,
        callers: { status: "loading" }
      };
    case "callers":
      return action.edits === state2.edits ? { ...state2, callers: action.callers } : state2;
  }
}

// src/views/mapSvg.ts
var SVG_CHARS = 131072;
var DESKTOP_MAX_COLUMNS = 160;
var DESKTOP_MAX_ROWS = 45;
var color = (c) => `#${c.toString(16).padStart(6, "0")}`;
var escape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function desktopSize(size) {
  return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };
}
var textAt = (l, fill) => `<text x="${l.col}" y="${2 * l.row + 1.6}" fill="${color(fill)}">${escape(l.text)}</text>`;
function svgLabels(layout, overlay) {
  const pal = MAP_PALETTES[layout.style.theme];
  const folder = layout.style.health ? LABEL_FG : pal.folder;
  const names2 = overlay.names.map((n) => textAt(n, n.color === TERMINAL_DEFAULT ? pal.read : n.color));
  return [...layout.labels.map((l) => textAt(l, folder)), ...names2].join("");
}
function mapSvg(layout, overlay) {
  const { width: width2, height } = layout;
  const { pixels } = framePixels(layout, overlay);
  const runs = /* @__PURE__ */ new Map();
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width2; ) {
      const c = pixels[y * width2 + x] ?? GROUND;
      let end = x + 1;
      while (end < width2 && pixels[y * width2 + end] === c) end++;
      if (c !== GROUND) {
        const list2 = runs.get(c) ?? [];
        list2.push(`M${x} ${y}.5h${end - x}`);
        runs.set(c, list2);
      }
      x = end;
    }
  }
  const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width2} ${height}" shape-rendering="crispEdges"><g stroke-width="1" fill="none">${paths}</g><g font-family="monospace" font-size="1.7">${svgLabels(layout, overlay)}</g></svg>`;
}
function svgPaneView(layout, overlay, parts) {
  const source = mapSvg(layout, overlay);
  const picture = source.length <= SVG_CHARS ? svg(source, mapAlt(layout.drawn.length)) : text(fit(MAP_COPY.tooLarge, layout.columns), { dimColor: true, wrap: "truncate-end" });
  return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(parts, layout.style, layout.columns)]);
}

// src/map-controller.ts
var MAP_CAP = 4e3;
var MAP_TIMEOUT_MS = 15e3;
var CALLERS_TIMEOUT_MS = 2e4;
var CALLERS_DEPTH = 1;
var NO_TURN = () => ({ lit: NO_LIT, story: NO_STORY });
function scopeFacts(layout, data, repo, offMap) {
  const whole = layout.root === null;
  return {
    drawn: layout.drawn.length,
    shown: whole ? data.files.length : layout.files.length,
    repositoryTotal: whole ? data.repository_total : layout.files.length,
    indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,
    beyondCap: whole ? data.omitted.files : 0,
    dense: layout.dense,
    notOnMap: offMap,
    zoom: layout.root
  };
}
var cacheKey = (k) => `${k.root ?? ""}|${k.columns}|${k.rows}|${k.style.theme}|${k.style.health}`;
var LAYOUT_CACHE = 6;
function parentOf(root) {
  const at = root === null ? -1 : root.lastIndexOf("/");
  return at === -1 ? null : root.slice(0, at);
}
function folderOf(layout, path) {
  const at = layout.index.get(layout.caseInsensitive ? path.toLowerCase() : path);
  if (at === void 0) return null;
  const b = litPixels(layout, layout.files[at]);
  const folder = folderAt(layout, Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2));
  return folder === layout.root ? null : folder;
}
var LensMap = class {
  trail = initialTrail;
  disposed = false;
  /** One band row the map asks for (the pane could not open), until the turn ends. */
  band = null;
  repo = null;
  feed = { status: "idle" };
  requested = false;
  autoOpenTried = false;
  /** The latest edit's absolute path with its case. */
  editPath = null;
  /**
   * Every file edited this session (absolute, case kept), and the importers
   * of each, asked once per distinct path. Ceiling: never asked again, so an
   * index update mid-session is not seen; nothing tells Lens it changed.
   */
  edited = /* @__PURE__ */ new Set();
  importers = /* @__PURE__ */ new Map();
  drawn = null;
  /** What the last render drew, for the keys: its layout and the lit files on it, in cursor order. */
  view = null;
  layoutCache = null;
  /** The inspector's selection (a repo-relative path) and the folder zoomed into. */
  selected = null;
  zoom = null;
  reducedMotion = false;
  /** Health colours on the tiles: off by default (`lens_map_health`), toggled from the pane. */
  health;
  /** Read at every frame, so an animation sees the turn as it is now. */
  turn;
  autoOpenOnRead;
  /** The pane's one animator, shared with the trail: whichever tab is shown drives it. */
  animator;
  constructor(autoOpenOnRead, animator2 = new Animator(), health2 = false, turn = NO_TURN) {
    this.autoOpenOnRead = autoOpenOnRead;
    this.animator = animator2;
    this.health = health2;
    this.turn = turn;
  }
  /** The importers of a repo-relative path, as far as they are known; null when never asked. */
  importersOf(path) {
    return this.importers.get(this.keyOf(path)) ?? null;
  }
  keyOf(rel2) {
    return this.repo?.caseInsensitive === false ? rel2 : rel2.toLowerCase();
  }
  /** A press of one of the map's keys (MAP_PRESSES): moves the cursor, zooms, or toggles health colours; one redraw. */
  press(io, key2) {
    const act = this.actions()[key2];
    if (act === void 0) return;
    act();
    io.redraw();
  }
  actions() {
    return {
      [MAP_KEYS.next.key]: () => this.move(1),
      [MAP_KEYS.previous.key]: () => this.move(-1),
      [MAP_KEYS.clear.key]: () => this.selected = null,
      [MAP_KEYS.zoom.key]: () => this.zoom = this.zoomTarget() ?? this.zoom,
      [MAP_KEYS.up.key]: () => this.zoom = parentOf(this.zoom),
      [HEALTH_KEY]: () => this.health = !this.health
    };
  }
  /** The cursor walks the lit files the last render drew, so a zoomed view walks only its own folder's. */
  move(by) {
    this.selected = step(this.view?.paths ?? [], this.selected, by);
  }
  /** Where the zoom key goes: the folder holding the selection, when one is drawn deeper than the current view. */
  zoomTarget() {
    const layout = this.view?.layout ?? null;
    return layout === null || this.selected === null ? null : folderOf(layout, this.selected);
  }
  /** A new prompt starts with nothing selected and the whole repo in view. */
  turnStarted() {
    this.selected = null;
    this.zoom = null;
  }
  /**
   * The lit files on this layout in cursor order, and the selection among them.
   * A selection the turn stops lighting (or this view no longer draws) is dropped
   * for good, so it never comes back ringed when the file is lit again.
   */
  see(layout, lit) {
    const paths = litPaths(lit).filter((p) => layout.index.has(layout.caseInsensitive ? p.toLowerCase() : p));
    const s = this.selected;
    if (s !== null && !paths.some((p) => p.toLowerCase() === s.toLowerCase())) this.selected = null;
    this.view = { layout, paths };
    return paths;
  }
  /** The detail line, the keys that would act, and the rest of the pane's parts. */
  parts(layout, lighting, scope, paths) {
    const turn = lighting.turn;
    const selected = this.selected;
    const knows = selected === null ? KNOWS_NOTHING : turn.knows?.(selected) ?? KNOWS_NOTHING;
    const detail = selected === null ? null : detailLine(selected, whyLit(selected, lighting.lit, turn.story, knows), knows);
    const keys = {
      items: paths.length > 0,
      selected: selected !== null,
      zoomable: selected !== null && folderOf(layout, selected) !== null,
      zoomed: layout.root !== null
    };
    return { story: turn.story, reach: lighting.reach, scope, detail, keys };
  }
  /** What the turn lit, with the latest edit's importers joined as they stand now. */
  lighting() {
    const turn = this.turn();
    return { ...withImporters(turn.lit, (p) => this.importersOf(p)), turn };
  }
  /** The band row the map wants shown, if any. */
  bandLine() {
    return this.band;
  }
  /** The person's `prefersReducedMotion` setting: resting frames only. */
  setReducedMotion(reduced) {
    this.reducedMotion = reduced;
  }
  dispose() {
    this.disposed = true;
    this.animator.end();
  }
  /**
   * A `/clear`: the conversation's trail and edits go, with the selection and
   * the zoom, so nothing of it stays lit. The feed, the repo and the importers already asked for (index data,
   * by path) stay, and so does an open pane.
   */
  clearConversation(io) {
    this.trail = initialTrail;
    this.edited.clear();
    this.editPath = null;
    this.band = null;
    this.turnStarted();
    io.redraw();
  }
  setRepo(io, repo) {
    this.repo = repo;
    this.fetchWanted(io);
  }
  /** One observed tool call; `editPath` is the edited file's absolute path, case kept. */
  observe(io, action, editPath) {
    if (action.type === "edit" && editPath !== null) this.edited.add(editPath);
    if (action.type === "edit") this.editPath = editPath;
    this.apply(io, action);
    if (action.type === "edit") this.fetchWanted(io);
    if (action.type === "read") void this.autoOpen(io);
  }
  /** /lens: open the pane with focus (asked, so placed at any width) and start what it shows. */
  async request(io) {
    this.requested = true;
    this.band = null;
    if (this.feed.status === "failed") this.feed = { status: "idle" };
    const opened = await io.openPane(true);
    if (!opened.isPlaced) this.band = notPlacedLine(opened.reason);
    this.fetchWanted(io);
    io.redraw();
  }
  /** A main-loop turn ended: the band row has been seen. */
  turnEnded() {
    this.band = null;
  }
  /** Another tab is shown: nothing of the map is on screen to animate. */
  offScreen() {
    this.drawn = null;
  }
  /** The pane's tree; starts the feed fetch when the map is wanted and not yet asked for. */
  paneTree(io, pane) {
    this.drawn = null;
    const notice2 = this.noticeFor(io, pane);
    if (notice2 !== null) return noticeView(notice2, pane.bodyColumns);
    const { data } = this.feed;
    const repo = this.repo;
    const desktop = pane.surface === "desktop";
    const style = { theme: pane.theme, health: this.health };
    const size = mapSize(pane, this.health);
    const at = desktop ? desktopSize(size) : size;
    let layout = this.layoutFor({ data, ...at, style, root: this.zoom }, repo.caseInsensitive);
    if (layout.root !== null && layout.files.length === 0) {
      this.zoom = null;
      layout = this.layoutFor({ data, ...at, style, root: null }, repo.caseInsensitive);
    }
    const lighting = this.lighting();
    const paths = this.see(layout, lighting.lit);
    const overlay = resolveLit(layout, lighting.lit, this.selected);
    const parts = this.parts(layout, lighting, scopeFacts(layout, data, repo, notOnMap(layout, lighting.lit)), paths);
    if (desktop) return svgPaneView(layout, overlay, parts);
    this.drawn = { layout, root: repo.root };
    return mapPaneView(layout, frameCells(layout, overlay, mapStep(this.animator.progress(Date.now()))), parts);
  }
  /** Why there is no map to draw yet (and the feed fetch started when wanted), or null once it can be drawn. */
  noticeFor(io, pane) {
    if (pane.surface !== void 0 && pane.surface !== "terminal" && pane.surface !== "desktop") return MAP_COPY.desktop;
    if (this.repo === null) return pane.notice;
    this.requested = true;
    this.fetchWanted(io);
    const status = this.feed.status;
    if (status === "ready") return null;
    return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;
  }
  /** The layout for this feed, size, style and zoom; kept per (zoom, size, style) for the feed, a few at a time. */
  layoutFor(key2, caseInsensitive) {
    if (this.layoutCache?.data !== key2.data) this.layoutCache = { data: key2.data, layouts: /* @__PURE__ */ new Map() };
    const layouts = this.layoutCache.layouts;
    const cached = layouts.get(cacheKey(key2));
    if (cached !== void 0) return cached;
    const layout = layoutMap(key2.data.files, { columns: key2.columns, rows: key2.rows, caseInsensitive, style: key2.style, root: key2.root });
    if (layouts.size >= LAYOUT_CACHE) layouts.delete(layouts.keys().next().value);
    layouts.set(cacheKey(key2), layout);
    return layout;
  }
  apply(io, action) {
    const next = reduceTrail(this.trail, action);
    if (next === this.trail) return;
    this.trail = next;
    if (action.type === "search") this.animate(io, "flash");
    else if (action.type === "callers" && action.callers.status === "ready") this.animate(io, "ripple");
    else io.redraw();
  }
  /** The feed and the importers of every edited file not yet asked for, once the map is wanted and the repo known. */
  fetchWanted(io) {
    if (!this.requested || this.repo === null) return;
    this.loadFeed(io, this.repo);
    for (const path of this.edited) this.loadCallers(io, this.repo, path);
  }
  loadFeed(io, repo) {
    if (this.feed.status !== "idle") return;
    this.feed = { status: "loading" };
    withTimeout(getHealthMap(repo.id, { cap: MAP_CAP }), MAP_TIMEOUT_MS, "health map").then((data) => {
      this.feed = { status: "ready", data };
    }).catch((err) => {
      this.feed = { status: "failed" };
      io.debug(`health map failed: ${String(err)}`);
    }).finally(() => {
      if (!this.disposed) io.redraw();
    });
  }
  /** One edited file's importers, asked once; the answer is kept by path. */
  loadCallers(io, repo, abs) {
    const rel2 = relativeTo(abs, repo.root, repo.caseInsensitive);
    const key2 = rel2 === null ? null : this.keyOf(rel2);
    if (rel2 === null || key2 === null || this.importers.has(key2)) return;
    this.importers.set(key2, { status: "loading" });
    const request = { changed_files: [rel2], max_depth: CALLERS_DEPTH };
    withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers").then((r) => {
      const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel2);
      if (this.disposed) return;
      this.landed(io, abs, { status: "ready", paths });
      io.blastLanded?.(rel2, r);
    }).catch((err) => {
      io.debug(`importers failed: ${String(err)}`);
      if (!this.disposed) this.landed(io, abs, { status: "failed" });
    });
  }
  /** An answer for one edited file: kept by path; for the latest edit, also the trail's (which ripples). */
  landed(io, abs, callers) {
    const rel2 = this.repo === null ? null : relativeTo(abs, this.repo.root, this.repo.caseInsensitive);
    if (rel2 !== null) this.importers.set(this.keyOf(rel2), callers);
    if (abs === this.editPath) this.apply(io, { type: "callers", edits: this.trail.edits, callers });
    else io.redraw();
  }
  /** The first read opens the map when the toggle is on and the pane would be placed; never forced. */
  async autoOpen(io) {
    if (!this.mayAutoOpen()) return;
    this.autoOpenTried = true;
    const opened = await io.openPane(false);
    if (this.disposed || this.requested) return;
    if (opened.isPlaced) {
      this.requested = true;
      this.fetchWanted(io);
      return;
    }
    await io.closePane();
    this.band = MAP_COPY.waiting;
    io.redraw();
  }
  /** Once, with the toggle on, before the person asked, and only for a repo with a map. */
  mayAutoOpen() {
    return this.autoOpenOnRead && !this.autoOpenTried && !this.requested && this.repo !== null;
  }
  /** Whether an animation would show anything: a map on screen, motion allowed, a ripple with somewhere to go. */
  canAnimate(kind) {
    const drawn = this.drawn;
    if (this.reducedMotion || drawn === null) return false;
    return kind === "flash" || rippleRadius(drawn.layout, resolveLit(drawn.layout, this.lighting().lit)) > 0;
  }
  /**
   * A flash or a ripple when it would show; otherwise (reduced motion, nothing
   * on screen) the resting frame, leaving another tab's animation playing.
   */
  animate(io, kind) {
    if (!this.canAnimate(kind)) return io.redraw();
    this.animator.play(io, kind, kind === "flash" ? FLASH_MS : RIPPLE_MS, (step2) => this.frame(step2));
  }
  /** The current trail on the drawn map at one step, or null once the map is off screen. */
  frame(step2) {
    const drawn = this.drawn;
    const anim = mapStep(step2);
    if (drawn === null || anim === void 0) return null;
    const cells = frameCells(drawn.layout, resolveLit(drawn.layout, this.lighting().lit, this.selected), anim);
    return { key: MAP_KEY, cells, columns: drawn.layout.columns, rows: drawn.layout.rows };
  }
};
function mapStep(step2) {
  return step2 !== void 0 && (step2.kind === "flash" || step2.kind === "ripple") ? step2 : void 0;
}

// src/model/ask.ts
var TAB_BAR = ["flow", "map", "ask", "recap"];
function askRoute(question) {
  return /^\s*why\b/i.test(question) ? { tool: "get_why", args: { query: question } } : { tool: "get_answer", args: { question } };
}
function askReply(tool, reply) {
  const body = typeof reply === "object" && reply !== null ? reply : {};
  return tool === "get_why" ? { tool, reply: body } : { tool, reply: body };
}
function mayHaveUsedModel(a) {
  return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";
}
function lensCommand(args, tabs = TAB_BAR) {
  const [word = "", ...rest] = args.trim().split(/\s+/);
  const question = rest.join(" ");
  const named2 = word.toLowerCase();
  if (named2 === "ask") return { tab: "ask", question: question === "" ? null : question };
  const tab = tabs.find((t) => t === named2);
  return { tab: tab ?? null, question: null };
}
function whyDraft(decision) {
  return `why ${decision}`;
}

// src/model/review.ts
var initialReview = { edited: false, outcome: { phase: "none" }, decision: null };
function reduceReview(state2, action) {
  switch (action.type) {
    case "turnStarted":
      return state2.edited || state2.outcome.phase !== "none" || state2.decision !== null ? initialReview : state2;
    case "fileEdited":
      return state2.edited ? state2 : { ...state2, edited: true };
    case "reviewStarted":
      return { ...state2, outcome: { phase: "reviewing" } };
    case "reviewed":
      return { ...state2, outcome: { phase: "done", risk: action.risk } };
    case "reviewFailed":
      return { ...state2, outcome: { phase: "failed", reason: action.reason, message: action.message } };
    case "decisionNoted":
      return state2.decision === action.title ? state2 : { ...state2, decision: action.title };
  }
}
function emptyDiff(risk) {
  return risk.status === "nothing_to_score" || risk.health_delta?.scope?.changed === 0;
}
function reviewable(risk) {
  return risk.error === void 0 && !emptyDiff(risk);
}
var WRITE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
function isFileEdit(e, result) {
  if (typeof e.tool !== "string" || !WRITE_TOOLS.has(e.tool)) return false;
  if (typeof e.tool_use_id === "string" && e.tool_use_id.startsWith("toolu_plugin_")) return false;
  if (typeof result !== "object" || result === null) return false;
  const r = result;
  return r.deny === void 0 && r.isError !== true;
}
function shouldReview(e, edits) {
  if (e.agentId !== void 0 || edits === 0) return false;
  return e.isAborted !== true && e.reason !== "aborted" && e.reason !== "error";
}
function isRetryable(action) {
  return action.type === "reviewFailed" && action.reason !== "timeout";
}
function testsToRun(risk) {
  const block = risk.impacted_tests;
  const tests = block?.tests_to_run ?? [];
  const runAll = block?.run_all === true ? block.reasons?.[0] ?? block.summary ?? "" : null;
  if (block === void 0 || tests.length === 0 && runAll === null) return null;
  return {
    tests,
    total: block.total ?? tests.length,
    truncated: block.truncated === true,
    files: block.tests_to_run_kind === "test_file",
    measured: block.basis === "measured",
    runAll
  };
}

// src/model/session.ts
var initialSession = {
  mode: null,
  freshness: null,
  hint: null,
  hintsShown: [],
  repoRoot: null,
  running: null,
  contexts: {},
  notes: {},
  savings: null,
  review: initialReview,
  lastReview: null,
  touched: [],
  pane: { tab: "flow", draft: "" },
  ask: { phase: "idle" },
  modelAsks: 0,
  compacted: false
};
function hintFor(mode, liteReason) {
  if (mode === "full" || mode === "no-repo") return null;
  if (mode === "lite") return liteReason ?? "no-server";
  return mode;
}
function clearedConversation(state2) {
  const { mode, freshness, hint, hintsShown, repoRoot, contexts } = state2;
  return { ...initialSession, mode, freshness, hint, hintsShown, repoRoot, contexts, pane: { tab: state2.pane.tab, draft: "" } };
}
function reduce(state2, action) {
  switch (action.type) {
    case "discovered": {
      const kind = hintFor(action.mode, action.liteReason);
      const indexed = action.mode === "full" || action.mode === "lite";
      const freshness = indexed ? action.freshness : null;
      const repoRoot = indexed ? action.repoRoot ?? null : null;
      const savings = action.mode === "full" ? state2.savings : null;
      if (kind !== null && !state2.hintsShown.includes(kind)) {
        const hintsShown = [...state2.hintsShown, kind];
        return { ...state2, mode: action.mode, freshness, repoRoot, savings, hint: kind, hintsShown };
      }
      const hint = state2.hint === kind ? state2.hint : null;
      return { ...state2, mode: action.mode, freshness, repoRoot, savings, hint };
    }
    case "turnCompleted":
      return state2.hint === null ? state2 : { ...state2, hint: null };
    case "toolStarted":
      return { ...state2, running: action.tool };
    case "toolEnded":
      return state2.running?.id === action.id ? { ...state2, running: null } : state2;
    case "contextLoaded":
      return { ...state2, contexts: { ...state2.contexts, [action.file]: action.context } };
    case "notesFor": {
      if (action.notes.length === 0) return state2;
      const notes = { ...state2.notes, [action.id]: action.notes };
      const decision = action.notes.find((n) => n.kind === "decision");
      const review = decision === void 0 ? state2.review : reduceReview(state2.review, { type: "decisionNoted", title: decision.title });
      return { ...state2, notes, review };
    }
    case "savings":
      return { ...state2, savings: action.delta.tokens > 0 ? action.delta : null };
    case "touched":
      return state2.touched.includes(action.path) ? state2 : { ...state2, touched: [...state2.touched, action.path] };
    case "tab":
      return { ...state2, pane: { tab: action.tab, draft: action.draft ?? state2.pane.draft } };
    case "asked": {
      const modelAsks = state2.modelAsks + (action.tool === "get_answer" ? 1 : 0);
      const ask = { phase: "asking", question: action.question, tool: action.tool, busy: false };
      return { ...state2, modelAsks, ask, pane: { ...state2.pane, draft: "" } };
    }
    case "askBusy":
      return state2.ask.phase === "asking" && !state2.ask.busy ? { ...state2, ask: { ...state2.ask, busy: true } } : state2;
    case "answered": {
      const modelAsks = Math.max(0, state2.modelAsks - (action.answer.tool === "get_answer" && !mayHaveUsedModel(action.answer) ? 1 : 0));
      return { ...state2, modelAsks, ask: { phase: "answered", question: action.question, answer: action.answer } };
    }
    case "askFailed":
      return { ...state2, ask: { phase: "failed", question: action.question, tool: action.tool, message: action.message } };
    case "compacted":
      return state2.compacted ? state2 : { ...state2, compacted: true };
    case "briefDone":
      return state2.compacted ? { ...state2, compacted: false } : state2;
    default:
      return reduceTurn(state2, action);
  }
}
function reduceTurn(state2, action) {
  const review = reduceReview(state2.review, action);
  const compacted = action.type === "turnStarted" ? false : state2.compacted;
  const lastReview = action.type === "reviewed" && reviewable(action.risk) ? action.risk : state2.lastReview;
  if (review === state2.review && compacted === state2.compacted && lastReview === state2.lastReview) return state2;
  return { ...state2, review, compacted, lastReview };
}
function surfacedDecisions(state2) {
  const seen = /* @__PURE__ */ new Map();
  for (const notes of Object.values(state2.notes)) {
    for (const n of notes) if (n.kind === "decision" && !seen.has(n.title)) seen.set(n.title, n.reviewed);
  }
  return [...seen].map(([title, reviewed]) => ({ title, reviewed }));
}

// src/views/review.ts
var PRESS = { tests: "lens-review-tests", why: "lens-review-why", details: "lens-review-details" };
var COMPARED = /* @__PURE__ */ new Set(["available", "partial"]);
var NOT_REPORTED = { words: HEALTH_NOT_REPORTED, short: HEALTH_NOT_REPORTED };
function notComparedWords(hd) {
  return { words: notCompared(hd.explanation.replace(/\.$/, "")), short: notCompared("") };
}
function clearWords(hd) {
  if (hd.resolved === 0) return { words: noNewFindings(hd.scope?.analyzed ?? 0), short: NO_NEW_FINDINGS };
  return { words: healthImproved(hd.resolved), short: improvedShort(hd.resolved), color: DARK.success };
}
var FINDINGS_TONE = {
  review_required: { required: true, color: DARK.error },
  review_recommended: { required: false, color: DARK.warning }
};
function findingsWords(d, hd) {
  const headline = d.headline.replace(/\.$/, "");
  const words = hd.resolved > 0 ? `${headline}; ${resolvedToo(hd.resolved)}` : headline;
  const tone = FINDINGS_TONE[d.status];
  if (tone === void 0) return { words, short: PARTLY_COMPARED };
  return { words, short: newFindings(hd.findings_total, tone.required), color: tone.color };
}
function health(risk) {
  const d = risk.directive;
  const hd = risk.health_delta;
  if (d === void 0 || hd === void 0) return NOT_REPORTED;
  if (!COMPARED.has(hd.status)) return notComparedWords(hd);
  if (d.status === "clear_in_analyzed_scope") return clearWords(hd);
  return findingsWords(d, hd);
}
function overlap(risk) {
  const block = risk.branch_overlap;
  const branches = block?.branches ?? [];
  if (branches.length === 0) return null;
  const files = [...new Set(branches.flatMap((b) => (b.files ?? []).map((f) => f.file)))];
  return { branches: branches.map((b) => b.branch), files, more: block?.truncated === true };
}
function isClear(risk) {
  return risk.directive?.status === "clear_in_analyzed_scope";
}
function header2(risk, changed) {
  return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree === true, changed)})`;
}
function findingSegments(hd) {
  const rows = hd?.top_findings ?? [];
  const segments = rows.map(findingLine);
  const more = (hd?.findings_total ?? 0) - rows.length;
  if (more > 0) segments.push(moreFindings(more));
  return segments;
}
function scopeSegments(hd) {
  if (hd?.status !== "partial" || hd.scope === void 0) return [];
  return [partialScope(hd.scope.analyzed, hd.scope.changed, hd.skipped?.by_reason ?? {})];
}
function testSegments(risk) {
  const tests = testsToRun(risk);
  return tests === null ? [] : [testsLine(tests)];
}
function overlapSegments(risk) {
  const shared = overlap(risk);
  return shared === null ? [] : [`Branches: ${overlapLine(shared.branches, shared.files, shared.more)}`];
}
function cardSegments(risk) {
  if (isClear(risk) && overlap(risk) === null) return [header2(risk, null), `health: ${health(risk).words}`];
  const hd = risk.health_delta;
  return [
    header2(risk, hd?.scope?.changed ?? null),
    `Health: ${health(risk).words}`,
    ...findingSegments(hd),
    ...scopeSegments(hd),
    diffShape(risk.risk_percentile),
    ...testSegments(risk),
    ...overlapSegments(risk)
  ];
}
function doneText(risk) {
  if (risk.error !== void 0) return reviewFailed(risk.error);
  if (emptyDiff(risk)) return null;
  return cardSegments(risk).join(" · ");
}
function reviewText(outcome) {
  switch (outcome.phase) {
    case "none":
    case "reviewing":
      return null;
    case "failed":
      return outcome.reason === "timeout" ? REVIEW_TIMED_OUT : reviewFailed(outcome.message);
    case "done":
      return doneText(outcome.risk);
  }
}
function buttons(risk, decision) {
  const out = [];
  if (testsToRun(risk) !== null) out.push(button(PRESS.tests, "1", RUN_TESTS));
  if (decision !== null) out.push(button(PRESS.why, "2", WHY));
  if (risk.directive !== void 0) out.push(button(PRESS.details, "3", DETAILS));
  return out;
}
var GAP2 = 2;
function buttonCells(pressable) {
  return pressable.reduce((n, b) => n + (b.type === "Button" ? b.props.label.length + 3 : 0) + GAP2, 0);
}
function quietInBand(risk, decision) {
  return isClear(risk) && testsToRun(risk) === null && overlap(risk) === null && decision === null;
}
function summaryParts(risk, room) {
  const h = health(risk);
  const words = fit(`review · health: ${h.short}`, room);
  const parts = [text(words, h.color === void 0 ? { dimColor: true } : { color: h.color })];
  const shared = overlap(risk);
  const tail = shared === null ? "" : ` · ${overlapShort(shared.branches.length)}`;
  if (tail !== "" && room - words.length >= tail.length) parts.push(text(tail, { dimColor: true }));
  return parts;
}
function resultRow(risk, columns, decision) {
  if (!reviewable(risk) || quietInBand(risk, decision)) return null;
  const pressable = buttons(risk, decision);
  const room = Math.max(0, columns - buttonCells(pressable));
  return box({ key: "lens-review", flexDirection: "row", columnGap: GAP2 }, [
    box({ flexDirection: "row" }, summaryParts(risk, room)),
    ...pressable
  ]);
}
function reviewBandRow(outcome, columns, decision = null) {
  if (outcome.phase === "reviewing") return text(fit(REVIEWING, columns), { dimColor: true, wrap: "truncate-end" });
  return outcome.phase === "done" ? resultRow(outcome.risk, columns, decision) : null;
}
function directiveRows(outcome) {
  if (outcome.phase !== "done" || outcome.risk.directive === void 0) return null;
  return directiveLines(outcome.risk.directive);
}
function runTestsText(outcome) {
  if (outcome.phase !== "done") return null;
  const tests = testsToRun(outcome.risk);
  return tests === null ? null : runTestsPrompt(tests);
}
function withCard(result, answer, card) {
  if (typeof result !== "object" || result === null) return result;
  const r = result;
  if (typeof r.text !== "string") return result;
  return { ...r, text: r.text === answer ? card : `${r.text} · ${card}` };
}

// src/views/brief.ts
var BRIEF_PRESS = "lens-brief";
var ITEM_CHARS = 240;
function listWithin(head, items, room) {
  const cut = items.map((i) => fit(i.replace(/\s+/g, " ").trim(), ITEM_CHARS));
  for (let k = cut.length; k >= 0; k--) {
    const more = cut.length - k;
    const shown = cut.slice(0, k).join("; ");
    const tail = more === 0 ? "" : `${shown === "" ? "" : "; "}and ${more} more`;
    const line2 = `${head} ${shown}${tail}`;
    if (line2.length <= room) return line2;
  }
  return fit(`${head} and ${cut.length} more`, room);
}
function reviewItems(state2) {
  const risk = state2.lastReview;
  if (risk === null) return [];
  const findings = (risk.health_delta?.findings_total ?? 0) > 0 ? (risk.health_delta?.top_findings ?? []).map(findingLine) : [];
  const tests = testsToRun(risk);
  const shared = overlap(risk);
  return [
    ...findings,
    ...tests === null ? [] : [briefTests(tests)],
    ...shared === null ? [] : [overlapLine(shared.branches, shared.files, shared.more)]
  ];
}
function briefText(state2) {
  const sections = [
    [BRIEF_COPY.files, [...state2.touched]],
    [BRIEF_COPY.decisions, surfacedDecisions(state2).map((d) => briefDecision(d.title, d.reviewed))],
    [BRIEF_COPY.review, reviewItems(state2)]
  ];
  const filled = sections.filter(([, items]) => items.length > 0);
  if (filled.length === 0) return null;
  let brief = BRIEF_COPY.intro;
  filled.forEach(([head, items], i) => {
    const room = Math.floor((BRIEF_CHARS - brief.length) / (filled.length - i)) - 1;
    brief += `
${listWithin(head, items, Math.max(0, room))}`;
  });
  return brief;
}
function briefBandRow(state2, columns, besideReview = false) {
  if (!state2.compacted || briefText(state2) === null) return null;
  return box({ key: "lens-brief", flexDirection: "row", columnGap: 2 }, [
    text(fit(BRIEF_COPY.compacted, Math.max(1, columns - BRIEF_COPY.button.length - 5)), { dimColor: true }),
    button(BRIEF_PRESS, besideReview ? "4" : "1", BRIEF_COPY.button)
  ]);
}

// src/views/band.ts
var MAX_BAND_ROWS = 2;
function bandRows(state2, columns = Number.POSITIVE_INFINITY) {
  const rows = [];
  if (state2.hint !== null) rows.push(HINTS[state2.hint]);
  if (state2.freshness !== null) rows.push(freshnessLine(state2.freshness));
  if (state2.savings !== null) rows.push(savingsLine(state2.savings, columns));
  return rows.slice(0, MAX_BAND_ROWS);
}
function bandView(state2, viewport, extra = []) {
  if (viewport.hasSurvey) return null;
  const review = reviewBandRow(state2.review.outcome, viewport.columns, state2.review.decision);
  const actions = [review, briefBandRow(state2, viewport.columns, review !== null)].filter((n) => n !== null);
  const own = [...bandRows(state2, viewport.columns), ...extra].slice(0, Math.max(0, MAX_BAND_ROWS - actions.length));
  if (own.length === 0 && actions.length === 0) return null;
  const nodes = own.map((row2) => text(fit(row2, viewport.columns), { dimColor: true, wrap: "truncate-end" }));
  return box({ key: "lens-band", flexDirection: "column" }, [...nodes, ...actions]);
}

// src/views/margin.ts
var MAX_MARGIN_LINES = 2;
function marginView(notes) {
  if (notes === void 0 || notes.length === 0) return null;
  return box(
    { key: "lens-margin", flexDirection: "column" },
    notes.slice(0, MAX_MARGIN_LINES).map((n) => text(`  ${marginLine(n)}`, { dimColor: true, wrap: "truncate-end" }))
  );
}

// src/views/answer.ts
var LIST_ROWS = 5;
var ROW_CHARS = 300;
var code = (s) => `\`${s.replace(/`/g, "'")}\``;
var line = (s, chars = ROW_CHARS) => fit(s.replace(/\s+/g, " ").trim(), chars);
function ids(refs) {
  const found = (refs ?? []).map((r) => r.id).filter((id) => typeof id === "string");
  return found.length === 0 ? "" : ` · ${found.map(code).join(" ")}`;
}
function list(head, rows, row2, total2) {
  if (rows === void 0 || rows.length === 0) return [];
  const shown = rows.slice(0, LIST_ROWS);
  const more = Math.max(total2 ?? 0, rows.length) - shown.length;
  return [`**${head}**`, ...shown.map((r) => `- ${row2(r)}`), ...more > 0 ? [`- ${moreRows(more)}`] : []];
}
function answerHead(a) {
  const parts = [`**${a.degraded === void 0 ? PANE_COPY.fromModel : PANE_COPY.fromIndex}**`];
  if (a.confidence !== void 0) parts.push(`confidence ${a.confidence}`);
  if (a.retrieval_quality !== void 0) parts.push(`retrieval ${a.retrieval_quality}`);
  return parts.join(" · ");
}
function answerMarkdown(a) {
  const cited = a.citations ?? [];
  const evidence = cited.length === 0 ? PANE_COPY.noEvidence : `evidence: ${cited.map(code).join(", ")}`;
  return [answerHead(a), a.answer ?? "", evidence];
}
var decisionRow = (d) => {
  const facts = [d.status, d.authority, d.confidence === null || d.confidence === void 0 ? void 0 : `confidence ${d.confidence}`].filter((f) => f !== void 0).join(" · ");
  const id = d.id === void 0 ? "" : ` · ${code(d.id)}`;
  const body = d.decision === void 0 ? "" : `: ${line(d.decision)}`;
  return `**${line(d.title, 120)}**${facts === "" ? "" : ` (${facts})`}${id}${body}`;
};
var commitRow = (c) => `${code(c.sha ?? "?")} ${line(c.message ?? "", 160)}${c.date === void 0 ? "" : ` (${c.date.slice(0, 10)})`}${ids(c.evidence_refs)}`;
var rationaleRow = (r) => `${code(r.lines === void 0 ? r.path : `${r.path}:${r.lines[0]}`)} ${line(r.comment)}${ids(r.evidence_refs)}`;
function whyMarkdown(w) {
  const from = `**${PANE_COPY.fromIndex}**`;
  const head = w.answer_basis === void 0 ? from : `${from} · basis ${w.answer_basis}`;
  const commits = w.git_archaeology?.git_log ?? w.git_archaeology?.file_commits;
  return [
    head,
    ...w.reason === void 0 ? [] : [w.reason],
    ...list("Decisions", w.decisions, decisionRow),
    ...list("Commits", commits, commitRow),
    ...list("Rationale in the code", w.code_rationale, rationaleRow, w.code_rationale_total)
  ];
}
function replyMarkdown(question, a) {
  const body = a.tool === "get_answer" ? answerMarkdown(a.reply) : whyMarkdown(a.reply);
  const text2 = [`> ${line(question, 200)}`, ...body].join("\n\n");
  if (text2.length <= ASK_CHARS) return text2;
  const note = `

_${askCut(ASK_CHARS)}_`;
  return `${text2.slice(0, ASK_CHARS - note.length).trimEnd()}${note}`;
}

// src/views/pane.ts
function tabBar(flowOn2) {
  return flowOn2 ? TAB_BAR : TAB_BAR.filter((t) => t !== "flow");
}
var tabPress = (tab) => `lens-tab-${tab}`;
var ASK_KEY = "lens-ask";
var TAB_ROWS = 1;
function tabsView(current, tabs = TAB_BAR) {
  return box(
    { key: "lens-tabs", flexDirection: "row", columnGap: 2 },
    tabs.map((tab, i) => button(tabPress(tab), String(i + 1), PANE_COPY.tabs[tab], tab !== current))
  );
}
var dim = (line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" });
function askStatus(state2, columns) {
  const ask = state2.ask;
  switch (ask.phase) {
    case "idle":
      return [dim(PANE_COPY.askIdle, columns)];
    case "asking":
      return [
        dim(`> ${ask.question}`, columns),
        dim(askingLine(ask.tool), columns),
        ...ask.busy ? [dim(PANE_COPY.askBusy, columns)] : []
      ];
    case "failed":
      return [dim(`> ${ask.question}`, columns), dim(askFailedLine(ask.message), columns)];
    case "answered":
      return [markdown(replyMarkdown(ask.question, ask.answer))];
  }
}
function askView(state2, columns) {
  const field = input({
    key: ASK_KEY,
    label: PANE_COPY.askLabel,
    placeholder: PANE_COPY.askPlaceholder,
    submitLabel: PANE_COPY.askSubmit,
    autoFocus: true,
    ...state2.pane.draft === "" ? {} : { value: state2.pane.draft }
  });
  return box({ key: "lens-ask-tab", flexDirection: "column" }, [field, ...askStatus(state2, columns)]);
}
function overlapWords(risk) {
  const shared = overlap(risk);
  if (shared !== null) return overlapLine(shared.branches, shared.files, shared.more);
  return risk.branch_overlap === void 0 ? RECAP_COPY.notReported : RECAP_COPY.noOverlap;
}
function reviewRows(state2) {
  const risk = state2.lastReview;
  if (risk === null) return [[RECAP_COPY.review, RECAP_COPY.noReview]];
  const hd = risk.health_delta;
  const compared = hd !== void 0 && (hd.status === "available" || hd.status === "partial");
  const tests = testsToRun(risk);
  return [
    RECAP_COPY.fromReview,
    [RECAP_COPY.health, health(risk).words],
    [RECAP_COPY.findings, compared ? findingsCounts(hd.resolved, hd.findings_total) : RECAP_COPY.notCompared],
    [RECAP_COPY.tests, tests === null ? RECAP_COPY.noTests : testsToRunCount(tests)],
    [RECAP_COPY.overlap, overlapWords(risk)]
  ];
}
function savedRow(state2) {
  if (state2.savings !== null) return savingsLine(state2.savings, Number.POSITIVE_INFINITY);
  return state2.mode === "full" ? RECAP_COPY.noSavings : RECAP_COPY.savingsNeedServer;
}
function recapRows(state2, touched) {
  const decisions = surfacedDecisions(state2).map((d) => d.title);
  return [
    [RECAP_COPY.files, filesTouched(state2.touched.length, touched)],
    ...reviewRows(state2),
    [RECAP_COPY.saved, savedRow(state2)],
    [RECAP_COPY.decisions, decisions.length === 0 ? RECAP_COPY.noDecisions : decisionsSurfaced(decisions)]
  ];
}
function recapView(state2, touched, columns) {
  const rows = recapRows(state2, touched);
  const width2 = Math.max(...rows.map((r) => typeof r === "string" ? 0 : r[0].length)) + 2;
  const drawn = rows.map(
    (r) => typeof r === "string" ? dim(r, columns) : box({ flexDirection: "row" }, [
      text(r[0].padEnd(width2), { dimColor: true }),
      text(fit(r[1], Math.max(1, columns - width2)), { wrap: "truncate-end" })
    ])
  );
  return box({ key: "lens-recap", flexDirection: "column" }, [...drawn, dim(recapFooter(state2.modelAsks), columns)]);
}
function paneView(tab, body, tabs = TAB_BAR) {
  return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab, tabs), body]);
}

// src/views/spinner.ts
function spinnerSuffix(state2) {
  if (state2.running === null) return null;
  const ctx = state2.contexts[state2.running.file];
  return ctx === void 0 ? null : spinnerLine(state2.running.file, ctx);
}

// src/model/squeeze.ts
var MARKER = /^\[repowise#([0-9a-f]{12}): (\d+) lines omitted \(~(\d+) tokens\); restore: repowise expand \1\]$/;
function markerOf(line2) {
  const m = MARKER.exec(line2.trim());
  return m === null ? null : { ref: m[1], lines: Number(m[2]), tokens: Number(m[3]) };
}
var isBlank = (line2) => line2.trim() === "";
function trailingMarkers(lines) {
  let end = lines.length;
  const markers = [];
  while (end > 0) {
    const line2 = lines[end - 1];
    const marker = isBlank(line2) ? null : markerOf(line2);
    if (!isBlank(line2) && marker === null) break;
    if (marker !== null) markers.unshift(marker);
    end--;
  }
  return { kept: lines.slice(0, end), markers };
}
var PYTEST_SUMMARY = /^=+ (.*\b(?:passed|failed|error|errors|skipped)\b.*) =+$/;
var PYTEST_FAILED = /\b(\d+) failed\b/;
var PYTEST_ERRORS = /\b(\d+) errors?\b/;
var JEST_SUMMARY = /^\s*Tests?:\s.*?\b(\d+) failed\b/;
var CARGO_SUMMARY = /^test result: \w+\. \d+ passed; (\d+) failed;/;
var GO_FAIL = /^--- FAIL:/;
function pytestCounts(line2) {
  const m = PYTEST_SUMMARY.exec(line2);
  if (m === null) return null;
  return { failed: Number(PYTEST_FAILED.exec(m[1])?.[1] ?? 0), errors: Number(PYTEST_ERRORS.exec(m[1])?.[1] ?? 0) };
}
function runnerFailures(kept) {
  let cargo = 0;
  let go = 0;
  for (const line2 of kept) {
    const pytest = pytestCounts(line2);
    if (pytest !== null) return pytest;
    const jest = JEST_SUMMARY.exec(line2);
    if (jest !== null) return { failed: Number(jest[1]), errors: 0 };
    cargo += Number(CARGO_SUMMARY.exec(line2)?.[1] ?? 0);
    if (GO_FAIL.test(line2)) go++;
  }
  return { failed: cargo + go, errors: 0 };
}
function parseSqueeze(output) {
  const { kept, markers } = trailingMarkers(output.split(/\r?\n/));
  if (markers.length === 0) return null;
  const refs = /* @__PURE__ */ new Set();
  let lines = 0;
  let tokens = 0;
  for (const m of markers) {
    if (refs.has(m.ref)) continue;
    refs.add(m.ref);
    lines += m.lines;
    tokens += m.tokens;
  }
  return {
    originalLines: kept.length + lines,
    keptLines: kept.length,
    omittedTokens: tokens,
    ...runnerFailures(kept),
    refs: [...refs]
  };
}
function bashText(output) {
  if (typeof output === "string") return output;
  const stdout = output?.stdout;
  return typeof stdout === "string" ? stdout : null;
}

// src/views/squeeze.ts
var BAR_CELLS = 12;
function squeezeBar(s, cells = BAR_CELLS) {
  const filled = Math.min(cells, Math.max(1, Math.round(cells * s.keptLines / Math.max(1, s.originalLines))));
  return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;
}
function squeezeView(s) {
  return text(`${squeezeBar(s)} ${squeezeLine(s)}`, { dimColor: true, wrap: "truncate-end" });
}

// src/register.ts
var PROCESS_TIMEOUT_MS = 5e3;
var SAVINGS_TIMEOUT_MS = 3e4;
var SAVINGS_COOLDOWN_MS = 6e4;
var MCP_SERVER_KEY = "repowise";
var PANE_ID = "lens";
var PANE_ROWS = 29;
var ASK_TIMEOUT_MS = 3e4;
var flowOn = true;
var flow = new LensFlow();
var reducedMotion = false;
function freshSession() {
  return flowOn ? initialSession : reduce(initialSession, { type: "tab", tab: "map" });
}
var state = initialSession;
var generation = 0;
var running = false;
var dirty = false;
var latest = null;
var mcpConnected = false;
var savingsBase = null;
var savingsBusy = false;
var savingsAskedAt = Number.NEGATIVE_INFINITY;
var squeezes = /* @__PURE__ */ new Map();
var contextAsked = /* @__PURE__ */ new Set();
var reviewOn = true;
var reviewGeneration = 0;
var editsThisTurn = 0;
var started2 = null;
var autoOpenOn = false;
var healthOn = false;
var discovery = null;
var cwd = null;
var map = new LensMap(false);
var animator = new Animator();
var ERROR_CELLS = 160;
function bind($) {
  const host = {
    session: { cwd: () => $.session.cwd() },
    fs: {
      read: (path) => $.fs.read(path),
      exists: (path) => $.fs.exists(path)
    },
    process: {
      run: (argv, cwd2) => $.process.run(argv, { cwd: cwd2, timeoutMs: PROCESS_TIMEOUT_MS })
    },
    http: (url, init) => {
      const request = {};
      if (init.method !== void 0) request.method = init.method;
      if (init.headers !== void 0) request.headers = init.headers;
      if (init.body !== void 0) request.body = init.body;
      return $.http.fetch(url, request);
    },
    mcp: {
      connect: async () => mcpConnected ||= (await $.mcp.connect(MCP_SERVER_KEY)).isConnected,
      server: async () => {
        const r = await $.mcp.connect(MCP_SERVER_KEY);
        return r.isConnected && typeof r.server === "string" ? r.server : null;
      },
      call: (server, tool, args) => $.mcp.call(server, tool, args)
    }
  };
  const bound = {
    host,
    blastLanded: (path, r) => flowBlast(bound, path, r),
    redraw: () => $.ui.invalidate("ui.render"),
    debug: (message) => $.ui.log(`lens: ${message}`, { to: "debug" }),
    blit: (key2, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: key2, cells, columns, rows }),
    // Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.
    // Opened unasked on a read: the map is what it opens to. This happens at most once, and never
    // after the person opened the pane (/lens, Why), the only ways to have picked a tab by then.
    openPane: (focus) => (focus ? null : state = reduce(state, { type: "tab", tab: "map" }), $.ui.open(
      focus ? { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS, focus: true } : { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS }
    )),
    closePane: () => $.ui.close({ id: PANE_ID })
  };
  animator.use(bound);
  return bound;
}
function mapRepo(d) {
  if (d.mode !== "full" || d.repo === void 0 || d.repoRoot === null) return null;
  return { id: d.repo.id, root: d.repoRoot, updatedAt: d.repo.updatedAt, caseInsensitive: isWindowsPath(d.repoRoot) };
}
function dispatch(b, action) {
  const next = reduce(state, action);
  if (next === state) return;
  state = next;
  b.redraw();
}
async function refreshOnce(b, gen) {
  const h = b.host;
  const found = await discover(h);
  const indexed = found.mode === "full" || found.mode === "lite";
  const freshness = indexed && found.repoRoot !== null ? await readFreshness(h, found.repoRoot) : null;
  if (gen !== generation) return;
  if (indexed) warmMcp(h);
  discovery = found;
  const action = { type: "discovered", mode: found.mode, freshness, repoRoot: found.repoRoot };
  if (found.liteReason !== void 0) action.liteReason = found.liteReason;
  dispatch(b, action);
  if (found.repo !== void 0) refreshSavings(b, found.repo.id, gen);
  map.setRepo(b, mapRepo(found));
}
function refreshSavings(b, repoId, gen) {
  const now = Date.now();
  if (savingsBusy || now - savingsAskedAt < SAVINGS_COOLDOWN_MS) return;
  savingsBusy = true;
  savingsAskedAt = now;
  withTimeout(getSavings(repoId), SAVINGS_TIMEOUT_MS, "savings").then((s) => {
    if (gen !== generation) return;
    const totals = savingsTotals(s);
    const delta = savingsBase?.repoId === repoId ? savingsSince(totals, savingsBase.totals) : null;
    if (delta !== null) {
      dispatch(b, { type: "savings", delta });
      return;
    }
    if (savingsBase !== null) dispatch(b, { type: "savings", delta: { tokens: 0, inferredTokens: 0, usd: 0 } });
    savingsBase = { repoId, totals };
  }).catch((err) => b.debug(`savings failed: ${String(err)}`)).finally(() => savingsBusy = false);
}
function refresh(b) {
  latest = b;
  if (running) {
    dirty = true;
    return;
  }
  running = true;
  dirty = false;
  refreshOnce(b, generation).catch((err) => b.debug(`refresh failed: ${String(err)}`)).finally(() => {
    running = false;
    if (dirty && latest !== null) refresh(latest);
  });
}
async function onSessionStart($, e, next) {
  const b = bind($);
  try {
    generation++;
    cwd = typeof e.cwd === "string" ? e.cwd : null;
    map.dispose();
    animator.end();
    animator = new Animator();
    map = new LensMap(autoOpenOn, animator, healthOn, mapTurn);
    flow.dispose();
    flow = new LensFlow();
    state = freshSession();
    reviewGeneration++;
    editsThisTurn = 0;
    started2 = null;
    contextAsked.clear();
    squeezes.clear();
    savingsBase = null;
    savingsAskedAt = Number.NEGATIVE_INFINITY;
    resetMcp();
    warmMcp(b.host);
    refresh(b);
    await $.command.register({ name: "lens", description: PANE_COPY.command, argumentHint: PANE_COPY.argumentHint, immediate: true });
    readTheme($);
    reducedMotion = (await $.settings.read())["prefersReducedMotion"] === true;
    map.setReducedMotion(reducedMotion);
    flow.setReducedMotion(reducedMotion);
  } catch (err) {
    b.debug(`session.start failed: ${String(err)}`);
  }
  return next(e);
}
async function onTurnComplete($, e, next) {
  const b = bind($);
  noteTurnEnd(b, e);
  const result = await next(e);
  return reviewOn && shouldReview(e, editsThisTurn) ? withReview(b, e, result) : result;
}
function noteTurnEnd(b, e) {
  try {
    const action = fromTurnComplete(e);
    if (action === null) return;
    noteFlow(b, () => ({ type: "turnEnded", at: Date.now(), durationMs: e.durationMs ?? null, end: turnEnd(e.reason, e.isAborted) }));
    map.turnEnded();
    dispatch(b, action);
    refresh(b);
  } catch (err) {
    b.debug(`turn.complete failed: ${String(err)}`);
  }
}
async function withReview(b, e, result) {
  try {
    const card = await finishReview(b);
    return card === null ? result : withCard(result, e.answer ?? "", card);
  } catch (err) {
    b.debug(`change review failed: ${String(err)}`);
    return result;
  }
}
async function fetchReview(b) {
  try {
    const risk = await callTool(b.host, "get_change_risk", {}, { timeoutMs: REVIEW_TIMEOUT_S * 1e3 });
    return { type: "reviewed", risk };
  } catch (err) {
    b.debug(`change review failed: ${String(err)}`);
    const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);
    return { type: "reviewFailed", reason: err instanceof Error && err.name === "TimeoutError" ? "timeout" : "error", message };
  }
}
function startReview(b) {
  const review = { gen: reviewGeneration, covers: editsThisTurn, settled: false, outcome: fetchReview(b) };
  void review.outcome.then(() => {
    review.settled = true;
  });
  started2 = review;
  return review;
}
function reviewAfterEdit(b) {
  editsThisTurn++;
  dispatch(b, { type: "fileEdited" });
  if (started2 !== null && started2.gen === reviewGeneration && !started2.settled) return;
  startReview(b);
}
function coveringReview() {
  const s = started2;
  return s !== null && s.gen === reviewGeneration && s.covers === editsThisTurn ? s : null;
}
async function outcomeOf(b, review, reused) {
  const action = await review.outcome;
  return reused && isRetryable(action) ? startReview(b).outcome : action;
}
async function finishReview(b) {
  const gen = reviewGeneration;
  const reused = coveringReview();
  const review = reused ?? startReview(b);
  if (!review.settled) dispatch(b, { type: "reviewStarted" });
  const action = await outcomeOf(b, review, reused !== null);
  if (gen !== reviewGeneration) return null;
  dispatch(b, action);
  return reviewText(state.review.outcome);
}
async function onTurnStart($, e, next) {
  noteFlow(bind($), () => ({ type: "turnStarted", turnId: e.turnId ?? null, prompt: e.text ?? "", at: Date.now() }));
  try {
    if (reviewOn) {
      reviewGeneration++;
      editsThisTurn = 0;
      started2 = null;
    }
    dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });
    map.turnStarted();
  } catch (err) {
    bind($).debug(`turn.start failed: ${String(err)}`);
  }
  return next(e);
}
function pressRunTests($) {
  try {
    const prompt = runTestsText(state.review.outcome);
    if (prompt === null) return;
    $.prompt.submit({ text: prompt }).catch((err) => bind($).debug(`run tests failed: ${String(err)}`));
  } catch (err) {
    bind($).debug(`run tests failed: ${String(err)}`);
  }
}
function pressWhy($) {
  const b = bind($);
  try {
    const decision = state.review.decision;
    if (decision === null) return;
    dispatch(b, { type: "tab", tab: "ask", draft: whyDraft(decision) });
    map.request(b).catch((err) => b.debug(`why failed: ${String(err)}`));
  } catch (err) {
    b.debug(`why failed: ${String(err)}`);
  }
}
function pressBrief($) {
  const b = bind($);
  try {
    const brief = briefText(state);
    dispatch(b, { type: "briefDone" });
    if (brief === null) return;
    $.prompt.submit({ text: brief }).catch((err) => b.debug(`brief failed: ${String(err)}`));
  } catch (err) {
    b.debug(`brief failed: ${String(err)}`);
  }
}
async function onSessionEnd($, e, next) {
  if (e.reason !== "clear") return next(e);
  const b = bind($);
  try {
    animator.end();
    flow.dispose();
    flow = new LensFlow();
    flow.setReducedMotion(reducedMotion);
    map.clearConversation(b);
    state = clearedConversation(state);
    reviewGeneration++;
    editsThisTurn = 0;
    started2 = null;
    squeezes.clear();
    savingsBase = null;
    savingsAskedAt = Number.NEGATIVE_INFINITY;
    b.redraw();
  } catch (err) {
    b.debug(`clear failed: ${String(err)}`);
  }
  return next(e);
}
async function onPostCompact($, e, next) {
  try {
    dispatch(bind($), { type: "compacted" });
  } catch (err) {
    bind($).debug(`PostCompact failed: ${String(err)}`);
  }
  return next(e);
}
function startAsk(b, question) {
  const q = question.trim();
  if (q === "") return;
  if (state.ask.phase === "asking") return dispatch(b, { type: "askBusy" });
  const { tool, args } = askRoute(q);
  dispatch(b, { type: "asked", question: q, tool });
  const gen = generation;
  callTool(b.host, tool, args, { timeoutMs: ASK_TIMEOUT_MS }).then((reply) => {
    if (gen !== generation) return;
    const answer = askReply(tool, reply);
    dispatch(b, { type: "answered", question: q, answer });
  }).catch((err) => {
    b.debug(`ask failed: ${String(err)}`);
    const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);
    if (gen !== generation) return;
    dispatch(b, { type: "askFailed", question: q, tool, message });
  });
}
async function onAskInput($, e, next) {
  try {
    if (e.kind === "submit" && e.element === ASK_KEY) startAsk(bind($), e.value);
  } catch (err) {
    bind($).debug(`ask failed: ${String(err)}`);
  }
  return next(e);
}
function pressDetails($) {
  try {
    for (const row2 of directiveRows(state.review.outcome) ?? []) $.ui.log(row2, { to: "transcript" });
  } catch (err) {
    bind($).debug(`details failed: ${String(err)}`);
  }
}
async function onBand($, e, next) {
  const theirs = await next(e);
  try {
    const line2 = map.bandLine();
    const viewport = { columns: e.props.bodyColumns ?? 80, hasSurvey: e.props.hasSurvey === true };
    const tree = bandView(state, viewport, line2 === null ? [] : [line2]);
    if (tree === null) return theirs;
    const elements = $.ui.resolve(e);
    const ours = materialize(tree, elements, {
      [PRESS.tests]: () => pressRunTests($),
      [PRESS.why]: () => pressWhy($),
      [PRESS.details]: () => pressDetails($),
      [BRIEF_PRESS]: () => pressBrief($)
    });
    const box2 = elements["Box"];
    if (theirs === null || theirs === void 0 || box2 === void 0) return ours;
    return box2({ flexDirection: "column", children: [ours, theirs] });
  } catch (err) {
    bind($).debug(`band render failed: ${String(err)}`);
    return theirs;
  }
}
function fetchContext(b, file) {
  if (contextAsked.has(file)) return;
  contextAsked.add(file);
  const gen = generation;
  fetchFileContext(b.host, file).then((context) => {
    if (gen !== generation || context === null) return;
    dispatch(b, { type: "contextLoaded", file, context });
  }).catch((err) => {
    contextAsked.delete(file);
    b.debug(`context for ${file} failed: ${String(err)}`);
  });
}
async function onToolCall($, e, next) {
  const b = bind($);
  const file = fileToolStarted(b, e);
  noteFlow(b, () => {
    const activity = activityOf(e, Date.now(), flowRoot());
    return activity === null ? null : { type: "toolStarted", activity };
  });
  let result = null;
  try {
    result = await next(e);
  } finally {
    if (file !== null) dispatch(b, { type: "toolEnded", id: e.tool_use_id });
    noteFlow(b, () => toolEnded(e, result, Date.now(), flowRoot()));
  }
  editLanded(b, e, result);
  observeTrail($, b, e, result);
  return result;
}
function flowPane(columns, rows) {
  const outcome = state.review.outcome;
  return { columns, rows, mode: state.mode, contexts: state.contexts, review: outcome.phase === "done" ? outcome.risk : null, light: theme === "light" };
}
function flowBlast(b, path, r) {
  noteFlow(b, () => ({ type: "blastLanded", path, facts: blastFacts(path, r) }));
}
function flowRoot() {
  return state.repoRoot ?? cwd;
}
function noteFlow(b, action) {
  if (!flowOn) return;
  try {
    const a = action();
    if (a !== null) flow.dispatch(b, a);
  } catch (err) {
    flowFailed(b, err);
  }
}
function flowFailed(b, err) {
  try {
    b.debug(`flow failed: ${String(err)}`);
  } catch {
    flowOn = false;
  }
}
function observeTrail($, b, e, result) {
  if (!OBSERVED_TOOLS.has(e.tool)) return;
  try {
    const here = cwd;
    if (here === null) {
      void $.session.cwd().then(
        (c) => cwd = c,
        (err) => b.debug(`cwd failed: ${String(err)}`)
      );
      return;
    }
    const ctx = { cwd: here, isWindows: isWindowsPath(here) };
    const action = fromToolCall(e, result, ctx);
    const raw = e.file_path;
    if (action !== null) map.observe(b, action, typeof raw === "string" ? absolutePath(raw, ctx) : null);
  } catch (err) {
    b.debug(`tool.call observe failed: ${String(err)}`);
  }
}
function fileToolStarted(b, e) {
  try {
    const file = fileTarget(e, state.repoRoot);
    if (file === null) return null;
    dispatch(b, { type: "toolStarted", tool: { id: e.tool_use_id, file } });
    fetchContext(b, file);
    return file;
  } catch (err) {
    b.debug(`tool.call failed: ${String(err)}`);
    return null;
  }
}
function editLanded(b, e, result) {
  try {
    if (!isFileEdit(e, result)) return;
    const path = touchedPath(e, cwd, state.repoRoot);
    if (path !== null) dispatch(b, { type: "touched", path });
    if (reviewOn) reviewAfterEdit(b);
  } catch (err) {
    b.debug(`tool.call failed: ${String(err)}`);
  }
}
async function onSpinner($, e, next) {
  let line2 = null;
  try {
    line2 = spinnerSuffix(state);
  } catch (err) {
    bind($).debug(`spinner render failed: ${String(err)}`);
  }
  if (line2 === null) return next(e);
  const theirs = typeof e.props.suffix === "string" ? e.props.suffix : "";
  return next({ ...e, props: { ...e.props, suffix: `${theirs} ${line2}` } });
}
function below(elements, theirs, tree) {
  const ours = materialize(tree, elements);
  const box2 = elements["Box"];
  if (theirs === null || theirs === void 0 || box2 === void 0) return ours;
  return box2({ flexDirection: "column", children: [theirs, ours] });
}
function squeezeOf(e) {
  const id = e.props.tool_use_id;
  const known = squeezes.get(id);
  if (known !== void 0 || e.props.tool !== "Bash") return known ?? null;
  const out = bashText(e.props.output);
  const found = out === null ? null : parseSqueeze(out);
  if (found !== null) squeezes.set(id, found);
  return found;
}
async function onToolResult($, e, next) {
  const theirs = await next(e);
  try {
    const s = squeezeOf(e);
    return s === null ? theirs : below($.ui.resolve(e), theirs, squeezeView(s));
  } catch (err) {
    bind($).debug(`squeeze render failed: ${String(err)}`);
    return theirs;
  }
}
async function onPostToolUse($, e, next) {
  const result = await next(e);
  try {
    if (EDIT_TOOLS.has(e.tool_name) && !e.tool_use_id.startsWith("toolu_plugin_")) {
      const notes = notesFromAugment(result?.additionalContext);
      if (notes.length > 0) dispatch(bind($), { type: "notesFor", id: e.tool_use_id, notes });
    }
  } catch (err) {
    bind($).debug(`PostToolUse failed: ${String(err)}`);
  }
  return result;
}
async function onToolUse($, e, next) {
  const theirs = await next(e);
  try {
    const tree = marginView(state.notes[e.props.tool_use_id]);
    return tree === null ? theirs : below($.ui.resolve(e), theirs, tree);
  } catch (err) {
    bind($).debug(`margin render failed: ${String(err)}`);
    return theirs;
  }
}
async function onLensCommand($, e) {
  const b = bind($);
  try {
    readTheme($);
    const asked = lensCommand(e.args ?? "", tabBar(flowOn));
    if (asked.tab !== null) dispatch(b, { type: "tab", tab: asked.tab });
    if (discovery === null || mapRepo(discovery) === null) refresh(b);
    await map.request(b);
    if (asked.question !== null) {
      await mcpReady(b.host);
      startAsk(b, asked.question);
    }
  } catch (err) {
    b.debug(`/lens failed: ${String(err)}`);
  }
  return {};
}
function tabPresses($, bar) {
  return Object.fromEntries(bar.map((tab) => [tabPress(tab), () => selectTab($, tab)]));
}
function flowRowPresses($) {
  return Object.fromEntries(flowPresses(flow.state).map(([key2, id]) => [key2, () => pressFlow($, key2, id)]));
}
function pressFlow($, key2, id) {
  noteFlow(bind($), () => id !== null ? { type: "toggle", id } : { type: "step", by: key2 === FLOW_NEXT ? 1 : -1 });
}
function selectTab($, tab) {
  try {
    dispatch(bind($), { type: "tab", tab });
  } catch (err) {
    bind($).debug(`tab failed: ${String(err)}`);
  }
}
var theme = "dark";
function readTheme($) {
  $.config.list().then((rows) => {
    theme = themeOf(rows.find((r) => r.key === "theme")?.value);
  }).catch((err) => bind($).debug(`theme failed: ${String(err)}`));
}
var TAB_BODIES = {
  flow: (b, e, rows) => flow.paneTree(b, flowPane(e.props.bodyColumns, rows), Date.now()),
  ask: (_b, e) => askView(state, e.props.bodyColumns),
  recap: (_b, e) => recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, e.props.bodyColumns),
  map: (b, e) => mapBody(b, e)
};
function mapTurn() {
  const knows = (path) => knowsOf(path, state.contexts, flowOn ? flow.state : null);
  if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state), knows };
  const root = state.repoRoot;
  const lit = root === null ? NO_LIT : litFromTrail(map.trail, root, isWindowsPath(root));
  return { lit, story: storyFromTrail(map.trail), knows };
}
function mapBody(b, e) {
  const { bodyColumns, placement, scroll } = e.props;
  const d = discovery;
  const notice2 = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];
  return map.paneTree(b, { surface: e.surface, notice: notice2, bodyColumns, placement, bodyRows: scroll.bodyRows - TAB_ROWS, theme });
}
function pressMap($, key2) {
  try {
    map.press(bind($), key2);
  } catch (err) {
    bind($).debug(`map key failed: ${String(err)}`);
  }
}
function mapPresses($) {
  return Object.fromEntries(MAP_PRESSES.map((key2) => [key2, () => pressMap($, key2)]));
}
function tabBody(b, e) {
  const tab = state.pane.tab;
  if (tab !== "map") map.offScreen();
  if (tab !== "flow") flow.hide();
  const rows = (e.props.placement === "dock" ? e.props.scroll.bodyRows : PANE_ROWS) - TAB_ROWS;
  try {
    return TAB_BODIES[tab](b, e, rows);
  } catch (err) {
    b.debug(`${tab} tab render failed: ${String(err)}`);
    return text(fit(PANE_COPY.bodyFailed, e.props.bodyColumns), { dimColor: true, wrap: "truncate-end" });
  }
}
async function onPane($, e, next) {
  if (e.requestId !== PANE_ID) return next(e);
  const b = bind($);
  try {
    const bar = tabBar(flowOn);
    const presses = { ...tabPresses($, bar), ...flowRowPresses($), ...mapPresses($) };
    return materialize(paneView(state.pane.tab, tabBody(b, e), bar), $.ui.resolve(e), presses);
  } catch (err) {
    b.debug(`pane render failed: ${String(err)}`);
    return next(e);
  }
}
function register(on, options = {}) {
  reviewOn = options["lens_review"] !== false;
  autoOpenOn = options["lens_pane_autoopen"] === true;
  healthOn = options["lens_map_health"] === true;
  flowOn = options["lens_flow"] !== false;
  state = freshSession();
  on("session.start", onSessionStart);
  on("session.end", onSessionEnd);
  on("turn.start", onTurnStart);
  on("turn.complete", onTurnComplete);
  on("ui.render", { component: "AbovePrompt" }, onBand);
  on("ui.render", { component: "Pane" }, onPane);
  on("command.run", { command: "lens" }, onLensCommand);
  on("ui.input", { plugin: "repowise", element: "lens-ask" }, onAskInput);
  on("classic.PostCompact", onPostCompact);
  on("tool.call", onToolCall);
  on("ui.render", { component: "Spinner" }, onSpinner);
  if (options["lens_squeeze"] !== false) {
    on("ui.render", { component: "ToolResult" }, onToolResult);
  }
  if (options["lens_margin"] !== false) {
    on("classic.PostToolUse", onPostToolUse);
    on("ui.render", { component: "ToolUse" }, onToolUse);
  }
}
export {
  register
};