{
  "version": 3,
  "sources": ["../../../src/rendering-util/layout-algorithms/layout-utils/geometry.ts", "../../../src/rendering-util/layout-algorithms/layout-utils/helpers.ts", "../../../src/rendering-util/layout-algorithms/grid/types.ts", "../../../src/rendering-util/layout-algorithms/grid/labelGeometry.ts", "../../../src/rendering-util/layout-algorithms/grid/edgeLabels.ts", "../../../src/rendering-util/layout-algorithms/grid/groups.ts", "../../../src/rendering-util/layout-algorithms/grid/labelSpacing.ts", "../../../src/rendering-util/layout-algorithms/grid/placement.ts", "../../../src/rendering-util/layout-algorithms/grid/routerErrors.ts", "../../../src/rendering-util/layout-algorithms/grid/routerTopology.ts", "../../../src/rendering-util/layout-algorithms/grid/routerPlanning.ts", "../../../src/rendering-util/layout-algorithms/grid/routerConstraint.ts", "../../../src/rendering-util/layout-algorithms/grid/routerOccupancy.ts", "../../../src/rendering-util/layout-algorithms/grid/routerCompatibility.ts", "../../../src/rendering-util/layout-algorithms/grid/routerInstrumentation.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSearch.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSparse.ts", "../../../src/rendering-util/layout-algorithms/grid/routerSession.ts", "../../../src/rendering-util/layout-algorithms/grid/router.ts", "../../../src/rendering-util/layout-algorithms/grid/layoutCore.ts", "../../../src/rendering-util/layout-algorithms/grid/lineHops.ts", "../../../src/rendering-util/layout-algorithms/grid/index.ts"],
  "sourcesContent": ["/**\n * Shared geometry helpers for layout validation and scoring.\n *\n * Extracted from validateLayout.ts so both validateLayout and scoreLayout\n * can reuse the same normalization, distance, and crossing logic.\n */\nimport type { Point } from './types.js';\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Constants\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Canonical one-pixel tolerance shared by routing geometry and final layout validation. */\nexport const PIXEL_EPSILON = 1;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Segment representation for geometry processing\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Segment {\n  a: Point;\n  b: Point;\n  orientation: 'H' | 'V' | 'Z'; // Horizontal, Vertical, Zero-length\n}\n\nexport interface NormalizedPolyline {\n  points: Point[];\n  segments: Segment[];\n  bends: number;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Geometry normalization helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Get segment orientation */\nexport function segmentOrientation(a: Point, b: Point, tolerance = PIXEL_EPSILON): 'H' | 'V' | 'Z' {\n  const dx = Math.abs(b.x - a.x);\n  const dy = Math.abs(b.y - a.y);\n  if (dx <= tolerance && dy <= tolerance) {\n    return 'Z';\n  }\n  if (dy <= tolerance) {\n    return 'H';\n  }\n  return 'V';\n}\n\n/** Create segments from consecutive point pairs */\nexport function segmentsFromPoints(points: Point[], tolerance = PIXEL_EPSILON): Segment[] {\n  const segments: Segment[] = [];\n  for (let i = 0; i < points.length - 1; i++) {\n    const a = points[i];\n    const b = points[i + 1];\n    segments.push({ a, b, orientation: segmentOrientation(a, b, tolerance) });\n  }\n  return segments;\n}\n\n/** Merge consecutive collinear segments */\nexport function mergeCollinear(segments: Segment[], tolerance = PIXEL_EPSILON): Segment[] {\n  if (segments.length === 0) {\n    return [];\n  }\n  const result: Segment[] = [];\n  let current = { ...segments[0] };\n\n  for (let i = 1; i < segments.length; i++) {\n    const next = segments[i];\n    // Skip zero-length segments\n    if (next.orientation === 'Z') {\n      continue;\n    }\n    if (current.orientation === 'Z') {\n      current = { ...next };\n      continue;\n    }\n    // Merge if same orientation and collinear\n    if (current.orientation === next.orientation) {\n      if (\n        current.orientation === 'H' &&\n        Math.abs(current.b.y - next.a.y) <= tolerance &&\n        Math.abs(current.a.y - next.a.y) <= tolerance\n      ) {\n        // Extend horizontal segment\n        current.b = next.b;\n        continue;\n      }\n      if (\n        current.orientation === 'V' &&\n        Math.abs(current.b.x - next.a.x) <= tolerance &&\n        Math.abs(current.a.x - next.a.x) <= tolerance\n      ) {\n        // Extend vertical segment\n        current.b = next.b;\n        continue;\n      }\n    }\n    // Not mergeable: push current and start new\n    // @ts-expect-error - current.orientation should be 'H' | 'V' here due to filtering, but TS doesn't track that\n    if (current.orientation !== 'Z') {\n      result.push(current);\n    }\n    current = { ...next };\n  }\n  if (current.orientation !== 'Z') {\n    result.push(current);\n  }\n  return result;\n}\n\n/** Normalize a polyline: remove zero-length, merge collinear, count bends */\nexport function normalizePolyline(points: Point[], tolerance = PIXEL_EPSILON): NormalizedPolyline {\n  if (points.length < 2) {\n    return { points: [...points], segments: [], bends: 0 };\n  }\n\n  // Create segments and filter zero-length\n  const rawSegments = segmentsFromPoints(points, tolerance).filter((s) => s.orientation !== 'Z');\n\n  // Merge collinear\n  const merged = mergeCollinear(rawSegments, tolerance);\n\n  // Rebuild points from merged segments\n  const newPoints: Point[] = [];\n  for (const [i, element] of merged.entries()) {\n    if (i === 0) {\n      newPoints.push(element.a);\n    }\n    newPoints.push(element.b);\n  }\n\n  // Count bends: direction changes between consecutive segments\n  let bends = 0;\n  for (let i = 1; i < merged.length; i++) {\n    if (merged[i - 1].orientation !== merged[i].orientation) {\n      bends++;\n    }\n  }\n\n  return { points: newPoints.length > 0 ? newPoints : [...points], segments: merged, bends };\n}\n\n/** Euclidean distance between two points */\nexport function distance(a: Point, b: Point): number {\n  return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2);\n}\n\n/**\n * Check if two orthogonal segments cross.\n *\n * Detects proper interior crossings as well as T-intersections where one\n * segment's endpoint lies on the other segment's interior.  The only case\n * that is excluded is a *shared endpoint*: when the intersection point is\n * an endpoint of **both** segments (two edges departing from the same node\n * corner should not count as a crossing).\n */\nexport function segmentsCross(s1: Segment, s2: Segment): boolean {\n  // Must be H/V pair\n  if (s1.orientation === 'Z' || s2.orientation === 'Z') {\n    return false;\n  }\n  if (s1.orientation === s2.orientation) {\n    return false;\n  }\n\n  const horiz = s1.orientation === 'H' ? s1 : s2;\n  const vert = s1.orientation === 'V' ? s1 : s2;\n\n  const hY = horiz.a.y;\n  const hX1 = Math.min(horiz.a.x, horiz.b.x);\n  const hX2 = Math.max(horiz.a.x, horiz.b.x);\n\n  const vX = vert.a.x;\n  const vY1 = Math.min(vert.a.y, vert.b.y);\n  const vY2 = Math.max(vert.a.y, vert.b.y);\n\n  // Use non-strict inequalities to also detect T-intersections\n  if (vX >= hX1 && vX <= hX2 && hY >= vY1 && hY <= vY2) {\n    // The intersection point is (vX, hY).\n    // Exclude shared endpoints: if (vX, hY) matches an endpoint of BOTH\n    // segments, it's a shared departure/arrival, not a real crossing.\n    const TOL = 1e-6;\n    const ix = vX;\n    const iy = hY;\n\n    const matchesHorizEndpoint =\n      (Math.abs(ix - horiz.a.x) < TOL && Math.abs(iy - horiz.a.y) < TOL) ||\n      (Math.abs(ix - horiz.b.x) < TOL && Math.abs(iy - horiz.b.y) < TOL);\n\n    const matchesVertEndpoint =\n      (Math.abs(ix - vert.a.x) < TOL && Math.abs(iy - vert.a.y) < TOL) ||\n      (Math.abs(ix - vert.b.x) < TOL && Math.abs(iy - vert.b.y) < TOL);\n\n    if (matchesHorizEndpoint && matchesVertEndpoint) {\n      // Shared endpoint \u2014 not a crossing\n      return false;\n    }\n\n    return true;\n  }\n\n  return false;\n}\n", "/**\n * Shared utility functions for the orthogonal routing pipeline.\n *\n * This module contains geometry helpers, distance calculations, and other\n * low-level utilities used across the routing stages.\n */\nimport type { Edge, Node } from '../../types.js';\nimport type { Point, Rect, PortSide } from './types.js';\n\n/**\n * Compare strings by UTF-16 code units so algorithmic ordering is independent of locale and ICU.\n */\nexport function compareCodeUnits(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Create a Rect from a Node's x, y, width, height properties.\n * The node's x, y are assumed to be the center coordinates.\n */\nexport function rectForNode(node: Node): Rect {\n  const cx = node.x ?? 0;\n  const cy = node.y ?? 0;\n  const w = node.width ?? 40;\n  const h = node.height ?? 40;\n  return {\n    cx,\n    cy,\n    left: cx - w / 2,\n    right: cx + w / 2,\n    top: cy - h / 2,\n    bottom: cy + h / 2,\n  };\n}\n\n/**\n * Reserve the marker-facing portion of an orthogonal terminal segment.\n *\n * Placement and validation share this geometry so a label accepted during routing cannot later\n * fail because the validator modeled the arrowhead clearance differently.\n */\nexport function terminalMarkerClearanceRect(\n  points: Point[],\n  terminal: 'start' | 'end',\n  length: number,\n  halfWidth: number,\n  tolerance = 0\n): Rect | null {\n  if (points.length < 2) {\n    return null;\n  }\n\n  const tip = terminal === 'end' ? points[points.length - 1] : points[0];\n  const inner = terminal === 'end' ? points[points.length - 2] : points[1];\n  const dx = inner.x - tip.x;\n  const dy = inner.y - tip.y;\n\n  if (Math.abs(dx) <= tolerance && Math.abs(dy) <= tolerance) {\n    return null;\n  }\n  if (Math.abs(dy) <= tolerance) {\n    const innerX = tip.x + Math.sign(dx) * length;\n    const left = Math.min(tip.x, innerX);\n    const right = Math.max(tip.x, innerX);\n    return {\n      cx: (left + right) / 2,\n      cy: tip.y,\n      left,\n      right,\n      top: tip.y - halfWidth,\n      bottom: tip.y + halfWidth,\n    };\n  }\n  if (Math.abs(dx) <= tolerance) {\n    const innerY = tip.y + Math.sign(dy) * length;\n    const top = Math.min(tip.y, innerY);\n    const bottom = Math.max(tip.y, innerY);\n    return {\n      cx: tip.x,\n      cy: (top + bottom) / 2,\n      left: tip.x - halfWidth,\n      right: tip.x + halfWidth,\n      top,\n      bottom,\n    };\n  }\n  return null;\n}\n\nexport function hasTerminalMarker(edge: Edge, terminal: 'start' | 'end'): boolean {\n  const markerType = terminal === 'start' ? edge.arrowTypeStart : edge.arrowTypeEnd;\n  // Explicit terminal settings override edge.type, including values that disable markers.\n  if (typeof markerType === 'string') {\n    const trimmed = markerType.trim();\n    if (trimmed.length > 0) {\n      return trimmed !== 'none' && trimmed !== 'arrow_open';\n    }\n  }\n\n  if (typeof edge.type !== 'string') {\n    return false;\n  }\n  // Flowchart/swimlane edges often carry marker semantics in `type`.\n  if (terminal === 'start' && edge.type.startsWith('double_')) {\n    return true;\n  }\n  return terminal === 'end' && /arrow_(point|cross|circle|barb)|double_arrow/.test(edge.type);\n}\n\n/**\n * Check if a point is strictly inside a rectangle (not on the boundary).\n */\nexport function pointInRectInterior(p: Point, rect: Rect): boolean {\n  return p.x > rect.left && p.x < rect.right && p.y > rect.top && p.y < rect.bottom;\n}\n\n/**\n * Approximate floating-point equality check.\n */\nexport function approxEqual(a: number, b: number, tol = 1e-6): boolean {\n  return Math.abs(a - b) <= tol;\n}\n\nexport function orthogonalPolylineContainsPoint(\n  points: Point[],\n  point: Point,\n  tolerance = 1e-6\n): boolean {\n  for (let index = 1; index < points.length; index++) {\n    const a = points[index - 1];\n    const b = points[index];\n    if (approxEqual(a.y, b.y, tolerance) && !approxEqual(a.x, b.x, tolerance)) {\n      if (\n        approxEqual(point.y, a.y, tolerance) &&\n        point.x >= Math.min(a.x, b.x) - tolerance &&\n        point.x <= Math.max(a.x, b.x) + tolerance\n      ) {\n        return true;\n      }\n    } else if (approxEqual(a.x, b.x, tolerance) && !approxEqual(a.y, b.y, tolerance)) {\n      if (\n        approxEqual(point.x, a.x, tolerance) &&\n        point.y >= Math.min(a.y, b.y) - tolerance &&\n        point.y <= Math.max(a.y, b.y) + tolerance\n      ) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * Calculate the total Manhattan length of a polyline.\n */\nexport function manhattanLength(points: Point[]): number {\n  let total = 0;\n  for (let i = 1; i < points.length; i++) {\n    const a = points[i - 1];\n    const b = points[i];\n    total += Math.abs(b.x - a.x) + Math.abs(b.y - a.y);\n  }\n  return total;\n}\n\n/**\n * Calculate the Manhattan distance between two points.\n */\nexport function manhattanDistance(a: Point, b: Point): number {\n  return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n}\n\n/**\n * Count the number of bends (direction changes) in a polyline.\n */\nexport function bendCount(points: Point[]): number {\n  let bends = 0;\n  for (let i = 2; i < points.length; i++) {\n    const a = points[i - 2];\n    const b = points[i - 1];\n    const c = points[i];\n    const dxAB = b.x - a.x;\n    const dyAB = b.y - a.y;\n    const dxBC = c.x - b.x;\n    const dyBC = c.y - b.y;\n    const isHorizAB = !approxEqual(dxAB, 0) && approxEqual(dyAB, 0);\n    const isVertAB = approxEqual(dxAB, 0) && !approxEqual(dyAB, 0);\n    const isHorizBC = !approxEqual(dxBC, 0) && approxEqual(dyBC, 0);\n    const isVertBC = approxEqual(dxBC, 0) && !approxEqual(dyBC, 0);\n    if ((isHorizAB && isVertBC) || (isVertAB && isHorizBC)) {\n      bends++;\n    }\n  }\n  return bends;\n}\n\n/**\n * Check if an axis-aligned segment intersects a rectangle's interior.\n * Non-orthogonal segments are ignored (return false).\n */\nexport function segmentIntersectsRectInterior(a: Point, b: Point, rect: Rect): boolean {\n  // We only care about axis-aligned segments; non-orthogonal segments are ignored\n  // in this helper since the pipeline only produces orthogonal polylines.\n  if (a.x === b.x && a.y === b.y) {\n    return false;\n  }\n\n  if (a.y === b.y) {\n    // Horizontal segment. Treat segments that run exactly along the top/bottom\n    // boundary of the rectangle as collisions as well, so that edges do not\n    // visually \"run under\" or \"on\" other nodes.\n    const y = a.y;\n    const x1 = Math.min(a.x, b.x);\n    const x2 = Math.max(a.x, b.x);\n    const crossesVertically = y >= rect.top && y <= rect.bottom;\n    const overlapsHorizontally = Math.max(x1, rect.left) < Math.min(x2, rect.right);\n    return crossesVertically && overlapsHorizontally;\n  }\n\n  if (a.x === b.x) {\n    // Vertical segment. Similarly, segments that run exactly along the\n    // left/right boundary of the rectangle are treated as collisions.\n    const x = a.x;\n    const y1 = Math.min(a.y, b.y);\n    const y2 = Math.max(a.y, b.y);\n    const crossesHorizontally = x >= rect.left && x <= rect.right;\n    const overlapsVertically = Math.max(y1, rect.top) < Math.min(y2, rect.bottom);\n    return crossesHorizontally && overlapsVertically;\n  }\n\n  return false;\n}\n\n/**\n * Check if a polyline crosses a single rectangle.\n */\nexport function polylineIntersectsRect(points: Point[], rect: Rect): boolean {\n  for (let i = 1; i < points.length; i++) {\n    if (segmentIntersectsRectInterior(points[i - 1], points[i], rect)) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Check if a polyline crosses an array of obstacle rectangles.\n */\nexport function polylineIntersectsRects(points: Point[], rects: Rect[]): boolean {\n  for (const rect of rects) {\n    if (polylineIntersectsRect(points, rect)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport function pointInsideAnyRectInterior(p: Point, rects: Rect[]): boolean {\n  for (const r of rects) {\n    if (pointInRectInterior(p, r)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport function clamp(v: number, lo: number, hi: number): number {\n  return Math.max(lo, Math.min(hi, v));\n}\n\n/**\n * Remove duplicates from a sorted number array.\n */\nexport function uniqSorted(numbers: number[]): number[] {\n  const s = new Set<number>();\n  for (const n of numbers) {\n    s.add(n);\n  }\n  return [...s].sort((a, b) => a - b);\n}\n\n/**\n * Compute the boundary port point for a side of a rectangle.\n */\nexport function computeBoundaryPort(rect: Rect, side: PortSide): Point {\n  switch (side) {\n    case 'E':\n      return { x: rect.right, y: rect.cy };\n    case 'W':\n      return { x: rect.left, y: rect.cy };\n    case 'N':\n      return { x: rect.cx, y: rect.top };\n    case 'S':\n      return { x: rect.cx, y: rect.bottom };\n  }\n}\n", "import type { GridHorizontalAlign, GridPlacement, GridVerticalAlign } from '../../../types.js';\nimport type { LayoutData, Node } from '../../types.js';\nimport type { Point } from '../../../types.js';\nimport { DEFAULT_EDGE_CORNER_RADIUS } from '../../edgeCornerRadius.js';\nimport type {\n  GridRoutingFallbackReason,\n  GridRoutingInstrumentation,\n} from './routerInstrumentation.js';\nimport type { GridLabelRequirements } from './labelSpacing.js';\n\n// The root participates in the same container algorithms as groups but has no backing Node.\nexport const ROOT_CONTAINER_ID = '__grid_root__';\n// Label helpers belong to edges and must not consume cells in the node-placement forest.\nexport const GRID_LABEL_PREFIX = 'edge-label-';\n\nexport type GridContainerId = string;\nexport type GridSide = 'left' | 'right' | 'top' | 'bottom';\nexport type GridOrientation = 'H' | 'V';\nexport type GridCurve =\n  | 'basis'\n  | 'bumpX'\n  | 'bumpY'\n  | 'cardinal'\n  | 'catmullRom'\n  | 'linear'\n  | 'monotoneX'\n  | 'monotoneY'\n  | 'natural'\n  | 'step'\n  | 'stepAfter'\n  | 'stepBefore'\n  | 'rounded';\nexport type RouterVertexId = number;\n\n// Routing uses a compact orthogonal visibility graph. The richer arc form supports validation and\n// overlays; RouterSearchArc is the allocation-conscious representation consumed by hot searches.\nexport interface RouterPoint {\n  x: number;\n  y: number;\n}\n\nexport interface RouterRect {\n  left: number;\n  right: number;\n  top: number;\n  bottom: number;\n}\n\nexport interface RouterObstacle extends RouterRect {\n  id: string;\n}\n\nexport interface PortalRange {\n  ownerId: string;\n  side: GridSide;\n  low: number;\n  high: number;\n  coordinate?: number;\n}\n\n// Crossing a group boundary is represented as two vertices plus one explicit transition. Keeping\n// both sides of the boundary prevents a route from accidentally treating hierarchy as open space.\nexport interface PairedPortal {\n  ownerId: string;\n  side: GridSide;\n  tangentialCoordinate: number;\n  interior: RouterPoint;\n  exterior: RouterPoint;\n  transition: {\n    from: RouterPoint;\n    to: RouterPoint;\n    orientation: GridOrientation;\n    length: number;\n    kind: 'portal';\n  };\n}\n\nexport interface RouterVertex {\n  id: RouterVertexId;\n  point: RouterPoint;\n  kind: 'corner' | 'projection' | 'portal' | 'endpoint' | 'lane';\n  ownerId?: string;\n  side?: GridSide;\n}\n\nexport interface RouterArc {\n  from: RouterVertexId;\n  to: RouterVertexId;\n  orientation: GridOrientation;\n  length: number;\n  kind: 'visibility' | 'terminal' | 'portal' | 'lane';\n  intervalStart: number;\n  intervalEnd: number;\n}\n\nexport interface RouterSearchArc {\n  to: RouterVertexId;\n  orientationOrdinal: 1 | 2;\n  length: number;\n  boundaryTransitions: 0 | 1;\n}\n\nexport interface OrthogonalIntervalIndex {\n  readonly coordinateCount: number;\n  readonly intervalCount: number;\n  intersects(coordinate: number, intervalStart: number, intervalEnd: number): boolean;\n  contains(coordinate: number, varying: number): boolean;\n  nearestBoundary(coordinate: number, origin: number, direction: -1 | 1): number | undefined;\n}\n\nexport interface ContainerRoutingTopology {\n  // Base topologies are immutable and shared by all edges in a container. Optional accessors expose\n  // lightweight endpoint overlays without copying the base vertex and adjacency arrays.\n  containerId: GridContainerId;\n  bounds: RouterRect;\n  obstacles: readonly RouterObstacle[];\n  vertices: readonly RouterVertex[];\n  pointVertexIds: ReadonlyMap<string, RouterVertexId>;\n  horizontalVertexLines: ReadonlyMap<number, readonly RouterVertex[]>;\n  verticalVertexLines: ReadonlyMap<number, readonly RouterVertex[]>;\n  adjacency: ReadonlyMap<RouterVertexId, readonly RouterArc[]>;\n  adjacencyByVertex: readonly (readonly RouterArc[])[];\n  searchAdjacencyByVertex: readonly (readonly RouterSearchArc[])[];\n  adjacencyEntries: number;\n  horizontalIntervals: OrthogonalIntervalIndex;\n  verticalIntervals: OrthogonalIntervalIndex;\n  portalRanges: readonly PortalRange[];\n  seedCount: number;\n  estimatedBytes: number;\n  readonly vertexCount?: number;\n  getVertex?(id: RouterVertexId): RouterVertex | undefined;\n  getSearchArcs?(id: RouterVertexId): readonly RouterSearchArc[];\n}\n\nexport interface GridRoutingContext {\n  // Containers that exceed a topology cap are recorded here and routed through the validated\n  // compatibility path; resource exhaustion is degradation, not permission to emit invalid paths.\n  topologies: Map<GridContainerId, ContainerRoutingTopology>;\n  fallbackContainers: Map<GridContainerId, GridRoutingFallbackReason>;\n  searchBudget: { expandedStates: number };\n  searchBudgetWarningEmitted: boolean;\n  baseEstimatedBytes: number;\n  metrics?: GridRoutingInstrumentation;\n}\n\nexport interface GridLayoutConfigNormalized {\n  placements: Map<string, GridPlacement[]>;\n  columns: number;\n  rowGap: number;\n  columnGap: number;\n  cellGap: number;\n  containerPadding: number;\n  titleGap: number;\n  horizontalAlign: GridHorizontalAlign;\n  verticalAlign: GridVerticalAlign;\n  // Routing publishes these values on each edge so shared rendering and line hops use identical\n  // corner geometry without depending on grid internals.\n  curve: GridCurve;\n  edgeCornerRadius: number;\n}\n\nexport interface GridResolvedPlacement {\n  item: Node;\n  row: number;\n  column: number;\n  horizontalAlign: GridHorizontalAlign;\n  verticalAlign: GridVerticalAlign;\n  sourceOrder: number;\n  explicitRow: boolean;\n  explicitColumn: boolean;\n  explicitCell: boolean;\n}\n\n// Multiple nodes may intentionally share a cell; they are laid out as one vertical stack.\nexport interface GridCellStack {\n  row: number;\n  column: number;\n  items: GridResolvedPlacement[];\n  width: number;\n  height: number;\n  verticalAlign: GridVerticalAlign;\n}\n\nexport interface GridItemLayoutMeta {\n  containerId: GridContainerId;\n  row: number;\n  column: number;\n  cellLeft: number;\n  cellTop: number;\n  cellWidth: number;\n  cellHeight: number;\n  leftCorridorX: number;\n  rightCorridorX: number;\n  topCorridorY: number;\n  bottomCorridorY: number;\n}\n\nexport interface GridContainerLayoutMeta {\n  id: GridContainerId;\n  left: number;\n  top: number;\n  width: number;\n  height: number;\n  contentLeft: number;\n  contentTop: number;\n  contentRight: number;\n  contentBottom: number;\n  // Corridors describe empty track boundaries for the routing layer added by the next stack PR.\n  verticalCorridors: number[];\n  horizontalCorridors: number[];\n}\n\nexport interface GridForest {\n  nodeById: Map<string, Node>;\n  groupById: Map<string, Node & { isGroup: true }>;\n  childrenByParent: Map<GridContainerId, Node[]>;\n  rootChildren: Node[];\n  // Children-first ordering lets parent groups measure already-sized nested groups.\n  postOrderGroups: (Node & { isGroup: true })[];\n  helperNodeIds: Set<string>;\n}\n\nexport interface GridAttachmentDemand {\n  // demandKey identifies one edge endpoint at one hierarchy boundary and remains stable across\n  // retries so portal coordinates can be captured and restored transactionally.\n  ownerId: string;\n  side: GridSide;\n  edgeId: string;\n  demandKey: string;\n  oppositeCoord: number;\n  preferredCoord: number;\n  compactPortal: boolean;\n  // The next entry inward along the endpoint chain; a compact portal lines up with its port.\n  inner?: { demandKey: string; side: GridSide };\n}\n\nexport interface GridAttachment {\n  port: Point;\n  connect: Point;\n  orientation: GridOrientation;\n  side: GridSide;\n}\n\nexport interface GridLayoutResult {\n  forest: GridForest;\n  config: GridLayoutConfigNormalized;\n  containers: Map<GridContainerId, GridContainerLayoutMeta>;\n  itemMeta: Map<string, GridItemLayoutMeta>;\n  sourceOrder: Map<string, number>;\n  labelRequirements: GridLabelRequirements;\n}\n\nexport interface GridError extends Error {\n  code: GridErrorCode;\n  details?: Record<string, unknown>;\n}\n\nexport type GridErrorCode =\n  | 'GRID_INVALID_COORDINATE'\n  | 'GRID_CELL_ALIGNMENT_CONFLICT'\n  | 'GRID_INVALID_CONTAINMENT'\n  | 'GRID_MISSING_MEASUREMENT'\n  | 'GRID_MISSING_ENDPOINT'\n  | 'GRID_ROUTE_NOT_FOUND';\n\nexport function gridError(\n  code: GridErrorCode,\n  message: string,\n  details?: Record<string, unknown>\n): GridError {\n  const error = new Error(`${code}: ${message}`) as GridError;\n  error.code = code;\n  error.details = details;\n  return error;\n}\n\nexport const GRID_DEFAULTS = {\n  columns: 0,\n  rowGap: 50,\n  columnGap: 50,\n  cellGap: 20,\n  containerPadding: 20,\n  titleGap: 8,\n  horizontalAlign: 'center' as GridHorizontalAlign,\n  verticalAlign: 'center' as GridVerticalAlign,\n  curve: 'rounded' as GridCurve,\n  edgeCornerRadius: DEFAULT_EDGE_CORNER_RADIUS,\n};\n\nexport type GridLayoutData = LayoutData;\n\nexport function isEdgeLabelNode(node: Node): boolean {\n  return Boolean((node as { isEdgeLabel?: boolean }).isEdgeLabel);\n}\n\nexport function isFinitePositiveNumber(value: unknown): value is number {\n  return typeof value === 'number' && Number.isFinite(value) && value > 0;\n}\n", "import type { Node } from '../../types.js';\nimport type { GridOrientation } from './types.js';\nimport { isFinitePositiveNumber } from './types.js';\n\nexport const GRID_LABEL_CLEARANCE = 6;\nexport const GRID_EDGE_END_MARKER_CLEARANCE = 12;\nexport const GRID_LABEL_SPAN_MARGIN = 2;\n\nexport interface GridLabelSpanRequirement {\n  along: number;\n  cross: number;\n  startInset: number;\n  endInset: number;\n  requiredAlongSpan: number;\n}\n\nexport function gridLabelSpanRequirement(\n  labelNode: Node,\n  orientation: GridOrientation\n): GridLabelSpanRequirement | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  const along = orientation === 'H' ? labelNode.width : labelNode.height;\n  const cross = orientation === 'H' ? labelNode.height : labelNode.width;\n  const startInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);\n  const endInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);\n\n  return {\n    along,\n    cross,\n    startInset,\n    endInset,\n    requiredAlongSpan: along + startInset + endInset + GRID_LABEL_SPAN_MARGIN,\n  };\n}\n\nexport function gridLabelRequiredSegmentLength(\n  labelNode: Node,\n  orientation: GridOrientation\n): number {\n  const along = orientation === 'H' ? labelNode.width : labelNode.height;\n  return isFinitePositiveNumber(along) ? along + GRID_LABEL_CLEARANCE * 2 : 0;\n}\n", "import type { Point } from '../../../types.js';\nimport { log } from '../../../logger.js';\nimport type { Edge, LayoutData, Node, NonClusterNode } from '../../types.js';\nimport {\n  normalizePolyline as normalizeLayoutPolyline,\n  segmentsCross,\n  type Segment,\n} from '../layout-utils/geometry.js';\nimport {\n  clamp,\n  compareCodeUnits,\n  hasTerminalMarker,\n  orthogonalPolylineContainsPoint,\n  polylineIntersectsRect,\n  rectForNode,\n  segmentIntersectsRectInterior,\n  terminalMarkerClearanceRect,\n} from '../layout-utils/helpers.js';\nimport type { Rect } from '../layout-utils/types.js';\nimport {\n  GRID_EDGE_END_MARKER_CLEARANCE,\n  GRID_LABEL_CLEARANCE,\n  gridLabelRequiredSegmentLength,\n} from './labelGeometry.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport { GRID_LABEL_PREFIX, gridError, isEdgeLabelNode, isFinitePositiveNumber } from './types.js';\n\n// prepareGridLayout moves edge label text into helper nodes linked to their owners by labelNodeId.\n// The caller measures those nodes before grid layout, but they stay out of normal node placement.\n// After routing, positionGridEdgeLabels uses their measured bounds to place labels on their owning\n// edges, rerouting affected edges as needed and storing the final helper-node positions for rendering.\nconst LABEL_CLEARANCE = GRID_LABEL_CLEARANCE;\nconst LABEL_GUTTER = 14;\nconst LABEL_GUTTER_STEP = 18;\nconst MAX_GUTTER_STEPS = 16;\nconst MAX_DETOUR_LINE_CANDIDATES = 128;\nconst MAX_DETOUR_CENTER_CANDIDATES = 64;\n// Match the router's invocation-wide search budget: retries share one deterministic work ceiling.\nconst DEFAULT_MAX_INDEX_WORK = 2_000_000;\nconst EDGE_END_MARKER_CLEARANCE = GRID_EDGE_END_MARKER_CLEARANCE;\nconst LABEL_EPSILON = 1e-6;\nconst MIN_SELF_PARALLEL_GAP = 7;\nconst MIN_SELF_PARALLEL_OVERLAP = 8;\n\n// Preserve subpixel detours with the same tolerance used to validate label anchors.\nconst normalizePolyline = (points: Point[]) => normalizeLayoutPolyline(points, LABEL_EPSILON);\n\ninterface Interval {\n  start: number;\n  end: number;\n}\n\ninterface PlacedLabel {\n  edgeId: string;\n  nodeId: string;\n  center: Point;\n  rect: Rect;\n}\n\ninterface SegmentCandidate {\n  segment: Segment;\n  segmentIndex: number;\n  order: number;\n}\n\ninterface LabelWorkItem {\n  edge: Edge;\n  labelNode: Node;\n  sourceIndex: number;\n}\n\ntype EdgePointOverrides = Map<string, Point[]>;\n\ninterface Bounds {\n  left: number;\n  right: number;\n  top: number;\n  bottom: number;\n}\n\nfunction rangeOverlapLength(\n  firstStart: number,\n  firstEnd: number,\n  secondStart: number,\n  secondEnd: number\n) {\n  const start = Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd));\n  const end = Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd));\n  return Math.max(0, end - start);\n}\n\nfunction polylineHasSelfConflict(points: readonly Point[]): boolean {\n  const segments = normalizePolyline([...points]).segments;\n  for (let firstIndex = 0; firstIndex < segments.length; firstIndex++) {\n    const first = segments[firstIndex];\n    for (let secondIndex = firstIndex + 2; secondIndex < segments.length; secondIndex++) {\n      const second = segments[secondIndex];\n      if (segmentsCross(first, second)) {\n        return true;\n      }\n      if (first.orientation !== second.orientation || first.orientation === 'Z') {\n        continue;\n      }\n\n      const sameAxis =\n        first.orientation === 'H'\n          ? Math.abs(first.a.y - second.a.y) <= LABEL_EPSILON\n          : Math.abs(first.a.x - second.a.x) <= LABEL_EPSILON;\n      const overlap =\n        first.orientation === 'H'\n          ? rangeOverlapLength(first.a.x, first.b.x, second.a.x, second.b.x)\n          : rangeOverlapLength(first.a.y, first.b.y, second.a.y, second.b.y);\n      if (sameAxis && overlap > LABEL_EPSILON) {\n        return true;\n      }\n      const gap =\n        first.orientation === 'H'\n          ? Math.abs(first.a.y - second.a.y)\n          : Math.abs(first.a.x - second.a.x);\n      if (!sameAxis && gap < MIN_SELF_PARALLEL_GAP && overlap >= MIN_SELF_PARALLEL_OVERLAP) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\ninterface ObstacleEntry {\n  id: string;\n  bounds: Bounds;\n  rect: Rect;\n  nodeId?: string;\n}\n\ninterface BorderEntry {\n  id: string;\n  bounds: Bounds;\n  rect: Rect;\n}\n\ninterface EdgeSegmentEntry {\n  id: string;\n  bounds: Bounds;\n  edgeId: string;\n  segment: Segment;\n}\n\ninterface EdgeGeometryCache {\n  points: Point[];\n  segments: Segment[];\n  candidateSegments: SegmentCandidate[];\n  markerRects: Rect[];\n}\n\nexport interface GridEdgeLabelInstrumentation {\n  obstacleRectQueries: number;\n  obstacleBandQueries: number;\n  obstaclePolylineQueries: number;\n  obstacleCandidatesVisited: number;\n  segmentRectQueries: number;\n  segmentBandQueries: number;\n  segmentCandidatesVisited: number;\n  foreignEdgeLookups: number;\n  labelPasses: number;\n  frozenReservations: number;\n  impactedEdgeReroutes: number;\n  preservedAnchors: number;\n  rerouteCandidatesEvaluated: number;\n  rerouteRejectedBlockedRect: number;\n  rerouteRejectedProtectedObstacle: number;\n  rerouteRejectedLabelAnchor: number;\n  rerouteRejectedDegenerateSpan: number;\n  reroutePartialProgressCandidates: number;\n  individualLabelRerouteAttempts: number;\n  individualLabelRerouteSuccesses: number;\n  labelOverlapFallbacks: number;\n  labelOverlapReservations: number;\n  degenerateLabelRoutesSkipped: number;\n  unmeasuredLabelsSkipped: number;\n  indexWorkUnits: number;\n  indexWorkLimitFallbacks: number;\n  placementSearchFallbacks: number;\n  rollbacks: number;\n  indexCoordinateCount: number;\n}\n\nexport interface GridEdgeLabelOptions {\n  maxIndexWork?: number;\n}\n\ninterface EdgeLabelContext {\n  // These indexes are updated with every provisional route so later searches see one coherent\n  // geometry snapshot rather than rescanning stale edge and obstacle arrays.\n  edgeById: Map<string, Edge>;\n  edgeGeometryById: Map<string, EdgeGeometryCache>;\n  obstacleIndex: CompressedBoundsIndex<ObstacleEntry>;\n  placedLabelIndex: CompressedBoundsIndex<ObstacleEntry>;\n  groupBorderIndex: CompressedBoundsIndex<BorderEntry>;\n  segmentIndex: CompressedBoundsIndex<EdgeSegmentEntry>;\n  searchBounds: Bounds;\n  metrics?: GridEdgeLabelInstrumentation;\n}\n\ntype ObstacleQueryMetric =\n  | 'obstacleRectQueries'\n  | 'obstacleBandQueries'\n  | 'obstaclePolylineQueries';\ntype SegmentQueryMetric = 'segmentRectQueries' | 'segmentBandQueries';\n\nexport function createGridEdgeLabelInstrumentation(): GridEdgeLabelInstrumentation {\n  return {\n    obstacleRectQueries: 0,\n    obstacleBandQueries: 0,\n    obstaclePolylineQueries: 0,\n    obstacleCandidatesVisited: 0,\n    segmentRectQueries: 0,\n    segmentBandQueries: 0,\n    segmentCandidatesVisited: 0,\n    foreignEdgeLookups: 0,\n    labelPasses: 0,\n    frozenReservations: 0,\n    impactedEdgeReroutes: 0,\n    preservedAnchors: 0,\n    rerouteCandidatesEvaluated: 0,\n    rerouteRejectedBlockedRect: 0,\n    rerouteRejectedProtectedObstacle: 0,\n    rerouteRejectedLabelAnchor: 0,\n    rerouteRejectedDegenerateSpan: 0,\n    reroutePartialProgressCandidates: 0,\n    individualLabelRerouteAttempts: 0,\n    individualLabelRerouteSuccesses: 0,\n    labelOverlapFallbacks: 0,\n    labelOverlapReservations: 0,\n    degenerateLabelRoutesSkipped: 0,\n    unmeasuredLabelsSkipped: 0,\n    indexWorkUnits: 0,\n    indexWorkLimitFallbacks: 0,\n    placementSearchFallbacks: 0,\n    rollbacks: 0,\n    indexCoordinateCount: 0,\n  };\n}\n\nclass LabelPlacementSearchExhaustedError extends Error {\n  constructor(public readonly details: Record<string, unknown> & { edgeId: string }) {\n    super(`Could not place label for edge \"${details.edgeId}\"`);\n    this.name = 'LabelPlacementSearchExhaustedError';\n  }\n}\n\n/**\n * A dynamic coordinate-compressed bounds index. Entries are keyed by their\n * actual boundaries; no bucket is allocated for any coordinate between them.\n * Label routing mutates these indexes often enough that a sorted sweep on the\n * compressed entries is both simpler and more predictable than rebuilding a\n * tree after every provisional reservation.\n */\nclass LabelIndexWorkLimitError extends Error {\n  constructor() {\n    super('Grid label index work cap exceeded');\n    this.name = 'LabelIndexWorkLimitError';\n  }\n}\n\nclass LabelIndexWorkBudget {\n  private used = 0;\n\n  constructor(\n    private readonly limit: number,\n    private readonly metrics?: GridEdgeLabelInstrumentation\n  ) {}\n\n  charge(units: number): void {\n    if (units <= 0) {\n      return;\n    }\n    if (this.used + units > this.limit) {\n      throw new LabelIndexWorkLimitError();\n    }\n    this.used += units;\n    incrementMetric(this.metrics, 'indexWorkUnits', units);\n  }\n}\n\nclass CompressedBoundsIndex<T extends { id: string; bounds: Bounds }> {\n  private readonly entriesById = new Map<string, T>();\n  private sortedByLeft: T[] = [];\n  private dirty = false;\n\n  constructor(\n    private readonly workBudget: LabelIndexWorkBudget,\n    private readonly metrics?: GridEdgeLabelInstrumentation\n  ) {}\n\n  upsert(entry: T): void {\n    const isNew = !this.entriesById.has(entry.id);\n    this.entriesById.set(entry.id, entry);\n    this.dirty = true;\n    if (isNew && this.metrics) {\n      // Four stored boundary coordinates per entry, independent of their span.\n      this.metrics.indexCoordinateCount += 4;\n    }\n  }\n\n  remove(id: string): void {\n    if (this.entriesById.delete(id)) {\n      this.dirty = true;\n    }\n  }\n\n  query(bounds: Bounds): T[] {\n    if (this.dirty) {\n      const entryCount = this.entriesById.size;\n      // Charge a deterministic n log n estimate before sorting so the cap is independent of the\n      // JavaScript engine's comparison order.\n      this.workBudget.charge(entryCount * Math.max(1, Math.ceil(Math.log2(entryCount + 1))));\n      this.sortedByLeft = [...this.entriesById.values()].sort(\n        (a, b) => a.bounds.left - b.bounds.left || compareCodeUnits(a.id, b.id)\n      );\n      this.dirty = false;\n    }\n    const result: T[] = [];\n    for (const entry of this.sortedByLeft) {\n      this.workBudget.charge(1);\n      if (entry.bounds.left > bounds.right) {\n        break;\n      }\n      if (boundsOverlap(entry.bounds, bounds)) {\n        result.push(entry);\n      }\n    }\n    return result;\n  }\n}\n\nfunction rectOverlap(a: Rect, b: Rect): boolean {\n  return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;\n}\n\nfunction labelRectAt(node: Node, center: Point): Rect {\n  const width = node.width ?? 0;\n  const height = node.height ?? 0;\n  return {\n    cx: center.x,\n    cy: center.y,\n    left: center.x - width / 2,\n    right: center.x + width / 2,\n    top: center.y - height / 2,\n    bottom: center.y + height / 2,\n  };\n}\n\nfunction groupTitleRect(node: Node): Rect | null {\n  const rect = node.groupTitleRect;\n  if (!rect) {\n    return null;\n  }\n  return {\n    cx: (rect.left + rect.right) / 2,\n    cy: (rect.top + rect.bottom) / 2,\n    left: rect.left,\n    right: rect.right,\n    top: rect.top,\n    bottom: rect.bottom,\n  };\n}\n\nfunction incrementMetric(\n  metrics: GridEdgeLabelInstrumentation | undefined,\n  key: keyof GridEdgeLabelInstrumentation,\n  delta = 1\n): void {\n  if (metrics) {\n    metrics[key] += delta;\n  }\n}\n\nfunction clonePoint(point: Point): Point {\n  return { ...point };\n}\n\nfunction boundsForRect(rect: Rect): Bounds {\n  return {\n    left: rect.left,\n    right: rect.right,\n    top: rect.top,\n    bottom: rect.bottom,\n  };\n}\n\nfunction boundsForSegment(segment: Segment): Bounds {\n  return {\n    left: Math.min(segment.a.x, segment.b.x),\n    right: Math.max(segment.a.x, segment.b.x),\n    top: Math.min(segment.a.y, segment.b.y),\n    bottom: Math.max(segment.a.y, segment.b.y),\n  };\n}\n\nfunction boundsForPoints(points: Point[]): Bounds | null {\n  if (points.length === 0) {\n    return null;\n  }\n  let left = points[0].x;\n  let right = points[0].x;\n  let top = points[0].y;\n  let bottom = points[0].y;\n  for (const point of points.slice(1)) {\n    left = Math.min(left, point.x);\n    right = Math.max(right, point.x);\n    top = Math.min(top, point.y);\n    bottom = Math.max(bottom, point.y);\n  }\n  return { left, right, top, bottom };\n}\n\nfunction mergeBounds(a: Bounds, b: Bounds): Bounds {\n  return {\n    left: Math.min(a.left, b.left),\n    right: Math.max(a.right, b.right),\n    top: Math.min(a.top, b.top),\n    bottom: Math.max(a.bottom, b.bottom),\n  };\n}\n\nfunction expandBounds(bounds: Bounds, padding: number): Bounds {\n  return {\n    left: bounds.left - padding,\n    right: bounds.right + padding,\n    top: bounds.top - padding,\n    bottom: bounds.bottom + padding,\n  };\n}\n\nfunction boundsOverlap(a: Bounds, b: Bounds): boolean {\n  return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;\n}\n\nfunction candidateSegmentsFromSegments(segments: Segment[]): SegmentCandidate[] {\n  const indexes =\n    segments.length <= 2\n      ? segments.map((_, index) => index)\n      : [...segments.slice(1, -1).map((_, index) => index + 1), 0, segments.length - 1];\n  return indexes.map((segmentIndex, order) => ({\n    segment: segments[segmentIndex],\n    segmentIndex,\n    order,\n  }));\n}\n\nfunction markerClearanceRectsFromPoints(edge: Edge, points: Point[]): Rect[] {\n  const terminals = ['start', 'end'] as const;\n  return terminals\n    .filter((terminal) => hasTerminalMarker(edge, terminal))\n    .map((terminal) =>\n      terminalMarkerClearanceRect(points, terminal, EDGE_END_MARKER_CLEARANCE, 7, LABEL_EPSILON)\n    )\n    .filter((rect): rect is Rect => rect !== null);\n}\n\nfunction buildEdgeGeometry(edge: Edge, points: Point[]): EdgeGeometryCache {\n  const normalized = normalizePolyline(points);\n  return {\n    points: normalized.points,\n    segments: normalized.segments,\n    candidateSegments: candidateSegmentsFromSegments(normalized.segments),\n    markerRects: markerClearanceRectsFromPoints(edge, normalized.points),\n  };\n}\n\nfunction segmentLength(segment: Segment): number {\n  return segment.orientation === 'H'\n    ? Math.abs(segment.b.x - segment.a.x)\n    : Math.abs(segment.b.y - segment.a.y);\n}\n\nfunction borderCutsRect(rect: Rect, border: Rect): boolean {\n  const corners: Point[] = [\n    { x: border.left, y: border.top },\n    { x: border.right, y: border.top },\n    { x: border.right, y: border.bottom },\n    { x: border.left, y: border.bottom },\n  ];\n  for (let i = 0; i < corners.length; i++) {\n    if (segmentIntersectsRectInterior(corners[i], corners[(i + 1) % corners.length], rect)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction hasFinitePosition(node: Node): boolean {\n  return Number.isFinite(node.x) && Number.isFinite(node.y);\n}\n\nfunction pointsForEdge(\n  edge: Edge,\n  overrides?: EdgePointOverrides,\n  context?: EdgeLabelContext\n): Point[] {\n  const overridePoints = overrides?.get(edge.id);\n  if (overridePoints) {\n    return normalizePolyline(overridePoints).points;\n  }\n  const cached = context?.edgeGeometryById.get(edge.id);\n  if (cached) {\n    return cached.points;\n  }\n  return normalizePolyline(edge.points ?? []).points;\n}\n\nfunction markerClearanceRectsForEdge(\n  edge: Edge,\n  overrides?: EdgePointOverrides,\n  context?: EdgeLabelContext\n): Rect[] {\n  if (!overrides?.has(edge.id)) {\n    const cached = context?.edgeGeometryById.get(edge.id);\n    if (cached) {\n      return cached.markerRects;\n    }\n  }\n  return markerClearanceRectsFromPoints(edge, pointsForEdge(edge, overrides, context));\n}\n\nfunction rangeOverlaps(aStart: number, aEnd: number, bStart: number, bEnd: number): boolean {\n  return (\n    Math.max(Math.min(aStart, aEnd), Math.min(bStart, bEnd)) <\n    Math.min(Math.max(aStart, aEnd), Math.max(bStart, bEnd)) - LABEL_EPSILON\n  );\n}\n\nfunction clampInterval(interval: Interval, low: number, high: number): Interval | null {\n  const start = clamp(Math.min(interval.start, interval.end), low, high);\n  const end = clamp(Math.max(interval.start, interval.end), low, high);\n  return end - start > LABEL_EPSILON ? { start, end } : null;\n}\n\nfunction mergeBlockedLabelIntervals(intervals: Interval[], low: number, high: number): Interval[] {\n  const clamped = intervals\n    .map((interval) => clampInterval(interval, low, high))\n    .filter((interval): interval is Interval => interval !== null)\n    .sort((a, b) => a.start - b.start || a.end - b.end);\n\n  if (clamped.length === 0) {\n    return [];\n  }\n\n  const merged: Interval[] = [clamped[0]];\n  for (let index = 1; index < clamped.length; index++) {\n    const current = clamped[index];\n    const previous = merged[merged.length - 1];\n    if (current.start <= previous.end + LABEL_EPSILON) {\n      previous.end = Math.max(previous.end, current.end);\n    } else {\n      merged.push(current);\n    }\n  }\n  return merged;\n}\n\nfunction centerCandidatesFromIntervals(\n  low: number,\n  high: number,\n  blocked: Interval[],\n  preferred: number\n): number[] {\n  if (high - low <= LABEL_EPSILON) {\n    return [];\n  }\n\n  const allowed: Interval[] = [];\n  let cursor = low;\n  for (const interval of mergeBlockedLabelIntervals(blocked, low, high)) {\n    if (interval.start - cursor > LABEL_EPSILON) {\n      allowed.push({ start: cursor, end: interval.start });\n    }\n    cursor = Math.max(cursor, interval.end);\n  }\n  if (high - cursor > LABEL_EPSILON) {\n    allowed.push({ start: cursor, end: high });\n  }\n\n  const candidates = allowed.map((interval) => ({\n    value: clamp(preferred, interval.start, interval.end),\n    start: interval.start,\n    end: interval.end,\n  }));\n  candidates.sort((a, b) => {\n    const preferredDelta = Math.abs(a.value - preferred) - Math.abs(b.value - preferred);\n    if (Math.abs(preferredDelta) > LABEL_EPSILON) {\n      return preferredDelta;\n    }\n    const widthDelta = b.end - b.start - (a.end - a.start);\n    if (Math.abs(widthDelta) > LABEL_EPSILON) {\n      return widthDelta;\n    }\n    return a.value - b.value;\n  });\n\n  const seen = new Set<number>();\n  const values: number[] = [];\n  for (const candidate of candidates) {\n    const rounded = Math.round(candidate.value * 1e6) / 1e6;\n    if (seen.has(rounded)) {\n      continue;\n    }\n    seen.add(rounded);\n    values.push(candidate.value);\n  }\n  return values;\n}\n\nfunction obstacleRectForNode(node: Node): Rect | null {\n  if (node.isGroup) {\n    return null;\n  }\n  if (isEdgeLabelNode(node) && !hasFinitePosition(node)) {\n    return null;\n  }\n  return rectForNode(node);\n}\n\nfunction candidateSegments(edge: Edge, context?: EdgeLabelContext): SegmentCandidate[] {\n  const cached = context?.edgeGeometryById.get(edge.id);\n  if (cached) {\n    return cached.candidateSegments;\n  }\n  return candidateSegmentsFromSegments(normalizePolyline(edge.points ?? []).segments);\n}\n\nfunction storeEdgeGeometry(\n  context: EdgeLabelContext,\n  edgeId: string,\n  geometry: EdgeGeometryCache\n): void {\n  const previous = context.edgeGeometryById.get(edgeId);\n  if (previous) {\n    previous.segments.forEach((_, index) => context.segmentIndex.remove(`${edgeId}:${index}`));\n  }\n\n  context.edgeGeometryById.set(edgeId, geometry);\n  geometry.segments.forEach((segment, index) => {\n    context.segmentIndex.upsert({\n      id: `${edgeId}:${index}`,\n      edgeId,\n      segment,\n      bounds: boundsForSegment(segment),\n    });\n  });\n}\n\nfunction setEdgePoints(context: EdgeLabelContext, edge: Edge, points: Point[]): void {\n  const geometry = buildEdgeGeometry(edge, points);\n  edge.points = geometry.points.map(clonePoint);\n  storeEdgeGeometry(context, edge.id, geometry);\n}\n\nfunction upsertPlacedLabelObstacle(context: EdgeLabelContext, placedLabel: PlacedLabel): void {\n  context.placedLabelIndex.upsert({\n    id: `label:${placedLabel.nodeId}`,\n    nodeId: placedLabel.nodeId,\n    rect: placedLabel.rect,\n    bounds: boundsForRect(placedLabel.rect),\n  });\n}\n\nfunction createEdgeLabelContext(\n  data: LayoutData,\n  workBudget: LabelIndexWorkBudget,\n  metrics?: GridEdgeLabelInstrumentation\n): EdgeLabelContext {\n  // A fresh context is the isolation boundary for one placement pass. Nothing indexed here is\n  // reused after rollback because route proposals and label reservations are pass-local.\n  const context: EdgeLabelContext = {\n    edgeById: new Map(),\n    edgeGeometryById: new Map(),\n    obstacleIndex: new CompressedBoundsIndex<ObstacleEntry>(workBudget, metrics),\n    placedLabelIndex: new CompressedBoundsIndex<ObstacleEntry>(workBudget, metrics),\n    groupBorderIndex: new CompressedBoundsIndex<BorderEntry>(workBudget, metrics),\n    segmentIndex: new CompressedBoundsIndex<EdgeSegmentEntry>(workBudget, metrics),\n    searchBounds: { left: 0, right: 0, top: 0, bottom: 0 },\n    metrics,\n  };\n\n  let aggregateBounds: Bounds | null = null;\n  const rememberBounds = (bounds: Bounds) => {\n    aggregateBounds = aggregateBounds ? mergeBounds(aggregateBounds, bounds) : { ...bounds };\n  };\n\n  for (const node of data.nodes) {\n    if (node.isGroup) {\n      const borderRect = rectForNode(node);\n      const borderBounds = boundsForRect(borderRect);\n      context.groupBorderIndex.upsert({\n        id: `border:${node.id}`,\n        rect: borderRect,\n        bounds: borderBounds,\n      });\n      rememberBounds(borderBounds);\n\n      const titleRect = groupTitleRect(node);\n      if (titleRect) {\n        const titleBounds = boundsForRect(titleRect);\n        context.obstacleIndex.upsert({\n          id: `title:${node.id}`,\n          rect: titleRect,\n          bounds: titleBounds,\n        });\n        rememberBounds(titleBounds);\n      }\n      continue;\n    }\n\n    const obstacleRect = obstacleRectForNode(node);\n    if (!obstacleRect) {\n      continue;\n    }\n\n    const entry: ObstacleEntry = {\n      id: `${isEdgeLabelNode(node) ? 'label' : 'node'}:${node.id}`,\n      rect: obstacleRect,\n      bounds: boundsForRect(obstacleRect),\n      nodeId: node.id,\n    };\n    if (isEdgeLabelNode(node)) {\n      context.placedLabelIndex.upsert(entry);\n    } else {\n      context.obstacleIndex.upsert(entry);\n    }\n    rememberBounds(entry.bounds);\n  }\n\n  for (const edge of data.edges) {\n    context.edgeById.set(edge.id, edge);\n    const geometry = buildEdgeGeometry(edge, edge.points ?? []);\n    storeEdgeGeometry(context, edge.id, geometry);\n    const pointBounds = boundsForPoints(geometry.points);\n    if (pointBounds) {\n      rememberBounds(pointBounds);\n    }\n  }\n\n  context.searchBounds = expandBounds(\n    aggregateBounds ?? { left: 0, right: 0, top: 0, bottom: 0 },\n    128\n  );\n  return context;\n}\n\nfunction queryObstacleEntries(\n  context: EdgeLabelContext,\n  bounds: Bounds,\n  metricKey: ObstacleQueryMetric,\n  options: {\n    excludeNodeId?: string;\n    skipNodeIds?: ReadonlySet<string>;\n  } = {}\n): ObstacleEntry[] {\n  incrementMetric(context.metrics, metricKey);\n\n  const collected: ObstacleEntry[] = [];\n  const appendEntries = (entries: ObstacleEntry[]) => {\n    for (const entry of entries) {\n      if (\n        entry.nodeId &&\n        (entry.nodeId === options.excludeNodeId || options.skipNodeIds?.has(entry.nodeId))\n      ) {\n        continue;\n      }\n      collected.push(entry);\n    }\n  };\n\n  appendEntries(context.obstacleIndex.query(bounds));\n  appendEntries(context.placedLabelIndex.query(bounds));\n  incrementMetric(context.metrics, 'obstacleCandidatesVisited', collected.length);\n  return collected;\n}\n\nfunction queryForeignSegments(\n  context: EdgeLabelContext,\n  bounds: Bounds,\n  selfEdgeId: string,\n  overrides: EdgePointOverrides | undefined,\n  metricKey: SegmentQueryMetric\n): EdgeSegmentEntry[] {\n  incrementMetric(context.metrics, metricKey);\n\n  const overriddenEdgeIds = overrides ? new Set(overrides.keys()) : undefined;\n  const collected: EdgeSegmentEntry[] = [];\n  const indexedEntries = context.segmentIndex.query(bounds);\n  for (const entry of indexedEntries) {\n    if (entry.edgeId === selfEdgeId || overriddenEdgeIds?.has(entry.edgeId)) {\n      continue;\n    }\n    collected.push(entry);\n  }\n\n  let visited = indexedEntries.length;\n  if (overrides) {\n    for (const [edgeId, points] of overrides) {\n      if (edgeId === selfEdgeId) {\n        continue;\n      }\n      const edge = context.edgeById.get(edgeId);\n      if (!edge) {\n        continue;\n      }\n      const geometry = buildEdgeGeometry(edge, points);\n      geometry.segments.forEach((segment, index) => {\n        const segmentBounds = boundsForSegment(segment);\n        if (!boundsOverlap(segmentBounds, bounds)) {\n          return;\n        }\n        visited += 1;\n        collected.push({\n          id: `override:${edgeId}:${index}`,\n          edgeId,\n          segment,\n          bounds: segmentBounds,\n        });\n      });\n    }\n  }\n\n  incrementMetric(context.metrics, 'segmentCandidatesVisited', visited);\n  return collected;\n}\n\nfunction foreignEdgeIdsIntersectingRect(\n  context: EdgeLabelContext,\n  rect: Rect,\n  selfEdgeId: string,\n  overrides?: EdgePointOverrides\n): string[] {\n  incrementMetric(context.metrics, 'foreignEdgeLookups');\n  const ids = new Set<string>();\n  for (const entry of queryForeignSegments(\n    context,\n    boundsForRect(rect),\n    selfEdgeId,\n    overrides,\n    'segmentRectQueries'\n  )) {\n    if (segmentIntersectsRectInterior(entry.segment.a, entry.segment.b, rect)) {\n      ids.add(entry.edgeId);\n    }\n  }\n  return [...ids].sort(compareCodeUnits);\n}\n\nfunction obstacleBandQueryBounds(segment: Segment, labelNode: Node): Bounds | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  if (segment.orientation === 'H') {\n    return {\n      left: Math.min(segment.a.x, segment.b.x) - labelNode.width / 2,\n      right: Math.max(segment.a.x, segment.b.x) + labelNode.width / 2,\n      top: segment.a.y - labelNode.height / 2,\n      bottom: segment.a.y + labelNode.height / 2,\n    };\n  }\n\n  return {\n    left: segment.a.x - labelNode.width / 2,\n    right: segment.a.x + labelNode.width / 2,\n    top: Math.min(segment.a.y, segment.b.y) - labelNode.height / 2,\n    bottom: Math.max(segment.a.y, segment.b.y) + labelNode.height / 2,\n  };\n}\n\nfunction detourLineQueryBounds(segment: Segment, labelNode: Node, searchBounds: Bounds): Bounds {\n  if (segment.orientation === 'H') {\n    const alongPadding = (labelNode.width ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;\n    return {\n      left: Math.min(segment.a.x, segment.b.x) - alongPadding,\n      right: Math.max(segment.a.x, segment.b.x) + alongPadding,\n      top: searchBounds.top,\n      bottom: searchBounds.bottom,\n    };\n  }\n\n  const alongPadding = (labelNode.height ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;\n  return {\n    left: searchBounds.left,\n    right: searchBounds.right,\n    top: Math.min(segment.a.y, segment.b.y) - alongPadding,\n    bottom: Math.max(segment.a.y, segment.b.y) + alongPadding,\n  };\n}\n\nfunction rerouteLineQueryBounds(segment: Segment, searchBounds: Bounds): Bounds {\n  if (segment.orientation === 'H') {\n    return {\n      left: Math.min(segment.a.x, segment.b.x) - LABEL_CLEARANCE,\n      right: Math.max(segment.a.x, segment.b.x) + LABEL_CLEARANCE,\n      top: searchBounds.top,\n      bottom: searchBounds.bottom,\n    };\n  }\n\n  return {\n    left: searchBounds.left,\n    right: searchBounds.right,\n    top: Math.min(segment.a.y, segment.b.y) - LABEL_CLEARANCE,\n    bottom: Math.max(segment.a.y, segment.b.y) + LABEL_CLEARANCE,\n  };\n}\n\nfunction rectSafeForLabel(\n  rect: Rect,\n  edge: Edge,\n  labelNodeId: string,\n  context: EdgeLabelContext,\n  overrides?: EdgePointOverrides,\n  allowedForeignEdgeIds?: ReadonlySet<string>\n): boolean {\n  for (const obstacle of queryObstacleEntries(context, boundsForRect(rect), 'obstacleRectQueries', {\n    excludeNodeId: labelNodeId,\n  })) {\n    if (rectOverlap(rect, obstacle.rect)) {\n      return false;\n    }\n  }\n\n  for (const border of context.groupBorderIndex.query(boundsForRect(rect))) {\n    if (borderCutsRect(rect, border.rect)) {\n      return false;\n    }\n  }\n\n  for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {\n    if (rectOverlap(rect, clearanceRect)) {\n      return false;\n    }\n  }\n\n  for (const foreignSegment of queryForeignSegments(\n    context,\n    boundsForRect(rect),\n    edge.id,\n    overrides,\n    'segmentRectQueries'\n  )) {\n    if (allowedForeignEdgeIds?.has(foreignSegment.edgeId)) {\n      continue;\n    }\n    if (segmentIntersectsRectInterior(foreignSegment.segment.a, foreignSegment.segment.b, rect)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction requiredSegmentLength(node: Node, segment: Segment): number {\n  return segment.orientation === 'Z'\n    ? 0\n    : gridLabelRequiredSegmentLength(node, segment.orientation);\n}\n\nfunction blockedCenterIntervals(\n  edge: Edge,\n  labelNode: Node,\n  segment: Segment,\n  context: EdgeLabelContext,\n  overrides: EdgePointOverrides | undefined,\n  includeForeignEdges: boolean\n): { low: number; high: number; blocked: Interval[] } | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n  const labelWidth = labelNode.width;\n  const labelHeight = labelNode.height;\n\n  const alongHalf =\n    segment.orientation === 'H'\n      ? labelWidth / 2 + LABEL_CLEARANCE\n      : labelHeight / 2 + LABEL_CLEARANCE;\n  const low =\n    segment.orientation === 'H'\n      ? Math.min(segment.a.x, segment.b.x) + alongHalf\n      : Math.min(segment.a.y, segment.b.y) + alongHalf;\n  const high =\n    segment.orientation === 'H'\n      ? Math.max(segment.a.x, segment.b.x) - alongHalf\n      : Math.max(segment.a.y, segment.b.y) - alongHalf;\n  if (high - low <= LABEL_EPSILON) {\n    return null;\n  }\n\n  // Project every obstacle onto the candidate segment. The remaining interval gaps are the only\n  // centers worth testing, which keeps placement deterministic and avoids pixel-by-pixel search.\n  const blocked: Interval[] = [];\n  const bandBounds = obstacleBandQueryBounds(segment, labelNode);\n  if (!bandBounds) {\n    return null;\n  }\n  const addRect = (rect: Rect) => {\n    if (segment.orientation === 'H') {\n      const bandTop = segment.a.y - labelHeight / 2;\n      const bandBottom = segment.a.y + labelHeight / 2;\n      if (rangeOverlaps(bandTop, bandBottom, rect.top, rect.bottom)) {\n        blocked.push({\n          start: rect.left - labelWidth / 2,\n          end: rect.right + labelWidth / 2,\n        });\n      }\n      return;\n    }\n\n    const bandLeft = segment.a.x - labelWidth / 2;\n    const bandRight = segment.a.x + labelWidth / 2;\n    if (rangeOverlaps(bandLeft, bandRight, rect.left, rect.right)) {\n      blocked.push({\n        start: rect.top - labelHeight / 2,\n        end: rect.bottom + labelHeight / 2,\n      });\n    }\n  };\n\n  for (const obstacle of queryObstacleEntries(context, bandBounds, 'obstacleBandQueries', {\n    excludeNodeId: labelNode.id,\n  })) {\n    addRect(obstacle.rect);\n  }\n  for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {\n    addRect(clearanceRect);\n  }\n\n  if (includeForeignEdges) {\n    for (const foreignSegment of queryForeignSegments(\n      context,\n      bandBounds,\n      edge.id,\n      overrides,\n      'segmentBandQueries'\n    )) {\n      const segmentEntry = foreignSegment.segment;\n      if (segment.orientation === 'H') {\n        const bandTop = segment.a.y - labelNode.height / 2;\n        const bandBottom = segment.a.y + labelNode.height / 2;\n        if (segmentEntry.orientation === 'H') {\n          if (bandTop < segmentEntry.a.y && bandBottom > segmentEntry.a.y) {\n            blocked.push({\n              start: Math.min(segmentEntry.a.x, segmentEntry.b.x) - labelNode.width / 2,\n              end: Math.max(segmentEntry.a.x, segmentEntry.b.x) + labelNode.width / 2,\n            });\n          }\n        } else if (\n          rangeOverlaps(\n            bandTop,\n            bandBottom,\n            Math.min(segmentEntry.a.y, segmentEntry.b.y),\n            Math.max(segmentEntry.a.y, segmentEntry.b.y)\n          )\n        ) {\n          blocked.push({\n            start: segmentEntry.a.x - labelNode.width / 2,\n            end: segmentEntry.a.x + labelNode.width / 2,\n          });\n        }\n        continue;\n      }\n\n      const bandLeft = segment.a.x - labelNode.width / 2;\n      const bandRight = segment.a.x + labelNode.width / 2;\n      if (segmentEntry.orientation === 'V') {\n        if (bandLeft < segmentEntry.a.x && bandRight > segmentEntry.a.x) {\n          blocked.push({\n            start: Math.min(segmentEntry.a.y, segmentEntry.b.y) - labelNode.height / 2,\n            end: Math.max(segmentEntry.a.y, segmentEntry.b.y) + labelNode.height / 2,\n          });\n        }\n      } else if (\n        rangeOverlaps(\n          bandLeft,\n          bandRight,\n          Math.min(segmentEntry.a.x, segmentEntry.b.x),\n          Math.max(segmentEntry.a.x, segmentEntry.b.x)\n        )\n      ) {\n        blocked.push({\n          start: segmentEntry.a.y - labelNode.height / 2,\n          end: segmentEntry.a.y + labelNode.height / 2,\n        });\n      }\n    }\n  }\n\n  return { low, high, blocked };\n}\n\nfunction placementOnExistingSegment(\n  edge: Edge,\n  labelNode: Node,\n  segment: Segment,\n  context: EdgeLabelContext\n): Point | null {\n  if (segmentLength(segment) < requiredSegmentLength(labelNode, segment)) {\n    return null;\n  }\n\n  const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, undefined, true);\n  if (!intervalData) {\n    return null;\n  }\n\n  const preferred =\n    segment.orientation === 'H'\n      ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n      : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n\n  const candidates = centerCandidatesFromIntervals(\n    intervalData.low,\n    intervalData.high,\n    intervalData.blocked,\n    preferred\n  );\n  for (const candidate of candidates) {\n    const center =\n      segment.orientation === 'H'\n        ? { x: candidate, y: segment.a.y }\n        : { x: segment.a.x, y: candidate };\n    const rect = labelRectAt(labelNode, center);\n    if (rectSafeForLabel(rect, edge, labelNode.id, context)) {\n      return center;\n    }\n  }\n\n  return null;\n}\n\nfunction placementOnExistingSegmentWithReroutes(\n  edge: Edge,\n  labelNode: Node,\n  segment: Segment,\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n  const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, undefined, false);\n  if (!intervalData) {\n    return null;\n  }\n\n  const preferred =\n    segment.orientation === 'H'\n      ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n      : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n  const candidates = centerCandidatesFromIntervals(\n    intervalData.low,\n    intervalData.high,\n    intervalData.blocked,\n    preferred\n  );\n\n  for (const candidate of candidates) {\n    const center =\n      segment.orientation === 'H'\n        ? { x: candidate, y: segment.a.y }\n        : { x: segment.a.x, y: candidate };\n    const rect = labelRectAt(labelNode, center);\n    const overrides: EdgePointOverrides = new Map();\n    const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id)\n      .map((edgeId) => context.edgeById.get(edgeId))\n      .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n    let ok = true;\n    for (const foreignEdge of foreignEdges) {\n      const reroutedPoints = rerouteForeignEdgeAroundRect(\n        foreignEdge,\n        rect,\n        context,\n        placedLabelsByEdgeId,\n        overrides\n      );\n      if (!reroutedPoints) {\n        ok = false;\n        break;\n      }\n      overrides.set(foreignEdge.id, reroutedPoints);\n    }\n\n    if (!ok) {\n      continue;\n    }\n    if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n      continue;\n    }\n\n    for (const [edgeId, points] of overrides) {\n      const foreignEdge = context.edgeById.get(edgeId);\n      if (foreignEdge) {\n        setEdgePoints(context, foreignEdge, points);\n      }\n    }\n    return center;\n  }\n\n  return null;\n}\n\nfunction polylineHitsProtectedObstacles(\n  points: Point[],\n  context: EdgeLabelContext,\n  skipNodeIds: ReadonlySet<string>\n): boolean {\n  for (const segment of normalizePolyline(points).segments) {\n    for (const obstacle of queryObstacleEntries(\n      context,\n      boundsForSegment(segment),\n      'obstaclePolylineQueries',\n      { skipNodeIds }\n    )) {\n      if (segmentIntersectsRectInterior(segment.a, segment.b, obstacle.rect)) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nfunction labelStillAnchored(\n  edgeId: string,\n  points: Point[],\n  placedLabelsByEdgeId: Map<string, PlacedLabel>\n): boolean {\n  const placed = placedLabelsByEdgeId.get(edgeId);\n  // Owner reroutes may change the supporting segment, but the reserved center must remain on the\n  // polyline. Merely touching the label border would leave the rendered label beside its edge.\n  return !placed || orthogonalPolylineContainsPoint(points, placed.center, LABEL_EPSILON);\n}\n\nfunction detourOffsets(crossHalfSize: number): number[] {\n  const out: number[] = [];\n  for (let step = 0; step < MAX_GUTTER_STEPS; step++) {\n    const offset = crossHalfSize + LABEL_GUTTER + step * LABEL_GUTTER_STEP;\n    out.push(-offset, offset);\n  }\n  return out;\n}\n\nfunction uniqueSortedCandidates(values: number[], anchor: number): number[] {\n  const rounded = new Map<number, number>();\n  for (const value of values) {\n    const key = Math.round(value * 1e6) / 1e6;\n    if (!rounded.has(key)) {\n      rounded.set(key, value);\n    }\n  }\n  return [...rounded.values()].sort((a, b) => {\n    const distanceDelta = Math.abs(a - anchor) - Math.abs(b - anchor);\n    if (Math.abs(distanceDelta) > LABEL_EPSILON) {\n      return distanceDelta;\n    }\n    return a - b;\n  });\n}\n\nfunction detourLineCandidates(\n  edge: Edge,\n  labelNode: Node,\n  segment: Segment,\n  context: EdgeLabelContext\n): number[] {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return [];\n  }\n\n  const labelWidth = labelNode.width;\n  const labelHeight = labelNode.height;\n  const anchor = segment.orientation === 'H' ? segment.a.y : segment.a.x;\n  const crossHalfSize = segment.orientation === 'H' ? labelHeight / 2 : labelWidth / 2;\n  const candidates = detourOffsets(crossHalfSize).map((offset) => anchor + offset);\n  const addRect = (rect: Rect) => {\n    if (segment.orientation === 'H') {\n      candidates.push(rect.top - crossHalfSize - LABEL_GUTTER);\n      candidates.push(rect.bottom + crossHalfSize + LABEL_GUTTER);\n      return;\n    }\n    candidates.push(rect.left - crossHalfSize - LABEL_GUTTER);\n    candidates.push(rect.right + crossHalfSize + LABEL_GUTTER);\n  };\n\n  for (const obstacle of queryObstacleEntries(\n    context,\n    detourLineQueryBounds(segment, labelNode, context.searchBounds),\n    'obstacleBandQueries',\n    { excludeNodeId: labelNode.id }\n  )) {\n    addRect(obstacle.rect);\n  }\n  for (const clearanceRect of markerClearanceRectsForEdge(edge, undefined, context)) {\n    addRect(clearanceRect);\n  }\n\n  return uniqueSortedCandidates(candidates, anchor).slice(0, MAX_DETOUR_LINE_CANDIDATES);\n}\n\nfunction rerouteLineCandidates(\n  segment: Segment,\n  blockedRect: Rect,\n  context: EdgeLabelContext,\n  skipNodeIds: ReadonlySet<string>,\n  lane?: RerouteLane\n): number[] {\n  const anchor = segment.orientation === 'H' ? segment.a.y : segment.a.x;\n  const candidates: number[] = [];\n  for (const offset of detourOffsets(0)) {\n    if (segment.orientation === 'H') {\n      candidates.push(offset < 0 ? blockedRect.top + offset : blockedRect.bottom + offset);\n    } else {\n      candidates.push(offset < 0 ? blockedRect.left + offset : blockedRect.right + offset);\n    }\n  }\n\n  const addRect = (rect: Rect) => {\n    if (segment.orientation === 'H') {\n      candidates.push(rect.top - LABEL_GUTTER);\n      candidates.push(rect.bottom + LABEL_GUTTER);\n      return;\n    }\n    candidates.push(rect.left - LABEL_GUTTER);\n    candidates.push(rect.right + LABEL_GUTTER);\n  };\n\n  for (const obstacle of queryObstacleEntries(\n    context,\n    rerouteLineQueryBounds(segment, context.searchBounds),\n    'obstacleBandQueries',\n    { skipNodeIds }\n  )) {\n    addRect(obstacle.rect);\n  }\n\n  const sorted = uniqueSortedCandidates(candidates, anchor);\n  const sideCandidates =\n    lane?.orientation === segment.orientation\n      ? sorted.filter((candidate) => {\n          if (lane.side === 'top') {\n            return candidate < blockedRect.top;\n          }\n          if (lane.side === 'bottom') {\n            return candidate > blockedRect.bottom;\n          }\n          if (lane.side === 'left') {\n            return candidate < blockedRect.left;\n          }\n          return candidate > blockedRect.right;\n        })\n      : sorted;\n  return sideCandidates.slice(0, MAX_DETOUR_LINE_CANDIDATES);\n}\n\nfunction detourCenterCandidates(\n  edge: Edge,\n  labelNode: Node,\n  segment: Segment,\n  detourLineCoord: number,\n  context: EdgeLabelContext\n): number[] {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return [];\n  }\n\n  const labelWidth = labelNode.width;\n  const labelHeight = labelNode.height;\n  const detourSegment: Segment =\n    segment.orientation === 'H'\n      ? {\n          orientation: 'H',\n          a: { x: segment.a.x, y: detourLineCoord },\n          b: { x: segment.b.x, y: detourLineCoord },\n        }\n      : {\n          orientation: 'V',\n          a: { x: detourLineCoord, y: segment.a.y },\n          b: { x: detourLineCoord, y: segment.b.y },\n        };\n\n  const intervalData = blockedCenterIntervals(\n    edge,\n    labelNode,\n    detourSegment,\n    context,\n    undefined,\n    false\n  );\n  if (!intervalData) {\n    const preferred =\n      segment.orientation === 'H'\n        ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n        : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n    const candidates = [preferred];\n    const queryBounds = obstacleBandQueryBounds(detourSegment, labelNode);\n    const addRect = (rect: Rect) => {\n      if (segment.orientation === 'H') {\n        candidates.push(rect.left - LABEL_GUTTER - labelWidth / 2);\n        candidates.push(rect.right + LABEL_GUTTER + labelWidth / 2);\n        return;\n      }\n      candidates.push(rect.top - LABEL_GUTTER - labelHeight / 2);\n      candidates.push(rect.bottom + LABEL_GUTTER + labelHeight / 2);\n    };\n    if (queryBounds) {\n      for (const obstacle of queryObstacleEntries(context, queryBounds, 'obstacleBandQueries', {\n        excludeNodeId: labelNode.id,\n      })) {\n        addRect(obstacle.rect);\n      }\n    }\n    return uniqueSortedCandidates(candidates, preferred).slice(0, MAX_DETOUR_CENTER_CANDIDATES);\n  }\n\n  const preferred =\n    segment.orientation === 'H'\n      ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n      : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;\n\n  return centerCandidatesFromIntervals(\n    intervalData.low,\n    intervalData.high,\n    intervalData.blocked,\n    preferred\n  );\n}\n\nfunction detourReturnCoordinate(\n  sourceLine: number,\n  detourLine: number,\n  labelHalfSize: number\n): number {\n  const direction = detourLine >= sourceLine ? 1 : -1;\n  return detourLine + direction * (labelHalfSize + LABEL_CLEARANCE);\n}\n\ninterface DetourAxis {\n  along(point: Point): number;\n  cross(point: Point): number;\n  point(along: number, cross: number): Point;\n  labelAlongSize(labelNode: Node): number;\n  labelCrossSize(labelNode: Node): number;\n}\n\nconst HORIZONTAL_DETOUR_AXIS: DetourAxis = {\n  along: (point) => point.x,\n  cross: (point) => point.y,\n  point: (along, cross) => ({ x: along, y: cross }),\n  labelAlongSize: (labelNode) => labelNode.width ?? 0,\n  labelCrossSize: (labelNode) => labelNode.height ?? 0,\n};\n\nconst VERTICAL_DETOUR_AXIS: DetourAxis = {\n  along: (point) => point.y,\n  cross: (point) => point.x,\n  point: (along, cross) => ({ x: cross, y: along }),\n  labelAlongSize: (labelNode) => labelNode.height ?? 0,\n  labelCrossSize: (labelNode) => labelNode.width ?? 0,\n};\n\nfunction detourAxis(segment: Segment): DetourAxis {\n  return segment.orientation === 'H' ? HORIZONTAL_DETOUR_AXIS : VERTICAL_DETOUR_AXIS;\n}\n\nfunction buildLabelDetourPoints(\n  points: Point[],\n  segmentIndex: number,\n  segment: Segment,\n  labelNode: Node,\n  centerAlong: number,\n  detourLineCoord: number\n): Point[] | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  // Keep the original terminal-adjacent anchors intact; marker clearance and node clipping own\n  // endpoint geometry, while label placement owns only the interior detour.\n  const a = points[segmentIndex];\n  const b = points[segmentIndex + 1];\n  const axis = detourAxis(segment);\n  const sourceLine = axis.cross(segment.a);\n  const aAlong = axis.along(a);\n  const bAlong = axis.along(b);\n  const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;\n  const detourStart = centerAlong - span / 2;\n  const detourEnd = centerAlong + span / 2;\n  const extendsBeforeStart = detourStart < Math.min(aAlong, bAlong) - LABEL_EPSILON;\n  const extendsAfterEnd = detourEnd > Math.max(aAlong, bAlong) + LABEL_EPSILON;\n  const alongDirection = bAlong >= aAlong ? 1 : -1;\n  const segmentInset = Math.max(\n    0,\n    Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / 2 - LABEL_EPSILON)\n  );\n  const entryAlong = aAlong + alongDirection * segmentInset;\n  const exitAlong = bAlong - alongDirection * segmentInset;\n  if (!extendsBeforeStart && !extendsAfterEnd) {\n    return normalizePolyline([\n      ...points.slice(0, segmentIndex),\n      a,\n      axis.point(detourStart, sourceLine),\n      axis.point(detourStart, detourLineCoord),\n      axis.point(detourEnd, detourLineCoord),\n      axis.point(detourEnd, sourceLine),\n      b,\n      ...points.slice(segmentIndex + 2),\n    ]).points;\n  }\n\n  const returnLine = detourReturnCoordinate(\n    sourceLine,\n    detourLineCoord,\n    axis.labelCrossSize(labelNode) / 2\n  );\n  const detourPoints: Point[] = [...points.slice(0, segmentIndex), a];\n  if (extendsBeforeStart) {\n    detourPoints.push(\n      axis.point(entryAlong, sourceLine),\n      axis.point(entryAlong, returnLine),\n      axis.point(detourStart, returnLine),\n      axis.point(detourStart, detourLineCoord)\n    );\n  } else {\n    detourPoints.push(\n      axis.point(detourStart, sourceLine),\n      axis.point(detourStart, detourLineCoord)\n    );\n  }\n  detourPoints.push(axis.point(detourEnd, detourLineCoord));\n  if (extendsAfterEnd) {\n    detourPoints.push(\n      axis.point(detourEnd, returnLine),\n      axis.point(exitAlong, returnLine),\n      axis.point(exitAlong, sourceLine)\n    );\n  } else {\n    detourPoints.push(axis.point(detourEnd, sourceLine));\n  }\n  detourPoints.push(b, ...points.slice(segmentIndex + 2));\n  return normalizePolyline(detourPoints).points;\n}\n\nfunction buildExtendedLabelDetourPoints(\n  points: Point[],\n  segmentIndex: number,\n  segment: Segment,\n  labelNode: Node,\n  centerAlong: number,\n  detourLineCoord: number,\n  separateEntryAndExit: boolean\n): Point[] | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  const a = points[segmentIndex];\n  const b = points[segmentIndex + 1];\n  // Self-loop terminal segments are short; quarter points keep the entry and exit lanes distinct.\n  const insetDivisor = separateEntryAndExit ? 4 : 2;\n  const axis = detourAxis(segment);\n  const sourceLine = axis.cross(segment.a);\n  const aAlong = axis.along(a);\n  const bAlong = axis.along(b);\n  const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;\n  const detourStart = centerAlong - span / 2;\n  const detourEnd = centerAlong + span / 2;\n  const alongDirection = bAlong >= aAlong ? 1 : -1;\n  const segmentInset = Math.max(\n    0,\n    Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / insetDivisor - LABEL_EPSILON)\n  );\n  const entryAlong = aAlong + alongDirection * segmentInset;\n  const exitAlong = bAlong - alongDirection * segmentInset;\n  const returnLine = detourReturnCoordinate(\n    sourceLine,\n    detourLineCoord,\n    axis.labelCrossSize(labelNode) / 2\n  );\n  return normalizePolyline([\n    ...points.slice(0, segmentIndex),\n    a,\n    axis.point(entryAlong, sourceLine),\n    axis.point(entryAlong, detourLineCoord),\n    axis.point(detourStart, detourLineCoord),\n    axis.point(detourEnd, detourLineCoord),\n    axis.point(detourEnd, returnLine),\n    axis.point(exitAlong, returnLine),\n    axis.point(exitAlong, sourceLine),\n    b,\n    ...points.slice(segmentIndex + 2),\n  ]).points;\n}\n\nfunction externalDetourCenterCandidates(segment: Segment, labelNode: Node): number[] {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return [];\n  }\n\n  if (segment.orientation === 'H') {\n    const minX = Math.min(segment.a.x, segment.b.x);\n    const maxX = Math.max(segment.a.x, segment.b.x);\n    return [minX - labelNode.width / 2 - LABEL_GUTTER, maxX + labelNode.width / 2 + LABEL_GUTTER];\n  }\n\n  const minY = Math.min(segment.a.y, segment.b.y);\n  const maxY = Math.max(segment.a.y, segment.b.y);\n  return [minY - labelNode.height / 2 - LABEL_GUTTER, maxY + labelNode.height / 2 + LABEL_GUTTER];\n}\n\ninterface BlockedIntersectionScore {\n  count: number;\n  length: number;\n}\n\nfunction blockedIntersectionScore(points: readonly Point[], rect: Rect): BlockedIntersectionScore {\n  let count = 0;\n  let length = 0;\n  for (const segment of normalizePolyline([...points]).segments) {\n    if (!segmentIntersectsRectInterior(segment.a, segment.b, rect)) {\n      continue;\n    }\n    count++;\n    if (segment.orientation === 'H') {\n      length += Math.max(\n        0,\n        Math.min(Math.max(segment.a.x, segment.b.x), rect.right) -\n          Math.max(Math.min(segment.a.x, segment.b.x), rect.left)\n      );\n    } else if (segment.orientation === 'V') {\n      length += Math.max(\n        0,\n        Math.min(Math.max(segment.a.y, segment.b.y), rect.bottom) -\n          Math.max(Math.min(segment.a.y, segment.b.y), rect.top)\n      );\n    }\n  }\n  return { count, length };\n}\n\nfunction reducesBlockedIntersections(\n  candidate: readonly Point[],\n  blockedRect: Rect,\n  baseline: BlockedIntersectionScore\n): boolean {\n  const score = blockedIntersectionScore(candidate, blockedRect);\n  return (\n    score.count < baseline.count ||\n    (score.count === baseline.count && score.length < baseline.length - LABEL_EPSILON)\n  );\n}\n\ninterface RerouteLane {\n  key: string;\n  orientation: 'H' | 'V';\n  side: 'top' | 'bottom' | 'left' | 'right';\n}\n\nfunction rerouteLane(\n  points: readonly Point[],\n  blockedRect: Rect,\n  blockingReservations: readonly PlacedLabel[]\n): RerouteLane | null {\n  const segment = normalizePolyline([...points]).segments.find((candidate) =>\n    segmentIntersectsRectInterior(candidate.a, candidate.b, blockedRect)\n  );\n  if (!segment || segment.orientation === 'Z') {\n    return null;\n  }\n\n  const side =\n    segment.orientation === 'H'\n      ? Math.abs(segment.a.y - blockedRect.top) <= Math.abs(blockedRect.bottom - segment.a.y)\n        ? 'top'\n        : 'bottom'\n      : Math.abs(segment.a.x - blockedRect.left) <= Math.abs(blockedRect.right - segment.a.x)\n        ? 'left'\n        : 'right';\n  const reservationIds = blockingReservations\n    .map((reservation) => reservation.edgeId)\n    .sort(compareCodeUnits);\n  return {\n    key: JSON.stringify([reservationIds, segment.orientation, side]),\n    orientation: segment.orientation,\n    side,\n  };\n}\n\nfunction rerouteSegmentAroundRect(\n  edge: Edge,\n  points: Point[],\n  segmentIndex: number,\n  blockedRect: Rect,\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>,\n  lane?: RerouteLane\n): Point[] | null {\n  const normalized = normalizePolyline(points);\n  const baselineScore = blockedIntersectionScore(normalized.points, blockedRect);\n  const segment = normalized.segments[segmentIndex];\n  if (!segment || segment.orientation === 'Z') {\n    return null;\n  }\n\n  const a = normalized.points[segmentIndex];\n  const b = normalized.points[segmentIndex + 1];\n  const ownLabelNodeId = placedLabelsByEdgeId.get(edge.id)?.nodeId;\n  const skipNodeIds = new Set<string>();\n  if (ownLabelNodeId) {\n    skipNodeIds.add(ownLabelNodeId);\n  }\n\n  // One detour may remove only the first intersection with a wide label. Accept strictly\n  // monotonic progress here; the bounded outer loop completes the reroute segment by segment.\n  if (segment.orientation === 'H') {\n    const minX = Math.min(a.x, b.x);\n    const maxX = Math.max(a.x, b.x);\n    const entry = Math.max(minX, blockedRect.left - LABEL_CLEARANCE);\n    const exit = Math.min(maxX, blockedRect.right + LABEL_CLEARANCE);\n    if (exit - entry <= LABEL_EPSILON) {\n      incrementMetric(context.metrics, 'rerouteRejectedDegenerateSpan');\n      return null;\n    }\n\n    for (const y of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {\n      incrementMetric(context.metrics, 'rerouteCandidatesEvaluated');\n      const candidatePoints = normalizePolyline([\n        ...normalized.points.slice(0, segmentIndex),\n        a,\n        { x: entry, y: segment.a.y },\n        { x: entry, y },\n        { x: exit, y },\n        { x: exit, y: segment.a.y },\n        b,\n        ...normalized.points.slice(segmentIndex + 2),\n      ]).points;\n      if (\n        polylineIntersectsRect(candidatePoints, blockedRect) &&\n        !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)\n      ) {\n        incrementMetric(context.metrics, 'rerouteRejectedBlockedRect');\n        continue;\n      }\n      if (polylineIntersectsRect(candidatePoints, blockedRect)) {\n        incrementMetric(context.metrics, 'reroutePartialProgressCandidates');\n      }\n      if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {\n        incrementMetric(context.metrics, 'rerouteRejectedProtectedObstacle');\n        continue;\n      }\n      if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {\n        incrementMetric(context.metrics, 'rerouteRejectedLabelAnchor');\n        continue;\n      }\n      return candidatePoints;\n    }\n    return null;\n  }\n\n  const minY = Math.min(a.y, b.y);\n  const maxY = Math.max(a.y, b.y);\n  const entry = Math.max(minY, blockedRect.top - LABEL_CLEARANCE);\n  const exit = Math.min(maxY, blockedRect.bottom + LABEL_CLEARANCE);\n  if (exit - entry <= LABEL_EPSILON) {\n    incrementMetric(context.metrics, 'rerouteRejectedDegenerateSpan');\n    return null;\n  }\n\n  for (const x of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {\n    incrementMetric(context.metrics, 'rerouteCandidatesEvaluated');\n    const candidatePoints = normalizePolyline([\n      ...normalized.points.slice(0, segmentIndex),\n      a,\n      { x: segment.a.x, y: entry },\n      { x, y: entry },\n      { x, y: exit },\n      { x: segment.a.x, y: exit },\n      b,\n      ...normalized.points.slice(segmentIndex + 2),\n    ]).points;\n    if (\n      polylineIntersectsRect(candidatePoints, blockedRect) &&\n      !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)\n    ) {\n      incrementMetric(context.metrics, 'rerouteRejectedBlockedRect');\n      continue;\n    }\n    if (polylineIntersectsRect(candidatePoints, blockedRect)) {\n      incrementMetric(context.metrics, 'reroutePartialProgressCandidates');\n    }\n    if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {\n      incrementMetric(context.metrics, 'rerouteRejectedProtectedObstacle');\n      continue;\n    }\n    if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {\n      incrementMetric(context.metrics, 'rerouteRejectedLabelAnchor');\n      continue;\n    }\n    return candidatePoints;\n  }\n\n  return null;\n}\n\nfunction rerouteForeignEdgeAroundRect(\n  edge: Edge,\n  blockedRect: Rect,\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>,\n  overrides: EdgePointOverrides,\n  lane?: RerouteLane\n): Point[] | null {\n  let currentPoints = pointsForEdge(edge, overrides, context);\n  for (let attempt = 0; attempt < 8; attempt++) {\n    if (!polylineIntersectsRect(currentPoints, blockedRect)) {\n      return currentPoints;\n    }\n\n    const normalized = normalizePolyline(currentPoints);\n    const segmentIndex = normalized.points.findIndex((point, index) => {\n      if (index === normalized.points.length - 1) {\n        return false;\n      }\n      return segmentIntersectsRectInterior(point, normalized.points[index + 1], blockedRect);\n    });\n    if (segmentIndex < 0) {\n      return currentPoints;\n    }\n\n    const rerouted = rerouteSegmentAroundRect(\n      edge,\n      normalized.points,\n      segmentIndex,\n      blockedRect,\n      context,\n      placedLabelsByEdgeId,\n      lane\n    );\n    if (!rerouted) {\n      return null;\n    }\n    currentPoints = rerouted;\n  }\n\n  return polylineIntersectsRect(currentPoints, blockedRect) ? null : currentPoints;\n}\n\nfunction rerouteForeignEdgeAroundLabels(\n  edge: Edge,\n  reservations: readonly PlacedLabel[],\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>,\n  overrides: EdgePointOverrides\n): Point[] | null {\n  const initialPoints = pointsForEdge(edge, overrides, context);\n  let currentPoints = initialPoints;\n  // A detour around a later label can re-enter an earlier reservation, so make one deterministic\n  // repair pass and one convergence pass before abandoning the edge-level recovery.\n  for (let pass = 0; pass < 2; pass++) {\n    let changed = false;\n    for (const reservation of reservations) {\n      if (!polylineIntersectsRect(currentPoints, reservation.rect)) {\n        continue;\n      }\n      incrementMetric(context.metrics, 'individualLabelRerouteAttempts');\n      overrides.set(edge.id, currentPoints);\n      const rerouted = rerouteForeignEdgeAroundRect(\n        edge,\n        reservation.rect,\n        context,\n        placedLabelsByEdgeId,\n        overrides\n      );\n      if (!rerouted) {\n        overrides.set(edge.id, initialPoints);\n        return null;\n      }\n      incrementMetric(context.metrics, 'individualLabelRerouteSuccesses');\n      currentPoints = rerouted;\n      changed = true;\n    }\n    if (\n      reservations.every((reservation) => !polylineIntersectsRect(currentPoints, reservation.rect))\n    ) {\n      return currentPoints;\n    }\n    if (!changed) {\n      break;\n    }\n  }\n  overrides.set(edge.id, initialPoints);\n  return null;\n}\n\nfunction labelPlacementWithExtendedDetour(\n  edge: Edge,\n  labelNode: Node,\n  segmentCandidate: SegmentCandidate,\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  const basePoints = pointsForEdge(edge, undefined, context);\n  const segment = segmentCandidate.segment;\n\n  for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {\n    const centerCandidates = uniqueSortedCandidates(\n      externalDetourCenterCandidates(segment, labelNode),\n      segment.orientation === 'H'\n        ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2\n        : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2\n    );\n\n    for (const centerAlong of centerCandidates) {\n      const candidatePoints = buildExtendedLabelDetourPoints(\n        basePoints,\n        segmentCandidate.segmentIndex,\n        segment,\n        labelNode,\n        centerAlong,\n        detourLineCoord,\n        edge.start === edge.end\n      );\n      if (!candidatePoints) {\n        continue;\n      }\n\n      if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {\n        continue;\n      }\n\n      if (polylineHitsProtectedObstacles(candidatePoints, context, new Set([labelNode.id]))) {\n        continue;\n      }\n\n      const center =\n        segment.orientation === 'H'\n          ? { x: centerAlong, y: detourLineCoord }\n          : { x: detourLineCoord, y: centerAlong };\n      const rect = labelRectAt(labelNode, center);\n      const overrides: EdgePointOverrides = new Map([[edge.id, candidatePoints]]);\n\n      const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides)\n        .map((edgeId) => context.edgeById.get(edgeId))\n        .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n      let ok = true;\n      for (const foreignEdge of foreignEdges) {\n        const reroutedPoints = rerouteForeignEdgeAroundRect(\n          foreignEdge,\n          rect,\n          context,\n          placedLabelsByEdgeId,\n          overrides\n        );\n        if (!reroutedPoints) {\n          ok = false;\n          break;\n        }\n        overrides.set(foreignEdge.id, reroutedPoints);\n      }\n\n      if (!ok) {\n        continue;\n      }\n      if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n        continue;\n      }\n\n      setEdgePoints(context, edge, candidatePoints);\n      for (const [edgeId, points] of overrides) {\n        if (edgeId === edge.id) {\n          continue;\n        }\n        const foreignEdge = context.edgeById.get(edgeId);\n        if (foreignEdge) {\n          setEdgePoints(context, foreignEdge, points);\n        }\n      }\n      return center;\n    }\n  }\n\n  return null;\n}\n\nfunction labelPlacementWithDetour(\n  edge: Edge,\n  labelNode: Node,\n  segmentCandidate: SegmentCandidate,\n  context: EdgeLabelContext,\n  placedLabelsByEdgeId: Map<string, PlacedLabel>\n): Point | null {\n  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n    return null;\n  }\n\n  const basePoints = pointsForEdge(edge, undefined, context);\n  const segment = segmentCandidate.segment;\n\n  for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {\n    const centerCandidates = detourCenterCandidates(\n      edge,\n      labelNode,\n      segment,\n      detourLineCoord,\n      context\n    );\n    for (const centerAlong of centerCandidates) {\n      const candidatePoints = buildLabelDetourPoints(\n        basePoints,\n        segmentCandidate.segmentIndex,\n        segment,\n        labelNode,\n        centerAlong,\n        detourLineCoord\n      );\n      if (!candidatePoints) {\n        continue;\n      }\n\n      if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {\n        continue;\n      }\n\n      if (polylineHitsProtectedObstacles(candidatePoints, context, new Set([labelNode.id]))) {\n        continue;\n      }\n\n      const center =\n        segment.orientation === 'H'\n          ? { x: centerAlong, y: detourLineCoord }\n          : { x: detourLineCoord, y: centerAlong };\n      const rect = labelRectAt(labelNode, center);\n      const overrides: EdgePointOverrides = new Map([[edge.id, candidatePoints]]);\n\n      const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides)\n        .map((edgeId) => context.edgeById.get(edgeId))\n        .filter((foreignEdge): foreignEdge is Edge => foreignEdge !== undefined);\n\n      let ok = true;\n      for (const foreignEdge of foreignEdges) {\n        const reroutedPoints = rerouteForeignEdgeAroundRect(\n          foreignEdge,\n          rect,\n          context,\n          placedLabelsByEdgeId,\n          overrides\n        );\n        if (!reroutedPoints) {\n          ok = false;\n          break;\n        }\n        overrides.set(foreignEdge.id, reroutedPoints);\n      }\n\n      if (!ok) {\n        continue;\n      }\n      if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {\n        continue;\n      }\n\n      setEdgePoints(context, edge, candidatePoints);\n      for (const [edgeId, points] of overrides) {\n        if (edgeId === edge.id) {\n          continue;\n        }\n        const foreignEdge = context.edgeById.get(edgeId);\n        if (foreignEdge) {\n          setEdgePoints(context, foreignEdge, points);\n        }\n      }\n      return center;\n    }\n  }\n\n  return null;\n}\n\nfunction isPreparedLabelNode(node: Node | undefined): node is NonClusterNode {\n  return Boolean(node && isEdgeLabelNode(node));\n}\n\nfunction parkDegenerateLabel(\n  edge: Edge,\n  labelNode: Node,\n  nodeById: ReadonlyMap<string, Node>\n): void {\n  const routePoint = edge.points?.find(\n    (point) => Number.isFinite(point.x) && Number.isFinite(point.y)\n  );\n  const source = edge.start ? nodeById.get(edge.start) : undefined;\n  const target = edge.end ? nodeById.get(edge.end) : undefined;\n  const fallback =\n    routePoint ?? (source && hasFinitePosition(source) ? source : undefined) ?? target;\n  if (fallback && Number.isFinite(fallback.x) && Number.isFinite(fallback.y)) {\n    labelNode.x = fallback.x;\n    labelNode.y = fallback.y;\n    return;\n  }\n  delete labelNode.x;\n  delete labelNode.y;\n}\n\nfunction placeLabelAtRouteMidpoint(\n  edge: Edge,\n  labelNode: Node,\n  nodeById: ReadonlyMap<string, Node>\n): void {\n  let longestSegment: Segment | undefined;\n  for (const segment of normalizePolyline(edge.points ?? []).segments) {\n    if (segment.orientation === 'Z') {\n      continue;\n    }\n    if (!longestSegment || segmentLength(segment) > segmentLength(longestSegment)) {\n      longestSegment = segment;\n    }\n  }\n  if (!longestSegment) {\n    parkDegenerateLabel(edge, labelNode, nodeById);\n    return;\n  }\n  labelNode.x = (longestSegment.a.x + longestSegment.b.x) / 2;\n  labelNode.y = (longestSegment.a.y + longestSegment.b.y) / 2;\n}\n\nfunction preferredGridLabelNodeId(edge: Edge): string {\n  return `${GRID_LABEL_PREFIX}${edge.start ?? ''}-${edge.end ?? ''}-${edge.id}`;\n}\n\nfunction ensureUniqueGridLabelNodeId(edge: Edge, nodeById: Map<string, Node>): string {\n  const baseId = edge.labelNodeId ?? preferredGridLabelNodeId(edge);\n  let candidateId = baseId;\n  let suffix = 1;\n  while (true) {\n    if (!nodeById.has(candidateId)) {\n      return candidateId;\n    }\n    candidateId = `${baseId}-${suffix}`;\n    suffix += 1;\n  }\n}\n\nexport function prepareGridLayout(data: LayoutData): void {\n  // Labels become measured helper nodes before grid sizing, but remain outside the placement\n  // forest. The original edge text is cleared so the shared renderer does not draw it twice.\n  const nodeById = new Map<string, Node>();\n  for (const node of data.nodes) {\n    nodeById.set(node.id, node);\n  }\n\n  const newNodes: NonClusterNode[] = [];\n  for (const edge of data.edges) {\n    if (!edge.label || edge.label.length === 0) {\n      continue;\n    }\n\n    const sourceNode = edge.start ? nodeById.get(edge.start) : undefined;\n    const existingHelper = edge.labelNodeId ? nodeById.get(edge.labelNodeId) : undefined;\n    if (isPreparedLabelNode(existingHelper)) {\n      existingHelper.label = edge.label;\n      existingHelper.labelStyle = Array.isArray(edge.labelStyle)\n        ? edge.labelStyle[0]\n        : (edge.labelStyle ?? '');\n      existingHelper.edgeStart = edge.start ?? '';\n      existingHelper.edgeEnd = edge.end ?? '';\n      if (sourceNode?.dir) {\n        existingHelper.dir = sourceNode.dir;\n      }\n      edge.label = undefined;\n      (edge as Edge & { text?: string }).text = undefined;\n      continue;\n    }\n\n    const labelNodeId = ensureUniqueGridLabelNodeId(edge, nodeById);\n    const labelNode: NonClusterNode = {\n      id: labelNodeId,\n      label: edge.label,\n      edgeStart: edge.start ?? '',\n      edgeEnd: edge.end ?? '',\n      shape: 'labelRect',\n      width: 0,\n      height: 0,\n      isEdgeLabel: true,\n      isDummy: true,\n      isGroup: false,\n      parentId: undefined,\n      labelStyle: Array.isArray(edge.labelStyle) ? edge.labelStyle[0] : (edge.labelStyle ?? ''),\n      ...(sourceNode?.dir ? { dir: sourceNode.dir } : {}),\n    };\n    newNodes.push(labelNode);\n    nodeById.set(labelNodeId, labelNode);\n    edge.labelNodeId = labelNodeId;\n    edge.label = undefined;\n    (edge as Edge & { text?: string }).text = undefined;\n  }\n\n  data.nodes.push(...newNodes);\n}\n\nexport function positionGridEdgeLabels(\n  data: LayoutData,\n  instrumentation?: GridEdgeLabelInstrumentation,\n  routingInstrumentation?: GridRoutingInstrumentation,\n  options: GridEdgeLabelOptions = {}\n): void {\n  const nodeById = new Map<string, Node>();\n  for (const node of data.nodes) {\n    nodeById.set(node.id, node);\n  }\n  // Coordinates belong to the previous invocation. Retain them only for rollback; the current\n  // placement pass must build its obstacle index from labels placed during this invocation.\n  const labelNodes = data.nodes.filter(isEdgeLabelNode);\n  const baseLabelPositions = new Map<string, { x?: number; y?: number }>(\n    labelNodes.map((labelNode) => [labelNode.id, { x: labelNode.x, y: labelNode.y }])\n  );\n  for (const labelNode of labelNodes) {\n    delete labelNode.x;\n    delete labelNode.y;\n  }\n\n  const preparedLabels = data.edges\n    .map((edge, sourceIndex) => {\n      if (!edge.labelNodeId) {\n        return null;\n      }\n      const labelNode = nodeById.get(edge.labelNodeId);\n      if (!labelNode) {\n        return null;\n      }\n      if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {\n        incrementMetric(instrumentation, 'unmeasuredLabelsSkipped');\n        return null;\n      }\n      return { edge, labelNode, sourceIndex };\n    })\n    .filter((entry): entry is LabelWorkItem => entry !== null);\n\n  if (preparedLabels.length === 0) {\n    return;\n  }\n\n  // Keep the routed geometry for midpoint degradation and the full snapshot for error rollback.\n  const baseEdgePoints = new Map<string, Point[] | undefined>(\n    data.edges.map((edge) => [edge.id, edge.points?.map((point) => ({ ...point }))])\n  );\n\n  const restoreBaseEdgePoints = (): void => {\n    for (const edge of data.edges) {\n      const points = baseEdgePoints.get(edge.id);\n      if (points) {\n        edge.points = points.map((point) => ({ ...point }));\n      } else {\n        delete edge.points;\n      }\n    }\n  };\n\n  const restoreBaseState = (): void => {\n    restoreBaseEdgePoints();\n    for (const labelNode of labelNodes) {\n      const position = baseLabelPositions.get(labelNode.id);\n      if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) {\n        labelNode.x = position.x;\n        labelNode.y = position.y;\n      } else {\n        delete labelNode.x;\n        delete labelNode.y;\n      }\n    }\n  };\n\n  const workItems = preparedLabels\n    .filter(({ edge, labelNode }) => {\n      if (normalizePolyline(edge.points ?? []).segments.length > 0) {\n        return true;\n      }\n      parkDegenerateLabel(edge, labelNode, nodeById);\n      incrementMetric(instrumentation, 'degenerateLabelRoutesSkipped');\n      return false;\n    })\n    .sort((a, b) => a.sourceIndex - b.sourceIndex || compareCodeUnits(a.edge.id, b.edge.id));\n  if (workItems.length === 0) {\n    return;\n  }\n  const placeLabelsAtRouteMidpoints = (): void => {\n    restoreBaseEdgePoints();\n    for (const { edge, labelNode } of workItems) {\n      placeLabelAtRouteMidpoint(edge, labelNode, nodeById);\n    }\n  };\n\n  const configuredIndexWork = options.maxIndexWork ?? DEFAULT_MAX_INDEX_WORK;\n  const indexWorkLimit =\n    Number.isFinite(configuredIndexWork) && configuredIndexWork >= 0\n      ? Math.floor(configuredIndexWork)\n      : DEFAULT_MAX_INDEX_WORK;\n  const indexWorkBudget = new LabelIndexWorkBudget(indexWorkLimit, instrumentation);\n  const placementFailures: LabelPlacementSearchExhaustedError[] = [];\n  for (let pass = 1; pass <= 2; pass++) {\n    // Pass 1 prefers existing segments and foreign-edge reroutes. Pass 2 additionally permits\n    // owner-edge detours, rebuilding every route from the original routing result.\n    incrementMetric(instrumentation, 'labelPasses');\n    const context = createEdgeLabelContext(data, indexWorkBudget, instrumentation);\n    const placedLabelsByEdgeId = new Map<string, PlacedLabel>();\n    const allowedOverlapsByLabelEdgeId = new Map<string, Set<string>>();\n    const passStartPoints = new Map(\n      data.edges.map((edge) => [edge.id, pointsForEdge(edge, undefined, context).map(clonePoint)])\n    );\n    const proposedOwnerRoutes = new Map<string, Point[]>();\n    try {\n      for (const { edge, labelNode } of workItems) {\n        const segments = [...candidateSegments(edge, context)].sort((a, b) => {\n          const lengthDelta = segmentLength(b.segment) - segmentLength(a.segment);\n          if (Math.abs(lengthDelta) > LABEL_EPSILON) {\n            return lengthDelta;\n          }\n          return a.order - b.order;\n        });\n\n        let labelCenter: Point | null = null;\n        for (const segmentCandidate of segments) {\n          labelCenter = placementOnExistingSegment(\n            edge,\n            labelNode,\n            segmentCandidate.segment,\n            context\n          );\n          if (labelCenter) {\n            break;\n          }\n        }\n\n        if (!labelCenter) {\n          for (const segmentCandidate of segments) {\n            labelCenter = placementOnExistingSegmentWithReroutes(\n              edge,\n              labelNode,\n              segmentCandidate.segment,\n              context,\n              placedLabelsByEdgeId\n            );\n            if (labelCenter) {\n              break;\n            }\n          }\n        }\n\n        if (pass === 2 && !labelCenter) {\n          for (const segmentCandidate of segments) {\n            labelCenter = labelPlacementWithDetour(\n              edge,\n              labelNode,\n              segmentCandidate,\n              context,\n              placedLabelsByEdgeId\n            );\n            if (labelCenter) {\n              break;\n            }\n          }\n        }\n\n        if (pass === 2 && !labelCenter) {\n          for (const segmentCandidate of segments) {\n            labelCenter = labelPlacementWithExtendedDetour(\n              edge,\n              labelNode,\n              segmentCandidate,\n              context,\n              placedLabelsByEdgeId\n            );\n            if (labelCenter) {\n              break;\n            }\n          }\n        }\n\n        if (!labelCenter) {\n          throw new LabelPlacementSearchExhaustedError({\n            edgeId: edge.id,\n            labelNodeId: labelNode.id,\n            labelWidth: labelNode.width,\n            labelHeight: labelNode.height,\n            pointCount: edge.points?.length ?? 0,\n            points: edge.points?.map((point) => ({ ...point })) ?? [],\n            segments: segments.map(({ segment }) => ({\n              orientation: segment.orientation,\n              length: segmentLength(segment),\n              a: { ...segment.a },\n              b: { ...segment.b },\n            })),\n          });\n        }\n\n        labelNode.x = labelCenter.x;\n        labelNode.y = labelCenter.y;\n        const placedLabel: PlacedLabel = {\n          edgeId: edge.id,\n          nodeId: labelNode.id,\n          center: labelCenter,\n          rect: labelRectAt(labelNode, labelCenter),\n        };\n        placedLabelsByEdgeId.set(edge.id, placedLabel);\n        upsertPlacedLabelObstacle(context, placedLabel);\n      }\n\n      // Once every label has a provisional home, freeze the complete reservation set before\n      // rerouting. This prevents result order from changing which labels an edge must avoid.\n      const frozenLabels = [...placedLabelsByEdgeId.values()];\n      incrementMetric(instrumentation, 'frozenReservations', frozenLabels.length);\n      if (routingInstrumentation) {\n        routingInstrumentation.labelOverlayBuilds++;\n        routingInstrumentation.labelOverlayVertices += frozenLabels.length * 4;\n      }\n\n      // The placement search is provisional: capture its route proposals, roll\n      // the routes back to the pass boundary, and only then commit each\n      // impacted edge once against the complete frozen reservation set.\n      for (const edge of data.edges) {\n        const passStart = passStartPoints.get(edge.id) ?? [];\n        const proposed = pointsForEdge(edge, undefined, context);\n        if (JSON.stringify(proposed) !== JSON.stringify(passStart)) {\n          proposedOwnerRoutes.set(edge.id, proposed.map(clonePoint));\n        }\n        setEdgePoints(context, edge, passStart.map(clonePoint));\n      }\n      for (const [edgeId, points] of proposedOwnerRoutes) {\n        if (!placedLabelsByEdgeId.has(edgeId)) {\n          continue;\n        }\n        const owner = context.edgeById.get(edgeId);\n        if (owner) {\n          setEdgePoints(context, owner, points);\n        }\n      }\n\n      const impacted = new Set<string>(proposedOwnerRoutes.keys());\n      for (const edge of data.edges) {\n        const ownLabel = placedLabelsByEdgeId.get(edge.id);\n        const points = pointsForEdge(edge, undefined, context);\n        for (const reservation of frozenLabels) {\n          if (reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)) {\n            impacted.add(edge.id);\n          }\n        }\n        if (ownLabel && !labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {\n          impacted.add(edge.id);\n        }\n      }\n\n      const rerouteLaneOrdinals = new Map<string, number>();\n      for (const edge of data.edges) {\n        if (!impacted.has(edge.id)) {\n          continue;\n        }\n        let points = pointsForEdge(edge, undefined, context);\n        const overrides: EdgePointOverrides = new Map([[edge.id, points]]);\n        const blockingReservations = frozenLabels.filter(\n          (reservation) =>\n            reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)\n        );\n        if (blockingReservations.length > 0) {\n          const combinedRect = blockingReservations.slice(1).reduce<Rect>(\n            (combined, reservation) => ({\n              cx:\n                (Math.min(combined.left, reservation.rect.left) +\n                  Math.max(combined.right, reservation.rect.right)) /\n                2,\n              cy:\n                (Math.min(combined.top, reservation.rect.top) +\n                  Math.max(combined.bottom, reservation.rect.bottom)) /\n                2,\n              left: Math.min(combined.left, reservation.rect.left),\n              right: Math.max(combined.right, reservation.rect.right),\n              top: Math.min(combined.top, reservation.rect.top),\n              bottom: Math.max(combined.bottom, reservation.rect.bottom),\n            }),\n            { ...blockingReservations[0].rect }\n          );\n          const lane = rerouteLane(points, combinedRect, blockingReservations);\n          const rerouteOrdinal = lane ? (rerouteLaneOrdinals.get(lane.key) ?? 0) : 0;\n          // Leave one full separation lane beyond the 6 px label clearance;\n          // only routes avoiding the same reservation set on the same side share an ordinal.\n          const lanePadding = (rerouteOrdinal + 2) * 12;\n          const blockedRect: Rect = {\n            cx: combinedRect.cx,\n            cy: combinedRect.cy,\n            left: combinedRect.left - lanePadding,\n            right: combinedRect.right + lanePadding,\n            top: combinedRect.top - lanePadding,\n            bottom: combinedRect.bottom + lanePadding,\n          };\n          let rerouted = rerouteForeignEdgeAroundRect(\n            edge,\n            blockedRect,\n            context,\n            placedLabelsByEdgeId,\n            overrides,\n            lane ?? undefined\n          );\n          const usedScopedLane = rerouted !== null;\n          rerouted ??= rerouteForeignEdgeAroundLabels(\n            edge,\n            blockingReservations,\n            context,\n            placedLabelsByEdgeId,\n            overrides\n          );\n          if (rerouted) {\n            points = rerouted;\n            overrides.set(edge.id, points);\n            if (lane && usedScopedLane) {\n              rerouteLaneOrdinals.set(lane.key, rerouteOrdinal + 1);\n            }\n          } else {\n            // Preserving a valid edge and anchored labels is safer than failing the whole layout.\n            // Record the unavoidable overlap so final validation permits only this edge-label pair.\n            incrementMetric(instrumentation, 'labelOverlapFallbacks');\n            for (const reservation of blockingReservations) {\n              if (!polylineIntersectsRect(points, reservation.rect)) {\n                continue;\n              }\n              const allowedEdges =\n                allowedOverlapsByLabelEdgeId.get(reservation.edgeId) ?? new Set<string>();\n              if (!allowedEdges.has(edge.id)) {\n                incrementMetric(instrumentation, 'labelOverlapReservations');\n              }\n              allowedEdges.add(edge.id);\n              allowedOverlapsByLabelEdgeId.set(reservation.edgeId, allowedEdges);\n            }\n          }\n        }\n        if (!labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {\n          throw gridError('GRID_ROUTE_NOT_FOUND', `Label anchor was lost for edge \"${edge.id}\"`, {\n            edgeId: edge.id,\n            pass,\n          });\n        }\n        if (placedLabelsByEdgeId.has(edge.id)) {\n          incrementMetric(instrumentation, 'preservedAnchors');\n        }\n        setEdgePoints(context, edge, points);\n        incrementMetric(instrumentation, 'impactedEdgeReroutes');\n      }\n      for (const { edge, labelNode } of workItems) {\n        const reservation = placedLabelsByEdgeId.get(edge.id);\n        if (\n          !reservation ||\n          !labelStillAnchored(\n            edge.id,\n            pointsForEdge(edge, undefined, context),\n            placedLabelsByEdgeId\n          ) ||\n          !rectSafeForLabel(\n            reservation.rect,\n            edge,\n            labelNode.id,\n            context,\n            undefined,\n            allowedOverlapsByLabelEdgeId.get(edge.id)\n          )\n        ) {\n          throw gridError('GRID_ROUTE_NOT_FOUND', `Label pass ${pass} did not validate`, {\n            edgeId: edge.id,\n            pass,\n          });\n        }\n      }\n      return;\n    } catch (error) {\n      if (error instanceof LabelIndexWorkLimitError) {\n        placeLabelsAtRouteMidpoints();\n        incrementMetric(instrumentation, 'indexWorkLimitFallbacks');\n        if (routingInstrumentation) {\n          routingInstrumentation.resourceLimitFallbacks++;\n          routingInstrumentation.fallbackReasons.label_index_work_cap++;\n        }\n        return;\n      }\n      if (!(error instanceof LabelPlacementSearchExhaustedError)) {\n        restoreBaseState();\n        incrementMetric(instrumentation, 'rollbacks');\n        throw error;\n      }\n      placementFailures.push(error);\n      // A failed pass may contain detours around provisional label positions. Restore routing\n      // before retrying so the next pass depends only on the labels it successfully places.\n      restoreBaseEdgePoints();\n      for (const { labelNode } of workItems) {\n        delete labelNode.x;\n        delete labelNode.y;\n      }\n    }\n  }\n\n  placeLabelsAtRouteMidpoints();\n  incrementMetric(instrumentation, 'placementSearchFallbacks');\n  if (routingInstrumentation) {\n    routingInstrumentation.fallbackReasons.label_placement_exhausted++;\n  }\n  log.warn(\n    '[grid]',\n    'Label placement search exhausted; using route midpoints. Labels may overlap.',\n    {\n      reason: 'label_placement_exhausted',\n      edgeIds: workItems.map(({ edge }) => edge.id),\n      failures: placementFailures.map(({ details }) => details),\n    }\n  );\n}\n", "import type { Node } from '../../types.js';\nimport {\n  ROOT_CONTAINER_ID,\n  type GridContainerId,\n  type GridForest,\n  gridError,\n  isEdgeLabelNode,\n} from './types.js';\n\n/*\n * Builds the containment model used by every later grid-layout phase.\n *\n * The returned forest excludes synthetic edge-label nodes from the geometry hierarchy, validates\n * every parent reference, and orders groups children-first so nested containers can be measured\n * before their parents.\n */\nfunction asGroup(node: Node): (Node & { isGroup: true }) | undefined {\n  return node.isGroup ? (node as Node & { isGroup: true }) : undefined;\n}\n\nexport function buildGridForest(nodes: Node[]): GridForest {\n  const nodeById = new Map<string, Node>();\n  const groupById = new Map<string, Node & { isGroup: true }>();\n  const helperNodeIds = new Set<string>();\n\n  for (const node of nodes) {\n    if (node.id === ROOT_CONTAINER_ID) {\n      throw gridError(\n        'GRID_INVALID_CONTAINMENT',\n        `Node id \"${ROOT_CONTAINER_ID}\" is reserved for the grid layout root`,\n        { traversedIds: [node.id] }\n      );\n    }\n    if (nodeById.has(node.id)) {\n      throw gridError('GRID_INVALID_CONTAINMENT', `Duplicate node id \"${node.id}\"`, {\n        traversedIds: [node.id],\n      });\n    }\n    nodeById.set(node.id, node);\n    if (isEdgeLabelNode(node)) {\n      helperNodeIds.add(node.id);\n      continue;\n    }\n    const group = asGroup(node);\n    if (group) {\n      groupById.set(group.id, group);\n    }\n  }\n\n  const childrenByParent = new Map<GridContainerId, Node[]>();\n  childrenByParent.set(ROOT_CONTAINER_ID, []);\n\n  for (const node of nodes) {\n    if (helperNodeIds.has(node.id)) {\n      continue;\n    }\n    const parentId = node.parentId ?? ROOT_CONTAINER_ID;\n    if (parentId !== ROOT_CONTAINER_ID) {\n      const parent = groupById.get(parentId);\n      if (!parent) {\n        throw gridError(\n          'GRID_INVALID_CONTAINMENT',\n          `Missing parent \"${parentId}\" for \"${node.id}\"`,\n          {\n            traversedIds: [node.id, parentId],\n          }\n        );\n      }\n    }\n    if (!childrenByParent.has(parentId)) {\n      childrenByParent.set(parentId, []);\n    }\n    childrenByParent.get(parentId)!.push(node);\n  }\n\n  const state = new Map<string, 0 | 1 | 2>();\n  const postOrderGroups: (Node & { isGroup: true })[] = [];\n\n  // Use an explicit stack rather than recursion so deeply nested diagrams do not consume the\n  // JavaScript call stack. State 1 means \"on the active path\"; encountering it again is a cycle.\n  interface VisitFrame {\n    groupId: string;\n    childGroups: (Node & { isGroup: true })[];\n    nextChildIndex: number;\n  }\n\n  const directChildGroups = (groupId: string): (Node & { isGroup: true })[] =>\n    (childrenByParent.get(groupId) ?? [])\n      .map((child) => asGroup(child))\n      .filter((group): group is Node & { isGroup: true } => group !== undefined);\n\n  const visit = (startGroupId: string): void => {\n    const currentState = state.get(startGroupId) ?? 0;\n    if (currentState === 1) {\n      throw gridError('GRID_INVALID_CONTAINMENT', `Containment cycle at \"${startGroupId}\"`, {\n        traversedIds: [startGroupId],\n      });\n    }\n    if (currentState === 2) {\n      return;\n    }\n\n    state.set(startGroupId, 1);\n    const stack: VisitFrame[] = [\n      {\n        groupId: startGroupId,\n        childGroups: directChildGroups(startGroupId),\n        nextChildIndex: 0,\n      },\n    ];\n\n    while (stack.length > 0) {\n      const frame = stack[stack.length - 1];\n      const child = frame.childGroups[frame.nextChildIndex];\n\n      if (child) {\n        frame.nextChildIndex += 1;\n        const childState = state.get(child.id) ?? 0;\n        if (childState === 1) {\n          throw gridError('GRID_INVALID_CONTAINMENT', `Containment cycle at \"${child.id}\"`, {\n            traversedIds: [...stack.map((item) => item.groupId), child.id],\n          });\n        }\n        if (childState === 2) {\n          continue;\n        }\n\n        state.set(child.id, 1);\n        stack.push({\n          groupId: child.id,\n          childGroups: directChildGroups(child.id),\n          nextChildIndex: 0,\n        });\n        continue;\n      }\n\n      stack.pop();\n      state.set(frame.groupId, 2);\n      const group = groupById.get(frame.groupId);\n      if (group) {\n        postOrderGroups.push(group);\n      }\n    }\n  };\n\n  for (const rootChild of childrenByParent.get(ROOT_CONTAINER_ID) ?? []) {\n    const group = asGroup(rootChild);\n    if (group) {\n      visit(group.id);\n    }\n  }\n\n  // Normally every group is reached from a root child. This second pass also validates malformed\n  // disconnected components and produces a useful cycle error instead of silently dropping them.\n  for (const groupId of groupById.keys()) {\n    if ((state.get(groupId) ?? 0) === 0) {\n      visit(groupId);\n    }\n  }\n\n  return {\n    nodeById,\n    groupById,\n    childrenByParent,\n    rootChildren: childrenByParent.get(ROOT_CONTAINER_ID) ?? [],\n    postOrderGroups,\n    helperNodeIds,\n  };\n}\n\nexport function isAncestorGroup(\n  ancestorId: string,\n  node: Node | undefined,\n  nodeById: Map<string, Node>\n): boolean {\n  let current = node;\n  const seen = new Set<string>();\n  // The forest builder already rejects cycles. The guard keeps this predicate safe when callers\n  // provide a partially constructed or independently sourced node map.\n  while (current?.parentId) {\n    if (current.parentId === ancestorId) {\n      return true;\n    }\n    if (seen.has(current.parentId)) {\n      return false;\n    }\n    seen.add(current.parentId);\n    current = nodeById.get(current.parentId);\n  }\n  return false;\n}\n", "import type { Edge, LayoutData, Node } from '../../types.js';\nimport { gridLabelSpanRequirement, type GridLabelSpanRequirement } from './labelGeometry.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n  GridCellStack,\n  GridContainerId,\n  GridForest,\n  GridOrientation,\n  GridResolvedPlacement,\n} from './types.js';\nimport { ROOT_CONTAINER_ID } from './types.js';\n\ninterface GridLabelledEdge {\n  edge: Edge;\n  labelNode: Node;\n}\n\nexport interface GridLabelRequirements {\n  byContainer: Map<GridContainerId, GridLabelledEdge[]>;\n  selfLoops: Map<string, GridLabelSpanRequirement>;\n}\n\nexport interface GridContainerLabelGaps {\n  rowGapAfter: Map<number, number>;\n  columnGapAfter: Map<number, number>;\n}\n\nexport function buildGridLabelRequirements(\n  data: LayoutData,\n  forest: GridForest,\n  metrics?: GridRoutingInstrumentation\n): GridLabelRequirements {\n  const byContainer = new Map<GridContainerId, GridLabelledEdge[]>();\n  const selfLoops = new Map<string, GridLabelSpanRequirement>();\n\n  for (const edge of data.edges) {\n    if (!edge.start || !edge.end || !edge.labelNodeId) {\n      continue;\n    }\n    if (metrics) {\n      metrics.labelSpacingEdgesExamined++;\n    }\n    const labelNode = forest.nodeById.get(edge.labelNodeId);\n    const source = forest.nodeById.get(edge.start);\n    const target = forest.nodeById.get(edge.end);\n    if (!labelNode || !source || !target) {\n      continue;\n    }\n    if (edge.start === edge.end) {\n      const horizontal = gridLabelSpanRequirement(labelNode, 'H');\n      if (horizontal) {\n        selfLoops.set(edge.id, horizontal);\n      }\n      continue;\n    }\n    const sourceContainer = source.parentId ?? ROOT_CONTAINER_ID;\n    const targetContainer = target.parentId ?? ROOT_CONTAINER_ID;\n    if (sourceContainer !== targetContainer) {\n      continue;\n    }\n    const entries = byContainer.get(sourceContainer);\n    if (entries) {\n      entries.push({ edge, labelNode });\n    } else {\n      byContainer.set(sourceContainer, [{ edge, labelNode }]);\n    }\n  }\n\n  return { byContainer, selfLoops };\n}\n\nfunction trackOrigins(\n  tracks: readonly number[],\n  sizes: ReadonlyMap<number, number>,\n  gap: number\n): Map<number, number> {\n  const origins = new Map<number, number>();\n  let cursor = 0;\n  for (const track of tracks) {\n    origins.set(track, cursor);\n    cursor += (sizes.get(track) ?? 0) + gap;\n  }\n  return origins;\n}\n\nfunction crossAxisFits(\n  track: number,\n  crossSize: number,\n  tracks: readonly number[],\n  sizes: ReadonlyMap<number, number>,\n  gap: number\n): boolean {\n  const origins = trackOrigins(tracks, sizes, gap);\n  const origin = origins.get(track);\n  const size = sizes.get(track);\n  if (origin === undefined || size === undefined) {\n    return false;\n  }\n  const center = origin + size / 2;\n  const low = center - crossSize / 2;\n  const high = center + crossSize / 2;\n  return tracks.every((other) => {\n    if (other === track) {\n      return true;\n    }\n    const otherOrigin = origins.get(other)!;\n    const otherEnd = otherOrigin + (sizes.get(other) ?? 0);\n    return high <= otherOrigin || low >= otherEnd;\n  });\n}\n\nfunction placementByNodeId(cells: ReadonlyMap<string, GridCellStack>) {\n  const placements = new Map<string, GridResolvedPlacement>();\n  for (const cell of cells.values()) {\n    for (const placement of cell.items) {\n      placements.set(placement.item.id, placement);\n    }\n  }\n  return placements;\n}\n\nfunction areConsecutive(first: number, second: number, tracks: readonly number[]): boolean {\n  const low = Math.min(first, second);\n  const high = Math.max(first, second);\n  const index = tracks.indexOf(low);\n  return index >= 0 && tracks[index + 1] === high;\n}\n\nfunction addGapRequirement(gaps: Map<number, number>, track: number, required: number): void {\n  gaps.set(track, Math.max(gaps.get(track) ?? 0, required));\n}\n\nexport function deriveGridContainerLabelGaps(\n  entries: readonly GridLabelledEdge[],\n  cells: ReadonlyMap<string, GridCellStack>,\n  rowHeights: ReadonlyMap<number, number>,\n  columnWidths: ReadonlyMap<number, number>,\n  sortedRows: readonly number[],\n  sortedColumns: readonly number[],\n  configuredRowGap: number,\n  configuredColumnGap: number,\n  metrics?: GridRoutingInstrumentation\n): GridContainerLabelGaps {\n  const rowGapAfter = new Map<number, number>();\n  const columnGapAfter = new Map<number, number>();\n  const placements = placementByNodeId(cells);\n\n  const requirementFor = (\n    entry: GridLabelledEdge,\n    orientation: GridOrientation\n  ): GridLabelSpanRequirement | null => gridLabelSpanRequirement(entry.labelNode, orientation);\n\n  for (const entry of entries) {\n    const source = entry.edge.start ? placements.get(entry.edge.start) : undefined;\n    const target = entry.edge.end ? placements.get(entry.edge.end) : undefined;\n    if (!source || !target) {\n      continue;\n    }\n    if (source.row === target.row && areConsecutive(source.column, target.column, sortedColumns)) {\n      const requirement = requirementFor(entry, 'H');\n      if (\n        requirement &&\n        crossAxisFits(source.row, requirement.cross, sortedRows, rowHeights, configuredRowGap)\n      ) {\n        if (metrics) {\n          metrics.labelSpacingEligibleEdges++;\n        }\n        addGapRequirement(\n          columnGapAfter,\n          Math.min(source.column, target.column),\n          requirement.requiredAlongSpan\n        );\n      }\n      continue;\n    }\n    if (source.column === target.column && areConsecutive(source.row, target.row, sortedRows)) {\n      const requirement = requirementFor(entry, 'V');\n      if (\n        requirement &&\n        crossAxisFits(\n          source.column,\n          requirement.cross,\n          sortedColumns,\n          columnWidths,\n          configuredColumnGap\n        )\n      ) {\n        if (metrics) {\n          metrics.labelSpacingEligibleEdges++;\n        }\n        addGapRequirement(\n          rowGapAfter,\n          Math.min(source.row, target.row),\n          requirement.requiredAlongSpan\n        );\n      }\n    }\n  }\n\n  return { rowGapAfter, columnGapAfter };\n}\n", "import { log } from '../../../logger.js';\nimport type { GridPlacement } from '../../../types.js';\nimport {\n  isGridHorizontalAlign,\n  isGridVerticalAlign,\n  validateGridCoordinate,\n} from '../../../utils/gridPlacement.js';\nimport { resolveEdgeCornerRadius } from '../../edgeCornerRadius.js';\nimport type { Node } from '../../types.js';\nimport { compareCodeUnits } from '../layout-utils/helpers.js';\nimport {\n  GRID_DEFAULTS,\n  type GridCurve,\n  type GridLayoutConfigNormalized,\n  type GridResolvedPlacement,\n  type GridLayoutData,\n  gridError,\n  type GridCellStack,\n} from './types.js';\n\n/*\n * Normalizes placement input and deterministically assigns each direct child of a container to a\n * grid cell. Placement metadata on a node takes precedence over the container-level placement map.\n */\nconst GRID_LOG_PREFIX = '[grid]';\n// Grid accepts the same named curves as the shared edge renderer; rejecting unknown values here\n// keeps layout metadata serializable and leaves renderer fallback behavior unambiguous.\nconst GRID_CURVES = new Set<GridCurve>([\n  'basis',\n  'bumpX',\n  'bumpY',\n  'cardinal',\n  'catmullRom',\n  'linear',\n  'monotoneX',\n  'monotoneY',\n  'natural',\n  'step',\n  'stepAfter',\n  'stepBefore',\n  'rounded',\n]);\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction ownPlacementFrom(value: unknown): Partial<GridPlacement> {\n  if (!isObjectRecord(value)) {\n    return {};\n  }\n  const placement: Partial<GridPlacement> = {};\n  if (Object.hasOwn(value, 'row')) {\n    placement.row = value.row as number | undefined;\n  }\n  if (Object.hasOwn(value, 'column')) {\n    placement.column = value.column as number | undefined;\n  }\n  if (isGridHorizontalAlign(value.horizontalAlign)) {\n    placement.horizontalAlign = value.horizontalAlign;\n  }\n  if (isGridVerticalAlign(value.verticalAlign)) {\n    placement.verticalAlign = value.verticalAlign;\n  }\n  return placement;\n}\n\nexport function buildGridSourceOrder(nodes: Node[]): Map<string, number> {\n  const order = new Map<string, number>();\n  let index = 0;\n  for (const node of nodes) {\n    if (!order.has(node.id)) {\n      order.set(node.id, index++);\n    }\n  }\n  return order;\n}\n\n/**\n * Normalizes public grid options, applying defaults to unsupported spacing and rendering values.\n * Placement objects become occurrence arrays; authored coordinates remain unchanged so\n * placement resolution can reject invalid values rather than silently moving nodes.\n */\nexport function readGridConfig(data: GridLayoutData): GridLayoutConfigNormalized {\n  const raw = isObjectRecord(data.config?.grid) ? data.config.grid : {};\n  const placementsRaw = isObjectRecord(raw.placements) ? raw.placements : {};\n  const placements = new Map<string, GridPlacement[]>();\n  for (const key of Object.keys(placementsRaw)) {\n    const value = placementsRaw[key];\n    const occurrencePlacements = Array.isArray(value) ? value : [value];\n    placements.set(\n      key,\n      occurrencePlacements.map((placement) => ownPlacementFrom(placement))\n    );\n  }\n\n  return {\n    placements,\n    columns:\n      typeof raw.columns === 'number' && Number.isFinite(raw.columns) && raw.columns >= 0\n        ? Math.trunc(raw.columns)\n        : GRID_DEFAULTS.columns,\n    rowGap:\n      typeof raw.rowGap === 'number' && Number.isFinite(raw.rowGap) && raw.rowGap >= 0\n        ? raw.rowGap\n        : GRID_DEFAULTS.rowGap,\n    columnGap:\n      typeof raw.columnGap === 'number' && Number.isFinite(raw.columnGap) && raw.columnGap >= 0\n        ? raw.columnGap\n        : GRID_DEFAULTS.columnGap,\n    cellGap:\n      typeof raw.cellGap === 'number' && Number.isFinite(raw.cellGap) && raw.cellGap >= 0\n        ? raw.cellGap\n        : GRID_DEFAULTS.cellGap,\n    containerPadding:\n      typeof raw.containerPadding === 'number' &&\n      Number.isFinite(raw.containerPadding) &&\n      raw.containerPadding >= 0\n        ? raw.containerPadding\n        : GRID_DEFAULTS.containerPadding,\n    titleGap:\n      typeof raw.titleGap === 'number' && Number.isFinite(raw.titleGap) && raw.titleGap >= 0\n        ? raw.titleGap\n        : GRID_DEFAULTS.titleGap,\n    horizontalAlign: isGridHorizontalAlign(raw.horizontalAlign)\n      ? raw.horizontalAlign\n      : GRID_DEFAULTS.horizontalAlign,\n    verticalAlign: isGridVerticalAlign(raw.verticalAlign)\n      ? raw.verticalAlign\n      : GRID_DEFAULTS.verticalAlign,\n    // Normalize rendering options with placement so every routed edge receives one stable style.\n    curve:\n      typeof raw.curve === 'string' && GRID_CURVES.has(raw.curve as GridCurve)\n        ? (raw.curve as GridCurve)\n        : GRID_DEFAULTS.curve,\n    edgeCornerRadius: resolveEdgeCornerRadius(raw.edgeCornerRadius),\n  };\n}\n\n/**\n * Warns about unknown placement targets and entries exceeding the number of matching nodes.\n * Matches authored placement IDs when available, otherwise emitted IDs; does not mutate the map.\n */\nexport function validateGridPlacementMap(\n  items: Iterable<Node>,\n  config: GridLayoutConfigNormalized\n): void {\n  // Diagram adapters may retain a generated rendering ID while exposing the authored ID expected\n  // by public placement maps. Fall back to `id` for diagrams whose IDs are already author-stable.\n  const knownIdCounts = new Map<string, number>();\n  for (const item of items) {\n    const placementId = item.placementId ?? item.id;\n    knownIdCounts.set(placementId, (knownIdCounts.get(placementId) ?? 0) + 1);\n  }\n  for (const [key, placements] of config.placements) {\n    const matchingItems = knownIdCounts.get(key) ?? 0;\n    if (matchingItems === 0) {\n      log.warn(GRID_LOG_PREFIX, `Ignoring grid placement for unknown target \"${key}\"`);\n      continue;\n    }\n    if (placements.length > matchingItems) {\n      log.warn(\n        GRID_LOG_PREFIX,\n        `Ignoring ${placements.length - matchingItems} extra grid placement occurrence(s) for target \"${key}\"; found ${matchingItems} matching node(s)`\n      );\n    }\n  }\n}\n\nfunction itemComparator(sourceOrder: Map<string, number>) {\n  return (a: Node, b: Node): number => {\n    const aOrder = sourceOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;\n    const bOrder = sourceOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;\n    if (aOrder !== bOrder) {\n      return aOrder - bOrder;\n    }\n    return compareCodeUnits(a.id, b.id);\n  };\n}\n\n/**\n * Resolves one authored-ID occurrence, with inline metadata overriding placement-map fields.\n * Validates coordinates before supplying placeholders for axes left to automatic placement.\n */\nfunction resolveItemPlacement(\n  item: Node,\n  sourceOrder: Map<string, number>,\n  config: GridLayoutConfigNormalized,\n  occurrenceIndex: number\n): GridResolvedPlacement {\n  // Resolve configuration through the authored identity while retaining the generated rendering\n  // identity for deterministic ordering and diagnostic context.\n  const authoredPlacementId = item.placementId ?? item.id;\n  const configPlacement = config.placements.get(authoredPlacementId)?.[occurrenceIndex] ?? {};\n  const metadataPlacement = ownPlacementFrom(item.metadata);\n\n  // Node metadata is closest to the authored node, so it deliberately wins over the shared map.\n  // Log disagreements to make an otherwise valid but surprising layout diagnosable.\n  for (const field of ['row', 'column', 'horizontalAlign', 'verticalAlign'] as const) {\n    if (\n      Object.hasOwn(configPlacement, field) &&\n      Object.hasOwn(metadataPlacement, field) &&\n      configPlacement[field] !== metadataPlacement[field]\n    ) {\n      log.debug(GRID_LOG_PREFIX, 'metadata overrides placement map', {\n        nodeId: item.id,\n        field,\n        metadata: metadataPlacement[field],\n        config: configPlacement[field],\n      });\n    }\n  }\n\n  const row = Object.hasOwn(metadataPlacement, 'row') ? metadataPlacement.row : configPlacement.row;\n  const column = Object.hasOwn(metadataPlacement, 'column')\n    ? metadataPlacement.column\n    : configPlacement.column;\n  validateGridCoordinate(authoredPlacementId, 'row', row, item.id);\n  validateGridCoordinate(authoredPlacementId, 'column', column, item.id);\n\n  return {\n    item,\n    row: row ?? 0,\n    column: column ?? 0,\n    horizontalAlign:\n      metadataPlacement.horizontalAlign ??\n      configPlacement.horizontalAlign ??\n      config.horizontalAlign,\n    verticalAlign:\n      metadataPlacement.verticalAlign ?? configPlacement.verticalAlign ?? config.verticalAlign,\n    sourceOrder: sourceOrder.get(item.id) ?? Number.MAX_SAFE_INTEGER,\n    explicitRow: row !== undefined,\n    explicitColumn: column !== undefined,\n    explicitCell: row !== undefined && column !== undefined,\n  };\n}\n\nfunction nextFreeColumn(row: number, occupied: Set<string>, startColumn: number): number {\n  let column = startColumn;\n  while (occupied.has(`${row}:${column}`)) {\n    column++;\n  }\n  return column;\n}\n\nfunction nextFreeRow(column: number, occupied: Set<string>, startRow: number): number {\n  let row = startRow;\n  while (occupied.has(`${row}:${column}`)) {\n    row++;\n  }\n  return row;\n}\n\nfunction nextAutoCell(\n  occupied: Set<string>,\n  candidateColumns: number,\n  startIndex: number\n): {\n  row: number;\n  column: number;\n  nextIndex: number;\n} {\n  let index = startIndex;\n  // The occupied set is finite while the row-major coordinate space is unbounded, so a free cell\n  // must eventually be found.\n  for (;;) {\n    const row = Math.floor(index / candidateColumns) + 1;\n    const column = (index % candidateColumns) + 1;\n    index++;\n    if (!occupied.has(`${row}:${column}`)) {\n      return { row, column, nextIndex: index };\n    }\n  }\n}\n\n/**\n * Assigns sibling nodes to cells in source order, reserving explicit cells before auto-placement.\n * Repeated authored IDs consume successive map entries. Explicit cell occupants form stacks,\n * but conflicting vertical alignments throw `GRID_CELL_ALIGNMENT_CONFLICT`.\n */\nexport function resolveGridPlacements(\n  items: Node[],\n  sourceOrder: Map<string, number>,\n  config: GridLayoutConfigNormalized\n): {\n  placements: GridResolvedPlacement[];\n  cells: Map<string, GridCellStack>;\n} {\n  const sortedItems = [...items].sort(itemComparator(sourceOrder));\n  const occurrenceByPlacementId = new Map<string, number>();\n  const resolved = sortedItems.map((item) => {\n    const placementId = item.placementId ?? item.id;\n    const occurrenceIndex = occurrenceByPlacementId.get(placementId) ?? 0;\n    occurrenceByPlacementId.set(placementId, occurrenceIndex + 1);\n    return resolveItemPlacement(item, sourceOrder, config, occurrenceIndex);\n  });\n\n  const cells = new Map<string, GridCellStack>();\n  const occupied = new Set<string>();\n\n  // Reserve fully specified cells first. Auto-placement must route around authored coordinates\n  // regardless of source order, while multiple explicit occupants intentionally form a stack.\n  for (const placement of resolved) {\n    if (!placement.explicitCell) {\n      continue;\n    }\n    const key = `${placement.row}:${placement.column}`;\n    occupied.add(key);\n    const existing = cells.get(key);\n    if (existing) {\n      if (existing.verticalAlign !== placement.verticalAlign) {\n        throw gridError(\n          'GRID_CELL_ALIGNMENT_CONFLICT',\n          `Conflicting vertical alignment in cell (${placement.row}, ${placement.column})`,\n          {\n            containerId: placement.item.parentId ?? 'root',\n            row: placement.row,\n            column: placement.column,\n            itemIds: [...existing.items.map((item) => item.item.id), placement.item.id],\n            values: [...existing.items.map((item) => item.verticalAlign), placement.verticalAlign],\n          }\n        );\n      }\n      existing.items.push(placement);\n    } else {\n      cells.set(key, {\n        row: placement.row,\n        column: placement.column,\n        items: [placement],\n        width: 0,\n        height: 0,\n        verticalAlign: placement.verticalAlign,\n      });\n    }\n  }\n\n  const candidateColumns =\n    config.columns > 0 ? config.columns : Math.max(1, Math.ceil(Math.sqrt(sortedItems.length)));\n  let nextAutoIndex = 0;\n  const nextColumnByRow = new Map<number, number>();\n  const nextRowByColumn = new Map<number, number>();\n\n  // Partially specified placements scan only their missing axis. Fully automatic placements use a\n  // compact row-major grid whose default width keeps roughly square diagrams. Each cursor only\n  // moves forward because occupied cells are never released.\n  for (const placement of resolved) {\n    if (placement.explicitCell) {\n      continue;\n    }\n\n    if (placement.explicitRow) {\n      const column = nextFreeColumn(\n        placement.row,\n        occupied,\n        nextColumnByRow.get(placement.row) ?? 1\n      );\n      placement.column = column;\n      nextColumnByRow.set(placement.row, column + 1);\n    } else if (placement.explicitColumn) {\n      const row = nextFreeRow(\n        placement.column,\n        occupied,\n        nextRowByColumn.get(placement.column) ?? 1\n      );\n      placement.row = row;\n      nextRowByColumn.set(placement.column, row + 1);\n    } else {\n      const next = nextAutoCell(occupied, candidateColumns, nextAutoIndex);\n      placement.row = next.row;\n      placement.column = next.column;\n      nextAutoIndex = next.nextIndex;\n    }\n\n    const key = `${placement.row}:${placement.column}`;\n    occupied.add(key);\n    cells.set(key, {\n      row: placement.row,\n      column: placement.column,\n      items: [placement],\n      width: 0,\n      height: 0,\n      verticalAlign: placement.verticalAlign,\n    });\n  }\n\n  return { placements: resolved, cells };\n}\n", "import type { GridRoutingFallbackReason } from './routerInstrumentation.js';\n\nexport class GridRoutingResourceLimitError extends Error {\n  constructor(\n    public readonly reason: GridRoutingFallbackReason,\n    message: string,\n    public readonly searchStateScope?: 'edge' | 'invocation'\n  ) {\n    super(message);\n    this.name = 'GridRoutingResourceLimitError';\n  }\n}\n", "import { compareCodeUnits } from '../layout-utils/helpers.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n  ContainerRoutingTopology,\n  GridOrientation,\n  GridSide,\n  OrthogonalIntervalIndex,\n  PairedPortal,\n  PortalRange,\n  RouterArc,\n  RouterObstacle,\n  RouterPoint,\n  RouterRect,\n  RouterSearchArc,\n  RouterVertex,\n} from './types.js';\n\n// Builds immutable orthogonal visibility graphs per container. Endpoint-specific vertices are added\n// through bounded overlays so the expensive obstacle sweep is paid once per container.\nexport const ROUTE_CLEARANCE_PX = 6;\n\n/**\n * Parallel runs of different edges closer than this are hard to tell apart, so candidates avoid them.\n * Perpendicular crossings are not affected. Lives here (rather than routerOccupancy.ts) because it is\n * shared with routerPlanning.ts and routerConstraint.ts already imports from this module.\n */\nexport const EDGE_CLEARANCE_PX = 24;\n\n// Caps bound both adversarial geometry and ordinary large-diagram memory growth. Exceeding one is a\n// recoverable routing condition handled by the validated compatibility path.\nconst DEFAULT_MAX_VERTICES = 50_000;\nconst MAX_VISIBILITY_ADJACENCY_PER_VERTEX = 4;\nexport const DEFAULT_MAX_ROUTING_ESTIMATED_BYTES = 64 * 1024 * 1024;\n\nexport interface RouterObstacleInput {\n  id: string;\n  bounds: RouterRect;\n}\n\nexport interface ContainerTopologyInput {\n  containerId: string;\n  bounds: RouterRect;\n  obstacles: readonly RouterObstacleInput[];\n  titleExclusions?: readonly RouterObstacleInput[];\n  portalRanges?: readonly PortalRange[];\n}\n\nexport interface TopologyResourceCaps {\n  maxVertices?: number;\n  maxAdjacencyEntries?: number;\n  maxEstimatedBytes?: number;\n}\n\nexport interface BuildTopologyOptions {\n  metrics?: GridRoutingInstrumentation;\n  caps?: TopologyResourceCaps;\n}\n\ninterface VertexRecord {\n  point: RouterPoint;\n  kind: RouterVertex['kind'];\n  ownerId?: string;\n  side?: GridSide;\n}\n\ninterface IndexedBand {\n  low: number;\n  high: number;\n  intervals: readonly (readonly [number, number])[];\n}\n\nclass CompressedIntervalIndex implements OrthogonalIntervalIndex {\n  // Obstacle occupancy is constant between sorted boundaries, so bands share merged interval lists.\n  // Exact boundaries use strict intervals to allow visibility paths to run along obstacle edges.\n  readonly coordinateCount: number;\n  readonly intervalCount: number;\n  private readonly byLow = new Map<number, IndexedBand>();\n  private readonly byHigh = new Map<number, IndexedBand>();\n\n  constructor(\n    private readonly bands: readonly IndexedBand[],\n    private readonly strictBoundaryIntervals: ReadonlyMap<\n      number,\n      readonly (readonly [number, number])[]\n    >\n  ) {\n    this.coordinateCount = new Set(bands.flatMap(({ low, high }) => [low, high])).size;\n    let intervalCount = bands.reduce((total, band) => total + band.intervals.length, 0);\n    for (const intervals of strictBoundaryIntervals.values()) {\n      intervalCount += intervals.length;\n    }\n    this.intervalCount = intervalCount;\n    for (const band of bands) {\n      this.byLow.set(band.low, band);\n      this.byHigh.set(band.high, band);\n    }\n    Object.freeze(this.bands);\n    Object.freeze(this);\n  }\n\n  private containingBand(coordinate: number): IndexedBand | undefined {\n    let low = 0;\n    let high = this.bands.length - 1;\n    while (low <= high) {\n      const middle = (low + high) >>> 1;\n      const band = this.bands[middle];\n      if (coordinate <= band.low) {\n        high = middle - 1;\n      } else if (coordinate >= band.high) {\n        low = middle + 1;\n      } else {\n        return band;\n      }\n    }\n    return undefined;\n  }\n\n  private overlaps(\n    intervals: readonly (readonly [number, number])[],\n    low: number,\n    high: number\n  ): boolean {\n    let left = 0;\n    let right = intervals.length;\n    while (left < right) {\n      const middle = (left + right) >>> 1;\n      if (intervals[middle][1] <= low) {\n        left = middle + 1;\n      } else {\n        right = middle;\n      }\n    }\n    return left < intervals.length && intervals[left][0] < high;\n  }\n\n  intersects(coordinate: number, intervalStart: number, intervalEnd: number): boolean {\n    const low = Math.min(intervalStart, intervalEnd);\n    const high = Math.max(intervalStart, intervalEnd);\n    const before = this.byHigh.get(coordinate);\n    const after = this.byLow.get(coordinate);\n    const containing = before || after ? undefined : this.containingBand(coordinate);\n    if (containing) {\n      return this.overlaps(containing.intervals, low, high);\n    }\n    if (!before || !after) {\n      return false;\n    }\n    let beforeIndex = 0;\n    let afterIndex = 0;\n    while (beforeIndex < before.intervals.length && afterIndex < after.intervals.length) {\n      const overlapLow = Math.max(\n        low,\n        before.intervals[beforeIndex][0],\n        after.intervals[afterIndex][0]\n      );\n      const overlapHigh = Math.min(\n        high,\n        before.intervals[beforeIndex][1],\n        after.intervals[afterIndex][1]\n      );\n      if (overlapLow < overlapHigh) {\n        return true;\n      }\n      if (before.intervals[beforeIndex][1] < after.intervals[afterIndex][1]) {\n        beforeIndex++;\n      } else {\n        afterIndex++;\n      }\n    }\n    return false;\n  }\n\n  contains(coordinate: number, varying: number): boolean {\n    const intervals =\n      this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;\n    if (!intervals) {\n      return false;\n    }\n    let low = 0;\n    let high = intervals.length;\n    while (low < high) {\n      const middle = (low + high) >>> 1;\n      if (intervals[middle][0] < varying) {\n        low = middle + 1;\n      } else {\n        high = middle;\n      }\n    }\n    return low > 0 && varying < intervals[low - 1][1];\n  }\n\n  nearestBoundary(coordinate: number, origin: number, direction: -1 | 1): number | undefined {\n    const intervals =\n      this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;\n    if (!intervals) {\n      return undefined;\n    }\n    if (direction < 0) {\n      let low = 0;\n      let high = intervals.length;\n      while (low < high) {\n        const middle = (low + high) >>> 1;\n        if (intervals[middle][1] <= origin) {\n          low = middle + 1;\n        } else {\n          high = middle;\n        }\n      }\n      return low > 0 ? intervals[low - 1][1] : undefined;\n    }\n    let low = 0;\n    let high = intervals.length;\n    while (low < high) {\n      const middle = (low + high) >>> 1;\n      if (intervals[middle][0] < origin) {\n        low = middle + 1;\n      } else {\n        high = middle;\n      }\n    }\n    return low < intervals.length ? intervals[low][0] : undefined;\n  }\n}\n\nclass ImmutableMap<K, V> implements ReadonlyMap<K, V> {\n  readonly [Symbol.toStringTag] = 'ImmutableMap';\n\n  constructor(private readonly backing: ReadonlyMap<K, V>) {\n    Object.freeze(this);\n  }\n\n  get size(): number {\n    return this.backing.size;\n  }\n\n  entries(): MapIterator<[K, V]> {\n    return this.backing.entries();\n  }\n\n  forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: unknown): void {\n    for (const [key, value] of this.backing) {\n      callbackfn.call(thisArg, value, key, this);\n    }\n  }\n\n  get(key: K): V | undefined {\n    return this.backing.get(key);\n  }\n\n  has(key: K): boolean {\n    return this.backing.has(key);\n  }\n\n  keys(): MapIterator<K> {\n    return this.backing.keys();\n  }\n\n  values(): MapIterator<V> {\n    return this.backing.values();\n  }\n\n  [Symbol.iterator](): MapIterator<[K, V]> {\n    return this.entries();\n  }\n}\n\nclass OverlayMap<K, V> implements ReadonlyMap<K, V> {\n  readonly [Symbol.toStringTag] = 'OverlayMap';\n\n  constructor(\n    private readonly base: ReadonlyMap<K, V>,\n    private readonly overrides: ReadonlyMap<K, V>\n  ) {}\n\n  get size(): number {\n    let added = 0;\n    for (const key of this.overrides.keys()) {\n      if (!this.base.has(key)) {\n        added++;\n      }\n    }\n    return this.base.size + added;\n  }\n\n  private materialize(): Map<K, V> {\n    return new Map([...this.base, ...this.overrides]);\n  }\n\n  entries(): MapIterator<[K, V]> {\n    return this.materialize().entries();\n  }\n\n  forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: unknown): void {\n    for (const [key, value] of this) {\n      callbackfn.call(thisArg, value, key, this);\n    }\n  }\n\n  get(key: K): V | undefined {\n    return this.overrides.get(key) ?? this.base.get(key);\n  }\n\n  has(key: K): boolean {\n    return this.overrides.has(key) || this.base.has(key);\n  }\n\n  keys(): MapIterator<K> {\n    return this.materialize().keys();\n  }\n\n  values(): MapIterator<V> {\n    return this.materialize().values();\n  }\n\n  [Symbol.iterator](): MapIterator<[K, V]> {\n    return this.entries();\n  }\n}\n\nfunction overlayArray<T>(base: readonly T[], additions: readonly T[]): readonly T[] {\n  // Numeric access and iteration are enough for search. A proxy avoids copying the immutable base\n  // array for every endpoint pair.\n  return new Proxy([] as T[], {\n    get(_target, property) {\n      if (property === 'length') {\n        return base.length + additions.length;\n      }\n      if (property === Symbol.iterator) {\n        return function* () {\n          yield* base;\n          yield* additions;\n        };\n      }\n      if (typeof property === 'string' && /^\\d+$/.test(property)) {\n        const index = Number(property);\n        return index < base.length ? base[index] : additions[index - base.length];\n      }\n      return Reflect.get(Array.prototype, property);\n    },\n  });\n}\n\nfunction overrideArray<T>(\n  base: readonly T[],\n  overrides: ReadonlyMap<number, T>,\n  length: number\n): readonly T[] {\n  return new Proxy([] as T[], {\n    get(_target, property) {\n      if (property === 'length') {\n        return length;\n      }\n      if (property === Symbol.iterator) {\n        return function* () {\n          for (let index = 0; index < length; index++) {\n            yield overrides.get(index) ?? base[index];\n          }\n        };\n      }\n      if (typeof property === 'string' && /^\\d+$/.test(property)) {\n        const index = Number(property);\n        return overrides.get(index) ?? base[index];\n      }\n      return Reflect.get(Array.prototype, property);\n    },\n  });\n}\n\nexport class EndpointOverlayScratch {\n  // One scratch object belongs to one base topology. The undo log clears only overridden base\n  // vertices, keeping reset cost proportional to the previous overlay rather than the whole graph.\n  readonly addedVertices: RouterVertex[] = [];\n  readonly adjacencyOverrides = new Map<number, readonly RouterArc[]>();\n  readonly searchAdjacencyOverrides = new Map<number, readonly RouterSearchArc[]>();\n  readonly pointOverrides = new Map<string, number>();\n  readonly undoLog: number[] = [];\n  resetCount = 0;\n\n  constructor(readonly base: ContainerRoutingTopology) {}\n\n  reset(base: ContainerRoutingTopology): void {\n    if (base !== this.base) {\n      throw new Error('Endpoint overlay scratch cannot be shared across base topologies');\n    }\n    for (const id of this.undoLog) {\n      this.adjacencyOverrides.delete(id);\n      this.searchAdjacencyOverrides.delete(id);\n    }\n    this.undoLog.length = 0;\n    this.addedVertices.length = 0;\n    this.pointOverrides.clear();\n    this.resetCount++;\n  }\n\n  setArcs(id: number, arcs: readonly RouterArc[]): void {\n    if (!this.adjacencyOverrides.has(id)) {\n      this.undoLog.push(id);\n    }\n    this.adjacencyOverrides.set(id, arcs);\n    this.searchAdjacencyOverrides.set(id, searchArcs(arcs));\n  }\n}\n\nfunction normalizeCoordinate(value: number): number {\n  return Object.is(value, -0) ? 0 : value;\n}\n\nfunction normalizeRect(rect: RouterRect): RouterRect {\n  const values = [rect.left, rect.right, rect.top, rect.bottom];\n  if (!values.every(Number.isFinite)) {\n    throw new Error('Grid routing geometry must contain only finite coordinates');\n  }\n  const left = normalizeCoordinate(Math.min(rect.left, rect.right));\n  const right = normalizeCoordinate(Math.max(rect.left, rect.right));\n  const top = normalizeCoordinate(Math.min(rect.top, rect.bottom));\n  const bottom = normalizeCoordinate(Math.max(rect.top, rect.bottom));\n  if (left === right || top === bottom) {\n    // The production layout path should reject zero-area nodes before routing; this guards direct\n    // topology callers and invalid derived geometry.\n    throw new Error('Grid routing rectangles must have positive area');\n  }\n  return { left, right, top, bottom };\n}\n\nfunction inflateAndClip(\n  input: RouterObstacleInput,\n  domain: RouterRect\n): RouterObstacle | undefined {\n  const bounds = normalizeRect(input.bounds);\n  const obstacle = {\n    id: input.id,\n    left: Math.max(domain.left, bounds.left - ROUTE_CLEARANCE_PX),\n    right: Math.min(domain.right, bounds.right + ROUTE_CLEARANCE_PX),\n    top: Math.max(domain.top, bounds.top - ROUTE_CLEARANCE_PX),\n    bottom: Math.min(domain.bottom, bounds.bottom + ROUTE_CLEARANCE_PX),\n  };\n  return obstacle.left < obstacle.right && obstacle.top < obstacle.bottom ? obstacle : undefined;\n}\n\nfunction mergeObstacleIntervals(\n  intervals: { low: number; high: number; id: string }[]\n): { low: number; high: number; id: string }[] {\n  const sorted = [...intervals].sort(\n    (a, b) => a.low - b.low || a.high - b.high || compareCodeUnits(a.id, b.id)\n  );\n  const merged: { low: number; high: number; id: string }[] = [];\n  for (const interval of sorted) {\n    const previous = merged.at(-1);\n    if (!previous || interval.low > previous.high) {\n      merged.push({ ...interval });\n      continue;\n    }\n    previous.high = Math.max(previous.high, interval.high);\n    if (compareCodeUnits(interval.id, previous.id) < 0) {\n      previous.id = interval.id;\n    }\n  }\n  return merged;\n}\n\nfunction unionObstacles(obstacles: readonly RouterObstacle[]): RouterObstacle[] {\n  // Sweep x-slabs and merge active y-intervals into a non-overlapping obstacle union. This prevents\n  // intersecting inflated nodes and title exclusions from multiplying visibility vertices.\n  const events = new Map<number, { starts: RouterObstacle[]; ends: RouterObstacle[] }>();\n  for (const obstacle of obstacles) {\n    const start = events.get(obstacle.left) ?? { starts: [], ends: [] };\n    start.starts.push(obstacle);\n    events.set(obstacle.left, start);\n    const end = events.get(obstacle.right) ?? { starts: [], ends: [] };\n    end.ends.push(obstacle);\n    events.set(obstacle.right, end);\n  }\n  const xCoordinates = [...events.keys()].sort((a, b) => a - b);\n  const active = new Set<RouterObstacle>();\n  const slabs: RouterObstacle[] = [];\n  let previousByInterval = new Map<string, RouterObstacle>();\n  for (let index = 0; index < xCoordinates.length - 1; index++) {\n    const left = xCoordinates[index];\n    const right = xCoordinates[index + 1];\n    const event = events.get(left)!;\n    for (const obstacle of event.ends) {\n      active.delete(obstacle);\n    }\n    for (const obstacle of event.starts) {\n      active.add(obstacle);\n    }\n    const nextByInterval = new Map<string, RouterObstacle>();\n    for (const interval of mergeObstacleIntervals(\n      [...active].map((obstacle) => ({\n        low: obstacle.top,\n        high: obstacle.bottom,\n        id: obstacle.id,\n      }))\n    )) {\n      const key = `${interval.low}:${interval.high}`;\n      const previous = previousByInterval.get(key);\n      if (previous) {\n        previous.right = right;\n        if (compareCodeUnits(interval.id, previous.id) < 0) {\n          previous.id = interval.id;\n        }\n      } else {\n        const slab = {\n          id: interval.id,\n          left,\n          right,\n          top: interval.low,\n          bottom: interval.high,\n        };\n        slabs.push(slab);\n        nextByInterval.set(key, slab);\n        continue;\n      }\n      nextByInterval.set(key, previous);\n    }\n    previousByInterval = nextByInterval;\n  }\n  return slabs.sort(\n    (a, b) =>\n      a.top - b.top ||\n      a.left - b.left ||\n      a.bottom - b.bottom ||\n      a.right - b.right ||\n      compareCodeUnits(a.id, b.id)\n  );\n}\n\nexport function routingPointKey(point: RouterPoint): string {\n  return `${normalizeCoordinate(point.x)}:${normalizeCoordinate(point.y)}`;\n}\n\nfunction topologySideOrdinal(side?: GridSide): number {\n  return side === 'left'\n    ? 0\n    : side === 'right'\n      ? 1\n      : side === 'top'\n        ? 2\n        : side === 'bottom'\n          ? 3\n          : 4;\n}\n\nfunction vertexRecordOrder(a: VertexRecord, b: VertexRecord): number {\n  return (\n    compareCodeUnits(a.kind, b.kind) ||\n    topologySideOrdinal(a.side) - topologySideOrdinal(b.side) ||\n    a.point.x - b.point.x ||\n    a.point.y - b.point.y ||\n    compareCodeUnits(a.ownerId ?? '', b.ownerId ?? '')\n  );\n}\n\nfunction canonicalRecords(records: readonly VertexRecord[]): VertexRecord[] {\n  // Sorting before duplicate removal makes vertex identity and numeric ids independent of discovery\n  // order.\n  const byPoint = new Map<string, VertexRecord>();\n  for (const record of [...records].sort(vertexRecordOrder)) {\n    const normalized = {\n      ...record,\n      point: {\n        x: normalizeCoordinate(record.point.x),\n        y: normalizeCoordinate(record.point.y),\n      },\n    };\n    const key = routingPointKey(normalized.point);\n    if (!byPoint.has(key)) {\n      byPoint.set(key, normalized);\n    }\n  }\n  return [...byPoint.values()];\n}\n\nfunction cornerRecords(\n  bounds: RouterRect,\n  ownerId: string,\n  kind: RouterVertex['kind'] = 'corner'\n): VertexRecord[] {\n  return [\n    { point: { x: bounds.left, y: bounds.top }, kind, ownerId },\n    { point: { x: bounds.right, y: bounds.top }, kind, ownerId },\n    { point: { x: bounds.left, y: bounds.bottom }, kind, ownerId },\n    { point: { x: bounds.right, y: bounds.bottom }, kind, ownerId },\n  ];\n}\n\nfunction portalRecords(range: PortalRange, bounds: RouterRect): VertexRecord[] {\n  const coordinate =\n    range.coordinate ??\n    (range.side === 'left'\n      ? bounds.left\n      : range.side === 'right'\n        ? bounds.right\n        : range.side === 'top'\n          ? bounds.top\n          : bounds.bottom);\n  const points =\n    range.side === 'left' || range.side === 'right'\n      ? [\n          { x: coordinate, y: range.low },\n          { x: coordinate, y: range.high },\n        ]\n      : [\n          { x: range.low, y: coordinate },\n          { x: range.high, y: coordinate },\n        ];\n  return points.map((value) => ({\n    point: value,\n    kind: 'portal',\n    ownerId: range.ownerId,\n    side: range.side,\n  }));\n}\n\nfunction rayHit(\n  point: RouterPoint,\n  side: GridSide,\n  bounds: RouterRect,\n  horizontalIntervals: OrthogonalIntervalIndex,\n  verticalIntervals: OrthogonalIntervalIndex\n): RouterPoint {\n  if (side === 'left' || side === 'right') {\n    const hit =\n      horizontalIntervals.nearestBoundary(point.y, point.x, side === 'left' ? -1 : 1) ??\n      (side === 'left' ? bounds.left : bounds.right);\n    return { x: hit, y: point.y };\n  }\n\n  const hit =\n    verticalIntervals.nearestBoundary(point.x, point.y, side === 'top' ? -1 : 1) ??\n    (side === 'top' ? bounds.top : bounds.bottom);\n  return { x: point.x, y: hit };\n}\n\nfunction createIntervalIndex(\n  obstacles: readonly RouterObstacle[],\n  orientation: GridOrientation,\n  budget: { intervalCount: number; maxEstimatedBytes: number }\n): OrthogonalIntervalIndex {\n  const coordinates = [\n    ...new Set(\n      obstacles.flatMap((obstacle) =>\n        orientation === 'H' ? [obstacle.top, obstacle.bottom] : [obstacle.left, obstacle.right]\n      )\n    ),\n  ].sort((a, b) => a - b);\n  const bands: IndexedBand[] = [];\n  const strictBoundaryIntervals = new Map<number, readonly (readonly [number, number])[]>();\n  const starts = new Map<number, RouterObstacle[]>();\n  const ends = new Map<number, RouterObstacle[]>();\n  for (const obstacle of obstacles) {\n    const start = orientation === 'H' ? obstacle.top : obstacle.left;\n    const end = orientation === 'H' ? obstacle.bottom : obstacle.right;\n    const startEvents = starts.get(start) ?? [];\n    startEvents.push(obstacle);\n    starts.set(start, startEvents);\n    const endEvents = ends.get(end) ?? [];\n    endEvents.push(obstacle);\n    ends.set(end, endEvents);\n  }\n  const active = new Set<RouterObstacle>();\n  const activeIntervals = () =>\n    mergeObstacleIntervals(\n      [...active].map((obstacle) =>\n        orientation === 'H'\n          ? { low: obstacle.left, high: obstacle.right, id: obstacle.id }\n          : { low: obstacle.top, high: obstacle.bottom, id: obstacle.id }\n      )\n    );\n  const freezeIntervals = (\n    intervals: readonly { low: number; high: number }[]\n  ): readonly (readonly [number, number])[] => {\n    const intervalCount = budget.intervalCount + intervals.length;\n    enforceCap(\n      estimatedTopologyBytes(0, 0, obstacles.length, intervalCount),\n      budget.maxEstimatedBytes,\n      'estimated_memory_cap'\n    );\n    budget.intervalCount = intervalCount;\n    return Object.freeze(\n      intervals.map((interval) => Object.freeze([interval.low, interval.high] as const))\n    );\n  };\n  for (let index = 0; index < coordinates.length; index++) {\n    const coordinate = coordinates[index];\n    for (const obstacle of ends.get(coordinate) ?? []) {\n      active.delete(obstacle);\n    }\n    strictBoundaryIntervals.set(coordinate, freezeIntervals(activeIntervals()));\n    for (const obstacle of starts.get(coordinate) ?? []) {\n      active.add(obstacle);\n    }\n    const high = coordinates[index + 1];\n    if (high === undefined) {\n      continue;\n    }\n    const intervals = activeIntervals();\n    if (intervals.length > 0) {\n      bands.push({\n        low: coordinate,\n        high,\n        intervals: freezeIntervals(intervals),\n      });\n    }\n  }\n  return new CompressedIntervalIndex(\n    Object.freeze(bands),\n    new ImmutableMap(strictBoundaryIntervals)\n  );\n}\n\nfunction estimatedTopologyBytes(\n  vertices: number,\n  adjacencyEntries: number,\n  obstacles: number,\n  intervals: number\n): number {\n  return vertices * 64 + adjacencyEntries * 56 + obstacles * 48 + intervals * 24;\n}\n\nfunction enforceCap(\n  actual: number,\n  maximum: number,\n  reason: 'vertex_cap' | 'adjacency_cap' | 'estimated_memory_cap'\n): void {\n  if (actual > maximum) {\n    throw new GridRoutingResourceLimitError(\n      reason,\n      `Grid routing ${reason} exceeded: ${actual} > ${maximum}`\n    );\n  }\n}\n\nfunction indexVertexLines(\n  vertices: readonly RouterVertex[],\n  orientation: GridOrientation\n): ReadonlyMap<number, readonly RouterVertex[]> {\n  const lines = new Map<number, RouterVertex[]>();\n  for (const vertex of vertices) {\n    const fixed = orientation === 'H' ? vertex.point.y : vertex.point.x;\n    const line = lines.get(fixed) ?? [];\n    line.push(vertex);\n    lines.set(fixed, line);\n  }\n\n  for (const line of lines.values()) {\n    line.sort((a, b) =>\n      orientation === 'H'\n        ? a.point.x - b.point.x || a.id - b.id\n        : a.point.y - b.point.y || a.id - b.id\n    );\n    Object.freeze(line);\n  }\n  return new ImmutableMap(lines);\n}\n\nfunction searchArcs(arcs: readonly RouterArc[]): readonly RouterSearchArc[] {\n  /*\n   * Occupancy and crossing tie-breakers are left for future route-quality work.\n   *\n   * A minimal implementation could scan every committed route segment for every candidate arc:\n   * - Sum collinear overlap into an occupied-length cost.\n   * - Count perpendicular interior intersections as crossings.\n   * - Pass those values into the search arcs.\n   * - Recompute them after each committed route.\n   *\n   * That approach is simple, but likely too expensive: roughly routes x route segments x graph\n   * arcs for each edge search. It also risks inconsistent handling of endpoints, terminal\n   * segments, portals, and touching-versus-crossing geometry.\n   *\n   * A production-quality implementation would need:\n   * - A container-scoped horizontal/vertical segment index.\n   * - Efficient overlap and perpendicular-intersection queries.\n   * - Dynamic search or overlay costs without mutating the immutable base topology.\n   * - Updates only after route validation succeeds.\n   * - Rollback support for bundle retries.\n   * - Clear rules for endpoint touches, partial shared arcs, hierarchy segments, and routes that\n   *   span multiple containers.\n   * - Search tests proving occupancy changes only the intended late tie-breakers.\n   * - Routing tests showing reduced sharing and crossings.\n   * - Performance tests for the 500-edge contract.\n   */\n  return Object.freeze(\n    arcs.map((arc) =>\n      Object.freeze({\n        to: arc.to,\n        orientationOrdinal: arc.orientation === 'H' ? 1 : 2,\n        length: arc.length,\n        boundaryTransitions: arc.kind === 'portal' ? 1 : 0,\n      } as const)\n    )\n  );\n}\n\nfunction buildVisibilityGraph(\n  records: readonly VertexRecord[],\n  horizontalIntervals: OrthogonalIntervalIndex,\n  verticalIntervals: OrthogonalIntervalIndex,\n  caps: TopologyResourceCaps\n): {\n  vertices: readonly RouterVertex[];\n  adjacency: ReadonlyMap<number, readonly RouterArc[]>;\n  adjacencyEntries: number;\n} {\n  // Vertices connect only to their immediate visible neighbor on each shared x/y line; longer paths\n  // are represented by graph traversal instead of quadratic all-pairs arcs.\n  const canonical = canonicalRecords(records).sort(vertexRecordOrder);\n  const vertexCap = caps.maxVertices ?? DEFAULT_MAX_VERTICES;\n  enforceCap(canonical.length, vertexCap, 'vertex_cap');\n  const vertices = canonical.map<RouterVertex>((record, id) =>\n    Object.freeze({ id, ...record, point: Object.freeze({ ...record.point }) })\n  );\n  const adjacency = new Map<number, RouterArc[]>(\n    vertices.map((vertex) => [vertex.id, [] as RouterArc[]])\n  );\n  const addArcPair = (a: RouterVertex, b: RouterVertex, orientation: GridOrientation) => {\n    const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);\n    if (length === 0) {\n      return;\n    }\n\n    const intervalStart =\n      orientation === 'H' ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);\n    const intervalEnd = intervalStart + length;\n    for (const [from, to] of [\n      [a, b],\n      [b, a],\n    ] as const) {\n      adjacency.get(from.id)!.push({\n        from: from.id,\n        to: to.id,\n        orientation,\n        length,\n        kind: 'visibility',\n        intervalStart,\n        intervalEnd,\n      });\n    }\n  };\n\n  for (const orientation of ['H', 'V'] as const) {\n    const lines = new Map<number, RouterVertex[]>();\n    for (const vertex of vertices) {\n      const coordinate = orientation === 'H' ? vertex.point.y : vertex.point.x;\n      const line = lines.get(coordinate) ?? [];\n      line.push(vertex);\n      lines.set(coordinate, line);\n    }\n    for (const [fixed, line] of lines) {\n      line.sort((a, b) =>\n        orientation === 'H'\n          ? a.point.x - b.point.x || a.id - b.id\n          : a.point.y - b.point.y || a.id - b.id\n      );\n      for (let index = 1; index < line.length; index++) {\n        const a = line[index - 1];\n        const b = line[index];\n        const start = orientation === 'H' ? a.point.x : a.point.y;\n        const end = orientation === 'H' ? b.point.x : b.point.y;\n        const intervalIndex = orientation === 'H' ? horizontalIntervals : verticalIntervals;\n        if (!intervalIndex.intersects(fixed, start, end)) {\n          addArcPair(a, b, orientation);\n        }\n      }\n    }\n  }\n\n  const arcKindOrder: Record<RouterArc['kind'], number> = {\n    visibility: 0,\n    terminal: 1,\n    portal: 2,\n    lane: 3,\n  };\n  let adjacencyEntries = 0;\n  const immutableAdjacency = new Map<number, readonly RouterArc[]>();\n  for (const vertex of vertices) {\n    const arcs = adjacency.get(vertex.id)!;\n    arcs.sort(\n      (a, b) =>\n        arcKindOrder[a.kind] - arcKindOrder[b.kind] ||\n        compareCodeUnits(a.orientation, b.orientation) ||\n        vertices[a.to].point.x - vertices[b.to].point.x ||\n        vertices[a.to].point.y - vertices[b.to].point.y ||\n        a.to - b.to\n    );\n    const unique = arcs.filter(\n      (arc, index) =>\n        index === 0 ||\n        arc.to !== arcs[index - 1].to ||\n        arc.orientation !== arcs[index - 1].orientation ||\n        arc.kind !== arcs[index - 1].kind\n    );\n    adjacencyEntries += unique.length;\n    immutableAdjacency.set(vertex.id, Object.freeze(unique.map((arc) => Object.freeze(arc))));\n  }\n  enforceCap(\n    adjacencyEntries,\n    // Each vertex has at most one immediate visible neighbor in each cardinal direction. The\n    // override remains a test seam for exercising adjacency-cap fallback behavior.\n    caps.maxAdjacencyEntries ?? vertexCap * MAX_VISIBILITY_ADJACENCY_PER_VERTEX,\n    'adjacency_cap'\n  );\n  return {\n    vertices: Object.freeze(vertices),\n    adjacency: new ImmutableMap(immutableAdjacency),\n    adjacencyEntries,\n  };\n}\n\nexport function derivePortalRanges(\n  ownerId: string,\n  rawBounds: RouterRect,\n  rawTitle?: RouterRect\n): PortalRange[] {\n  const bounds = normalizeRect(rawBounds);\n  const title = rawTitle ? normalizeRect(rawTitle) : undefined;\n  const verticalLow = Math.max(\n    bounds.top + ROUTE_CLEARANCE_PX,\n    (title?.bottom ?? -Infinity) + ROUTE_CLEARANCE_PX\n  );\n  const verticalHigh = bounds.bottom - ROUTE_CLEARANCE_PX;\n  const horizontalLow = bounds.left + ROUTE_CLEARANCE_PX;\n  const horizontalHigh = bounds.right - ROUTE_CLEARANCE_PX;\n  const ranges: PortalRange[] = [];\n  if (verticalLow <= verticalHigh) {\n    ranges.push(\n      { ownerId, side: 'left', low: verticalLow, high: verticalHigh },\n      { ownerId, side: 'right', low: verticalLow, high: verticalHigh }\n    );\n  }\n  if (horizontalLow <= horizontalHigh) {\n    ranges.push({ ownerId, side: 'bottom', low: horizontalLow, high: horizontalHigh });\n    if (!title || title.bottom + ROUTE_CLEARANCE_PX <= bounds.top) {\n      ranges.push({ ownerId, side: 'top', low: horizontalLow, high: horizontalHigh });\n    }\n  }\n  return ranges;\n}\n\nexport function buildPairedPortal(\n  ownerId: string,\n  bounds: RouterRect,\n  title: RouterRect | undefined,\n  side: GridSide,\n  tangentialCoordinate: number\n): PairedPortal {\n  // Interior and exterior points sit one clearance unit from the group boundary. The explicit\n  // transition is the only hierarchy-crossing arc and contributes one boundary transition to cost.\n  const range = derivePortalRanges(ownerId, bounds, title).find((entry) => entry.side === side);\n  if (!range || tangentialCoordinate < range.low || tangentialCoordinate > range.high) {\n    throw new Error(`Illegal ${side} portal for \"${ownerId}\" at ${tangentialCoordinate}`);\n  }\n  const boundary =\n    side === 'left'\n      ? bounds.left\n      : side === 'right'\n        ? bounds.right\n        : side === 'top'\n          ? bounds.top\n          : bounds.bottom;\n  const inward =\n    side === 'left' || side === 'top'\n      ? boundary + ROUTE_CLEARANCE_PX\n      : boundary - ROUTE_CLEARANCE_PX;\n  const outward =\n    side === 'left' || side === 'top'\n      ? boundary - ROUTE_CLEARANCE_PX\n      : boundary + ROUTE_CLEARANCE_PX;\n  const interior =\n    side === 'left' || side === 'right'\n      ? { x: inward, y: tangentialCoordinate }\n      : { x: tangentialCoordinate, y: inward };\n  const exterior =\n    side === 'left' || side === 'right'\n      ? { x: outward, y: tangentialCoordinate }\n      : { x: tangentialCoordinate, y: outward };\n  return {\n    ownerId,\n    side,\n    tangentialCoordinate,\n    interior,\n    exterior,\n    transition: {\n      from: interior,\n      to: exterior,\n      orientation: side === 'left' || side === 'right' ? 'H' : 'V',\n      length: ROUTE_CLEARANCE_PX * 2,\n      kind: 'portal',\n    },\n  };\n}\n\nexport function buildContainerRoutingTopology(\n  input: ContainerTopologyInput,\n  options: BuildTopologyOptions = {}\n): ContainerRoutingTopology {\n  // Build phases are normalize/inflate, union obstacles, seed corners and portal endpoints, project\n  // rays to blocking boundaries, then connect immediate line-of-sight neighbors.\n  const bounds = normalizeRect(input.bounds);\n  const inflated = [...input.obstacles, ...(input.titleExclusions ?? [])]\n    .map((obstacle) => inflateAndClip(obstacle, bounds))\n    .filter((obstacle): obstacle is RouterObstacle => Boolean(obstacle));\n  const obstacles = unionObstacles(inflated);\n  const portalRanges = [...(input.portalRanges ?? [])].sort(\n    (a, b) =>\n      topologySideOrdinal(a.side) - topologySideOrdinal(b.side) ||\n      a.low - b.low ||\n      a.high - b.high ||\n      compareCodeUnits(a.ownerId, b.ownerId)\n  );\n\n  const seeds = canonicalRecords([\n    ...cornerRecords(bounds, input.containerId),\n    ...obstacles.flatMap((obstacle) => cornerRecords(obstacle, obstacle.id)),\n    ...portalRanges.flatMap((range) => portalRecords(range, bounds)),\n  ]);\n  const intervalBudget = {\n    intervalCount: 0,\n    maxEstimatedBytes: options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n  };\n  enforceCap(\n    estimatedTopologyBytes(0, 0, obstacles.length, 0),\n    intervalBudget.maxEstimatedBytes,\n    'estimated_memory_cap'\n  );\n  const horizontalIntervals = createIntervalIndex(obstacles, 'H', intervalBudget);\n  const verticalIntervals = createIntervalIndex(obstacles, 'V', intervalBudget);\n  const projections: VertexRecord[] = [];\n  const sides: readonly GridSide[] = ['left', 'right', 'top', 'bottom'];\n  for (const seed of seeds) {\n    for (const side of sides) {\n      const hit = rayHit(seed.point, side, bounds, horizontalIntervals, verticalIntervals);\n      if (hit.x !== seed.point.x || hit.y !== seed.point.y) {\n        projections.push({ point: hit, kind: 'projection', side });\n      }\n    }\n  }\n\n  const { vertices, adjacency, adjacencyEntries } = buildVisibilityGraph(\n    [...seeds, ...projections],\n    horizontalIntervals,\n    verticalIntervals,\n    options.caps ?? {}\n  );\n\n  const estimatedBytes = estimatedTopologyBytes(\n    vertices.length,\n    adjacencyEntries,\n    obstacles.length,\n    horizontalIntervals.intervalCount + verticalIntervals.intervalCount\n  );\n  enforceCap(\n    estimatedBytes,\n    options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n    'estimated_memory_cap'\n  );\n\n  if (options.metrics) {\n    options.metrics.containersBuilt++;\n    options.metrics.baseTopologyBuilds++;\n    options.metrics.baseVertices += vertices.length;\n    options.metrics.baseAdjacencyEntries += adjacencyEntries;\n    options.metrics.buildSweepEvents += seeds.length * 4 + obstacles.length * 4;\n    options.metrics.estimatedBytes += estimatedBytes;\n  }\n\n  return Object.freeze({\n    containerId: input.containerId,\n    bounds: Object.freeze(bounds),\n    obstacles: Object.freeze(obstacles.map((obstacle) => Object.freeze(obstacle))),\n    vertices: Object.freeze(vertices),\n    pointVertexIds: new ImmutableMap(\n      new Map(vertices.map(({ id, point }) => [routingPointKey(point), id]))\n    ),\n    horizontalVertexLines: indexVertexLines(vertices, 'H'),\n    verticalVertexLines: indexVertexLines(vertices, 'V'),\n    adjacency,\n    adjacencyByVertex: Object.freeze(vertices.map(({ id }) => adjacency.get(id) ?? [])),\n    searchAdjacencyByVertex: Object.freeze(\n      vertices.map(({ id }) => searchArcs(adjacency.get(id) ?? []))\n    ),\n    adjacencyEntries,\n    horizontalIntervals,\n    verticalIntervals,\n    portalRanges: Object.freeze(portalRanges.map((range) => Object.freeze(range))),\n    seedCount: seeds.length,\n    estimatedBytes,\n  });\n}\n\nfunction pointInsideObstacle(\n  point: RouterPoint,\n  horizontalIntervals: OrthogonalIntervalIndex\n): boolean {\n  return horizontalIntervals.contains(point.y, point.x);\n}\n\nexport function buildEndpointRoutingOverlay(\n  base: ContainerRoutingTopology,\n  source: RouterPoint,\n  target: RouterPoint,\n  metrics?: GridRoutingInstrumentation,\n  reusableScratch?: EndpointOverlayScratch,\n  lanePoints: readonly RouterPoint[] = []\n): ContainerRoutingTopology {\n  // Overlays are intentionally tiny: two endpoints, optional bundle lane points, orthogonal\n  // projections, and four obstacle/bounds ray hits per endpoint. Local caps enforce that invariant.\n  const scratch = reusableScratch ?? new EndpointOverlayScratch(base);\n  scratch.reset(base);\n  const endpointRecords: VertexRecord[] = [\n    { point: source, kind: 'endpoint', ownerId: 'source' },\n    { point: target, kind: 'endpoint', ownerId: 'target' },\n    ...lanePoints\n      .filter((point) => !pointInsideObstacle(point, base.horizontalIntervals))\n      .map((point) => ({ point, kind: 'lane' as const })),\n  ];\n  for (const point of [\n    { x: source.x, y: target.y },\n    { x: target.x, y: source.y },\n  ]) {\n    if (!pointInsideObstacle(point, base.horizontalIntervals)) {\n      endpointRecords.push({ point, kind: 'projection' });\n    }\n  }\n  for (const record of endpointRecords.slice(0, 2)) {\n    for (const side of ['left', 'right', 'top', 'bottom'] as const) {\n      const hit = rayHit(\n        record.point,\n        side,\n        base.bounds,\n        base.horizontalIntervals,\n        base.verticalIntervals\n      );\n      if (hit.x !== record.point.x || hit.y !== record.point.y) {\n        endpointRecords.push({ point: hit, kind: 'projection', side });\n      }\n    }\n  }\n  const additions = canonicalRecords(endpointRecords)\n    .filter(({ point }) => !base.pointVertexIds.has(routingPointKey(point)))\n    .sort(vertexRecordOrder);\n  enforceCap(additions.length, 32, 'vertex_cap');\n  scratch.addedVertices.push(\n    ...additions.map<RouterVertex>((record, index) =>\n      Object.freeze({\n        id: base.vertices.length + index,\n        ...record,\n        point: Object.freeze({ ...record.point }),\n      })\n    )\n  );\n  const vertices = overlayArray(base.vertices, scratch.addedVertices);\n  const vertexAt = (id: number): RouterVertex =>\n    id < base.vertices.length\n      ? base.vertices[id]\n      : scratch.addedVertices[id - base.vertices.length];\n  const adjacency = new Map<number, RouterArc[]>();\n  const mutableArcs = (id: number): RouterArc[] => {\n    let arcs = adjacency.get(id);\n    if (!arcs) {\n      arcs = [...(base.adjacency.get(id) ?? [])];\n      adjacency.set(id, arcs);\n    }\n    return arcs;\n  };\n  for (const vertex of scratch.addedVertices) {\n    adjacency.set(vertex.id, []);\n  }\n  const addedIds = new Set(scratch.addedVertices.map(({ id }) => id));\n  const addedArcKeys = new Set<string>();\n  const connect = (a: RouterVertex, b: RouterVertex, orientation: GridOrientation): void => {\n    const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);\n    if (length === 0) {\n      return;\n    }\n    const intervalStart =\n      orientation === 'H' ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);\n    const intervalEnd = intervalStart + length;\n    for (const [from, to] of [\n      [a, b],\n      [b, a],\n    ] as const) {\n      const key = `${from.id}:${to.id}:${orientation}:visibility`;\n      if (\n        addedArcKeys.has(key) ||\n        (base.adjacency.get(from.id) ?? []).some(\n          (arc) => arc.to === to.id && arc.orientation === orientation && arc.kind === 'visibility'\n        )\n      ) {\n        continue;\n      }\n      addedArcKeys.add(key);\n      mutableArcs(from.id).push({\n        from: from.id,\n        to: to.id,\n        orientation,\n        length,\n        kind: 'visibility',\n        intervalStart,\n        intervalEnd,\n      });\n    }\n  };\n\n  for (const orientation of ['H', 'V'] as const) {\n    const baseLines = orientation === 'H' ? base.horizontalVertexLines : base.verticalVertexLines;\n    const affected = new Set(\n      scratch.addedVertices.map(({ point }) => (orientation === 'H' ? point.y : point.x))\n    );\n    for (const fixed of affected) {\n      const line = [\n        ...(baseLines.get(fixed) ?? []),\n        ...scratch.addedVertices.filter(\n          ({ point }) => (orientation === 'H' ? point.y : point.x) === fixed\n        ),\n      ];\n      line.sort((a, b) =>\n        orientation === 'H'\n          ? a.point.x - b.point.x || a.id - b.id\n          : a.point.y - b.point.y || a.id - b.id\n      );\n      for (let index = 1; index < line.length; index++) {\n        const a = line[index - 1];\n        const b = line[index];\n        if (!addedIds.has(a.id) && !addedIds.has(b.id)) {\n          continue;\n        }\n        const start = orientation === 'H' ? a.point.x : a.point.y;\n        const end = orientation === 'H' ? b.point.x : b.point.y;\n        const intervalIndex =\n          orientation === 'H' ? base.horizontalIntervals : base.verticalIntervals;\n        if (!intervalIndex.intersects(fixed, start, end)) {\n          connect(a, b, orientation);\n        }\n      }\n    }\n  }\n\n  for (const [id, arcs] of adjacency) {\n    arcs.sort(\n      (a, b) =>\n        compareCodeUnits(a.kind, b.kind) ||\n        compareCodeUnits(a.orientation, b.orientation) ||\n        vertexAt(a.to).point.x - vertexAt(b.to).point.x ||\n        vertexAt(a.to).point.y - vertexAt(b.to).point.y ||\n        a.to - b.to\n    );\n    const immutableArcs = Object.freeze(arcs.map((arc) => Object.freeze(arc)));\n    scratch.setArcs(id, immutableArcs);\n  }\n  const adjacencyEntries = base.adjacencyEntries + addedArcKeys.size;\n  enforceCap(adjacencyEntries, base.adjacencyEntries + 64, 'adjacency_cap');\n  const addedVertices = additions.length;\n  const estimatedBytes =\n    base.estimatedBytes + addedVertices * 64 + (adjacencyEntries - base.adjacencyEntries) * 56;\n  if (metrics) {\n    metrics.endpointOverlayBuilds++;\n    metrics.endpointOverlayVertices += addedVertices;\n    metrics.estimatedBytes = Math.max(metrics.estimatedBytes, estimatedBytes);\n  }\n  const vertexCount = base.vertices.length + scratch.addedVertices.length;\n  const adjacencyByVertex = overrideArray(\n    base.adjacencyByVertex,\n    scratch.adjacencyOverrides,\n    vertexCount\n  );\n  const searchAdjacencyByVertex = overrideArray(\n    base.searchAdjacencyByVertex,\n    scratch.searchAdjacencyOverrides,\n    vertexCount\n  );\n  for (const vertex of scratch.addedVertices) {\n    scratch.pointOverrides.set(routingPointKey(vertex.point), vertex.id);\n  }\n  return Object.freeze({\n    ...base,\n    vertices,\n    pointVertexIds: new OverlayMap(base.pointVertexIds, scratch.pointOverrides),\n    adjacency: new OverlayMap(base.adjacency, scratch.adjacencyOverrides),\n    adjacencyByVertex,\n    searchAdjacencyByVertex,\n    adjacencyEntries,\n    estimatedBytes,\n    vertexCount,\n    getVertex: vertexAt,\n    getSearchArcs: (id: number) =>\n      scratch.searchAdjacencyOverrides.get(id) ?? base.searchAdjacencyByVertex[id] ?? [],\n  });\n}\n", "import type { Point } from '../../../types.js';\nimport type { Edge, LayoutData, Node } from '../../types.js';\nimport { PIXEL_EPSILON } from '../layout-utils/geometry.js';\nimport { clamp, compareCodeUnits, rectForNode } from '../layout-utils/helpers.js';\nimport { isAncestorGroup } from './groups.js';\nimport { EDGE_CLEARANCE_PX, ROUTE_CLEARANCE_PX, routingPointKey } from './routerTopology.js';\nimport type {\n  GridAttachmentDemand,\n  GridContainerId,\n  GridLayoutResult,\n  GridSide,\n  RouterPoint,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// Planning is deterministic and side-effect free: it resolves hierarchy chains, bundle lanes,\n// endpoint demand, and route order before the session creates any routing topology.\nconst MIN_PORT_SEPARATION_PX = 4;\nexport const TERMINAL_APPROACH_PX = 20;\nexport const LANE_SEPARATION_PX = 8;\n\nexport interface EdgeEndpointEntry {\n  ownerId: string;\n  side: GridSide;\n  demandKey: string;\n  oppositeCoord: number;\n  preferredCoord: number;\n  compactPortal: boolean;\n  ambiguousSides?: readonly GridSide[];\n  inner?: { demandKey: string; side: GridSide };\n}\n\nexport interface EdgeEndpointPlan {\n  // Entries walk from the endpoint outward toward the least common container. Each adjacent pair\n  // represents one hierarchy boundary that the final route must cross through a paired portal.\n  chain: EdgeEndpointEntry[];\n  finalKind: 'item' | 'boundary';\n}\n\nexport interface EdgeRoutePlan {\n  edge: Edge;\n  lcaContainerId: GridContainerId;\n  source: EdgeEndpointPlan;\n  target: EdgeEndpointPlan;\n  laneIndex: number;\n  laneOffset: number;\n  bundleSize: number;\n  pairKey: string;\n}\n\nexport interface EdgeRouteCandidates {\n  sources: EndpointCandidate[];\n  targets: EndpointCandidate[];\n}\n\nexport interface PreparedEdgeRoutes {\n  plans: EdgeRoutePlan[];\n  eligiblePlans: EdgeRoutePlan[];\n  eligibleIds: Set<string>;\n  orderedPlans: EdgeRoutePlan[];\n  demandCoords: Map<string, number>;\n  endpointCandidatesByEdge: Map<string, EdgeRouteCandidates>;\n  endpointIncidentCounts: Map<string, number>;\n  coordinatedEndpointIds: Set<string>;\n}\n\nexport function ownerGroupTitle(node: Node): boolean {\n  return Boolean(node.groupTitleRect);\n}\n\nexport function ownerSideKey(ownerId: string, side: GridSide): string {\n  return JSON.stringify([ownerId, side]);\n}\n\nfunction preferredSide(node: Node, toward: Point): GridSide {\n  const rect = rectForNode(node);\n  const dx = toward.x - rect.cx;\n  const dy = toward.y - rect.cy;\n  const avoidTop = node.isGroup && ownerGroupTitle(node);\n\n  if (Math.abs(dx) >= Math.abs(dy)) {\n    return dx >= 0 ? 'right' : 'left';\n  }\n  if (dy >= 0) {\n    return 'bottom';\n  }\n  if (avoidTop) {\n    return dx >= 0 ? 'right' : 'left';\n  }\n  return 'top';\n}\n\nfunction containerChain(node: Node, nodeById: Map<string, Node>): GridContainerId[] {\n  const chain: GridContainerId[] = [];\n  let currentParent = node.parentId ?? ROOT_CONTAINER_ID;\n  const seen = new Set<string>();\n  while (true) {\n    chain.push(currentParent);\n    if (currentParent === ROOT_CONTAINER_ID) {\n      break;\n    }\n    if (seen.has(currentParent)) {\n      break;\n    }\n    seen.add(currentParent);\n    currentParent = nodeById.get(currentParent)?.parentId ?? ROOT_CONTAINER_ID;\n  }\n  return chain;\n}\n\nfunction commonContainerId(\n  source: Node,\n  target: Node,\n  nodeById: Map<string, Node>\n): GridContainerId {\n  if (source.isGroup && isAncestorGroup(source.id, target, nodeById)) {\n    return source.parentId ?? ROOT_CONTAINER_ID;\n  }\n  if (target.isGroup && isAncestorGroup(target.id, source, nodeById)) {\n    return target.parentId ?? ROOT_CONTAINER_ID;\n  }\n  const targetContainers = new Set(containerChain(target, nodeById));\n  for (const containerId of containerChain(source, nodeById)) {\n    if (targetContainers.has(containerId)) {\n      return containerId;\n    }\n  }\n  return ROOT_CONTAINER_ID;\n}\n\nfunction oppositeCoordFor(rect: ReturnType<typeof rectForNode>, side: GridSide): number {\n  return side === 'left' || side === 'right' ? rect.cy : rect.cx;\n}\n\nfunction sideMidpoint(rect: ReturnType<typeof rectForNode>, side: GridSide): Point {\n  return side === 'left' || side === 'right'\n    ? { x: side === 'left' ? rect.left : rect.right, y: rect.cy }\n    : { x: rect.cx, y: side === 'top' ? rect.top : rect.bottom };\n}\n\nfunction tangentialCoordinate(point: Point, side: GridSide): number {\n  return side === 'left' || side === 'right' ? point.y : point.x;\n}\n\nfunction buildEndpointPlan(\n  endpoint: Node,\n  other: Node,\n  lcaContainerId: GridContainerId,\n  nodeById: Map<string, Node>,\n  edgeId: string,\n  role: 'source' | 'target'\n): EdgeEndpointPlan {\n  const chain: EdgeEndpointEntry[] = [];\n  const endpointRect = rectForNode(endpoint);\n  const otherRect = rectForNode(other);\n  const otherCenter = { x: other.x ?? 0, y: other.y ?? 0 };\n  let current = endpoint;\n\n  for (;;) {\n    const parentId = current.parentId ?? ROOT_CONTAINER_ID;\n    const parent = nodeById.get(parentId);\n    const currentCenter = { x: current.x ?? 0, y: current.y ?? 0 };\n    const dx = otherCenter.x - currentCenter.x;\n    const dy = otherCenter.y - currentCenter.y;\n    const titleAvoidanceTie =\n      dy < 0 &&\n      Math.abs(dx) <= PIXEL_EPSILON &&\n      Boolean((current.isGroup ? current.groupTitleRect : undefined) ?? parent?.groupTitleRect);\n    const directSideCandidates: GridSide[] = [];\n    if (Math.abs(Math.abs(dx) - Math.abs(dy)) <= PIXEL_EPSILON && Math.abs(dx) > PIXEL_EPSILON) {\n      directSideCandidates.push(dx >= 0 ? 'right' : 'left', dy >= 0 ? 'bottom' : 'top');\n    }\n    const topBlocked = Boolean(\n      (current.isGroup ? current.groupTitleRect : undefined) ?? parent?.groupTitleRect\n    );\n    const ambiguousSides = (\n      titleAvoidanceTie ? (['left', 'right'] as GridSide[]) : directSideCandidates\n    ).filter((candidate) => candidate !== 'top' || !topBlocked);\n    let side = preferredSide(current, otherCenter);\n    if (side === 'top' && parent?.groupTitleRect) {\n      side = dx >= 0 ? 'right' : 'left';\n    }\n    chain.push({\n      ownerId: current.id,\n      side,\n      demandKey: JSON.stringify([edgeId, role, current.id, side]),\n      oppositeCoord: oppositeCoordFor(otherRect, side),\n      preferredCoord: oppositeCoordFor(endpointRect, side),\n      compactPortal: current.id !== endpoint.id,\n      ambiguousSides: ambiguousSides.length > 1 ? ambiguousSides : undefined,\n      inner: chain.length\n        ? { demandKey: chain[chain.length - 1].demandKey, side: chain[chain.length - 1].side }\n        : undefined,\n    });\n\n    if (\n      current.isGroup &&\n      current.id === lcaContainerId &&\n      isAncestorGroup(current.id, other, nodeById)\n    ) {\n      return { chain, finalKind: 'boundary' };\n    }\n    if (parentId === lcaContainerId) {\n      return { chain, finalKind: 'item' };\n    }\n\n    if (!parent?.isGroup) {\n      throw gridError('GRID_INVALID_CONTAINMENT', `Missing parent group \"${parentId}\"`, {\n        traversedIds: chain.map((entry) => entry.ownerId),\n      });\n    }\n    current = parent;\n  }\n}\n\ninterface PairLane {\n  index: number;\n  size: number;\n  offset: number;\n  pairKey: string;\n}\n\nfunction buildPairLanes(edges: Edge[]): Map<string, PairLane> {\n  const byPair = new Map<string, Edge[]>();\n  for (const edge of edges) {\n    if (!edge.start || !edge.end) {\n      continue;\n    }\n    const pairKey =\n      edge.start < edge.end ? `${edge.start}|${edge.end}` : `${edge.end}|${edge.start}`;\n    if (!byPair.has(pairKey)) {\n      byPair.set(pairKey, []);\n    }\n    byPair.get(pairKey)!.push(edge);\n  }\n\n  const out = new Map<string, PairLane>();\n  for (const [pairKey, entries] of byPair) {\n    // Directed endpoint order and edge id make lane assignment stable even if input edges arrive in\n    // a different order.\n    entries.sort(\n      (a, b) =>\n        compareCodeUnits(`${a.start}|${a.end}`, `${b.start}|${b.end}`) ||\n        compareCodeUnits(a.id, b.id)\n    );\n    entries.forEach((edge, index) =>\n      out.set(edge.id, {\n        index,\n        size: entries.length,\n        offset: (index - (entries.length - 1) / 2) * LANE_SEPARATION_PX,\n        pairKey,\n      })\n    );\n  }\n  return out;\n}\n\nfunction resolveAmbiguousEndpointSides(plans: EdgeRoutePlan[], result: GridLayoutResult): void {\n  // Reserve geometrically preferred sides first. Equal-cost endpoint choices then use the legal\n  // side with the fewest strong reservations, preserving the original preference as a stable tie.\n  const reserved = new Map<string, number>();\n  const reservationKey = (ownerId: string, side: GridSide) => ownerSideKey(ownerId, side);\n  for (const plan of plans) {\n    for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n      if (!entry.ambiguousSides) {\n        const key = reservationKey(entry.ownerId, entry.side);\n        reserved.set(key, (reserved.get(key) ?? 0) + 1);\n      }\n    }\n  }\n\n  const resolveEndpoint = (\n    plan: EdgeRoutePlan,\n    endpoint: EdgeEndpointPlan,\n    role: 'source' | 'target'\n  ): void => {\n    const ambiguous = endpoint.chain.filter(({ ambiguousSides }) => ambiguousSides);\n    if (ambiguous.length === 0) {\n      return;\n    }\n    const legalSides = (['right', 'bottom', 'left', 'top'] as const).filter(\n      (side) =>\n        ambiguous.every((entry) => entry.ambiguousSides?.includes(side)) &&\n        ambiguous.every((entry) => {\n          const owner = result.forest.nodeById.get(entry.ownerId);\n          return owner !== undefined && sideInterval(owner, side) !== undefined;\n        })\n    );\n    const selected = legalSides.sort(\n      (a, b) =>\n        ambiguous.reduce(\n          (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, a)) ?? 0),\n          0\n        ) -\n          ambiguous.reduce(\n            (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, b)) ?? 0),\n            0\n          ) || Number(a !== ambiguous[0].side) - Number(b !== ambiguous[0].side)\n    )[0];\n    if (!selected) {\n      return;\n    }\n    for (const entry of ambiguous) {\n      entry.side = selected;\n      const key = reservationKey(entry.ownerId, selected);\n      reserved.set(key, (reserved.get(key) ?? 0) + 1);\n      const owner = result.forest.nodeById.get(entry.ownerId);\n      if (owner) {\n        entry.preferredCoord = oppositeCoordFor(rectForNode(owner), selected);\n      }\n    }\n    for (const [index, entry] of endpoint.chain.entries()) {\n      entry.demandKey = JSON.stringify([plan.edge.id, role, entry.ownerId, entry.side]);\n      entry.inner =\n        index > 0\n          ? {\n              demandKey: endpoint.chain[index - 1].demandKey,\n              side: endpoint.chain[index - 1].side,\n            }\n          : undefined;\n    }\n  };\n\n  const endpoints = plans\n    .flatMap((plan) => [\n      { plan, endpoint: plan.source, role: 'source' as const },\n      { plan, endpoint: plan.target, role: 'target' as const },\n    ])\n    .sort((a, b) =>\n      compareCodeUnits(\n        `${a.plan.edge.start ?? ''}|${a.plan.edge.end ?? ''}|${a.plan.edge.id}|${a.role}`,\n        `${b.plan.edge.start ?? ''}|${b.plan.edge.end ?? ''}|${b.plan.edge.id}|${b.role}`\n      )\n    );\n  for (const { plan, endpoint, role } of endpoints) {\n    resolveEndpoint(plan, endpoint, role);\n  }\n\n  for (const plan of plans) {\n    const sourceFinal = plan.source.chain.at(-1);\n    const targetFinal = plan.target.chain.at(-1);\n    const sourceOwner = sourceFinal ? result.forest.nodeById.get(sourceFinal.ownerId) : undefined;\n    const targetOwner = targetFinal ? result.forest.nodeById.get(targetFinal.ownerId) : undefined;\n    if (!sourceFinal || !targetFinal || !sourceOwner || !targetOwner) {\n      continue;\n    }\n    const sourcePoint = sideMidpoint(rectForNode(sourceOwner), sourceFinal.side);\n    const targetPoint = sideMidpoint(rectForNode(targetOwner), targetFinal.side);\n    for (const entry of plan.source.chain) {\n      entry.oppositeCoord = tangentialCoordinate(targetPoint, entry.side);\n    }\n    for (const entry of plan.target.chain) {\n      entry.oppositeCoord = tangentialCoordinate(sourcePoint, entry.side);\n    }\n  }\n}\n\nfunction collectRoutePlans(layout: LayoutData, result: GridLayoutResult): EdgeRoutePlan[] {\n  const nodeById = result.forest.nodeById;\n  const pairLanes = buildPairLanes(layout.edges);\n\n  const plans = layout.edges.map((edge) => {\n    const source = edge.start ? nodeById.get(edge.start) : undefined;\n    const target = edge.end ? nodeById.get(edge.end) : undefined;\n    if (!source || !target) {\n      throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${edge.id}\"`, {\n        edgeId: edge.id,\n        start: edge.start,\n        end: edge.end,\n      });\n    }\n    const lcaContainerId = commonContainerId(source, target, nodeById);\n    const pairLane = pairLanes.get(edge.id) ?? {\n      index: 0,\n      size: 1,\n      offset: 0,\n      pairKey: endpointPairKey(edge),\n    };\n    return {\n      edge,\n      lcaContainerId,\n      source: buildEndpointPlan(source, target, lcaContainerId, nodeById, edge.id, 'source'),\n      target: buildEndpointPlan(target, source, lcaContainerId, nodeById, edge.id, 'target'),\n      laneIndex: pairLane.index,\n      laneOffset: pairLane.offset,\n      bundleSize: pairLane.size,\n      pairKey: pairLane.pairKey,\n    };\n  });\n  resolveAmbiguousEndpointSides(plans, result);\n  return plans;\n}\n\nexport function assignCompactPortalCoordinates(\n  desired: readonly number[],\n  low: number,\n  high: number\n): number[] {\n  // Forward/backward constraint passes enforce minimum spacing; the final common shift preserves\n  // the requested center of mass as far as the legal interval permits.\n  const coordinates: number[] = [];\n  for (const [index, coordinate] of desired.entries()) {\n    coordinates.push(\n      index === 0\n        ? coordinate\n        : Math.max(coordinate, coordinates[index - 1] + MIN_PORT_SEPARATION_PX)\n    );\n  }\n  for (let index = coordinates.length - 1; index >= 0; index--) {\n    coordinates[index] = Math.min(\n      coordinates[index],\n      index === coordinates.length - 1 ? high : coordinates[index + 1] - MIN_PORT_SEPARATION_PX\n    );\n  }\n  const averageDesired = desired.reduce((sum, coordinate) => sum + coordinate, 0) / desired.length;\n  const averageAssigned =\n    coordinates.reduce((sum, coordinate) => sum + coordinate, 0) / coordinates.length;\n  const minimumShift = low - coordinates[0];\n  const maximumShift = high - coordinates[coordinates.length - 1];\n  const shift = clamp(averageDesired - averageAssigned, minimumShift, maximumShift);\n  return coordinates.map((coordinate) => coordinate + shift);\n}\n\nfunction assignDemandCoordinates(\n  plans: EdgeRoutePlan[],\n  result: GridLayoutResult,\n  endpointIncidentCounts: ReadonlyMap<string, number>\n): Map<string, number> {\n  // Allocate all demands for an owner side together. This prevents independently routed edges from\n  // selecting the same port and lets bundles retain symmetric lane offsets when capacity allows.\n  const nodeById = result.forest.nodeById;\n  const planByEdgeId = new Map(plans.map((plan) => [plan.edge.id, plan]));\n  const demandByKey = new Map<string, GridAttachmentDemand>();\n  for (const plan of plans) {\n    if (plan.edge.start === plan.edge.end) {\n      continue;\n    }\n    for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n      if (!demandByKey.has(entry.demandKey)) {\n        demandByKey.set(entry.demandKey, {\n          ownerId: entry.ownerId,\n          side: entry.side,\n          edgeId: plan.edge.id,\n          demandKey: entry.demandKey,\n          oppositeCoord: entry.oppositeCoord,\n          preferredCoord: entry.preferredCoord,\n          compactPortal: entry.compactPortal,\n          inner: entry.inner,\n        });\n      }\n    }\n  }\n\n  const byOwnerSide = new Map<\n    string,\n    { ownerId: string; side: GridSide; demands: GridAttachmentDemand[] }\n  >();\n  for (const demand of demandByKey.values()) {\n    const key = ownerSideKey(demand.ownerId, demand.side);\n    const group = byOwnerSide.get(key) ?? {\n      ownerId: demand.ownerId,\n      side: demand.side,\n      demands: [],\n    };\n    group.demands.push(demand);\n    byOwnerSide.set(key, group);\n  }\n\n  // Ports are placed before the compact portals that line up with them, innermost group first.\n  const depthOf = (ownerId: string): number => {\n    const owner = nodeById.get(ownerId);\n    return owner ? containerChain(owner, nodeById).length : 0;\n  };\n  const orderedOwnerSides = [...byOwnerSide.values()].sort(\n    (a, b) =>\n      Number(a.demands.every((d) => d.compactPortal)) -\n        Number(b.demands.every((d) => d.compactPortal)) || depthOf(b.ownerId) - depthOf(a.ownerId)\n  );\n  const assigned = new Map<string, number>();\n  for (const { ownerId, side, demands } of orderedOwnerSides) {\n    const owner = nodeById.get(ownerId);\n    if (!owner) {\n      continue;\n    }\n    const rect = rectForNode(owner);\n    let low =\n      side === 'left' || side === 'right'\n        ? rect.top + ROUTE_CLEARANCE_PX\n        : rect.left + ROUTE_CLEARANCE_PX;\n    const high =\n      side === 'left' || side === 'right'\n        ? rect.bottom - ROUTE_CLEARANCE_PX\n        : rect.right - ROUTE_CLEARANCE_PX;\n    if ((side === 'left' || side === 'right') && owner.groupTitleRect) {\n      low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);\n    }\n    const span = Math.max(0, high - low);\n    demands.sort(\n      (a, b) => a.oppositeCoord - b.oppositeCoord || compareCodeUnits(a.edgeId, b.edgeId)\n    );\n    const demandPlans = demands.map((demand) => planByEdgeId.get(demand.edgeId));\n    const pairKeys = new Set(demandPlans.map((plan) => plan?.pairKey));\n    const compactHierarchyPortals =\n      owner.isGroup && demands.every(({ compactPortal }) => compactPortal);\n    if (\n      !(compactHierarchyPortals && demands.length === 1) &&\n      pairKeys.size === 1 &&\n      demandPlans.every(\n        (plan) =>\n          plan &&\n          plan.bundleSize === demands.length &&\n          endpointIncidentCounts.get(plan.edge.start!) === plan.bundleSize &&\n          endpointIncidentCounts.get(plan.edge.end!) === plan.bundleSize\n      )\n    ) {\n      const center = (low + high) / 2;\n      const coordinates = demandPlans.map((plan) => center + plan!.laneOffset);\n      if (coordinates.every((coordinate) => coordinate >= low && coordinate <= high)) {\n        demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));\n        continue;\n      }\n    }\n    if (compactHierarchyPortals) {\n      const container = result.containers.get(owner.id);\n      const corridorCoordinates =\n        side === 'left' || side === 'right'\n          ? container?.horizontalCorridors\n          : container?.verticalCorridors;\n      const innerCoordinate = (demand: GridAttachmentDemand): number => {\n        const inner = demand.inner ? demandByKey.get(demand.inner.demandKey) : undefined;\n        const innerOwner = inner ? nodeById.get(inner.ownerId) : undefined;\n        const coordinate = inner ? assigned.get(inner.demandKey) : undefined;\n        if (!inner || !innerOwner || coordinate === undefined) {\n          return demand.preferredCoord;\n        }\n        const point = sideMidpoint(rectForNode(innerOwner), inner.side);\n        if (inner.side === 'left' || inner.side === 'right') {\n          point.y = coordinate;\n        } else {\n          point.x = coordinate;\n        }\n        return tangentialCoordinate(point, side);\n      };\n      const preferredCoordinate = (demand: GridAttachmentDemand): number => {\n        const innerCoord = demand.inner ? assigned.get(demand.inner.demandKey) : undefined;\n        const alignedWithInner =\n          demand.inner !== undefined &&\n          innerCoord !== undefined &&\n          (demand.inner.side === 'left' || demand.inner.side === 'right') ===\n            (side === 'left' || side === 'right');\n        const clamped = clamp(alignedWithInner ? innerCoord : demand.preferredCoord, low, high);\n        const nearest = corridorCoordinates?.reduce(\n          (best, coordinate) =>\n            Math.abs(coordinate - clamped) < Math.abs(best - clamped) ? coordinate : best,\n          corridorCoordinates[0]\n        );\n        return nearest !== undefined && Math.abs(nearest - clamped) <= PIXEL_EPSILON\n          ? nearest\n          : clamped;\n      };\n      if (demands.length === 1) {\n        assigned.set(demands[0].demandKey, preferredCoordinate(demands[0]));\n        continue;\n      }\n      if (span >= MIN_PORT_SEPARATION_PX * (demands.length - 1)) {\n        demands.sort(\n          (a, b) =>\n            innerCoordinate(a) - innerCoordinate(b) ||\n            a.oppositeCoord - b.oppositeCoord ||\n            compareCodeUnits(a.edgeId, b.edgeId)\n        );\n        const desired = demands.map(preferredCoordinate);\n        const coordinates = assignCompactPortalCoordinates(desired, low, high);\n        demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));\n        continue;\n      }\n    }\n    if (demands.length === 1 || span <= 0) {\n      assigned.set(demands[0].demandKey, (low + high) / 2);\n      continue;\n    }\n    const step = span / (demands.length - 1);\n    demands.forEach((demand, index) => {\n      assigned.set(demand.demandKey, low + step * index);\n    });\n  }\n\n  // Keep a nearly aligned hierarchy route on one exact coordinate. Sub-pixel differences between\n  // independently allocated endpoint and portal slots are otherwise normalized away as a diagonal,\n  // which unnecessarily demotes the route to sparse search.\n  for (const plan of plans) {\n    if (plan.bundleSize !== 1) {\n      continue;\n    }\n    const sourceFinal = plan.source.chain.at(-1);\n    const targetFinal = plan.target.chain.at(-1);\n    if (!sourceFinal || !targetFinal) {\n      continue;\n    }\n    const verticalSide = (side: GridSide) => side === 'left' || side === 'right';\n    if (verticalSide(sourceFinal.side) !== verticalSide(targetFinal.side)) {\n      continue;\n    }\n    const sourceCoord = assigned.get(sourceFinal.demandKey);\n    const targetCoord = assigned.get(targetFinal.demandKey);\n    if (\n      sourceCoord === undefined ||\n      targetCoord === undefined ||\n      Math.abs(sourceCoord - targetCoord) > PIXEL_EPSILON\n    ) {\n      continue;\n    }\n    const entries = [...plan.source.chain, ...plan.target.chain];\n    if (entries.some((entry) => verticalSide(entry.side) !== verticalSide(sourceFinal.side))) {\n      continue;\n    }\n    const alignedCoord = [sourceCoord, targetCoord].find((coordinate) =>\n      entries.every((entry) => {\n        const owner = nodeById.get(entry.ownerId);\n        const interval = owner ? sideInterval(owner, entry.side) : undefined;\n        return (\n          interval !== undefined &&\n          coordinate >= interval.low - PIXEL_EPSILON &&\n          coordinate <= interval.high + PIXEL_EPSILON\n        );\n      })\n    );\n    if (alignedCoord !== undefined) {\n      entries.forEach((entry) => assigned.set(entry.demandKey, alignedCoord));\n    }\n  }\n  return assigned;\n}\n\nexport interface EndpointCandidate {\n  ownerId: string;\n  side: GridSide;\n  port: RouterPoint;\n  connect: RouterPoint;\n  rank: number;\n  // Set only at owners that mix aligned and unaligned edges: whether the candidate uses the side the\n  // allocator assigned. The sparse search keeps those owners on their assigned side when it can.\n  onAssignedSide?: boolean;\n}\n\ninterface EndpointDemandEntry {\n  plan: EdgeRoutePlan;\n  role: 'source' | 'target';\n  opposite: Node;\n}\n\ninterface EndpointSlotAssignment {\n  side: GridSide;\n  coordinate: number;\n}\n\nexport function sideOrder(side: GridSide): number {\n  // Endpoint preference order is independent of topology's canonical record ordering.\n  return side === 'right' ? 0 : side === 'bottom' ? 1 : side === 'left' ? 2 : 3;\n}\n\nexport function sideInterval(\n  owner: Node,\n  side: GridSide\n): { low: number; high: number } | undefined {\n  const rect = rectForNode(owner);\n  if (side === 'top' && owner.groupTitleRect) {\n    return undefined;\n  }\n  let low =\n    side === 'left' || side === 'right'\n      ? rect.top + ROUTE_CLEARANCE_PX\n      : rect.left + ROUTE_CLEARANCE_PX;\n  const high =\n    side === 'left' || side === 'right'\n      ? rect.bottom - ROUTE_CLEARANCE_PX\n      : rect.right - ROUTE_CLEARANCE_PX;\n  if ((side === 'left' || side === 'right') && owner.groupTitleRect) {\n    low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);\n  }\n  return low <= high ? { low, high } : undefined;\n}\n\nfunction endpointPairKey(edge: Edge): string {\n  const start = edge.start ?? '';\n  const end = edge.end ?? '';\n  return start < end ? `${start}|${end}` : `${end}|${start}`;\n}\n\nfunction compareEndpointDemands(\n  a: EndpointDemandEntry,\n  b: EndpointDemandEntry,\n  side: GridSide\n): number {\n  const aRect = rectForNode(a.opposite);\n  const bRect = rectForNode(b.opposite);\n  const aCoord = side === 'left' || side === 'right' ? aRect.cy : aRect.cx;\n  const bCoord = side === 'left' || side === 'right' ? bRect.cy : bRect.cx;\n  return (\n    aCoord - bCoord ||\n    compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) ||\n    compareCodeUnits(\n      `${a.plan.edge.start}|${a.plan.edge.end}`,\n      `${b.plan.edge.start}|${b.plan.edge.end}`\n    ) ||\n    compareCodeUnits(a.plan.edge.id, b.plan.edge.id) ||\n    compareCodeUnits(a.role, b.role)\n  );\n}\n\nfunction endpointDemandKey(demand: EndpointDemandEntry): string {\n  return `${demand.plan.edge.id}:${demand.role}`;\n}\n\nfunction compareEndpointDemandIdentity(a: EndpointDemandEntry, b: EndpointDemandEntry): number {\n  return (\n    compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) ||\n    compareCodeUnits(\n      `${a.plan.edge.start}|${a.plan.edge.end}`,\n      `${b.plan.edge.start}|${b.plan.edge.end}`\n    ) ||\n    compareCodeUnits(a.plan.edge.id, b.plan.edge.id) ||\n    compareCodeUnits(a.role, b.role)\n  );\n}\n\nfunction preferredEndpointCoordinates(\n  owner: Node,\n  side: GridSide,\n  demands: readonly EndpointDemandEntry[]\n): ReadonlyMap<EndpointDemandEntry, number> {\n  const interval = sideInterval(owner, side);\n  if (!interval || demands.length === 0) {\n    return new Map();\n  }\n  const sorted = [...demands].sort((a, b) => compareEndpointDemands(a, b, side));\n  if (sorted.length === 1) {\n    const rect = rectForNode(owner);\n    const center = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n    return new Map([[sorted[0], clamp(center, interval.low, interval.high)]]);\n  }\n  if ((interval.high - interval.low) / (sorted.length - 1) < MIN_PORT_SEPARATION_PX) {\n    return new Map(\n      sorted.map((demand, index) => [\n        demand,\n        interval.low + (index * (interval.high - interval.low)) / (sorted.length - 1),\n      ])\n    );\n  }\n  const desired = sorted.map(({ opposite }) => {\n    const rect = rectForNode(opposite);\n    const coordinate = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n    return clamp(coordinate, interval.low, interval.high);\n  });\n  const coordinates = assignCompactPortalCoordinates(desired, interval.low, interval.high);\n  return new Map(sorted.map((demand, index) => [demand, coordinates[index]]));\n}\n\nfunction endpointSideCapacity(owner: Node, side: GridSide): number {\n  const interval = sideInterval(owner, side);\n  if (!interval) {\n    return 0;\n  }\n  return 1 + Math.floor((interval.high - interval.low) / MIN_PORT_SEPARATION_PX);\n}\n\nfunction endpointSidePreferences(owner: Node, demand: EndpointDemandEntry): GridSide[] {\n  const oppositeRect = rectForNode(demand.opposite);\n  const preferred = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });\n  return (['right', 'bottom', 'left', 'top'] as const)\n    .filter((side) => endpointSideCapacity(owner, side) > 0)\n    .sort((a, b) => {\n      if (a === preferred) {\n        return -1;\n      }\n      if (b === preferred) {\n        return 1;\n      }\n      const ownerRect = rectForNode(owner);\n      const aPoint = sideMidpoint(ownerRect, a);\n      const bPoint = sideMidpoint(ownerRect, b);\n      const aDistance = Math.abs(aPoint.x - oppositeRect.cx) + Math.abs(aPoint.y - oppositeRect.cy);\n      const bDistance = Math.abs(bPoint.x - oppositeRect.cx) + Math.abs(bPoint.y - oppositeRect.cy);\n      return aDistance - bDistance || sideOrder(a) - sideOrder(b);\n    });\n}\n\nfunction isAxisAlignedDemand(owner: Node, demand: EndpointDemandEntry): boolean {\n  const ownerRect = rectForNode(owner);\n  const oppositeRect = rectForNode(demand.opposite);\n  return (\n    Math.abs(ownerRect.cx - oppositeRect.cx) <= PIXEL_EPSILON ||\n    Math.abs(ownerRect.cy - oppositeRect.cy) <= PIXEL_EPSILON\n  );\n}\n\n// Places unaligned ports on a side that already carries fixed (aligned) ports. Each port takes the\n// legal coordinate nearest its desired one that keeps EDGE_CLEARANCE_PX from every other port, so the\n// aligned ports stay on their straight lines. Returns undefined when the side cannot fit them all.\nfunction placePortsBesideFixed(\n  owner: Node,\n  side: GridSide,\n  fixed: readonly number[],\n  movable: readonly EndpointDemandEntry[]\n): Map<EndpointDemandEntry, number> | undefined {\n  const interval = sideInterval(owner, side);\n  if (!interval) {\n    return undefined;\n  }\n  const placed = [...fixed];\n  const placements = new Map<EndpointDemandEntry, number>();\n  for (const demand of movable) {\n    const opposite = rectForNode(demand.opposite);\n    const desired = clamp(\n      side === 'left' || side === 'right' ? opposite.cy : opposite.cx,\n      interval.low,\n      interval.high\n    );\n    const candidates = [\n      desired,\n      interval.low,\n      interval.high,\n      ...placed.flatMap((coordinate) => [\n        coordinate - EDGE_CLEARANCE_PX,\n        coordinate + EDGE_CLEARANCE_PX,\n      ]),\n    ]\n      .filter(\n        (coordinate) =>\n          coordinate >= interval.low - PIXEL_EPSILON &&\n          coordinate <= interval.high + PIXEL_EPSILON &&\n          placed.every((other) => Math.abs(coordinate - other) >= EDGE_CLEARANCE_PX - PIXEL_EPSILON)\n      )\n      .sort((a, b) => Math.abs(a - desired) - Math.abs(b - desired) || a - b);\n    if (candidates.length === 0) {\n      return undefined;\n    }\n    placements.set(demand, candidates[0]);\n    placed.push(candidates[0]);\n  }\n  return placements;\n}\n\nfunction allocateEndpointSlots(\n  owner: Node,\n  demands: readonly EndpointDemandEntry[]\n): ReadonlyMap<string, EndpointSlotAssignment> {\n  // Aligned edges get first choice of their direct side and keep their straight port. Other edges\n  // prefer an unreserved side, or share a reserved side when their port can sit a full clearance\n  // away from the aligned ports. This stops a diagonal approach from displacing a straight one.\n  const assignedBySide = new Map<GridSide, EndpointDemandEntry[]>();\n  const capacities = new Map(\n    (['right', 'bottom', 'left', 'top'] as const).map((side) => [\n      side,\n      endpointSideCapacity(owner, side),\n    ])\n  );\n\n  const orderedDemands = [...demands].sort(compareEndpointDemandIdentity);\n  const alignedDemands = orderedDemands.filter((demand) => isAxisAlignedDemand(owner, demand));\n  const unalignedDemands = orderedDemands.filter((demand) => !isAxisAlignedDemand(owner, demand));\n  const reservedSides = new Set<GridSide>();\n  const alignedCoordinates = new Map<GridSide, number[]>();\n  const sharedPlacements = new Map<GridSide, Map<EndpointDemandEntry, number>>();\n  const hasCapacity = (candidate: GridSide) =>\n    (assignedBySide.get(candidate)?.length ?? 0) < (capacities.get(candidate) ?? 0);\n  const record = (demand: EndpointDemandEntry, side: GridSide) => {\n    const assigned = assignedBySide.get(side) ?? [];\n    assigned.push(demand);\n    assignedBySide.set(side, assigned);\n  };\n  const assignAligned = (demand: EndpointDemandEntry): void => {\n    const side = endpointSidePreferences(owner, demand).find(hasCapacity);\n    if (side) {\n      record(demand, side);\n      reservedSides.add(side);\n    }\n  };\n  const tryShareReservedSide = (demand: EndpointDemandEntry, side: GridSide): boolean => {\n    const shared = sharedPlacements.get(side) ?? new Map<EndpointDemandEntry, number>();\n    const placements = placePortsBesideFixed(\n      owner,\n      side,\n      [...(alignedCoordinates.get(side) ?? []), ...shared.values()],\n      [demand]\n    );\n    if (!placements) {\n      return false;\n    }\n    shared.set(demand, placements.get(demand)!);\n    sharedPlacements.set(side, shared);\n    record(demand, side);\n    return true;\n  };\n  const assignUnaligned = (demand: EndpointDemandEntry): void => {\n    const preferences = endpointSidePreferences(owner, demand).filter(hasCapacity);\n    const unreserved = preferences.find((candidate) => !reservedSides.has(candidate));\n    const sharable = preferences.find(\n      (candidate) =>\n        (unreserved === undefined ||\n          preferences.indexOf(candidate) < preferences.indexOf(unreserved)) &&\n        reservedSides.has(candidate) &&\n        tryShareReservedSide(demand, candidate)\n    );\n    if (sharable) {\n      return;\n    }\n    const side = unreserved ?? preferences[0];\n    if (side) {\n      record(demand, side);\n    }\n  };\n\n  for (const demand of alignedDemands) {\n    assignAligned(demand);\n  }\n  for (const [side, assigned] of assignedBySide) {\n    alignedCoordinates.set(side, [...preferredEndpointCoordinates(owner, side, assigned).values()]);\n  }\n  for (const demand of unalignedDemands) {\n    assignUnaligned(demand);\n  }\n\n  const assignments = new Map<string, EndpointSlotAssignment>();\n  for (const [side, assigned] of assignedBySide) {\n    const interval = sideInterval(owner, side);\n    if (!interval) {\n      continue;\n    }\n    const shared = sharedPlacements.get(side);\n    const fixedDemands = shared ? assigned.filter((demand) => !shared.has(demand)) : assigned;\n    const preferredCoordinates = new Map([\n      ...preferredEndpointCoordinates(owner, side, fixedDemands),\n      ...(shared ?? []),\n    ]);\n    const sorted = [...assigned].sort((a, b) => compareEndpointDemands(a, b, side));\n    for (const [index, demand] of sorted.entries()) {\n      const coordinate =\n        preferredCoordinates.get(demand) ??\n        (sorted.length === 1\n          ? (interval.low + interval.high) / 2\n          : interval.low + (index * (interval.high - interval.low)) / (sorted.length - 1));\n      assignments.set(endpointDemandKey(demand), { side, coordinate });\n    }\n  }\n  return assignments;\n}\n\nfunction endpointCandidates(\n  plan: EdgeRoutePlan,\n  role: 'source' | 'target',\n  demandsByOwner: ReadonlyMap<string, readonly EndpointDemandEntry[]>,\n  assignmentsByOwner: ReadonlyMap<string, ReadonlyMap<string, EndpointSlotAssignment>>,\n  coordinatedOwnerIds: ReadonlySet<string>,\n  result: GridLayoutResult\n): EndpointCandidate[] {\n  const ownerId = role === 'source' ? plan.edge.start! : plan.edge.end!;\n  const oppositeId = role === 'source' ? plan.edge.end! : plan.edge.start!;\n  const owner = result.forest.nodeById.get(ownerId);\n  const opposite = result.forest.nodeById.get(oppositeId);\n  if (!owner || !opposite) {\n    throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${plan.edge.id}\"`);\n  }\n  const oppositeRect = rectForNode(opposite);\n  const candidates: EndpointCandidate[] = [];\n  const candidateKeys = new Set<string>();\n\n  const assignment = assignmentsByOwner.get(ownerId)?.get(`${plan.edge.id}:${role}`);\n  const trackAssignedSide = coordinatedOwnerIds.has(ownerId) && assignment !== undefined;\n  const addCandidate = (side: GridSide, coordinate: number, rank: number): void => {\n    const interval = sideInterval(owner, side);\n    if (!interval || coordinate < interval.low || coordinate > interval.high) {\n      return;\n    }\n    const rect = rectForNode(owner);\n    const port =\n      side === 'left' || side === 'right'\n        ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n        : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n    const key = `${side}:${routingPointKey(port)}`;\n    if (candidateKeys.has(key)) {\n      return;\n    }\n    candidateKeys.add(key);\n    candidates.push({\n      ownerId,\n      side,\n      port,\n      connect: {\n        x:\n          port.x +\n          (side === 'left' ? -TERMINAL_APPROACH_PX : side === 'right' ? TERMINAL_APPROACH_PX : 0),\n        y:\n          port.y +\n          (side === 'top' ? -TERMINAL_APPROACH_PX : side === 'bottom' ? TERMINAL_APPROACH_PX : 0),\n      },\n      rank,\n      onAssignedSide: trackAssignedSide ? side === assignment.side : undefined,\n    });\n  };\n\n  // Negative ranks reserve precedence for the globally allocated slot and the bundle lane. The\n  // remaining geometric alternatives are re-ranked after deterministic sorting.\n  if (assignment && plan.bundleSize === 1) {\n    addCandidate(assignment.side, assignment.coordinate, -2);\n  }\n\n  if (plan.bundleSize > 1) {\n    const side = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });\n    const ownerRect = rectForNode(owner);\n    const center = side === 'left' || side === 'right' ? ownerRect.cy : ownerRect.cx;\n    addCandidate(side, center + plan.laneOffset, -1);\n  }\n\n  const ownerDemands = [...(demandsByOwner.get(ownerId) ?? [])];\n  for (const side of ['right', 'bottom', 'left', 'top'] as const) {\n    const interval = sideInterval(owner, side);\n    if (!interval) {\n      continue;\n    }\n    const coordinates = preferredEndpointCoordinates(owner, side, ownerDemands);\n    const demand = ownerDemands.find((entry) => entry.plan === plan && entry.role === role);\n    const coordinate = demand ? coordinates.get(demand) : undefined;\n    if (coordinate === undefined) {\n      continue;\n    }\n    const rect = rectForNode(owner);\n    const port =\n      side === 'left' || side === 'right'\n        ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n        : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n    const distance = Math.abs(port.x - oppositeRect.cx) + Math.abs(port.y - oppositeRect.cy);\n    addCandidate(side, coordinate, distance);\n  }\n\n  candidates.sort((a, b) => a.rank - b.rank || sideOrder(a.side) - sideOrder(b.side));\n  candidates.forEach((candidate, index) => {\n    candidate.rank = index;\n  });\n  return candidates;\n}\n\nexport function prepareEdgeRoutes(\n  layout: LayoutData,\n  result: GridLayoutResult\n): PreparedEdgeRoutes {\n  // Route order is a correctness input because committed routes constrain later bundle siblings.\n  // Harder hierarchy and loop routes go first, followed by fewer candidate combinations and stable\n  // lexical tie-breakers.\n  const plans = collectRoutePlans(layout, result);\n  const pairCounts = new Map<string, number>();\n  const endpointIncidentCounts = new Map<string, number>();\n  for (const plan of plans) {\n    const key = endpointPairKey(plan.edge);\n    pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);\n    if (plan.edge.start) {\n      endpointIncidentCounts.set(\n        plan.edge.start,\n        (endpointIncidentCounts.get(plan.edge.start) ?? 0) + 1\n      );\n    }\n    if (plan.edge.end && plan.edge.end !== plan.edge.start) {\n      endpointIncidentCounts.set(\n        plan.edge.end,\n        (endpointIncidentCounts.get(plan.edge.end) ?? 0) + 1\n      );\n    }\n  }\n  const eligiblePlans = plans.filter(\n    (plan) =>\n      plan.edge.start !== plan.edge.end &&\n      plan.source.chain.length === 1 &&\n      plan.target.chain.length === 1 &&\n      plan.source.finalKind === 'item' &&\n      plan.target.finalKind === 'item'\n  );\n  const endpointDemandsByOwner = new Map<string, EndpointDemandEntry[]>();\n  for (const plan of eligiblePlans) {\n    const source = result.forest.nodeById.get(plan.edge.start!);\n    const target = result.forest.nodeById.get(plan.edge.end!);\n    if (!source || !target) {\n      continue;\n    }\n    const sourceDemands = endpointDemandsByOwner.get(source.id) ?? [];\n    sourceDemands.push({ plan, role: 'source', opposite: target });\n    endpointDemandsByOwner.set(source.id, sourceDemands);\n    const targetDemands = endpointDemandsByOwner.get(target.id) ?? [];\n    targetDemands.push({ plan, role: 'target', opposite: source });\n    endpointDemandsByOwner.set(target.id, targetDemands);\n  }\n  const endpointAssignmentsByOwner = new Map(\n    [...endpointDemandsByOwner].map(([ownerId, demands]) => {\n      const owner = result.forest.nodeById.get(ownerId);\n      return [ownerId, owner ? allocateEndpointSlots(owner, demands) : new Map()] as const;\n    })\n  );\n  const coordinatedEndpointIds = new Set<string>();\n  const coordinatedOwnerIds = new Set<string>();\n  for (const [ownerId, demands] of endpointDemandsByOwner) {\n    const owner = result.forest.nodeById.get(ownerId);\n    if (!owner) {\n      continue;\n    }\n    const hasAligned = demands.some((demand) => isAxisAlignedDemand(owner, demand));\n    const hasUnaligned = demands.some((demand) => !isAxisAlignedDemand(owner, demand));\n    if (hasAligned && hasUnaligned) {\n      coordinatedOwnerIds.add(ownerId);\n      // The aligned edge already has its straight route, so only the others need the sparse search.\n      for (const demand of demands) {\n        if (!isAxisAlignedDemand(owner, demand)) {\n          coordinatedEndpointIds.add(demand.plan.edge.id);\n        }\n      }\n    }\n  }\n  const endpointCandidatesByEdge = new Map(\n    eligiblePlans.map((plan) => [\n      plan.edge.id,\n      {\n        sources: endpointCandidates(\n          plan,\n          'source',\n          endpointDemandsByOwner,\n          endpointAssignmentsByOwner,\n          coordinatedOwnerIds,\n          result\n        ),\n        targets: endpointCandidates(\n          plan,\n          'target',\n          endpointDemandsByOwner,\n          endpointAssignmentsByOwner,\n          coordinatedOwnerIds,\n          result\n        ),\n      },\n    ])\n  );\n  const endpointCandidateProducts = new Map(\n    [...endpointCandidatesByEdge].map(([edgeId, candidates]) => [\n      edgeId,\n      candidates.sources.length * candidates.targets.length,\n    ])\n  );\n  const routeClass = (plan: EdgeRoutePlan): number => {\n    const source = result.forest.nodeById.get(plan.edge.start!);\n    const target = result.forest.nodeById.get(plan.edge.end!);\n    if (plan.edge.start === plan.edge.end) {\n      return 0;\n    }\n    if (\n      (source?.isGroup && target && isAncestorGroup(source.id, target, result.forest.nodeById)) ||\n      (target?.isGroup && source && isAncestorGroup(target.id, source, result.forest.nodeById))\n    ) {\n      return 1;\n    }\n    if ((source?.parentId ?? ROOT_CONTAINER_ID) !== (target?.parentId ?? ROOT_CONTAINER_ID)) {\n      return 2;\n    }\n    return pairCounts.get(endpointPairKey(plan.edge))! > 1 ? 3 : 4;\n  };\n  const orderedPlans = [...plans].sort((a, b) => {\n    const aUnordered = endpointPairKey(a.edge);\n    const bUnordered = endpointPairKey(b.edge);\n    const aDirected = `${a.edge.start ?? ''}|${a.edge.end ?? ''}`;\n    const bDirected = `${b.edge.start ?? ''}|${b.edge.end ?? ''}`;\n    const aBoundaryCount = a.source.chain.length + a.target.chain.length - 2;\n    const bBoundaryCount = b.source.chain.length + b.target.chain.length - 2;\n    return (\n      routeClass(a) - routeClass(b) ||\n      bBoundaryCount - aBoundaryCount ||\n      (endpointCandidateProducts.get(a.edge.id) ?? 0) -\n        (endpointCandidateProducts.get(b.edge.id) ?? 0) ||\n      compareCodeUnits(aUnordered, bUnordered) ||\n      compareCodeUnits(aDirected, bDirected) ||\n      compareCodeUnits(a.edge.id, b.edge.id)\n    );\n  });\n  return {\n    plans,\n    eligiblePlans,\n    eligibleIds: new Set(eligiblePlans.map(({ edge }) => edge.id)),\n    orderedPlans,\n    demandCoords: assignDemandCoordinates(orderedPlans, result, endpointIncidentCounts),\n    endpointCandidatesByEdge,\n    endpointIncidentCounts,\n    coordinatedEndpointIds,\n  };\n}\n", "import type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline, PIXEL_EPSILON } from '../layout-utils/geometry.js';\nimport { rectForNode } from '../layout-utils/helpers.js';\nimport {\n  LANE_SEPARATION_PX,\n  TERMINAL_APPROACH_PX,\n  type EndpointCandidate,\n} from './routerPlanning.js';\nimport { ROUTE_CLEARANCE_PX } from './routerTopology.js';\nimport type {\n  GridContainerId,\n  GridLayoutResult,\n  GridOrientation,\n  RouterPoint,\n  RouterRect,\n} from './types.js';\nimport { isEdgeLabelNode } from './types.js';\n\n// Centralizes post-route validity checks so sparse routes, compatibility fallbacks, and bundle\n// retries all enforce the same obstacle-clearance and lane-separation contract.\nexport function isPairSeparationError(error: unknown): boolean {\n  if (!(error instanceof Error) || !('details' in error)) {\n    return false;\n  }\n  const details = error.details;\n  return (\n    typeof details === 'object' &&\n    details !== null &&\n    'reason' in details &&\n    details.reason === 'pair-separation'\n  );\n}\n\nexport function routerRect(node: Node): RouterRect {\n  const rect = rectForNode(node);\n  return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom };\n}\n\nfunction canonicalizeOrthogonalPolyline(points: readonly Point[]): Point[] | undefined {\n  if (points.length < 2 || points.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))) {\n    return undefined;\n  }\n\n  const collapsed: Point[] = [{ ...points[0] }];\n  for (let index = 1; index < points.length; index++) {\n    const point = points[index];\n    const previous = collapsed.at(-1)!;\n    const isNearDuplicate =\n      Math.abs(point.x - previous.x) <= PIXEL_EPSILON &&\n      Math.abs(point.y - previous.y) <= PIXEL_EPSILON;\n    if (!isNearDuplicate) {\n      collapsed.push({ ...point });\n      continue;\n    }\n    if (index !== points.length - 1) {\n      continue;\n    }\n    while (collapsed.length > 1) {\n      const beforePrevious = collapsed.at(-2)!;\n      if (\n        Math.abs(point.x - beforePrevious.x) > PIXEL_EPSILON ||\n        Math.abs(point.y - beforePrevious.y) > PIXEL_EPSILON\n      ) {\n        break;\n      }\n      collapsed.pop();\n    }\n    if (collapsed.length === 1) {\n      return undefined;\n    }\n    collapsed[collapsed.length - 1] = { ...point };\n  }\n  if (collapsed.length < 2) {\n    return undefined;\n  }\n\n  const orientations: GridOrientation[] = [];\n  for (let index = 0; index < collapsed.length - 1; index++) {\n    const a = collapsed[index];\n    const b = collapsed[index + 1];\n    const dx = Math.abs(b.x - a.x);\n    const dy = Math.abs(b.y - a.y);\n    if (dy <= PIXEL_EPSILON) {\n      orientations.push('H');\n    } else if (dx <= PIXEL_EPSILON) {\n      orientations.push('V');\n    } else {\n      return undefined;\n    }\n  }\n\n  const canonical = collapsed.map((point) => ({ ...point }));\n  for (let start = 0; start < orientations.length; ) {\n    const orientation = orientations[start];\n    let end = start + 1;\n    while (end < orientations.length && orientations[end] === orientation) {\n      end++;\n    }\n    const axis = orientation === 'H' ? 'y' : 'x';\n    if (\n      start === 0 &&\n      end === collapsed.length - 1 &&\n      collapsed[start][axis] !== collapsed[end][axis]\n    ) {\n      return undefined;\n    }\n    const coordinate = end === collapsed.length - 1 ? collapsed[end][axis] : collapsed[start][axis];\n    for (let pointIndex = start; pointIndex <= end; pointIndex++) {\n      if (Math.abs(collapsed[pointIndex][axis] - coordinate) > PIXEL_EPSILON) {\n        return undefined;\n      }\n      canonical[pointIndex][axis] = coordinate;\n    }\n    start = end;\n  }\n  return canonical;\n}\n\nfunction segmentEntersRect(a: Point, b: Point, rect: RouterRect): boolean {\n  if (a.y === b.y) {\n    return (\n      a.y > rect.top &&\n      a.y < rect.bottom &&\n      Math.max(a.x, b.x) > rect.left &&\n      Math.min(a.x, b.x) < rect.right\n    );\n  }\n  if (a.x === b.x) {\n    return (\n      a.x > rect.left &&\n      a.x < rect.right &&\n      Math.max(a.y, b.y) > rect.top &&\n      Math.min(a.y, b.y) < rect.bottom\n    );\n  }\n  return true;\n}\n\nfunction inflatedRect(node: Node): RouterRect {\n  const rect = routerRect(node);\n  return {\n    left: rect.left - ROUTE_CLEARANCE_PX,\n    right: rect.right + ROUTE_CLEARANCE_PX,\n    top: rect.top - ROUTE_CLEARANCE_PX,\n    bottom: rect.bottom + ROUTE_CLEARANCE_PX,\n  };\n}\n\nexport function validateSameContainerRoute(\n  points: readonly Point[],\n  source: Node,\n  target: Node,\n  containerId: GridContainerId,\n  result: GridLayoutResult\n): boolean {\n  // Terminal segments may touch their own endpoint rectangles, but must leave them directly and\n  // every other segment must remain outside clearance-inflated child geometry.\n  const canonical = canonicalizeOrthogonalPolyline(points);\n  if (!canonical) {\n    return false;\n  }\n  const normalized = normalizePolyline(canonical);\n  if (normalized.points.length < 2) {\n    return false;\n  }\n  if (\n    normalized.segments.length > 1 &&\n    (Math.abs(normalized.segments[0].a.x - normalized.segments[0].b.x) +\n      Math.abs(normalized.segments[0].a.y - normalized.segments[0].b.y) <\n      TERMINAL_APPROACH_PX ||\n      Math.abs(normalized.segments.at(-1)!.a.x - normalized.segments.at(-1)!.b.x) +\n        Math.abs(normalized.segments.at(-1)!.a.y - normalized.segments.at(-1)!.b.y) <\n        TERMINAL_APPROACH_PX)\n  ) {\n    return false;\n  }\n  const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n    (node) => !isEdgeLabelNode(node)\n  );\n  for (const obstacle of children) {\n    const rect = inflatedRect(obstacle);\n    for (let index = 0; index < normalized.points.length - 1; index++) {\n      const terminalObstacle =\n        (obstacle.id === source.id && index === 0) ||\n        (obstacle.id === target.id && index === normalized.points.length - 2);\n      if (terminalObstacle) {\n        if (\n          segmentEntersRect(\n            normalized.points[index],\n            normalized.points[index + 1],\n            routerRect(obstacle)\n          )\n        ) {\n          return false;\n        }\n        continue;\n      }\n      if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nexport function validateContainerSegment(\n  points: readonly Point[],\n  startOwnerId: string,\n  endOwnerId: string,\n  containerId: GridContainerId,\n  result: GridLayoutResult\n): boolean {\n  const canonical = canonicalizeOrthogonalPolyline(points);\n  if (!canonical) {\n    return false;\n  }\n  const normalized = normalizePolyline(canonical);\n  if (normalized.points.length < 2) {\n    return false;\n  }\n  const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n    (node) => !isEdgeLabelNode(node)\n  );\n  for (const obstacle of children) {\n    const rect = inflatedRect(obstacle);\n    for (let index = 0; index < normalized.points.length - 1; index++) {\n      const terminalObstacle =\n        (obstacle.id === startOwnerId && index === 0) ||\n        (obstacle.id === endOwnerId && index === normalized.points.length - 2);\n      if (terminalObstacle) {\n        if (\n          segmentEntersRect(\n            normalized.points[index],\n            normalized.points[index + 1],\n            routerRect(obstacle)\n          )\n        ) {\n          return false;\n        }\n        continue;\n      }\n      if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nexport interface OrthogonalSegment {\n  a: Point;\n  b: Point;\n  orientation: GridOrientation;\n}\n\nfunction segmentSpan(segment: OrthogonalSegment): { low: number; high: number } {\n  return segment.orientation === 'H'\n    ? { low: Math.min(segment.a.x, segment.b.x), high: Math.max(segment.a.x, segment.b.x) }\n    : { low: Math.min(segment.a.y, segment.b.y), high: Math.max(segment.a.y, segment.b.y) };\n}\n\nexport function nonterminalSegments(points: readonly Point[]): OrthogonalSegment[] {\n  const segments = normalizePolyline([...points])\n    .segments.filter((segment) => segment.orientation !== 'Z')\n    .map((segment) => ({\n      a: { ...segment.a },\n      b: { ...segment.b },\n      orientation: segment.orientation as GridOrientation,\n    }));\n  if (segments.length === 0) {\n    return [];\n  }\n  if (\n    segments.length === 1 &&\n    Math.abs(segments[0].a.x - segments[0].b.x) + Math.abs(segments[0].a.y - segments[0].b.y) <=\n      TERMINAL_APPROACH_PX * 2\n  ) {\n    return [];\n  }\n  // Pair lanes may share the short attachment stubs at nodes. Trim those stubs before measuring\n  // corridor overlap so only the independently routable interior is constrained.\n  const trim = (segment: OrthogonalSegment, atStart: boolean): void => {\n    if (segment.orientation === 'H') {\n      const direction = Math.sign(segment.b.x - segment.a.x);\n      if (atStart) {\n        segment.a.x += direction * TERMINAL_APPROACH_PX;\n      } else {\n        segment.b.x -= direction * TERMINAL_APPROACH_PX;\n      }\n    } else {\n      const direction = Math.sign(segment.b.y - segment.a.y);\n      if (atStart) {\n        segment.a.y += direction * TERMINAL_APPROACH_PX;\n      } else {\n        segment.b.y -= direction * TERMINAL_APPROACH_PX;\n      }\n    }\n  };\n  trim(segments[0], true);\n  trim(segments[segments.length - 1], false);\n  return segments.filter(({ a, b }) => a.x !== b.x || a.y !== b.y);\n}\n\nexport function pairSegmentsConflict(\n  candidate: OrthogonalSegment,\n  committed: OrthogonalSegment\n): boolean {\n  if (candidate.orientation !== committed.orientation) {\n    return false;\n  }\n  const first = segmentSpan(candidate);\n  const second = segmentSpan(committed);\n  const overlap = Math.max(0, Math.min(first.high, second.high) - Math.max(first.low, second.low));\n  if (overlap <= 0) {\n    return false;\n  }\n  const separation =\n    candidate.orientation === 'H'\n      ? Math.abs(candidate.a.y - committed.a.y)\n      : Math.abs(candidate.a.x - committed.a.x);\n  // Collinear overlap is illegal when lanes coincide for a meaningful distance or are closer than\n  // the configured lane spacing. Endpoint-only contact has zero overlap and remains legal.\n  return (\n    (separation === 0 && overlap >= LANE_SEPARATION_PX) ||\n    (separation > 0 && separation < LANE_SEPARATION_PX)\n  );\n}\n\nexport function routeSatisfiesPairConstraints(\n  points: readonly Point[],\n  pairRoutes: readonly (readonly Point[])[]\n): boolean {\n  const normalized = normalizePolyline([...points]).points;\n  const candidatePorts = [normalized[0], normalized.at(-1)!];\n  const candidateSegments = nonterminalSegments(normalized);\n  return pairRoutes.every((route) => {\n    const committed = normalizePolyline([...route]).points;\n    const committedPorts = [committed[0], committed.at(-1)!];\n    if (\n      candidatePorts.some((port) =>\n        committedPorts.some((other) => port.x === other.x && port.y === other.y)\n      )\n    ) {\n      return false;\n    }\n    return candidateSegments.every((candidate) =>\n      nonterminalSegments(committed).every(\n        (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)\n      )\n    );\n  });\n}\n\nexport function routeHasDistinctPairPorts(\n  points: readonly Point[],\n  pairRoutes: readonly (readonly Point[])[]\n): boolean {\n  const normalized = normalizePolyline([...points]).points;\n  const candidatePorts = [normalized[0], normalized.at(-1)!];\n  return pairRoutes.every((route) => {\n    const committed = normalizePolyline([...route]).points;\n    const committedPorts = [committed[0], committed.at(-1)!];\n    return !candidatePorts.some((port) =>\n      committedPorts.some((other) => port.x === other.x && port.y === other.y)\n    );\n  });\n}\n\nexport function pairArcAllowed(\n  from: RouterPoint,\n  to: RouterPoint,\n  pairRoutes: readonly (readonly Point[])[]\n): boolean {\n  const orientation: GridOrientation = from.y === to.y ? 'H' : 'V';\n  const candidate = { a: from, b: to, orientation };\n  return pairRoutes.every((route) =>\n    nonterminalSegments(route).every(\n      (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)\n    )\n  );\n}\n\nexport function endpointPairLowerBound(\n  source: EndpointCandidate,\n  target: EndpointCandidate\n): readonly [length: number, bends: number] {\n  // This admissible lower bound includes both terminal stubs and the minimum bend count implied by\n  // endpoint orientations; candidate-pair search can safely prune against it.\n  const sourceOrientation: GridOrientation =\n    source.side === 'left' || source.side === 'right' ? 'H' : 'V';\n  const targetOrientation: GridOrientation =\n    target.side === 'left' || target.side === 'right' ? 'H' : 'V';\n  const dx = Math.abs(source.connect.x - target.connect.x);\n  const dy = Math.abs(source.connect.y - target.connect.y);\n  let bends: number;\n  if (dx === 0 && dy === 0) {\n    bends = Number(sourceOrientation !== targetOrientation);\n  } else if (dx === 0 || dy === 0) {\n    const pathOrientation: GridOrientation = dx === 0 ? 'V' : 'H';\n    bends =\n      Number(sourceOrientation !== pathOrientation) + Number(targetOrientation !== pathOrientation);\n  } else {\n    bends = Math.min(\n      Number(sourceOrientation !== 'H') + 1 + Number(targetOrientation !== 'V'),\n      Number(sourceOrientation !== 'V') + 1 + Number(targetOrientation !== 'H')\n    );\n  }\n  return [TERMINAL_APPROACH_PX * 2 + dx + dy, bends];\n}\n", "import type { Point } from '../../../types.js';\nimport { nonterminalSegments, type OrthogonalSegment } from './routerConstraint.js';\nimport { EDGE_CLEARANCE_PX } from './routerTopology.js';\nimport type { GridOrientation, RouterPoint } from './types.js';\n\nfunction segmentsTooClose(candidate: OrthogonalSegment, committed: OrthogonalSegment): boolean {\n  if (candidate.orientation !== committed.orientation) {\n    return false;\n  }\n  const horizontal = candidate.orientation === 'H';\n  const lowOf = (segment: OrthogonalSegment) =>\n    horizontal ? Math.min(segment.a.x, segment.b.x) : Math.min(segment.a.y, segment.b.y);\n  const highOf = (segment: OrthogonalSegment) =>\n    horizontal ? Math.max(segment.a.x, segment.b.x) : Math.max(segment.a.y, segment.b.y);\n  const overlap =\n    Math.min(highOf(candidate), highOf(committed)) - Math.max(lowOf(candidate), lowOf(committed));\n  const separation = horizontal\n    ? Math.abs(candidate.a.y - committed.a.y)\n    : Math.abs(candidate.a.x - committed.a.x);\n  return overlap > 0 && separation < EDGE_CLEARANCE_PX;\n}\n\ninterface OccupiedSegment {\n  segment: OrthogonalSegment;\n  pairKey: string;\n}\n\ninterface OccupancyLogEntry {\n  orientation: GridOrientation;\n  coordinate: number;\n}\n\n/**\n * Container-scoped index of committed route segments.\n *\n * Routes from different edges must not share a corridor, so every routed edge registers its\n * nonterminal segments here and later candidates query it with the clearance rule\n * (`segmentsTooClose`). Segments are bucketed by their fixed coordinate so a query\n * only inspects lines within the clearance instead of every committed segment.\n *\n * Routes are append-only and can be truncated back to an earlier size, which is how bundle retries\n * roll back state.\n */\nexport class RouteOccupancyIndex {\n  private readonly lines: Record<'H' | 'V', Map<number, OccupiedSegment[]>> = {\n    H: new Map(),\n    V: new Map(),\n  };\n  private readonly sortedCoordinates: Record<'H' | 'V', number[] | undefined> = {\n    H: undefined,\n    V: undefined,\n  };\n  private readonly log: OccupancyLogEntry[] = [];\n\n  get size(): number {\n    return this.log.length;\n  }\n\n  add(route: readonly Point[], pairKey: string): void {\n    for (const segment of nonterminalSegments(route)) {\n      const orientation = segment.orientation as 'H' | 'V';\n      const coordinate = orientation === 'H' ? segment.a.y : segment.a.x;\n      const bucket = this.lines[orientation].get(coordinate);\n      if (bucket) {\n        bucket.push({ segment, pairKey });\n      } else {\n        this.lines[orientation].set(coordinate, [{ segment, pairKey }]);\n        this.sortedCoordinates[orientation] = undefined;\n      }\n      this.log.push({ orientation, coordinate });\n    }\n  }\n\n  truncate(size: number): void {\n    while (this.log.length > size) {\n      const { orientation, coordinate } = this.log.pop()!;\n      this.lines[orientation].get(coordinate)?.pop();\n    }\n  }\n\n  /** Reports whether a route shares a corridor with a committed route of another edge pair. */\n  conflictsWithRoute(route: readonly Point[], pairKey: string): boolean {\n    return nonterminalSegments(route).some((segment) => this.conflicts(segment, pairKey));\n  }\n\n  conflictsWithArc(from: RouterPoint, to: RouterPoint, pairKey: string): boolean {\n    const orientation: GridOrientation = from.y === to.y ? 'H' : 'V';\n    return this.conflicts({ a: from, b: to, orientation }, pairKey);\n  }\n\n  private conflicts(candidate: OrthogonalSegment, pairKey: string): boolean {\n    const orientation = candidate.orientation as string;\n    if (orientation !== 'H' && orientation !== 'V') {\n      return false;\n    }\n    const coordinate = orientation === 'H' ? candidate.a.y : candidate.a.x;\n    const coordinates = this.coordinatesFor(orientation);\n    let low = 0;\n    let high = coordinates.length;\n    while (low < high) {\n      const middle = (low + high) >> 1;\n      if (coordinates[middle] <= coordinate - EDGE_CLEARANCE_PX) {\n        low = middle + 1;\n      } else {\n        high = middle;\n      }\n    }\n    for (let index = low; index < coordinates.length; index++) {\n      const key = coordinates[index];\n      if (key >= coordinate + EDGE_CLEARANCE_PX) {\n        break;\n      }\n      for (const occupied of this.lines[orientation].get(key)!) {\n        if (occupied.pairKey !== pairKey && segmentsTooClose(candidate, occupied.segment)) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  private coordinatesFor(orientation: 'H' | 'V'): number[] {\n    return (this.sortedCoordinates[orientation] ??= [...this.lines[orientation].keys()].sort(\n      (a, b) => a - b\n    ));\n  }\n}\n", "import type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline } from '../layout-utils/geometry.js';\nimport { manhattanLength, polylineIntersectsRect, rectForNode } from '../layout-utils/helpers.js';\nimport type { Rect } from '../layout-utils/types.js';\nimport { isAncestorGroup } from './groups.js';\nimport {\n  GRID_LABEL_CLEARANCE,\n  GRID_LABEL_SPAN_MARGIN,\n  type GridLabelSpanRequirement,\n} from './labelGeometry.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport {\n  routerRect,\n  validateContainerSegment,\n  validateSameContainerRoute,\n} from './routerConstraint.js';\nimport { RouteOccupancyIndex } from './routerOccupancy.js';\nimport {\n  LANE_SEPARATION_PX,\n  TERMINAL_APPROACH_PX,\n  ownerGroupTitle,\n  ownerSideKey,\n  type EdgeEndpointPlan,\n  type EdgeRoutePlan,\n  type PreparedEdgeRoutes,\n} from './routerPlanning.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport {\n  buildContainerRoutingTopology,\n  DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n  derivePortalRanges,\n  ROUTE_CLEARANCE_PX,\n} from './routerTopology.js';\nimport type {\n  GridAttachment,\n  GridContainerId,\n  GridLayoutResult,\n  GridRoutingContext,\n  GridSide,\n  PairedPortal,\n  PortalRange,\n  RouterRect,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError, isEdgeLabelNode } from './types.js';\n\n// Deterministic corridor routing remains the validated fast path and the resource-limit fallback\n// while sparse visibility routing is incrementally adopted for harder routes.\nconst ROOT_OUTER_MARGIN = 24;\n\nexport const SELF_LOOP_PORT_GAP = 18;\n\nconst SELF_LOOP_APPROACH = 14;\n\n// validateLayout rejects endpoints within 3 px of a node corner.\nconst SELF_LOOP_CORNER_CLEARANCE = 4;\n\nconst SELF_LOOP_TRACK_GAP = 18;\n\nexport const SELF_LOOP_PORT_OFFSET_STEP = 4;\n\nexport interface PreparedRoutingModes {\n  overlapAvoidanceEnabled: boolean;\n  compatibilityFastRoutes: Map<string, Point[]>;\n  sparseHierarchyIds: Set<string>;\n  sparseLcaIds: Set<string>;\n  routedContainerIds: GridContainerId[];\n  routeOccupancy: Map<GridContainerId, RouteOccupancyIndex>;\n}\n\nconst MAX_PLANS_FOR_OVERLAP_AVOIDANCE = 64;\nconst MAX_FAST_ROUTE_SEPARATION_STEPS = 4;\n\n/**\n * Moves one interior segment of a minimal corridor route sideways until it no longer shares a\n * corridor with another edge's route. Shifting an interior segment keeps both terminal stubs and\n * the Manhattan length, so the result is accepted only if it still passes the caller's validation.\n */\nfunction separateRouteFromOccupied(\n  route: readonly Point[],\n  occupancy: RouteOccupancyIndex,\n  pairKey: string,\n  isAcceptable: (candidate: Point[]) => boolean\n): Point[] | undefined {\n  if (!occupancy.conflictsWithRoute(route, pairKey)) {\n    return [...route];\n  }\n  const points = normalizePolyline([...route]).points;\n  for (let step = 1; step <= MAX_FAST_ROUTE_SEPARATION_STEPS; step++) {\n    for (const sign of [1, -1]) {\n      const delta = sign * step * LANE_SEPARATION_PX;\n      for (let index = 1; index < points.length - 2; index++) {\n        const vertical = points[index].x === points[index + 1].x;\n        const shifted = points.map((point, pointIndex) =>\n          pointIndex === index || pointIndex === index + 1\n            ? vertical\n              ? { x: point.x + delta, y: point.y }\n              : { x: point.x, y: point.y + delta }\n            : point\n        );\n        if (!occupancy.conflictsWithRoute(shifted, pairKey) && isAcceptable(shifted)) {\n          return shifted;\n        }\n      }\n    }\n  }\n  return undefined;\n}\n\nfunction terminalStubsAreLongEnough(points: readonly Point[]): boolean {\n  const stub = (a: Point, b: Point) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n  return (\n    stub(points[0], points[1]) >= TERMINAL_APPROACH_PX &&\n    stub(points.at(-1)!, points.at(-2)!) >= TERMINAL_APPROACH_PX\n  );\n}\n\nexport function boundedAlternativePortalCoordinates(\n  selected: number,\n  low: number,\n  high: number,\n  corridors: readonly number[],\n  limit = 3\n): number[] {\n  // Retry the nearest established corridors first, then the range's canonical midpoint and ends.\n  // The hard limit bounds hierarchy retry fan-out and keeps output independent of map iteration.\n  const candidates = [\n    ...corridors\n      .filter((coordinate) => coordinate >= low && coordinate <= high)\n      .sort((a, b) => Math.abs(a - selected) - Math.abs(b - selected) || a - b),\n    (low + high) / 2,\n    low,\n    high,\n  ];\n  const seen = new Set<number>([selected]);\n  const alternatives: number[] = [];\n  for (const coordinate of candidates) {\n    if (seen.has(coordinate)) {\n      continue;\n    }\n    seen.add(coordinate);\n    alternatives.push(coordinate);\n    if (alternatives.length === limit) {\n      break;\n    }\n  }\n  return alternatives;\n}\n\nfunction equalPoint(a: Point, b: Point): boolean {\n  return Math.abs(a.x - b.x) <= 1e-6 && Math.abs(a.y - b.y) <= 1e-6;\n}\n\nexport function areExactlyAxisAligned(a: Point, b: Point): boolean {\n  return a.x === b.x || a.y === b.y;\n}\n\nfunction chooseIntermediateCoordinate(\n  values: number[],\n  start: number,\n  end: number,\n  variant: number\n): number {\n  const sorted = [...values].sort(\n    (a, b) =>\n      Math.abs(a - start) + Math.abs(a - end) - (Math.abs(b - start) + Math.abs(b - end)) || a - b\n  );\n  return sorted[Math.min(variant, Math.max(0, sorted.length - 1))] ?? (start + end) / 2;\n}\n\nfunction dedupeConsecutive(points: Point[]): Point[] {\n  const out: Point[] = [];\n  for (const point of points) {\n    if (out.length === 0 || !equalPoint(out[out.length - 1], point)) {\n      out.push(point);\n    }\n  }\n  return out;\n}\n\nexport function routeWithinContainer(\n  containerId: GridContainerId,\n  result: GridLayoutResult,\n  start: GridAttachment,\n  end: GridAttachment,\n  variant: number\n): Point[] {\n  // This compatibility router only chooses among measured grid corridors. `variant` selects the\n  // next deterministic dogleg when a bundle retry needs a different lane.\n  const container = result.containers.get(containerId);\n  if (!container) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container layout \"${containerId}\"`);\n  }\n\n  const points: Point[] = [start.port, start.connect];\n  if (start.orientation === 'V' && end.orientation === 'V') {\n    if (\n      !equalPoint(start.connect, end.connect) &&\n      Math.abs(start.connect.x - end.connect.x) > 1e-6\n    ) {\n      const y = chooseIntermediateCoordinate(\n        container.horizontalCorridors,\n        start.connect.y,\n        end.connect.y,\n        variant\n      );\n      points.push({ x: start.connect.x, y }, { x: end.connect.x, y });\n    } else if (\n      !equalPoint(start.connect, end.connect) &&\n      Math.abs(start.connect.y - end.connect.y) > 1e-6 &&\n      variant > 0\n    ) {\n      const alternateCorridors = container.verticalCorridors.filter(\n        (value) => Math.abs(value - start.connect.x) > 1e-6\n      );\n      const x = chooseIntermediateCoordinate(\n        alternateCorridors.length > 0 ? alternateCorridors : container.verticalCorridors,\n        start.connect.x,\n        end.connect.x,\n        variant - 1\n      );\n      points.push({ x, y: start.connect.y }, { x, y: end.connect.y });\n    }\n  } else if (start.orientation === 'H' && end.orientation === 'H') {\n    if (\n      !equalPoint(start.connect, end.connect) &&\n      Math.abs(start.connect.y - end.connect.y) > 1e-6\n    ) {\n      const x = chooseIntermediateCoordinate(\n        container.verticalCorridors,\n        start.connect.x,\n        end.connect.x,\n        variant\n      );\n      points.push({ x, y: start.connect.y }, { x, y: end.connect.y });\n    }\n  } else if (start.orientation === 'V' && end.orientation === 'H') {\n    points.push({ x: start.connect.x, y: end.connect.y });\n  } else {\n    points.push({ x: end.connect.x, y: start.connect.y });\n  }\n  points.push(end.connect, end.port);\n  return normalizePolyline(dedupeConsecutive(points)).points;\n}\n\nexport function itemAttachment(\n  ownerId: string,\n  side: GridSide,\n  demandKey: string,\n  containerId: GridContainerId,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>,\n  coordinate?: number\n): GridAttachment {\n  const owner = result.forest.nodeById.get(ownerId);\n  const item = result.itemMeta.get(ownerId);\n  if (!owner || !item || item.containerId !== containerId) {\n    throw gridError(\n      'GRID_ROUTE_NOT_FOUND',\n      `Missing item metadata for \"${ownerId}\" in \"${containerId}\"`\n    );\n  }\n\n  const rect = rectForNode(owner);\n  const coord =\n    coordinate ??\n    demandCoords.get(demandKey) ??\n    (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n  switch (side) {\n    case 'left':\n      return {\n        port: { x: rect.left, y: coord },\n        connect: { x: item.leftCorridorX, y: coord },\n        orientation: 'V',\n        side,\n      };\n    case 'right':\n      return {\n        port: { x: rect.right, y: coord },\n        connect: { x: item.rightCorridorX, y: coord },\n        orientation: 'V',\n        side,\n      };\n    case 'top':\n      return {\n        port: { x: coord, y: rect.top },\n        connect: { x: coord, y: item.topCorridorY },\n        orientation: 'H',\n        side,\n      };\n    case 'bottom':\n      return {\n        port: { x: coord, y: rect.bottom },\n        connect: { x: coord, y: item.bottomCorridorY },\n        orientation: 'H',\n        side,\n      };\n  }\n}\n\nexport function boundaryAttachment(\n  containerId: GridContainerId,\n  side: GridSide,\n  demandKey: string,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>\n): GridAttachment {\n  const owner = result.forest.nodeById.get(containerId);\n  const container = result.containers.get(containerId);\n  if (!owner || !container) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing boundary metadata for \"${containerId}\"`);\n  }\n  const rect = rectForNode(owner);\n  const coord =\n    demandCoords.get(demandKey) ?? (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n  switch (side) {\n    case 'left':\n      return {\n        port: { x: rect.left, y: coord },\n        connect: { x: container.verticalCorridors[0], y: coord },\n        orientation: 'V',\n        side,\n      };\n    case 'right':\n      return {\n        port: { x: rect.right, y: coord },\n        connect: {\n          x: container.verticalCorridors[container.verticalCorridors.length - 1],\n          y: coord,\n        },\n        orientation: 'V',\n        side,\n      };\n    case 'top':\n      return {\n        port: { x: coord, y: rect.top },\n        connect: { x: coord, y: container.horizontalCorridors[0] },\n        orientation: 'H',\n        side,\n      };\n    case 'bottom':\n      return {\n        port: { x: coord, y: rect.bottom },\n        connect: {\n          x: coord,\n          y: container.horizontalCorridors[container.horizontalCorridors.length - 1],\n        },\n        orientation: 'H',\n        side,\n      };\n  }\n}\n\nexport interface SegmentAttachment extends GridAttachment {\n  ownerId: string;\n}\n\nexport interface SegmentAttachmentAlternative {\n  attachment: SegmentAttachment;\n  select: () => void;\n}\n\nfunction portalBoundaryPoint(portal: PairedPortal): Point {\n  return {\n    x: (portal.interior.x + portal.exterior.x) / 2,\n    y: (portal.interior.y + portal.exterior.y) / 2,\n  };\n}\n\nexport function portalAttachment(portal: PairedPortal, interior: boolean): SegmentAttachment {\n  // The visible port is the group boundary midpoint; search starts on one side of the clearance\n  // transition so each container topology remains independent.\n  return {\n    ownerId: portal.ownerId,\n    port: portalBoundaryPoint(portal),\n    connect: interior ? portal.interior : portal.exterior,\n    orientation: portal.side === 'left' || portal.side === 'right' ? 'V' : 'H',\n    side: portal.side,\n  };\n}\n\nexport function groupBoundaryEndpointAttachment(\n  ownerId: string,\n  side: GridSide,\n  demandKey: string,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>\n): SegmentAttachment {\n  const owner = result.forest.nodeById.get(ownerId);\n  if (!owner?.isGroup) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing group endpoint \"${ownerId}\"`);\n  }\n  const rect = rectForNode(owner);\n  const coordinate =\n    demandCoords.get(demandKey) ?? (side === 'left' || side === 'right' ? rect.cy : rect.cx);\n  const port =\n    side === 'left' || side === 'right'\n      ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n      : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n  return {\n    ownerId,\n    port,\n    connect: {\n      x:\n        port.x +\n        (side === 'left' ? TERMINAL_APPROACH_PX : side === 'right' ? -TERMINAL_APPROACH_PX : 0),\n      y:\n        port.y +\n        (side === 'top' ? TERMINAL_APPROACH_PX : side === 'bottom' ? -TERMINAL_APPROACH_PX : 0),\n    },\n    orientation: side === 'left' || side === 'right' ? 'V' : 'H',\n    side,\n  };\n}\n\nexport function reversePoints(points: Point[]): Point[] {\n  return [...points].reverse();\n}\n\nexport function combinePointChains(chains: Point[][]): Point[] {\n  const points: Point[] = [];\n  for (const chain of chains) {\n    for (const point of chain) {\n      if (points.length === 0 || !equalPoint(points[points.length - 1], point)) {\n        points.push(point);\n      }\n    }\n  }\n  return normalizePolyline(points).points;\n}\n\nfunction routeSelfLoop(owner: Node, side: GridSide, index: number, demandCoord: number): Point[] {\n  const rect = rectForNode(owner);\n  const depth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;\n  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n  switch (side) {\n    case 'right': {\n      const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n      const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n      return normalizePolyline([\n        { x: rect.right, y: startY },\n        { x: rect.right + SELF_LOOP_APPROACH, y: startY },\n        { x: rect.right + depth, y: startY },\n        { x: rect.right + depth, y: endY },\n        { x: rect.right + SELF_LOOP_APPROACH, y: endY },\n        { x: rect.right, y: endY },\n      ]).points;\n    }\n    case 'left': {\n      const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n      const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n      return normalizePolyline([\n        { x: rect.left, y: startY },\n        { x: rect.left - SELF_LOOP_APPROACH, y: startY },\n        { x: rect.left - depth, y: startY },\n        { x: rect.left - depth, y: endY },\n        { x: rect.left - SELF_LOOP_APPROACH, y: endY },\n        { x: rect.left, y: endY },\n      ]).points;\n    }\n    case 'top': {\n      const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n      const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n      return normalizePolyline([\n        { x: startX, y: rect.top },\n        { x: startX, y: rect.top - SELF_LOOP_APPROACH },\n        { x: startX, y: rect.top - depth },\n        { x: endX, y: rect.top - depth },\n        { x: endX, y: rect.top - SELF_LOOP_APPROACH },\n        { x: endX, y: rect.top },\n      ]).points;\n    }\n    case 'bottom': {\n      const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n      const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n      return normalizePolyline([\n        { x: startX, y: rect.bottom },\n        { x: startX, y: rect.bottom + SELF_LOOP_APPROACH },\n        { x: startX, y: rect.bottom + depth },\n        { x: endX, y: rect.bottom + depth },\n        { x: endX, y: rect.bottom + SELF_LOOP_APPROACH },\n        { x: endX, y: rect.bottom },\n      ]).points;\n    }\n  }\n}\n\nexport function labelAwareSelfLoopCandidates(\n  owner: Node,\n  side: GridSide,\n  index: number,\n  demandCoord: number,\n  requirement: GridLabelSpanRequirement\n): Point[][] {\n  const rect = rectForNode(owner);\n  const baseDepth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;\n  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n  const baseSpan = SELF_LOOP_PORT_GAP + portOffset * 2;\n  const verticalSide = side === 'left' || side === 'right';\n  const span = Math.max(\n    baseSpan,\n    (verticalSide ? requirement.cross : requirement.along) +\n      GRID_LABEL_CLEARANCE * 2 +\n      GRID_LABEL_SPAN_MARGIN\n  );\n  const depth = Math.max(\n    baseDepth,\n    (verticalSide ? requirement.along : requirement.cross) / 2 + GRID_LABEL_CLEARANCE\n  );\n  const interval = verticalSide ? [rect.top, rect.bottom] : [rect.left, rect.right];\n  const directStart = demandCoord - span / 2;\n  const directEnd = demandCoord + span / 2;\n\n  if (\n    directStart - interval[0] >= SELF_LOOP_CORNER_CLEARANCE &&\n    interval[1] - directEnd >= SELF_LOOP_CORNER_CLEARANCE\n  ) {\n    switch (side) {\n      case 'right':\n        return [\n          normalizePolyline([\n            { x: rect.right, y: directStart },\n            { x: rect.right + depth, y: directStart },\n            { x: rect.right + depth, y: directEnd },\n            { x: rect.right, y: directEnd },\n          ]).points,\n        ];\n      case 'left':\n        return [\n          normalizePolyline([\n            { x: rect.left, y: directStart },\n            { x: rect.left - depth, y: directStart },\n            { x: rect.left - depth, y: directEnd },\n            { x: rect.left, y: directEnd },\n          ]).points,\n        ];\n      case 'top':\n        return [\n          normalizePolyline([\n            { x: directStart, y: rect.top },\n            { x: directStart, y: rect.top - depth },\n            { x: directEnd, y: rect.top - depth },\n            { x: directEnd, y: rect.top },\n          ]).points,\n        ];\n      case 'bottom':\n        return [\n          normalizePolyline([\n            { x: directStart, y: rect.bottom },\n            { x: directStart, y: rect.bottom + depth },\n            { x: directEnd, y: rect.bottom + depth },\n            { x: directEnd, y: rect.bottom },\n          ]).points,\n        ];\n    }\n  }\n\n  const portStart = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;\n  const portEnd = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;\n  if (portStart < interval[0] || portEnd > interval[1]) {\n    return [];\n  }\n  const outerStart = demandCoord - span / 2;\n  const outerEnd = demandCoord + span / 2;\n  const shoulderApproach = Math.max(SELF_LOOP_APPROACH, TERMINAL_APPROACH_PX);\n  // Keep the label clear of the return shoulders as well as the owner.\n  const shoulderDepth = Math.max(\n    depth,\n    shoulderApproach +\n      (verticalSide ? requirement.along : requirement.cross) / 2 +\n      GRID_LABEL_CLEARANCE\n  );\n  switch (side) {\n    case 'right':\n      return [\n        normalizePolyline([\n          { x: rect.right, y: portStart },\n          { x: rect.right + shoulderApproach, y: portStart },\n          { x: rect.right + shoulderApproach, y: outerStart },\n          { x: rect.right + shoulderDepth, y: outerStart },\n          { x: rect.right + shoulderDepth, y: outerEnd },\n          { x: rect.right + shoulderApproach, y: outerEnd },\n          { x: rect.right + shoulderApproach, y: portEnd },\n          { x: rect.right, y: portEnd },\n        ]).points,\n      ];\n    case 'left':\n      return [\n        normalizePolyline([\n          { x: rect.left, y: portStart },\n          { x: rect.left - shoulderApproach, y: portStart },\n          { x: rect.left - shoulderApproach, y: outerStart },\n          { x: rect.left - shoulderDepth, y: outerStart },\n          { x: rect.left - shoulderDepth, y: outerEnd },\n          { x: rect.left - shoulderApproach, y: outerEnd },\n          { x: rect.left - shoulderApproach, y: portEnd },\n          { x: rect.left, y: portEnd },\n        ]).points,\n      ];\n    case 'top':\n      return [\n        normalizePolyline([\n          { x: portStart, y: rect.top },\n          { x: portStart, y: rect.top - shoulderApproach },\n          { x: outerStart, y: rect.top - shoulderApproach },\n          { x: outerStart, y: rect.top - shoulderDepth },\n          { x: outerEnd, y: rect.top - shoulderDepth },\n          { x: outerEnd, y: rect.top - shoulderApproach },\n          { x: portEnd, y: rect.top - shoulderApproach },\n          { x: portEnd, y: rect.top },\n        ]).points,\n      ];\n    case 'bottom':\n      return [\n        normalizePolyline([\n          { x: portStart, y: rect.bottom },\n          { x: portStart, y: rect.bottom + shoulderApproach },\n          { x: outerStart, y: rect.bottom + shoulderApproach },\n          { x: outerStart, y: rect.bottom + shoulderDepth },\n          { x: outerEnd, y: rect.bottom + shoulderDepth },\n          { x: outerEnd, y: rect.bottom + shoulderApproach },\n          { x: portEnd, y: rect.bottom + shoulderApproach },\n          { x: portEnd, y: rect.bottom },\n        ]).points,\n      ];\n  }\n}\n\nexport function orderedSelfLoopSides(\n  node: Node,\n  counts: Map<string, number>,\n  selfLoopCounts: Map<string, number>\n): GridSide[] {\n  const sides: GridSide[] =\n    node.isGroup && ownerGroupTitle(node)\n      ? ['left', 'right', 'bottom']\n      : ['left', 'right', 'top', 'bottom'];\n  return sides.sort((a, b) => {\n    const aCount =\n      (counts.get(ownerSideKey(node.id, a)) ?? 0) + (selfLoopCounts.get(`${node.id}:${a}`) ?? 0);\n    const bCount =\n      (counts.get(ownerSideKey(node.id, b)) ?? 0) + (selfLoopCounts.get(`${node.id}:${b}`) ?? 0);\n    return aCount - bCount;\n  });\n}\n\nfunction selfLoopObstacles(owner: Node, result: GridLayoutResult): Rect[] {\n  const obstacles: Rect[] = [];\n  for (const node of result.forest.nodeById.values()) {\n    if (node.id !== owner.id && !node.isGroup && node.x !== undefined && node.y !== undefined) {\n      obstacles.push(rectForNode(node));\n    }\n    if (node.id !== owner.id && node.groupTitleRect) {\n      const { left, right, top, bottom } = node.groupTitleRect;\n      obstacles.push({\n        cx: (left + right) / 2,\n        cy: (top + bottom) / 2,\n        left,\n        right,\n        top,\n        bottom,\n      });\n    }\n  }\n  return obstacles;\n}\n\nexport function routeObstacleClearSelfLoop(\n  owner: Node,\n  ownerSideCounts: Map<string, number>,\n  selfLoopCounts: Map<string, number>,\n  result: GridLayoutResult,\n  labelRequirement?: GridLabelSpanRequirement,\n  metrics?: GridRoutingInstrumentation\n): { points: Point[]; side: GridSide; index: number } {\n  // Side load determines preference, but fixed side ordering breaks ties deterministically.\n  const rect = rectForNode(owner);\n  const obstacles = selfLoopObstacles(owner, result);\n  for (const side of orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts)) {\n    const countKey = `${owner.id}:${side}`;\n    const index = selfLoopCounts.get(countKey) ?? 0;\n    const demandCoord = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n    const candidates = labelRequirement\n      ? labelAwareSelfLoopCandidates(owner, side, index, demandCoord, labelRequirement)\n      : [routeSelfLoop(owner, side, index, demandCoord)];\n    if (labelRequirement && metrics) {\n      metrics.labelAwareSelfLoopCandidates += candidates.length;\n    }\n    for (const points of candidates) {\n      if (!obstacles.some((obstacle) => polylineIntersectsRect(points, obstacle))) {\n        return { points, side, index };\n      }\n    }\n  }\n  throw gridError('GRID_ROUTE_NOT_FOUND', `No obstacle-clear self-loop route for \"${owner.id}\"`, {\n    nodeId: owner.id,\n  });\n}\n\nexport function rootContainerMeta(result: GridLayoutResult): void {\n  if (result.containers.has(ROOT_CONTAINER_ID)) {\n    return;\n  }\n  let minLeft = 0;\n  let maxRight = 0;\n  let minTop = 0;\n  let maxBottom = 0;\n  let first = true;\n  for (const item of result.itemMeta.values()) {\n    if (item.containerId !== ROOT_CONTAINER_ID) {\n      continue;\n    }\n    if (first) {\n      minLeft = item.cellLeft;\n      maxRight = item.cellLeft + item.cellWidth;\n      minTop = item.cellTop;\n      maxBottom = item.cellTop + item.cellHeight;\n      first = false;\n    } else {\n      minLeft = Math.min(minLeft, item.cellLeft);\n      maxRight = Math.max(maxRight, item.cellLeft + item.cellWidth);\n      minTop = Math.min(minTop, item.cellTop);\n      maxBottom = Math.max(maxBottom, item.cellTop + item.cellHeight);\n    }\n  }\n\n  const horizontalCorridors = new Set<number>([\n    minTop - ROOT_OUTER_MARGIN,\n    maxBottom + ROOT_OUTER_MARGIN,\n  ]);\n  // The synthetic root has no node bounds, so derive its routable domain from root cells and keep\n  // an outer track available for routes that must pass around the whole diagram.\n  const verticalCorridors = new Set<number>([\n    minLeft - ROOT_OUTER_MARGIN,\n    maxRight + ROOT_OUTER_MARGIN,\n  ]);\n  for (const item of result.itemMeta.values()) {\n    if (item.containerId !== ROOT_CONTAINER_ID) {\n      continue;\n    }\n    horizontalCorridors.add(item.topCorridorY);\n    horizontalCorridors.add(item.bottomCorridorY);\n    verticalCorridors.add(item.leftCorridorX);\n    verticalCorridors.add(item.rightCorridorX);\n  }\n  result.containers.set(ROOT_CONTAINER_ID, {\n    id: ROOT_CONTAINER_ID,\n    left: minLeft - ROOT_OUTER_MARGIN,\n    top: minTop - ROOT_OUTER_MARGIN,\n    width: maxRight - minLeft + ROOT_OUTER_MARGIN * 2,\n    height: maxBottom - minTop + ROOT_OUTER_MARGIN * 2,\n    contentLeft: minLeft,\n    contentTop: minTop,\n    contentRight: maxRight,\n    contentBottom: maxBottom,\n    verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),\n    horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b),\n  });\n}\n\nfunction containerBounds(containerId: GridContainerId, result: GridLayoutResult): RouterRect {\n  const container = result.containers.get(containerId);\n  if (!container) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container layout \"${containerId}\"`);\n  }\n  if (containerId === ROOT_CONTAINER_ID) {\n    const rootItems = [...result.itemMeta.values()].filter(\n      ({ containerId: ownerContainerId }) => ownerContainerId === ROOT_CONTAINER_ID\n    );\n    if (rootItems.length > 0) {\n      return {\n        left: Math.min(...rootItems.map(({ cellLeft }) => cellLeft)) - ROOT_OUTER_MARGIN,\n        right:\n          Math.max(...rootItems.map(({ cellLeft, cellWidth }) => cellLeft + cellWidth)) +\n          ROOT_OUTER_MARGIN,\n        top: Math.min(...rootItems.map(({ cellTop }) => cellTop)) - ROOT_OUTER_MARGIN,\n        bottom:\n          Math.max(...rootItems.map(({ cellTop, cellHeight }) => cellTop + cellHeight)) +\n          ROOT_OUTER_MARGIN,\n      };\n    }\n    return {\n      left: container.left,\n      right: container.left + container.width,\n      top: container.top,\n      bottom: container.top + container.height,\n    };\n  }\n  const owner = result.forest.nodeById.get(containerId);\n  if (!owner) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing container owner \"${containerId}\"`);\n  }\n  const ownerBounds = routerRect(owner);\n  return {\n    left: ownerBounds.left + ROUTE_CLEARANCE_PX,\n    right: ownerBounds.right - ROUTE_CLEARANCE_PX,\n    top: ownerBounds.top + ROUTE_CLEARANCE_PX,\n    bottom: ownerBounds.bottom - ROUTE_CLEARANCE_PX,\n  };\n}\n\nfunction portalCoordinate(bounds: RouterRect, side: GridSide, interior: boolean): number {\n  const boundary =\n    side === 'left'\n      ? bounds.left\n      : side === 'right'\n        ? bounds.right\n        : side === 'top'\n          ? bounds.top\n          : bounds.bottom;\n  const towardInterior = side === 'left' || side === 'top' ? 1 : -1;\n  return boundary + towardInterior * ROUTE_CLEARANCE_PX * (interior ? 1 : -1);\n}\n\nfunction containerPortalRanges(\n  containerId: GridContainerId,\n  result: GridLayoutResult\n): PortalRange[] {\n  const ranges: PortalRange[] = [];\n  if (containerId !== ROOT_CONTAINER_ID) {\n    const owner = result.forest.nodeById.get(containerId);\n    if (owner) {\n      const bounds = routerRect(owner);\n      ranges.push(\n        ...derivePortalRanges(containerId, bounds, owner.groupTitleRect).map((range) => ({\n          ...range,\n          coordinate: portalCoordinate(bounds, range.side, true),\n        }))\n      );\n    }\n  }\n  for (const child of result.forest.childrenByParent.get(containerId) ?? []) {\n    if (!child.isGroup) {\n      continue;\n    }\n    const bounds = routerRect(child);\n    ranges.push(\n      ...derivePortalRanges(child.id, bounds, child.groupTitleRect).map((range) => ({\n        ...range,\n        coordinate: portalCoordinate(bounds, range.side, false),\n      }))\n    );\n  }\n  return ranges;\n}\n\nexport function buildRoutingContext(\n  containerIds: readonly GridContainerId[],\n  result: GridLayoutResult,\n  metrics: GridRoutingInstrumentation | undefined,\n  options: GridRoutingTestOptions\n): GridRoutingContext {\n  // Build each immutable container topology once. Per-edge endpoints are added later as cheap\n  // overlays, avoiding repeated obstacle sweeps for large diagrams.\n  const context: GridRoutingContext = {\n    topologies: new Map(),\n    fallbackContainers: new Map(),\n    searchBudget: { expandedStates: 0 },\n    searchBudgetWarningEmitted: false,\n    baseEstimatedBytes: 0,\n    metrics,\n  };\n  let estimatedBytes = 0;\n  for (const containerId of [...new Set(containerIds)].sort()) {\n    const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(\n      (node) => !isEdgeLabelNode(node)\n    );\n    const title = result.forest.nodeById.get(containerId)?.groupTitleRect;\n    try {\n      const topology = buildContainerRoutingTopology(\n        {\n          containerId,\n          bounds: containerBounds(containerId, result),\n          obstacles: children.map((node) => ({ id: node.id, bounds: routerRect(node) })),\n          titleExclusions: title\n            ? [{ id: `${containerId}:title`, bounds: { ...title } }]\n            : undefined,\n          portalRanges: containerPortalRanges(containerId, result),\n        },\n        { caps: options.topologyCaps }\n      );\n      const invocationMemoryCap =\n        options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES;\n      if (estimatedBytes + topology.estimatedBytes > invocationMemoryCap) {\n        // Keep the invocation-wide cap honest: an individually valid topology may still exceed the\n        // aggregate budget when combined with topologies already retained by this routing session.\n        context.fallbackContainers.set(containerId, 'estimated_memory_cap');\n        continue;\n      }\n      estimatedBytes += topology.estimatedBytes;\n      context.baseEstimatedBytes = estimatedBytes;\n      context.topologies.set(containerId, topology);\n      if (metrics) {\n        metrics.containersBuilt++;\n        metrics.baseTopologyBuilds++;\n        metrics.baseVertices += topology.vertices.length;\n        metrics.baseAdjacencyEntries += topology.adjacencyEntries;\n        metrics.buildSweepEvents += topology.seedCount * 4 + topology.obstacles.length * 4;\n        metrics.estimatedBytes = estimatedBytes;\n      }\n    } catch (error) {\n      if (!(error instanceof GridRoutingResourceLimitError)) {\n        throw error;\n      }\n      context.fallbackContainers.set(containerId, error.reason);\n    }\n  }\n  return context;\n}\n\nexport function validatedCompatibilitySegment(\n  edgeId: string,\n  containerId: GridContainerId,\n  start: SegmentAttachment,\n  end: SegmentAttachment,\n  route: () => Point[],\n  result: GridLayoutResult,\n  metrics?: GridRoutingInstrumentation\n): Point[] {\n  const points = route();\n  if (metrics) {\n    metrics.compatibilitySegments++;\n  }\n  if (validateContainerSegment(points, start.ownerId, end.ownerId, containerId, result)) {\n    return points;\n  }\n  if (metrics) {\n    metrics.compatibilityValidationFailures++;\n    metrics.routesImpossible++;\n  }\n  throw gridError('GRID_ROUTE_NOT_FOUND', `Invalid compatibility route for \"${edgeId}\"`, {\n    edgeId,\n    containerId,\n  });\n}\n\nexport function compatibilityLcaAttachments(\n  plan: EdgeRoutePlan,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>\n): { start: SegmentAttachment; end: SegmentAttachment } {\n  const sourceFinal = plan.source.chain.at(-1)!;\n  const targetFinal = plan.target.chain.at(-1)!;\n  const finalAttachment = (\n    endpoint: typeof plan.source,\n    final: (typeof plan.source.chain)[number]\n  ): SegmentAttachment => ({\n    ownerId: final.ownerId,\n    ...(endpoint.finalKind === 'boundary'\n      ? boundaryAttachment(plan.lcaContainerId, final.side, final.demandKey, result, demandCoords)\n      : itemAttachment(\n          final.ownerId,\n          final.side,\n          final.demandKey,\n          plan.lcaContainerId,\n          result,\n          demandCoords\n        )),\n  });\n  return {\n    start: finalAttachment(plan.source, sourceFinal),\n    end: finalAttachment(plan.target, targetFinal),\n  };\n}\n\nexport interface CompatibilitySegmentAttachments {\n  containerId: GridContainerId;\n  start: SegmentAttachment;\n  end: SegmentAttachment;\n}\n\nexport function compatibilityHierarchyAttachments(\n  endpoint: EdgeEndpointPlan,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>\n): CompatibilitySegmentAttachments[] {\n  return endpoint.chain.slice(0, -1).map((from, index) => {\n    const to = endpoint.chain[index + 1];\n    return {\n      containerId: to.ownerId,\n      start: {\n        ownerId: from.ownerId,\n        ...itemAttachment(\n          from.ownerId,\n          from.side,\n          from.demandKey,\n          to.ownerId,\n          result,\n          demandCoords\n        ),\n      },\n      end: {\n        ownerId: to.ownerId,\n        ...boundaryAttachment(to.ownerId, to.side, to.demandKey, result, demandCoords),\n      },\n    };\n  });\n}\n\nfunction compatibilityPlanIsValid(\n  plan: EdgeRoutePlan,\n  result: GridLayoutResult,\n  demandCoords: Map<string, number>\n): boolean {\n  const segmentIsValid = (\n    containerId: GridContainerId,\n    start: SegmentAttachment,\n    end: SegmentAttachment\n  ): boolean =>\n    validateContainerSegment(\n      routeWithinContainer(containerId, result, start, end, plan.laneIndex),\n      start.ownerId,\n      end.ownerId,\n      containerId,\n      result\n    );\n  for (const endpoint of [plan.source, plan.target]) {\n    for (const { containerId, start, end } of compatibilityHierarchyAttachments(\n      endpoint,\n      result,\n      demandCoords\n    )) {\n      if (!segmentIsValid(containerId, start, end)) {\n        return false;\n      }\n    }\n  }\n  const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n  return segmentIsValid(plan.lcaContainerId, attachments.start, attachments.end);\n}\n\nexport /*\n * Grid routing currently uses two algorithms:\n *\n * - `routeWithinContainer()` is the deterministic corridor router. During normal rendering, an\n *   ordinary unbundled same-container edge uses it as a fast path when its endpoint ports are\n *   legal, the complete route passes measured-geometry validation, and its length equals the\n *   Manhattan lower bound. This avoids building a visibility topology and running A* for\n *   routes that sparse search cannot improve.\n * - The sparse visibility router handles self-loops, bundles, ordinary routes that fail the\n *   fast path, and hierarchy routes that need alternative portals or obstacle-aware search.\n *\n * Test-only topology/search caps and dual-route comparison disable the fast path intentionally:\n * those modes must exercise sparse topology, search, and fallback behavior. Normal router and\n * performance tests cover the production fast path separately.\n *\n * Hierarchy routing is still partially migrated. Bundles, routes whose two endpoints have no\n * unrelated incident edges, and plans whose corridor route fails validation use sparse routing\n * for every hierarchy-chain segment. Other single hierarchy edges may retain validated\n * corridor segments when at least one endpoint is shared with another edge.\n * Group-to-descendant routes always use sparse routing for their LCA segment, even when their\n * ascent or descent chain still uses corridor routing. Defined sparse resource-limit failures\n * also use the corridor route as a fallback, but only after that route passes the same geometry\n * and pair-separation validation.\n *\n * Finishing the migration requires sparse routing to handle the remaining mixed-demand\n * hierarchy segments without introducing shared subpaths or crossings, and to meet the large\n * graph performance target without the common-edge fast path. It also requires generated\n * nested hierarchy, label, loop, bundle, and fallback coverage plus release-level validation.\n * Only then can `routeWithinContainer()`, corridor metadata, compatibility/fallback\n * instrumentation, and their obsolete tests be removed.\n */\nfunction prepareRoutingModes(\n  prepared: PreparedEdgeRoutes,\n  result: GridLayoutResult,\n  metrics: GridRoutingInstrumentation | undefined,\n  options: GridRoutingTestOptions\n): PreparedRoutingModes {\n  // Classify every plan before building topologies: proven minimal corridor routes avoid sparse\n  // setup, while only containers needed by sparse LCA, hierarchy, or loop segments are materialized.\n  const {\n    plans,\n    eligiblePlans,\n    eligibleIds,\n    demandCoords,\n    endpointCandidatesByEdge,\n    endpointIncidentCounts,\n    coordinatedEndpointIds,\n  } = prepared;\n  const hasIsolatedEndpoints = (plan: EdgeRoutePlan): boolean =>\n    (endpointIncidentCounts.get(plan.edge.start!) ?? 0) === plan.bundleSize &&\n    (endpointIncidentCounts.get(plan.edge.end!) ?? 0) === plan.bundleSize;\n  const hasAncestorEndpoint = (plan: EdgeRoutePlan): boolean => {\n    const source = result.forest.nodeById.get(plan.edge.start!);\n    const target = result.forest.nodeById.get(plan.edge.end!);\n    return Boolean(\n      source &&\n        target &&\n        ((source.isGroup && isAncestorGroup(source.id, target, result.forest.nodeById)) ||\n          (target.isGroup && isAncestorGroup(target.id, source, result.forest.nodeById)))\n    );\n  };\n  const compatibilityFastRoutes = new Map<string, Point[]>();\n  const routeOccupancy = new Map<GridContainerId, RouteOccupancyIndex>();\n  const overlapAvoidanceEnabled = plans.length <= MAX_PLANS_FOR_OVERLAP_AVOIDANCE;\n  const compatibilityFastPathEnabled =\n    options.topologyCaps === undefined &&\n    options.searchCaps === undefined &&\n    options.onDualRouteComparison === undefined;\n  for (const plan of compatibilityFastPathEnabled ? eligiblePlans : []) {\n    if (coordinatedEndpointIds.has(plan.edge.id)) {\n      continue;\n    }\n    const candidates = endpointCandidatesByEdge.get(plan.edge.id);\n    if (plan.bundleSize !== 1 || !candidates?.sources.length || !candidates.targets.length) {\n      continue;\n    }\n    const source = result.forest.nodeById.get(plan.edge.start!);\n    const target = result.forest.nodeById.get(plan.edge.end!);\n    if (!source || !target) {\n      continue;\n    }\n    const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n    const route = routeWithinContainer(\n      plan.lcaContainerId,\n      result,\n      attachments.start,\n      attachments.end,\n      plan.laneIndex\n    );\n    const normalized = normalizePolyline(route);\n    const first = normalized.points[0];\n    const last = normalized.points.at(-1);\n    if (!first || !last) {\n      continue;\n    }\n    const sourceCandidate = candidates.sources.find(\n      ({ port }) => port.x === first.x && port.y === first.y\n    );\n    const targetCandidate = candidates.targets.find(\n      ({ port }) => port.x === last.x && port.y === last.y\n    );\n    if (!sourceCandidate || !targetCandidate) {\n      continue;\n    }\n    if (metrics) {\n      metrics.compatibilityFastPathAttempts++;\n    }\n    const lowerBoundLength = Math.abs(first.x - last.x) + Math.abs(first.y - last.y);\n    if (!validateSameContainerRoute(route, source, target, plan.lcaContainerId, result)) {\n      if (metrics) {\n        metrics.compatibilityFastPathValidationFailures++;\n      }\n      continue;\n    }\n    if (manhattanLength(normalized.points) !== lowerBoundLength) {\n      if (metrics) {\n        metrics.compatibilityFastPathNonMinimalRoutes++;\n      }\n      continue;\n    }\n    // Small layouts demote a route that runs close and parallel to an earlier edge to sparse\n    // routing. Large layouts keep the fast path to stay search-free within the performance\n    // contract, nudging the route sideways when possible.\n    let occupancy = routeOccupancy.get(plan.lcaContainerId);\n    if (!occupancy) {\n      occupancy = new RouteOccupancyIndex();\n      routeOccupancy.set(plan.lcaContainerId, occupancy);\n    }\n    const conflicting = occupancy.conflictsWithRoute(normalized.points, plan.pairKey);\n    if (conflicting && overlapAvoidanceEnabled) {\n      // The sparse router can choose other ports and corridors, which reads better than a nudge.\n      continue;\n    }\n    const separated = separateRouteFromOccupied(\n      normalized.points,\n      occupancy,\n      plan.pairKey,\n      (candidate) =>\n        terminalStubsAreLongEnough(candidate) &&\n        manhattanLength(candidate) === lowerBoundLength &&\n        validateSameContainerRoute(candidate, source, target, plan.lcaContainerId, result)\n    );\n    const finalRoute = separated ?? route;\n    occupancy.add(finalRoute, plan.pairKey);\n    compatibilityFastRoutes.set(plan.edge.id, finalRoute);\n  }\n  const sparseCandidate = (plan: EdgeRoutePlan): boolean =>\n    !eligibleIds.has(plan.edge.id) &&\n    plan.edge.start !== plan.edge.end &&\n    (plan.bundleSize > 1 ||\n      hasIsolatedEndpoints(plan) ||\n      !compatibilityPlanIsValid(plan, result, demandCoords));\n  const planningOccupancy = new Map<GridContainerId, RouteOccupancyIndex>();\n  const overlappingHierarchyIds = new Set<string>();\n  if (overlapAvoidanceEnabled) {\n    for (const plan of prepared.orderedPlans) {\n      if (\n        eligibleIds.has(plan.edge.id) ||\n        plan.edge.start === plan.edge.end ||\n        hasAncestorEndpoint(plan) ||\n        sparseCandidate(plan)\n      ) {\n        continue;\n      }\n      const attachments = compatibilityLcaAttachments(plan, result, demandCoords);\n      const route = routeWithinContainer(\n        plan.lcaContainerId,\n        result,\n        attachments.start,\n        attachments.end,\n        plan.laneIndex\n      );\n      let occupancy = planningOccupancy.get(plan.lcaContainerId);\n      if (!occupancy) {\n        occupancy = new RouteOccupancyIndex();\n        planningOccupancy.set(plan.lcaContainerId, occupancy);\n      }\n      if (occupancy.conflictsWithRoute(route, plan.pairKey)) {\n        overlappingHierarchyIds.add(plan.edge.id);\n      } else {\n        occupancy.add(route, plan.pairKey);\n      }\n    }\n  }\n  const sparseHierarchyIds = new Set([\n    ...plans.filter(sparseCandidate).map(({ edge }) => edge.id),\n    ...overlappingHierarchyIds,\n  ]);\n  const sparseLcaIds = new Set([\n    ...sparseHierarchyIds,\n    ...plans.filter(hasAncestorEndpoint).map(({ edge }) => edge.id),\n  ]);\n  const routedContainerIds = plans\n    .filter(\n      (plan) =>\n        (eligibleIds.has(plan.edge.id) && !compatibilityFastRoutes.has(plan.edge.id)) ||\n        sparseLcaIds.has(plan.edge.id) ||\n        plan.edge.start === plan.edge.end\n    )\n    .flatMap((plan) => [\n      plan.lcaContainerId,\n      ...plan.source.chain.slice(1).map(({ ownerId }) => ownerId),\n      ...plan.target.chain.slice(1).map(({ ownerId }) => ownerId),\n    ]);\n  return {\n    overlapAvoidanceEnabled,\n    compatibilityFastRoutes,\n    sparseHierarchyIds,\n    sparseLcaIds,\n    routedContainerIds,\n    routeOccupancy,\n  };\n}\n", "import type { Point } from '../../../types.js';\nimport { normalizePolyline, segmentsCross } from '../layout-utils/geometry.js';\nimport { manhattanLength } from '../layout-utils/helpers.js';\n\n// Instrumentation doubles as observable behavior for retries. Work counters are cumulative, while\n// committed-output counters must roll back with a failed bundle attempt.\nexport type GridRoutingFallbackReason =\n  | 'vertex_cap'\n  | 'adjacency_cap'\n  | 'estimated_memory_cap'\n  | 'search_state_cap'\n  | 'label_index_work_cap'\n  | 'label_placement_exhausted';\n\nexport interface GridRouteInstrumentation {\n  edgeId: string;\n  routeOrder: number;\n  laneOffset: number;\n  routeLength: number;\n  bendCount: number;\n  crossingCount: number;\n  sharedLength: number;\n  boundaryTransitionCount: number;\n  routeSignature: string;\n}\n\nexport interface GridRoutingInstrumentation {\n  containersBuilt: number;\n  baseTopologyBuilds: number;\n  baseVertices: number;\n  baseAdjacencyEntries: number;\n  buildSweepEvents: number;\n  endpointOverlayBuilds: number;\n  endpointOverlayVertices: number;\n  hierarchyPortalPairs: number;\n  hierarchyPortalTransitionLength: number;\n  hierarchyPortalAlternativeAttempts: number;\n  hierarchyPortalAlternativeSelections: number;\n  hierarchyBoundaryTransitions: number;\n  labelOverlayBuilds: number;\n  labelOverlayVertices: number;\n  labelSpacingEdgesExamined: number;\n  labelSpacingEligibleEdges: number;\n  labelSpacingBoundariesExpanded: number;\n  labelSpacingPixelsAdded: number;\n  labelAwareSelfLoopCandidates: number;\n  labelAwareSelfLoopsCommitted: number;\n  labelAwareSelfLoopFallbacks: number;\n  searches: number;\n  expandedStates: number;\n  maxOpenSet: number;\n  routesFound: number;\n  routesImpossible: number;\n  resourceLimitFallbacks: number;\n  fallbackReasons: Record<GridRoutingFallbackReason, number>;\n  fallbackValidationFailures: number;\n  compatibilitySegments: number;\n  compatibilityFastPathAttempts: number;\n  compatibilityFastPaths: number;\n  compatibilityFastPathValidationFailures: number;\n  compatibilityFastPathNonMinimalRoutes: number;\n  compatibilityRecoveries: number;\n  compatibilityValidationFailures: number;\n  bundleSeparationRelaxations: number;\n  routeLength: number;\n  bendCount: number;\n  crossingCount: number;\n  sharedLength: number;\n  estimatedBytes: number;\n  searchWorkspaceBytes: number;\n  routeOrder: string[];\n  routes: GridRouteInstrumentation[];\n}\n\nexport const gridRoutingMetricDisposition = {\n  containersBuilt: 'cumulative',\n  baseTopologyBuilds: 'cumulative',\n  baseVertices: 'cumulative',\n  baseAdjacencyEntries: 'cumulative',\n  buildSweepEvents: 'cumulative',\n  endpointOverlayBuilds: 'cumulative',\n  endpointOverlayVertices: 'cumulative',\n  hierarchyPortalPairs: 'transactional',\n  hierarchyPortalTransitionLength: 'transactional',\n  hierarchyPortalAlternativeAttempts: 'cumulative',\n  hierarchyPortalAlternativeSelections: 'transactional',\n  hierarchyBoundaryTransitions: 'transactional',\n  labelOverlayBuilds: 'cumulative',\n  labelOverlayVertices: 'cumulative',\n  labelSpacingEdgesExamined: 'cumulative',\n  labelSpacingEligibleEdges: 'cumulative',\n  labelSpacingBoundariesExpanded: 'cumulative',\n  labelSpacingPixelsAdded: 'cumulative',\n  labelAwareSelfLoopCandidates: 'cumulative',\n  labelAwareSelfLoopsCommitted: 'transactional',\n  labelAwareSelfLoopFallbacks: 'cumulative',\n  searches: 'cumulative',\n  expandedStates: 'cumulative',\n  maxOpenSet: 'cumulative',\n  routesFound: 'transactional',\n  routesImpossible: 'transactional',\n  resourceLimitFallbacks: 'cumulative',\n  fallbackReasons: 'cumulative',\n  fallbackValidationFailures: 'cumulative',\n  compatibilitySegments: 'transactional',\n  compatibilityFastPathAttempts: 'cumulative',\n  compatibilityFastPaths: 'cumulative',\n  compatibilityFastPathValidationFailures: 'cumulative',\n  compatibilityFastPathNonMinimalRoutes: 'cumulative',\n  compatibilityRecoveries: 'transactional',\n  compatibilityValidationFailures: 'cumulative',\n  bundleSeparationRelaxations: 'transactional',\n  routeLength: 'transactional',\n  bendCount: 'transactional',\n  crossingCount: 'transactional',\n  sharedLength: 'transactional',\n  estimatedBytes: 'cumulative',\n  searchWorkspaceBytes: 'cumulative',\n  routeOrder: 'transactional',\n  routes: 'transactional',\n} as const satisfies Record<keyof GridRoutingInstrumentation, 'transactional' | 'cumulative'>;\n\n// Deriving checkpoint keys from the exhaustive disposition map forces every new metric to declare\n// whether retries preserve the work or restore the committed result.\ntype TransactionalGridRoutingMetric = {\n  [K in keyof typeof gridRoutingMetricDisposition]: (typeof gridRoutingMetricDisposition)[K] extends 'transactional'\n    ? K\n    : never;\n}[keyof typeof gridRoutingMetricDisposition];\n\ntype TransactionalGridRoutingValueMetric = Exclude<\n  TransactionalGridRoutingMetric,\n  'routeOrder' | 'routes'\n>;\n\nconst transactionalGridRoutingValueMetrics = (\n  Object.keys(gridRoutingMetricDisposition) as (keyof GridRoutingInstrumentation)[]\n).filter(\n  (key): key is TransactionalGridRoutingValueMetric =>\n    gridRoutingMetricDisposition[key] === 'transactional' &&\n    key !== 'routeOrder' &&\n    key !== 'routes'\n);\n\nexport interface GridRoutingInstrumentationCheckpoint {\n  routeOrderLength: number;\n  routesLength: number;\n  values: Pick<GridRoutingInstrumentation, TransactionalGridRoutingValueMetric>;\n}\n\nexport function createGridRoutingInstrumentationCheckpoint(\n  metrics: GridRoutingInstrumentation\n): GridRoutingInstrumentationCheckpoint {\n  // Route arrays are append-only during an attempt, so lengths are sufficient and avoid cloning\n  // potentially large per-edge records on every bundle retry.\n  return {\n    routeOrderLength: metrics.routeOrder.length,\n    routesLength: metrics.routes.length,\n    values: Object.fromEntries(\n      transactionalGridRoutingValueMetrics.map((key) => [key, metrics[key]])\n    ) as GridRoutingInstrumentationCheckpoint['values'],\n  };\n}\n\nexport function restoreGridRoutingInstrumentationCheckpoint(\n  metrics: GridRoutingInstrumentation,\n  checkpoint: GridRoutingInstrumentationCheckpoint\n): void {\n  metrics.routeOrder.length = checkpoint.routeOrderLength;\n  metrics.routes.length = checkpoint.routesLength;\n  Object.assign(metrics, checkpoint.values);\n}\n\nexport function createGridRoutingInstrumentation(): GridRoutingInstrumentation {\n  return {\n    containersBuilt: 0,\n    baseTopologyBuilds: 0,\n    baseVertices: 0,\n    baseAdjacencyEntries: 0,\n    buildSweepEvents: 0,\n    endpointOverlayBuilds: 0,\n    endpointOverlayVertices: 0,\n    hierarchyPortalPairs: 0,\n    hierarchyPortalTransitionLength: 0,\n    hierarchyPortalAlternativeAttempts: 0,\n    hierarchyPortalAlternativeSelections: 0,\n    hierarchyBoundaryTransitions: 0,\n    labelOverlayBuilds: 0,\n    labelOverlayVertices: 0,\n    labelSpacingEdgesExamined: 0,\n    labelSpacingEligibleEdges: 0,\n    labelSpacingBoundariesExpanded: 0,\n    labelSpacingPixelsAdded: 0,\n    labelAwareSelfLoopCandidates: 0,\n    labelAwareSelfLoopsCommitted: 0,\n    labelAwareSelfLoopFallbacks: 0,\n    searches: 0,\n    expandedStates: 0,\n    maxOpenSet: 0,\n    routesFound: 0,\n    routesImpossible: 0,\n    resourceLimitFallbacks: 0,\n    fallbackReasons: {\n      vertex_cap: 0,\n      adjacency_cap: 0,\n      estimated_memory_cap: 0,\n      search_state_cap: 0,\n      label_index_work_cap: 0,\n      label_placement_exhausted: 0,\n    },\n    fallbackValidationFailures: 0,\n    compatibilitySegments: 0,\n    compatibilityFastPathAttempts: 0,\n    compatibilityFastPaths: 0,\n    compatibilityFastPathValidationFailures: 0,\n    compatibilityFastPathNonMinimalRoutes: 0,\n    compatibilityRecoveries: 0,\n    compatibilityValidationFailures: 0,\n    bundleSeparationRelaxations: 0,\n    routeLength: 0,\n    bendCount: 0,\n    crossingCount: 0,\n    sharedLength: 0,\n    estimatedBytes: 0,\n    searchWorkspaceBytes: 0,\n    routeOrder: [],\n    routes: [],\n  };\n}\n\nfunction intervalOverlap(\n  firstStart: number,\n  firstEnd: number,\n  secondStart: number,\n  secondEnd: number\n): number {\n  return Math.max(\n    0,\n    Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd)) -\n      Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd))\n  );\n}\n\nfunction sharedSegmentLength(first: Point[], second: Point[]): number {\n  const firstSegments = normalizePolyline(first).segments;\n  const secondSegments = normalizePolyline(second).segments;\n  let total = 0;\n\n  for (const a of firstSegments) {\n    for (const b of secondSegments) {\n      if (a.orientation !== b.orientation) {\n        continue;\n      }\n      if (a.orientation === 'H' && a.a.y === b.a.y) {\n        total += intervalOverlap(a.a.x, a.b.x, b.a.x, b.b.x);\n      } else if (a.orientation === 'V' && a.a.x === b.a.x) {\n        total += intervalOverlap(a.a.y, a.b.y, b.a.y, b.b.y);\n      }\n    }\n  }\n  return total;\n}\n\nexport function recordGridRoute(\n  metrics: GridRoutingInstrumentation,\n  edgeId: string,\n  points: Point[],\n  previousRoutes: readonly Point[][],\n  boundaryTransitionCount = 0,\n  laneOffset = 0\n): void {\n  // Quality metrics compare only against previously committed routes, matching visible route order\n  // and avoiding double-counting pairs.\n  const normalized = normalizePolyline(points);\n  let crossingCount = 0;\n  let sharedLength = 0;\n\n  for (const previous of previousRoutes) {\n    const previousSegments = normalizePolyline(previous).segments;\n    for (const segment of normalized.segments) {\n      for (const previousSegment of previousSegments) {\n        if (segmentsCross(segment, previousSegment)) {\n          crossingCount++;\n        }\n      }\n    }\n    sharedLength += sharedSegmentLength(normalized.points, previous);\n  }\n\n  const route: GridRouteInstrumentation = {\n    edgeId,\n    routeOrder: metrics.routes.length,\n    laneOffset,\n    routeLength: manhattanLength(normalized.points),\n    bendCount: normalized.bends,\n    crossingCount,\n    sharedLength,\n    boundaryTransitionCount,\n    routeSignature: JSON.stringify(normalized.points),\n  };\n  metrics.routeOrder.push(edgeId);\n  metrics.routes.push(route);\n  metrics.routesFound++;\n  metrics.routeLength += route.routeLength;\n  metrics.bendCount += route.bendCount;\n  metrics.crossingCount += route.crossingCount;\n  metrics.sharedLength += route.sharedLength;\n  metrics.hierarchyBoundaryTransitions += boundaryTransitionCount;\n}\n", "import { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type {\n  ContainerRoutingTopology,\n  GridOrientation,\n  GridSide,\n  RouterPoint,\n  RouterVertex,\n} from './types.js';\n\n// A* minimizes this tuple lexicographically. Length and bends dominate hierarchy transitions and\n// endpoint preference, which are deterministic tie-breakers rather than weighted approximations.\nexport type RouterTupleCost = [\n  length: number,\n  bends: number,\n  boundaryTransitions: number,\n  endpointCandidateRank: number,\n];\n\nexport interface RouterSearchResult {\n  points: RouterPoint[];\n  vertexIds: number[];\n  cost: RouterTupleCost;\n}\n\nexport interface RouterSearchCaps {\n  maxExpandedStates?: number;\n  maxInvocationExpandedStates?: number;\n  maxEstimatedBytes?: number;\n}\n\nexport interface RouterSearchBudget {\n  expandedStates: number;\n}\n\nexport interface RouterSearchOptions {\n  metrics?: GridRoutingInstrumentation;\n  caps?: RouterSearchCaps;\n  endpointCandidateRank?: number;\n  recordOutcome?: boolean;\n  budget?: RouterSearchBudget;\n  initialOrientation?: GridOrientation;\n  initialSide?: GridSide;\n  initialLength?: number;\n  targetOrientation?: GridOrientation;\n  targetSide?: GridSide;\n  targetLength?: number;\n  topologyValidated?: boolean;\n  workspace?: RouterSearchWorkspace;\n  heuristic?: 'bend-aware' | 'zero';\n  queueOrder?: 'canonical' | 'reverse';\n  estimatedBytesBase?: number;\n  arcAllowed?: (from: RouterPoint, to: RouterPoint) => boolean;\n}\n\nconst DEFAULT_MAX_EDGE_STATES = 100_000;\nconst DEFAULT_MAX_INVOCATION_STATES = 2_000_000;\n\nexport class RouterSearchWorkspace {\n  // Typed arrays are retained across searches to avoid allocating object-heavy state graphs for\n  // every endpoint candidate pair. State capacity grows geometrically and never shrinks mid-session.\n  stateVertices = new Int32Array(256);\n  orientations = new Uint8Array(256);\n  gLengths = new Float64Array(256);\n  gBends = new Float64Array(256);\n  gBoundaryTransitions = new Float64Array(256);\n  fLengths = new Float64Array(256);\n  fBends = new Float64Array(256);\n  predecessors = new Int32Array(256);\n  depths = new Int32Array(256);\n  ancestor4 = new Int32Array(256);\n  best = new Int32Array(256);\n  heapChildren = new Int32Array(256);\n  heapSiblings = new Int32Array(256);\n  heapPairs: number[] = [];\n  touchedBestIndices: number[] = [];\n\n  constructor() {\n    this.best.fill(-1);\n  }\n\n  reset(vertexCount: number): void {\n    const bestLength = vertexCount * 3;\n    if (this.best.length < bestLength) {\n      this.best = new Int32Array(bestLength);\n      this.best.fill(-1);\n    } else {\n      for (const index of this.touchedBestIndices) {\n        this.best[index] = -1;\n      }\n    }\n    this.touchedBestIndices.length = 0;\n    this.heapPairs.length = 0;\n  }\n\n  setBest(index: number, state: number): void {\n    if (this.best[index] < 0) {\n      this.touchedBestIndices.push(index);\n    }\n    this.best[index] = state;\n  }\n\n  ensureStateCapacity(required: number): void {\n    if (this.stateVertices.length >= required) {\n      return;\n    }\n    const capacity = Math.max(required, this.stateVertices.length * 2);\n    this.stateVertices = growTypedArray(this.stateVertices, capacity);\n    this.orientations = growTypedArray(this.orientations, capacity);\n    this.gLengths = growTypedArray(this.gLengths, capacity);\n    this.gBends = growTypedArray(this.gBends, capacity);\n    this.gBoundaryTransitions = growTypedArray(this.gBoundaryTransitions, capacity);\n    this.fLengths = growTypedArray(this.fLengths, capacity);\n    this.fBends = growTypedArray(this.fBends, capacity);\n    this.predecessors = growTypedArray(this.predecessors, capacity);\n    this.depths = growTypedArray(this.depths, capacity);\n    this.ancestor4 = growTypedArray(this.ancestor4, capacity);\n    this.heapChildren = growTypedArray(this.heapChildren, capacity);\n    this.heapSiblings = growTypedArray(this.heapSiblings, capacity);\n  }\n\n  estimatedBytes(): number {\n    return (\n      this.stateVertices.byteLength +\n      this.orientations.byteLength +\n      this.gLengths.byteLength +\n      this.gBends.byteLength +\n      this.gBoundaryTransitions.byteLength +\n      this.fLengths.byteLength +\n      this.fBends.byteLength +\n      this.predecessors.byteLength +\n      this.depths.byteLength +\n      this.ancestor4.byteLength +\n      this.best.byteLength +\n      this.heapChildren.byteLength +\n      this.heapSiblings.byteLength +\n      (this.heapPairs.length + this.touchedBestIndices.length) * 8\n    );\n  }\n}\n\nexport function assertSearchBudgetAvailable(\n  options: Pick<RouterSearchOptions, 'metrics' | 'caps' | 'budget'>\n): void {\n  const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;\n  const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;\n  const invocationStart = options.budget?.expandedStates ?? options.metrics?.expandedStates ?? 0;\n  if (edgeCap > 0 && invocationStart < invocationCap) {\n    return;\n  }\n  throw new GridRoutingResourceLimitError(\n    'search_state_cap',\n    'Grid routing search-state cap exceeded',\n    invocationStart >= invocationCap ? 'invocation' : 'edge'\n  );\n}\n\nfunction growTypedArray<T extends Int32Array | Uint8Array | Float64Array>(\n  values: T,\n  capacity: number\n): T {\n  const grown = new (values.constructor as new (length: number) => T)(capacity);\n  grown.set(values);\n  return grown;\n}\nexport function compareTupleCost(a: RouterTupleCost, b: RouterTupleCost): number {\n  for (let index = 0; index < 4; index++) {\n    if (a[index] < b[index]) {\n      return -1;\n    }\n    if (a[index] > b[index]) {\n      return 1;\n    }\n  }\n  return 0;\n}\n\nfunction minimumBends(\n  dx: number,\n  dy: number,\n  incomingOrientation?: GridOrientation,\n  targetOrientation?: GridOrientation\n): number {\n  if (dx === 0 && dy === 0) {\n    return incomingOrientation && targetOrientation\n      ? Number(incomingOrientation !== targetOrientation)\n      : 0;\n  }\n  if (dx === 0) {\n    return (\n      (incomingOrientation ? Number(incomingOrientation !== 'V') : 0) +\n      (targetOrientation ? Number(targetOrientation !== 'V') : 0)\n    );\n  }\n  if (dy === 0) {\n    return (\n      (incomingOrientation ? Number(incomingOrientation !== 'H') : 0) +\n      (targetOrientation ? Number(targetOrientation !== 'H') : 0)\n    );\n  }\n  return Math.min(\n    (incomingOrientation ? Number(incomingOrientation !== 'H') : 0) +\n      1 +\n      (targetOrientation ? Number(targetOrientation !== 'V') : 0),\n    (incomingOrientation ? Number(incomingOrientation !== 'V') : 0) +\n      1 +\n      (targetOrientation ? Number(targetOrientation !== 'H') : 0)\n  );\n}\n\ntype OrientationOrdinal = 0 | 1 | 2;\n\nfunction orientationOrdinal(orientation: GridOrientation | undefined): OrientationOrdinal {\n  return orientation === undefined ? 0 : orientation === 'H' ? 1 : 2;\n}\n\nfunction movesTowardOwner(from: RouterPoint, to: RouterPoint, side: GridSide): boolean {\n  return side === 'left'\n    ? from.y === to.y && to.x > from.x\n    : side === 'right'\n      ? from.y === to.y && to.x < from.x\n      : side === 'top'\n        ? from.x === to.x && to.y > from.y\n        : from.x === to.x && to.y < from.y;\n}\n\nfunction stateIndex(vertexId: number, orientation: GridOrientation | undefined): number {\n  return vertexId * 3 + orientationOrdinal(orientation);\n}\n\nfunction normalizePoints(points: readonly RouterPoint[]): RouterPoint[] {\n  const result: RouterPoint[] = [];\n  for (const point of points) {\n    const previous = result.at(-1);\n    if (previous && previous.x === point.x && previous.y === point.y) {\n      continue;\n    }\n    const beforePrevious = result.at(-2);\n    if (\n      beforePrevious &&\n      previous &&\n      ((beforePrevious.x === previous.x && previous.x === point.x) ||\n        (beforePrevious.y === previous.y && previous.y === point.y))\n    ) {\n      result[result.length - 1] = { ...point };\n    } else {\n      result.push({ ...point });\n    }\n  }\n  return result;\n}\n\nfunction reconstruct(\n  stateId: number,\n  stateVertices: ArrayLike<number>,\n  predecessors: ArrayLike<number>,\n  cost: RouterTupleCost,\n  vertexAt: (id: number) => RouterVertex\n): RouterSearchResult {\n  const vertexIds: number[] = [];\n  let current = stateId;\n  while (current >= 0) {\n    vertexIds.push(stateVertices[current]);\n    current = predecessors[current];\n  }\n  vertexIds.reverse();\n  return {\n    points: normalizePoints(vertexIds.map((id) => vertexAt(id).point)),\n    vertexIds,\n    cost,\n  };\n}\n\nfunction validateSearchTopology(\n  topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'>\n): void {\n  for (const vertex of topology.vertices) {\n    if (\n      vertex.id < 0 ||\n      topology.vertices[vertex.id] !== vertex ||\n      !Number.isFinite(vertex.point.x) ||\n      !Number.isFinite(vertex.point.y)\n    ) {\n      throw new Error('Malformed grid routing vertex');\n    }\n    for (const arc of topology.adjacency.get(vertex.id) ?? []) {\n      const target = topology.vertices[arc.to];\n      const aligned =\n        target &&\n        (arc.orientation === 'H'\n          ? vertex.point.y === target.point.y\n          : vertex.point.x === target.point.x);\n      const length = target\n        ? Math.abs(vertex.point.x - target.point.x) + Math.abs(vertex.point.y - target.point.y)\n        : Number.NaN;\n      if (\n        arc.from !== vertex.id ||\n        !aligned ||\n        !Number.isFinite(arc.length) ||\n        arc.length <= 0 ||\n        arc.length !== length\n      ) {\n        throw new Error('Malformed grid routing arc');\n      }\n    }\n  }\n}\n\nfunction search(\n  topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'> &\n    Partial<\n      Pick<\n        ContainerRoutingTopology,\n        | 'adjacencyByVertex'\n        | 'searchAdjacencyByVertex'\n        | 'vertexCount'\n        | 'getVertex'\n        | 'getSearchArcs'\n      >\n    >,\n  sourceId: number,\n  targetId: number,\n  options: RouterSearchOptions\n): RouterSearchResult | undefined {\n  const vertexAt = (id: number): RouterVertex => {\n    const vertex = topology.getVertex?.(id) ?? topology.vertices[id];\n    if (!vertex) {\n      throw new Error(`Missing grid routing vertex ${id}`);\n    }\n    return vertex;\n  };\n  const source = vertexAt(sourceId);\n  const target = vertexAt(targetId);\n  if (!options.topologyValidated) {\n    validateSearchTopology(topology);\n  }\n\n  const metrics = options.metrics;\n  if (metrics) {\n    metrics.searches++;\n  }\n  assertSearchBudgetAvailable(options);\n  const workspace = options.workspace ?? new RouterSearchWorkspace();\n  workspace.reset(topology.vertexCount ?? topology.vertices.length);\n  let stateVertices = workspace.stateVertices;\n  let orientations = workspace.orientations;\n  let gLengths = workspace.gLengths;\n  let gBends = workspace.gBends;\n  let gBoundaryTransitions = workspace.gBoundaryTransitions;\n  let fLengths = workspace.fLengths;\n  let fBends = workspace.fBends;\n  let predecessors = workspace.predecessors;\n  let depths = workspace.depths;\n  let ancestor4 = workspace.ancestor4;\n  let heapChildren = workspace.heapChildren;\n  let heapSiblings = workspace.heapSiblings;\n  const best = workspace.best;\n  const heapPairs = workspace.heapPairs;\n  let stateCount = 1;\n  const endpointCandidateRank = options.endpointCandidateRank ?? 0;\n  const useBendHeuristic = options.heuristic !== 'zero';\n  function nonCostOrder(a: number, b: number): number {\n    return (\n      stateVertices[a] - stateVertices[b] ||\n      orientations[a] - orientations[b] ||\n      predecessors[a] - predecessors[b] ||\n      a - b\n    );\n  }\n  function compareStates(a: number, b: number): number {\n    return (\n      fLengths[a] - fLengths[b] ||\n      fBends[a] - fBends[b] ||\n      gBoundaryTransitions[a] - gBoundaryTransitions[b] ||\n      (options.queueOrder === 'reverse' ? -nonCostOrder(a, b) : nonCostOrder(a, b))\n    );\n  }\n  function compareChains(a: number, b: number): number {\n    // Equal-cost states choose the lexicographically smaller predecessor chain. Four-level jump\n    // pointers reduce the common-prefix walk without retaining full paths per state.\n    if (a === b) {\n      return 0;\n    }\n    if (a < 0) {\n      return -1;\n    }\n    if (b < 0) {\n      return 1;\n    }\n    const aDepth = depths[a];\n    const bDepth = depths[b];\n    let alignedA = a;\n    let alignedB = b;\n    while (depths[alignedA] > depths[alignedB]) {\n      alignedA = predecessors[alignedA];\n    }\n    while (depths[alignedB] > depths[alignedA]) {\n      alignedB = predecessors[alignedB];\n    }\n    if (alignedA === alignedB) {\n      return aDepth - bDepth;\n    }\n    while (\n      ancestor4[alignedA] >= 0 &&\n      ancestor4[alignedB] >= 0 &&\n      ancestor4[alignedA] !== ancestor4[alignedB]\n    ) {\n      alignedA = ancestor4[alignedA];\n      alignedB = ancestor4[alignedB];\n    }\n    while (predecessors[alignedA] !== predecessors[alignedB]) {\n      alignedA = predecessors[alignedA];\n      alignedB = predecessors[alignedB];\n    }\n    return (\n      stateVertices[alignedA] - stateVertices[alignedB] ||\n      orientations[alignedA] - orientations[alignedB]\n    );\n  }\n  let heapRoot = -1;\n  let heapSize = 0;\n  // A pairing heap supports cheap melds in flat arrays, preserving workspace reuse and avoiding one\n  // allocation per queue node.\n  function heapMeld(first: number, second: number): number {\n    if (first < 0) {\n      return second;\n    }\n    if (second < 0) {\n      return first;\n    }\n    if (compareStates(first, second) <= 0) {\n      heapSiblings[second] = heapChildren[first];\n      heapChildren[first] = second;\n      return first;\n    }\n    heapSiblings[first] = heapChildren[second];\n    heapChildren[second] = first;\n    return second;\n  }\n  const heapPush = (value: number): void => {\n    heapChildren[value] = -1;\n    heapSiblings[value] = -1;\n    heapRoot = heapMeld(heapRoot, value);\n    heapSize++;\n  };\n  const heapPop = (): number | undefined => {\n    if (heapRoot < 0) {\n      return undefined;\n    }\n    const first = heapRoot;\n    heapPairs.length = 0;\n    let child = heapChildren[first];\n    while (child >= 0) {\n      const next = heapSiblings[child];\n      heapSiblings[child] = -1;\n      heapPairs.push(child);\n      child = next;\n    }\n    for (let index = 0; index + 1 < heapPairs.length; index += 2) {\n      heapPairs[index >>> 1] = heapMeld(heapPairs[index], heapPairs[index + 1]);\n    }\n    let pairCount = Math.ceil(heapPairs.length / 2);\n    if (heapPairs.length % 2 !== 0) {\n      heapPairs[pairCount - 1] = heapPairs[heapPairs.length - 1];\n    }\n    heapRoot = -1;\n    while (pairCount > 0) {\n      heapRoot = heapMeld(heapPairs[--pairCount], heapRoot);\n    }\n    heapSize--;\n    return first;\n  };\n  let expandedThisSearch = 0;\n  const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;\n  const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;\n  const invocationStart = options.budget?.expandedStates ?? metrics?.expandedStates ?? 0;\n  const recordWorkspaceBytes = (): void => {\n    const bytes = workspace.estimatedBytes();\n    const totalBytes = (options.estimatedBytesBase ?? 0) + bytes;\n    if (metrics) {\n      metrics.searchWorkspaceBytes = Math.max(metrics.searchWorkspaceBytes, bytes);\n      metrics.estimatedBytes = Math.max(metrics.estimatedBytes, totalBytes);\n    }\n    if (totalBytes > (options.caps?.maxEstimatedBytes ?? Number.POSITIVE_INFINITY)) {\n      throw new GridRoutingResourceLimitError(\n        'estimated_memory_cap',\n        'Grid routing search workspace memory cap exceeded'\n      );\n    }\n  };\n  recordWorkspaceBytes();\n  const commitExpandedStates = (): void => {\n    // Charge states once on every exit path, including cap exceptions, so the invocation-wide\n    // budget cannot be reset by trying another candidate pair.\n    if (options.budget) {\n      options.budget.expandedStates += expandedThisSearch;\n    }\n    if (metrics) {\n      metrics.expandedStates += expandedThisSearch;\n    }\n  };\n  const initialLength = options.initialLength ?? 0;\n  stateVertices[0] = sourceId;\n  orientations[0] = orientationOrdinal(options.initialOrientation);\n  gLengths[0] = initialLength;\n  gBends[0] = 0;\n  gBoundaryTransitions[0] = 0;\n  const initialDx = Math.abs(source.point.x - target.point.x);\n  const initialDy = Math.abs(source.point.y - target.point.y);\n  fLengths[0] = initialLength + (useBendHeuristic ? initialDx + initialDy : 0);\n  fBends[0] = useBendHeuristic\n    ? minimumBends(initialDx, initialDy, options.initialOrientation, options.targetOrientation)\n    : 0;\n  predecessors[0] = -1;\n  depths[0] = 1;\n  ancestor4[0] = -1;\n  workspace.setBest(stateIndex(sourceId, options.initialOrientation), 0);\n  heapPush(0);\n  if (metrics) {\n    metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);\n  }\n  let bestGoalState = -1;\n  let bestGoalCost: RouterTupleCost | undefined;\n  const considerGoal = (state: number): void => {\n    const completedCost: RouterTupleCost = [\n      gLengths[state] + (options.targetLength ?? 0),\n      gBends[state] +\n        (options.targetOrientation !== undefined &&\n        orientations[state] !== 0 &&\n        orientationOrdinal(options.targetOrientation) !== orientations[state]\n          ? 1\n          : 0),\n      gBoundaryTransitions[state],\n      endpointCandidateRank,\n    ];\n    if (\n      !bestGoalCost ||\n      compareTupleCost(completedCost, bestGoalCost) < 0 ||\n      (compareTupleCost(completedCost, bestGoalCost) === 0 &&\n        compareChains(state, bestGoalState) < 0)\n    ) {\n      bestGoalState = state;\n      bestGoalCost = completedCost;\n    }\n  };\n  const relaxArc = (\n    current: number,\n    currentPoint: RouterPoint,\n    to: number,\n    orientation: OrientationOrdinal,\n    arcLength: number,\n    boundaryTransitions: number\n  ): void => {\n    const nextPoint = vertexAt(to).point;\n    if (options.arcAllowed && !options.arcAllowed(currentPoint, nextPoint)) {\n      return;\n    }\n    if (\n      options.initialSide &&\n      predecessors[current] < 0 &&\n      movesTowardOwner(currentPoint, nextPoint, options.initialSide)\n    ) {\n      return;\n    }\n    if (\n      options.targetSide &&\n      to === targetId &&\n      movesTowardOwner(target.point, currentPoint, options.targetSide)\n    ) {\n      return;\n    }\n    const index = to * 3 + orientation;\n    const previous = best[index];\n    const length = gLengths[current] + arcLength;\n    const bends =\n      gBends[current] +\n      (orientations[current] !== 0 && orientations[current] !== orientation ? 1 : 0);\n    const nextBoundaryTransitions = gBoundaryTransitions[current] + boundaryTransitions;\n    const previousComparison =\n      previous >= 0\n        ? length - gLengths[previous] ||\n          bends - gBends[previous] ||\n          nextBoundaryTransitions - gBoundaryTransitions[previous]\n        : -1;\n    if (\n      previous >= 0 &&\n      (previousComparison > 0 ||\n        (previousComparison === 0 && compareChains(current, predecessors[previous]) >= 0))\n    ) {\n      return;\n    }\n    const candidate = stateCount++;\n    if (stateCount > stateVertices.length) {\n      workspace.ensureStateCapacity(stateCount);\n      stateVertices = workspace.stateVertices;\n      orientations = workspace.orientations;\n      gLengths = workspace.gLengths;\n      gBends = workspace.gBends;\n      gBoundaryTransitions = workspace.gBoundaryTransitions;\n      fLengths = workspace.fLengths;\n      fBends = workspace.fBends;\n      predecessors = workspace.predecessors;\n      depths = workspace.depths;\n      ancestor4 = workspace.ancestor4;\n      heapChildren = workspace.heapChildren;\n      heapSiblings = workspace.heapSiblings;\n      recordWorkspaceBytes();\n    }\n    stateVertices[candidate] = to;\n    orientations[candidate] = orientation;\n    gLengths[candidate] = length;\n    gBends[candidate] = bends;\n    gBoundaryTransitions[candidate] = nextBoundaryTransitions;\n    const candidateDx = Math.abs(nextPoint.x - target.point.x);\n    const candidateDy = Math.abs(nextPoint.y - target.point.y);\n    fLengths[candidate] = length + (useBendHeuristic ? candidateDx + candidateDy : 0);\n    fBends[candidate] =\n      bends +\n      (useBendHeuristic\n        ? minimumBends(\n            candidateDx,\n            candidateDy,\n            orientation === 1 ? 'H' : 'V',\n            options.targetOrientation\n          )\n        : 0);\n    predecessors[candidate] = current;\n    depths[candidate] = depths[current] + 1;\n    const parent2 = predecessors[current];\n    const parent3 = parent2 >= 0 ? predecessors[parent2] : -1;\n    ancestor4[candidate] = parent3 >= 0 ? predecessors[parent3] : -1;\n    workspace.setBest(index, candidate);\n    heapPush(candidate);\n  };\n\n  while (heapSize > 0) {\n    const next = heapRoot;\n    // The queue is ordered by the same admissible tuple prefix as the goal. Once its best state is\n    // worse than the best goal, no remaining state can improve the result.\n    if (\n      bestGoalCost &&\n      (fLengths[next] - bestGoalCost[0] ||\n        fBends[next] - bestGoalCost[1] ||\n        gBoundaryTransitions[next] - bestGoalCost[2] ||\n        endpointCandidateRank - bestGoalCost[3]) > 0\n    ) {\n      break;\n    }\n    const current = heapPop()!;\n    if (best[stateVertices[current] * 3 + orientations[current]] !== current) {\n      continue;\n    }\n    if (expandedThisSearch >= edgeCap || invocationStart + expandedThisSearch >= invocationCap) {\n      if (bestGoalState >= 0 && bestGoalCost) {\n        if (metrics && options.recordOutcome !== false) {\n          metrics.routesFound++;\n        }\n        commitExpandedStates();\n        return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);\n      }\n      commitExpandedStates();\n      const searchStateScope =\n        invocationStart + expandedThisSearch >= invocationCap ? 'invocation' : 'edge';\n      throw new GridRoutingResourceLimitError(\n        'search_state_cap',\n        'Grid routing search-state cap exceeded',\n        searchStateScope\n      );\n    }\n    expandedThisSearch++;\n\n    if (stateVertices[current] === targetId) {\n      considerGoal(current);\n      continue;\n    }\n\n    const vertexId = stateVertices[current];\n    const currentPoint = vertexAt(vertexId).point;\n    const compactArcs =\n      topology.getSearchArcs?.(vertexId) ?? topology.searchAdjacencyByVertex?.[vertexId];\n    if (compactArcs) {\n      for (const arc of compactArcs) {\n        relaxArc(\n          current,\n          currentPoint,\n          arc.to,\n          arc.orientationOrdinal,\n          arc.length,\n          arc.boundaryTransitions\n        );\n      }\n    } else {\n      for (const arc of topology.adjacencyByVertex?.[vertexId] ??\n        topology.adjacency.get(vertexId) ??\n        []) {\n        relaxArc(\n          current,\n          currentPoint,\n          arc.to,\n          orientationOrdinal(arc.orientation),\n          arc.length,\n          arc.kind === 'portal' ? 1 : 0\n        );\n      }\n    }\n    if (metrics) {\n      metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);\n    }\n  }\n\n  if (bestGoalState < 0 || !bestGoalCost) {\n    commitExpandedStates();\n    if (metrics && options.recordOutcome !== false) {\n      metrics.routesImpossible++;\n    }\n    return undefined;\n  }\n  if (metrics && options.recordOutcome !== false) {\n    metrics.routesFound++;\n  }\n  commitExpandedStates();\n  return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);\n}\n\nexport function findShortestRoute(\n  topology: Pick<ContainerRoutingTopology, 'vertices' | 'adjacency'> &\n    Partial<\n      Pick<\n        ContainerRoutingTopology,\n        | 'adjacencyByVertex'\n        | 'searchAdjacencyByVertex'\n        | 'vertexCount'\n        | 'getVertex'\n        | 'getSearchArcs'\n      >\n    >,\n  sourceId: number,\n  targetId: number,\n  options: RouterSearchOptions = {}\n): RouterSearchResult | undefined {\n  return search(topology, sourceId, targetId, options);\n}\n", "import { log } from '../../../logger.js';\nimport type { Point } from '../../../types.js';\nimport type { Node } from '../../types.js';\nimport { normalizePolyline } from '../layout-utils/geometry.js';\nimport { manhattanLength, rectForNode } from '../layout-utils/helpers.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport type { RouteOccupancyIndex } from './routerOccupancy.js';\nimport {\n  SELF_LOOP_PORT_GAP,\n  SELF_LOOP_PORT_OFFSET_STEP,\n  areExactlyAxisAligned,\n  labelAwareSelfLoopCandidates,\n  orderedSelfLoopSides,\n  routeObstacleClearSelfLoop,\n  type SegmentAttachment,\n  type SegmentAttachmentAlternative,\n} from './routerCompatibility.js';\nimport {\n  endpointPairLowerBound,\n  pairArcAllowed,\n  routeHasDistinctPairPorts,\n  routeSatisfiesPairConstraints,\n  validateContainerSegment,\n  validateSameContainerRoute,\n} from './routerConstraint.js';\nimport {\n  TERMINAL_APPROACH_PX,\n  sideInterval,\n  sideOrder,\n  type EdgeRoutePlan,\n  type EndpointCandidate,\n} from './routerPlanning.js';\nimport { GridRoutingResourceLimitError } from './routerErrors.js';\nimport type { GridRoutingFallbackReason } from './routerInstrumentation.js';\nimport {\n  assertSearchBudgetAvailable,\n  compareTupleCost,\n  findShortestRoute,\n  type RouterSearchResult,\n  type RouterSearchWorkspace,\n  type RouterTupleCost,\n} from './routerSearch.js';\nimport {\n  buildEndpointRoutingOverlay,\n  DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n  routingPointKey,\n  type EndpointOverlayScratch,\n} from './routerTopology.js';\nimport type {\n  GridContainerId,\n  GridLayoutResult,\n  GridOrientation,\n  GridRoutingContext,\n  GridSide,\n  RouterPoint,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// Sparse routing overlays edge-specific endpoints onto immutable container visibility graphs, then\n// validates every result before it can replace the deterministic corridor route.\nconst ROUTER_DEBUG_KEY = 'grid-router';\n\nfunction recordFallback(\n  context: GridRoutingContext,\n  reason: GridRoutingFallbackReason,\n  edgeId: string,\n  containerId: GridContainerId,\n  searchStateScope?: GridRoutingResourceLimitError['searchStateScope']\n): void {\n  if (context.metrics) {\n    context.metrics.resourceLimitFallbacks++;\n    context.metrics.fallbackReasons[reason]++;\n  }\n  log.debug(ROUTER_DEBUG_KEY, 'GRID_ROUTING_RESOURCE_FALLBACK', {\n    edgeId,\n    containerId,\n    reason,\n  });\n  if (\n    reason === 'search_state_cap' &&\n    searchStateScope === 'invocation' &&\n    !context.searchBudgetWarningEmitted\n  ) {\n    context.searchBudgetWarningEmitted = true;\n    log.warn(ROUTER_DEBUG_KEY, 'GRID_ROUTING_INVOCATION_SEARCH_BUDGET_EXHAUSTED', {\n      edgeId,\n      containerId,\n      expandedStates: context.searchBudget.expandedStates,\n    });\n  }\n}\n\ninterface ValidatedFallbackOptions<T> {\n  context: GridRoutingContext;\n  reason: GridRoutingFallbackReason;\n  edgeId: string;\n  containerId: GridContainerId;\n  searchStateScope?: GridRoutingResourceLimitError['searchStateScope'];\n  route: () => T;\n  isValid: (fallback: T) => boolean;\n  includeContainerIdInError?: boolean;\n}\n\nfunction runValidatedFallback<T>({\n  context,\n  reason,\n  edgeId,\n  containerId,\n  searchStateScope,\n  route,\n  isValid,\n  includeContainerIdInError,\n}: ValidatedFallbackOptions<T>): T {\n  const fallback = route();\n  recordFallback(context, reason, edgeId, containerId, searchStateScope);\n  if (isValid(fallback)) {\n    return fallback;\n  }\n  if (context.metrics) {\n    context.metrics.fallbackValidationFailures++;\n  }\n  throw gridError('GRID_ROUTE_NOT_FOUND', `Invalid legacy fallback for \"${edgeId}\"`, {\n    edgeId,\n    ...(includeContainerIdInError ? { containerId } : {}),\n    reason,\n  });\n}\n\n/*\n * TODO: Consider an opt-in `grid.routingPolicy: 'best-effort'` mode while keeping validated\n * routing as the default.\n *\n * A minimal implementation could catch recoverable per-edge routing exhaustion after both the\n * sparse router and validated compatibility route fail, then construct a deterministic orthogonal\n * dogleg between the measured source and target bounds. Self-loops would need a similarly\n * deterministic rectangular loop. The fallback could cross protected geometry or share bundle\n * lanes, but it must still use finite coordinates, preserve valid endpoints, avoid partially\n * committed state, and emit a warning containing the edge id and original failure reason.\n *\n * A production-quality implementation would need:\n * - Explicit classification of recoverable geometry exhaustion versus malformed input and internal\n *   invariants. Invalid coordinates, containment, measurements, endpoints, and topology state must\n *   remain errors in every mode.\n * - Transactional per-edge fallback that updates pair-route, portal, instrumentation, and retry\n *   state consistently.\n * - Documented constraints that best-effort routing may relax, with deterministic output and\n *   observable warnings or metrics for every degraded edge.\n * - A matching label policy that restores provisional label-routing state before placing a label\n *   at a deterministic fallback position or omitting it.\n * - Tests for both policies using the same production paths, including hierarchy routes,\n *   self-loops, bundles, resource-limit fallbacks, and label-placement exhaustion.\n */\nexport function sparseSameContainerRoute(\n  plan: EdgeRoutePlan,\n  sources: readonly EndpointCandidate[],\n  targets: readonly EndpointCandidate[],\n  source: Node,\n  target: Node,\n  legacyRoute: () => Point[],\n  result: GridLayoutResult,\n  context: GridRoutingContext,\n  searchWorkspace: RouterSearchWorkspace,\n  overlayScratch: EndpointOverlayScratch,\n  options: GridRoutingTestOptions,\n  pairRoutes: readonly (readonly Point[])[],\n  occupied?: {\n    index: RouteOccupancyIndex;\n    pairKey: string;\n    prioritizeEndpointCandidates?: boolean;\n  }\n): Point[] {\n  const fallbackReason = context.fallbackContainers.get(plan.lcaContainerId);\n  if (fallbackReason) {\n    return runValidatedFallback({\n      context,\n      reason: fallbackReason,\n      edgeId: plan.edge.id,\n      containerId: plan.lcaContainerId,\n      route: legacyRoute,\n      isValid: (legacy) =>\n        validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) &&\n        (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)),\n    });\n  }\n  const topology = context.topologies.get(plan.lcaContainerId);\n  if (!topology) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${plan.lcaContainerId}\"`);\n  }\n  if (sources.length === 0 || targets.length === 0) {\n    if (context.metrics) {\n      context.metrics.routesImpossible++;\n    }\n    throw gridError(\n      'GRID_ROUTE_NOT_FOUND',\n      plan.bundleSize > 1\n        ? `No distinct lane route for \"${plan.edge.id}\"`\n        : `No legal endpoint candidates for \"${plan.edge.id}\"`,\n      { edgeId: plan.edge.id }\n    );\n  }\n\n  let best: { result: RouterSearchResult; points: Point[] } | undefined;\n  let searchCap: GridRoutingResourceLimitError | undefined;\n  const pairs = sources\n    .flatMap((sourceCandidate) =>\n      targets.map((targetCandidate) => {\n        const pairRank = sourceCandidate.rank * targets.length + targetCandidate.rank;\n        const [length, bends] = endpointPairLowerBound(sourceCandidate, targetCandidate);\n        const lowerCost: RouterTupleCost = [length, bends, 0, pairRank];\n        return { sourceCandidate, targetCandidate, pairRank, lowerCost };\n      })\n    )\n    .sort(\n      (a, b) =>\n        compareTupleCost(a.lowerCost, b.lowerCost) ||\n        sideOrder(a.sourceCandidate.side) - sideOrder(b.sourceCandidate.side) ||\n        sideOrder(a.targetCandidate.side) - sideOrder(b.targetCandidate.side)\n    );\n\n  // Candidate pairs are ordered by an admissible lower bound. Once a completed route is no worse\n  // than that bound, neither this pair nor any remaining pair can improve the current best.\n  const searchPairs = (\n    avoidOccupied: boolean,\n    mode: 'all' | 'preferred' | 'assigned-side' = 'all'\n  ): void => {\n    const arcAllowed: ((from: RouterPoint, to: RouterPoint) => boolean) | undefined =\n      plan.bundleSize > 1 || avoidOccupied\n        ? (from, to) =>\n            (plan.bundleSize <= 1 || pairArcAllowed(from, to, pairRoutes)) &&\n            !(avoidOccupied && occupied!.index.conflictsWithArc(from, to, occupied!.pairKey))\n        : undefined;\n    for (const { sourceCandidate, targetCandidate, pairRank, lowerCost } of pairs) {\n      if (mode === 'preferred' && pairRank !== 0) {\n        continue;\n      }\n      if (\n        mode === 'assigned-side' &&\n        (sourceCandidate.onAssignedSide === false || targetCandidate.onAssignedSide === false)\n      ) {\n        continue;\n      }\n      if (best && compareTupleCost(best.result.cost, lowerCost) <= 0) {\n        break;\n      }\n      try {\n        assertSearchBudgetAvailable({\n          metrics: context.metrics,\n          caps: options.searchCaps,\n          budget: context.searchBudget,\n        });\n        const overlay = buildEndpointRoutingOverlay(\n          topology,\n          sourceCandidate.connect,\n          targetCandidate.connect,\n          context.metrics,\n          overlayScratch,\n          plan.bundleSize > 1 &&\n            (sourceCandidate.connect.x === targetCandidate.connect.x ||\n              sourceCandidate.connect.y === targetCandidate.connect.y)\n            ? [\n                {\n                  x: (sourceCandidate.connect.x + targetCandidate.connect.x) / 2,\n                  y: (sourceCandidate.connect.y + targetCandidate.connect.y) / 2,\n                },\n              ]\n            : []\n        );\n        const liveEstimatedBytes =\n          context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;\n        if (\n          liveEstimatedBytes >\n          (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)\n        ) {\n          throw new GridRoutingResourceLimitError(\n            'estimated_memory_cap',\n            'Grid routing estimated_memory_cap exceeded'\n          );\n        }\n        if (context.metrics) {\n          context.metrics.estimatedBytes = Math.max(\n            context.metrics.estimatedBytes,\n            liveEstimatedBytes\n          );\n        }\n        const sourceId = overlay.pointVertexIds.get(routingPointKey(sourceCandidate.connect));\n        const targetId = overlay.pointVertexIds.get(routingPointKey(targetCandidate.connect));\n        if (sourceId === undefined || targetId === undefined) {\n          throw gridError(\n            'GRID_ROUTE_NOT_FOUND',\n            `Endpoint projection is missing from the routing overlay for \"${plan.edge.id}\"`,\n            {\n              edgeId: plan.edge.id,\n              containerId: plan.lcaContainerId,\n              source: sourceCandidate.connect,\n              target: targetCandidate.connect,\n            }\n          );\n        }\n        const sourceOrientation: GridOrientation =\n          sourceCandidate.side === 'left' || sourceCandidate.side === 'right' ? 'H' : 'V';\n        const targetOrientation: GridOrientation =\n          targetCandidate.side === 'left' || targetCandidate.side === 'right' ? 'H' : 'V';\n        const resultForPair = findShortestRoute(overlay, sourceId, targetId, {\n          metrics: context.metrics,\n          caps: {\n            ...options.searchCaps,\n            maxEstimatedBytes:\n              options.searchCaps?.maxEstimatedBytes ??\n              options.topologyCaps?.maxEstimatedBytes ??\n              DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n          },\n          endpointCandidateRank: pairRank,\n          recordOutcome: false,\n          budget: context.searchBudget,\n          initialOrientation: sourceOrientation,\n          initialLength: TERMINAL_APPROACH_PX,\n          targetOrientation,\n          targetLength: TERMINAL_APPROACH_PX,\n          topologyValidated: true,\n          workspace: searchWorkspace,\n          estimatedBytesBase: liveEstimatedBytes,\n          arcAllowed,\n        });\n        if (!resultForPair) {\n          continue;\n        }\n        const points = normalizePolyline([\n          sourceCandidate.port,\n          ...resultForPair.points,\n          targetCandidate.port,\n        ]).points;\n        if (!validateSameContainerRoute(points, source, target, plan.lcaContainerId, result)) {\n          continue;\n        }\n        if (plan.bundleSize > 1 && !routeSatisfiesPairConstraints(points, pairRoutes)) {\n          continue;\n        }\n        if (avoidOccupied && occupied!.index.conflictsWithRoute(points, occupied!.pairKey)) {\n          continue;\n        }\n        if (!best || compareTupleCost(resultForPair.cost, best.result.cost) < 0) {\n          best = { result: resultForPair, points };\n          searchCap = undefined;\n        }\n      } catch (error) {\n        if (!(error instanceof GridRoutingResourceLimitError)) {\n          throw error;\n        }\n        if (best) {\n          break;\n        }\n        searchCap = error;\n        break;\n      }\n    }\n  };\n  // Prefer a route that does not share a corridor with another edge. Sharing is the last resort,\n  // so a failed constrained search retries without it instead of reporting no route.\n  const avoidOccupied = occupied !== undefined && occupied.index.size > 0;\n  if (occupied?.prioritizeEndpointCandidates) {\n    // The assigned ports win unless another pair on the same sides at coordinated owners is cheaper,\n    // which avoids accepting a legal but contorted route for the assigned ports.\n    searchPairs(avoidOccupied, 'preferred');\n    searchPairs(avoidOccupied, 'assigned-side');\n  }\n  if (!best) {\n    searchPairs(avoidOccupied);\n  }\n  if (!best && !searchCap && occupied !== undefined && occupied.index.size > 0) {\n    searchPairs(false);\n  }\n  if (searchCap) {\n    // Resource caps select the compatibility route only after it passes the same geometry and bundle\n    // constraints; caps never weaken correctness.\n    return runValidatedFallback({\n      context,\n      reason: searchCap.reason,\n      edgeId: plan.edge.id,\n      containerId: plan.lcaContainerId,\n      searchStateScope: searchCap.searchStateScope,\n      route: legacyRoute,\n      isValid: (legacy) =>\n        validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) &&\n        (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)),\n    });\n  }\n  if (!best) {\n    if (context.metrics) {\n      context.metrics.routesImpossible++;\n    }\n    throw gridError(\n      'GRID_ROUTE_NOT_FOUND',\n      plan.bundleSize > 1\n        ? `No distinct lane route for \"${plan.edge.id}\"`\n        : `No cell-aware route for \"${plan.edge.id}\"`,\n      {\n        edgeId: plan.edge.id,\n      }\n    );\n  }\n  if (options.onDualRouteComparison) {\n    const legacy = legacyRoute();\n    const sparseNormalized = normalizePolyline(best.points);\n    const legacyNormalized = normalizePolyline(legacy);\n    options.onDualRouteComparison({\n      edgeId: plan.edge.id,\n      sparse: {\n        valid: true,\n        length: manhattanLength(sparseNormalized.points),\n        bends: sparseNormalized.bends,\n      },\n      legacy: {\n        valid: validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result),\n        length: manhattanLength(legacyNormalized.points),\n        bends: legacyNormalized.bends,\n      },\n    });\n  }\n  return best.points;\n}\n\nfunction selfLoopAttachments(\n  owner: Node,\n  side: GridSide,\n  index: number\n): { start: EndpointCandidate; target: EndpointCandidate } | undefined {\n  const interval = sideInterval(owner, side);\n  if (!interval || interval.high - interval.low < SELF_LOOP_PORT_GAP) {\n    return undefined;\n  }\n  const rect = rectForNode(owner);\n  const center = (interval.low + interval.high) / 2;\n  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;\n  const coordinates = [\n    center - SELF_LOOP_PORT_GAP / 2 - portOffset,\n    center + SELF_LOOP_PORT_GAP / 2 + portOffset,\n  ];\n  if (coordinates[0] < interval.low || coordinates[1] > interval.high) {\n    return undefined;\n  }\n  const candidate = (coordinate: number): EndpointCandidate => {\n    const port =\n      side === 'left' || side === 'right'\n        ? { x: side === 'left' ? rect.left : rect.right, y: coordinate }\n        : { x: coordinate, y: side === 'top' ? rect.top : rect.bottom };\n    return {\n      ownerId: owner.id,\n      side,\n      port,\n      connect: {\n        x:\n          port.x +\n          (side === 'left' ? -TERMINAL_APPROACH_PX : side === 'right' ? TERMINAL_APPROACH_PX : 0),\n        y:\n          port.y +\n          (side === 'top' ? -TERMINAL_APPROACH_PX : side === 'bottom' ? TERMINAL_APPROACH_PX : 0),\n      },\n      rank: 0,\n    };\n  };\n  return { start: candidate(coordinates[0]), target: candidate(coordinates[1]) };\n}\n\nexport function sparseSelfLoopRoute(\n  plan: EdgeRoutePlan,\n  owner: Node,\n  result: GridLayoutResult,\n  context: GridRoutingContext,\n  searchWorkspace: RouterSearchWorkspace,\n  overlayScratch: EndpointOverlayScratch | undefined,\n  ownerSideCounts: Map<string, number>,\n  selfLoopCounts: Map<string, number>,\n  pairRoutes: readonly (readonly Point[])[],\n  options: GridRoutingTestOptions\n): { points: Point[]; side: GridSide; index: number } {\n  // Try sides in load order and reserve progressively wider port pairs for repeated loops on the\n  // same side.\n  const containerId = owner.parentId ?? ROOT_CONTAINER_ID;\n  const labelRequirement = result.labelRequirements.selfLoops.get(plan.edge.id);\n  const fallbackReason = context.fallbackContainers.get(containerId);\n  const legacyRoute = (): { points: Point[]; side: GridSide; index: number } =>\n    routeObstacleClearSelfLoop(\n      owner,\n      ownerSideCounts,\n      selfLoopCounts,\n      result,\n      labelRequirement,\n      context.metrics\n    );\n  if (fallbackReason) {\n    const fallback = runValidatedFallback({\n      context,\n      reason: fallbackReason,\n      edgeId: plan.edge.id,\n      containerId,\n      route: legacyRoute,\n      isValid: (legacy) =>\n        validateSameContainerRoute(legacy.points, owner, owner, containerId, result) &&\n        routeSatisfiesPairConstraints(legacy.points, pairRoutes),\n    });\n    if (labelRequirement && context.metrics) {\n      context.metrics.labelAwareSelfLoopsCommitted++;\n    }\n    return fallback;\n  }\n  const topology = context.topologies.get(containerId);\n  if (!topology || !overlayScratch) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${containerId}\"`);\n  }\n  const orderedSides = orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts);\n  if (labelRequirement) {\n    for (const side of orderedSides) {\n      const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;\n      const rect = rectForNode(owner);\n      const demandCoord = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n      const candidates = labelAwareSelfLoopCandidates(\n        owner,\n        side,\n        index,\n        demandCoord,\n        labelRequirement\n      );\n      if (context.metrics) {\n        context.metrics.labelAwareSelfLoopCandidates += candidates.length;\n      }\n      for (const points of candidates) {\n        if (\n          validateSameContainerRoute(points, owner, owner, containerId, result) &&\n          routeSatisfiesPairConstraints(points, pairRoutes)\n        ) {\n          if (context.metrics) {\n            context.metrics.labelAwareSelfLoopsCommitted++;\n          }\n          return { points, side, index };\n        }\n      }\n    }\n    if (context.metrics) {\n      context.metrics.labelAwareSelfLoopFallbacks++;\n    }\n  }\n  for (const side of orderedSides) {\n    const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;\n    const attachments = selfLoopAttachments(owner, side, index);\n    if (!attachments) {\n      continue;\n    }\n    const { start, target } = attachments;\n    try {\n      assertSearchBudgetAvailable({\n        metrics: context.metrics,\n        caps: options.searchCaps,\n        budget: context.searchBudget,\n      });\n      const overlay = buildEndpointRoutingOverlay(\n        topology,\n        start.connect,\n        target.connect,\n        context.metrics,\n        overlayScratch,\n        [\n          {\n            x: (start.connect.x + target.connect.x) / 2,\n            y: (start.connect.y + target.connect.y) / 2,\n          },\n        ]\n      );\n      const sourceId = overlay.pointVertexIds.get(routingPointKey(start.connect));\n      const targetId = overlay.pointVertexIds.get(routingPointKey(target.connect));\n      if (sourceId === undefined || targetId === undefined) {\n        throw gridError(\n          'GRID_ROUTE_NOT_FOUND',\n          `Self-loop endpoint projection is missing from the routing overlay for \"${plan.edge.id}\"`,\n          {\n            edgeId: plan.edge.id,\n            containerId,\n            source: start.connect,\n            target: target.connect,\n            side,\n          }\n        );\n      }\n      const orientation: GridOrientation = side === 'left' || side === 'right' ? 'H' : 'V';\n      const route = findShortestRoute(overlay, sourceId, targetId, {\n        metrics: context.metrics,\n        caps: {\n          ...options.searchCaps,\n          maxEstimatedBytes:\n            options.searchCaps?.maxEstimatedBytes ??\n            options.topologyCaps?.maxEstimatedBytes ??\n            DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n        },\n        recordOutcome: false,\n        budget: context.searchBudget,\n        initialOrientation: orientation,\n        initialSide: side,\n        initialLength: TERMINAL_APPROACH_PX,\n        targetOrientation: orientation,\n        targetSide: side,\n        targetLength: TERMINAL_APPROACH_PX,\n        topologyValidated: true,\n        workspace: searchWorkspace,\n        estimatedBytesBase:\n          context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes,\n        arcAllowed: (from, to) => pairArcAllowed(from, to, pairRoutes),\n      });\n      if (!route) {\n        continue;\n      }\n      const points = normalizePolyline([start.port, ...route.points, target.port]).points;\n      if (\n        validateSameContainerRoute(points, owner, owner, containerId, result) &&\n        routeSatisfiesPairConstraints(points, pairRoutes)\n      ) {\n        return {\n          points,\n          side,\n          index,\n        };\n      }\n    } catch (error) {\n      if (!(error instanceof GridRoutingResourceLimitError)) {\n        throw error;\n      }\n      const fallback = runValidatedFallback({\n        context,\n        reason: error.reason,\n        edgeId: plan.edge.id,\n        containerId,\n        searchStateScope: error.searchStateScope,\n        route: legacyRoute,\n        isValid: (legacy) =>\n          validateSameContainerRoute(legacy.points, owner, owner, containerId, result) &&\n          routeSatisfiesPairConstraints(legacy.points, pairRoutes),\n      });\n      if (labelRequirement && context.metrics) {\n        context.metrics.labelAwareSelfLoopsCommitted++;\n      }\n      return fallback;\n    }\n  }\n  if (context.metrics) {\n    context.metrics.routesImpossible++;\n  }\n  throw gridError('GRID_ROUTE_NOT_FOUND', `No distinct self-loop route for \"${plan.edge.id}\"`, {\n    edgeId: plan.edge.id,\n    nodeId: owner.id,\n  });\n}\n\nexport function sparseContainerSegment(\n  edgeId: string,\n  containerId: GridContainerId,\n  start: SegmentAttachment,\n  end: SegmentAttachment,\n  legacyRoute: () => Point[],\n  result: GridLayoutResult,\n  context: GridRoutingContext,\n  searchWorkspace: RouterSearchWorkspace,\n  overlayScratch: EndpointOverlayScratch | undefined,\n  options: GridRoutingTestOptions,\n  pairRoutes: readonly (readonly Point[])[] = [],\n  endAlternatives: () => readonly SegmentAttachmentAlternative[] = () => [],\n  startAlternatives: () => readonly SegmentAttachmentAlternative[] = () => [],\n  allowSharedPairCorridors = false,\n  occupied?: { index: RouteOccupancyIndex; pairKey: string }\n): Point[] {\n  const fallbackReason = context.fallbackContainers.get(containerId);\n  if (fallbackReason) {\n    return runValidatedFallback({\n      context,\n      reason: fallbackReason,\n      edgeId,\n      containerId,\n      route: legacyRoute,\n      isValid: (legacy) =>\n        validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) &&\n        routeSatisfiesPairConstraints(legacy, pairRoutes),\n      includeContainerIdInError: true,\n    });\n  }\n  const topology = context.topologies.get(containerId);\n  if (!topology || !overlayScratch) {\n    throw gridError('GRID_ROUTE_NOT_FOUND', `Missing routing topology \"${containerId}\"`);\n  }\n  const attempts: {\n    start: SegmentAttachment;\n    end: SegmentAttachment;\n    select: readonly (() => void)[];\n  }[] = [{ start, end, select: [] }];\n  // Alternatives are generated lazily only after the selected attachments fail. Their `select`\n  // callbacks commit portal-coordinate changes after a complete route validates.\n  let alternativesAdded = false;\n  const appendAlternatives = (): void => {\n    if (alternativesAdded) {\n      return;\n    }\n    alternativesAdded = true;\n    const starts = startAlternatives();\n    const ends = endAlternatives();\n    attempts.push(\n      ...ends.map((alternative) => ({\n        start,\n        end: alternative.attachment,\n        select: [alternative.select],\n      })),\n      ...starts.map((alternative) => ({\n        start: alternative.attachment,\n        end,\n        select: [alternative.select],\n      })),\n      ...starts.flatMap((startAlternative) =>\n        ends.map((endAlternative) => ({\n          start: startAlternative.attachment,\n          end: endAlternative.attachment,\n          select: [startAlternative.select, endAlternative.select],\n        }))\n      )\n    );\n  };\n  // Prefer attachments and corridors that do not run along another edge. Sharing is the last\n  // resort, so a failed constrained pass retries without it.\n  const passes = occupied !== undefined && occupied.index.size > 0 ? [true, false] : [false];\n  try {\n    for (const avoidOccupied of passes) {\n      for (const [attemptIndex, attempt] of attempts.entries()) {\n        const attemptedStart = attempt.start;\n        const attemptedEnd = attempt.end;\n        if (attemptIndex > 0 && context.metrics) {\n          context.metrics.hierarchyPortalAlternativeAttempts++;\n        }\n        const aligned = areExactlyAxisAligned(attemptedStart.connect, attemptedEnd.connect);\n        if (aligned) {\n          const direct = normalizePolyline([\n            attemptedStart.port,\n            attemptedStart.connect,\n            attemptedEnd.connect,\n            attemptedEnd.port,\n          ]).points;\n          if (\n            validateContainerSegment(\n              direct,\n              attemptedStart.ownerId,\n              attemptedEnd.ownerId,\n              containerId,\n              result\n            ) &&\n            routeSatisfiesPairConstraints(direct, pairRoutes) &&\n            !(avoidOccupied && occupied!.index.conflictsWithRoute(direct, occupied!.pairKey))\n          ) {\n            for (const select of attempt.select) {\n              select();\n            }\n            if (attemptIndex > 0 && context.metrics) {\n              context.metrics.hierarchyPortalAlternativeSelections++;\n            }\n            return direct;\n          }\n        }\n        assertSearchBudgetAvailable({\n          metrics: context.metrics,\n          caps: options.searchCaps,\n          budget: context.searchBudget,\n        });\n        const overlay = buildEndpointRoutingOverlay(\n          topology,\n          attemptedStart.connect,\n          attemptedEnd.connect,\n          context.metrics,\n          overlayScratch\n        );\n        const liveEstimatedBytes =\n          context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;\n        if (\n          liveEstimatedBytes >\n          (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)\n        ) {\n          throw new GridRoutingResourceLimitError(\n            'estimated_memory_cap',\n            'Grid routing estimated_memory_cap exceeded'\n          );\n        }\n        const sourceId = overlay.pointVertexIds.get(routingPointKey(attemptedStart.connect));\n        const targetId = overlay.pointVertexIds.get(routingPointKey(attemptedEnd.connect));\n        if (sourceId === undefined || targetId === undefined) {\n          if (attemptIndex === 0) {\n            appendAlternatives();\n          }\n          continue;\n        }\n        const route = findShortestRoute(overlay, sourceId, targetId, {\n          metrics: context.metrics,\n          caps: {\n            ...options.searchCaps,\n            maxEstimatedBytes:\n              options.searchCaps?.maxEstimatedBytes ??\n              options.topologyCaps?.maxEstimatedBytes ??\n              DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,\n          },\n          recordOutcome: false,\n          budget: context.searchBudget,\n          initialOrientation:\n            attemptedStart.side === 'left' || attemptedStart.side === 'right' ? 'H' : 'V',\n          initialSide: attemptedStart.side,\n          initialLength:\n            Math.abs(attemptedStart.port.x - attemptedStart.connect.x) +\n            Math.abs(attemptedStart.port.y - attemptedStart.connect.y),\n          targetOrientation:\n            attemptedEnd.side === 'left' || attemptedEnd.side === 'right' ? 'H' : 'V',\n          targetSide: attemptedEnd.side,\n          targetLength:\n            Math.abs(attemptedEnd.port.x - attemptedEnd.connect.x) +\n            Math.abs(attemptedEnd.port.y - attemptedEnd.connect.y),\n          topologyValidated: true,\n          workspace: searchWorkspace,\n          estimatedBytesBase: liveEstimatedBytes,\n          arcAllowed:\n            pairRoutes.length > 0 || avoidOccupied\n              ? (from, to) =>\n                  (pairRoutes.length === 0 || pairArcAllowed(from, to, pairRoutes)) &&\n                  !(avoidOccupied && occupied!.index.conflictsWithArc(from, to, occupied!.pairKey))\n              : undefined,\n        });\n        if (!route) {\n          if (attemptIndex === 0) {\n            appendAlternatives();\n          }\n          continue;\n        }\n        const points = normalizePolyline([\n          attemptedStart.port,\n          ...route.points,\n          attemptedEnd.port,\n        ]).points;\n        if (\n          !validateContainerSegment(\n            points,\n            attemptedStart.ownerId,\n            attemptedEnd.ownerId,\n            containerId,\n            result\n          ) ||\n          !routeSatisfiesPairConstraints(points, pairRoutes) ||\n          (avoidOccupied && occupied!.index.conflictsWithRoute(points, occupied!.pairKey))\n        ) {\n          if (attemptIndex === 0) {\n            appendAlternatives();\n          }\n          continue;\n        }\n        for (const select of attempt.select) {\n          select();\n        }\n        if (attemptIndex > 0 && context.metrics) {\n          context.metrics.hierarchyPortalAlternativeSelections++;\n        }\n        return points;\n      }\n    }\n  } catch (error) {\n    if (!(error instanceof GridRoutingResourceLimitError)) {\n      throw error;\n    }\n    return runValidatedFallback({\n      context,\n      reason: error.reason,\n      edgeId,\n      containerId,\n      searchStateScope: error.searchStateScope,\n      route: legacyRoute,\n      isValid: (legacy) =>\n        validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) &&\n        routeSatisfiesPairConstraints(legacy, pairRoutes),\n      includeContainerIdInError: true,\n    });\n  }\n  const compatibility = legacyRoute();\n  // Exhausted sparse geometry may recover through the corridor router. Bundled hierarchy segments\n  // can share interior corridors only when their endpoint ports remain distinct.\n  if (\n    validateContainerSegment(compatibility, start.ownerId, end.ownerId, containerId, result) &&\n    (routeSatisfiesPairConstraints(compatibility, pairRoutes) ||\n      (allowSharedPairCorridors && routeHasDistinctPairPorts(compatibility, pairRoutes)))\n  ) {\n    if (context.metrics) {\n      context.metrics.compatibilitySegments++;\n      context.metrics.compatibilityRecoveries++;\n    }\n    return compatibility;\n  }\n  throw gridError(\n    'GRID_ROUTE_NOT_FOUND',\n    `No hierarchy route for \"${edgeId}\" in \"${containerId}\" from ${routingPointKey(start.connect)} to ${routingPointKey(end.connect)}`,\n    { edgeId, containerId }\n  );\n}\n", "import type { Point } from '../../../types.js';\nimport type { Edge, LayoutData } from '../../types.js';\nimport { clamp, rectForNode } from '../layout-utils/helpers.js';\nimport type { GridRoutingTestOptions } from './router.js';\nimport {\n  boundedAlternativePortalCoordinates,\n  buildRoutingContext,\n  combinePointChains,\n  compatibilityHierarchyAttachments,\n  compatibilityLcaAttachments,\n  groupBoundaryEndpointAttachment,\n  itemAttachment,\n  portalAttachment,\n  prepareRoutingModes,\n  reversePoints,\n  rootContainerMeta,\n  routeWithinContainer,\n  validatedCompatibilitySegment,\n  type PreparedRoutingModes,\n  type SegmentAttachment,\n  type SegmentAttachmentAlternative,\n} from './routerCompatibility.js';\nimport {\n  isPairSeparationError,\n  routeHasDistinctPairPorts,\n  routeSatisfiesPairConstraints,\n  routerRect,\n} from './routerConstraint.js';\nimport {\n  ownerGroupTitle,\n  ownerSideKey,\n  prepareEdgeRoutes,\n  sideInterval,\n  type EdgeEndpointEntry,\n  type EdgeEndpointPlan,\n  type EdgeRoutePlan,\n  type PreparedEdgeRoutes,\n} from './routerPlanning.js';\nimport {\n  createGridRoutingInstrumentationCheckpoint,\n  recordGridRoute,\n  restoreGridRoutingInstrumentationCheckpoint,\n  type GridRoutingInstrumentation,\n  type GridRoutingInstrumentationCheckpoint,\n} from './routerInstrumentation.js';\nimport { RouteOccupancyIndex } from './routerOccupancy.js';\nimport { RouterSearchWorkspace } from './routerSearch.js';\nimport {\n  sparseContainerSegment,\n  sparseSameContainerRoute,\n  sparseSelfLoopRoute,\n} from './routerSparse.js';\nimport { buildPairedPortal, derivePortalRanges, EndpointOverlayScratch } from './routerTopology.js';\nimport type {\n  GridContainerId,\n  GridLayoutResult,\n  GridRoutingContext,\n  PairedPortal,\n} from './types.js';\nimport { ROOT_CONTAINER_ID, gridError } from './types.js';\n\n// The session is the transaction boundary for one routing invocation. It owns mutable reservations,\n// reusable search memory, and retry state while the base layout geometry remains read-only.\ninterface BundleEdgeCheckpoint {\n  edge: Edge;\n  // Geometry and its rendering contract commit together; retries must not leak either half.\n  points: Edge['points'];\n  curve: Edge['curve'];\n  cornerRadius: Edge['cornerRadius'];\n}\n\ninterface BundleCheckpoint {\n  pairKey: string;\n  occupancy: { index: RouteOccupancyIndex; size: number } | undefined;\n  pairRoutes: Point[][] | undefined;\n  demandKeys: string[];\n  pairedPortals: Map<string, PairedPortal>;\n  demandCoords: Map<string, number>;\n  edges: BundleEdgeCheckpoint[];\n  instrumentedRoutesLength: number | undefined;\n  metrics: GridRoutingInstrumentationCheckpoint | undefined;\n}\n\nfunction createBundleCheckpoint(\n  pairPlans: readonly EdgeRoutePlan[],\n  pairRoutes: ReadonlyMap<string, Point[][]>,\n  pairedPortals: ReadonlyMap<string, PairedPortal>,\n  demandCoords: ReadonlyMap<string, number>,\n  instrumentedRoutes: readonly Point[][] | undefined,\n  metrics: GridRoutingInstrumentation | undefined,\n  routeOccupancy: ReadonlyMap<GridContainerId, RouteOccupancyIndex>\n): BundleCheckpoint {\n  // Snapshot only state a failed bundle can mutate. Topologies and prepared plans are immutable and\n  // intentionally shared across attempts.\n  const pairKey = pairPlans[0].pairKey;\n  const committedPairRoutes = pairRoutes.get(pairKey);\n  const demandKeys = [\n    ...new Set(\n      pairPlans.flatMap((plan) =>\n        [...plan.source.chain, ...plan.target.chain].map(({ demandKey }) => demandKey)\n      )\n    ),\n  ];\n  const bundlePairedPortals = new Map<string, PairedPortal>();\n  const bundleDemandCoords = new Map<string, number>();\n  for (const demandKey of demandKeys) {\n    const portal = pairedPortals.get(demandKey);\n    if (portal) {\n      bundlePairedPortals.set(demandKey, portal);\n    }\n    const coordinate = demandCoords.get(demandKey);\n    if (coordinate !== undefined) {\n      bundleDemandCoords.set(demandKey, coordinate);\n    }\n  }\n  // Pair members share endpoints, so they share one LCA container and one occupancy index.\n  const occupancyIndex = routeOccupancy.get(pairPlans[0].lcaContainerId);\n  return {\n    pairKey,\n    occupancy: occupancyIndex ? { index: occupancyIndex, size: occupancyIndex.size } : undefined,\n    pairRoutes: committedPairRoutes ? [...committedPairRoutes] : undefined,\n    demandKeys,\n    pairedPortals: bundlePairedPortals,\n    demandCoords: bundleDemandCoords,\n    edges: pairPlans.map(({ edge }) => ({\n      edge,\n      points: edge.points,\n      curve: edge.curve,\n      cornerRadius: edge.cornerRadius,\n    })),\n    instrumentedRoutesLength: instrumentedRoutes?.length,\n    metrics: metrics ? createGridRoutingInstrumentationCheckpoint(metrics) : undefined,\n  };\n}\n\nfunction restoreBundleCheckpoint(\n  checkpoint: BundleCheckpoint,\n  pairRoutes: Map<string, Point[][]>,\n  pairedPortals: Map<string, PairedPortal>,\n  demandCoords: Map<string, number>,\n  instrumentedRoutes: Point[][] | undefined,\n  metrics: GridRoutingInstrumentation | undefined\n): void {\n  checkpoint.occupancy?.index.truncate(checkpoint.occupancy.size);\n  if (checkpoint.pairRoutes) {\n    pairRoutes.set(checkpoint.pairKey, [...checkpoint.pairRoutes]);\n  } else {\n    pairRoutes.delete(checkpoint.pairKey);\n  }\n  for (const demandKey of checkpoint.demandKeys) {\n    const portal = checkpoint.pairedPortals.get(demandKey);\n    if (portal) {\n      pairedPortals.set(demandKey, portal);\n    } else {\n      pairedPortals.delete(demandKey);\n    }\n    const coordinate = checkpoint.demandCoords.get(demandKey);\n    if (coordinate !== undefined) {\n      demandCoords.set(demandKey, coordinate);\n    } else {\n      demandCoords.delete(demandKey);\n    }\n  }\n  for (const edgeCheckpoint of checkpoint.edges) {\n    edgeCheckpoint.edge.points = edgeCheckpoint.points;\n    edgeCheckpoint.edge.curve = edgeCheckpoint.curve;\n    edgeCheckpoint.edge.cornerRadius = edgeCheckpoint.cornerRadius;\n  }\n  if (instrumentedRoutes && checkpoint.instrumentedRoutesLength !== undefined) {\n    instrumentedRoutes.length = checkpoint.instrumentedRoutesLength;\n  }\n  if (metrics && checkpoint.metrics) {\n    restoreGridRoutingInstrumentationCheckpoint(metrics, checkpoint.metrics);\n  }\n}\n\nexport class GridEdgeRoutingSession {\n  private prepared!: PreparedEdgeRoutes;\n  private modes!: PreparedRoutingModes;\n  private routingContext!: GridRoutingContext;\n  private readonly searchWorkspace = new RouterSearchWorkspace();\n  private endpointOverlayScratch!: Map<GridContainerId, EndpointOverlayScratch>;\n  private readonly pairedPortals = new Map<string, PairedPortal>();\n  private readonly ownerSideCounts = new Map<string, number>();\n  private instrumentedRoutes!: Point[][] | undefined;\n  private readonly selfLoopCounts = new Map<string, number>();\n  private readonly pairRoutes = new Map<string, Point[][]>();\n  private routed = false;\n\n  constructor(\n    private readonly layout: LayoutData,\n    private readonly result: GridLayoutResult,\n    private readonly metrics: GridRoutingInstrumentation | undefined,\n    private readonly options: GridRoutingTestOptions\n  ) {}\n\n  route(): void {\n    if (this.routed) {\n      throw new Error('Grid edge routing session can only be run once');\n    }\n    this.routed = true;\n    this.prepare();\n\n    // Pair insertion order follows the already canonical plan order; Map preserves that order when\n    // bundles are routed as indivisible retry units.\n    const plansByPair = new Map<string, EdgeRoutePlan[]>();\n    for (const plan of this.prepared.orderedPlans) {\n      const pairPlans = plansByPair.get(plan.pairKey) ?? [];\n      pairPlans.push(plan);\n      plansByPair.set(plan.pairKey, pairPlans);\n    }\n    for (const pairPlans of plansByPair.values()) {\n      this.routeBundle(pairPlans);\n    }\n  }\n\n  private prepare(): void {\n    // Preparation is front-loaded so routing attempts never observe partially built planning or\n    // topology state.\n    rootContainerMeta(this.result);\n    this.prepared = prepareEdgeRoutes(this.layout, this.result);\n\n    this.modes = prepareRoutingModes(this.prepared, this.result, this.metrics, this.options);\n    this.routingContext = buildRoutingContext(\n      this.modes.routedContainerIds,\n      this.result,\n      this.metrics,\n      this.options\n    );\n    this.endpointOverlayScratch = new Map(\n      [...this.routingContext.topologies].map(([containerId, topology]) => [\n        containerId,\n        new EndpointOverlayScratch(topology),\n      ])\n    );\n    this.instrumentedRoutes = this.metrics ? [] : undefined;\n    const countedDemandKeys = new Set<string>();\n    for (const plan of this.prepared.orderedPlans) {\n      if (plan.edge.start === plan.edge.end) {\n        continue;\n      }\n      for (const entry of [...plan.source.chain, ...plan.target.chain]) {\n        if (countedDemandKeys.has(entry.demandKey)) {\n          continue;\n        }\n        countedDemandKeys.add(entry.demandKey);\n        const key = ownerSideKey(entry.ownerId, entry.side);\n        this.ownerSideCounts.set(key, (this.ownerSideCounts.get(key) ?? 0) + 1);\n      }\n    }\n  }\n\n  private pairedPortal(entry: EdgeEndpointEntry): PairedPortal {\n    const existing = this.pairedPortals.get(entry.demandKey);\n    if (existing) {\n      return existing;\n    }\n    const owner = this.result.forest.nodeById.get(entry.ownerId);\n    if (!owner?.isGroup) {\n      throw gridError('GRID_ROUTE_NOT_FOUND', `Missing portal owner \"${entry.ownerId}\"`);\n    }\n    const rect = routerRect(owner);\n    const coordinate =\n      this.prepared.demandCoords.get(entry.demandKey) ??\n      (entry.side === 'left' || entry.side === 'right'\n        ? (rect.top + rect.bottom) / 2\n        : (rect.left + rect.right) / 2);\n    const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(\n      ({ side }) => side === entry.side\n    );\n    if (!range) {\n      throw gridError(\n        'GRID_ROUTE_NOT_FOUND',\n        `No legal ${entry.side} portal for \"${entry.ownerId}\"`\n      );\n    }\n    const portal = buildPairedPortal(\n      entry.ownerId,\n      rect,\n      owner.groupTitleRect ? { ...owner.groupTitleRect } : undefined,\n      entry.side,\n      clamp(coordinate, range.low, range.high)\n    );\n    this.pairedPortals.set(entry.demandKey, portal);\n    if (this.metrics) {\n      this.metrics.hierarchyPortalPairs++;\n      this.metrics.hierarchyPortalTransitionLength += portal.transition.length;\n    }\n    return portal;\n  }\n\n  private alternativePairedPortals(\n    entry: EdgeEndpointEntry,\n    interior = true\n  ): SegmentAttachmentAlternative[] {\n    const selected = this.pairedPortal(entry);\n    const owner = this.result.forest.nodeById.get(entry.ownerId);\n    if (!owner?.isGroup) {\n      return [];\n    }\n    const rect = routerRect(owner);\n    const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(\n      ({ side }) => side === entry.side\n    );\n    if (!range) {\n      return [];\n    }\n    const container = this.result.containers.get(owner.id);\n    const corridors =\n      entry.side === 'left' || entry.side === 'right'\n        ? container?.horizontalCorridors\n        : container?.verticalCorridors;\n    // Keep retries bounded and deterministic: nearby established corridors are preferred, with\n    // range endpoints available when the originally selected portal blocks a hierarchy segment.\n    return boundedAlternativePortalCoordinates(\n      selected.tangentialCoordinate,\n      range.low,\n      range.high,\n      corridors ?? []\n    ).map((coordinate) => {\n      const portal = buildPairedPortal(\n        entry.ownerId,\n        rect,\n        owner.groupTitleRect ? { ...owner.groupTitleRect } : undefined,\n        entry.side,\n        coordinate\n      );\n      return {\n        attachment: portalAttachment(portal, interior),\n        select: () => {\n          this.pairedPortals.set(entry.demandKey, portal);\n          this.prepared.demandCoords.set(entry.demandKey, coordinate);\n        },\n      };\n    });\n  }\n\n  private itemSegmentAttachment(\n    entry: EdgeEndpointEntry,\n    containerId: GridContainerId\n  ): SegmentAttachment {\n    return {\n      ownerId: entry.ownerId,\n      ...itemAttachment(\n        entry.ownerId,\n        entry.side,\n        entry.demandKey,\n        containerId,\n        this.result,\n        this.prepared.demandCoords\n      ),\n    };\n  }\n\n  private alternativeItemAttachments(\n    plan: EdgeRoutePlan,\n    entry: EdgeEndpointEntry,\n    containerId: GridContainerId\n  ): SegmentAttachmentAlternative[] {\n    const current = this.itemSegmentAttachment(entry, containerId);\n    const owner = this.result.forest.nodeById.get(entry.ownerId);\n    if (!owner) {\n      return [];\n    }\n    return (['right', 'bottom', 'left', 'top'] as const)\n      .filter((side) => side !== current.side && !(side === 'top' && ownerGroupTitle(owner)))\n      .map((side) => {\n        const interval = sideInterval(owner, side);\n        if (!interval) {\n          return undefined;\n        }\n        const rect = rectForNode(owner);\n        const center = side === 'left' || side === 'right' ? rect.cy : rect.cx;\n        const coordinate = Math.max(\n          interval.low,\n          Math.min(interval.high, center + plan.laneOffset)\n        );\n        return {\n          ownerId: entry.ownerId,\n          ...itemAttachment(\n            entry.ownerId,\n            side,\n            entry.demandKey,\n            containerId,\n            this.result,\n            this.prepared.demandCoords,\n            coordinate\n          ),\n        };\n      })\n      .filter((attachment): attachment is SegmentAttachment => attachment !== undefined)\n      .slice(0, 3)\n      .map((attachment) => ({\n        attachment,\n        select: () => undefined,\n      }));\n  }\n\n  private routePlan(plan: EdgeRoutePlan, allowHierarchyRelaxation = true): void {\n    // A plan is routed in three phases: source ascent, one LCA-container segment, and reversed\n    // target descent. The chains are committed only after the combined route satisfies pair rules.\n    const result = this.result;\n    const routingContext = this.routingContext;\n    const searchWorkspace = this.searchWorkspace;\n    const endpointOverlayScratch = this.endpointOverlayScratch;\n    const demandCoords = this.prepared.demandCoords;\n    const ownerSideCounts = this.ownerSideCounts;\n    const selfLoopCounts = this.selfLoopCounts;\n    const pairRoutes = this.pairRoutes;\n    const instrumentedRoutes = this.instrumentedRoutes;\n    const metrics = this.metrics;\n    const options = this.options;\n    const eligibleIds = this.prepared.eligibleIds;\n    const endpointCandidatesByEdge = this.prepared.endpointCandidatesByEdge;\n    const compatibilityFastRoutes = this.modes.compatibilityFastRoutes;\n    const sparseHierarchyIds = this.modes.sparseHierarchyIds;\n    const sparseLcaIds = this.modes.sparseLcaIds;\n    const edge = plan.edge;\n    const sourceNode = edge.start ? result.forest.nodeById.get(edge.start) : undefined;\n    const targetNode = edge.end ? result.forest.nodeById.get(edge.end) : undefined;\n    if (!sourceNode || !targetNode) {\n      throw gridError('GRID_MISSING_ENDPOINT', `Missing endpoint for edge \"${edge.id}\"`, {\n        edgeId: edge.id,\n      });\n    }\n\n    if (sourceNode.id === targetNode.id) {\n      const committedPairRoutes = pairRoutes.get(plan.pairKey) ?? [];\n      const { points, side, index } = sparseSelfLoopRoute(\n        plan,\n        sourceNode,\n        result,\n        routingContext,\n        searchWorkspace,\n        endpointOverlayScratch.get(sourceNode.parentId ?? ROOT_CONTAINER_ID),\n        ownerSideCounts,\n        selfLoopCounts,\n        committedPairRoutes,\n        options\n      );\n      const countKey = `${sourceNode.id}:${side}`;\n      selfLoopCounts.set(countKey, index + 1);\n      edge.points = points;\n      // The router owns the polyline; attach its curve contract at the same commit boundary.\n      edge.curve = result.config.curve;\n      edge.cornerRadius = result.config.edgeCornerRadius;\n      committedPairRoutes.push(points);\n      pairRoutes.set(plan.pairKey, committedPairRoutes);\n      if (metrics && instrumentedRoutes) {\n        recordGridRoute(metrics, edge.id, points, instrumentedRoutes, 0, plan.laneOffset);\n        instrumentedRoutes.push(points);\n      }\n      return;\n    }\n\n    const sourceFinal = plan.source.chain[plan.source.chain.length - 1];\n    const targetFinal = plan.target.chain[plan.target.chain.length - 1];\n    const useSparseLca = sparseLcaIds.has(edge.id);\n    const compatibilityLca = useSparseLca\n      ? undefined\n      : compatibilityLcaAttachments(plan, result, demandCoords);\n    const lcaStart: SegmentAttachment = compatibilityLca\n      ? compatibilityLca.start\n      : plan.source.finalKind === 'boundary'\n        ? groupBoundaryEndpointAttachment(\n            sourceFinal.ownerId,\n            sourceFinal.side,\n            sourceFinal.demandKey,\n            result,\n            demandCoords\n          )\n        : plan.source.chain.length > 1\n          ? portalAttachment(this.pairedPortal(sourceFinal), false)\n          : this.itemSegmentAttachment(sourceFinal, plan.lcaContainerId);\n    const lcaEnd: SegmentAttachment = compatibilityLca\n      ? compatibilityLca.end\n      : plan.target.finalKind === 'boundary'\n        ? groupBoundaryEndpointAttachment(\n            targetFinal.ownerId,\n            targetFinal.side,\n            targetFinal.demandKey,\n            result,\n            demandCoords\n          )\n        : plan.target.chain.length > 1\n          ? portalAttachment(this.pairedPortal(targetFinal), false)\n          : this.itemSegmentAttachment(targetFinal, plan.lcaContainerId);\n    let legacyLcaPoints: Point[] | undefined;\n    const legacyRoute = () =>\n      (legacyLcaPoints ??= routeWithinContainer(\n        plan.lcaContainerId,\n        result,\n        lcaStart,\n        lcaEnd,\n        plan.laneIndex\n      ));\n    const compatibilityFastRoute = compatibilityFastRoutes.get(edge.id);\n    const lcaPoints = compatibilityFastRoute\n      ? (() => {\n          if (metrics) {\n            metrics.compatibilityFastPaths++;\n          }\n          return compatibilityFastRoute;\n        })()\n      : eligibleIds.has(edge.id)\n        ? sparseSameContainerRoute(\n            plan,\n            endpointCandidatesByEdge.get(edge.id)!.sources,\n            endpointCandidatesByEdge.get(edge.id)!.targets,\n            sourceNode,\n            targetNode,\n            legacyRoute,\n            result,\n            routingContext,\n            searchWorkspace,\n            endpointOverlayScratch.get(plan.lcaContainerId)!,\n            options,\n            pairRoutes.get(plan.pairKey) ?? [],\n            {\n              index: this.occupancyFor(plan.lcaContainerId),\n              pairKey: plan.pairKey,\n              prioritizeEndpointCandidates: this.prepared.coordinatedEndpointIds.has(edge.id),\n            }\n          )\n        : useSparseLca\n          ? sparseContainerSegment(\n              edge.id,\n              plan.lcaContainerId,\n              lcaStart,\n              lcaEnd,\n              legacyRoute,\n              result,\n              routingContext,\n              searchWorkspace,\n              endpointOverlayScratch.get(plan.lcaContainerId),\n              options,\n              pairRoutes.get(plan.pairKey) ?? [],\n              () =>\n                plan.target.finalKind === 'item' && plan.target.chain.length > 1\n                  ? this.alternativePairedPortals(targetFinal, false)\n                  : [],\n              () =>\n                plan.source.finalKind === 'item' && plan.source.chain.length > 1\n                  ? this.alternativePairedPortals(sourceFinal, false)\n                  : [],\n              plan.bundleSize > 1,\n              this.modes.overlapAvoidanceEnabled\n                ? { index: this.occupancyFor(plan.lcaContainerId), pairKey: plan.pairKey }\n                : undefined\n            )\n          : validatedCompatibilitySegment(\n              edge.id,\n              plan.lcaContainerId,\n              lcaStart,\n              lcaEnd,\n              legacyRoute,\n              result,\n              metrics\n            );\n\n    const routeHierarchyChain = (endpoint: EdgeEndpointPlan, chains: Point[][]): void => {\n      if (!sparseHierarchyIds.has(edge.id)) {\n        for (const { containerId, start, end } of compatibilityHierarchyAttachments(\n          endpoint,\n          result,\n          demandCoords\n        )) {\n          chains.push(\n            validatedCompatibilitySegment(\n              edge.id,\n              containerId,\n              start,\n              end,\n              () => routeWithinContainer(containerId, result, start, end, plan.laneIndex),\n              result,\n              metrics\n            )\n          );\n        }\n        return;\n      }\n      for (let index = 0; index < endpoint.chain.length - 1; index++) {\n        const from = endpoint.chain[index];\n        const to = endpoint.chain[index + 1];\n        const start =\n          index === 0\n            ? this.itemSegmentAttachment(from, to.ownerId)\n            : portalAttachment(this.pairedPortal(from), false);\n        const end = portalAttachment(this.pairedPortal(to), true);\n        chains.push(\n          sparseContainerSegment(\n            edge.id,\n            to.ownerId,\n            start,\n            end,\n            () => routeWithinContainer(to.ownerId, result, start, end, plan.laneIndex),\n            result,\n            routingContext,\n            searchWorkspace,\n            endpointOverlayScratch.get(to.ownerId),\n            options,\n            pairRoutes.get(plan.pairKey) ?? [],\n            () => this.alternativePairedPortals(to),\n            () => (index === 0 ? this.alternativeItemAttachments(plan, from, to.ownerId) : []),\n            plan.bundleSize > 1\n          )\n        );\n      }\n    };\n    const sourceChains: Point[][] = [];\n    const targetChains: Point[][] = [];\n    routeHierarchyChain(plan.source, sourceChains);\n    routeHierarchyChain(plan.target, targetChains);\n\n    const points = combinePointChains([\n      ...sourceChains,\n      lcaPoints,\n      ...targetChains.reverse().map((chain) => reversePoints(chain)),\n    ]);\n    const committedPairRoutes = pairRoutes.get(plan.pairKey) ?? [];\n    const satisfiesPairConstraints = routeSatisfiesPairConstraints(points, committedPairRoutes);\n    const relaxHierarchySeparation =\n      !satisfiesPairConstraints &&\n      plan.bundleSize > 1 &&\n      plan.source.chain.length + plan.target.chain.length > 2 &&\n      routeHasDistinctPairPorts(points, committedPairRoutes);\n    if (\n      plan.bundleSize > 1 &&\n      !satisfiesPairConstraints &&\n      (!relaxHierarchySeparation || !allowHierarchyRelaxation)\n    ) {\n      if (metrics) {\n        metrics.routesImpossible++;\n      }\n      throw gridError('GRID_ROUTE_NOT_FOUND', `No distinct lane route for \"${edge.id}\"`, {\n        edgeId: edge.id,\n        reason: relaxHierarchySeparation ? 'pair-separation' : 'no-distinct-route',\n      });\n    }\n    if (relaxHierarchySeparation && metrics) {\n      metrics.bundleSeparationRelaxations++;\n    }\n    edge.points = points;\n    // Publish style only after the route satisfies terminal and pair-separation invariants.\n    edge.curve = result.config.curve;\n    edge.cornerRadius = result.config.edgeCornerRadius;\n    committedPairRoutes.push(points);\n    pairRoutes.set(plan.pairKey, committedPairRoutes);\n    // Fast routes were registered while routing modes were prepared.\n    if (!compatibilityFastRoute) {\n      this.occupancyFor(plan.lcaContainerId).add(lcaPoints, plan.pairKey);\n    }\n    if (metrics && instrumentedRoutes) {\n      const boundaryTransitionCount = plan.source.chain.length + plan.target.chain.length - 2;\n      recordGridRoute(\n        metrics,\n        edge.id,\n        points,\n        instrumentedRoutes,\n        boundaryTransitionCount,\n        plan.laneOffset\n      );\n      instrumentedRoutes.push(points);\n    }\n  }\n\n  private occupancyFor(containerId: GridContainerId): RouteOccupancyIndex {\n    let occupancy = this.modes.routeOccupancy.get(containerId);\n    if (!occupancy) {\n      occupancy = new RouteOccupancyIndex();\n      this.modes.routeOccupancy.set(containerId, occupancy);\n    }\n    return occupancy;\n  }\n\n  private createBundleCheckpoint(pairPlans: readonly EdgeRoutePlan[]): BundleCheckpoint {\n    this.occupancyFor(pairPlans[0].lcaContainerId);\n    return createBundleCheckpoint(\n      pairPlans,\n      this.pairRoutes,\n      this.pairedPortals,\n      this.prepared.demandCoords,\n      this.instrumentedRoutes,\n      this.metrics,\n      this.modes.routeOccupancy\n    );\n  }\n\n  private restoreBundleCheckpoint(checkpoint: BundleCheckpoint): void {\n    restoreBundleCheckpoint(\n      checkpoint,\n      this.pairRoutes,\n      this.pairedPortals,\n      this.prepared.demandCoords,\n      this.instrumentedRoutes,\n      this.metrics\n    );\n  }\n\n  private routeBundle(pairPlans: EdgeRoutePlan[]): void {\n    // Small bundles first require strict pair separation. If that fails only because hierarchy\n    // interiors overlap, restore the whole bundle and retry with that separation relaxed while\n    // preserving distinct endpoint ports.\n    const canAttemptStrictSeparation =\n      pairPlans.length > 1 &&\n      pairPlans.length <= 8 &&\n      pairPlans.every(({ edge }) => edge.start !== edge.end);\n    if (!canAttemptStrictSeparation) {\n      for (const plan of pairPlans) {\n        this.routePlan(plan);\n      }\n      return;\n    }\n    // A bundle is the retry unit because earlier siblings reserve pair corridors and portals for\n    // later ones. Restore every transactional structure before relaxing separation. The cumulative\n    // search budget intentionally retains work performed by the discarded attempt.\n    const checkpoint = this.createBundleCheckpoint(pairPlans);\n    let initialError: unknown;\n    try {\n      for (const plan of pairPlans) {\n        this.routePlan(plan, false);\n      }\n      return;\n    } catch (error) {\n      initialError = error;\n      this.restoreBundleCheckpoint(checkpoint);\n    }\n\n    if (!isPairSeparationError(initialError)) {\n      throw initialError;\n    }\n    for (const plan of pairPlans) {\n      this.routePlan(plan);\n    }\n  }\n}\n", "import type { LayoutData } from '../../types.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport type { RouterSearchCaps } from './routerSearch.js';\nimport { GridEdgeRoutingSession } from './routerSession.js';\nimport type { TopologyResourceCaps } from './routerTopology.js';\nimport type { GridLayoutResult } from './types.js';\n\n// Public routing facade. The implementation is split by phase so callers only depend on the\n// stable options and compatibility exports that predate the module extraction.\nexport {\n  areExactlyAxisAligned,\n  boundedAlternativePortalCoordinates,\n} from './routerCompatibility.js';\nexport { validateSameContainerRoute } from './routerConstraint.js';\nexport { assignCompactPortalCoordinates } from './routerPlanning.js';\n\nexport interface GridRoutingDualRouteComparison {\n  edgeId: string;\n  sparse: { valid: boolean; length: number; bends: number };\n  legacy: { valid: boolean; length: number; bends: number };\n}\n\nexport interface GridRoutingOptions {\n  // Caps are also test seams, so enabling them deliberately bypasses compatibility fast paths.\n  topologyCaps?: TopologyResourceCaps;\n  searchCaps?: RouterSearchCaps;\n}\n\n/** @internal */\nexport interface GridRoutingTestOptions extends GridRoutingOptions {\n  onDualRouteComparison?: (comparison: GridRoutingDualRouteComparison) => void;\n}\n\nexport function routeGridEdges(\n  layout: LayoutData,\n  result: GridLayoutResult,\n  metrics?: GridRoutingInstrumentation,\n  options?: GridRoutingOptions\n): void;\nexport function routeGridEdges(\n  layout: LayoutData,\n  result: GridLayoutResult,\n  metrics?: GridRoutingInstrumentation,\n  options: GridRoutingTestOptions = {}\n): void {\n  // A fresh session owns every mutable routing structure and commits routes in deterministic order.\n  new GridEdgeRoutingSession(layout, result, metrics, options).route();\n}\n", "import type { LayoutData, Node } from '../../types.js';\nimport { positionGridEdgeLabels } from './edgeLabels.js';\nimport { buildGridForest } from './groups.js';\nimport { buildGridLabelRequirements, deriveGridContainerLabelGaps } from './labelSpacing.js';\nimport {\n  buildGridSourceOrder,\n  readGridConfig,\n  resolveGridPlacements,\n  validateGridPlacementMap,\n} from './placement.js';\nimport { routeGridEdges, type GridRoutingTestOptions } from './router.js';\nimport type { GridRoutingInstrumentation } from './routerInstrumentation.js';\nimport {\n  GRID_DEFAULTS,\n  ROOT_CONTAINER_ID,\n  type GridContainerId,\n  type GridContainerLayoutMeta,\n  type GridItemLayoutMeta,\n  type GridForest,\n  type GridLayoutResult,\n  type GridLayoutData,\n  gridError,\n  isEdgeLabelNode,\n  isFinitePositiveNumber,\n} from './types.js';\n\n/*\n * Computes grid geometry in two coordinate systems:\n *\n * 1. Each container lays out its direct children in local coordinates, children-first.\n * 2. A top-down pass translates those local results into absolute diagram coordinates.\n *\n * The public entry point runs both phases on a clone and commits only after the complete geometry\n * succeeds, so invalid input cannot leave the caller's graph partially positioned.\n */\nconst GROUP_ROUTING_GUTTER = 24;\nconst GROUP_ROUTING_CLEARANCE = 20;\n\nfunction titleBandFor(node: Node, titleGap: number): number {\n  if (!node.label || !node.labelBBox || !(node.labelBBox.height > 0)) {\n    return 0;\n  }\n  return node.labelBBox.height + titleGap;\n}\n\nfunction ensureMeasuredNode(node: Node): void {\n  if (!isFinitePositiveNumber(node.width) || !isFinitePositiveNumber(node.height)) {\n    throw gridError(\n      'GRID_MISSING_MEASUREMENT',\n      `Node \"${node.id}\" must have width and height greater than 0 (width: ${node.width}, height: ${node.height})`,\n      {\n        nodeId: node.id,\n        width: node.width,\n        height: node.height,\n      }\n    );\n  }\n}\n\nfunction measureChild(node: Node): { width: number; height: number } {\n  ensureMeasuredNode(node);\n  return { width: node.width!, height: node.height! };\n}\n\nfunction layoutContainer(\n  containerId: GridContainerId,\n  result: GridLayoutResult,\n  containers: Map<GridContainerId, GridContainerLayoutMeta>,\n  itemMeta: Map<string, GridItemLayoutMeta>,\n  metrics?: GridRoutingInstrumentation\n): void {\n  const { forest, config, sourceOrder } = result;\n  const group = containerId === ROOT_CONTAINER_ID ? undefined : forest.groupById.get(containerId);\n  const padding = group ? Math.max(group.padding ?? 0, config.containerPadding) : 0;\n  const titleBand = group ? titleBandFor(group, config.titleGap) : 0;\n  const routingGutter = group ? GROUP_ROUTING_GUTTER : 0;\n  const contentTop = group ? padding + titleBand + routingGutter : 0;\n\n  const directItems = (forest.childrenByParent.get(containerId) ?? []).filter(\n    (node) => !isEdgeLabelNode(node)\n  );\n\n  const { cells } = resolveGridPlacements(directItems, sourceOrder, config);\n  const cellEntries = [...cells.values()].sort((a, b) => a.row - b.row || a.column - b.column);\n\n  // A cell may contain an authored vertical stack. Columns and rows are sized from the largest\n  // complete stack in that track, which keeps neighboring cells aligned.\n  const columnWidths = new Map<number, number>();\n  const rowHeights = new Map<number, number>();\n  const rows = new Set<number>();\n  const columns = new Set<number>();\n\n  for (const cell of cellEntries) {\n    let stackWidth = 0;\n    let stackHeight = 0;\n    for (const placement of cell.items) {\n      const size = measureChild(placement.item);\n      stackWidth = Math.max(stackWidth, size.width);\n      stackHeight += size.height;\n    }\n    if (cell.items.length > 1) {\n      stackHeight += config.cellGap * (cell.items.length - 1);\n    }\n    cell.width = stackWidth;\n    cell.height = stackHeight;\n    rows.add(cell.row);\n    columns.add(cell.column);\n    columnWidths.set(cell.column, Math.max(columnWidths.get(cell.column) ?? 0, stackWidth));\n    rowHeights.set(cell.row, Math.max(rowHeights.get(cell.row) ?? 0, stackHeight));\n  }\n\n  const sortedRows = [...rows].sort((a, b) => a - b);\n  const sortedColumns = [...columns].sort((a, b) => a - b);\n  const labelGaps = deriveGridContainerLabelGaps(\n    result.labelRequirements.byContainer.get(containerId) ?? [],\n    cells,\n    rowHeights,\n    columnWidths,\n    sortedRows,\n    sortedColumns,\n    config.rowGap,\n    config.columnGap,\n    metrics\n  );\n  const rowGapAfter = (row: number) => Math.max(config.rowGap, labelGaps.rowGapAfter.get(row) ?? 0);\n  const columnGapAfter = (column: number) =>\n    Math.max(config.columnGap, labelGaps.columnGapAfter.get(column) ?? 0);\n  if (metrics) {\n    for (const gap of labelGaps.rowGapAfter.values()) {\n      if (gap > config.rowGap) {\n        metrics.labelSpacingBoundariesExpanded++;\n        metrics.labelSpacingPixelsAdded += gap - config.rowGap;\n      }\n    }\n    for (const gap of labelGaps.columnGapAfter.values()) {\n      if (gap > config.columnGap) {\n        metrics.labelSpacingBoundariesExpanded++;\n        metrics.labelSpacingPixelsAdded += gap - config.columnGap;\n      }\n    }\n  }\n\n  const contentWidth = sortedColumns.reduce(\n    (total, column, index) =>\n      total +\n      (columnWidths.get(column) ?? 0) +\n      (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0),\n    0\n  );\n  // A title sets the minimum group width. If it is wider than the content and its insets,\n  // center the occupied tracks so the extra horizontal space is split evenly on both sides.\n  const width = group\n    ? Math.max(\n        contentWidth + (padding + routingGutter) * 2,\n        (group.labelBBox?.width ?? 0) + padding * 2\n      )\n    : contentWidth;\n  const contentLeft = group ? (width - contentWidth) / 2 : 0;\n\n  const columnOrigins = new Map<number, number>();\n  let xCursor = contentLeft;\n  for (const [index, column] of sortedColumns.entries()) {\n    columnOrigins.set(column, xCursor);\n    xCursor +=\n      (columnWidths.get(column) ?? 0) +\n      (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0);\n  }\n\n  const rowOrigins = new Map<number, number>();\n  let yCursor = contentTop;\n  for (const [index, row] of sortedRows.entries()) {\n    rowOrigins.set(row, yCursor);\n    yCursor += (rowHeights.get(row) ?? 0) + (index < sortedRows.length - 1 ? rowGapAfter(row) : 0);\n  }\n  const gridHeight = sortedRows.length ? yCursor - contentTop : 0;\n\n  const outerLeftCorridor = group\n    ? contentLeft - GROUP_ROUTING_CLEARANCE\n    : -Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);\n  const outerRightCorridor = group\n    ? contentLeft + contentWidth + GROUP_ROUTING_CLEARANCE\n    : contentLeft + contentWidth + Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);\n  const outerTopCorridor = group\n    ? contentTop - GROUP_ROUTING_CLEARANCE\n    : -Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);\n  const outerBottomCorridor = group\n    ? contentTop + gridHeight + GROUP_ROUTING_CLEARANCE\n    : contentTop + gridHeight + Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);\n\n  // Record the empty bands between tracks while geometry is available. The routing layer consumes\n  // these coordinates later without needing to reconstruct placement decisions.\n  const verticalCorridors = new Set<number>([outerLeftCorridor, outerRightCorridor]);\n  const horizontalCorridors = new Set<number>([outerTopCorridor, outerBottomCorridor]);\n  const leftCorridorByColumn = new Map<number, number>();\n  const rightCorridorByColumn = new Map<number, number>();\n  const topCorridorByRow = new Map<number, number>();\n  const bottomCorridorByRow = new Map<number, number>();\n\n  if (sortedColumns.length > 0) {\n    leftCorridorByColumn.set(sortedColumns[0], outerLeftCorridor);\n    rightCorridorByColumn.set(sortedColumns.at(-1)!, outerRightCorridor);\n  }\n  for (let index = 0; index < sortedColumns.length - 1; index++) {\n    const current = sortedColumns[index];\n    const next = sortedColumns[index + 1];\n    const corridor =\n      (columnOrigins.get(current)! + (columnWidths.get(current) ?? 0) + columnOrigins.get(next)!) /\n      2;\n    verticalCorridors.add(corridor);\n    rightCorridorByColumn.set(current, corridor);\n    leftCorridorByColumn.set(next, corridor);\n  }\n  if (sortedRows.length > 0) {\n    topCorridorByRow.set(sortedRows[0], outerTopCorridor);\n    bottomCorridorByRow.set(sortedRows.at(-1)!, outerBottomCorridor);\n  }\n  for (let index = 0; index < sortedRows.length - 1; index++) {\n    const current = sortedRows[index];\n    const next = sortedRows[index + 1];\n    const corridor =\n      (rowOrigins.get(current)! + (rowHeights.get(current) ?? 0) + rowOrigins.get(next)!) / 2;\n    horizontalCorridors.add(corridor);\n    bottomCorridorByRow.set(current, corridor);\n    topCorridorByRow.set(next, corridor);\n  }\n\n  for (const cell of cellEntries) {\n    const cellLeft = columnOrigins.get(cell.column) ?? contentLeft;\n    const cellTop = rowOrigins.get(cell.row) ?? contentTop;\n    const cellWidth = columnWidths.get(cell.column) ?? cell.width;\n    const cellHeight = rowHeights.get(cell.row) ?? cell.height;\n    const verticalFactor =\n      cell.verticalAlign === 'top' ? 0 : cell.verticalAlign === 'bottom' ? 1 : 0.5;\n    const stackTop = cellTop + (cellHeight - cell.height) * verticalFactor;\n\n    let itemTop = stackTop;\n    for (const [itemIndex, placement] of cell.items.entries()) {\n      const { width, height } = measureChild(placement.item);\n      const horizontalFactor =\n        placement.horizontalAlign === 'left' ? 0 : placement.horizontalAlign === 'right' ? 1 : 0.5;\n      const itemLeft = cellLeft + (cellWidth - width) * horizontalFactor;\n      placement.item.x = itemLeft + width / 2;\n      placement.item.y = itemTop + height / 2;\n      const topCorridorY =\n        itemIndex > 0\n          ? itemTop - config.cellGap / 2\n          : (topCorridorByRow.get(cell.row) ?? outerTopCorridor);\n      const bottomCorridorY =\n        itemIndex < cell.items.length - 1\n          ? itemTop + height + config.cellGap / 2\n          : (bottomCorridorByRow.get(cell.row) ?? outerBottomCorridor);\n      if (itemIndex > 0) {\n        horizontalCorridors.add(topCorridorY);\n      }\n      if (itemIndex < cell.items.length - 1) {\n        horizontalCorridors.add(bottomCorridorY);\n      }\n\n      itemMeta.set(placement.item.id, {\n        containerId,\n        row: cell.row,\n        column: cell.column,\n        cellLeft,\n        cellTop,\n        cellWidth,\n        cellHeight,\n        leftCorridorX: leftCorridorByColumn.get(cell.column) ?? outerLeftCorridor,\n        rightCorridorX: rightCorridorByColumn.get(cell.column) ?? outerRightCorridor,\n        topCorridorY,\n        bottomCorridorY,\n      });\n\n      itemTop += height + config.cellGap;\n    }\n  }\n\n  const height = group ? gridHeight + titleBand + (padding + routingGutter) * 2 : gridHeight;\n\n  containers.set(containerId, {\n    id: containerId,\n    left: 0,\n    top: 0,\n    width,\n    height,\n    contentLeft,\n    contentTop,\n    contentRight: group ? contentLeft + contentWidth : contentWidth,\n    contentBottom: group ? contentTop + gridHeight : gridHeight,\n    verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),\n    horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b),\n  });\n\n  if (group) {\n    group.width = width;\n    group.height = height;\n    group.x = width / 2;\n    group.y = height / 2;\n    if (titleBand > 0) {\n      group.groupTitleRect = {\n        left: 0,\n        right: width,\n        top: 0,\n        bottom: padding + titleBand,\n      };\n    } else {\n      delete group.groupTitleRect;\n    }\n  }\n}\n\nfunction translateRect(\n  rect: NonNullable<Node['groupTitleRect']>,\n  dx: number,\n  dy: number\n): NonNullable<Node['groupTitleRect']> {\n  return {\n    left: rect.left + dx,\n    right: rect.right + dx,\n    top: rect.top + dy,\n    bottom: rect.bottom + dy,\n  };\n}\n\nfunction materializeAbsoluteGeometry(result: GridLayoutResult): void {\n  const { forest, containers, itemMeta } = result;\n\n  // Container layout is local to its parent. Walk top-down with accumulated offsets so nodes,\n  // title rectangles, cell metadata, and routing corridors all move as one coordinate system.\n  interface ShiftFrame {\n    containerId: GridContainerId;\n    offsetX: number;\n    offsetY: number;\n    children: Node[];\n    nextChildIndex: number;\n    entered: boolean;\n  }\n\n  const stack: ShiftFrame[] = [\n    {\n      containerId: ROOT_CONTAINER_ID,\n      offsetX: 0,\n      offsetY: 0,\n      children: forest.childrenByParent.get(ROOT_CONTAINER_ID) ?? [],\n      nextChildIndex: 0,\n      entered: false,\n    },\n  ];\n\n  while (stack.length > 0) {\n    const frame = stack[stack.length - 1];\n\n    if (!frame.entered) {\n      frame.entered = true;\n      const container = containers.get(frame.containerId);\n      if (container) {\n        container.left += frame.offsetX;\n        container.top += frame.offsetY;\n        container.contentLeft += frame.offsetX;\n        container.contentRight += frame.offsetX;\n        container.contentTop += frame.offsetY;\n        container.contentBottom += frame.offsetY;\n        container.verticalCorridors = container.verticalCorridors.map(\n          (value) => value + frame.offsetX\n        );\n        container.horizontalCorridors = container.horizontalCorridors.map(\n          (value) => value + frame.offsetY\n        );\n      }\n    }\n\n    const child = frame.children[frame.nextChildIndex];\n    if (!child) {\n      stack.pop();\n      continue;\n    }\n    frame.nextChildIndex += 1;\n\n    if (isEdgeLabelNode(child)) {\n      continue;\n    }\n\n    const meta = itemMeta.get(child.id);\n    if (meta) {\n      meta.cellLeft += frame.offsetX;\n      meta.cellTop += frame.offsetY;\n      meta.leftCorridorX += frame.offsetX;\n      meta.rightCorridorX += frame.offsetX;\n      meta.topCorridorY += frame.offsetY;\n      meta.bottomCorridorY += frame.offsetY;\n    }\n\n    child.x = (child.x ?? 0) + frame.offsetX;\n    child.y = (child.y ?? 0) + frame.offsetY;\n\n    if (!child.isGroup) {\n      continue;\n    }\n\n    if (child.groupTitleRect) {\n      child.groupTitleRect = translateRect(\n        child.groupTitleRect,\n        child.x - (child.width ?? 0) / 2,\n        child.y - (child.height ?? 0) / 2\n      );\n    }\n\n    stack.push({\n      containerId: child.id,\n      offsetX: child.x - (child.width ?? 0) / 2,\n      offsetY: child.y - (child.height ?? 0) / 2,\n      children: forest.childrenByParent.get(child.id) ?? [],\n      nextChildIndex: 0,\n      entered: false,\n    });\n  }\n}\n\nfunction commitGridGeometry(source: LayoutData, target: LayoutData): void {\n  // Preserve caller-owned node and edge identities. Downstream renderers may already hold\n  // references to these objects, so only calculated geometry is copied from the working graph.\n  const sourceNodeById = new Map(source.nodes.map((node) => [node.id, node]));\n  for (const targetNode of target.nodes) {\n    const sourceNode = sourceNodeById.get(targetNode.id);\n    if (!sourceNode) {\n      continue;\n    }\n    targetNode.x = sourceNode.x;\n    targetNode.y = sourceNode.y;\n    targetNode.width = sourceNode.width;\n    targetNode.height = sourceNode.height;\n    if (sourceNode.groupTitleRect) {\n      targetNode.groupTitleRect = { ...sourceNode.groupTitleRect };\n    } else {\n      delete targetNode.groupTitleRect;\n    }\n  }\n\n  const sourceEdgeById = new Map(source.edges.map((edge) => [edge.id, edge]));\n  for (const targetEdge of target.edges) {\n    const sourceEdge = sourceEdgeById.get(targetEdge.id);\n    if (!sourceEdge) {\n      continue;\n    }\n    targetEdge.points = sourceEdge.points?.map((point) => ({ ...point }));\n    targetEdge.curve = sourceEdge.curve;\n    targetEdge.cornerRadius = sourceEdge.cornerRadius;\n    targetEdge.portClipping = 'outline-orthogonal';\n    targetEdge.skipCornerFix = sourceEdge.curve === 'linear';\n  }\n}\n\nfunction cloneGridLayoutData(data: GridLayoutData): GridLayoutData {\n  return {\n    ...data,\n    nodes: data.nodes.map((node) => ({\n      ...node,\n      labelBBox: node.labelBBox ? { ...node.labelBBox } : node.labelBBox,\n      groupTitleRect: node.groupTitleRect ? { ...node.groupTitleRect } : node.groupTitleRect,\n    })),\n    edges: data.edges.map((edge) => ({\n      ...edge,\n      points: edge.points?.map((point) => ({ ...point })),\n    })),\n  };\n}\n\nfunction rebindGridForest(forest: GridForest, nodes: Node[]): GridForest {\n  // The calculation forest points at cloned nodes. Rebuild each collection against the committed\n  // caller-owned nodes before exposing the result to later routing and rendering phases.\n  const nodeById = new Map(nodes.map((node) => [node.id, node]));\n  const originalNode = (node: Node): Node => {\n    const original = nodeById.get(node.id);\n    if (!original) {\n      throw new Error(`Missing committed grid node \"${node.id}\"`);\n    }\n    return original;\n  };\n  const originalGroup = (group: Node & { isGroup: true }): Node & { isGroup: true } => {\n    const original = originalNode(group);\n    if (!original.isGroup) {\n      throw new Error(`Committed grid node \"${group.id}\" is no longer a group`);\n    }\n    return original as Node & { isGroup: true };\n  };\n\n  return {\n    nodeById,\n    groupById: new Map(\n      [...forest.groupById].map(([groupId, group]) => [groupId, originalGroup(group)])\n    ),\n    childrenByParent: new Map(\n      [...forest.childrenByParent].map(([parentId, children]) => [\n        parentId,\n        children.map(originalNode),\n      ])\n    ),\n    rootChildren: forest.rootChildren.map(originalNode),\n    postOrderGroups: forest.postOrderGroups.map(originalGroup),\n    helperNodeIds: new Set(forest.helperNodeIds),\n  };\n}\n\nfunction runGridLayoutCoreInPlace(\n  data: GridLayoutData,\n  options: GridLayoutCoreInternalOptions\n): GridLayoutResult {\n  const forest = buildGridForest(data.nodes);\n  const config = readGridConfig(data);\n  const sourceOrder = buildGridSourceOrder(data.nodes.filter((node) => !isEdgeLabelNode(node)));\n  validateGridPlacementMap(\n    data.nodes.filter((node) => !isEdgeLabelNode(node)),\n    config\n  );\n\n  const result: GridLayoutResult = {\n    forest,\n    config,\n    containers: new Map(),\n    itemMeta: new Map(),\n    sourceOrder,\n    labelRequirements: buildGridLabelRequirements(data, forest, options.metrics),\n  };\n\n  // Post-order is the key sizing invariant: a group becomes a measured child only after all of its\n  // descendants have established the group's final width and height.\n  for (const group of forest.postOrderGroups) {\n    layoutContainer(group.id, result, result.containers, result.itemMeta, options.metrics);\n  }\n  layoutContainer(ROOT_CONTAINER_ID, result, result.containers, result.itemMeta, options.metrics);\n  materializeAbsoluteGeometry(result);\n  // Routing consumes absolute node bounds and corridor coordinates, so it must run after the\n  // children-first sizing and top-down translation phases have both completed.\n  routeGridEdges(data, result, options.metrics, options.routing);\n  // Labels consume final routes and may transactionally reroute them, so they are the last layout\n  // phase before the working copy is committed to the render model.\n  positionGridEdgeLabels(data, undefined, options.metrics);\n  return result;\n}\n\n/** @internal */\nexport interface GridLayoutCoreInternalOptions {\n  metrics?: GridRoutingInstrumentation;\n  routing?: GridRoutingTestOptions;\n}\n\nexport function runGridLayoutCore(\n  data4Layout: LayoutData,\n  options: GridLayoutCoreInternalOptions = {}\n): GridLayoutResult {\n  const data = data4Layout;\n\n  // Routing and label placement are transactional: a failed recovery must not leave partial\n  // coordinates on the shared render model. Commit only the geometry from a complete run.\n  const working = cloneGridLayoutData(data);\n  const result = runGridLayoutCoreInPlace(working, options);\n  commitGridGeometry(working, data);\n  return {\n    ...result,\n    forest: rebindGridForest(result.forest, data.nodes),\n  };\n}\n", "import {\n  applyLineJumpsToSvg,\n  normalizeLineHops,\n  type EdgeGeom,\n} from '../../rendering-elements/lineJump.js';\nimport type { LayoutData } from '../../types.js';\nimport type { CommonLayoutPaintContext } from '../common/index.js';\n\ninterface EdgePaintGroups {\n  groups: { edgePaths: Parameters<typeof applyLineJumpsToSvg>[0] };\n}\n\nexport function applyGridLineJumps(\n  data: LayoutData,\n  { measure }: CommonLayoutPaintContext<unknown, EdgePaintGroups>\n): void {\n  const lineHops = normalizeLineHops(data.config.grid?.lineHops);\n  if (lineHops === false) {\n    return;\n  }\n\n  const edges = data.edges\n    .filter(\n      (edge): edge is typeof edge & { points: EdgeGeom['points'] } =>\n        Array.isArray(edge.points) && edge.points.length >= 2\n    )\n    .map((edge) => ({\n      id: edge.id,\n      points: edge.points,\n      curve: edge.curve,\n      cornerRadius: edge.cornerRadius,\n      arrowTypeStart: edge.arrowTypeStart,\n      arrowTypeEnd: edge.arrowTypeEnd,\n    }));\n\n  applyLineJumpsToSvg(measure.groups.edgePaths, edges, {\n    enabled: true,\n    jumpRadius: 6,\n    jumpStyle: lineHops,\n  });\n}\n", "import { createCommonLayoutRenderer } from '../common/index.js';\nimport { prepareGridLayout } from './edgeLabels.js';\nimport { runGridLayoutCore } from './layoutCore.js';\nimport { applyGridLineJumps } from './lineHops.js';\n\n// Keep this adapter deliberately small: the common renderer owns the public render lifecycle,\n// while grid-specific preparation and layout remain reusable by DDLT and focused tests.\nexport { prepareGridLayout, runGridLayoutCore };\n\nexport const render = createCommonLayoutRenderer({\n  prepareLayout: prepareGridLayout,\n  runLayoutCore: (data4Layout) => runGridLayoutCore(data4Layout),\n  afterPaint: applyGridLineJumps,\n});\n"],
  "mappings": "klBAoCO,SAASA,GAAmBC,EAAUC,EAAUC,EAAY,EAAgC,CACjG,IAAMC,EAAK,KAAK,IAAIF,EAAE,EAAID,EAAE,CAAC,EACvBI,EAAK,KAAK,IAAIH,EAAE,EAAID,EAAE,CAAC,EAC7B,OAAIG,GAAMD,GAAaE,GAAMF,EACpB,IAELE,GAAMF,EACD,IAEF,GACT,CAVgBG,EAAAN,GAAA,sBAaT,SAASO,GAAmBC,EAAiBL,EAAY,EAA0B,CACxF,IAAMM,EAAsB,CAAC,EAC7B,QAASC,EAAI,EAAGA,EAAIF,EAAO,OAAS,EAAGE,IAAK,CAC1C,IAAMT,EAAIO,EAAOE,CAAC,EACZR,EAAIM,E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,CACN,IAAMC,EAAWC,GAAkBH,EAAK,OAAO,MAAM,QAAQ,EAC7D,GAAIE,IAAa,GACf,OAGF,IAAME,EAAQJ,EAAK,MAChB,OACEK,GACC,MAAM,QAAQA,EAAK,MAAM,GAAKA,EAAK,OAAO,QAAU,CACxD,EACC,IAAKA,IAAU,CACd,GAAIA,EAAK,GACT,OAAQA,EAAK,OACb,MAAOA,EAAK,MACZ,aAAcA,EAAK,aACnB,eAAgBA,EAAK,eACrB,aAAcA,EAAK,YACrB,EAAE,EAEJC,GAAoBL,EAAQ,OAAO,UAAWG,EAAO,CACnD,QAAS,GACT,WAAY,EACZ,UAAWF,CACb,CAAC,CACH,CA5BgBK,EAAAR,GAAA,sBCHT,IAAMS,GAASC,GAA2B,CAC/C,cAAeC,GACf,cAAeC,EAACC,GAAgBC,GAAkBD,CAAW,EAA9C,iBACf,WAAYE,EACd,CAAC",
  "names": ["segmentOrientation", "a", "b", "tolerance", "dx", "dy", "__name", "segmentsFromPoints", "points", "segments", "i", "mergeCollinear", "result", "current", "next", "normalizePolyline", "rawSegments", "s", "merged", "newPoints", "element", "bends", "segmentsCross", "s1", "s2", "horiz", "vert", "hY", "hX1", "hX2", "vX", "vY1", "vY2", "ix", "iy", "matchesHorizEndpoint", "matchesVertEndpoint", "__name", "compareCodeUnits", "a", "b", "__name", "rectForNode", "node", "cx", "cy", "w", "h", "terminalMarkerClearanceRect", "points", "terminal", "length", "halfWidth", "tolerance", "tip", "inner", "dx", "dy", "innerX", "left", "right", "innerY", "top", "bottom", "hasTerminalMarker", "edge", "markerType", "trimmed", "approxEqual", "a", "b", "tol", "__name", "orthogonalPolylineContainsPoint", "points", "point", "tolerance", "index", "manhattanLength", "total", "i", "segmentIntersectsRectInterior", "a", "b", "rect", "y", "x1", "x2", "crossesVertically", "overlapsHorizontally", "x", "y1", "y2", "crossesHorizontally", "overlapsVertically", "__name", "polylineIntersectsRect", "points", "i", "clamp", "v", "lo", "hi", "__name", "ROOT_CONTAINER_ID", "GRID_LABEL_PREFIX", "gridError", "code", "message", "details", "error", "__name", "GRID_DEFAULTS", "isEdgeLabelNode", "node", "isFinitePositiveNumber", "value", "GRID_LABEL_CLEARANCE", "GRID_EDGE_END_MARKER_CLEARANCE", "GRID_LABEL_SPAN_MARGIN", "gridLabelSpanRequirement", "labelNode", "orientation", "isFinitePositiveNumber", "along", "cross", "startInset", "endInset", "__name", "gridLabelRequiredSegmentLength", "LABEL_CLEARANCE", "GRID_LABEL_CLEARANCE", "LABEL_GUTTER", "LABEL_GUTTER_STEP", "MAX_GUTTER_STEPS", "MAX_DETOUR_LINE_CANDIDATES", "MAX_DETOUR_CENTER_CANDIDATES", "DEFAULT_MAX_INDEX_WORK", "EDGE_END_MARKER_CLEARANCE", "GRID_EDGE_END_MARKER_CLEARANCE", "LABEL_EPSILON", "MIN_SELF_PARALLEL_GAP", "MIN_SELF_PARALLEL_OVERLAP", "normalizePolyline", "__name", "points", "rangeOverlapLength", "firstStart", "firstEnd", "secondStart", "secondEnd", "start", "end", "polylineHasSelfConflict", "segments", "firstIndex", "first", "secondIndex", "second", "segmentsCross", "sameAxis", "overlap", "gap", "LabelPlacementSearchExhaustedError", "details", "__name", "LabelIndexWorkLimitError", "LabelIndexWorkBudget", "limit", "metrics", "units", "incrementMetric", "CompressedBoundsIndex", "workBudget", "entry", "isNew", "id", "bounds", "entryCount", "a", "b", "compareCodeUnits", "result", "boundsOverlap", "rectOverlap", "labelRectAt", "node", "center", "width", "height", "groupTitleRect", "rect", "key", "delta", "clonePoint", "point", "boundsForRect", "boundsForSegment", "segment", "boundsForPoints", "points", "left", "right", "top", "bottom", "mergeBounds", "expandBounds", "padding", "candidateSegmentsFromSegments", "segments", "_", "index", "segmentIndex", "order", "markerClearanceRectsFromPoints", "edge", "terminal", "hasTerminalMarker", "terminalMarkerClearanceRect", "EDGE_END_MARKER_CLEARANCE", "LABEL_EPSILON", "buildEdgeGeometry", "normalized", "normalizePolyline", "segmentLength", "borderCutsRect", "border", "corners", "i", "segmentIntersectsRectInterior", "hasFinitePosition", "pointsForEdge", "overrides", "context", "overridePoints", "cached", "markerClearanceRectsForEdge", "rangeOverlaps", "aStart", "aEnd", "bStart", "bEnd", "clampInterval", "interval", "low", "high", "start", "clamp", "end", "mergeBlockedLabelIntervals", "intervals", "clamped", "merged", "current", "previous", "centerCandidatesFromIntervals", "blocked", "preferred", "allowed", "cursor", "candidates", "preferredDelta", "widthDelta", "seen", "values", "candidate", "rounded", "obstacleRectForNode", "isEdgeLabelNode", "rectForNode", "candidateSegments", "storeEdgeGeometry", "edgeId", "geometry", "setEdgePoints", "upsertPlacedLabelObstacle", "placedLabel", "createEdgeLabelContext", "data", "aggregateBounds", "rememberBounds", "borderRect", "borderBounds", "titleRect", "titleBounds", "obstacleRect", "pointBounds", "queryObstacleEntries", "metricKey", "options", "collected", "appendEntries", "entries", "queryForeignSegments", "selfEdgeId", "overriddenEdgeIds", "indexedEntries", "visited", "segmentBounds", "foreignEdgeIdsIntersectingRect", "ids", "obstacleBandQueryBounds", "labelNode", "isFinitePositiveNumber", "detourLineQueryBounds", "searchBounds", "alongPadding", "LABEL_CLEARANCE", "LABEL_GUTTER", "rerouteLineQueryBounds", "rectSafeForLabel", "labelNodeId", "allowedForeignEdgeIds", "obstacle", "clearanceRect", "foreignSegment", "requiredSegmentLength", "gridLabelRequiredSegmentLength", "blockedCenterIntervals", "includeForeignEdges", "labelWidth", "labelHeight", "alongHalf", "bandBounds", "addRect", "bandTop", "bandBottom", "bandLeft", "bandRight", "segmentEntry", "placementOnExistingSegment", "intervalData", "placementOnExistingSegmentWithReroutes", "placedLabelsByEdgeId", "foreignEdges", "foreignEdge", "ok", "reroutedPoints", "rerouteForeignEdgeAroundRect", "polylineHitsProtectedObstacles", "skipNodeIds", "labelStillAnchored", "placed", "orthogonalPolylineContainsPoint", "detourOffsets", "crossHalfSize", "out", "step", "MAX_GUTTER_STEPS", "offset", "LABEL_GUTTER_STEP", "uniqueSortedCandidates", "anchor", "value", "distanceDelta", "detourLineCandidates", "MAX_DETOUR_LINE_CANDIDATES", "rerouteLineCandidates", "blockedRect", "lane", "sorted", "detourCenterCandidates", "detourLineCoord", "detourSegment", "queryBounds", "MAX_DETOUR_CENTER_CANDIDATES", "detourReturnCoordinate", "sourceLine", "detourLine", "labelHalfSize", "direction", "HORIZONTAL_DETOUR_AXIS", "along", "cross", "VERTICAL_DETOUR_AXIS", "detourAxis", "buildLabelDetourPoints", "centerAlong", "axis", "aAlong", "bAlong", "span", "detourStart", "detourEnd", "extendsBeforeStart", "extendsAfterEnd", "alongDirection", "segmentInset", "entryAlong", "exitAlong", "returnLine", "detourPoints", "buildExtendedLabelDetourPoints", "separateEntryAndExit", "insetDivisor", "externalDetourCenterCandidates", "minX", "maxX", "minY", "maxY", "blockedIntersectionScore", "count", "length", "reducesBlockedIntersections", "baseline", "score", "rerouteLane", "blockingReservations", "side", "reservationIds", "reservation", "rerouteSegmentAroundRect", "baselineScore", "ownLabelNodeId", "exit", "y", "candidatePoints", "polylineIntersectsRect", "x", "currentPoints", "attempt", "rerouted", "rerouteForeignEdgeAroundLabels", "reservations", "initialPoints", "pass", "changed", "labelPlacementWithExtendedDetour", "segmentCandidate", "basePoints", "centerCandidates", "polylineHasSelfConflict", "labelPlacementWithDetour", "isPreparedLabelNode", "parkDegenerateLabel", "nodeById", "routePoint", "source", "target", "fallback", "placeLabelAtRouteMidpoint", "longestSegment", "preferredGridLabelNodeId", "GRID_LABEL_PREFIX", "ensureUniqueGridLabelNodeId", "baseId", "candidateId", "suffix", "prepareGridLayout", "newNodes", "sourceNode", "existingHelper", "positionGridEdgeLabels", "instrumentation", "routingInstrumentation", "labelNodes", "baseLabelPositions", "preparedLabels", "sourceIndex", "baseEdgePoints", "restoreBaseEdgePoints", "restoreBaseState", "position", "workItems", "placeLabelsAtRouteMidpoints", "configuredIndexWork", "DEFAULT_MAX_INDEX_WORK", "indexWorkLimit", "indexWorkBudget", "placementFailures", "allowedOverlapsByLabelEdgeId", "passStartPoints", "proposedOwnerRoutes", "lengthDelta", "labelCenter", "frozenLabels", "passStart", "proposed", "owner", "impacted", "ownLabel", "rerouteLaneOrdinals", "combinedRect", "combined", "rerouteOrdinal", "lanePadding", "usedScopedLane", "allowedEdges", "gridError", "error", "log", "asGroup", "node", "__name", "buildGridForest", "nodes", "nodeById", "groupById", "helperNodeIds", "ROOT_CONTAINER_ID", "gridError", "isEdgeLabelNode", "group", "childrenByParent", "parentId", "state", "postOrderGroups", "directChildGroups", "groupId", "child", "visit", "startGroupId", "currentState", "stack", "frame", "childState", "item", "rootChild", "isAncestorGroup", "ancestorId", "current", "seen", "buildGridLabelRequirements", "data", "forest", "metrics", "byContainer", "selfLoops", "edge", "labelNode", "source", "target", "horizontal", "gridLabelSpanRequirement", "sourceContainer", "ROOT_CONTAINER_ID", "targetContainer", "entries", "__name", "trackOrigins", "tracks", "sizes", "gap", "origins", "cursor", "track", "crossAxisFits", "crossSize", "origin", "size", "center", "low", "high", "other", "otherOrigin", "otherEnd", "placementByNodeId", "cells", "placements", "cell", "placement", "areConsecutive", "first", "second", "index", "addGapRequirement", "gaps", "required", "deriveGridContainerLabelGaps", "rowHeights", "columnWidths", "sortedRows", "sortedColumns", "configuredRowGap", "configuredColumnGap", "rowGapAfter", "columnGapAfter", "requirementFor", "entry", "orientation", "requirement", "GRID_LOG_PREFIX", "GRID_CURVES", "isObjectRecord", "value", "__name", "ownPlacementFrom", "placement", "isGridHorizontalAlign", "isGridVerticalAlign", "buildGridSourceOrder", "nodes", "order", "index", "node", "readGridConfig", "data", "raw", "placementsRaw", "placements", "key", "occurrencePlacements", "GRID_DEFAULTS", "resolveEdgeCornerRadius", "validateGridPlacementMap", "items", "config", "knownIdCounts", "item", "placementId", "matchingItems", "log", "itemComparator", "sourceOrder", "a", "b", "aOrder", "bOrder", "compareCodeUnits", "resolveItemPlacement", "occurrenceIndex", "authoredPlacementId", "configPlacement", "metadataPlacement", "field", "row", "column", "validateGridCoordinate", "nextFreeColumn", "occupied", "startColumn", "nextFreeRow", "startRow", "nextAutoCell", "candidateColumns", "startIndex", "resolveGridPlacements", "sortedItems", "occurrenceByPlacementId", "resolved", "cells", "existing", "gridError", "nextAutoIndex", "nextColumnByRow", "nextRowByColumn", "next", "GridRoutingResourceLimitError", "reason", "message", "searchStateScope", "__name", "ROUTE_CLEARANCE_PX", "EDGE_CLEARANCE_PX", "DEFAULT_MAX_VERTICES", "MAX_VISIBILITY_ADJACENCY_PER_VERTEX", "DEFAULT_MAX_ROUTING_ESTIMATED_BYTES", "CompressedIntervalIndex", "bands", "strictBoundaryIntervals", "low", "high", "intervalCount", "total", "band", "intervals", "__name", "coordinate", "middle", "left", "right", "intervalStart", "intervalEnd", "before", "after", "containing", "beforeIndex", "afterIndex", "overlapLow", "overlapHigh", "varying", "origin", "direction", "_a", "ImmutableMap", "backing", "callbackfn", "thisArg", "key", "value", "OverlayMap", "base", "overrides", "added", "overlayArray", "additions", "_target", "property", "index", "overrideArray", "length", "EndpointOverlayScratch", "id", "arcs", "searchArcs", "normalizeCoordinate", "normalizeRect", "rect", "top", "bottom", "inflateAndClip", "input", "domain", "bounds", "obstacle", "mergeObstacleIntervals", "sorted", "a", "b", "compareCodeUnits", "merged", "interval", "previous", "unionObstacles", "obstacles", "events", "start", "end", "xCoordinates", "active", "slabs", "previousByInterval", "event", "nextByInterval", "slab", "routingPointKey", "point", "topologySideOrdinal", "side", "vertexRecordOrder", "canonicalRecords", "records", "byPoint", "record", "normalized", "cornerRecords", "ownerId", "kind", "portalRecords", "range", "rayHit", "horizontalIntervals", "verticalIntervals", "hit", "createIntervalIndex", "orientation", "budget", "coordinates", "starts", "ends", "startEvents", "endEvents", "activeIntervals", "freezeIntervals", "enforceCap", "estimatedTopologyBytes", "vertices", "adjacencyEntries", "actual", "maximum", "reason", "GridRoutingResourceLimitError", "indexVertexLines", "lines", "vertex", "fixed", "line", "arc", "buildVisibilityGraph", "caps", "canonical", "vertexCap", "adjacency", "addArcPair", "from", "to", "arcKindOrder", "immutableAdjacency", "unique", "derivePortalRanges", "rawBounds", "rawTitle", "title", "verticalLow", "verticalHigh", "horizontalLow", "horizontalHigh", "ranges", "buildPairedPortal", "tangentialCoordinate", "entry", "boundary", "inward", "outward", "interior", "exterior", "buildContainerRoutingTopology", "options", "inflated", "portalRanges", "seeds", "intervalBudget", "projections", "sides", "seed", "estimatedBytes", "pointInsideObstacle", "buildEndpointRoutingOverlay", "source", "target", "metrics", "reusableScratch", "lanePoints", "scratch", "endpointRecords", "vertexAt", "mutableArcs", "addedIds", "addedArcKeys", "connect", "baseLines", "affected", "immutableArcs", "addedVertices", "vertexCount", "adjacencyByVertex", "searchAdjacencyByVertex", "MIN_PORT_SEPARATION_PX", "TERMINAL_APPROACH_PX", "LANE_SEPARATION_PX", "ownerGroupTitle", "node", "__name", "ownerSideKey", "ownerId", "side", "preferredSide", "toward", "rect", "rectForNode", "dx", "dy", "avoidTop", "containerChain", "nodeById", "chain", "currentParent", "ROOT_CONTAINER_ID", "seen", "commonContainerId", "source", "target", "isAncestorGroup", "targetContainers", "containerId", "oppositeCoordFor", "sideMidpoint", "tangentialCoordinate", "point", "buildEndpointPlan", "endpoint", "other", "lcaContainerId", "edgeId", "role", "endpointRect", "otherRect", "otherCenter", "current", "parentId", "parent", "currentCenter", "titleAvoidanceTie", "directSideCandidates", "topBlocked", "ambiguousSides", "candidate", "gridError", "entry", "buildPairLanes", "edges", "byPair", "edge", "pairKey", "out", "entries", "a", "b", "compareCodeUnits", "index", "resolveAmbiguousEndpointSides", "plans", "result", "reserved", "reservationKey", "plan", "key", "resolveEndpoint", "ambiguous", "selected", "owner", "sideInterval", "count", "endpoints", "sourceFinal", "targetFinal", "sourceOwner", "targetOwner", "sourcePoint", "targetPoint", "collectRoutePlans", "layout", "pairLanes", "pairLane", "endpointPairKey", "assignCompactPortalCoordinates", "desired", "low", "high", "coordinates", "coordinate", "averageDesired", "sum", "averageAssigned", "minimumShift", "maximumShift", "shift", "clamp", "assignDemandCoordinates", "endpointIncidentCounts", "planByEdgeId", "demandByKey", "byOwnerSide", "demand", "group", "depthOf", "orderedOwnerSides", "d", "assigned", "demands", "ROUTE_CLEARANCE_PX", "span", "demandPlans", "pairKeys", "compactHierarchyPortals", "compactPortal", "center", "container", "corridorCoordinates", "innerCoordinate", "inner", "innerOwner", "preferredCoordinate", "innerCoord", "alignedWithInner", "clamped", "nearest", "best", "step", "verticalSide", "sourceCoord", "targetCoord", "alignedCoord", "interval", "sideOrder", "start", "end", "compareEndpointDemands", "aRect", "bRect", "aCoord", "bCoord", "endpointDemandKey", "compareEndpointDemandIdentity", "preferredEndpointCoordinates", "sorted", "opposite", "endpointSideCapacity", "endpointSidePreferences", "oppositeRect", "preferred", "ownerRect", "aPoint", "bPoint", "aDistance", "bDistance", "isAxisAlignedDemand", "placePortsBesideFixed", "fixed", "movable", "placed", "placements", "candidates", "EDGE_CLEARANCE_PX", "allocateEndpointSlots", "assignedBySide", "capacities", "orderedDemands", "alignedDemands", "unalignedDemands", "reservedSides", "alignedCoordinates", "sharedPlacements", "hasCapacity", "record", "assignAligned", "tryShareReservedSide", "shared", "assignUnaligned", "preferences", "unreserved", "assignments", "fixedDemands", "preferredCoordinates", "endpointCandidates", "demandsByOwner", "assignmentsByOwner", "coordinatedOwnerIds", "oppositeId", "candidateKeys", "assignment", "trackAssignedSide", "addCandidate", "rank", "port", "routingPointKey", "ownerDemands", "distance", "prepareEdgeRoutes", "pairCounts", "eligiblePlans", "endpointDemandsByOwner", "sourceDemands", "targetDemands", "endpointAssignmentsByOwner", "coordinatedEndpointIds", "hasAligned", "hasUnaligned", "endpointCandidatesByEdge", "endpointCandidateProducts", "routeClass", "orderedPlans", "aUnordered", "bUnordered", "aDirected", "bDirected", "aBoundaryCount", "bBoundaryCount", "isPairSeparationError", "error", "details", "__name", "routerRect", "node", "rect", "rectForNode", "canonicalizeOrthogonalPolyline", "points", "x", "y", "collapsed", "index", "point", "previous", "beforePrevious", "orientations", "a", "b", "dx", "canonical", "start", "orientation", "end", "axis", "coordinate", "pointIndex", "segmentEntersRect", "inflatedRect", "ROUTE_CLEARANCE_PX", "validateSameContainerRoute", "source", "target", "containerId", "result", "normalized", "normalizePolyline", "TERMINAL_APPROACH_PX", "children", "isEdgeLabelNode", "obstacle", "validateContainerSegment", "startOwnerId", "endOwnerId", "segmentSpan", "segment", "nonterminalSegments", "segments", "trim", "atStart", "direction", "pairSegmentsConflict", "candidate", "committed", "first", "second", "overlap", "separation", "LANE_SEPARATION_PX", "routeSatisfiesPairConstraints", "pairRoutes", "candidatePorts", "candidateSegments", "route", "committedPorts", "port", "other", "committedSegment", "routeHasDistinctPairPorts", "pairArcAllowed", "from", "to", "endpointPairLowerBound", "sourceOrientation", "targetOrientation", "dy", "bends", "pathOrientation", "segmentsTooClose", "candidate", "committed", "horizontal", "lowOf", "__name", "segment", "highOf", "overlap", "separation", "EDGE_CLEARANCE_PX", "RouteOccupancyIndex", "route", "pairKey", "nonterminalSegments", "orientation", "coordinate", "bucket", "size", "from", "to", "coordinates", "low", "high", "middle", "index", "key", "occupied", "a", "b", "ROOT_OUTER_MARGIN", "SELF_LOOP_PORT_GAP", "SELF_LOOP_APPROACH", "SELF_LOOP_CORNER_CLEARANCE", "SELF_LOOP_TRACK_GAP", "SELF_LOOP_PORT_OFFSET_STEP", "MAX_PLANS_FOR_OVERLAP_AVOIDANCE", "MAX_FAST_ROUTE_SEPARATION_STEPS", "separateRouteFromOccupied", "route", "occupancy", "pairKey", "isAcceptable", "points", "normalizePolyline", "step", "sign", "delta", "LANE_SEPARATION_PX", "index", "vertical", "shifted", "point", "pointIndex", "__name", "terminalStubsAreLongEnough", "stub", "a", "b", "TERMINAL_APPROACH_PX", "boundedAlternativePortalCoordinates", "selected", "low", "high", "corridors", "limit", "candidates", "coordinate", "seen", "alternatives", "equalPoint", "areExactlyAxisAligned", "chooseIntermediateCoordinate", "values", "start", "end", "variant", "sorted", "dedupeConsecutive", "out", "routeWithinContainer", "containerId", "result", "container", "gridError", "y", "alternateCorridors", "value", "x", "itemAttachment", "ownerId", "side", "demandKey", "demandCoords", "owner", "item", "rect", "rectForNode", "coord", "boundaryAttachment", "portalBoundaryPoint", "portal", "portalAttachment", "interior", "groupBoundaryEndpointAttachment", "port", "reversePoints", "combinePointChains", "chains", "chain", "routeSelfLoop", "demandCoord", "depth", "portOffset", "startY", "endY", "startX", "endX", "labelAwareSelfLoopCandidates", "requirement", "baseDepth", "baseSpan", "verticalSide", "span", "GRID_LABEL_CLEARANCE", "GRID_LABEL_SPAN_MARGIN", "interval", "directStart", "directEnd", "portStart", "portEnd", "outerStart", "outerEnd", "shoulderApproach", "shoulderDepth", "orderedSelfLoopSides", "node", "counts", "selfLoopCounts", "ownerGroupTitle", "aCount", "ownerSideKey", "bCount", "selfLoopObstacles", "obstacles", "left", "right", "top", "bottom", "routeObstacleClearSelfLoop", "ownerSideCounts", "labelRequirement", "metrics", "countKey", "obstacle", "polylineIntersectsRect", "rootContainerMeta", "ROOT_CONTAINER_ID", "minLeft", "maxRight", "minTop", "maxBottom", "first", "horizontalCorridors", "verticalCorridors", "containerBounds", "rootItems", "ownerContainerId", "cellLeft", "cellWidth", "cellTop", "cellHeight", "ownerBounds", "routerRect", "ROUTE_CLEARANCE_PX", "portalCoordinate", "bounds", "containerPortalRanges", "ranges", "derivePortalRanges", "range", "child", "buildRoutingContext", "containerIds", "options", "context", "estimatedBytes", "children", "isEdgeLabelNode", "title", "topology", "buildContainerRoutingTopology", "invocationMemoryCap", "DEFAULT_MAX_ROUTING_ESTIMATED_BYTES", "error", "GridRoutingResourceLimitError", "validatedCompatibilitySegment", "edgeId", "validateContainerSegment", "compatibilityLcaAttachments", "plan", "sourceFinal", "targetFinal", "finalAttachment", "endpoint", "final", "compatibilityHierarchyAttachments", "from", "to", "compatibilityPlanIsValid", "segmentIsValid", "attachments", "prepareRoutingModes", "prepared", "plans", "eligiblePlans", "eligibleIds", "endpointCandidatesByEdge", "endpointIncidentCounts", "coordinatedEndpointIds", "hasIsolatedEndpoints", "hasAncestorEndpoint", "source", "target", "isAncestorGroup", "compatibilityFastRoutes", "routeOccupancy", "overlapAvoidanceEnabled", "compatibilityFastPathEnabled", "normalized", "last", "sourceCandidate", "targetCandidate", "lowerBoundLength", "validateSameContainerRoute", "manhattanLength", "RouteOccupancyIndex", "finalRoute", "candidate", "sparseCandidate", "planningOccupancy", "overlappingHierarchyIds", "sparseHierarchyIds", "edge", "sparseLcaIds", "routedContainerIds", "gridRoutingMetricDisposition", "transactionalGridRoutingValueMetrics", "key", "createGridRoutingInstrumentationCheckpoint", "metrics", "__name", "restoreGridRoutingInstrumentationCheckpoint", "checkpoint", "intervalOverlap", "firstStart", "firstEnd", "secondStart", "secondEnd", "__name", "sharedSegmentLength", "first", "second", "firstSegments", "normalizePolyline", "secondSegments", "total", "a", "b", "recordGridRoute", "metrics", "edgeId", "points", "previousRoutes", "boundaryTransitionCount", "laneOffset", "normalized", "crossingCount", "sharedLength", "previous", "previousSegments", "segment", "previousSegment", "segmentsCross", "route", "manhattanLength", "DEFAULT_MAX_EDGE_STATES", "DEFAULT_MAX_INVOCATION_STATES", "RouterSearchWorkspace", "__name", "vertexCount", "bestLength", "index", "state", "required", "capacity", "growTypedArray", "assertSearchBudgetAvailable", "options", "edgeCap", "invocationCap", "invocationStart", "GridRoutingResourceLimitError", "values", "grown", "compareTupleCost", "a", "b", "minimumBends", "dx", "dy", "incomingOrientation", "targetOrientation", "orientationOrdinal", "orientation", "movesTowardOwner", "from", "to", "side", "stateIndex", "vertexId", "normalizePoints", "points", "result", "point", "previous", "beforePrevious", "reconstruct", "stateId", "stateVertices", "predecessors", "cost", "vertexAt", "vertexIds", "current", "id", "validateSearchTopology", "topology", "vertex", "arc", "target", "aligned", "length", "search", "sourceId", "targetId", "source", "metrics", "workspace", "orientations", "gLengths", "gBends", "gBoundaryTransitions", "fLengths", "fBends", "depths", "ancestor4", "heapChildren", "heapSiblings", "best", "heapPairs", "stateCount", "endpointCandidateRank", "useBendHeuristic", "nonCostOrder", "compareStates", "compareChains", "aDepth", "bDepth", "alignedA", "alignedB", "heapRoot", "heapSize", "heapMeld", "first", "second", "heapPush", "value", "heapPop", "child", "next", "pairCount", "expandedThisSearch", "recordWorkspaceBytes", "bytes", "totalBytes", "commitExpandedStates", "initialLength", "initialDx", "initialDy", "bestGoalState", "bestGoalCost", "considerGoal", "completedCost", "relaxArc", "currentPoint", "arcLength", "boundaryTransitions", "nextPoint", "bends", "nextBoundaryTransitions", "previousComparison", "candidate", "candidateDx", "candidateDy", "parent2", "parent3", "searchStateScope", "compactArcs", "findShortestRoute", "ROUTER_DEBUG_KEY", "recordFallback", "context", "reason", "edgeId", "containerId", "searchStateScope", "log", "__name", "runValidatedFallback", "route", "isValid", "includeContainerIdInError", "fallback", "gridError", "sparseSameContainerRoute", "plan", "sources", "targets", "source", "target", "legacyRoute", "result", "searchWorkspace", "overlayScratch", "options", "pairRoutes", "occupied", "fallbackReason", "legacy", "validateSameContainerRoute", "routeSatisfiesPairConstraints", "topology", "best", "searchCap", "pairs", "sourceCandidate", "targetCandidate", "pairRank", "length", "bends", "endpointPairLowerBound", "a", "b", "compareTupleCost", "sideOrder", "searchPairs", "avoidOccupied", "mode", "arcAllowed", "from", "to", "pairArcAllowed", "lowerCost", "assertSearchBudgetAvailable", "overlay", "buildEndpointRoutingOverlay", "liveEstimatedBytes", "DEFAULT_MAX_ROUTING_ESTIMATED_BYTES", "GridRoutingResourceLimitError", "sourceId", "routingPointKey", "targetId", "sourceOrientation", "targetOrientation", "resultForPair", "findShortestRoute", "TERMINAL_APPROACH_PX", "points", "normalizePolyline", "error", "sparseNormalized", "legacyNormalized", "manhattanLength", "selfLoopAttachments", "owner", "side", "index", "interval", "sideInterval", "SELF_LOOP_PORT_GAP", "rect", "rectForNode", "center", "portOffset", "SELF_LOOP_PORT_OFFSET_STEP", "coordinates", "candidate", "coordinate", "port", "sparseSelfLoopRoute", "ownerSideCounts", "selfLoopCounts", "ROOT_CONTAINER_ID", "labelRequirement", "routeObstacleClearSelfLoop", "orderedSides", "orderedSelfLoopSides", "demandCoord", "candidates", "labelAwareSelfLoopCandidates", "attachments", "start", "orientation", "sparseContainerSegment", "end", "endAlternatives", "startAlternatives", "allowSharedPairCorridors", "validateContainerSegment", "attempts", "alternativesAdded", "appendAlternatives", "starts", "ends", "alternative", "startAlternative", "endAlternative", "passes", "attemptIndex", "attempt", "attemptedStart", "attemptedEnd", "areExactlyAxisAligned", "direct", "select", "compatibility", "routeHasDistinctPairPorts", "createBundleCheckpoint", "pairPlans", "pairRoutes", "pairedPortals", "demandCoords", "instrumentedRoutes", "metrics", "routeOccupancy", "pairKey", "committedPairRoutes", "demandKeys", "plan", "demandKey", "bundlePairedPortals", "bundleDemandCoords", "portal", "coordinate", "occupancyIndex", "edge", "createGridRoutingInstrumentationCheckpoint", "__name", "restoreBundleCheckpoint", "checkpoint", "edgeCheckpoint", "restoreGridRoutingInstrumentationCheckpoint", "GridEdgeRoutingSession", "layout", "result", "options", "RouterSearchWorkspace", "plansByPair", "rootContainerMeta", "prepareEdgeRoutes", "prepareRoutingModes", "buildRoutingContext", "containerId", "topology", "EndpointOverlayScratch", "countedDemandKeys", "entry", "key", "ownerSideKey", "existing", "owner", "gridError", "rect", "routerRect", "range", "derivePortalRanges", "side", "buildPairedPortal", "clamp", "interior", "selected", "container", "corridors", "boundedAlternativePortalCoordinates", "portalAttachment", "itemAttachment", "current", "ownerGroupTitle", "interval", "sideInterval", "rectForNode", "center", "attachment", "allowHierarchyRelaxation", "routingContext", "searchWorkspace", "endpointOverlayScratch", "ownerSideCounts", "selfLoopCounts", "eligibleIds", "endpointCandidatesByEdge", "compatibilityFastRoutes", "sparseHierarchyIds", "sparseLcaIds", "sourceNode", "targetNode", "points", "index", "sparseSelfLoopRoute", "ROOT_CONTAINER_ID", "countKey", "recordGridRoute", "sourceFinal", "targetFinal", "useSparseLca", "compatibilityLca", "compatibilityLcaAttachments", "lcaStart", "groupBoundaryEndpointAttachment", "lcaEnd", "legacyLcaPoints", "legacyRoute", "routeWithinContainer", "compatibilityFastRoute", "lcaPoints", "sparseSameContainerRoute", "sparseContainerSegment", "validatedCompatibilitySegment", "routeHierarchyChain", "endpoint", "chains", "start", "end", "compatibilityHierarchyAttachments", "from", "to", "sourceChains", "targetChains", "combinePointChains", "chain", "reversePoints", "satisfiesPairConstraints", "routeSatisfiesPairConstraints", "relaxHierarchySeparation", "routeHasDistinctPairPorts", "boundaryTransitionCount", "occupancy", "RouteOccupancyIndex", "initialError", "error", "isPairSeparationError", "routeGridEdges", "layout", "result", "metrics", "options", "GridEdgeRoutingSession", "__name", "GROUP_ROUTING_GUTTER", "GROUP_ROUTING_CLEARANCE", "titleBandFor", "node", "titleGap", "__name", "ensureMeasuredNode", "isFinitePositiveNumber", "gridError", "measureChild", "layoutContainer", "containerId", "result", "containers", "itemMeta", "metrics", "forest", "config", "sourceOrder", "group", "ROOT_CONTAINER_ID", "padding", "titleBand", "routingGutter", "contentTop", "directItems", "isEdgeLabelNode", "cells", "resolveGridPlacements", "cellEntries", "a", "b", "columnWidths", "rowHeights", "rows", "columns", "cell", "stackWidth", "stackHeight", "placement", "size", "sortedRows", "sortedColumns", "labelGaps", "deriveGridContainerLabelGaps", "rowGapAfter", "row", "columnGapAfter", "column", "gap", "contentWidth", "total", "index", "width", "contentLeft", "columnOrigins", "xCursor", "rowOrigins", "yCursor", "gridHeight", "outerLeftCorridor", "GRID_DEFAULTS", "outerRightCorridor", "outerTopCorridor", "outerBottomCorridor", "verticalCorridors", "horizontalCorridors", "leftCorridorByColumn", "rightCorridorByColumn", "topCorridorByRow", "bottomCorridorByRow", "current", "next", "corridor", "cellLeft", "cellTop", "cellWidth", "cellHeight", "verticalFactor", "itemTop", "itemIndex", "height", "horizontalFactor", "itemLeft", "topCorridorY", "bottomCorridorY", "translateRect", "rect", "dx", "dy", "materializeAbsoluteGeometry", "stack", "frame", "container", "value", "child", "meta", "commitGridGeometry", "source", "target", "sourceNodeById", "targetNode", "sourceNode", "sourceEdgeById", "edge", "targetEdge", "sourceEdge", "point", "cloneGridLayoutData", "data", "rebindGridForest", "nodes", "nodeById", "originalNode", "original", "originalGroup", "groupId", "parentId", "children", "runGridLayoutCoreInPlace", "options", "buildGridForest", "readGridConfig", "buildGridSourceOrder", "validateGridPlacementMap", "buildGridLabelRequirements", "routeGridEdges", "positionGridEdgeLabels", "runGridLayoutCore", "data4Layout", "working", "applyGridLineJumps", "data", "measure", "lineHops", "normalizeLineHops", "edges", "edge", "applyLineJumpsToSvg", "__name", "render", "createCommonLayoutRenderer", "prepareGridLayout", "__name", "data4Layout", "runGridLayoutCore", "applyGridLineJumps"]
}
