Просмотр исходного кода

merge: LLDP live + backhaul + nodos managed (Fase 5, C1/C2) desde fase5/lldp-live

agent 4 месяцев назад
Родитель
Сommit
df8ed51d40

+ 169 - 3
server-go/internal/adapters/adapters_test.go

@@ -52,7 +52,7 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 		t.Fatalf("peer0: %+v", p0)
 	}
 	// DeviceTotals
-	if ov.DeviceTotals != (DeviceTotals{Total: 67, Online: 59, KnownOffline: 8, NewToday: 3}) {
+	if ov.DeviceTotals != (DeviceTotals{Total: 66, Online: 58, KnownOffline: 8, NewToday: 3}) {
 		t.Fatalf("deviceTotals: %+v", ov.DeviceTotals)
 	}
 	// Health
@@ -69,10 +69,10 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	}
 }
 
-func TestDemoDevices67YTop(t *testing.T) {
+func TestDemoDevices66YTop(t *testing.T) {
 	d := NewDemo()
 	devs := d.GetDevices(context.Background())
-	if len(devs) != 67 {
+	if len(devs) != 66 {
 		t.Fatalf("devices: %d", len(devs))
 	}
 	offline := 0
@@ -393,3 +393,169 @@ func TestSparkDeterminista(t *testing.T) {
 		}
 	}
 }
+
+// --- Backhaul (C1-server): sonda ubus network.wireless status + canon demo ---
+
+// Fixture ubus network.wireless status: radio0 con AP + STA asociada
+// (uplink inalámbrico, p.ej. el EAP225 del patio).
+const wirelessStatusSta = `{
+  "radio0": {
+    "up": true,
+    "interfaces": [
+      {"section": "default_radio0", "ifname": "phy0-ap0",
+       "config": {"mode": "ap", "ssid": "Casa-Patio", "network": ["lan"]}},
+      {"section": "wifinet1", "ifname": "phy0-sta0",
+       "config": {"mode": "sta", "ssid": "Casa", "network": ["wwan"]}}
+    ]
+  }
+}`
+
+const wirelessStatusSoloAp = `{
+  "radio0": {
+    "up": true,
+    "interfaces": [
+      {"section": "default_radio0", "ifname": "phy0-ap0",
+       "config": {"mode": "ap", "ssid": "Casa", "network": ["lan"]}}
+    ]
+  }
+}`
+
+func TestParseWirelessUplink(t *testing.T) {
+	// STA asociada (radio up + ifname) → uplink inalámbrico
+	wifi, err := parseWirelessUplink([]byte(wirelessStatusSta))
+	if err != nil || !wifi {
+		t.Fatalf("sta asociada: %v %v", wifi, err)
+	}
+	// Solo APs → cable
+	wifi, err = parseWirelessUplink([]byte(wirelessStatusSoloAp))
+	if err != nil || wifi {
+		t.Fatalf("solo ap: %v %v", wifi, err)
+	}
+	// STA configurada pero NO activa (radio caída o sin asociar) → cable
+	for _, in := range []string{
+		`{"radio0":{"up":false,"interfaces":[{"ifname":"phy0-sta0","config":{"mode":"sta"}}]}}`,
+		`{"radio0":{"up":true,"interfaces":[{"ifname":"","config":{"mode":"sta"}}]}}`,
+		`{}`,
+	} {
+		wifi, err = parseWirelessUplink([]byte(in))
+		if err != nil || wifi {
+			t.Fatalf("%s → %v %v", in, wifi, err)
+		}
+	}
+	// Respuesta no JSON → error (el live omite el campo, no rompe)
+	if _, err = parseWirelessUplink([]byte("Command failed")); err == nil {
+		t.Fatal("no JSON debería dar error")
+	}
+}
+
+// Canon demo del backhaul: Patio "wifi" (único AP inalámbrico), resto "cable".
+func TestDemoBackhaulCanon(t *testing.T) {
+	d := NewDemo()
+	want := map[string]string{"flint2": "cable", "living": "cable", "estudio": "cable", "patio": "wifi"}
+	seen := 0
+	for _, r := range d.GetRouters(context.Background()) {
+		if r.Backhaul != want[r.ID] {
+			t.Fatalf("backhaul %s: %q (esperaba %q)", r.ID, r.Backhaul, want[r.ID])
+		}
+		seen++
+	}
+	if seen != 4 {
+		t.Fatalf("routers: %d", seen)
+	}
+	// El overview lleva el mismo dato (routersCopy preserva el campo)
+	ov, err := d.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, r := range ov.Routers {
+		if r.Backhaul != want[r.ID] {
+			t.Fatalf("overview backhaul %s: %q", r.ID, r.Backhaul)
+		}
+	}
+}
+
+// Canon demo del nodo "managed" (Fase 5): el GS308E del Salón es un
+// DistributionNode identificado por LLDP (NO un Device), con sus 3 clientes
+// en abanico. El fantasma inferido del gateway se mantiene (las dos
+// historias: inferido vs identificado).
+func TestDemoNodoManagedCanon(t *testing.T) {
+	d := NewDemo()
+	ov, err := d.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	var managed, inferred *DistributionNode
+	for i := range ov.DistributionNodes {
+		switch ov.DistributionNodes[i].ID {
+		case "dist-living-lan3":
+			managed = &ov.DistributionNodes[i]
+		case "dist-flint2-lan3":
+			inferred = &ov.DistributionNodes[i]
+		}
+	}
+	if inferred == nil || inferred.Kind != "inferred" {
+		t.Fatalf("el fantasma del gateway se mantiene: %+v", inferred)
+	}
+	if managed == nil {
+		t.Fatalf("falta el nodo managed: %+v", ov.DistributionNodes)
+	}
+	if managed.Kind != "managed" || managed.RouterID != "living" || managed.Port != "lan3" || managed.MacCount != 4 {
+		t.Fatalf("nodo managed: %+v", managed)
+	}
+	if managed.Name != "GS308E" || managed.Ip != "192.168.8.13" {
+		t.Fatalf("name/ip: %+v", managed)
+	}
+	if managed.Lldp == nil || managed.Lldp.Chassis != "GS308E" || managed.Lldp.Mgmt != "192.168.8.13" ||
+		managed.Lldp.Caps != "Bridge" || managed.Lldp.PortDesc != "ge5" {
+		t.Fatalf("lldp del nodo: %+v", managed.Lldp)
+	}
+	// El GS308E ya no es un Device; sus 3 clientes cuelgan del nodo
+	fan := 0
+	for _, dev := range d.GetDevices(context.Background()) {
+		if dev.ID == "switch-netgear" {
+			t.Fatal("switch-netgear no debe existir como Device (es el nodo managed)")
+		}
+		if dev.AttachTo == "dist-living-lan3" {
+			fan++
+			if dev.RouterID != "living" {
+				t.Fatalf("cliente del managed con routerId raro: %+v", dev)
+			}
+		}
+	}
+	if fan != 3 {
+		t.Fatalf("abanico del managed: %d (esperaba 3)", fan)
+	}
+}
+
+// Canon demo de Router.Lldp (Fase 5, ítem 4 de C2): los AP cableados
+// (living, estudio) tienen su uplink al gateway identificado por LLDP;
+// patio (uplink wifi) y el propio gateway NO llevan el campo.
+func TestDemoRouterLldpCanon(t *testing.T) {
+	d := NewDemo()
+	want := map[string]*LldpInfo{
+		"living":  {Chassis: "Flint 2", Mgmt: "192.168.8.1", Caps: "Bridge, Router", PortDesc: "lan1"},
+		"estudio": {Chassis: "Flint 2", Mgmt: "192.168.8.1", Caps: "Bridge, Router", PortDesc: "lan2"},
+		"patio":   nil, // uplink wifi: sin LLDP
+		"flint2":  nil, // gateway: su uplink es WAN
+	}
+	seen := 0
+	for _, r := range d.GetRouters(context.Background()) {
+		w, ok := want[r.ID]
+		if !ok {
+			t.Fatalf("router inesperado: %s", r.ID)
+		}
+		if w == nil {
+			if r.Lldp != nil {
+				t.Fatalf("%s no debería llevar lldp: %+v", r.ID, r.Lldp)
+			}
+		} else {
+			if r.Lldp == nil || *r.Lldp != *w {
+				t.Fatalf("%s lldp: %+v (esperaba %+v)", r.ID, r.Lldp, w)
+			}
+		}
+		seen++
+	}
+	if seen != 4 {
+		t.Fatalf("routers: %d", seen)
+	}
+}

+ 2 - 2
server-go/internal/adapters/demo.go

@@ -178,7 +178,7 @@ func (d *Demo) buildOverview() *Overview {
 		Adguard:      d.adguard,
 		Wireguard:    d.wireguardSnapshot(),
 		Routers:      d.routersCopy(),
-		DeviceTotals: DeviceTotals{Total: 67, Online: 59, KnownOffline: 8, NewToday: 3},
+		DeviceTotals: DeviceTotals{Total: 66, Online: 58, KnownOffline: 8, NewToday: 3},
 		TopDevices:   d.topDevices(5),
 		Alerts:       d.alertsCopy(),
 		UnreadAlerts: unread,
@@ -292,7 +292,7 @@ func (d *Demo) GetRouterDetail(_ context.Context, id string) (*RouterDetail, err
 	return detail, nil
 }
 
-// GetDevices devuelve copia de los 47 dispositivos.
+// GetDevices devuelve copia de los 66 dispositivos.
 func (d *Demo) GetDevices(context.Context) []Device {
 	d.mu.Lock()
 	defer d.mu.Unlock()

+ 34 - 18
server-go/internal/adapters/demo_dataset.go

@@ -1,7 +1,7 @@
 // demo_dataset.go — Dataset demo canónico COMPLETO (port literal de
 // server/src/demo/dataset.js, SPEC §7.1): 4 routers, WAN, trafficByRange,
-// health score, AdGuard, WireGuard, alertas, los 47 dispositivos (10
-// canónicos + 37 adicionales, sparklines deterministas con el mismo LCG),
+// health score, AdGuard, WireGuard, alertas, los 66 dispositivos (canon +
+// adicionales + fixtures topología v5, sparklines deterministas con el LCG),
 // routerExtras, perfSeries, WAN_LATENCY_24H, adguardSeries24h, wgPeerExtras
 // y WG_TOTALS_30D. Cada llamada a los builders devuelve estructuras NUEVAS
 // (el adapter muta su copia con el random walk; el canon no se toca).
@@ -23,18 +23,27 @@ func canonRouters() []Router {
 		{ID: "flint2", Name: "Gateway", Model: "GL.iNet Flint 2 (GL-MT6000)", ModelShort: "GL.iNet Flint 2",
 			Role: "Gateway principal", RoleBadge: "Principal", IP: "192.168.8.1", Status: "online",
 			Health: 98, CPU: iptr(23), RAM: iptr(41), Temp: iptr(54), Uptime: "32d 14h", Clients: 33,
+			Backhaul:  "cable",
 			Sparkline: []float64{8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40}},
 		{ID: "living", Name: "Salón", Model: "OpenWrt AP (Xiaomi AX3000T)", ModelShort: "Xiaomi AX3000T",
 			Role: "Punto de acceso", RoleBadge: "AP", IP: "192.168.8.2", Status: "online",
 			Health: 95, CPU: iptr(12), RAM: iptr(38), Temp: iptr(47), Uptime: "32d 14h", Clients: 22,
+			Backhaul: "cable",
+			// Uplink cableado al gateway identificado por LLDP (sufijo "· LLDP")
+			Lldp:      &LldpInfo{Chassis: "Flint 2", Mgmt: "192.168.8.1", Caps: "Bridge, Router", PortDesc: "lan1"},
 			Sparkline: []float64{4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28}},
 		{ID: "estudio", Name: "Estudio", Model: "OpenWrt (NanoPi R4S)", ModelShort: "NanoPi R4S",
 			Role: "AP + switch", RoleBadge: "AP", IP: "192.168.8.3", Status: "online",
 			Health: 92, CPU: iptr(18), RAM: iptr(44), Temp: iptr(51), Uptime: "11d 3h", Clients: 9,
+			Backhaul: "cable",
+			// Uplink cableado al gateway identificado por LLDP (sufijo "· LLDP")
+			Lldp:      &LldpInfo{Chassis: "Flint 2", Mgmt: "192.168.8.1", Caps: "Bridge, Router", PortDesc: "lan2"},
 			Sparkline: []float64{2, 2, 1, 1, 2, 4, 8, 15, 22, 25, 24, 22, 26, 24, 21, 24, 28, 31, 29, 24, 18, 12, 8, 4}},
+		// Patio: único AP con uplink inalámbrico del dataset (backhaul "wifi").
 		{ID: "patio", Name: "Patio", Model: "OpenWrt (TP-Link EAP225)", ModelShort: "TP-Link EAP225",
 			Role: "AP exterior", RoleBadge: "AP", IP: "192.168.8.4", Status: "warn",
 			Health: 68, CPU: iptr(31), RAM: iptr(57), Temp: iptr(71), Uptime: "4d 2h", Clients: 6, HotMetric: "temp",
+			Backhaul:  "wifi",
 			Sparkline: []float64{1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2}},
 	}
 }
@@ -269,12 +278,10 @@ func additionalDevices() []Device {
 			IP: "192.168.8.12", MAC: "DC:A6:32:4F:77:02", RouterID: "flint2", Band: "cable",
 			SignalDbm: nil, TrafficMbps: 0.8, Online: true, AttachTo: "dist-flint2-lan3"}, 14, 0),
 			"raspberrypi", "IP fija (reserva)", "hace 320 días", "3,4 GB", "890 MB", true, "red", ""),
-		// Switch gestionado identificado por LLDP (topología v5: type switch + Salón lan3)
-		withDetails(devExtra(Device{ID: "switch-netgear", Name: "Switch Netgear", Type: "switch", Manufacturer: "Netgear GS308E",
-			IP: "192.168.8.13", MAC: "28:C6:8E:1D:90:44", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 0.02, Online: true, Port: "lan3",
-			Lldp: &LldpInfo{Chassis: "GS308E", Mgmt: "192.168.8.13", Caps: "Bridge", PortDesc: "ge5"}}, 15, 0.04),
-			"gs308e", "IP fija (reserva)", "hace 300 días", "64 MB", "12 MB", false, "red", "Network"),
+		// NOTA (Fase 5): el switch gestionado GS308E (Salón lan3) ya NO es un
+		// Device: se representa como DistributionNode "managed" (ver
+		// canonDistributionNodes), con xbox/apple-tv/denon en abanico — la
+		// historia del mockup "identificado por LLDP" sin duplicar el chip.
 		withDetails(devExtra(Device{ID: "timbre-nest", Name: "Timbre Nest", Type: "camara", Manufacturer: "Google",
 			IP: "192.168.8.72", MAC: "F4:F5:D8:66:01:B8", RouterID: "flint2", Band: "2.4 GHz",
 			SignalDbm: iptr(-58), TrafficMbps: 0.6, Online: true}, 16, 0),
@@ -407,9 +414,10 @@ func withDetails(d Device, hostname, lease, firstSeen, rx, tx string, adguard bo
 	return d
 }
 
-// canonAllDevices: los 67 clientes (canon expandido + adicionales + fixtures
-// de topología v5: switch gestionado LLDP, hipervisor con CTs, switch
-// inferido FDB — espejo del mock front app/src/data/mock.ts).
+// canonAllDevices: los 66 clientes (canon expandido + adicionales + fixtures
+// de topología v5: hipervisor con CTs, clientes tras switch inferido FDB y
+// tras el switch gestionado — espejo del mock front app/src/data/mock.ts).
+// Fase 5: el GS308E deja de ser Device (es el DistributionNode managed).
 func canonAllDevices() []Device {
 	out := canonDevices()
 	out = append(out, additionalDevices()...)
@@ -418,24 +426,26 @@ func canonAllDevices() []Device {
 }
 
 // topologyDevices: fixtures NUEVAS de topología v5 (mockup aprobado
-// 2-Ago-2026). Los 3 clientes preexistentes (switch-netgear, pc-sobremesa,
-// raspberry-pi) se enriquecen in situ en additionalDevices — no se duplican.
+// 2-Ago-2026). Los clientes preexistentes (pc-sobremesa, raspberry-pi) se
+// enriquecen in situ en additionalDevices — no se duplican. El GS308E NO
+// existe como Device: es el DistributionNode "managed" (Fase 5).
 func topologyDevices() []Device {
 	out := []Device{
-		// 3 clientes detrás del switch gestionado (Salón)
+		// 3 clientes detrás del switch gestionado identificado por LLDP
+		// (nodo managed dist-living-lan3, Salón)
 		withDetails(Device{ID: "xbox-series-s", Name: "Xbox Series S", Type: "consola", Manufacturer: "Microsoft",
 			IP: "192.168.8.35", MAC: "7C:ED:8D:4A:11:22", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 9.8, Online: true, AttachTo: "switch-netgear",
+			SignalDbm: nil, TrafficMbps: 9.8, Online: true, AttachTo: "dist-living-lan3",
 			Sparkline: []float64{3, 5, 7, 9, 11, 12, 10, 9, 10, 9, 10, 9.8}},
 			"xbox-series-s", "renueva en 4 h 12 min", "hace 140 días", "31 GB", "1,9 GB", true, "tv", ""),
 		withDetails(Device{ID: "apple-tv-4k", Name: "Apple TV 4K", Type: "tv", Manufacturer: "Apple",
 			IP: "192.168.8.36", MAC: "F0:18:98:2B:33:44", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 15.2, Online: true, AttachTo: "switch-netgear",
+			SignalDbm: nil, TrafficMbps: 15.2, Online: true, AttachTo: "dist-living-lan3",
 			Sparkline: []float64{6, 8, 10, 12, 14, 16, 15, 14, 15, 15, 15, 15.2}},
 			"apple-tv-4k", "renueva en 6 h 3 min", "hace 210 días", "88 GB", "3,4 GB", true, "tv", ""),
 		withDetails(Device{ID: "receptor-denon", Name: "Receptor Denon", Type: "altavoz", Manufacturer: "Denon",
 			IP: "192.168.8.37", MAC: "00:05:CD:55:66:77", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 0.6, Online: true, AttachTo: "switch-netgear",
+			SignalDbm: nil, TrafficMbps: 0.6, Online: true, AttachTo: "dist-living-lan3",
 			Sparkline: []float64{0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6}},
 			"denon-avr", "IP fija (reserva)", "hace 320 días", "640 MB", "42 MB", true, "iot", ""),
 		// Hipervisor Proxmox (gateway lan2); sus 10 CTs se anidan (OUI BC:24:11)
@@ -512,11 +522,17 @@ func topologyDevices() []Device {
 	return out
 }
 
-// canonDistributionNodes: distnodes demo (en live los infiere el colector FDB).
+// canonDistributionNodes: distnodes demo (en live los infiere el colector
+// FDB/LLDP). Las DOS historias de switch: fantasma inferido (gateway lan3)
+// vs gestionado identificado por LLDP (Salón lan3, el GS308E del mockup con
+// sus 3 clientes en abanico; Fase 5: ya no existe como Device suelto).
 func canonDistributionNodes() []DistributionNode {
 	return []DistributionNode{
 		{ID: "dist-flint2-lan3", Kind: "inferred", RouterID: "flint2", Port: "lan3", MacCount: 8},
 		{ID: "dist-pve", Kind: "hypervisor", RouterID: "flint2", Port: "lan2", MacCount: 11, HostDeviceID: "pve", Name: "Proxmox pve"},
+		{ID: "dist-living-lan3", Kind: "managed", RouterID: "living", Port: "lan3", MacCount: 4,
+			Name: "GS308E", Ip: "192.168.8.13",
+			Lldp: &LldpInfo{Chassis: "GS308E", Mgmt: "192.168.8.13", Caps: "Bridge", PortDesc: "ge5"}},
 	}
 }
 

+ 170 - 26
server-go/internal/adapters/live.go

@@ -9,6 +9,7 @@ import (
 	"context"
 	"database/sql"
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log"
 	"math"
@@ -73,6 +74,10 @@ type routerPolled struct {
 	brMac     string
 	latencyMs *float64
 	lossPct   *float64
+	// backhaul: "cable"|"wifi"|"" (desconocido → se omite en el contrato).
+	backhaul string
+	// lldp: vecinos LLDP del tier lento (nil = sin lldpd o sonda fallida).
+	lldp []LldpNeighbor
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -83,6 +88,25 @@ type extrasSnapshot struct {
 	fdb      map[string]string
 }
 
+// backhaulCacheTTL: el medio del uplink cambia muy raro; no se sondea cada 5 s.
+const backhaulCacheTTL = 5 * time.Minute
+
+// backhaulCacheEntry: resultado cacheado de la detección de uplink wifi
+// (value "" = desconocido/sonda fallida → el campo se omite).
+type backhaulCacheEntry struct {
+	value string
+	at    time.Time
+}
+
+// lldpCacheTTL: tier lento LLDP (45 s, como los extras cacheados).
+const lldpCacheTTL = 45 * time.Second
+
+// lldpCacheEntry: vecinos LLDP cacheados por router (nil = sin datos).
+type lldpCacheEntry struct {
+	neighbors []LldpNeighbor
+	at        time.Time
+}
+
 // Live es el Snapshotter del modo live.
 type Live struct {
 	cfg  *config.Config
@@ -94,16 +118,18 @@ type Live struct {
 	gatewayCfg *RouterConfig
 	clients    map[string]*OpenWrtClient
 
-	lastGood    map[string]*Router
-	lastStatus  map[string]string
-	boardCache  map[string]*BoardInfo
-	layoutCache map[string][]PortLayout
-	extrasCache map[string]*extrasSnapshot
-	lastPolled  map[string]*routerPolled
-	failCount   map[string]int
-	alerts      []AlertEvent
-	wgActive    map[string]bool
-	weakAlerted map[string]int64
+	lastGood      map[string]*Router
+	lastStatus    map[string]string
+	boardCache    map[string]*BoardInfo
+	layoutCache   map[string][]PortLayout
+	extrasCache   map[string]*extrasSnapshot
+	lastPolled    map[string]*routerPolled
+	failCount     map[string]int
+	alerts        []AlertEvent
+	wgActive      map[string]bool
+	weakAlerted   map[string]int64
+	backhaulCache map[string]backhaulCacheEntry
+	lldpCache     map[string]lldpCacheEntry
 
 	agStd *AdGuardClient
 	agGL  *AdGuardGlinetClient
@@ -121,18 +147,20 @@ type sfResult struct {
 // NewLive crea el adapter live (db puede ser nil en tests).
 func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool) *Live {
 	l := &Live{
-		cfg:         cfg,
-		db:          d,
-		pool:        pool,
-		lastGood:    map[string]*Router{},
-		lastStatus:  map[string]string{},
-		boardCache:  map[string]*BoardInfo{},
-		layoutCache: map[string][]PortLayout{},
-		extrasCache: map[string]*extrasSnapshot{},
-		lastPolled:  map[string]*routerPolled{},
-		failCount:   map[string]int{},
-		wgActive:    map[string]bool{},
-		weakAlerted: map[string]int64{},
+		cfg:           cfg,
+		db:            d,
+		pool:          pool,
+		lastGood:      map[string]*Router{},
+		lastStatus:    map[string]string{},
+		boardCache:    map[string]*BoardInfo{},
+		layoutCache:   map[string][]PortLayout{},
+		extrasCache:   map[string]*extrasSnapshot{},
+		lastPolled:    map[string]*routerPolled{},
+		failCount:     map[string]int{},
+		wgActive:      map[string]bool{},
+		weakAlerted:   map[string]int64{},
+		backhaulCache: map[string]backhaulCacheEntry{},
+		lldpCache:     map[string]lldpCacheEntry{},
 	}
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
@@ -208,6 +236,63 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.failCount, id)
 		}
 	}
+	for id := range l.backhaulCache {
+		if !ids[id] {
+			delete(l.backhaulCache, id)
+		}
+	}
+	for id := range l.lldpCache {
+		if !ids[id] {
+			delete(l.lldpCache, id)
+		}
+	}
+}
+
+// probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";
+// si no → "cable") con caché de 5 min: no se sondea cada tick. Error (router
+// sin wifi, ubus caído) → "" cacheado igualmente (el campo se omite y el
+// sondeo no se rompe).
+func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
+	l.mu.Lock()
+	e, ok := l.backhaulCache[routerID]
+	l.mu.Unlock()
+	if ok && time.Since(e.at) < backhaulCacheTTL {
+		return e.value
+	}
+	value := ""
+	if wifi, err := client.GetWirelessUplink(); err == nil {
+		value = "cable"
+		if wifi {
+			value = "wifi"
+		}
+	}
+	l.mu.Lock()
+	l.backhaulCache[routerID] = backhaulCacheEntry{value: value, at: time.Now()}
+	l.mu.Unlock()
+	return value
+}
+
+// probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
+// extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
+// sigue mandando, comportamiento actual intacto).
+func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) []LldpNeighbor {
+	l.mu.Lock()
+	e, ok := l.lldpCache[routerID]
+	l.mu.Unlock()
+	if ok && time.Since(e.at) < lldpCacheTTL {
+		return e.neighbors
+	}
+	neighbors, err := client.LldpNeighbors(ctx)
+	if err != nil {
+		if !errors.Is(err, ErrLldpUnavailable) {
+			log.Printf("[netpulse] LLDP %s: %v", routerID, err)
+		}
+		neighbors = nil
+	}
+	l.mu.Lock()
+	l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, at: time.Now()}
+	l.mu.Unlock()
+	return neighbors
 }
 
 // getAdguardClient: kv (GL.iNet) con fallback a .env (AGH estándar).
@@ -320,7 +405,7 @@ func (l *Live) metricsHistory(routerID, rang string) []histPoint {
 }
 
 // pollRouter sondea un router; error si está inalcanzable.
-func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
+func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
 	l.mu.Lock()
 	client := l.clients[cfg.ID]
 	gw := l.gatewayCfg
@@ -363,6 +448,10 @@ func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
 	radios := client.GetRadios()
 	fdb := client.GetBridgeFdb()
 	brMac := client.GetBridgeMac()
+	// Tier lento: backhaul (5 min) y vecinos LLDP (45 s), ambos cacheados y
+	// tolerantes a error (router sin wifi/lldpd → campo ausente, sin romper).
+	backhaul := l.probeBackhaul(cfg.ID, client)
+	lldp := l.probeLldp(ctx, cfg.ID, client)
 	if !hasBoard {
 		if b, err := client.GetBoard(); err == nil {
 			board = b
@@ -431,6 +520,7 @@ func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
 		uptimeSec: sysInfo.Uptime, net: net, leases: leases,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
+		backhaul: backhaul, lldp: lldp,
 	}, nil
 }
 
@@ -494,6 +584,12 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.brMac != "" {
 		r.MAC = p.brMac
 	}
+	if p.backhaul != "" {
+		r.Backhaul = p.backhaul
+	}
+	if uplink := l.uplinkLldp(p); uplink != nil {
+		r.Lldp = uplink
+	}
 	if p.board != nil {
 		r.Firmware = p.board.Release.Description
 	}
@@ -503,6 +599,37 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	return r
 }
 
+// uplinkLldp: vecino LLDP del router que es OTRO router conocido (su
+// chassis-MAC es la bridge MAC de otro router de la config) → el uplink
+// está identificado por LLDP y la app muestra el sufijo "· LLDP". Si el FDB
+// dice dónde se aprendió esa MAC, el anuncio debe llegar por ese puerto
+// (uplink); sin FDB, la MAC ya es evidencia suficiente. nil si no hay dato.
+func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
+	if len(p.lldp) == 0 {
+		return nil
+	}
+	l.mu.Lock()
+	polled := l.lastPolled
+	l.mu.Unlock()
+	routerMacs := map[string]bool{}
+	for id, other := range polled {
+		if id != p.cfg.ID && other.brMac != "" {
+			routerMacs[other.brMac] = true
+		}
+	}
+	for i := range p.lldp {
+		nb := &p.lldp[i]
+		if nb.ChassisMac == "" || !routerMacs[nb.ChassisMac] {
+			continue
+		}
+		if port, ok := p.fdb[nb.ChassisMac]; ok && port != nb.Port {
+			continue
+		}
+		return nb.info()
+	}
+	return nil
+}
+
 // offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
 func (l *Live) offlineRouter(cfg RouterConfig) Router {
 	l.mu.Lock()
@@ -538,7 +665,7 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 }
 
 // pollAll sondea todos los routers en paralelo (Promise.allSettled).
-func (l *Live) pollAll() map[string]*routerPolled {
+func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	l.mu.Unlock()
@@ -554,7 +681,7 @@ func (l *Live) pollAll() map[string]*routerPolled {
 		wg.Add(1)
 		go func(i int, cfg RouterConfig) {
 			defer wg.Done()
-			p, err := l.pollRouter(cfg)
+			p, err := l.pollRouter(ctx, cfg)
 			results[i] = result{cfg, p, err}
 		}(i, cfg)
 	}
@@ -913,7 +1040,7 @@ func (l *Live) GetOverview(ctx context.Context) (*Overview, error) {
 }
 
 func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
-	polled := l.pollAll()
+	polled := l.pollAll(ctx)
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	gw := l.gatewayCfg
@@ -1161,6 +1288,11 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		if neighbor != "" {
 			port.ConnectedTo = routerByMac[neighbor]
 			port.Detail = "enlace entre routers"
+			// El vecino además se anuncia por LLDP → el frontend puede
+			// mostrar el sufijo "· LLDP" en la etiqueta del uplink (C2).
+			if nb := lldpNeighborOnPort(p.lldp, port.ID); nb != nil {
+				port.Detail = "enlace entre routers · LLDP"
+			}
 			enriched = append(enriched, port)
 			continue
 		}
@@ -1185,6 +1317,18 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		}
 		// 3) Varios: el vecino es un switch/hub
 		if len(all) > 1 {
+			// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
+			// es mejor pista que el hostname DHCP.
+			if nb := lldpNeighborOnPort(p.lldp, port.ID); nb != nil && nb.displayName() != "" {
+				port.ConnectedTo = nb.displayName()
+				if nb.Mgmt != "" {
+					port.Detail = nb.Mgmt + " · LLDP"
+				} else {
+					port.Detail = "LLDP"
+				}
+				enriched = append(enriched, port)
+				continue
+			}
 			infraMac := ""
 			for _, mac := range all {
 				if le, ok := leaseMap[mac]; ok && le.Hostname != "" {

+ 238 - 0
server-go/internal/adapters/lldp.go

@@ -0,0 +1,238 @@
+// lldp.go — Vecinos LLDP live (contrato C2, SPEC Fase 5): sonda SSH
+// `lldpcli -f json show neighbors` con timeout corto, error tipado
+// ErrLldpUnavailable cuando lldpd no está instalado (cacheado ≥5 min para no
+// martillear) y parseo defensivo del JSON (todos los campos opcionales; una
+// forma inesperada NUNCA debe romper el sondeo).
+package adapters
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"sort"
+	"strings"
+	"time"
+)
+
+// lldpTimeout: timeout corto de la sonda (≤5 s, contrato C2).
+const lldpTimeout = 5 * time.Second
+
+// lldpDownTTL: cuánto se cachea que lldpd NO está instalado (≥5 min, C2).
+const lldpDownTTL = 5 * time.Minute
+
+// ErrLldpUnavailable: lldpd no instalado en el router (lldpcli no existe:
+// exit 127 / "not found"). El caller lo trata como "sin datos LLDP", no como
+// fallo del router.
+var ErrLldpUnavailable = errors.New("lldpd no disponible")
+
+// LldpNeighbor es un vecino LLDP anunciado en un puerto local. Todos los
+// campos son opcionales en el anuncio; vacío = no anunciado.
+type LldpNeighbor struct {
+	Port       string   // puerto local que recibe el anuncio ("lan3"…)
+	ChassisMac string   // id del chasis tipo mac (mayúsculas)
+	Chassis    string   // nombre del chasis (o id si no hay nombre)
+	Mgmt       string   // primera mgmt-ip anunciada
+	Caps       []string // capacidades enabled ("Bridge", "Router", "Wlan"…)
+	PortDesc   string   // descripción del puerto remoto
+}
+
+// info construye el LldpInfo del contrato (Caps unidas, como la demo).
+func (n LldpNeighbor) info() *LldpInfo {
+	return &LldpInfo{
+		Chassis:  n.Chassis,
+		Mgmt:     n.Mgmt,
+		Caps:     strings.Join(n.Caps, ", "),
+		PortDesc: n.PortDesc,
+	}
+}
+
+// displayName: nombre del chasis o, en su defecto, su id (MAC).
+func (n LldpNeighbor) displayName() string {
+	if n.Chassis != "" {
+		return n.Chassis
+	}
+	return n.ChassisMac
+}
+
+// LldpNeighbors: vecinos LLDP del router (contrato C2). Si lldpcli no existe
+// devuelve ErrLldpUnavailable y cachea la indisponibilidad lldpDownTTL.
+func (c *OpenWrtClient) LldpNeighbors(ctx context.Context) ([]LldpNeighbor, error) {
+	if time.Now().Before(c.lldpDownUntil) {
+		return nil, ErrLldpUnavailable
+	}
+	out, err := c.pool.RunCtx(ctx, c.Host, "lldpcli -f json show neighbors", lldpTimeout)
+	if err != nil {
+		if isLldpUnavailable(err) {
+			c.lldpDownUntil = time.Now().Add(lldpDownTTL)
+			return nil, ErrLldpUnavailable
+		}
+		return nil, err
+	}
+	neighbors, perr := parseLldpNeighbors([]byte(out))
+	if perr != nil {
+		// Salida no JSON (p.ej. mensaje de error de lldpcli con exit 0):
+		// no es "no instalado", se reintenta en el próximo tick lento.
+		return nil, perr
+	}
+	return neighbors, nil
+}
+
+// isLldpUnavailable: el comando no existe en el router (exit 127 del shell,
+// "not found" en el mensaje…). Cualquier otro fallo (red, lldpd parado con
+// lldpcli instalado) NO es indisponibilidad cacheable.
+func isLldpUnavailable(err error) bool {
+	if err == nil {
+		return false
+	}
+	msg := err.Error()
+	return strings.Contains(msg, "status 127") || strings.Contains(msg, "not found")
+}
+
+// parseLldpNeighbors parsea `lldpcli -f json show neighbors`:
+//
+//	{"lldp":{"interface":[{"name","chassis":{<nombre>:{id{type,value},descr,
+//	  mgmt-ip,capability[]}},"port":{id{type,value},descr}}]}}
+//
+// Defensivo: campos ausentes o de tipo inesperado se ignoran (best-effort de
+// encoding/json rellena lo compatible); interface también se acepta como
+// mapa nombre→objeto (versiones viejas de lldpd). Error solo si la raíz no
+// es JSON válido.
+func parseLldpNeighbors(data []byte) ([]LldpNeighbor, error) {
+	var root struct {
+		Lldp struct {
+			Ifaces json.RawMessage `json:"interface"`
+		} `json:"lldp"`
+	}
+	if err := json.Unmarshal(data, &root); err != nil {
+		return nil, err
+	}
+	if len(root.Lldp.Ifaces) == 0 || string(root.Lldp.Ifaces) == "null" {
+		return []LldpNeighbor{}, nil
+	}
+	var entries []json.RawMessage
+	if err := json.Unmarshal(root.Lldp.Ifaces, &entries); err != nil {
+		// Forma mapa: {"lan3": {...}, "lan1": {...}} (lldpd viejo)
+		var byName map[string]json.RawMessage
+		if err2 := json.Unmarshal(root.Lldp.Ifaces, &byName); err2 != nil {
+			// Ni array ni mapa: forma desconocida → sin datos, no error
+			return []LldpNeighbor{}, nil
+		}
+		names := make([]string, 0, len(byName))
+		for name := range byName {
+			names = append(names, name)
+		}
+		sort.Strings(names)
+		neighbors := make([]LldpNeighbor, 0, len(names))
+		for _, name := range names {
+			// En la forma mapa el nombre de la interfaz es la CLAVE
+			neighbors = append(neighbors, parseLldpEntry(byName[name], name))
+		}
+		return neighbors, nil
+	}
+	neighbors := make([]LldpNeighbor, 0, len(entries))
+	for _, raw := range entries {
+		neighbors = append(neighbors, parseLldpEntry(raw, ""))
+	}
+	return neighbors, nil
+}
+
+// parseLldpEntry parsea una entrada de interface (nunca entra en pánico:
+// los Unmarshal secundarios ignoran el error a propósito — best-effort).
+// fallbackName es la clave de la forma mapa (lldpd viejo, sin campo "name").
+func parseLldpEntry(raw json.RawMessage, fallbackName string) LldpNeighbor {
+	var e struct {
+		Name    string                     `json:"name"`
+		Chassis map[string]json.RawMessage `json:"chassis"`
+		Port    json.RawMessage            `json:"port"`
+	}
+	// Best-effort: un campo de tipo inesperado (chassis como cadena, port
+	// como número…) no invalida el resto de la entrada.
+	_ = json.Unmarshal(raw, &e)
+	n := LldpNeighbor{Port: e.Name}
+	if n.Port == "" {
+		n.Port = fallbackName
+	}
+
+	// Chassis: mapa nombre→datos (normalmente uno; el primero ordenado)
+	keys := make([]string, 0, len(e.Chassis))
+	for k := range e.Chassis {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	if len(keys) > 0 {
+		n.Chassis = keys[0]
+		var ch struct {
+			ID struct {
+				Type  string `json:"type"`
+				Value string `json:"value"`
+			} `json:"id"`
+			MgmtIP json.RawMessage `json:"mgmt-ip"`
+			Caps   []struct {
+				Type    string `json:"type"`
+				Enabled bool   `json:"enabled"`
+			} `json:"capability"`
+		}
+		_ = json.Unmarshal(e.Chassis[keys[0]], &ch) // best-effort (ver cabecera)
+		if ch.ID.Type == "mac" {
+			n.ChassisMac = strings.ToUpper(ch.ID.Value)
+		}
+		if n.Chassis == "" {
+			n.Chassis = ch.ID.Value
+		}
+		n.Mgmt = firstMgmtIP(ch.MgmtIP)
+		for _, cap := range ch.Caps {
+			if cap.Enabled && cap.Type != "" {
+				n.Caps = append(n.Caps, cap.Type)
+			}
+		}
+	}
+
+	// Puerto remoto: descr; si no, el id
+	if len(e.Port) > 0 {
+		var p struct {
+			ID struct {
+				Value string `json:"value"`
+			} `json:"id"`
+			Descr string `json:"descr"`
+		}
+		if json.Unmarshal(e.Port, &p) == nil {
+			n.PortDesc = p.Descr
+			if n.PortDesc == "" {
+				n.PortDesc = p.ID.Value
+			}
+		}
+	}
+	return n
+}
+
+// firstMgmtIP: mgmt-ip viene como array (lldpd actual) o string suelto.
+func firstMgmtIP(raw json.RawMessage) string {
+	if len(raw) == 0 || string(raw) == "null" {
+		return ""
+	}
+	var list []string
+	if err := json.Unmarshal(raw, &list); err == nil {
+		for _, ip := range list {
+			if ip != "" {
+				return ip
+			}
+		}
+		return ""
+	}
+	var single string
+	if err := json.Unmarshal(raw, &single); err == nil {
+		return single
+	}
+	return ""
+}
+
+// lldpNeighborOnPort: vecino anunciado en un puerto local concreto (nil si
+// ninguno). Para el enriquecimiento de bocas del detalle ("· LLDP").
+func lldpNeighborOnPort(neighbors []LldpNeighbor, port string) *LldpNeighbor {
+	for i := range neighbors {
+		if neighbors[i].Port == port {
+			return &neighbors[i]
+		}
+	}
+	return nil
+}

+ 256 - 0
server-go/internal/adapters/lldp_test.go

@@ -0,0 +1,256 @@
+// lldp_test.go — fixture realista de `lldpcli -f json show neighbors`
+// (contrato C2): switch gestionado GS308E con mgmt-ip y caps Bridge, un AP
+// anunciándose (mgmt-ip como string suelto), un equipo sin mgmt-ip ni
+// descr de puerto, y formas degeneradas que NUNCA deben romper el parseo.
+package adapters
+
+import (
+	"errors"
+	"fmt"
+	"testing"
+)
+
+// Fixture realista (lldpd 1.0.x en OpenWrt).
+const lldpcliFixture = `{
+  "lldp": {
+    "interface": [
+      {
+        "name": "lan3",
+        "via": "LLDP",
+        "rid": "2",
+        "age": "0 day, 00:01:12",
+        "chassis": {
+          "GS308E": {
+            "id": {"type": "mac", "value": "28:c6:8e:1d:90:44"},
+            "descr": "Netgear GS308E 8-Port Gigabit Smart Managed Plus Switch",
+            "mgmt-ip": ["192.168.8.13", "fe80::2ac6:8eff:fe1d:9044"],
+            "capability": [
+              {"type": "Bridge", "enabled": true},
+              {"type": "Router", "enabled": false}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "ifname", "value": "ge5"},
+          "descr": "ge5",
+          "ttl": "120"
+        }
+      },
+      {
+        "name": "lan1",
+        "via": "LLDP",
+        "rid": "1",
+        "age": "0 day, 00:00:45",
+        "chassis": {
+          "EAP225": {
+            "id": {"type": "mac", "value": "B0:4A:39:2E:77:10"},
+            "descr": "TP-Link EAP225 (Outdoor)",
+            "mgmt-ip": "192.168.8.4",
+            "capability": [
+              {"type": "Bridge", "enabled": true},
+              {"type": "Wlan", "enabled": true}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "mac", "value": "B0:4A:39:2E:77:11"},
+          "descr": "eth0",
+          "ttl": "120"
+        }
+      },
+      {
+        "name": "lan2",
+        "via": "LLDP",
+        "rid": "3",
+        "age": "0 day, 00:02:03",
+        "chassis": {
+          "mini-pc": {
+            "id": {"type": "mac", "value": "3C:52:82:10:20:30"},
+            "descr": "Debian GNU/Linux",
+            "capability": [
+              {"type": "Station", "enabled": true}
+            ]
+          }
+        },
+        "port": {
+          "id": {"type": "ifname", "value": "eno1"},
+          "ttl": "120"
+        }
+      }
+    ]
+  }
+}`
+
+func TestParseLldpNeighborsFixture(t *testing.T) {
+	neighbors, err := parseLldpNeighbors([]byte(lldpcliFixture))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(neighbors) != 3 {
+		t.Fatalf("neighbors: %d", len(neighbors))
+	}
+	// Switch GS308E en lan3: mgmt-ip array (se coge la primera), caps enabled
+	sw := neighbors[0]
+	if sw.Port != "lan3" || sw.Chassis != "GS308E" || sw.ChassisMac != "28:C6:8E:1D:90:44" {
+		t.Fatalf("gs308e: %+v", sw)
+	}
+	if sw.Mgmt != "192.168.8.13" {
+		t.Fatalf("mgmt: %q", sw.Mgmt)
+	}
+	if len(sw.Caps) != 1 || sw.Caps[0] != "Bridge" {
+		t.Fatalf("caps (Router disabled no cuenta): %v", sw.Caps)
+	}
+	if sw.PortDesc != "ge5" {
+		t.Fatalf("portDesc: %q", sw.PortDesc)
+	}
+	if info := sw.info(); info.Chassis != "GS308E" || info.Mgmt != "192.168.8.13" || info.Caps != "Bridge" || info.PortDesc != "ge5" {
+		t.Fatalf("info: %+v", info)
+	}
+	// AP anunciándose: mgmt-ip como STRING suelto, dos caps enabled
+	ap := neighbors[1]
+	if ap.Port != "lan1" || ap.Chassis != "EAP225" || ap.ChassisMac != "B0:4A:39:2E:77:10" {
+		t.Fatalf("ap: %+v", ap)
+	}
+	if ap.Mgmt != "192.168.8.4" {
+		t.Fatalf("mgmt string suelto: %q", ap.Mgmt)
+	}
+	if len(ap.Caps) != 2 || ap.Caps[0] != "Bridge" || ap.Caps[1] != "Wlan" {
+		t.Fatalf("caps ap: %v", ap.Caps)
+	}
+	if ap.info().Caps != "Bridge, Wlan" {
+		t.Fatalf("caps unidas: %q", ap.info().Caps)
+	}
+	// Equipo sin mgmt-ip ni descr de puerto: PortDesc cae al id
+	pc := neighbors[2]
+	if pc.Port != "lan2" || pc.Mgmt != "" {
+		t.Fatalf("mini-pc: %+v", pc)
+	}
+	if pc.PortDesc != "eno1" {
+		t.Fatalf("portDesc fallback id: %q", pc.PortDesc)
+	}
+}
+
+func TestParseLldpNeighborsDefensivo(t *testing.T) {
+	// Raíz no JSON → error (el caller reintenta; NO es lldpd ausente)
+	if _, err := parseLldpNeighbors([]byte("lldpd is not running")); err == nil {
+		t.Fatal("no JSON debería dar error")
+	}
+	// Formas vacías → sin vecinos, sin error
+	for _, in := range []string{`{}`, `{"lldp":{}}`, `{"lldp":{"interface":null}}`, `{"lldp":{"interface":[]}}`, `null`} {
+		neighbors, err := parseLldpNeighbors([]byte(in))
+		if err != nil || len(neighbors) != 0 {
+			t.Fatalf("%s → %v %v", in, neighbors, err)
+		}
+	}
+	// Forma mapa (lldpd viejo): {"interface": {"lan3": {...}}}
+	mapForm := `{"lldp":{"interface":{"lan3":{"chassis":{"sw1":{"id":{"type":"mac","value":"AA:BB:CC:DD:EE:FF"}}}}}}}`
+	neighbors, err := parseLldpNeighbors([]byte(mapForm))
+	if err != nil || len(neighbors) != 1 {
+		t.Fatalf("forma mapa: %v %v", neighbors, err)
+	}
+	if neighbors[0].Port != "lan3" || neighbors[0].ChassisMac != "AA:BB:CC:DD:EE:FF" || neighbors[0].Chassis != "sw1" {
+		t.Fatalf("forma mapa parseada: %+v", neighbors[0])
+	}
+	// Tipos inesperados por todas partes: nunca panic, campos vacíos
+	weird := `{"lldp":{"interface":[
+		{"name":"lan1","chassis":"una cadena","port":123},
+		{"name":"lan2","chassis":{"x":{"id":"no-objeto","mgmt-ip":42,"capability":"no-array"}},"port":{"id":{}}},
+		42,
+		null
+	]}}`
+	neighbors, err = parseLldpNeighbors([]byte(weird))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(neighbors) != 4 {
+		t.Fatalf("entradas raras: %d", len(neighbors))
+	}
+	if neighbors[0].Port != "lan1" || neighbors[0].Chassis != "" || neighbors[0].PortDesc != "" {
+		t.Fatalf("chassis cadena: %+v", neighbors[0])
+	}
+	if neighbors[1].Port != "lan2" || neighbors[1].ChassisMac != "" || neighbors[1].Mgmt != "" {
+		t.Fatalf("subcampos raros: %+v", neighbors[1])
+	}
+	if neighbors[2].Port != "" || neighbors[2].Chassis != "" || neighbors[2].Caps != nil {
+		t.Fatalf("entrada no-objeto: %+v", neighbors[2])
+	}
+	if neighbors[3].Port != "" || neighbors[3].ChassisMac != "" {
+		t.Fatalf("entrada null: %+v", neighbors[3])
+	}
+	// interface con forma ni array ni mapa → sin datos, no error
+	neighbors, err = parseLldpNeighbors([]byte(`{"lldp":{"interface":42}}`))
+	if err != nil || len(neighbors) != 0 {
+		t.Fatalf("interface escalar: %v %v", neighbors, err)
+	}
+}
+
+func TestIsLldpUnavailable(t *testing.T) {
+	// lldpcli no existe: exit 127 del shell (mensaje de ssh.ExitError envuelto)
+	err127 := fmt.Errorf("ssh 192.168.8.2: %w", errors.New("Process exited with status 127"))
+	if !isLldpUnavailable(err127) {
+		t.Fatalf("exit 127: %v", err127)
+	}
+	if !isLldpUnavailable(errors.New("ssh h: ash: lldpcli: not found")) {
+		t.Fatal("not found")
+	}
+	// Otros fallos NO son indisponibilidad cacheable
+	for _, e := range []error{
+		errors.New("ssh h: timeout (5s)"),
+		errors.New("ssh h: Process exited with status 1"),
+		nil,
+	} {
+		if isLldpUnavailable(e) {
+			t.Fatalf("no debería ser unavailable: %v", e)
+		}
+	}
+}
+
+// Router.Lldp live (ítem 4 de C2): si los vecinos LLDP de un router incluyen
+// en su puerto de uplink a OTRO router conocido (chassis-MAC = bridge MAC de
+// otro router de la config), la tarjeta lleva Lldp; si no, se omite.
+func TestBuildRouterLldpUplink(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "flint2", Host: "192.168.8.1", IsGateway: true},
+		{ID: "living", Host: "192.168.8.2"},
+	}, nil)
+	gw := &routerPolled{cfg: RouterConfig{ID: "flint2", Host: "192.168.8.1", IsGateway: true},
+		brMac: "94:83:C4:00:00:01", fdb: map[string]string{}, lldp: []LldpNeighbor{}}
+	ap := &routerPolled{cfg: RouterConfig{ID: "living", Host: "192.168.8.2"},
+		brMac: "94:83:C4:00:00:02",
+		fdb:   map[string]string{"94:83:C4:00:00:01": "lan1"},
+		lldp: []LldpNeighbor{{
+			Port: "lan1", Chassis: "Flint 2", ChassisMac: "94:83:C4:00:00:01",
+			Mgmt: "192.168.8.1", Caps: []string{"Bridge", "Router"}, PortDesc: "lan3",
+		}}}
+	l.lastPolled = map[string]*routerPolled{"flint2": gw, "living": ap}
+
+	// AP: uplink al gateway identificado por LLDP (chassis-MAC = brMac del
+	// gateway, anunciada en el puerto donde el FDB la aprende)
+	r := l.buildRouter(ap, nil)
+	if r.Lldp == nil {
+		t.Fatal("living debería llevar Lldp (uplink identificado)")
+	}
+	if r.Lldp.Chassis != "Flint 2" || r.Lldp.Mgmt != "192.168.8.1" || r.Lldp.Caps != "Bridge, Router" || r.Lldp.PortDesc != "lan3" {
+		t.Fatalf("Router.Lldp: %+v", r.Lldp)
+	}
+	// Gateway: sin vecinos que sean routers → sin campo
+	if rgw := l.buildRouter(gw, nil); rgw.Lldp != nil {
+		t.Fatalf("gateway no debería llevar Lldp: %+v", rgw.Lldp)
+	}
+	// El anuncio llega por OTRO puerto (no es el uplink) → sin campo
+	ap.fdb["94:83:C4:00:00:01"] = "lan2"
+	if r := l.buildRouter(ap, nil); r.Lldp != nil {
+		t.Fatalf("anuncio por puerto distinto al del FDB: %+v", r.Lldp)
+	}
+	// Vecino LLDP que NO es un router de la config → sin campo
+	ap.fdb["94:83:C4:00:00:01"] = "lan1"
+	ap.lldp[0].ChassisMac = "28:C6:8E:1D:90:44"
+	if r := l.buildRouter(ap, nil); r.Lldp != nil {
+		t.Fatalf("vecino no-router: %+v", r.Lldp)
+	}
+	// Sin datos LLDP → sin campo (comportamiento intacto)
+	ap.lldp = nil
+	if r := l.buildRouter(ap, nil); r.Lldp != nil {
+		t.Fatalf("sin LLDP: %+v", r.Lldp)
+	}
+}

+ 43 - 0
server-go/internal/adapters/openwrt.go

@@ -40,6 +40,9 @@ type OpenWrtClient struct {
 	sid        string     // sesión ubus HTTP cacheada
 	lastStat   *cpuSample // /proc/stat previo
 	lastNetDev *netSample // /proc/net/dev previo
+	// lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
+	// martillear con un comando que no existe. Solo lo toca el sondeo.
+	lldpDownUntil time.Time
 }
 
 type cpuSample struct{ total, idleAll float64 }
@@ -501,6 +504,46 @@ func parseWirelessClients(out string) map[string]WirelessClient {
 	return m
 }
 
+// GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
+// interfaz STA activa/asociada en `ubus call network.wireless status`).
+// Error si el router no soporta la llamada (sin wifi → el caller omite el
+// campo backhaul, nunca rompe el sondeo).
+func (c *OpenWrtClient) GetWirelessUplink() (bool, error) {
+	raw, err := c.UbusCall("network.wireless", "status", nil)
+	if err != nil {
+		return false, err
+	}
+	return parseWirelessUplink(raw)
+}
+
+// parseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
+// up e ifname asignado = asociada). Tolerante con radios/entradas raras.
+func parseWirelessUplink(raw json.RawMessage) (bool, error) {
+	var radios map[string]struct {
+		Up         bool `json:"up"`
+		Interfaces []struct {
+			Ifname string `json:"ifname"`
+			Config struct {
+				Mode string `json:"mode"`
+			} `json:"config"`
+		} `json:"interfaces"`
+	}
+	if err := json.Unmarshal(raw, &radios); err != nil {
+		return false, err
+	}
+	for _, r := range radios {
+		if !r.Up {
+			continue
+		}
+		for _, itf := range r.Interfaces {
+			if itf.Config.Mode == "sta" && itf.Ifname != "" {
+				return true, nil
+			}
+		}
+	}
+	return false, nil
+}
+
 // ---------------------------------------------------------------------------
 // Puertos
 // ---------------------------------------------------------------------------

+ 57 - 1
server-go/internal/adapters/topology.go

@@ -24,9 +24,17 @@ import (
 //     "inferred" SOLO se crean en el gateway. En un AP, un puerto multi-MAC
 //     es casi seguro su UPLINK (aprende las MACs de toda la LAN) y el FDB
 //     no puede distinguirlo de un switch local → no se afirma nada: esos
-//     clientes quedan "sin evidencia" y el frontend los cuelga del gateway.
+//     clientes quedan "sin evidencia" y el frontend los cuelgan del gateway.
 //     Única excepción tras un AP: hipervisor con evidencia clara (MACs OUI
 //     de hipervisor + exactamente un host) = servidor con VMs tras ese AP.
+//   - LLDP (Fase 5, contrato C2): si en un puerto multi-MAC se anuncia un
+//     vecino LLDP cuya chassis-MAC está entre las aprendidas, el equipo que
+//     multiplexa queda IDENTIFICADO → nodo "managed" (nombre/mgmt-ip/caps
+//     anunciados). Es evidencia positiva, como la de hipervisor: aplica
+//     también tras un AP (el uplink al gateway no puede promover porque su
+//     MAC está excluida de las aprendidas). Además, cualquier vecino cuya
+//     chassis-MAC sea un Device conocido puebla Device.Lldp. Sin datos LLDP
+//     todo sigue exactamente como antes (inferred/hypervisor + reglas OUI).
 // ---------------------------------------------------------------------------
 
 // hypervisorOUI: prefijos de MAC de hipervisores conocidos.
@@ -167,6 +175,23 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 					continue
 				}
 			}
+			// LLDP: un vecino anunciado en este puerto cuya chassis-MAC está
+			// entre las aprendidas identifica el switch/AP gestionado que
+			// multiplexa → nodo "managed" (evidencia positiva, válida también
+			// tras un AP; ver cabecera).
+			if nb := findManagedNeighbor(p.lldp, port, kept); nb != nil {
+				setPort()
+				dists = append(dists, DistributionNode{
+					ID: id, Kind: "managed", RouterID: routerID, Port: port,
+					MacCount: len(kept), Name: nb.displayName(), Ip: nb.Mgmt, Lldp: nb.info(),
+				})
+				for _, mac := range kept {
+					if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+						devices[idx].AttachTo = id
+					}
+				}
+				continue
+			}
 			if routerID != gatewayID {
 				// AP con puerto multi-MAC sin evidencia de hipervisor: es casi
 				// seguro su uplink (aprende las MACs de toda la LAN). No se
@@ -187,5 +212,36 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 			}
 		}
 	}
+
+	// Post-paso LLDP: un vecino cuya chassis-MAC es un Device conocido lo
+	// identifica (Device.Lldp), en el puerto que sea y aunque no multiplexe.
+	for _, routerID := range routerIDs {
+		for i := range polled[routerID].lldp {
+			nb := &polled[routerID].lldp[i]
+			if nb.ChassisMac == "" {
+				continue
+			}
+			if idx, ok := byMAC[nb.ChassisMac]; ok {
+				devices[idx].Lldp = nb.info()
+			}
+		}
+	}
 	return devices, dists
 }
+
+// findManagedNeighbor: vecino LLDP anunciado en `port` cuya chassis-MAC está
+// entre las MACs aprendidas (nil si no hay evidencia).
+func findManagedNeighbor(neighbors []LldpNeighbor, port string, kept []string) *LldpNeighbor {
+	for i := range neighbors {
+		nb := &neighbors[i]
+		if nb.Port != port || nb.ChassisMac == "" {
+			continue
+		}
+		for _, mac := range kept {
+			if mac == nb.ChassisMac {
+				return nb
+			}
+		}
+	}
+	return nil
+}

+ 133 - 0
server-go/internal/adapters/topology_test.go

@@ -197,3 +197,136 @@ func TestInferTopologyApCableadoDirecto(t *testing.T) {
 		t.Fatalf("port: %q", devices[0].Port)
 	}
 }
+
+// --- LLDP (contrato C2): promoción a "managed" y Device.Lldp ---
+
+// gs308eNeighbor: switch gestionado anunciándose en lan3 (fixture GS308E).
+func gs308eNeighbor() []LldpNeighbor {
+	return []LldpNeighbor{{
+		Port: "lan3", Chassis: "GS308E", ChassisMac: "28:C6:8E:1D:90:44",
+		Mgmt: "192.168.8.13", Caps: []string{"Bridge"}, PortDesc: "ge5",
+	}}
+}
+
+// Puerto multi-MAC del gateway CON vecino LLDP cuya chassis-MAC está entre
+// las aprendidas → nodo "managed" con Name/Ip/Lldp; los equipos cuelgan de
+// él igual que del inferido.
+func TestInferTopologySwitchManagedLldp(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb: map[string]string{
+				"28:C6:8E:1D:90:44": "lan3", // el propio GS308E
+				"04:D4:C4:8B:30:A7": "lan3", // PC tras el switch
+				"DC:A6:32:4F:77:02": "lan3", // Raspberry tras el switch
+			},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{
+		dev("28:C6:8E:1D:90:44", "flint2", "cable"),
+		dev("04:D4:C4:8B:30:A7", "flint2", "cable"),
+		dev("DC:A6:32:4F:77:02", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	if dn.Kind != "managed" || dn.ID != "dist-flint2-lan3" || dn.MacCount != 3 {
+		t.Fatalf("distnode managed: %+v", dn)
+	}
+	if dn.Name != "GS308E" || dn.Ip != "192.168.8.13" {
+		t.Fatalf("name/ip: %+v", dn)
+	}
+	if dn.Lldp == nil || dn.Lldp.Chassis != "GS308E" || dn.Lldp.Mgmt != "192.168.8.13" || dn.Lldp.Caps != "Bridge" || dn.Lldp.PortDesc != "ge5" {
+		t.Fatalf("lldp del nodo: %+v", dn.Lldp)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-flint2-lan3" || d.Port != "lan3" {
+			t.Fatalf("%s debería colgar del nodo managed: port=%q attachTo=%q", d.MAC, d.Port, d.AttachTo)
+		}
+	}
+	// El propio switch queda identificado como Device
+	if devices[0].Lldp == nil || devices[0].Lldp.Chassis != "GS308E" {
+		t.Fatalf("Device.Lldp del switch: %+v", devices[0].Lldp)
+	}
+}
+
+// El mismo puerto multi-MAC SIN datos LLDP (lldpd ausente: lldp nil) sigue
+// fantasma: nodo "inferred" exactamente como antes.
+func TestInferTopologyMultiMacSinLldpSigueFantasma(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb: map[string]string{
+				"78:2B:CB:AA:01:01": "lan3",
+				"8C:EA:48:AA:02:02": "lan3",
+			}},
+	}
+	devices := []Device{
+		dev("78:2B:CB:AA:01:01", "flint2", "cable"),
+		dev("8C:EA:48:AA:02:02", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" || dists[0].Lldp != nil || dists[0].Ip != "" {
+		t.Fatalf("sin LLDP sigue inferido: %+v", dists)
+	}
+	// Vecino LLDP cuya chassis-MAC NO está aprendida en ese puerto → tampoco
+	// promociona (no es el equipo que multiplexa).
+	polled["flint2"].lldp = []LldpNeighbor{{
+		Port: "lan3", Chassis: "OtroEquipo", ChassisMac: "00:00:00:00:00:99",
+	}}
+	_, dists = inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" {
+		t.Fatalf("chassis no aprendida sigue inferido: %+v", dists)
+	}
+	// Vecino en OTRO puerto → no promociona este
+	polled["flint2"].lldp = []LldpNeighbor{{
+		Port: "lan1", Chassis: "GS308E", ChassisMac: "78:2B:CB:AA:01:01",
+	}}
+	_, dists = inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" {
+		t.Fatalf("vecino en otro puerto sigue inferido: %+v", dists)
+	}
+}
+
+// Managed también aplica tras un AP (evidencia positiva, como el hipervisor):
+// switch gestionado identificado colgando del AP, no del gateway.
+func TestInferTopologyManagedTrasAP(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01", fdb: map[string]string{}},
+		"living": {cfg: RouterConfig{ID: "living"}, brMac: "94:83:C4:00:00:02",
+			fdb: map[string]string{
+				"28:C6:8E:1D:90:44": "lan3",
+				"04:D4:C4:8B:30:A7": "lan3",
+			},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{
+		dev("28:C6:8E:1D:90:44", "living", "cable"),
+		dev("04:D4:C4:8B:30:A7", "living", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "managed" || dists[0].RouterID != "living" || dists[0].Name != "GS308E" {
+		t.Fatalf("managed tras AP: %+v", dists)
+	}
+	if devices[1].AttachTo != "dist-living-lan3" {
+		t.Fatalf("cliente tras el switch: %q", devices[1].AttachTo)
+	}
+}
+
+// Vecino LLDP cuya chassis-MAC es un Device conocido en puerto de UNA sola
+// MAC (cableado directo): no hay nodo, pero el Device queda identificado.
+func TestInferTopologyLldpIdentificaDeviceDirecto(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb:  map[string]string{"28:C6:8E:1D:90:44": "lan3"},
+			lldp: gs308eNeighbor()},
+	}
+	devices := []Device{dev("28:C6:8E:1D:90:44", "flint2", "cable")}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("cableado directo no genera nodo: %+v", dists)
+	}
+	if devices[0].Lldp == nil || devices[0].Lldp.Chassis != "GS308E" || devices[0].Lldp.Mgmt != "192.168.8.13" {
+		t.Fatalf("Device.Lldp: %+v", devices[0].Lldp)
+	}
+}

+ 13 - 2
server-go/internal/adapters/types.go

@@ -128,6 +128,13 @@ type Router struct {
 	Clients    int       `json:"clients"`
 	HotMetric  string    `json:"hotMetric,omitempty"` // "temp" solo si temp>65
 	Sparkline  []float64 `json:"sparkline"`
+	// Backhaul: medio del uplink del router ("cable"|"wifi"). Ausente =
+	// cable/desconocido (router sin wifi o sonda no disponible).
+	Backhaul string `json:"backhaul,omitempty"`
+	// Lldp: vecino LLDP del puerto de uplink cuando es OTRO router conocido
+	// (uplink identificado por LLDP). Ausente si no hay dato — la app lo usa
+	// para el sufijo "· LLDP" en la etiqueta del uplink.
+	Lldp *LldpInfo `json:"lldp,omitempty"`
 }
 
 // DeviceTotals del overview (quirk: NewToday=0 en live).
@@ -187,16 +194,20 @@ type LldpInfo struct {
 // DistributionNode: puerto físico con varias MACs aprendidas en el FDB.
 // "inferred" = OUI heterogéneo (switch o bridge desconocido, sin IP);
 // "hypervisor" = OUI de hipervisor (Proxmox/VMware/Hyper-V/KVM) → sus
-// CTs/VMs se anidan bajo el host en el mapa.
+// CTs/VMs se anidan bajo el host en el mapa;
+// "managed" = identificado por LLDP (vecino anunciado en ese puerto cuya
+// chassis-MAC está entre las aprendidas): lleva Name (chassis), Ip (mgmt)
+// y Lldp con las capacidades/puerto remoto anunciados.
 type DistributionNode struct {
 	ID       string    `json:"id"`
-	Kind     string    `json:"kind"` // "inferred"|"hypervisor"
+	Kind     string    `json:"kind"` // "inferred"|"hypervisor"|"managed"
 	RouterID string    `json:"routerId"`
 	Port     string    `json:"port"`
 	MacCount int       `json:"macCount"`
 	// HostDeviceID: hipervisor → id del Device host (Proxmox…), si es cliente.
 	HostDeviceID string    `json:"hostDeviceId,omitempty"`
 	Name         string    `json:"name,omitempty"`
+	Ip           string    `json:"ip,omitempty"` // managed: mgmt-ip anunciada por LLDP
 	Lldp         *LldpInfo `json:"lldp,omitempty"`
 }
 

+ 27 - 5
server-go/internal/httpapi/httpapi_test.go

@@ -490,10 +490,11 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	srv := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
 
-	// Paginación: 67 dispositivos del dataset canónico (47 base + 20 fixtures topología v5)
+	// Paginación: 66 dispositivos del dataset canónico (47 base − GS308E, que
+	// ahora es nodo managed, + 20 fixtures topología v5)
 	res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
 	body := readJSON(t, res)
-	if body["total"].(float64) != 67 || len(body["items"].([]any)) != 10 {
+	if body["total"].(float64) != 66 || len(body["items"].([]any)) != 10 {
 		t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
 	}
 	if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
@@ -501,7 +502,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	}
 	res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
 	body = readJSON(t, res)
-	if len(body["items"].([]any)) != 7 {
+	if len(body["items"].([]any)) != 6 {
 		t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
 	}
 	// Sin solape con la página anterior
@@ -525,7 +526,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	// Filtros
 	res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
 	body = readJSON(t, res)
-	if body["total"].(float64) != 22 { // 18 base + switch-netgear + 3 clientes detrás
+	if body["total"].(float64) != 21 { // 18 base + 3 clientes del switch gestionado (nodo managed)
 		t.Fatalf("routerId=living: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?band=cable", cookie)
@@ -535,7 +536,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 			t.Fatalf("band=cable con item de otra banda: %v", it)
 		}
 	}
-	if body["total"].(float64) != 27 { // 7 base + 20 fixtures cable (3 netgear + pve + 10 CTs + 6 tras switch)
+	if body["total"].(float64) != 26 { // 6 base + 20 fixtures cable (3 netgear + pve + 10 CTs + 6 tras switch)
 		t.Fatalf("band=cable: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?status=offline", cookie)
@@ -711,3 +712,24 @@ func TestSPAFallback(t *testing.T) {
 	// con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
 	_ = srv
 }
+
+// writeJSON debe serializar como Hono: JSON compacto SIN el '\n' final que
+// añade json.Encoder (consistencia con D5 WriteError).
+func TestWriteJSONSinSaltoFinal(t *testing.T) {
+	srv := makeTestServer(t)
+	res := get(t, srv.URL, "/api/health", "")
+	defer res.Body.Close()
+	body, err := io.ReadAll(res.Body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(body) == 0 {
+		t.Fatal("body vacío")
+	}
+	if body[len(body)-1] == '\n' {
+		t.Fatalf("el body NO debe terminar en '\\n': %q", body[len(body)-20:])
+	}
+	if !json.Valid(body) {
+		t.Fatalf("body no es JSON válido: %q", body)
+	}
+}

+ 9 - 5
server-go/internal/httpapi/server.go

@@ -10,6 +10,7 @@
 package httpapi
 
 import (
+	"bytes"
 	"encoding/json"
 	"net/http"
 	"strings"
@@ -129,14 +130,17 @@ func noStoreMux(next http.Handler) http.Handler {
 	})
 }
 
-// writeJSON serializa como JSON.stringify: compacto y SIN escapar HTML
-// (SetEscapeHTML(false)).
+// writeJSON serializa como JSON.stringify: compacto, SIN escapar HTML
+// (SetEscapeHTML(false)) y SIN el '\n' final que añade Encoder.Encode
+// (consistencia con D5 WriteError / paridad Hono: marshal + write).
 func writeJSON(w http.ResponseWriter, status int, v any) {
-	w.Header().Set("Content-Type", "application/json")
-	w.WriteHeader(status)
-	enc := json.NewEncoder(w)
+	var buf bytes.Buffer
+	enc := json.NewEncoder(&buf)
 	enc.SetEscapeHTML(false)
 	_ = enc.Encode(v)
+	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(status)
+	_, _ = w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
 }
 
 // writeError escribe el envelope {error, message?}.