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.

24.6 KB
Raw Blame
import Graph from "graphology";
import { isExternal } from "@repowise-dev/types";
import type {
  GraphExport,
  GraphNode,
  GraphLink,
  ModuleGraph,
  ModuleNode,
  ModuleEdge,
  CommunitySummaryItem,
} from "@repowise-dev/types/graph";
import forceAtlas2 from "graphology-layout-forceatlas2";
import noverlap from "graphology-layout-noverlap";
import type { SigmaNodeAttributes, SigmaEdgeAttributes } from "./types";
import {
  NODE_BASE_SIZES,
  EDGE_COLORS,
  EDGE_SIZE_MULTIPLIERS,
  CURVED_EDGE_THRESHOLD,
  PRESETTLE_MAX_NODES,
  SEED_JITTER_PER_SQRT_MEMBER,
  getFA2Settings,
  getPresettleIterations,
  getScaledNodeSize,
  getNodeMass,
  languageColor,
} from "./constants";

// Build-time placeholder for module/community node fills. The theme-aware
// community palette is applied by use-sigma's color effect (per light/dark);
// this neutral keeps modules visible for the one frame before that runs.
const PLACEHOLDER_NODE_COLOR = EDGE_COLORS.dynamic;
import { groupNodesAsModules } from "../elk-layout";

function simpleHash(str: string): number {
  let hash = 5381;
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) + hash + (str.charCodeAt(i) ?? 0)) | 0;
  }
  return Math.abs(hash);
}

/**
 * True for an edge that says two files change together rather than that one
 * depends on the other. The `"dynamic"` edge kind is this, keyed "Co-change".
 *
 * Read off `edge_type` when the payload carries it. On this repo's export
 * 5,521 of the 5,655 edges with no imported names are `co_changes`; the other
 * 134 (`framework`, `dynamic_uses`, name-less `imports`) are real dependencies
 * that the old names-only rule filed under the same key. A payload without
 * `edge_type` keeps that rule.
 */
export function isCoChangeLink(link: GraphLink): boolean {
  if (link.edge_type !== undefined) return link.edge_type === "co_changes";
  return link.imported_names.length === 0;
}

/** A dependency drawn by default: not co-change, not low confidence. */
export function isStructuralLink(link: GraphLink): boolean {
  if (link.confidence !== undefined && link.confidence < 0.5) return false;
  return !isCoChangeLink(link);
}

function classifyEdge(
  link: GraphLink,
  nodeMap: Map<string, GraphNode>,
): SigmaEdgeAttributes["edgeKind"] {
  if (link.confidence !== undefined && link.confidence < 0.5)
    return "lowConfidence";
  if (isCoChangeLink(link)) return "dynamic";
  const sourceNode = nodeMap.get(link.source);
  const targetNode = nodeMap.get(link.target);
  if (
    sourceNode &&
    targetNode &&
    sourceNode.community_id === targetNode.community_id
  )
    return "internal";
  // One endpoint is missing from `nodeMap`, which is built from exactly
  // `graph.nodes` — so the edge loop below drops this link before it is ever
  // drawn. It still needs a kind to be bucketed by; "crossCommunity" is the
  // honest reading of an edge leaving the known set.
  return "crossCommunity";
}

/**
 * Positions for a community slice, which the whole-repo seed lays out badly.
 *
 * That seed partitions by `community_id` and puts each community's centroid on
 * a golden-angle ring. A slice is one community by definition, so the partition
 * degenerates: every member shares an id and lands in a single small disc,
 * while the boundary stubs carry their own real community ids and get strewn
 * across the rest of the ring. Measured on a 94-node slice the members occupied
 * 3.4% of the drawn area and every member-to-stub edge was a chord longer than
 * the members' own diameter.
 *
 * So lay a slice out on its own terms: members fill the middle, stubs ring the
 * edge on the bearing of whatever they attach to.
 */
function seedSlicePositions(
  graph: GraphExport,
  boundaryNodeIds: Set<string>,
  spread: number,
): Map<string, { x: number; y: number }> {
  const goldenAngle = Math.PI * (3 - Math.sqrt(5));
  const positions = new Map<string, { x: number; y: number }>();
  const members = graph.nodes.filter((n) => !boundaryNodeIds.has(n.node_id));
  const stubs = graph.nodes.filter((n) => boundaryNodeIds.has(n.node_id));
  if (members.length === 0) return positions;

  // Sunflower over the inner 60% of the field. sqrt on the radius keeps the
  // distribution uniform over area rather than bunched at the centre.
  const memberRadius = spread * 0.6;
  const memberAngle = new Map<string, number>();
  members.forEach((node, i) => {
    const angle = i * goldenAngle;
    // `i / n`, so member 0 sits at the centre and member n-1 near the rim.
    // With `(i + 1) / n` the first member took the full radius, which drew a
    // one-file community out on the 3 o'clock ray with every stub stacked on
    // that same bearing and the rest of the field empty.
    const r = memberRadius * Math.sqrt(i / members.length);
    memberAngle.set(node.node_id, angle);
    positions.set(node.node_id, {
      x: r * Math.cos(angle),
      y: r * Math.sin(angle),
    });
  });

  // Vector mean of the bearings a stub is pulled toward, not a mean of the
  // angles: averaging 0.1 and 6.2 radians numerically would put the stub on the
  // opposite side of the graph from both of its neighbours.
  const pull = new Map<string, { x: number; y: number; n: number }>();
  for (const link of graph.links) {
    const sourceIsStub = boundaryNodeIds.has(link.source);
    const targetIsStub = boundaryNodeIds.has(link.target);
    if (sourceIsStub === targetIsStub) continue;
    const stub = sourceIsStub ? link.source : link.target;
    const angle = memberAngle.get(sourceIsStub ? link.target : link.source);
    if (angle === undefined) continue;
    const acc = pull.get(stub) ?? { x: 0, y: 0, n: 0 };
    acc.x += Math.cos(angle);
    acc.y += Math.sin(angle);
    acc.n += 1;
    pull.set(stub, acc);
  }

  // Resolve every bearing first, then fan. Cancellation is judged against a
  // residue scaled by the number of contributing links, because two exactly
  // opposite bearings sum to ~1e-17 rather than to 0.
  const bearings = stubs.map((node, i) => {
    const acc = pull.get(node.node_id);
    const cancelled =
      !acc || Math.hypot(acc.x, acc.y) < acc.n * 1e-9;
    // Nothing to point at, or pulls that cancel: spread the unanchored stubs
    // evenly instead of stacking them on one bearing.
    return cancelled ? i * goldenAngle : Math.atan2(acc.y, acc.x);
  });

  // Stubs that share a bearing get a band wide enough to hold them all. A
  // community whose boundary hangs off one high-degree member would otherwise
  // put every stub in one small box, and since the seed IS the layout — FA2
  // and noverlap are both off for a file graph — nothing separates them later.
  const perBearing = new Map<number, number>();
  const bucketOf = (a: number) => Math.round(a / 0.15);
  for (const a of bearings) {
    const b = bucketOf(a);
    perBearing.set(b, (perBearing.get(b) ?? 0) + 1);
  }
  const placedInBucket = new Map<number, number>();

  stubs.forEach((node, i) => {
    const angle = bearings[i]!;
    const bucket = bucketOf(angle);
    const crowd = perBearing.get(bucket) ?? 1;
    const seat = placedInBucket.get(bucket) ?? 0;
    placedInBucket.set(bucket, seat + 1);
    // The ring is a band, not a circle. The arc grows with the crowd so 40
    // stubs on one bearing occupy 40 seats rather than 40 overlapping discs;
    // the radial jitter is deterministic, like the rest of the seed.
    const arc = Math.min(0.2 * crowd, Math.PI / 2);
    const offset = crowd === 1 ? 0 : (seat / (crowd - 1) - 0.5) * arc;
    const hash = simpleHash(node.node_id);
    const ring = spread * (0.92 + (((hash >> 10) % 1000) / 1000) * 0.16);
    positions.set(node.node_id, {
      x: ring * Math.cos(angle + offset),
      y: ring * Math.sin(angle + offset),
    });
  });

  return positions;
}

function computeEdgeSize(
  edgeKind: SigmaEdgeAttributes["edgeKind"],
  nodeCount: number,
): number {
  const baseScale =
    nodeCount > 10000
      ? 0.15
      : nodeCount > 5000
        ? 0.25
        : nodeCount > 2000
          ? 0.35
          : nodeCount > 1000
            ? 0.5
            : nodeCount > 500
              ? 0.7
              : 1.0;
  return baseScale * EDGE_SIZE_MULTIPLIERS[edgeKind];
}

function smartLabel(fullPath: string): string {
  const parts = fullPath.split("/");
  if (parts.length >= 2) return parts.slice(-2).join("/");
  return parts[parts.length - 1] ?? fullPath;
}

function computeEdgeCurvature(edgeKey: string): number {
  const hash = simpleHash(edgeKey);
  return 0.12 + (hash % 80) / 1000;
}

// Yield to the event loop, preferring requestIdleCallback when available so we
// don't starve interaction; falls back to a macrotask elsewhere (tests, SSR).
function yieldToEventLoop(): Promise<void> {
  return new Promise((resolve) => {
    const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void })
      .requestIdleCallback;
    if (typeof ric === "function") {
      ric(() => resolve());
    } else {
      setTimeout(resolve, 0);
    }
  });
}

const CHUNK_SIZE = 500;

export type FileGraphAdapterOptions = {
  signals?: { hotNodeIds?: Set<string>; deadNodeIds?: Set<string> };
  nodeCount?: number;
  /** Nodes that are context rather than content — the one-hop stubs a community
   *  slice carries. Drawn as the boundary of the scoped view. */
  boundaryNodeIds?: Set<string>;
};

export function fileGraphToGraphology(
  graph: GraphExport,
  options?: FileGraphAdapterOptions,
): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {
  const it = buildFileGraph(graph, options);
  // Sync path: drain the generator without ever yielding.
  let next = it.next();
  while (!next.done) next = it.next();
  return next.value;
}

/**
 * Async variant of {@link fileGraphToGraphology} that yields to the event loop
 * every CHUNK_SIZE nodes/edges, keeping the main thread responsive while large
 * graphs are constructed. Callers should keep their loading state up until this
 * resolves.
 */
export async function fileGraphToGraphologyAsync(
  graph: GraphExport,
  options?: FileGraphAdapterOptions,
): Promise<Graph<SigmaNodeAttributes, SigmaEdgeAttributes>> {
  const it = buildFileGraph(graph, options);
  let next = it.next();
  while (!next.done) {
    await yieldToEventLoop();
    next = it.next();
  }
  return next.value;
}

// Generator that builds the file graph, yielding (an undefined) every CHUNK_SIZE
// items so callers can choose to await between chunks (async) or drain inline
// (sync). The single body keeps the two public entry points in lockstep.
function* buildFileGraph(
  graph: GraphExport,
  options?: FileGraphAdapterOptions,
): Generator<undefined, Graph<SigmaNodeAttributes, SigmaEdgeAttributes>, void> {
  const result = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();
  const nodeCount = options?.nodeCount ?? graph.nodes.length;

  // Build lookup maps
  const nodeMap = new Map<string, GraphNode>();
  const communityNodes = new Map<number, GraphNode[]>();
  for (const node of graph.nodes) {
    nodeMap.set(node.node_id, node);
    const list = communityNodes.get(node.community_id) ?? [];
    list.push(node);
    communityNodes.set(node.community_id, list);
  }

  // Warm-start positioning with golden-angle radial distribution
  const goldenAngle = Math.PI * (3 - Math.sqrt(5));
  const spread = Math.sqrt(nodeCount) * 40;
  const sortedCommunities = Array.from(communityNodes.keys()).sort(
    (a, b) => a - b,
  );
  const communityCount = sortedCommunities.length;

  // A slice gets its own seed; see seedSlicePositions for why the partition
  // above degenerates when every member shares one community id.
  const slicePositions =
    options?.boundaryNodeIds?.size && spread > 0
      ? seedSlicePositions(graph, options.boundaryNodeIds, spread)
      : null;

  let processed = 0;
  for (let i = 0; i < sortedCommunities.length; i++) {
    const communityId = sortedCommunities[i]!;
    const members = communityNodes.get(communityId)!;

    const angle = i * goldenAngle;
    const radius = spread * Math.sqrt((i + 1) / communityCount);
    const centroidX = radius * Math.cos(angle);
    const centroidY = radius * Math.sin(angle);
    // Per-community, not per-graph: a community's box grows with its own
    // membership so density stays even across very unequal communities.
    const jitter = SEED_JITTER_PER_SQRT_MEMBER * Math.sqrt(members.length);

    for (const node of members) {
      // Deterministic point in the community's disc. sqrt on the radius keeps
      // the distribution uniform over area rather than bunched at the centre.
      const hash = simpleHash(node.node_id);
      const r = (jitter / 2) * Math.sqrt((hash % 1000) / 1000);
      const theta = (((hash >> 10) % 1000) / 1000) * 2 * Math.PI;
      const seeded = slicePositions?.get(node.node_id);
      const x = seeded ? seeded.x : centroidX + r * Math.cos(theta);
      const y = seeded ? seeded.y : centroidY + r * Math.sin(theta);

      let baseSize: number;
      if (node.is_entry_point) {
        baseSize = NODE_BASE_SIZES.entryPoint;
      } else if (node.is_test) {
        baseSize = NODE_BASE_SIZES.test;
      } else {
        baseSize = NODE_BASE_SIZES.file;
      }
      let size = getScaledNodeSize(baseSize, nodeCount);
      size *= Math.min(1 + node.pagerank * 2, 2);

      const isBoundary = options?.boundaryNodeIds?.has(node.node_id) ?? false;
      // Two thirds, so a stub reads as smaller than every member without
      // vanishing. Colour is handled in use-sigma's colour pass, which runs
      // after this and would otherwise overwrite anything set here.
      if (isBoundary) size *= 0.65;

      const color = languageColor(node.language);

      const attrs: SigmaNodeAttributes = {
        x,
        y,
        size,
        color,
        label: smartLabel(node.node_id),
        nodeType: "file",
        fullPath: node.node_id,
        language: node.language,
        communityId: node.community_id,
        pagerank: node.pagerank,
        betweenness: node.betweenness,
        isTest: node.is_test,
        isEntryPoint: node.is_entry_point,
        hasDoc: node.has_doc,
        symbolCount: node.symbol_count,
        mass: getNodeMass("file", nodeCount),
        originalColor: color,
      };
      if (isBoundary) attrs.isBoundary = true;

      // Signal data may come from two sources: explicit overlay sets
      // (legacy unified-graph flow) or enriched node payloads from Phase A.
      // We OR them so adapters work with both backends.
      if (
        node.is_hotspot ||
        options?.signals?.hotNodeIds?.has(node.node_id)
      ) {
        attrs.isHotspot = true;
      }
      if (
        node.is_dead ||
        options?.signals?.deadNodeIds?.has(node.node_id)
      ) {
        attrs.isDead = true;
      }
      attrs.churnPercentile = node.churn_percentile ?? null;
      attrs.deadConfidence = node.dead_confidence ?? null;
      attrs.hasDecision = node.has_decision ?? false;
      attrs.primaryOwner = node.primary_owner ?? null;

      result.addNode(node.node_id, attrs);
      if (++processed % CHUNK_SIZE === 0) yield;
    }
  }

  // Classify edges in one O(E) pass, then bucket by kind (avoids O(E log E) sort)
  const kindBuckets: Record<SigmaEdgeAttributes["edgeKind"], GraphLink[]> = {
    crossCommunity: [],
    internal: [],
    dynamic: [],
    lowConfidence: [],
  };
  const edgeKindMap = new Map<GraphLink, SigmaEdgeAttributes["edgeKind"]>();
  for (const link of graph.links) {
    const kind = classifyEdge(link, nodeMap);
    edgeKindMap.set(link, kind);
    kindBuckets[kind].push(link);
  }
  const orderedLinks = (
    kindBuckets.crossCommunity
      .concat(kindBuckets.internal)
      .concat(kindBuckets.dynamic)
      .concat(kindBuckets.lowConfidence)
  );

  const maxEdgesPerNode = nodeCount > 1000 ? 25 : Infinity;
  const edgesPerSource = new Map<string, number>();

  // Curvature is an edge-count decision, so decide it on the edge count. The
  // per-source cap above bounds this, so `orderedLinks.length` is an upper
  // bound on what actually gets drawn — erring toward curved, which is the
  // nicer default, on graphs near the threshold.
  const useCurved = orderedLinks.length <= CURVED_EDGE_THRESHOLD;

  let edgeProcessed = 0;
  for (const link of orderedLinks) {
    if (++edgeProcessed % CHUNK_SIZE === 0) yield;
    if (!result.hasNode(link.source) || !result.hasNode(link.target)) continue;
    const edgeKey = link.source + "→" + link.target;
    if (result.hasEdge(edgeKey)) continue;

    const srcCount = edgesPerSource.get(link.source) ?? 0;
    if (srcCount >= maxEdgesPerNode) continue;
    edgesPerSource.set(link.source, srcCount + 1);

    const edgeKind = edgeKindMap.get(link) ?? classifyEdge(link, nodeMap);

    const edgeAttrs: SigmaEdgeAttributes = {
      size: computeEdgeSize(edgeKind, nodeCount),
      color: EDGE_COLORS[edgeKind],
      // Dense graphs drop the curvature, never the arrowhead: "line" would
      // erase the direction encoding that makes a dependency edge readable.
      type: useCurved ? "curvedArrow" : "arrow",
      curvature: useCurved ? computeEdgeCurvature(edgeKey) : 0,
      edgeKind,
      importedNames: link.imported_names,
      edgeCount: 1,
    };

    if (link.confidence !== undefined) {
      edgeAttrs.confidence = link.confidence;
    }

    result.addEdgeWithKey(edgeKey, link.source, link.target, edgeAttrs);
  }

  // The community seed above IS the layout — mark it settled so use-fa2-layout
  // skips its auto-run (the toolbar's manual toggle still starts FA2).
  //
  // This used to hand off to the animated FA2 worker for 8 seconds. Measured on
  // this repo's real 1,500-node export, that run does not improve the picture:
  // cluster separation *falls* monotonically with iterations (23.2 seeded →
  // 21.6 at 120 → 12.1 at 600 → 7.7 at 1200) as gravity pulls the golden-angle
  // spiral into one central hairball, while median node drift stays under 4% of
  // the graph radius for the first ~120. So the eight seconds bought a slower
  // arrival at a slightly worse layout. Removing it is a removal of known work,
  // not a speculative optimisation.
  result.setAttribute("presettled", true);

  return result;
}

/**
 * True for a module id naming code we do not own.
 *
 * Delegates rather than testing the prefix by hand: `framework:` nodes are
 * third-party too, and the hand-rolled check missed them, so a framework's
 * own code was drawn as one of the repository's modules.
 */
export function isExternalModuleId(id: string): boolean {
  return isExternal(id);
}

export function moduleGraphToGraphology(
  graph: ModuleGraph,
  options?: {
    communities?: CommunitySummaryItem[];
    nodeCount?: number;
    /** Drop `external:*` dependency modules (and their edges) so the repo's
     *  own structure defines the layout extent. */
    hideExternals?: boolean;
  },
): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {
  const result = new Graph<SigmaNodeAttributes, SigmaEdgeAttributes>();
  const nodes = options?.hideExternals
    ? graph.nodes.filter((n) => !isExternalModuleId(n.module_id))
    : graph.nodes;
  const nodeCount = options?.nodeCount ?? nodes.length;

  // Build community lookup: map module_id to community_id. For each community,
  // check each path-prefix of its top_file against the module-id set —
  // O(C × depth) instead of the old O(C × M) nested scan.
  const moduleCommunity = new Map<string, number>();
  if (options?.communities) {
    const moduleIds = new Set(nodes.map((n) => n.module_id));
    for (const community of options.communities) {
      const parts = community.top_file.split("/");
      for (let depth = 1; depth <= parts.length; depth++) {
        const prefix = parts.slice(0, depth).join("/");
        if (moduleIds.has(prefix)) {
          moduleCommunity.set(prefix, community.community_id);
        }
      }
    }
  }
  // Fill in missing modules with deterministic hash
  for (const mod of nodes) {
    if (!moduleCommunity.has(mod.module_id)) {
      moduleCommunity.set(mod.module_id, simpleHash(mod.module_id) % 24);
    }
  }

  // Group modules by community for warm-start positioning
  const communityModules = new Map<number, ModuleNode[]>();
  for (const mod of nodes) {
    const cid = moduleCommunity.get(mod.module_id) ?? 0;
    const list = communityModules.get(cid) ?? [];
    list.push(mod);
    communityModules.set(cid, list);
  }

  // Grid-based warm-start: communities in a grid, modules jittered around centroids
  const sortedCommunities = Array.from(communityModules.keys()).sort(
    (a, b) => a - b,
  );
  const communityCount = sortedCommunities.length;
  const cols = Math.max(Math.ceil(Math.sqrt(communityCount)), 1);
  const cellSize = Math.sqrt(nodeCount) * 80;
  const jitter = cellSize * 0.3;

  for (let i = 0; i < sortedCommunities.length; i++) {
    const communityId = sortedCommunities[i]!;
    const members = communityModules.get(communityId)!;

    const col = i % cols;
    const row = Math.floor(i / cols);
    const centroidX = (col - (cols - 1) / 2) * cellSize;
    const centroidY = (row - (Math.ceil(communityCount / cols) - 1) / 2) * cellSize;

    for (const mod of members) {
      // Deterministic per-module jitter (id hash) so the layout is stable
      // across mounts and rebuilds — no Math.random layout churn.
      const hash = simpleHash(mod.module_id);
      const x = centroidX + ((hash % 1000) / 1000 - 0.5) * jitter;
      const y = centroidY + (((hash >> 10) % 1000) / 1000 - 0.5) * jitter;

      const baseSize = getScaledNodeSize(NODE_BASE_SIZES.module, nodeCount);
      const size = baseSize * (0.5 + Math.min(Math.log2(Math.max(mod.file_count, 1)) * 0.3, 1.5));
      // Theme-aware community hub color is applied later by use-sigma; this is a
      // neutral placeholder for the initial (pre-effect) frame.
      const color = PLACEHOLDER_NODE_COLOR;

      result.addNode(mod.module_id, {
        x,
        y,
        size,
        color,
        label: smartLabel(mod.module_id),
        nodeType: "module",
        fullPath: mod.module_id,
        language: "",
        communityId,
        pagerank: mod.avg_pagerank,
        betweenness: 0,
        isTest: false,
        isEntryPoint: false,
        hasDoc: mod.doc_coverage_pct > 0,
        symbolCount: mod.symbol_count,
        fileCount: mod.file_count,
        avgPagerank: mod.avg_pagerank,
        docCoveragePct: mod.doc_coverage_pct,
        hotspotCount: mod.hotspot_count ?? 0,
        deadCount: mod.dead_count ?? 0,
        hasDecision: mod.has_decision ?? false,
        primaryOwner: mod.primary_owner ?? null,
        dominantCommunityId: communityId,
        mass: getNodeMass("module", nodeCount),
        originalColor: color,
      });
    }
  }

  // Add edges
  for (const edge of graph.edges) {
    if (!result.hasNode(edge.source) || !result.hasNode(edge.target)) continue;
    const edgeKey = edge.source + "→" + edge.target;
    if (result.hasEdge(edgeKey)) continue;

    const sourceCid = moduleCommunity.get(edge.source) ?? 0;
    const targetCid = moduleCommunity.get(edge.target) ?? 0;
    const edgeKind: SigmaEdgeAttributes["edgeKind"] =
      sourceCid === targetCid ? "internal" : "crossCommunity";

    const baseScale =
      nodeCount > 5000 ? 0.4 : nodeCount > 1000 ? 0.6 : 1.0;

    result.addEdgeWithKey(edgeKey, edge.source, edge.target, {
      size:
        baseScale *
        EDGE_SIZE_MULTIPLIERS[edgeKind] *
        (1 + Math.log2(edge.edge_count)),
      color: EDGE_COLORS[edgeKind],
      // Arrowhead points at the imported module — direction is the whole
      // point of a dependency edge.
      type: "curvedArrow",
      curvature: computeEdgeCurvature(edgeKey),
      edgeKind,
      importedNames: [],
      edgeCount: edge.edge_count,
    });
  }

  return result;
}

/**
 * Synchronously settle a small graph with FA2 + noverlap so the FIRST painted
 * frame is the final layout — no visible "expand then collapse into a blob"
 * convergence animation, no FA2 worker spin-up. Marks the graph `presettled`
 * so use-fa2-layout skips its auto-run (the manual layout toggle still works).
 *
 * No-ops above PRESETTLE_MAX_NODES: large graphs keep the animated worker
 * layout, which stays off the main thread.
 */
export function settleGraph(
  graph: Graph<SigmaNodeAttributes, SigmaEdgeAttributes>,
): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {
  if (graph.order === 0 || graph.order > PRESETTLE_MAX_NODES) return graph;
  const settings = {
    ...forceAtlas2.inferSettings(graph),
    ...getFA2Settings(graph.order),
  };
  forceAtlas2.assign(graph, {
    iterations: getPresettleIterations(graph.order),
    settings,
  });
  noverlap.assign(graph, {
    maxIterations: 60,
    settings: { ratio: 1.1, margin: 6, expansion: 1.1 },
  });
  graph.setAttribute("presettled", true);
  return graph;
}

export function groupFilesAsModules(
  graph: GraphExport,
  options?: { prefix?: string },
): Graph<SigmaNodeAttributes, SigmaEdgeAttributes> {
  const { moduleNodes, moduleEdges } = groupNodesAsModules(
    graph.nodes,
    graph.links,
    options?.prefix ?? "",
  );

  return moduleGraphToGraphology({ nodes: moduleNodes, edges: moduleEdges });
}