Sfoglia il codice sorgente

merge: topology overhaul into main (restore topology improvements) (#138)

* feat: agent-only routers — push-only devices without SSH

Add AgentOnly flag to RouterConfig for devices that have no SSH/SNMP
and only receive data from a push agent (e.g. switch scraper).

Changes:
- types.go: AgentOnly field in RouterConfig
- db.go: migration agent_only column
- routerstore: read/write agent_only
- config.go: agent_only in router input API
- agent.go: StalePayload method (use cached data for agent-only when
  agent is stale, instead of failing to SSH); agent-only alert message
- live.go: skip SSH client creation for agent-only; role Switch/SW
- topology.go: agent-only switches infer distribution nodes like gateway
  (hypervisor, managed, switch ports)

* fix: include devices in overview/SSE snapshot for topology consistency

Root cause: /api/overview and /api/devices use independent polled
snapshots, so topology.rings device IDs never matched the devices array —
WiFi clients disappeared from the topology map.

Fix: include the full devices array in the Overview struct (omitempty for
backward compat) and in the SSE snapshot. The frontend's applyOverview
now extracts devices from the overview when present, guaranteeing ID
consistency with topology rings.

Server: Overview.Devices field + buildOverview populates it.
Frontend: OverviewBundle.devices optional + applyOverview merges it.

* feat(topology): improve switch agent-only inference and hypervisor detection

- Add VirtualBox OUI (08:00:27) to hypervisorOUI list
- Exclude MACs reported by agent-only switches from routerMACs so
  the switch chassis MAC does not contaminate hypervisor host detection
  (switch chassis MAC was counted as a host MAC, preventing correct
  hypervisor inference on ports that contain both switch MAC + real hosts)
- Enrich gateway dist-nodes 'inferred' with agent-only switch name/IP
  when the MAC set of the dist-node is a subset of the switch FDB
  (e.g. gateway port 3 with 38 MACs = switch16 KP-9000)

* refactor(topology): unify pickGateway — extract pickGatewayCfg for polled routers

Replace inline gateway selection logic in inferTopology with
pickGatewayCfg(polled), sharing the same priority as pickGateway
(is_gateway → glinet → first). Reduces 3 copies to 2 (the third in
topo_semantics uses RoleBadge, a different concept).

* feat(topology): improve switch agent-only inference and hypervisor detection

- Add VirtualBox OUI (08:00:27) to hypervisorOUI list
- Enrich gateway dist-nodes 'inferred' with agent-only switch name/IP
  when the MAC set of the dist-node is a subset of the switch FDB
  (e.g. gateway port 3 with 38 MACs = switch16 KP-9000)
- Fix: do NOT exclude all FDB MACs of agent-only switches from
  routerMACs — that would also exclude real clients. Only brMac
  is excluded (existing behavior). The switch chassis MAC in the FDB
  is handled naturally: it appears in hostMACs, preventing false
  hypervisor detection on ports with switch+hosts mix.

* docs: architecture analysis and topology fix plan (reconciler + multi-source FDB/LLDP)

Two reference documents for the topology data reliability overhaul:
- architecture-and-stack.md: diagnosis, curated resources, actionable plan
- netpulse-topology-skills.md: Go code sketches (reconciler, FDB/LLDP collectors),
  confidence scoring, librerías (netlink, gosnmp, goubus), NetXMS pattern

* fix(topology): agent-only routers excluded from gwFDB filter + larger viewBox/rings

- Go: buildDevices skips gwFDB reconciliation for AgentOnly routers
  so switch FDB devices keep their RouterID (not absorbed by gateway)
- Frontend: VB_H 680→750, ring radii +4/+10/+10, caps +1/+1/+2,
  AP_BASE_Y 480→510 for more vertical room

* fix(topology): guaranteed minimum spacing between chips in ring layout

ringLayout now calculates minArcDeg per ring radius and chip size,
preventing overlap. Excess chips overflow to next ring tier.
Added CHIP_GAP=4px constant.

* feat(topology): move managed switch to NW, tighten wifi rings

- switch gestionado: SW_BASE 720,350 → 280,140 (noroeste del gateway,
  encima del hipervisor pve). label pasa a la izquierda (anchor end) para
  no pisar el anillo wifi del gateway; anillos wifi del gateway excluyen
  ahora el sector del switch (como ya pasaba con los APs).
- anillos wifi más pegados a los routers: GATEWAY_RINGS 130/190 → 100/155,
  AP_RINGS 120/180 → 95/145, anillos extra +45 → +38.
- WIP previo de la rama incluido (viewBox 750→850, rings, resolveCollisions,
  fans rehechos, AP_BASE_Y 510→560).
- docs: ajustes de redacción (quitar "Fable"/"bundle de Kimi").
- chore: ignorar bin/ (build artifacts).

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 mesi fa
parent
commit
c4fc746c38

+ 1 - 0
.gitignore

@@ -18,6 +18,7 @@ legacy/server-node/.env
 netpulse-agent*
 server-go/netpulse
 collector/netpulse-collector
+bin/
 
 # Binarios de agente embebidos (construidos por CI)
 server-go/internal/agentbin/agents/netpulse-agent-*

+ 172 - 55
app/src/components/topology/model.ts

@@ -19,7 +19,7 @@ import type { Band, Device, DistributionNode, Router, TopoSemantics, TopoSemLink
 
 /** viewBox del lienzo SVG */
 export const VB_W = 1000
-export const VB_H = 680
+export const VB_H = 850
 
 // ---------------------------------------------------------------------------
 // Tipos
@@ -204,53 +204,62 @@ export function linkColor(link: Pick<TopoLink, 'kind' | 'wifi'>): string {
 // ---------------------------------------------------------------------------
 
 const GATEWAY_COORD = { x: 500, y: 250, r: 40, label: { x: 446, y: 312, anchor: 'end' as const } }
-const AP_COORDS = [
-  { x: 195, y: 470, r: 32, label: { x: 124, y: 464, anchor: 'end' as const } },
-  { x: 500, y: 505, r: 32, label: { x: 554, y: 500, anchor: 'start' as const } },
-  { x: 805, y: 470, r: 32, label: { x: 858, y: 464, anchor: 'start' as const } },
-]
-const INTERNET_COORD = { x: 500, y: 58 }
+const AP_RADIUS = 32
+const AP_ARC_CENTER = 90
+const AP_ARC_HALF = 70
+const AP_BASE_Y = 560
+
+function apCoords(n: number, total: number): { x: number; y: number; r: number; label: { x: number; y: number; anchor: 'end' | 'start' } } {
+  let angle: number
+  if (total === 1) {
+    angle = AP_ARC_CENTER
+  } else {
+    angle = AP_ARC_CENTER - AP_ARC_HALF + (2 * AP_ARC_HALF * n) / (total - 1)
+  }
+  const x = Math.round(GATEWAY_COORD.x + 305 * Math.cos(rad(angle)))
+  const y = Math.round(AP_BASE_Y + 25 * Math.sin(rad(angle - AP_ARC_CENTER)))
+  const isLeft = x < GATEWAY_COORD.x
+  return {
+    x, y, r: AP_RADIUS,
+    label: { x: isLeft ? x - AP_RADIUS - 6 : x + AP_RADIUS + 6, y: y - 6, anchor: isLeft ? 'end' as const : 'start' as const },
+  }
+}
+const INTERNET_COORD = { x: 500, y: 68 }
 const PEER_COORDS = [
   { x: 265, y: 26 },
   { x: 735, y: 26 },
   { x: 140, y: 26 },
   { x: 860, y: 26 },
 ]
-/** Uplinks canónicos gateway→AP (cúbicas QA-das en el mockup) */
-const UPLINK_PATHS = [
-  { d: 'M 464 282 C 390 340, 290 400, 224 440', lx: 292, ly: 366 },
-  { d: 'M 500 292 C 500 360, 500 420, 500 468', lx: 514, ly: 418 },
-  { d: 'M 536 282 C 610 340, 710 400, 776 440', lx: 664, ly: 366 },
-]
 /** Túneles WG canónicos peer→Internet */
 const WG_PATHS = [
   { d: 'M 272 44 C 330 82, 410 94, 474 80', dur: 3 },
   { d: 'M 728 44 C 670 82, 590 94, 526 80', dur: 3.4 },
 ]
-/** Anillos wifi (v5: separados de los nodos; chips no "tocan" el router) */
+/** Anillos wifi: pocos chips por anillo + radios amplios = sin solape */
 const GATEWAY_RINGS = [
-  { r: 96, cap: 5 },
-  { r: 130, cap: 8 },
+  { r: 100, cap: 4 },
+  { r: 155, cap: 6 },
 ]
 const AP_RINGS = [
-  { r: 82, cap: 7 },
-  { r: 120, cap: 13 },
+  { r: 95, cap: 4 },
+  { r: 145, cap: 6 },
 ]
 /** Abanicos cableados: gateway tiene sector este (switch inferido) y oeste */
 const GW_EAST_FAN: [number, number] = [336, 24] // wrap (a1 < a0)
 const GW_WEST_FAN: [number, number] = [150, 210]
-const AP_WIRED_FAN: [number, number] = [50, 130]
-const DIST_FAN_RADIUS = 96
+const AP_WIRED_FAN: [number, number] = [150, 210]
+const DIST_FAN_RADIUS = 140
 /** distnodes: hasta DIST_FAN_MAX hijos en abanico de 136°; con más, el arco
  *  de radio fijo los amontona (issue #5 bug 2: 8 bocas tras un switch en el
  *  mismo puerto) → anillos concéntricos alrededor del círculo dashed. */
 const DIST_FAN_MAX = 5
 const DIST_RINGS = [
-  { r: 72, cap: 7 },
-  { r: 118, cap: 12 },
+  { r: 78, cap: 8 },
+  { r: 128, cap: 14 },
 ]
-const HUB_FAN_RADIUS = 68
-const ROUTER_FAN_RADIUS = 150
+const HUB_FAN_RADIUS = 120
+const ROUTER_FAN_RADIUS = 250
 /** Hosts hipervisores del gateway: lejos (su grid de CTs necesita espacio) */
 const HYPERVISOR_FAN_RADIUS = 320
 /** Grid de CTs bajo el host hipervisor */
@@ -302,29 +311,33 @@ function freeArcs(excludes: [number, number][]): [number, number][] {
 }
 
 /** reparte items en anillos concéntricos evitando arcos prohibidos */
-function ringLayout<T extends { x: number; y: number }>(
+const CHIP_GAP = 6
+function ringLayout<T extends { x: number; y: number; size?: number }>(
   items: T[],
   node: { x: number; y: number },
   rings: { r: number; cap: number }[],
   excludes: [number, number][],
 ): void {
   const free = freeArcs(excludes)
-  const total = free.reduce((a, [s, e]) => a + (e - s), 0)
-  if (total <= 0) return
+  const totalFree = free.reduce((a, [s, e]) => a + (e - s), 0)
+  if (totalFree <= 0) return
   let idx = 0
   for (const ring of rings) {
     if (idx >= items.length) break
-    const n = Math.min(ring.cap, items.length - idx)
-    let placed = 0
-    for (let ai = 0; ai < free.length && placed < n; ai++) {
+    const chipSize = items[idx]?.size ?? 24
+    const minArcDeg = ((chipSize + CHIP_GAP) * 180) / (Math.PI * ring.r)
+    let ringPlaced = 0
+    for (let ai = 0; ai < free.length && ringPlaced < ring.cap && idx < items.length; ai++) {
       const [s, e] = free[ai]
-      let k = Math.min(Math.round((n * (e - s)) / total), n - placed)
-      if (ai === free.length - 1) k = n - placed
+      const arcLen = e - s
+      const maxFit = Math.max(1, Math.floor(arcLen / minArcDeg))
+      const remaining = items.length - idx
+      const k = Math.min(maxFit, ring.cap - ringPlaced, remaining)
       for (let i = 0; i < k; i++) {
-        const a = s + ((e - s) * (i + 0.5)) / k
+        const a = s + (arcLen * (i + 0.5)) / k
         const p = pos(node.x, node.y, a, ring.r)
         Object.assign(items[idx++], p)
-        placed++
+        ringPlaced++
       }
     }
   }
@@ -359,6 +372,52 @@ function gridLayoutWest<T extends { x: number; y: number }>(items: T[], node: {
   })
 }
 
+/** Resolución de colisiones por empuje iterativo + fuerza centrípeta.
+ *  Cada chip tiene opcionalmente un hubId que lo atrae suavemente hacia su padre.
+ *  Los nodos fijos (routers, distnodes) no se mueven. */
+function resolveCollisions(
+  items: { x: number; y: number; r: number; fixed?: boolean; hubX?: number; hubY?: number }[],
+  iterations = 80,
+  padding = 14,
+): void {
+  for (let iter = 0; iter < iterations; iter++) {
+    let moved = false
+    for (let i = 0; i < items.length; i++) {
+      for (let j = i + 1; j < items.length; j++) {
+        const a = items[i]
+        const b = items[j]
+        const dx = b.x - a.x
+        const dy = b.y - a.y
+        const dist = Math.sqrt(dx * dx + dy * dy) || 0.001
+        const minDist = a.r + b.r + padding
+        if (dist < minDist) {
+          const overlap = (minDist - dist) * 0.45
+          const nx = dx / dist
+          const ny = dy / dist
+          if (!a.fixed) { a.x -= nx * overlap; a.y -= ny * overlap }
+          if (!b.fixed) { b.x += nx * overlap; b.y += ny * overlap }
+          moved = true
+        }
+      }
+    }
+    // fuerza centrípeta leve: cada chip no-fijo es atraído hacia su hub
+    for (const item of items) {
+      if (item.fixed || item.hubX === undefined) continue
+      const dx = item.hubX! - item.x
+      const dy = item.hubY! - item.y
+      const dist = Math.sqrt(dx * dx + dy * dy) || 0.001
+      // solo tira si está demasiado lejos (> 350px) para evitar que se amontone
+      if (dist > 350) {
+        const pull = (dist - 350) * 0.02
+        item.x += (dx / dist) * pull
+        item.y += (dy / dist) * pull
+        moved = true
+      }
+    }
+    if (!moved) break
+  }
+}
+
 /** flujo de paquetes ∝ tráfico (mockup: umbrales 35/15/2 Mbps, guardrail 60).
  *  `alive`: enlace físico activo sin medición de tráfico (live no mide Mbps
  *  por cliente) → 1 paquete lento para que el cable "respire" (5s). */
@@ -376,13 +435,33 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   // `topology` presente; sin ella, fallback EXACTO al cálculo local.
   const sem = topology && (vm ?? 1) >= 1 ? topology : undefined
   const gateway = routers.find((r) => r.roleBadge === 'Principal') ?? routers[0]
-  const aps = routers.filter((r) => r.id !== gateway?.id).slice(0, AP_COORDS.length)
+  const aps = routers.filter((r) => r.id !== gateway?.id && r.roleBadge !== 'SW')
+  const switches = routers.filter((r) => r.roleBadge === 'SW')
 
   const gatewayNode: RouterNode | null = gateway
     ? { kind: 'router', id: gateway.id, router: gateway, ...GATEWAY_COORD }
     : null
-  const apNodes: RouterNode[] = aps.map((router, i) => ({ kind: 'router', id: router.id, router, ...AP_COORDS[i] }))
-  const routerNodes: RouterNode[] = gatewayNode ? [gatewayNode, ...apNodes] : apNodes
+  const apNodes: RouterNode[] = aps.map((router, i) => ({ kind: 'router', id: router.id, router, ...apCoords(i, aps.length) }))
+  // Switches gestionados: al NOROESTE del gateway (esquina sup. izq.), uno debajo
+  // de otro. Antes al sureste (x=720); al moverlo arriba-izq. libera la banda
+  // este para los APs y no choca con el hipervisor (far-west, más abajo).
+  // Coordenadas deterministas para máximo 3 switches; el 4+ no se pinta.
+  const SW_BASE_X = 280
+  const SW_BASE_Y = 140
+  const SW_GAP_Y = 90
+  const switchNodes: RouterNode[] = switches.slice(0, 3).map((router, i) => ({
+    kind: 'router' as const,
+    id: router.id,
+    router,
+    x: SW_BASE_X,
+    y: SW_BASE_Y + i * SW_GAP_Y,
+    r: 28,
+    // label a la IZQUIERDA del icono (anchor end): el gateway está a la derecha
+    // y su anillo wifi llegaría hasta ~x310; un label a la derecha del switch
+    // (x~314) quedaría pegado al anillo.
+    label: { x: SW_BASE_X - 34, y: SW_BASE_Y + i * SW_GAP_Y - 6, anchor: 'end' as const },
+  }))
+  const routerNodes: RouterNode[] = gatewayNode ? [gatewayNode, ...apNodes, ...switchNodes] : [...apNodes, ...switchNodes]
   const routerById = new Map(routerNodes.map((n) => [n.id, n]))
 
   const internetNode = { id: 'internet' as const, ...INTERNET_COORD }
@@ -518,7 +597,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     device: d,
     x: 0,
     y: 0,
-    size: isWired(d) ? 26 : 24,
+    size: isWired(d) ? 22 : 20,
     wired: isWired(d),
     band: d.band,
     weak: d.signalDbm != null && d.signalDbm <= -65,
@@ -539,25 +618,26 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       excludes.push(...arcAround(270, 14)) // WAN hacia Internet
       if (gatewayNode) excludes.push(...arcAround(angleTo(gatewayNode.x, gatewayNode.y, gatewayNode.label.x, gatewayNode.label.y), 22))
       for (const ap of apNodes) excludes.push(...arcAround(angleTo(node.x, node.y, ap.x, ap.y), 15))
+      // switches gestionados: ahora al NW del gateway; sin este exclude los
+      // chips wifi del anillo externo (r=190) caerían encima del icono del switch.
+      for (const sw of switchNodes) excludes.push(...arcAround(angleTo(node.x, node.y, sw.x, sw.y), 20))
     } else {
       if (gatewayNode) excludes.push(...arcAround(angleTo(node.x, node.y, gatewayNode.x, gatewayNode.y), 27))
       excludes.push(...arcAround(angleTo(node.x, node.y, node.label.x, node.label.y), 22))
     }
     excludes.push(...(fanArcByRouter.get(node.id) ?? []))
     const baseRings = isGw ? GATEWAY_RINGS : AP_RINGS
-    // anillos extra si el wifi supera el aforo de los dos primeros
     const rings = [...baseRings]
     let cap = rings.reduce((a, r) => a + r.cap, 0)
     while (cap < wifi.length) {
       const last = rings[rings.length - 1]
-      rings.push({ r: last.r + 30, cap: last.cap + 5 })
+      rings.push({ r: last.r + 38, cap: Math.min(last.cap + 3, 10) })
       cap = rings.reduce((a, r) => a + r.cap, 0)
     }
     ringRadii.set(node.id, rings.map((r) => r.r))
     ringLayout(wifi, node, rings, excludes)
-    // chips algo menores en anillos externos
     wifi.forEach((c, i) => {
-      if (i >= baseRings[0].cap) c.size = 22
+      if (i >= baseRings[0].cap) c.size = 20
     })
     chips.push(...wifi)
   }
@@ -696,22 +776,36 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       from: 'internet', to: gatewayNode.id,
     })
   }
-  apNodes.forEach((node, i) => {
-    const p = UPLINK_PATHS[i]
-    // C1: backhaul real del router (ausente = cable); sin hardcode por id.
+  const makeUplink = (node: RouterNode) => {
     const isWifi = node.router.backhaul === 'wifi'
+    const isSwitch = node.router.roleBadge === 'SW'
     const traffic = subtreeTraffic(node.id)
-    // Etiqueta wifi: genérica (no hay dato de señal en el contrato Router);
-    // cable: sufijo "· LLDP" si el AP se anuncia en el puerto del uplink (C2).
-    const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
+    const label = isWifi
+      ? 'WiFi uplink'
+      : isSwitch
+        ? `Switch ${node.router.name}${node.router.lldp ? ' · LLDP' : ''}`
+        : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
+    const from = gatewayNode ?? null
+    let d = ''
+    let lx = 0, ly = 0
+    if (from) {
+      const edge = pos(from.x, from.y, angleTo(from.x, from.y, node.x, node.y), from.r + 2)
+      const dx = node.x - edge.x
+      const dy = node.y - edge.y
+      d = `M ${edge.x} ${edge.y} C ${edge.x + dx * 0.35} ${edge.y + dy * 0.15}, ${node.x - dx * 0.15} ${node.y - dy * 0.35}, ${node.x} ${node.y}`
+      lx = Math.round((edge.x + node.x) / 2)
+      ly = Math.round((edge.y + node.y) / 2)
+    }
     links.push({
       id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
-      d: p.d, lx: p.lx, ly: p.ly,
+      d, lx, ly,
       label,
-      width: isWifi ? 2 : 3, ...flowFor(Math.max(traffic, isWifi ? 40 : 120)),
-      from: gatewayNode?.id ?? 'internet', to: node.id,
+      width: isSwitch ? 2 : isWifi ? 2 : 3, ...flowFor(Math.max(traffic, isWifi ? 40 : isSwitch ? 60 : 120)),
+      from: from?.id ?? 'internet', to: node.id,
     })
-  })
+  }
+  apNodes.forEach(makeUplink)
+  switchNodes.forEach(makeUplink)
   // enlaces router → distnode / device-hub / cableado directo
   for (const dv of distNodes) {
     const rn = routerById.get(dv.node.routerId)
@@ -812,12 +906,12 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
           if (!node) return null
           const isWifi = node.router.backhaul === 'wifi'
           const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
-          const p = i >= 0 ? UPLINK_PATHS[i] : null
           const from = gatewayNode ?? null
+          const d = from ? curve(from, node) : ''
           return {
             id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
-            d: p?.d ?? (from ? curve(from, node) : ''),
-            lx: p?.lx ?? 0, ly: p?.ly ?? 0,
+            d,
+            lx: 0, ly: 0,
             label,
             width: isWifi ? 2 : 3, ...flowFor(Math.max(subtreeTraffic(node.id), isWifi ? 40 : 120)),
             from: sl.from, to: sl.to,
@@ -1003,6 +1097,29 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const relatedTo = (nodeId: string) =>
     adjacency.get(nodeId) ?? { nodes: new Set([nodeId]), links: new Set<string>() }
 
+  // --- Resolución de colisiones ---
+  // Routers fijos (no se mueven); chips se empujan y atraen hacia su hub padre.
+  const collidables: { x: number; y: number; r: number; fixed?: boolean; hubX?: number; hubY?: number }[] = [
+    ...routerNodes.map((rn) => ({ x: rn.x, y: rn.y, r: rn.r, fixed: true })),
+  ]
+  // chips: buscar coords del hub padre
+  for (const c of chips) {
+    const hub = routerNodes.find(rn => rn.id === c.hubId) ?? distNodes.find(dn => dn.id === c.hubId)
+    collidables.push({
+      x: c.x, y: c.y, r: c.size / 2,
+      hubX: hub ? hub.x : undefined,
+      hubY: hub ? hub.y : undefined,
+    })
+  }
+  // distnodes fijos
+  for (const dn of distNodes) {
+    collidables.push({ x: dn.x, y: dn.y, r: dn.r, fixed: true })
+  }
+  resolveCollisions(collidables)
+  // Escribir posiciones de vuelta (solo chips; routers y distnodes son fixed)
+  let ci = routerNodes.length
+  for (const c of chips) { c.x = collidables[ci].x; c.y = collidables[ci].y; ci++ }
+
   return {
     gatewayNode,
     apNodes,

+ 1 - 0
app/src/data/DataProvider.tsx

@@ -377,6 +377,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       topology: o.topology,
       dawn: o.dawn,
       orchestration: o.orchestration,
+      ...(o.devices ? { devices: o.devices } : {}),
     }))
   }, [])
 

+ 6 - 2
app/src/data/types.ts

@@ -21,8 +21,8 @@ export interface Router {
   /** Modelo corto para captions: "GL.iNet Flint 2" */
   modelShort: string
   role: string
-  /** Pill de rol: "Principal" | "AP" */
-  roleBadge: 'Principal' | 'AP'
+  /** Pill de rol: "Principal" | "AP" | "SW" */
+  roleBadge: 'Principal' | 'AP' | 'SW'
   ip: string
   /** MAC del bridge br-lan (live) */
   mac?: string
@@ -311,6 +311,10 @@ export interface OverviewBundle {
   dawn?: { available: boolean }
   /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
   orchestration?: boolean
+  /** Devices from the same polled snapshot as topology.rings. When present,
+   *  the frontend uses this instead of the separate /api/devices fetch
+   *  to guarantee ID consistency with topology rings. */
+  devices?: Device[]
   ts: number
 }
 

+ 2 - 3
app/src/pages/Topology.tsx

@@ -10,7 +10,7 @@ import { ChevronRight, Maximize, RefreshCw, ZoomIn, ZoomOut } from 'lucide-react
 import { Switch } from '@/components/ui/switch'
 import { LegendCard, LegendSheet } from '@/components/topology/LegendCard'
 import { LinksTable } from '@/components/topology/LinksTable'
-import { DawnPanel } from '@/components/topology/DawnPanel'
+
 import { TopologyMap } from '@/components/topology/TopologyMap'
 import type { TopologyMapApi } from '@/components/topology/TopologyMap'
 import { buildTopologyModel } from '@/components/topology/model'
@@ -205,8 +205,7 @@ export default function Topology() {
         <LegendSheet model={model} />
       </section>
 
-      {/* ⑤ DAWN (roaming/band-steering) */}
-      <DawnPanel />
+
 
       {/* ③ + ④ Leyenda y enlaces (desktop: 5/7 cols; móvil: solo enlaces en lista) */}
       <div className="grid grid-cols-1 gap-4 md:gap-5 lg:grid-cols-12">

+ 1 - 1
docs/AUDITORIA-FASE65.md

@@ -19,7 +19,7 @@ E2E demo local (login → overview → agents → push → alerts config).
 
 ## 1. Incidente de seguridad durante la integración (RESUELTO)
 
-El bundle de Kimi traía commiteada por error **una clave privada SSH**
+El bundle de integración traía commiteada por error **una clave privada SSH**
 (`app/data/.ssh/id_ed25519`, commit 5f7a74c) junto a una BD demo. Gitleaks lo
 detectó al pushear el tag. Acciones tomadas:
 

+ 1 - 1
docs/ROADMAP.md

@@ -471,7 +471,7 @@ PR (convención issue→PR).
 
 ---
 
-## Fase 13 — Auditoría Fable de robustez de código (COMPLETA, v2.7.2)
+## Fase 13 — Auditoría de robustez de código (COMPLETA, v2.7.2)
 
 Objetivo: auditoría dirigida de concurrencia, manejo de errores y fronteras
 en server-go. Cada hallazgo con mecanismo completo, test de regresión y fix.

+ 75 - 0
docs/architecture-and-stack.md

@@ -0,0 +1,75 @@
+# Netpulse: Análisis Arquitectónico y Guía de Mejoras de Stack
+
+## 1. Diagnóstico y Decisión Arquitectónica (Opciones A/B/C)
+
+El problema de raíz radica en cómo el colector asigna el `routerId` basándose en qué router reporta la MAC en su tabla ARP, en lugar de basarse en la topología física. En topologías bridged (rt2 ↔ switch16), el ARP de rt2 ve TODO el segmento L2, incluyendo dispositivos detrás de switch16.
+
+### Recomendación: Opción C (con un matiz importante)
+
+El fix A (corrección en el servidor usando FDB/LLDP) **no es solo un parche — es la corrección arquitectónica necesaria**. El colector no puede saber con certeza dónde cuelga un dispositivo cableado solo desde su ARP local.
+
+El contrato correcto agente→server a medio plazo (Opción B) debería ser: *"reporto asociaciones WiFi mías + vecino LLDP directo + FDB de mis propios puertos"*. No "todo lo que veo en ARP".
+
+Mientras tanto, la Opción A permite descifrar la topología en el servidor cruzando FDB de switch16 + LLDP.
+
+**Bug aparte urgente:** El límite hardcoded de 4 routerNodes (gateway + 3 APs) que excluye a switch16 con `roleBadge=SW` debe ser eliminado.
+
+---
+
+## 2. Recursos y Skills Curadas para el Stack
+
+### 2.1 Descubrimiento de Topología de Red (El núcleo del bug)
+
+| Recurso | Por qué sirve / Cómo usarlo |
+|---|---|
+| **`lldpd`** — [github.com/lldpd/lldpd](https://github.com/lldpd/lldpd) | Implementación de referencia de IEEE 802.1AB. Permite entender qué campos exportar del agente (ChassisID, PortID, TTL). Su cliente `lldpcli` tiene salida JSON. |
+| **Linux `bridge fdb show` + `bridge -j`** | JSON estructurado del FDB (Forwarding DataBase). Esto es lo que el agente en switch16 debe reportar al servidor para que el cruce de topología funcione. Doc: `man 8 bridge`. |
+| **`ip -j neigh show`** | ARP en JSON. Asegurar que el agente lo usa con este formato para estandarizar. |
+| **OpenWrt `ubus`** — [openwrt.org/docs/techref/ubus](https://openwrt.org/docs/techref/ubus) | Si redmi-ax6 y rt2 corren OpenWrt, `ubus call network.device status` da datos canónicos sin parsear texto. |
+| **RFC 8174 / IEEE 802.1AB-2016** | Especificación LLDP. Especialmente §7 (TLVs). |
+
+**Patrón arquitectónico a estudiar:** **`ntopng` + `nProbe`** — [github.com/ntop/ntopng](https://github.com/ntop/ntopng). Su collector de capa 2 cruza FDB+LLDP+ARP y construye topología. Sus algoritmos (resolve_bridge_port, etc.) son trasladables a TS/JS.
+
+### 2.2 Patrones de Arquitectura Agente→Servidor
+
+| Recurso | Lección para Netpulse |
+|---|---|
+| **Telegraf** — [github.com/influxdata/telegraf](https://github.com/influxdata/telegraf) | Su división input/processor/aggregator separa los datos crudos del host (FDB, LLDP) de la inferencia. El "routerId assignment" debe ir en el servidor, no en el agente. |
+| **Prometheus `node_exporter`** — [github.com/prometheus/node_exporter](https://github.com/prometheus/node_exporter) | Cada collector es independiente y reporta solo hechos locales del host. Nunca infiere topología. Esa es la disciplina que el agente de Netpulse necesita. |
+| **Sensu Go** — [github.com/sensu/sensu-go](https://github.com/sensu/sensu-go) | Modelo de contrato agente→backend con agentes ligeros en routers: "agent solo reporta, backend decide". |
+
+### 2.3 Inferencia de Topología (Algoritmos para el servidor)
+
+Para implementar la Opción A, el servidor necesita:
+
+- **Algoritmo de Spanning Tree inverso**: reconstruir el árbol cruzando BPDU de STP + FDB.
+- **Cross-referencing FDB multi-switch**: si switch16 ve MAC X en puerto P5, y rt2 ve MAC X en su ARP, entonces X cuelga de switch16:P5, no de rt2.
+- **Paper de referencia**: *"Inferring Network Topology from Layer-2 and Layer-3 Information"* — Chua & Kolaczyk (2006). Define el algoritmo canónico.
+- **Prototipado**: Usar `scapy` + `scapy-lldp` para probar el parser antes de integrarlo al agente.
+
+### 2.4 Stack TS/JS del Servidor
+
+| Skill / Recurso | Uso |
+|---|---|
+| **`awesome-nodejs`** — [github.com/sindresorhus/awesome-nodejs](https://github.com/sindresorhus/awesome-nodejs) | Lista curada general. Filtrar por "network" y "streams". |
+| **`fastify`** | Mejor que Express para endpoints como `/api/overview`. Da Schema validation de JSON Schema gratis, útil para validar el reporte del agente. |
+| **`cytoscape.js`** — [github.com/cytoscape/cytoscape.js](https://github.com/cytoscape/cytoscape.js) | Para visualizar la topología real durante debugging. Sus layouts `breadthfirst` permiten validar que el cruce FDB+LLDP da el árbol correcto. |
+| **`json-schema`** validation | Base para definir el contrato agente→server formalmente y que la evolución del colector no rompa el servidor. |
+
+### 2.5 Testing Reproducible
+
+- **`containerlab`** — [github.com/srl-labs/containerlab](https://github.com/srl-labs/containerlab): Levanta topologías L2/L3 realistas con containers. Permite simular rt2+switch16+CTs sin hardware real.
+- **`batfish`** — [github.com/batfish/batfish](https://github.com/batfish/batfish): Su modelo de topología es instructivo para validar configuraciones de red.
+
+---
+
+## 3. Plan de Acción Ejecutable
+
+1. **Inmediato:** Quitar el límite hardcoded de 4 routerNodes. switch16 debe entrar en el cálculo con `roleBadge=SW`.
+2. **Esta semana (Fix A - Servidor):**
+   - Agente en switch16 reporta `bridge -j fdb show` + `lldpcli show neighbors -f json`.
+   - Servidor cruza FDB(switch16) × ARP(rt2) → reasigna `routerId` y `attachTo` de los dispositivos cableados mal asignados.
+3. **Medio plazo (Fix B - Contrato Agente):**
+   - Redactar el JSON Schema del contrato agente→server.
+   - El agente deja de reportar ARP como fuente de "tengo esto colgando". ARP solo se usa en el servidor como pista secundaria.
+4. **Documentación del algoritmo:** Capturar el conocimiento implícito de la topología en documentación reproducible dentro del repo.

+ 631 - 0
docs/netpulse-topology-skills.md

@@ -0,0 +1,631 @@
+# NetPulse: Skills y Recursos para Arreglar la Topología de Red
+
+> Problema: El colector asigna `routerId` por quién reporta la MAC en su ARP, no por topología física real. Dispositivos cableados tras `switch16` se ven en el ARP de `rt2` (porque `rt2` está bridged al switch) y el colector les pone `routerId=redmi-ax6`. Luego `hubOf` en el servidor no los puede corregir porque no tienen `AttachTo` ni `Port`.
+
+---
+
+## Índice
+
+1. [Patrón de Arquitectura: Reconciliación Multi-Fuente](#1-patrón-de-arquitectura-reconciliación-multi-fuente)
+2. [Librerías Go Recomendadas](#2-librerías-go-recomendadas)
+   - [A) ubus (OpenWrt)](#a-ubus-openwrt)
+   - [B) Bridge FDB vía netlink](#b-bridge-fdb-vía-netlink)
+   - [C) LLDP](#c-lldp)
+   - [D) SNMP (switches no-OpenWrt)](#d-snmp-switches-no-openwrt)
+   - [E) SQLite WAL](#e-sqlite-wal)
+3. [Análisis de Opciones A / B / C](#3-análisis-de-opciones-a--b--c)
+4. [Estructura de Código Sugerida](#4-estructura-de-código-sugerida)
+5. [Fuentes y Referencias](#5-fuentes-y-referencias)
+
+---
+
+## 1. Patrón de Arquitectura: Reconciliación Multi-Fuente
+
+Tu problema es clásico de **reconciliación de múltiples fuentes de datos con granularidad diferente**. El colector reporta "vista L3" (ARP) y necesitas inferir "vista L2" (FDB + LLDP). Los NMS maduros (NetXMS, WhatsUp Gold) resuelven esto con un **pipeline de reconciliación** en el servidor, no confiando ciegamente en lo que reporta cada agente.
+
+### Diagrama del patrón
+
+```
+┌─────────────┐     ┌─────────────┐     ┌─────────────┐
+│  Source 1   │     │  Source 2   │     │  Source 3   │
+│  ARP table  │     │  Bridge FDB │     │   LLDP      │
+│  (router)   │     │  (switch)   │     │  (switch)   │
+└──────┬──────┘     └──────┬──────┘     └──────┬──────┘
+       │                   │                   │
+       └───────────────────┼───────────────────┘
+                           ▼
+              ┌─────────────────────┐
+              │  Reconciliation     │
+              │  Engine (server)    │
+              │  - MAC → port (FDB) │
+              │  - Port → neighbor  │
+              │    (LLDP)           │
+              │  - Confidence score   │
+              └─────────────────────┘
+```
+
+### Cómo lo hacen los NMS maduros
+
+**NetXMS** implementa exactamente esto:
+
+> *"From FDB table we take ports where only one MAC address is present — this means that something is directly connected. If this device is present in NetXMS and its MAC address is known, we have a peer."*
+
+> *"LLDP: if we have another switch connected, that switch is sending LLDP packets... we read this table and we know that there's a device with some LLDP ID connected to port X."*
+
+**WhatsUp Gold** usa un patrón similar:
+
+> *"WhatsUp Gold uses layer 2 and layer 3 discovery to identify and map devices on your network. Layer 2 discovery uses the Address Resolution Protocol (ARP) cache... Layer 3 discovery uses the Simple Network Management Protocol (SNMP) to query devices for information."*
+
+**Aplicación a tu caso:**
+- `switch16` debe reportar su propia FDB (no depender de que `rt2` la vea en ARP)
+- El servidor debe cruzar MAC → port → neighbor (LLDP) para determinar el attachment point real
+- Los dispositivos sin `AttachTo` ni `Port` pero presentes en FDB de un switch conocido → se les asigna `routerId = switch16`
+
+---
+
+## 2. Librerías Go Recomendadas
+
+### A) ubus (OpenWrt)
+
+Tu colector habla con OpenWrt vía ubus. Opciones mejores que parsear raw:
+
+| Librería | URL | Características |
+|----------|-----|-----------------|
+| `goubus` | `github.com/honeybbq/goubus` | Type-safe, dual transport (HTTP JSON-RPC + Unix socket), manager pattern (`client.System()`, `client.Network()`). Soporta exec de comandos vía `client.File().Exec()`. |
+| `go-ubus-rpc` | `github.com/daimonaslabs/go-ubus-rpc` | CLI + library, typed results, maneja todo el marshaling de ubus responses. |
+
+**Skill:** Si tu colector actual parsea output de `ssh` o `ubus` raw, migrar a una de estas librerías te da type safety y reduce bugs de parsing.
+
+### B) Bridge FDB vía netlink
+
+En vez de hacer `ssh router "bridge fdb show"` y parsear texto, puedes usar **`github.com/vishvananda/netlink`** directamente desde Go.
+
+```go
+import "github.com/vishvananda/netlink"
+
+// Listar FDB (Forwarding Database)
+neighs, err := netlink.NeighList(0, netlink.FAMILY_ALL)
+// Filtrar solo entries de tipo bridge fdb
+for _, n := range neighs {
+    if n.Family == netlink.FAMILY_BRIDGE {
+        // n.IP, n.HardwareAddr, n.LinkIndex, n.State
+    }
+}
+```
+
+**Funciones clave:**
+- `NeighList()` — Equivalente a `ip neighbor show`
+- `NeighSubscribe()` — Updates en tiempo real vía netlink socket
+- `LinkList()` — Interfaces disponibles
+
+**Esto es clave para tu opción A (fix en servidor):** si `switch16` corre Linux (OpenWrt o similar), puedes leer su FDB vía netlink y cruzar MAC→port sin depender de lo que reporte el agente del router.
+
+### C) LLDP
+
+| Librería | URL | Características |
+|----------|-----|-----------------|
+| `gotopo/lldp` | `github.com/ksang/gotopo/lldp` | Estructuras de datos y colección de endpoints LLDP. |
+| `lldp2map` | `github.com/buraglio/lldp2map` | Herramienta Go que hace walk recursivo de tablas LLDP vía SNMP y genera diagramas. Estudia cómo resuelve neighbor discovery. |
+
+**Nota:** Para LLDP nativo en OpenWrt, necesitas `lldpd` instalado. El daemon expone datos vía:
+- Unix socket (`/var/run/lldpd.socket`)
+- SNMP (si está habilitado)
+- CLI (`lldpcli show neighbors`)
+
+### D) SNMP (switches no-OpenWrt)
+
+| Librería | URL | Características |
+|----------|-----|-----------------|
+| `gosnmp` | `github.com/gosnmp/gosnmp` | Librería SNMP estándar en Go. Soporta v1/v2c/v3, Walk, BulkWalk, Traps. |
+
+**OIDs útiles para topología:**
+- `1.3.6.1.2.1.17.4.3` — `dot1dTpFdbTable` (FDB/bridge MAC table)
+- `1.0.8802.1.1.2.1.4.1` — `lldpRemTable` (LLDP neighbors)
+- `1.3.6.1.2.1.2.2.1.2` — `ifDescr` (interface descriptions)
+
+Esto te abre la puerta a soportar switches que no sean OpenWrt (managed switches con SNMP LLDP).
+
+### E) SQLite WAL
+
+Usas `modernc.org/sqlite` (bien, sin CGO). Asegúrate de tener los pragmas correctos para el patrón "un writer, muchos readers" que necesitas con SSE + collector concurrente:
+
+```go
+dsn := fmt.Sprintf(
+    "%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)",
+    path,
+)
+db.SetMaxOpenConns(1)  // CRÍTICO para SQLite
+db.SetMaxIdleConns(1)
+```
+
+**Si necesitas reads concurrentes mientras escribes**, la recomendación es **dos instancias `*sql.DB`**:
+- Una para writes (`MaxOpenConns=1`)
+- Otra para reads (`MaxOpenConns` ilimitado, WAL permite concurrent reads)
+
+---
+
+## 3. Análisis de Opciones A / B / C
+
+### Hechos verificados (de tu análisis)
+
+1. `/api/overview` devuelve 69 devices online, 51 wifi + 18 wired
+2. 46 devices en el ring del gateway (cap=13, overflow +33) — la mayoría mal asignados
+3. 12 wired bajo `rt2` que físicamente están tras `switch16` → el colector los asignó a `rt2` porque `rt2` los ve en su ARP
+4. `switch16` (5º router, `roleBadge=SW`) queda fuera de `routerNodes` (hardcodeado a máx 4: gw + 3 APs)
+5. Los 3 CTs bajo `switch16` (citadel-01/02, PBS) no aparecen en ningún ring
+6. Los distnodes (inferred en lan3, hypervisor en switch16) se crean pero el hipervisor no genera enlaces porque su router (`switch16`) no está en `routerNodes`
+
+### Opción A: Fix en el servidor (Recomendado como parche inmediato)
+
+**Qué hace:** Implementa un **Topology Reconciler** en el servidor que:
+
+1. **Ingesta múltiples fuentes** por router/switch:
+   - `arp_table` (de cada agente)
+   - `bridge_fdb` (de cada dispositivo que lo soporte, incluido `switch16`)
+   - `lldp_neighbors` (de cada dispositivo)
+
+2. **Asigna `routerId` por evidencia, no por reporte:**
+   - Si un dispositivo cableado aparece en el FDB de `switch16` en `port X`, y `switch16` es un nodo conocido → `routerId = switch16`.
+   - Si aparece en FDB de `rt2` pero también en FDB de `switch16` → la fuente "más específica" (`switch16`, que es L2 puro) gana.
+   - Usa un **confidence score**: FDB directo > ARP indirecto.
+
+3. **Expande `routerNodes` dinámicamente:**
+   - En vez de hardcodear 4 nodos, detecta switches vía LLDP o FDB y los añade como `roleBadge=SW` con su propio ring.
+
+4. **Genera `attachTo` + `port` inferidos:**
+   - Del FDB: MAC → port → si el port tiene un LLDP neighbor conocido, `attachTo = neighbor`.
+   - Si no hay LLDP, `attachTo = switch16` (el switch es el attachment point).
+
+**Pros:**
+- No toca firmware de routers
+- Funciona con datos actuales del colector
+- Contained, reversible
+
+**Cons:**
+- Lógica más compleja en servidor
+- Sigue dependiendo de ARP "sucio" del colector
+
+### Opción B: Fix en el colector (Rediseño del contrato)
+
+**Qué hace:** Cambia el contrato agente→server para que cada agente reporte:
+
+- **WiFi clients:** solo los que tiene asociados (`iwinfo`/`ubus`)
+- **Wired clients:** solo los que aparecen en su **FDB local** con `master br0` y no son `self`/`permanent` de otros puertos
+- **ARP table:** como fuente secundaria, etiquetada como `source:arp`, no como `source:direct`
+
+**Pros:**
+- Datos más limpios desde la fuente
+- Menos trabajo de reconciliación en servidor
+- Cada agente solo reporta lo que "ve" realmente
+
+**Cons:**
+- Requiere desplegar nuevo firmware en todos los routers
+- Cambia el contrato agente→server (breaking change)
+- No resuelve el caso de `switch16` si no tiene agente propio
+
+### Opción C: Ambos (Recomendación final)
+
+**Voto por C, con prioridad en A como parche inmediato.**
+
+- **A** resuelve tu problema *ahora* sin tocar firmware de routers.
+- **B** reduce la carga de reconciliación y hace el sistema más robusto a largo plazo.
+- **A+B juntos** = el servidor tiene un reconciliador defensivo (por si un agente miente o no sabe) y los agentes reportan datos más limpios.
+
+**Roadmap sugerido:**
+
+```
+Fase 1 (ahora):   Implementar Reconciler en servidor (Opción A)
+                  → switch16 aparece en topology, CTs visibles
+                  → 46 devices del gateway se redistribuyen
+
+Fase 2 (próximo): Rediseñar contrato del colector (Opción B)
+                  → Cada agente reporta solo dispositivos "propios"
+                  → Reducir carga de reconciliación
+
+Fase 3 (futuro):  Soporte SNMP para switches no-OpenWrt
+                  → NetPulse soporta cualquier switch managed
+```
+
+---
+
+## 4. Estructura de Código Sugerida
+
+### 4.1 Reconciler
+
+```go
+// pkg/topology/reconciler.go
+package topology
+
+import (
+    "database/sql"
+    "fmt"
+    "sort"
+)
+
+// EvidenceSource indica de dónde viene la evidencia
+type EvidenceSource string
+
+const (
+    SourceARP        EvidenceSource = "arp"
+    SourceFDB        EvidenceSource = "fdb"
+    SourceLLDP       EvidenceSource = "lldp"
+    SourceWiFiAssoc  EvidenceSource = "wifi_assoc"
+)
+
+// DeviceEvidence es una observación de un dispositivo en la red
+type DeviceEvidence struct {
+    MAC        string
+    IP         string
+    Source     EvidenceSource
+    RouterID   string   // quien reportó
+    Port       string   // para FDB/LLDP
+    NeighborID string   // para LLDP
+    Confidence int      // 1-10
+    Timestamp  int64
+}
+
+// Reconciler engine de topología
+type Reconciler struct {
+    db *sql.DB
+}
+
+func NewReconciler(db *sql.DB) *Reconciler {
+    return &Reconciler{db: db}
+}
+
+// Reconcile toma evidencia cruda y produce dispositivos con routerId correcto
+func (r *Reconciler) Reconcile(evidence []DeviceEvidence) (map[string]*Device, error) {
+    byMAC := make(map[string][]DeviceEvidence)
+
+    // 1. Agrupar por MAC
+    for _, e := range evidence {
+        byMAC[e.MAC] = append(byMAC[e.MAC], e)
+    }
+
+    devices := make(map[string]*Device)
+
+    for mac, evs := range byMAC {
+        // 2. Ordenar por confidence (mayor primero)
+        sort.Slice(evs, func(i, j int) bool {
+            return evs[i].Confidence > evs[j].Confidence
+        })
+
+        best := evs[0]
+
+        device := &Device{
+            MAC:      mac,
+            IP:       best.IP,
+            RouterID: best.RouterID,
+            Source:   best.Source,
+        }
+
+        // 3. Si hay FDB, extraer port
+        for _, e := range evs {
+            if e.Source == SourceFDB && e.Port != "" {
+                device.Port = e.Port
+                device.AttachTo = e.RouterID
+                break
+            }
+        }
+
+        // 4. Si hay LLDP neighbor en ese port, actualizar attachTo
+        for _, e := range evs {
+            if e.Source == SourceLLDP && e.NeighborID != "" {
+                device.AttachTo = e.NeighborID
+                break
+            }
+        }
+
+        devices[mac] = device
+    }
+
+    return devices, nil
+}
+
+// Confidence scoring
+func ConfidenceFor(source EvidenceSource) int {
+    switch source {
+    case SourceFDB:
+        return 9  // FDB local = muy confiable
+    case SourceLLDP:
+        return 10 // LLDP = máxima confianza
+    case SourceWiFiAssoc:
+        return 8  // WiFi association = confiable
+    case SourceARP:
+        return 3  // ARP = puede ser indirecto (bridge)
+    default:
+        return 1
+    }
+}
+
+type Device struct {
+    MAC      string
+    IP       string
+    RouterID string
+    Port     string
+    AttachTo string
+    Source   EvidenceSource
+}
+```
+
+### 4.2 FDB Collector (para switch16 u otros dispositivos L2)
+
+```go
+// pkg/collector/fdb.go
+package collector
+
+import (
+    "fmt"
+    "net"
+    "strings"
+
+    "github.com/vishvananda/netlink"
+)
+
+// FDBEntry representa una entrada de la forwarding database
+type FDBEntry struct {
+    MAC       net.HardwareAddr
+    Port      string
+    LinkIndex int
+    State     int
+}
+
+// CollectFDB lee la bridge FDB de un dispositivo Linux (OpenWrt, etc.)
+func CollectFDB() ([]FDBEntry, error) {
+    neighs, err := netlink.NeighList(0, netlink.FAMILY_ALL)
+    if err != nil {
+        return nil, fmt.Errorf("neighlist: %w", err)
+    }
+
+    links, err := netlink.LinkList()
+    if err != nil {
+        return nil, fmt.Errorf("linklist: %w", err)
+    }
+
+    linkByIndex := make(map[int]netlink.Link)
+    for _, l := range links {
+        linkByIndex[l.Attrs().Index] = l
+    }
+
+    var entries []FDBEntry
+    for _, n := range neighs {
+        if n.Family != netlink.FAMILY_BRIDGE {
+            continue
+        }
+
+        link := linkByIndex[n.LinkIndex]
+        if link == nil {
+            continue
+        }
+
+        entries = append(entries, FDBEntry{
+            MAC:       n.HardwareAddr,
+            Port:      link.Attrs().Name,
+            LinkIndex: n.LinkIndex,
+            State:     n.State,
+        })
+    }
+
+    return entries, nil
+}
+
+// FilterDirectlyConnected filtra entries que son dispositivos directamente conectados
+// (excluye self/permanent entries del propio switch)
+func FilterDirectlyConnected(entries []FDBEntry) []FDBEntry {
+    var result []FDBEntry
+    for _, e := range entries {
+        // Skip permanent/self entries
+        if e.State == netlink.NUD_PERMANENT || e.State == netlink.NUD_NOARP {
+            continue
+        }
+        // Skip internal bridge ports
+        if strings.HasPrefix(e.Port, "br-") {
+            continue
+        }
+        result = append(result, e)
+    }
+    return result
+}
+```
+
+### 4.3 LLDP Collector
+
+```go
+// pkg/collector/lldp.go
+package collector
+
+import (
+    "encoding/json"
+    "fmt"
+    "os/exec"
+)
+
+// LLDPNeighbor representa un vecino descubierto por LLDP
+type LLDPNeighbor struct {
+    LocalPort    string `json:"port"`
+    ChassisID    string `json:"chassis-id"`
+    PortID       string `json:"port-id"`
+    SysName      string `json:"sys-name"`
+    SysDescr     string `json:"sys-descr"`
+}
+
+// CollectLLDP ejecuta lldpcli y parsea el output JSON
+func CollectLLDP() ([]LLDPNeighbor, error) {
+    cmd := exec.Command("lldpcli", "show", "neighbors", "-f", "json")
+    out, err := cmd.Output()
+    if err != nil {
+        return nil, fmt.Errorf("lldpcli: %w", err)
+    }
+
+    var result struct {
+        LLDP struct {
+            Interface map[string]struct {
+                Via string `json:"via"`
+                Port struct {
+                    ID struct {
+                        Type  string `json:"type"`
+                        Value string `json:"value"`
+                    } `json:"id"`
+                } `json:"port"`
+                Chassis map[string]struct {
+                    ID struct {
+                        Type  string `json:"type"`
+                        Value string `json:"value"`
+                    } `json:"id"`
+                    Descr string `json:"descr"`
+                } `json:"chassis"`
+            } `json:"interface"`
+        } `json:"lldp"`
+    }
+
+    if err := json.Unmarshal(out, &result); err != nil {
+        return nil, fmt.Errorf("parse lldp: %w", err)
+    }
+
+    var neighbors []LLDPNeighbor
+    for portName, iface := range result.LLDP.Interface {
+        for chassisName, chassis := range iface.Chassis {
+            neighbors = append(neighbors, LLDPNeighbor{
+                LocalPort: portName,
+                ChassisID: chassis.ID.Value,
+                PortID:    iface.Port.ID.Value,
+                SysName:   chassisName,
+                SysDescr:  chassis.Descr,
+            })
+        }
+    }
+
+    return neighbors, nil
+}
+```
+
+### 4.4 Router Discovery (expandir routerNodes dinámicamente)
+
+```go
+// pkg/topology/discovery.go
+package topology
+
+import (
+    "database/sql"
+    "fmt"
+)
+
+// RouterDiscovery detecta routers/switches automáticamente
+type RouterDiscovery struct {
+    db *sql.DB
+}
+
+// DiscoverFromLLDP encuentra switches vía LLDP neighbors
+func (rd *RouterDiscovery) DiscoverFromLLDP(neighbors []LLDPNeighbor) error {
+    for _, n := range neighbors {
+        // Si el neighbor es un switch/router conocido, añadirlo
+        if isNetworkDevice(n.SysDescr) {
+            if err := rd.upsertRouter(n.SysName, n.ChassisID, RoleSwitch); err != nil {
+                return err
+            }
+        }
+    }
+    return nil
+}
+
+// DiscoverFromFDB encuentra switches analizando patrones de FDB
+func (rd *RouterDiscovery) DiscoverFromFDB(entries []FDBEntry) error {
+    // Si un dispositivo tiene múltiples MACs en su FDB, probablemente es un switch
+    macCount := make(map[string]int)
+    for _, e := range entries {
+        macCount[e.Port]++
+    }
+
+    for port, count := range macCount {
+        if count > 10 { // Umbral arbitrario
+            // Investigar si este port pertenece a un switch
+            fmt.Printf("Port %s has %d MACs, possible trunk
+", port, count)
+        }
+    }
+    return nil
+}
+
+type RouterRole string
+
+const (
+    RoleGateway RouterRole = "GW"
+    RoleAP      RouterRole = "AP"
+    RoleSwitch  RouterRole = "SW"
+)
+
+func (rd *RouterDiscovery) upsertRouter(name, mac string, role RouterRole) error {
+    _, err := rd.db.Exec(`
+        INSERT INTO routers (name, mac, role_badge, discovered_at)
+        VALUES (?, ?, ?, datetime('now'))
+        ON CONFLICT(mac) DO UPDATE SET
+            name = excluded.name,
+            role_badge = excluded.role_badge,
+            last_seen = datetime('now')
+    `, name, mac, string(role))
+    return err
+}
+
+func isNetworkDevice(sysDescr string) bool {
+    // Heurística simple
+    keywords := []string{"switch", "router", "bridge", "openwrt", "linux"}
+    lower := strings.ToLower(sysDescr)
+    for _, kw := range keywords {
+        if strings.Contains(lower, kw) {
+            return true
+        }
+    }
+    return false
+}
+```
+
+---
+
+## 5. Fuentes y Referencias
+
+### Artículos y documentación
+
+| Recurso | URL | Relevancia |
+|---------|-----|------------|
+| NetXMS Topology Discovery | `https://www.netxms.org/topology-discovery/` | Patrón de reconciliación FDB + LLDP |
+| WhatsUp Gold Layer 2/3 Discovery | `https://docs.ipswitch.com/NM/WhatsUpGold/2021/01_Guide/WhatsUpGoldLayer2_3Discovery.htm` | SNMP + ARP para topología |
+| Go netlink package docs | `https://pkg.go.dev/github.com/vishvananda/netlink` | API para FDB, ARP, interfaces |
+| SQLite WAL mode | `https://www.sqlite.org/wal.html` | Documentación oficial WAL |
+| Go SQLite best practices | `https://turso.tech/blog/the-definitive-guide-to-sqlite-on-golang` | Concurrency, pragmas, WAL |
+
+### Librerías Go
+
+| Librería | URL | Uso |
+|----------|-----|-----|
+| `goubus` | `github.com/honeybbq/goubus` | Cliente ubus type-safe para OpenWrt |
+| `go-ubus-rpc` | `github.com/daimonaslabs/go-ubus-rpc` | Cliente ubus con CLI |
+| `netlink` | `github.com/vishvananda/netlink` | FDB, ARP, interfaces vía netlink |
+| `gotopo/lldp` | `github.com/ksang/gotopo/lldp` | Estructuras LLDP en Go |
+| `lldp2map` | `github.com/buraglio/lldp2map` | Walk recursivo LLDP + diagramas |
+| `gosnmp` | `github.com/gosnmp/gosnmp` | Cliente SNMP v1/v2c/v3 |
+| `modernc.org/sqlite` | `modernc.org/sqlite` | SQLite sin CGO |
+
+### Comandos útiles para debugging
+
+```bash
+# Ver FDB en OpenWrt
+bridge fdb show
+
+# Ver ARP table
+ip neigh show
+
+# Ver LLDP neighbors
+lldpcli show neighbors
+
+# Ver WiFi associations (OpenWrt)
+iwinfo wlan0 assoclist
+ubus call hostapd.wlan0 get_clients
+
+# Ver bridge details
+brctl show
+bridge link show
+```
+
+---
+
+*Documento generado para el proyecto NetPulse — https://github.com/gnacho/netpulse*

+ 45 - 2
server-go/internal/adapters/live.go

@@ -58,6 +58,29 @@ func pickGateway(routers []RouterConfig) *RouterConfig {
 	return nil
 }
 
+// pickGatewayCfg: same logic as pickGateway but from polled router configs.
+func pickGatewayCfg(polled map[string]*routerPolled) *RouterConfig {
+	ids := make([]string, 0, len(polled))
+	for id := range polled {
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	for _, id := range ids {
+		if polled[id].cfg.IsGateway {
+			return &polled[id].cfg
+		}
+	}
+	for _, id := range ids {
+		if polled[id].cfg.Type == "glinet" {
+			return &polled[id].cfg
+		}
+	}
+	if len(ids) > 0 {
+		return &polled[ids[0]].cfg
+	}
+	return nil
+}
+
 // routerPolled es el sondeo de un tick de un router.
 type routerPolled struct {
 	cfg       RouterConfig
@@ -1063,13 +1086,33 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	if gw != nil {
 		gwID = gw.ID
 	}
-	// (2) FDB de satélites: pista solo de ESTE tick (no se guarda)
+	// (2) FDB de satélites: pista solo de ESTE tick (no se guarda).
+	// REGLA DE RECONCILIACIÓN: si una MAC cableada aparece tanto en el FDB
+	// del gateway como en el FDB de un satélite, el satélite la ve porque
+	// está bridged al mismo segmento L2 — NO es un cliente directo del
+	// satélite. Solo cuentan como clientes del satélite las MACs que el
+	// gateway NO ve (dispositivos realmente tras ese satélite, sin bridge
+	// al gateway).
+	// EXCEPCIÓN: los routers agent-only (switches con agente propio) son la
+	// fuente más específica — sus dispositivos se conservan con RouterID
+	// del switch, aunque el gateway también los vea en su FDB.
+	gwFDB := map[string]bool{}
+	if gwID != "" {
+		if gwPolled := polled[gwID]; gwPolled != nil {
+			for mac := range gwPolled.fdb {
+				gwFDB[mac] = true
+			}
+		}
+	}
 	for routerID, p := range polled {
 		if routerID == gwID {
 			continue
 		}
 		for mac := range p.fdb {
 			if _, ok := seen[mac]; !ok {
+				if gwFDB[mac] && !p.cfg.AgentOnly {
+					continue // gateway bridge pasivo, no es cliente del satélite
+				}
 				seen[mac] = seenInfo{routerID, "cable", nil}
 			}
 		}
@@ -1286,7 +1329,6 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		routerList = append(routerList, router)
 	}
 	devices := l.buildDevices(polled)
-	// Topología v5: puertos FDB + switches/hipervisores inferidos
 	devices, distNodes := inferTopology(polled, devices)
 	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
 	for _, d := range devices {
@@ -1371,6 +1413,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
 		DistributionNodes: distNodes,
 		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes), // SPEC-65 D65-3
+		Devices:           devices,
 		Dawn:              &DawnOverview{Available: l.dawnAvailableCached()},
 		VM:                ViewModelVersion,                                            // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),

+ 9 - 11
server-go/internal/adapters/topo_semantics.go

@@ -38,8 +38,10 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 		return sem
 	}
 
-	// Gateway y APs como model.ts: roleBadge "Principal" → gateway (si no,
-	// el primero); el resto (máx 3 = coordenadas canónicas de AP) son APs.
+	// Gateway y APs/switches como model.ts: roleBadge "Principal" → gateway
+	// (si no, el primero); el resto son routers (APs y switches gestionados).
+	// Sin límite de 3 APs — el frontend decide cuántos dibujar con coordenadas
+	// canónicas y cuáles como "extra" (switches, APs adicionales).
 	gateway := routers[0]
 	for _, r := range routers {
 		if r.RoleBadge == "Principal" {
@@ -47,17 +49,13 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 			break
 		}
 	}
-	aps := make([]Router, 0, 3)
+	nonGateway := make([]Router, 0, len(routers)-1)
 	for _, r := range routers {
-		if r.ID == gateway.ID {
-			continue
-		}
-		if len(aps) >= 3 {
-			break
+		if r.ID != gateway.ID {
+			nonGateway = append(nonGateway, r)
 		}
-		aps = append(aps, r)
 	}
-	routerNodes := append([]Router{gateway}, aps...)
+	routerNodes := append([]Router{gateway}, nonGateway...)
 	inRouter := map[string]bool{}
 	for _, r := range routerNodes {
 		inRouter[r.ID] = true
@@ -135,7 +133,7 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 
 	// -- enlaces (mismo orden que model.ts) --------------------------------
 	sem.Links = append(sem.Links, TopoLink{From: "internet", To: gateway.ID, Kind: "wan"})
-	for _, ap := range aps {
+	for _, ap := range nonGateway {
 		l := TopoLink{From: gateway.ID, To: ap.ID, Kind: "uplink"}
 		if ap.Lldp != nil {
 			l.Port = ap.Lldp.PortDesc // puerto del uplink en el gateway (C2)

+ 32 - 21
server-go/internal/adapters/topology.go

@@ -44,6 +44,7 @@ var hypervisorOUI = []string{
 	"00:0C:29", // VMware
 	"00:15:5D", // Hyper-V
 	"52:54:00", // KVM/QEMU
+	"08:00:27", // VirtualBox
 }
 
 func isHypervisorMAC(mac string) bool {
@@ -81,22 +82,8 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 	// Gateway con la misma prioridad que pickGateway (is_gateway → glinet →
 	// primero): solo él puede anclar nodos "inferred".
 	gatewayID := ""
-	for _, id := range routerIDs {
-		if polled[id].cfg.IsGateway {
-			gatewayID = id
-			break
-		}
-	}
-	if gatewayID == "" {
-		for _, id := range routerIDs {
-			if polled[id].cfg.Type == "glinet" {
-				gatewayID = id
-				break
-			}
-		}
-	}
-	if gatewayID == "" && len(routerIDs) > 0 {
-		gatewayID = routerIDs[0]
+	if gw := pickGatewayCfg(polled); gw != nil {
+		gatewayID = gw.ID
 	}
 
 	for _, routerID := range routerIDs {
@@ -119,15 +106,15 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 			var kept []string
 			for _, mac := range byPort[port] {
 				if routerMACs[mac] {
-					continue // el propio router/AP no es un cliente
+					continue
 				}
 				if idx, ok := byMAC[mac]; ok {
 					d := devices[idx]
 					if d.RouterID != routerID {
-						continue // cliente de otro router (visto por el uplink)
+						continue
 					}
 					if d.Band != "cable" && d.Band != "—" {
-						continue // wifi no cuelga de un puerto físico
+						continue
 					}
 				}
 				kept = append(kept, mac)
@@ -219,9 +206,33 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 			// Gateway, OUI heterogéneo (o hipervisor ambiguo sin host claro):
 			// algo multiplexa ese puerto → nodo inferido colgando del gateway.
 			setPort()
-			dists = append(dists, DistributionNode{
+			dn := DistributionNode{
 				ID: id, Kind: "inferred", RouterID: routerID, Port: port, MacCount: len(kept),
-			})
+			}
+			if routerID == gatewayID {
+				for _, rp := range polled {
+					if !rp.cfg.AgentOnly {
+						continue
+					}
+					swMacs := map[string]bool{}
+					for mac := range rp.fdb {
+						swMacs[mac] = true
+					}
+					allKnown := true
+					for _, mac := range kept {
+						if !swMacs[mac] {
+							allKnown = false
+							break
+						}
+					}
+					if allKnown && len(kept) > 0 {
+						dn.Name = rp.cfg.Name
+						dn.Ip = rp.cfg.Host
+						break
+					}
+				}
+			}
+			dists = append(dists, dn)
 			for _, mac := range kept {
 				if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
 					devices[idx].AttachTo = id

+ 5 - 0
server-go/internal/adapters/types.go

@@ -273,6 +273,11 @@ type Overview struct {
 	// Topology: semántica de topología precalculada (SPEC-65 D65-3). Puntero:
 	// ausente en snapshots viejos → la app usa su cálculo actual como fallback.
 	Topology *TopoSemantics `json:"topology,omitempty"`
+	// Devices: lista completa de dispositivos (misma snapshot que topology.rings).
+	// Omitido en snapshots viejos → el frontend sigue usando /api/devices.
+	// Cuando está presente, el frontend lo usa en vez de fetch independiente
+	// para garantizar consistencia con los anillos de topología.
+	Devices []Device `json:"devices,omitempty"`
 	// Dawn: disponibilidad de DAWN (roaming/band-steering) para decidir si la
 	// app muestra la entrada /roaming. Puntero: ausente en snapshots viejos y
 	// cuando ningún router tiene DAWN → nil = no mostrar la página.