Jelajahi Sumber

merge: Fase 6 + 6.5 — agente OpenWrt piloto, Web Push VAPID, view-model semántico, topología infra, displayName y remodel de Ajustes

gnacho 4 bulan lalu
induk
melakukan
0e5acc177b
93 mengubah file dengan 11975 tambahan dan 1434 penghapusan
  1. 27 1
      .goreleaser.yaml
  2. 68 4
      ARCHITECTURE.md
  3. 160 0
      agent/cmd/netpulse-agent/main.go
  4. 30 0
      agent/deploy/netpulse-agent.init
  5. 3 0
      agent/go.mod
  6. 190 0
      agent/internal/push/push.go
  7. 152 0
      agent/internal/push/push_test.go
  8. 249 0
      agent/probe/local.go
  9. 54 0
      agent/probe/payload.go
  10. 582 0
      agent/probe/probe.go
  11. 243 0
      agent/probe/probe_test.go
  12. 1 0
      app/.gitignore
  13. 3 0
      app/package.json
  14. 95 4
      app/public/locales/en/translation.json
  15. 95 4
      app/public/locales/es/translation.json
  16. 22 2
      app/src/components/AuthGate.tsx
  17. 5 1
      app/src/components/RouterCard.tsx
  18. 35 0
      app/src/components/routers/AgentBadge.tsx
  19. 5 1
      app/src/components/routers/FleetCard.tsx
  20. 11 3
      app/src/components/routers/FleetTable.tsx
  21. 12 0
      app/src/components/routers/RouterDetailHeader.tsx
  22. 16 11
      app/src/components/routers/routerExtras.ts
  23. 30 0
      app/src/components/topology/LegendCard.tsx
  24. 2 1
      app/src/components/topology/LinksTable.tsx
  25. 44 5
      app/src/components/topology/TopologyMap.tsx
  26. 238 8
      app/src/components/topology/model.ts
  27. 2 0
      app/src/data/AuthContext.tsx
  28. 227 3
      app/src/data/DataProvider.tsx
  29. 83 0
      app/src/data/alertConfig.ts
  30. 57 1
      app/src/data/alertFeed.ts
  31. 2544 0
      app/src/data/demo-canon.json
  32. 38 330
      app/src/data/mock.ts
  33. 92 0
      app/src/data/push.ts
  34. 90 2
      app/src/data/types.ts
  35. 8 0
      app/src/hooks/useAgentFor.ts
  36. 16 9
      app/src/hooks/useServicesVisibility.ts
  37. 29 4
      app/src/i18n.ts
  38. 214 25
      app/src/pages/Alerts.tsx
  39. 88 7
      app/src/pages/Devices.tsx
  40. 492 12
      app/src/pages/Settings.tsx
  41. 64 8
      app/src/pages/Topology.tsx
  42. 70 315
      app/src/pages/devices-data.ts
  43. 19 2
      app/src/sections/HeroStrip.tsx
  44. 93 0
      app/src/sw.ts
  45. 15 3
      app/vite.config.ts
  46. 7 1
      docs/AGENTE-OPENWRT.md
  47. 203 0
      install-agent.sh
  48. 64 0
      server-go/cmd/gen-demo-canon/main.go
  49. 36 3
      server-go/cmd/netpulse/main.go
  50. 7 0
      server-go/go.mod
  51. 71 2
      server-go/go.sum
  52. 36 9
      server-go/internal/adapters/adapters_test.go
  53. 264 0
      server-go/internal/adapters/agent.go
  54. 206 0
      server-go/internal/adapters/agent_live_test.go
  55. 193 0
      server-go/internal/adapters/alerts_live_test.go
  56. 63 34
      server-go/internal/adapters/demo.go
  57. 47 0
      server-go/internal/adapters/demo_canon.go
  58. 41 0
      server-go/internal/adapters/demo_canon_json_test.go
  59. 187 0
      server-go/internal/adapters/demo_canon_test.go
  60. 110 41
      server-go/internal/adapters/demo_dataset.go
  61. 16 10
      server-go/internal/adapters/demo_extras.go
  62. 102 0
      server-go/internal/adapters/infra_test.go
  63. 159 56
      server-go/internal/adapters/live.go
  64. 68 440
      server-go/internal/adapters/openwrt.go
  65. 263 0
      server-go/internal/adapters/topo_semantics.go
  66. 150 0
      server-go/internal/adapters/topo_semantics_test.go
  67. 18 1
      server-go/internal/adapters/topology.go
  68. 23 6
      server-go/internal/adapters/topology_test.go
  69. 65 25
      server-go/internal/adapters/types.go
  70. 355 0
      server-go/internal/alerts/alerts.go
  71. 252 0
      server-go/internal/alerts/alerts_test.go
  72. 5 2
      server-go/internal/auth/middleware.go
  73. 11 0
      server-go/internal/db/db.go
  74. 300 0
      server-go/internal/httpapi/agent.go
  75. 298 0
      server-go/internal/httpapi/agent_api_test.go
  76. 197 0
      server-go/internal/httpapi/alerts_api_test.go
  77. 12 5
      server-go/internal/httpapi/auth.go
  78. 70 9
      server-go/internal/httpapi/data.go
  79. 131 0
      server-go/internal/httpapi/display_name_test.go
  80. 13 10
      server-go/internal/httpapi/httpapi_test.go
  81. 89 0
      server-go/internal/httpapi/push.go
  82. 118 0
      server-go/internal/httpapi/push_api_test.go
  83. 41 0
      server-go/internal/httpapi/refresh.go
  84. 140 0
      server-go/internal/httpapi/refresh_test.go
  85. 42 3
      server-go/internal/httpapi/server.go
  86. 112 0
      server-go/internal/httpapi/system.go
  87. 57 0
      server-go/internal/httpapi/system_api_test.go
  88. 58 0
      server-go/internal/httpapi/system_internal_test.go
  89. 39 9
      server-go/internal/httpapi/users.go
  90. 23 2
      server-go/internal/poller/poller.go
  91. 163 0
      server-go/internal/push/notifier.go
  92. 110 0
      server-go/internal/push/push.go
  93. 327 0
      server-go/internal/push/push_test.go

+ 27 - 1
.goreleaser.yaml

@@ -1,8 +1,9 @@
 version: 2
 
-# Releases de NetPulse: dos binarios estáticos por tag v*
+# Releases de NetPulse: tres binarios estáticos por tag v*
 #   netpulse            app completa (backend Go + frontend embebido)
 #   netpulse-collector  sidecar de latencia TCP con series temporales propias
+#   netpulse-agent      agente nativo OpenWrt (push al servidor; Fase 6)
 #
 # OJO: los hooks globales `before:` son feature GoReleaser PRO (en OSS se
 # "ejecutan" en el log pero no hacen nada, y encima rompen el embed).
@@ -35,6 +36,21 @@ builds:
     flags: [-trimpath]
     ldflags: [-s, -w]
 
+  # Agente nativo OpenWrt (Fase 6): binario stateless que empuja al servidor.
+  # arm64 = GL-MT6000 + APs (Cortex-A53); armv7 por si aparece un AP más
+  # viejo; amd64 para pilotos locales.
+  - id: netpulse-agent
+    dir: agent
+    main: ./cmd/netpulse-agent
+    binary: netpulse-agent
+    env:
+      - CGO_ENABLED=0
+    goos: [linux]
+    goarch: [amd64, arm64, arm]
+    goarm: [7]
+    flags: [-trimpath]
+    ldflags: [-s, -w]
+
 archives:
   - id: netpulse
     ids: [netpulse]
@@ -54,6 +70,16 @@ archives:
     files:
       - LICENSE
 
+  - id: netpulse-agent
+    ids: [netpulse-agent]
+    formats: [tar.gz]
+    name_template: >-
+      {{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}
+    files:
+      - LICENSE
+      - src: agent/deploy/netpulse-agent.init
+        dst: netpulse-agent.init
+
 checksum:
   name_template: checksums.txt
 

+ 68 - 4
ARCHITECTURE.md

@@ -82,6 +82,32 @@
   lento): asciende el nodo a **"managed"** (identificado: chasis, IP de
   gestión, capacidades, puerto remoto, badge cyan) y puebla `Device.Lldp`.
 
+## View-model versionado (Fase 6.5)
+
+La API es un **view-model de presentación versionado**: `GET /api/overview`
+lleva siempre `vm` (`adapters.ViewModelVersion`, hoy `1`). Un cliente (p.ej.
+Fase 7 LuCI) debe rechazar/avisar si `vm` supera la versión que soporta. Bump
+de versión = cualquier cambio incompatible de forma; añadir campos opcionales
+NO bumpea. El overview gana además `topology` (semántica precalculada:
+enlaces, anillos por router y peers ocultos "+N") y los devices pueden llevar
+`infra` (`hypervisor`|`ct`|`managed-switch`, sellado server-side — la app no
+infiere). El dataset demo canónico es single-source en Go:
+`app/src/data/demo-canon.json` se GENERA con `go run ./cmd/gen-demo-canon`
+(hay test de frescura; la app lo importa en build — `mock.ts` re-exporta
+desde el JSON, sin arrays canon duplicados).
+
+Consumo en la app: `types.ts` fija `VM_SUPPORTED = 1` y DataProvider avisa
+por consola (una vez, sin romper UI) si llega un `vm` mayor; la topología
+semántica del snapshot se usa cuando está presente (anillos, enlaces y "+N"
+del server; la geometría de píxeles sigue siendo local) con fallback exacto
+al cálculo cliente si el servidor es viejo.
+
+Endpoints de soporte (Fase 6.5): `GET /api/system/info` (datos reales del
+proceso: versión Go, distro, kernel, CPU, RAM, uptime — alimenta el bloque
+Sistema de Acerca de) y `PUT /api/users/me/display-name` (nombre de saludo
+del Resumen, ≠ username; columna `users.display_name` migrada como
+`language`; `GET /api/auth/me` y `/api/users` lo devuelven).
+
 ## Auth y seguridad
 
 - Credenciales en `.env` (`AUTH_USER`/`AUTH_PASS`); bcrypt (coste 10) en
@@ -111,10 +137,45 @@
 | Tabla | Contenido |
 |---|---|
 | `sessions(id, created_at, expires_at, ua)` | Sesiones (cookie `session=id.hmac`, 30 d) |
-| `kv(key, value)` | `session_secret`, `auth_pass_hash` (bcrypt) + fingerprint, `adguard_*`, `go_migration` |
+| `kv(key, value)` | `session_secret`, `auth_pass_hash` (bcrypt) + fingerprint, `adguard_*`, `go_migration`, `alerts.config.v1`, `alerts.read.v1`, `agent.token.<slug>` (sha256), `push.vapid.*` |
 | `login_attempts(ip, attempts, locked_until)` | Rate-limit persistente |
 | `metrics(router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps)` | 1 fila/router/tick; retención 7 días |
 | `adguard_stats(ts, queries, blocked)` | 1 fila/tick; retención 7 días |
+| `push_subscriptions(endpoint, keys_auth, keys_p256dh, user_agent, created_at)` | Suscripciones Web Push; 404/410 al enviar → borrado |
+
+## Alertas (motor `internal/alerts`)
+
+Eventos con `Category` (router|internet|clients|signal|vpn|system), `Urgent`
+y `Ts`. El motor aplica **config por categoría de 3 niveles** (`urgent` / `all`
+/ `none`, en `kv alerts.config.v1`) EN CREACIÓN: `none` descarta, `urgent` solo
+deja pasar los urgentes, `all` pasa todo. Dedup 5 min por
+(categoría,título,router), cap 100. Read-state en servidor (`kv
+alerts.read.v1`, FIFO 200) — la campana usa `overview.unreadAlerts` (server
+truth). Fuentes live: router offline (2 fallos seguidos) y recuperado, WAN
+down (lossPct=100 en 2 sondeos), temperatura > 65 °C, señal < −70 dBm
+(1/día/device), handshake WireGuard, dispositivo desconocido (sin nombre DHCP,
+primer ciclo mudo). La demo siembra sus 5 canon vía `Engine.Seed` (omite solo
+el filtro de config). Hook `Notifier` para canales externos.
+
+## Web Push
+
+VAPID en `kv` (generado en primer arranque), suscripciones en tabla propia,
+`push.Notifier` envía SOLO las alertas que pasan config y son urgentes
+(payload `{title, body, category, severity, url, tag}`; tag = dedup del
+navegador). SW propio (`injectManifest`) con handlers `push` y
+`notificationclick` → abre `/alerts`. Requiere contexto seguro (HTTPS o
+localhost) — en LAN HTTP la tarjeta de Ajustes lo avisa.
+
+## Agente OpenWrt (Fase 6, piloto)
+
+`POST /api/ingest/agent` (Bearer por equipo, token sha256 en `kv`, rate-limit
+30/min, body ≤ 2 MB) + CRUD `/api/agents`. El adapter live-agent usa el último
+payload como estado del router; si `last_seen` expira (TTL 90 s) degrada a SSH
+con alerta `system` y avisa al recuperar. El binario `agent/` (stdlib-only,
+CGO=0, ~5,8 MB arm64 — suelo realista con TLS/x509) ejecuta localmente las
+sondas del tier rápido (package `probe` compartido con server-go vía
+`replace ../agent`), stateless, push con backoff y buffer RAM acotado; procd +
+`install-agent.sh`. Diseño completo y hoja de ruta en `docs/AGENTE-OPENWRT.md`.
 
 Jobs de mantenimiento (cada hora): borrado de filas > 7 días, sesiones
 expiradas y `PRAGMA wal_checkpoint(TRUNCATE)`. Migración Node→Go automática
@@ -138,7 +199,10 @@ Ver `server-go/.env.example`. Resumen: `PORT`, `STATIC_DIR`, `DATA_DIR`,
 
 ## Hoja de ruta
 
-- **Fase 6 — agente OpenWrt (nativo en el router):** diseño en
-  `docs/AGENTE-OPENWRT.md` (agente stateless con push HTTPS+token, procd,
-  tmpfs; el colector-satélite actual se conserva para series largas).
+- **Fase 6 — incremento 2 del agente:** netlink/nl80211 nativo, eventos ubus
+  (assoc/disassoc en tiempo real), `.ipk`, medición en hardware real.
+  Piloto (ingesta + push + fallback SSH) YA implementado — ver sección
+  "Agente OpenWrt".
+- **Fase 7 (opcional):** `luci-app-netpulse` — gestión del agente desde la
+  interfaz web del router.
 - Integración de las series del collector en server-go (hoy son independientes).

+ 160 - 0
agent/cmd/netpulse-agent/main.go

@@ -0,0 +1,160 @@
+// netpulse-agent — agente nativo OpenWrt (SPEC-AGENTE-PILOTO §2): sondea
+// LOCALMENTE el equipo (los mismos comandos que el servidor lanza por SSH,
+// package probe compartido) y empuja el resultado a POST /api/ingest/agent
+// con Bearer + backoff + buffer RAM acotado. Stateless: NADA en flash; logs
+// a stderr (procd los manda a syslog).
+//
+// Config (env o /etc/netpulse-agent.env; el env gana):
+//
+//	NETPULSE_SERVER    URL del servidor (https://... o http://...:3000) [obligatoria]
+//	NETPULSE_TOKEN     token del equipo (64 hex; se muestra una vez al crearlo)
+//	NETPULSE_SLUG      slug del equipo (agent.token.<slug> en el servidor)
+//	NETPULSE_INTERVAL  intervalo de push (default 15s; "15", "15s", "1m")
+//	NETPULSE_ENV_FILE  fichero env alternativo (default /etc/netpulse-agent.env)
+//	NETPULSE_WAN_TARGET    ping WAN con pérdida (gateway; p. ej. 1.1.1.1)
+//	NETPULSE_GW_TARGET     ping corto al gateway (APs; p. ej. 192.168.8.1)
+//	NETPULSE_INSECURE_TLS  "1" → no verificar el certificado (LAN autofirmado)
+package main
+
+import (
+	"context"
+	"crypto/tls"
+	"log"
+	"net/http"
+	"os"
+	"os/signal"
+	"strconv"
+	"strings"
+	"syscall"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/internal/push"
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// Version del agente (la reporta cada push; se puede fijar con
+// -ldflags "-X main.Version=x.y.z").
+var Version = "0.1.0"
+
+type config struct {
+	server, token, slug string
+	interval            time.Duration
+	wanTarget, gwTarget string
+	insecureTLS         bool
+}
+
+// loadEnvFile lee KEY=VALUE de un fichero env (líneas # = comentario).
+func loadEnvFile(path string) map[string]string {
+	out := map[string]string{}
+	data, err := os.ReadFile(path)
+	if err != nil {
+		return out
+	}
+	for _, line := range strings.Split(string(data), "\n") {
+		line = strings.TrimSpace(line)
+		if line == "" || strings.HasPrefix(line, "#") {
+			continue
+		}
+		k, v, ok := strings.Cut(line, "=")
+		if !ok {
+			continue
+		}
+		out[strings.TrimSpace(k)] = strings.Trim(strings.TrimSpace(v), `"'`)
+	}
+	return out
+}
+
+// loadConfig: env del proceso > fichero env; fail-fast si falta lo obligatorio.
+func loadConfig() (config, error) {
+	file := os.Getenv("NETPULSE_ENV_FILE")
+	if file == "" {
+		file = "/etc/netpulse-agent.env"
+	}
+	fromFile := loadEnvFile(file)
+	get := func(key string) string {
+		if v := os.Getenv(key); v != "" {
+			return v
+		}
+		return fromFile[key]
+	}
+	cfg := config{
+		server:      strings.TrimRight(get("NETPULSE_SERVER"), "/"),
+		token:       get("NETPULSE_TOKEN"),
+		slug:        get("NETPULSE_SLUG"),
+		interval:    15 * time.Second,
+		wanTarget:   get("NETPULSE_WAN_TARGET"),
+		gwTarget:    get("NETPULSE_GW_TARGET"),
+		insecureTLS: get("NETPULSE_INSECURE_TLS") == "1",
+	}
+	if v := get("NETPULSE_INTERVAL"); v != "" {
+		if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
+			cfg.interval = time.Duration(sec) * time.Second
+		} else if d, err := time.ParseDuration(v); err == nil && d > 0 {
+			cfg.interval = d
+		} else {
+			log.Printf("[netpulse-agent] NETPULSE_INTERVAL %q inválido; usando 15s", v)
+		}
+	}
+	for _, kv := range [][2]string{
+		{"NETPULSE_SERVER", cfg.server},
+		{"NETPULSE_TOKEN", cfg.token},
+		{"NETPULSE_SLUG", cfg.slug},
+	} {
+		if kv[1] == "" {
+			return config{}, &configError{kv[0]}
+		}
+	}
+	return cfg, nil
+}
+
+type configError struct{ key string }
+
+func (e *configError) Error() string {
+	return "falta " + e.key + " (env o /etc/netpulse-agent.env)"
+}
+
+func main() {
+	log.SetOutput(os.Stderr)
+	log.SetPrefix("")
+	if err := run(); err != nil {
+		log.Printf("[netpulse-agent] error fatal: %v", err)
+		os.Exit(1)
+	}
+}
+
+func run() error {
+	cfg, err := loadConfig()
+	if err != nil {
+		return err
+	}
+
+	transport := http.DefaultTransport.(*http.Transport).Clone()
+	if cfg.insecureTLS {
+		transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // opt-in documentado (LAN autofirmada)
+	}
+	client := push.New(cfg.server, cfg.token, &http.Client{Timeout: 10 * time.Second, Transport: transport})
+	client.SetLogger(func(format string, args ...any) { log.Printf(format, args...) })
+
+	prober := probe.NewProber(probe.ShellRunner{}, probe.Options{
+		WanPingTarget: cfg.wanTarget,
+		GwPingTarget:  cfg.gwTarget,
+	})
+
+	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
+	defer stop()
+
+	log.Printf("[netpulse-agent] v%s · %s → %s cada %s", Version, cfg.slug, cfg.server, cfg.interval)
+	for {
+		payload := prober.Build(ctx, cfg.slug, Version)
+		if err := client.Push(ctx, payload); err != nil {
+			log.Printf("[netpulse-agent] push falló (%v); buffered=%d descartados=%d",
+				err, client.Buffered(), client.Dropped())
+		}
+		select {
+		case <-ctx.Done():
+			log.Printf("[netpulse-agent] saliendo")
+			return nil
+		case <-time.After(client.Delay(cfg.interval)):
+		}
+	}
+}

+ 30 - 0
agent/deploy/netpulse-agent.init

@@ -0,0 +1,30 @@
+#!/bin/sh /etc/rc.common
+# =============================================================================
+# netpulse-agent — agente nativo NetPulse para OpenWrt (SPEC-AGENTE-PILOTO §2)
+#
+# procd con respawn; logs del agente (stderr) van a syslog (logread -e
+# netpulse-agent). La config vive en /etc/netpulse-agent.env (chmod 600) —
+# procd reinicia el servicio si ese fichero cambia (procd_set_param file).
+#
+# Variante /tmp (equipos con flash justa): si el binario no está en
+# /usr/sbin se usa /tmp/netpulse-agent (RAM; hay que reinstalar tras reboot —
+# ver install-agent.sh --tmp).
+# =============================================================================
+
+START=99
+STOP=10
+USE_PROCD=1
+
+BIN=/usr/sbin/netpulse-agent
+[ -x "$BIN" ] || BIN=/tmp/netpulse-agent
+
+start_service() {
+    procd_open_instance netpulse-agent
+    procd_set_param command "$BIN"
+    # respawn: si muere, procd lo levanta (5 s entre intentos, 5 intentos/hora)
+    procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
+    procd_set_param stdout 1
+    procd_set_param stderr 1
+    procd_set_param file /etc/netpulse-agent.env
+    procd_close_instance
+}

+ 3 - 0
agent/go.mod

@@ -0,0 +1,3 @@
+module github.com/gnacho/netpulse/agent
+
+go 1.25.0

+ 190 - 0
agent/internal/push/push.go

@@ -0,0 +1,190 @@
+// Package push — cliente HTTPS del agente (SPEC-AGENTE-PILOTO §2): POST del
+// payload a /api/ingest/agent con Bearer; si falla, backoff exponencial
+// 5 s → 5 min y buffer en RAM acotado (cap 100, drop-oldest + contador en
+// log; mismo patrón que el fix del buffer del collector). Stateless: el
+// buffer vive SOLO en memoria (nada en flash).
+package push
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+const (
+	// MinBackoff / MaxBackoff: 5 s → 5 min (SPEC §2).
+	MinBackoff = 5 * time.Second
+	MaxBackoff = 5 * time.Minute
+	// BufferCap: payloads retenidos en RAM durante una caída del servidor.
+	BufferCap = 100
+)
+
+// Client empuja payloads con token, backoff y buffer acotado.
+type Client struct {
+	url   string
+	token string
+	hc    *http.Client
+
+	minBackoff time.Duration
+	maxBackoff time.Duration
+	bufCap     int
+	logf       func(string, ...any)
+
+	mu      sync.Mutex
+	backoff time.Duration
+	buf     []*probe.Payload
+	dropped uint64
+}
+
+// New crea el cliente contra serverURL (p. ej. "https://192.168.8.1:3000")
+// con el token del equipo. hc nil → cliente por defecto con timeout 10 s.
+func New(serverURL, token string, hc *http.Client) *Client {
+	if hc == nil {
+		hc = &http.Client{Timeout: 10 * time.Second}
+	}
+	return &Client{
+		url:        serverURL + "/api/ingest/agent",
+		token:      token,
+		hc:         hc,
+		minBackoff: MinBackoff, maxBackoff: MaxBackoff, bufCap: BufferCap,
+		logf: func(string, ...any) {},
+	}
+}
+
+// SetBackoffBounds ajusta los límites (tests; producción usa 5 s→5 min).
+func (c *Client) SetBackoffBounds(min, max time.Duration) { c.minBackoff, c.maxBackoff = min, max }
+
+// SetBufferCap ajusta el cap del buffer (tests).
+func (c *Client) SetBufferCap(n int) { c.bufCap = n }
+
+// SetLogger enchufa el log (stderr en producción).
+func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
+
+// Dropped: payloads descartados por buffer lleno (drop-oldest).
+func (c *Client) Dropped() uint64 {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	return c.dropped
+}
+
+// Buffered: payloads pendientes de envío.
+func (c *Client) Buffered() int {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	return len(c.buf)
+}
+
+// Delay: cuánto dormir hasta el próximo ciclo (max(interval, backoff)).
+func (c *Client) Delay(interval time.Duration) time.Duration {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	if c.backoff > interval {
+		return c.backoff
+	}
+	return interval
+}
+
+// Push envía el payload; si hay buffer pendiente lo drena primero (FIFO:
+// los payloads llevan su propio ts). Devuelve error si el payload quedó
+// buffered sin confirmar (el caller duerme Delay y reintenta en el próximo
+// ciclo — el payload NO se pierde mientras quepa en el buffer).
+func (c *Client) Push(ctx context.Context, p *probe.Payload) error {
+	c.mu.Lock()
+	if len(c.buf) > 0 {
+		// Hay pendientes: drena primero (FIFO) y luego envía el nuevo; si el
+		// drenado falla, el nuevo entra al buffer (drop-oldest si está lleno).
+		if err := c.flushLocked(ctx); err != nil {
+			c.enqueueLocked(p)
+			c.mu.Unlock()
+			return err
+		}
+		if err := c.post(ctx, p); err != nil {
+			c.enqueueLocked(p)
+			c.growBackoffLocked()
+			c.mu.Unlock()
+			return err
+		}
+		c.mu.Unlock()
+		return nil
+	}
+	c.mu.Unlock()
+
+	if err := c.post(ctx, p); err != nil {
+		c.mu.Lock()
+		c.enqueueLocked(p)
+		c.growBackoffLocked()
+		c.mu.Unlock()
+		return err
+	}
+	c.mu.Lock()
+	c.backoff = 0
+	c.mu.Unlock()
+	return nil
+}
+
+// enqueueLocked mete en el buffer con drop-oldest + contador en log.
+func (c *Client) enqueueLocked(p *probe.Payload) {
+	if len(c.buf) >= c.bufCap {
+		c.buf = c.buf[1:]
+		c.dropped++
+		c.logf("[netpulse-agent] buffer lleno (%d): descartado el payload más viejo (total descartados: %d)", c.bufCap, c.dropped)
+	}
+	c.buf = append(c.buf, p)
+}
+
+// flushLocked intenta drenar el buffer en orden; para al primer fallo.
+func (c *Client) flushLocked(ctx context.Context) error {
+	for len(c.buf) > 0 {
+		if err := c.post(ctx, c.buf[0]); err != nil {
+			c.growBackoffLocked()
+			return err
+		}
+		c.buf = c.buf[1:]
+	}
+	c.backoff = 0
+	c.logf("[netpulse-agent] buffer drenado tras reconexión")
+	return nil
+}
+
+// growBackoffLocked: 5 s → 10 → 20 → … → 5 min (cap).
+func (c *Client) growBackoffLocked() {
+	if c.backoff == 0 {
+		c.backoff = c.minBackoff
+		return
+	}
+	c.backoff *= 2
+	if c.backoff > c.maxBackoff {
+		c.backoff = c.maxBackoff
+	}
+}
+
+// post hace el POST con Bearer; error si no hay 2xx.
+func (c *Client) post(ctx context.Context, p *probe.Payload) error {
+	body, err := json.Marshal(p)
+	if err != nil {
+		return err
+	}
+	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+c.token)
+	res, err := c.hc.Do(req)
+	if err != nil {
+		return err
+	}
+	defer res.Body.Close()
+	_, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16))
+	if res.StatusCode < 200 || res.StatusCode > 299 {
+		return fmt.Errorf("ingest HTTP %d", res.StatusCode)
+	}
+	return nil
+}

+ 152 - 0
agent/internal/push/push_test.go

@@ -0,0 +1,152 @@
+// push_test.go — cliente push contra httptest (SPEC-AGENTE-PILOTO §2):
+// Bearer en cada POST, backoff 5s→5m con reset al éxito, buffer RAM cap con
+// drop-oldest + contador, y drenado FIFO al reconectar.
+package push
+
+import (
+	"context"
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+type sink struct {
+	mu       sync.Mutex
+	tokens   []string
+	payloads []probe.Payload
+	fail     bool
+}
+
+func (s *sink) handler(w http.ResponseWriter, r *http.Request) {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	s.tokens = append(s.tokens, r.Header.Get("Authorization"))
+	if s.fail {
+		w.WriteHeader(http.StatusServiceUnavailable)
+		return
+	}
+	var p probe.Payload
+	body, _ := io.ReadAll(r.Body)
+	if err := json.Unmarshal(body, &p); err != nil {
+		w.WriteHeader(http.StatusBadRequest)
+		return
+	}
+	s.payloads = append(s.payloads, p)
+	w.WriteHeader(http.StatusAccepted)
+}
+
+func mkPayload(ts int64) *probe.Payload {
+	return &probe.Payload{Router: "patio", Ts: ts, Version: "0.1.0"}
+}
+
+func TestPushEnviaBearer(t *testing.T) {
+	s := &sink{}
+	srv := httptest.NewServer(http.HandlerFunc(s.handler))
+	defer srv.Close()
+	c := New(srv.URL, "tok123", srv.Client())
+	if err := c.Push(context.Background(), mkPayload(1)); err != nil {
+		t.Fatalf("push: %v", err)
+	}
+	if len(s.tokens) != 1 || s.tokens[0] != "Bearer tok123" {
+		t.Fatalf("Authorization: %v", s.tokens)
+	}
+	if s.payloads[0].Router != "patio" || s.payloads[0].Version != "0.1.0" {
+		t.Fatalf("payload: %+v", s.payloads[0])
+	}
+}
+
+func TestPushBackoffCreceYSeResetea(t *testing.T) {
+	s := &sink{fail: true}
+	srv := httptest.NewServer(http.HandlerFunc(s.handler))
+	defer srv.Close()
+	c := New(srv.URL, "tok", srv.Client())
+	c.SetBackoffBounds(5*time.Second, 5*time.Minute)
+	interval := 15 * time.Second
+
+	// 1er fallo → backoff 5s (Delay sigue siendo el intervalo, 15s > 5s)
+	_ = c.Push(context.Background(), mkPayload(1))
+	if d := c.Delay(interval); d != interval {
+		t.Fatalf("delay 1er fallo: %s", d)
+	}
+	// 2º fallo → 10 s; 3º → 20 s (> intervalo, Delay manda el backoff)
+	_ = c.Push(context.Background(), mkPayload(2))
+	_ = c.Push(context.Background(), mkPayload(3))
+	if d := c.Delay(interval); d != 20*time.Second {
+		t.Fatalf("backoff tras 3 fallos: %s", d)
+	}
+	// Cap 5 min: muchos fallos seguidos no lo superan
+	for i := 0; i < 20; i++ {
+		_ = c.Push(context.Background(), mkPayload(int64(i)))
+	}
+	if d := c.Delay(interval); d != 5*time.Minute {
+		t.Fatalf("cap backoff: %s", d)
+	}
+	// Éxito → reset: el buffer se drena y Delay vuelve al intervalo
+	s.mu.Lock()
+	s.fail = false
+	s.mu.Unlock()
+	if err := c.Push(context.Background(), mkPayload(999)); err != nil {
+		t.Fatalf("push tras recuperación: %v", err)
+	}
+	if d := c.Delay(interval); d != interval {
+		t.Fatalf("delay tras éxito: %s", d)
+	}
+	if c.Buffered() != 0 {
+		t.Fatalf("buffer debería estar drenado: %d", c.Buffered())
+	}
+}
+
+func TestPushBufferDropOldestYDrenadoFIFO(t *testing.T) {
+	s := &sink{fail: true}
+	srv := httptest.NewServer(http.HandlerFunc(s.handler))
+	defer srv.Close()
+	c := New(srv.URL, "tok", srv.Client())
+	c.SetBufferCap(100)
+
+	// Servidor caído: 105 pushes → buffer 100, 5 descartados (los más viejos)
+	for i := 1; i <= 105; i++ {
+		_ = c.Push(context.Background(), mkPayload(int64(i)))
+	}
+	if c.Buffered() != 100 {
+		t.Fatalf("buffer: %d", c.Buffered())
+	}
+	if c.Dropped() != 5 {
+		t.Fatalf("descartados: %d", c.Dropped())
+	}
+
+	// Reconexión: drenado FIFO — el primer ts recibido tras la caída es 6
+	s.mu.Lock()
+	s.fail = false
+	s.payloads = nil
+	s.mu.Unlock()
+	if err := c.Push(context.Background(), mkPayload(106)); err != nil {
+		t.Fatalf("drenado: %v", err)
+	}
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	if len(s.payloads) != 101 {
+		t.Fatalf("drenados: %d", len(s.payloads))
+	}
+	if s.payloads[0].Ts != 6 || s.payloads[100].Ts != 106 {
+		t.Fatalf("orden FIFO: primero=%d último=%d", s.payloads[0].Ts, s.payloads[100].Ts)
+	}
+}
+
+func TestPushErrorNo2xx(t *testing.T) {
+	s := &sink{fail: true} // 503
+	srv := httptest.NewServer(http.HandlerFunc(s.handler))
+	defer srv.Close()
+	c := New(srv.URL, "tok", srv.Client())
+	if err := c.Push(context.Background(), mkPayload(1)); err == nil {
+		t.Fatal("503 debería devolver error")
+	}
+	if c.Buffered() != 1 {
+		t.Fatalf("payload debería quedar buffered: %d", c.Buffered())
+	}
+}

+ 249 - 0
agent/probe/local.go

@@ -0,0 +1,249 @@
+// local.go — prober local del agente: ejecuta EN EL ROUTER los mismos
+// comandos que el servidor lanza por SSH (constantes Cmd* de probe.go) y
+// construye el Payload con los shapes parseados. Cada sonda es best-effort:
+// si un comando no existe (ubus, iwinfo, brctl...) la sección queda ausente
+// y el servidor conserva el último dato bueno (anti-parpadeo).
+package probe
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"os/exec"
+	"strings"
+	"time"
+)
+
+// Runner ejecuta un comando de shell local y devuelve su stdout.
+// timeout 0 = default corto de sonda.
+type Runner interface {
+	Run(ctx context.Context, cmd string, timeout time.Duration) (string, error)
+}
+
+// ShellRunner ejecuta con /bin/sh -c (BusyBox ash en OpenWrt).
+type ShellRunner struct {
+	DefaultTimeout time.Duration
+}
+
+// Run implementa Runner.
+func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) {
+	if timeout <= 0 {
+		timeout = s.DefaultTimeout
+		if timeout <= 0 {
+			timeout = 5 * time.Second
+		}
+	}
+	cctx, cancel := context.WithTimeout(ctx, timeout)
+	defer cancel()
+	out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output()
+	if err != nil {
+		return "", err
+	}
+	return string(out), nil
+}
+
+// Options configura las sondas opcionales del prober.
+type Options struct {
+	// WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway.
+	WanPingTarget string
+	// GwPingTarget: si no está vacío, ping corto al gateway (latencia) — AP.
+	GwPingTarget string
+}
+
+// Prober sondea el equipo local y construye payloads. Mantiene el estado de
+// deltas (/proc/stat y /proc/net/dev) entre muestras — es el único estado
+// del agente y vive solo en RAM.
+type Prober struct {
+	run  Runner
+	opts Options
+
+	lastStat   *CPUSample
+	lastNetRx  float64
+	lastNetTx  float64
+	lastNetAt  time.Time
+	hasLastNet bool
+}
+
+// NewProber crea el prober con el runner dado.
+func NewProber(run Runner, opts Options) *Prober {
+	return &Prober{run: run, opts: opts}
+}
+
+// runBest es best-effort: error → "" (la sección queda ausente).
+func (p *Prober) runBest(ctx context.Context, cmd string, timeout time.Duration) string {
+	out, err := p.run.Run(ctx, cmd, timeout)
+	if err != nil {
+		return ""
+	}
+	return out
+}
+
+// Build ejecuta una ronda de sondas y devuelve el payload listo para empujar.
+// router/version los rellena el caller (main) o van aquí por comodidad.
+func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
+	pl := &Payload{
+		Router:  router,
+		Ts:      time.Now().Unix(),
+		Version: version,
+	}
+	pl.Data.System = p.probeSystem(ctx)
+	pl.Data.Wireless = p.probeWireless(ctx)
+	pl.Data.DHCP = p.probeDHCP(ctx)
+	pl.Data.FDB = p.probeFDB(ctx)
+	return pl
+}
+
+// probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC
+// del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin
+// ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests).
+func (p *Prober) probeSystem(ctx context.Context) *SystemData {
+	sd := &SystemData{}
+	any := false
+
+	if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" {
+		var si SysInfo
+		if err := json.Unmarshal([]byte(out), &si); err == nil {
+			sd.SysInfo = &si
+			any = true
+		}
+	}
+	if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" {
+		var b BoardInfo
+		if err := json.Unmarshal([]byte(out), &b); err == nil {
+			sd.Board = &b
+			any = true
+		}
+	}
+
+	if out := p.runBest(ctx, CmdProcStat, 0); out != "" {
+		if cur, err := ParseProcStat(out); err == nil {
+			if p.lastStat != nil {
+				sd.CPU = CPUPercent(*p.lastStat, cur)
+			}
+			c := cur
+			p.lastStat = &c
+			any = true
+		}
+	}
+	if out := p.runBest(ctx, CmdTemp, 0); out != "" {
+		sd.Temp = ParseTempC(out)
+		any = true
+	}
+	if out := p.runBest(ctx, CmdNetDev, 0); out != "" {
+		rx, tx := ParseNetDev(out)
+		now := time.Now()
+		if p.hasLastNet {
+			sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds())
+		}
+		p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true
+		any = true
+	}
+
+	if p.opts.WanPingTarget != "" {
+		out := p.runBest(ctx, fmt.Sprintf(CmdPingWan, p.opts.WanPingTarget), 10*time.Second)
+		sd.LatencyMs, sd.LossPct = ParsePingSummary(out)
+		any = true
+	} else if p.opts.GwPingTarget != "" {
+		out := p.runBest(ctx, fmt.Sprintf(CmdPingGateway, p.opts.GwPingTarget), 10*time.Second)
+		sd.LatencyMs, _ = ParsePingSummary(out)
+		any = true
+	}
+
+	if out := p.runBest(ctx, CmdUbusWireless, 0); out != "" {
+		if wifi, err := ParseWirelessUplink([]byte(out)); err == nil {
+			sd.Backhaul = "cable"
+			if wifi {
+				sd.Backhaul = "wifi"
+			}
+			any = true
+		}
+	}
+	if out := p.runBest(ctx, CmdBridgeMAC, 0); out != "" {
+		sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out))
+		any = true
+	}
+
+	if !any {
+		return nil
+	}
+	return sd
+}
+
+// probeWireless: clientes asociados (iwinfo assoclist) + radios por banda.
+// nil si iwinfo no existe en el equipo.
+func (p *Prober) probeWireless(ctx context.Context) *WirelessData {
+	wd := &WirelessData{}
+	any := false
+	if out := p.runBest(ctx, CmdIwinfoAssoc, 8*time.Second); out != "" {
+		wd.Clients = ParseWirelessClients(out)
+		any = true
+	}
+	if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" {
+		wd.Radios = ParseRadios(out)
+		any = true
+	}
+	if !any {
+		return nil
+	}
+	if wd.Clients == nil {
+		wd.Clients = map[string]WirelessClient{}
+	}
+	if wd.Radios == nil {
+		wd.Radios = []Radio{}
+	}
+	return wd
+}
+
+// probeDHCP: ubus dhcp ipv4leases con fallback a /tmp/dhcp.leases.
+func (p *Prober) probeDHCP(ctx context.Context) *DHCPData {
+	if out := p.runBest(ctx, CmdDhcpUbus, 0); out != "" {
+		if leases, err := ParseDhcpUbus([]byte(out)); err == nil {
+			return &DHCPData{Leases: leases}
+		}
+	}
+	out := p.runBest(ctx, CmdDhcpFile, 0)
+	if out == "" {
+		return nil
+	}
+	return &DHCPData{Leases: ParseDhcpLeasesFile(out)}
+}
+
+// probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys).
+func (p *Prober) probeFDB(ctx context.Context) *FDBData {
+	fd := &FDBData{}
+	any := false
+	if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
+		fd.MACs = ParseBridgeFdb(out)
+		any = true
+	}
+	statesOut := p.runBest(ctx, CmdPortStates, 0)
+	if statesOut != "" {
+		states := ParsePortStates(statesOut)
+		layout := []PortLayout{}
+		if out := p.runBest(ctx, CmdBoardJSON, 0); out != "" {
+			if lay, err := ParsePortLayout(out); err == nil {
+				layout = lay
+			}
+		}
+		members := map[string]bool{}
+		if out := p.runBest(ctx, CmdBrifMembers, 0); out != "" {
+			for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
+				if l != "" {
+					members[l] = true
+				}
+			}
+		}
+		fd.Ports = BuildEthPorts(layout, states, members)
+		any = true
+	}
+	if !any {
+		return nil
+	}
+	if fd.MACs == nil {
+		fd.MACs = map[string]string{}
+	}
+	if fd.Ports == nil {
+		fd.Ports = []EthPort{}
+	}
+	return fd
+}

+ 54 - 0
agent/probe/payload.go

@@ -0,0 +1,54 @@
+// payload.go — wire format de POST /api/ingest/agent (SPEC-AGENTE-PILOTO §1).
+// `data` lleva los shapes PARSEADOS de las sondas de este package (los mismos
+// que produce el sondeo SSH de internal/adapters/openwrt.go), para que el
+// pipeline del servidor (snapshot → SSE → persistencia) no cambie.
+package probe
+
+// Payload es el cuerpo JSON único que el agente empuja cada intervalo.
+type Payload struct {
+	Router  string      `json:"router"`  // slug del equipo (token agent.token.<slug>)
+	Ts      int64       `json:"ts"`      // unix SEGUNDOS de la muestra
+	Version string      `json:"version"` // versión del agente (la muestra GET /api/agents)
+	Data    PayloadData `json:"data"`
+}
+
+// PayloadData agrupa las 4 secciones del tier rápido. Punteros/mapas nil =
+// sonda fallida en este push (el servidor conserva el último dato bueno,
+// mismo anti-parpadeo que el pipeline SSH).
+type PayloadData struct {
+	System   *SystemData   `json:"system,omitempty"`
+	Wireless *WirelessData `json:"wireless,omitempty"`
+	DHCP     *DHCPData     `json:"dhcp,omitempty"`
+	FDB      *FDBData      `json:"fdb,omitempty"`
+}
+
+// SystemData: salud del equipo + tráfico + latencias.
+type SystemData struct {
+	SysInfo   *SysInfo   `json:"sysinfo,omitempty"`
+	Board     *BoardInfo `json:"board,omitempty"`
+	CPU       *int       `json:"cpu"`  // null en la primera muestra (delta /proc/stat)
+	Temp      *int       `json:"temp"` // null si no hay thermal zone
+	RxBps     *float64   `json:"rxBps"`
+	TxBps     *float64   `json:"txBps"`
+	LatencyMs *float64   `json:"latencyMs"`           // gateway: ping WAN; AP: ping al gateway
+	LossPct   *float64   `json:"lossPct"`             // solo gateway (ping WAN)
+	Backhaul  string     `json:"backhaul,omitempty"`  // "cable"|"wifi" (ausente = desconocido)
+	BridgeMAC string     `json:"bridgeMac,omitempty"` // MAC de br-lan (uplinks/topología)
+}
+
+// WirelessData: clientes asociados + radios agregadas por banda.
+type WirelessData struct {
+	Clients map[string]WirelessClient `json:"clients"` // {} = sin clientes; sección ausente = sonda fallida
+	Radios  []Radio                   `json:"radios"`
+}
+
+// DHCPData: leases ipv4 (mac en mayúsculas).
+type DHCPData struct {
+	Leases []DhcpLease `json:"leases"`
+}
+
+// FDBData: MAC aprendida → puerto del bridge + puertos ethernet.
+type FDBData struct {
+	MACs  map[string]string `json:"macs"` // {} = sin entradas; ausente = sonda fallida
+	Ports []EthPort         `json:"ports"`
+}

+ 582 - 0
agent/probe/probe.go

@@ -0,0 +1,582 @@
+// Package probe — sondas del tier rápido OpenWrt: comandos (los LITERALES que
+// internal/adapters/openwrt.go lanza por SSH) + parseo de sus salidas +
+// shapes JSON del payload que el agente empuja a POST /api/ingest/agent.
+//
+// Es la ÚNICA fuente de verdad del parseo: server-go (internal/adapters) lo
+// importa con un replace ../agent, y el binario netpulse-agent ejecuta los
+// mismos comandos localmente. Solo stdlib (el binario del agente tiene
+// objetivo ≤ 3 MB y CGO_ENABLED=0).
+package probe
+
+import (
+	"encoding/json"
+	"fmt"
+	"regexp"
+	"sort"
+	"strconv"
+	"strings"
+)
+
+// ---------------------------------------------------------------------------
+// Comandos (idénticos a los del sondeo SSH de openwrt.go)
+// ---------------------------------------------------------------------------
+
+const (
+	CmdProcStat = "grep '^cpu ' /proc/stat"
+	CmdTemp     = `for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && cat "$f" && break; done`
+	CmdNetDev   = "cat /proc/net/dev | tail -n +3"
+	// CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target.
+	CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2"
+	// CmdPingGateway: ping corto al gateway desde un AP. %s = host gateway.
+	CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1"
+	CmdDhcpUbus    = "ubus call dhcp ipv4leases"
+	CmdDhcpFile    = "cat /tmp/dhcp.leases 2>/dev/null || true"
+	// CmdIwinfoAssoc: "<mac> <sig> <freq>" por cliente wifi asociado.
+	CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
+		`freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
+		`iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do ` +
+		`echo "$mac $sig $freq"; done; done`
+	// CmdRadios: "freq|ch|ht|tx|n" por radio (se agrega por banda al parsear).
+	CmdRadios = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
+		`info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
+		`echo "$info" | grep -q ESSID || continue; ` +
+		`freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
+		`ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
+		`ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
+		`tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
+		`n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); ` +
+		`echo "$freq|$ch|$ht|$tx|$n"; done`
+	// CmdPortStates: "<name> <operstate> <speed>" por interfaz.
+	CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
+		`echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1)"; done`
+	CmdBoardJSON   = "cat /etc/board.json 2>/dev/null"
+	CmdBrifMembers = "ls /sys/class/net/br-lan/brif/ 2>/dev/null"
+	// CmdBridgeFDB: "==PORTS==" (port_no ifname) + "==MACS==" (port mac).
+	CmdBridgeFDB = `echo "==PORTS=="; for d in /sys/class/net/br-lan/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; ` +
+		`echo "==MACS=="; brctl showmacs br-lan 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}'`
+	CmdBridgeMAC       = "cat /sys/class/net/br-lan/address 2>/dev/null"
+	CmdUbusSystemBoard = "ubus call system board"
+	CmdUbusSystemInfo  = "ubus call system info"
+	CmdUbusWireless    = "ubus call network.wireless status"
+)
+
+// ---------------------------------------------------------------------------
+// Shapes parseados (salida de las sondas; contrato del payload del agente)
+// ---------------------------------------------------------------------------
+
+// SysInfo: ubus system info (uptime, memoria, load).
+type SysInfo struct {
+	Uptime float64   `json:"uptime"`
+	Load   []float64 `json:"load"`
+	Memory struct {
+		Total     float64 `json:"total"`
+		Free      float64 `json:"free"`
+		Buffered  float64 `json:"buffered"`
+		Available float64 `json:"available"`
+	} `json:"memory"`
+}
+
+// BoardInfo: ubus system board (metadatos estáticos).
+type BoardInfo struct {
+	Model    string `json:"model"`
+	Hostname string `json:"hostname"`
+	System   string `json:"system"`
+	Release  struct {
+		Version     string `json:"version"`
+		Description string `json:"description"`
+	} `json:"release"`
+}
+
+// DhcpLease es {mac, ip, hostname} (mac en mayúsculas).
+type DhcpLease struct {
+	MAC      string `json:"mac"`
+	IP       string `json:"ip"`
+	Hostname string `json:"hostname"`
+}
+
+// WirelessClient es {signalDbm, band} por MAC.
+type WirelessClient struct {
+	SignalDbm int    `json:"signalDbm"`
+	Band      string `json:"band"`
+}
+
+// PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
+type PortState struct {
+	Name  string `json:"name"`
+	Up    bool   `json:"up"`
+	Speed string `json:"speed"` // "1 Gbps" | "100 Mbps" | "—"
+}
+
+// PortLayout es una boca del layout canónico (/etc/board.json).
+type PortLayout struct {
+	ID    string `json:"id"`
+	Name  string `json:"name"`
+	Label string `json:"label"`
+	Role  string `json:"role"` // "lan" | "wan"
+}
+
+// EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}).
+type EthPort struct {
+	ID    string `json:"id"`
+	Label string `json:"label"`
+	Up    bool   `json:"up"`
+	Speed string `json:"speed,omitempty"` // solo si up
+}
+
+// Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
+type Radio struct {
+	Name     string  `json:"name"` // "5 GHz"|"2.4 GHz"
+	Channel  int     `json:"channel"`
+	WidthMhz int     `json:"widthMhz"`
+	PowerDbm float64 `json:"powerDbm"`
+	Clients  int     `json:"clients"`
+}
+
+// ---------------------------------------------------------------------------
+// Sistema: /proc/stat, thermal, /proc/net/dev, ping
+// ---------------------------------------------------------------------------
+
+// CPUSample es la muestra agregada de "cpu " de /proc/stat.
+type CPUSample struct{ Total, IdleAll float64 }
+
+// ParseProcStat parsea "cpu  user nice system idle iowait irq softirq ...".
+func ParseProcStat(out string) (CPUSample, error) {
+	fields := strings.Fields(strings.TrimSpace(out))
+	if len(fields) < 5 || fields[0] != "cpu" {
+		return CPUSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
+	}
+	nums := make([]float64, 0, len(fields)-1)
+	for _, f := range fields[1:] {
+		n, err := strconv.ParseFloat(f, 64)
+		if err != nil {
+			n = 0
+		}
+		nums = append(nums, n)
+	}
+	get := func(i int) float64 {
+		if i < len(nums) {
+			return nums[i]
+		}
+		return 0
+	}
+	idleAll := get(3) + get(4)                            // idle + iowait
+	nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
+	return CPUSample{Total: idleAll + nonIdle, IdleAll: idleAll}, nil
+}
+
+// CPUPercent: % de CPU por delta de muestras (nil si no hay delta válido:
+// primera muestra o contadores reseteados).
+func CPUPercent(prev, cur CPUSample) *int {
+	dTotal := cur.Total - prev.Total
+	dIdle := cur.IdleAll - prev.IdleAll
+	if dTotal <= 0 {
+		return nil
+	}
+	v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
+	return &v
+}
+
+// ParseTempC: °C del primer thermal zone (nil si la salida no es un entero).
+func ParseTempC(out string) *int {
+	milli, err := strconv.Atoi(strings.TrimSpace(out))
+	if err != nil {
+		return nil
+	}
+	v := milli / 1000
+	if milli%1000 >= 500 {
+		v++
+	}
+	return &v
+}
+
+var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
+
+// ParseNetDev suma rx/tx de las interfaces físicas (excluye lo, bridges,
+// ifb, wg, tun/tap para no duplicar contadores).
+func ParseNetDev(out string) (rx, tx float64) {
+	lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		m := lineRe.FindStringSubmatch(line)
+		if m == nil || netdevSkipRe.MatchString(m[1]) {
+			continue
+		}
+		fields := strings.Fields(strings.TrimSpace(m[2]))
+		num := func(i int) float64 {
+			if i < len(fields) {
+				n, _ := strconv.ParseFloat(fields[i], 64)
+				return n
+			}
+			return 0
+		}
+		rx += num(0)
+		tx += num(8)
+	}
+	return rx, tx
+}
+
+// NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o
+// contadores reseteados).
+func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) {
+	if dt <= 0 {
+		return nil, nil
+	}
+	rb := round0(max0((rx - prevRx) * 8 / dt))
+	tb := round0(max0((tx - prevTx) * 8 / dt))
+	return &rb, &tb
+}
+
+var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
+var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)/[\d.]+/[\d.]+ ms`)
+
+// ParsePingSummary extrae (latencia avg redondeada, pérdida %) del resumen de
+// ping; cada una es nil si su línea no está.
+func ParsePingSummary(out string) (latency, loss *float64) {
+	if m := pingRTTRe.FindStringSubmatch(out); m != nil {
+		v, _ := strconv.ParseFloat(m[1], 64)
+		v = float64(int(v + 0.5))
+		latency = &v
+	}
+	if m := pingLossRe.FindStringSubmatch(out); m != nil {
+		v, _ := strconv.ParseFloat(m[1], 64)
+		loss = &v
+	}
+	return latency, loss
+}
+
+// ---------------------------------------------------------------------------
+// Clientes (DHCP + wireless)
+// ---------------------------------------------------------------------------
+
+// ParseDhcpUbus parsea la respuesta de `ubus call dhcp ipv4leases`
+// ({lease: [...]} o {leases: [...]}). Error si no es JSON con esas claves.
+func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
+	type leaseJSON struct {
+		MAC      string `json:"mac"`
+		IPAddr   string `json:"ip-address"`
+		IP       string `json:"ip"`
+		Hostname string `json:"hostname"`
+	}
+	var data struct {
+		Lease  []leaseJSON `json:"lease"`
+		Leases []leaseJSON `json:"leases"`
+	}
+	if err := json.Unmarshal(raw, &data); err != nil {
+		return nil, err
+	}
+	leases := data.Lease
+	if leases == nil {
+		leases = data.Leases
+	}
+	if leases == nil {
+		return nil, fmt.Errorf("ubus dhcp: sin clave lease/leases")
+	}
+	out := make([]DhcpLease, 0, len(leases))
+	for _, l := range leases {
+		ip := l.IPAddr
+		if ip == "" {
+			ip = l.IP
+		}
+		out = append(out, DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname})
+	}
+	return out, nil
+}
+
+// ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
+// <expiry> <mac> <ip> <hostname> <clientid>
+func ParseDhcpLeasesFile(out string) []DhcpLease {
+	leases := []DhcpLease{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 3 {
+			continue
+		}
+		hostname := ""
+		if len(p) > 3 && p[3] != "*" {
+			hostname = p[3]
+		}
+		leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname})
+	}
+	return leases
+}
+
+// ParseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
+func ParseWirelessClients(out string) map[string]WirelessClient {
+	m := map[string]WirelessClient{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 2 {
+			continue
+		}
+		freq := 0.0
+		if len(p) > 2 {
+			freq, _ = strconv.ParseFloat(p[2], 64)
+		}
+		sig, _ := strconv.Atoi(p[1])
+		band := "2.4 GHz"
+		if freq >= 5 {
+			band = "5 GHz"
+		}
+		m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
+	}
+	return m
+}
+
+// ParseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
+// up e ifname asignado = asociada) → uplink inalámbrico. Tolerante con
+// radios/entradas raras; error si la respuesta no es JSON.
+func ParseWirelessUplink(raw []byte) (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
+// ---------------------------------------------------------------------------
+
+// ParsePortStates parsea líneas "<name> <operstate> <speed>".
+func ParsePortStates(out string) []PortState {
+	ports := []PortState{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 3 {
+			continue
+		}
+		mbps, _ := strconv.Atoi(p[2])
+		speed := "—"
+		if mbps > 0 {
+			if mbps >= 1000 {
+				speed = strconv.Itoa(mbps/1000) + " Gbps"
+			} else {
+				speed = strconv.Itoa(mbps) + " Mbps"
+			}
+		}
+		ports = append(ports, PortState{Name: p[0], Up: p[1] == "up", Speed: speed})
+	}
+	return ports
+}
+
+// ParsePortLayout parsea board.json → [{id, name, label, role}] (WAN
+// normalizado a id 'wan').
+func ParsePortLayout(out string) ([]PortLayout, error) {
+	var board struct {
+		Network struct {
+			Lan struct {
+				Ports []string `json:"ports"`
+			} `json:"lan"`
+			Wan struct {
+				Device string `json:"device"`
+			} `json:"wan"`
+		} `json:"network"`
+	}
+	if err := json.Unmarshal([]byte(out), &board); err != nil {
+		return nil, err
+	}
+	ports := []PortLayout{}
+	for _, name := range board.Network.Lan.Ports {
+		ports = append(ports, PortLayout{ID: name, Name: name, Label: strings.Replace(name, "lan", "LAN ", 1), Role: "lan"})
+	}
+	if wanDev := board.Network.Wan.Device; wanDev != "" {
+		ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
+	}
+	return ports, nil
+}
+
+// BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
+// brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
+// N+1); sin layout, fallback heurístico. Literal de openwrt.go GetEthPorts.
+func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool) []EthPort {
+	byName := map[string]PortState{}
+	for _, p := range states {
+		byName[p.Name] = p
+	}
+	if len(layout) > 0 {
+		lanCount := 0
+		for _, p := range layout {
+			if p.Role == "lan" {
+				lanCount++
+			}
+		}
+		ports := make([]EthPort, 0, len(layout))
+		for _, p := range layout {
+			st, ok := byName[p.Name]
+			up := ok && st.Up
+			label := p.Label
+			if p.Role == "wan" && brMembers[p.Name] {
+				label = "LAN " + strconv.Itoa(lanCount+1)
+			}
+			ep := EthPort{ID: p.ID, Label: label, Up: up}
+			if up {
+				ep.Speed = st.Speed
+			}
+			ports = append(ports, ep)
+		}
+		return ports
+	}
+	// Fallback sin config
+	lanRe := regexp.MustCompile(`^lan\d+$`)
+	lans := []PortState{}
+	for _, p := range states {
+		if lanRe.MatchString(p.Name) {
+			lans = append(lans, p)
+		}
+	}
+	sort.Slice(lans, func(i, j int) bool { return NaturalLess(lans[i].Name, lans[j].Name) })
+	ports := make([]EthPort, 0, len(lans)+1)
+	for _, p := range lans {
+		ep := EthPort{ID: p.Name, Label: strings.Replace(p.Name, "lan", "LAN ", 1), Up: p.Up}
+		if p.Up {
+			ep.Speed = p.Speed
+		}
+		ports = append(ports, ep)
+	}
+	wanName := ""
+	if _, ok := byName["wan"]; ok {
+		wanName = "wan"
+	} else if _, ok := byName["pppoe-wan"]; ok {
+		wanName = "eth1"
+	} else if _, ok := byName["eth1"]; ok {
+		wanName = "eth1"
+	}
+	if wanName != "" {
+		st := byName[wanName]
+		ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
+		if st.Up {
+			ep.Speed = st.Speed
+		}
+		ports = append([]EthPort{ep}, ports...)
+	}
+	return ports
+}
+
+// NaturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
+func NaturalLess(a, b string) bool {
+	re := regexp.MustCompile(`^(.*?)(\d+)$`)
+	ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
+	if ma != nil && mb != nil && ma[1] == mb[1] {
+		na, _ := strconv.Atoi(ma[2])
+		nb, _ := strconv.Atoi(mb[2])
+		return na < nb
+	}
+	return a < b
+}
+
+var fdbPortRe = regexp.MustCompile(`^(lan\d+|wan)$`)
+
+// ParseBridgeFdb parsea la salida ==PORTS==/==MACS== → MAC aprendida → puerto.
+func ParseBridgeFdb(out string) map[string]string {
+	m := map[string]string{}
+	portNames := map[string]string{}
+	section := byte(0)
+	for _, line := range strings.Split(out, "\n") {
+		t := strings.TrimSpace(line)
+		if strings.HasPrefix(t, "==PORTS==") {
+			section = 'p'
+			continue
+		}
+		if strings.HasPrefix(t, "==MACS==") {
+			section = 'm'
+			continue
+		}
+		p := strings.Fields(t)
+		if len(p) < 2 {
+			continue
+		}
+		switch section {
+		case 'p':
+			no, name := p[0], p[1]
+			if strings.HasPrefix(no, "0x") {
+				if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
+					no = strconv.FormatInt(n, 10)
+				}
+			}
+			portNames[no] = name
+		case 'm':
+			no, mac := p[0], p[1]
+			if port, ok := portNames[no]; ok && mac != "" && fdbPortRe.MatchString(port) {
+				m[strings.ToUpper(mac)] = port
+			}
+		}
+	}
+	return m
+}
+
+var nonDigitRe = regexp.MustCompile(`\D`)
+
+// ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
+func ParseRadios(out string) []Radio {
+	byBand := map[string]*Radio{}
+	order := []string{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Split(line, "|")
+		if len(p) < 5 {
+			continue
+		}
+		freq, _ := strconv.ParseFloat(p[0], 64)
+		if freq == 0 {
+			continue
+		}
+		band := "2.4 GHz"
+		if freq >= 5 {
+			band = "5 GHz"
+		}
+		width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
+		if width == 0 {
+			width = 20
+		}
+		ch, _ := strconv.Atoi(p[1])
+		tx, _ := strconv.Atoi(p[3])
+		n, _ := strconv.Atoi(p[4])
+		if cur, ok := byBand[band]; ok {
+			cur.Clients += n
+		} else {
+			byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n}
+			order = append(order, band)
+		}
+	}
+	radios := []Radio{}
+	for _, b := range order {
+		radios = append(radios, *byBand[b])
+	}
+	return radios
+}
+
+func round0(v float64) float64 { return float64(int64(v + 0.5)) }
+func max0(v float64) float64 {
+	if v < 0 {
+		return 0
+	}
+	return v
+}

+ 243 - 0
agent/probe/probe_test.go

@@ -0,0 +1,243 @@
+// probe_test.go — parsers sobre fixtures de salidas reales (los MISMOS
+// fixtures que internal/adapters/adapters_test.go del servidor: al compartir
+// package, estos tests son el test cruzado agente↔servidor) + Build del
+// prober local con runner fake.
+package probe
+
+import (
+	"context"
+	"encoding/json"
+	"strings"
+	"testing"
+	"time"
+)
+
+func TestParseProcStat(t *testing.T) {
+	s, err := ParseProcStat("cpu  4705 356 584 3699 23 0 23 0 0 0\n")
+	if err != nil {
+		t.Fatal(err)
+	}
+	idle := float64(3699 + 23)
+	total := idle + float64(4705+356+584+0+23)
+	if s.Total != total || s.IdleAll != idle {
+		t.Fatalf("procstat: %+v", s)
+	}
+	// Delta → porcentaje
+	prev := CPUSample{Total: 1000, IdleAll: 500}
+	cur := CPUSample{Total: 2000, IdleAll: 750}
+	pct := CPUPercent(prev, cur)
+	if pct == nil || *pct != 75 {
+		t.Fatalf("cpu%%: %v", pct)
+	}
+	if CPUPercent(cur, prev) != nil {
+		t.Fatal("contadores reseteados → nil")
+	}
+	if _, err := ParseProcStat("basura"); err == nil {
+		t.Fatal("procstat basura debería dar error")
+	}
+}
+
+func TestParseTempC(t *testing.T) {
+	if v := ParseTempC("43500\n"); v == nil || *v != 44 {
+		t.Fatalf("temp: %v", v)
+	}
+	if ParseTempC("") != nil || ParseTempC("nan") != nil {
+		t.Fatal("temp inválida → nil")
+	}
+}
+
+func TestParseNetDevYBps(t *testing.T) {
+	out := "  eth0: 1000000    0    0    0    0     0          0         0   500000    0\n" +
+		"    lo: 9999999    0    0    0    0     0          0         0  8888888    0\n" +
+		"br-lan: 7000000    0    0    0    0     0          0         0  6000000    0\n" +
+		"  lan1: 2000000    0    0    0    0     0          0         0  1000000    0\n"
+	rx, tx := ParseNetDev(out)
+	if rx != 3000000 || tx != 1500000 { // lo, br-lan excluidos
+		t.Fatalf("netdev: %v/%v", rx, tx)
+	}
+	rxBps, txBps := NetDevBps(1000, 2000, 3000, 6000, 2)
+	if rxBps == nil || *rxBps != 8000 || txBps == nil || *txBps != 16000 {
+		t.Fatalf("bps: %v/%v", rxBps, txBps)
+	}
+	if a, b := NetDevBps(0, 0, 0, 0, 0); a != nil || b != nil {
+		t.Fatal("dt=0 → nil")
+	}
+}
+
+func TestParsePingSummary(t *testing.T) {
+	out := "3 packets transmitted, 3 received, 0% packet loss, time 2003ms\nrtt min/avg/max/mdev = 8.123/9.456/10.999/0.5 ms"
+	lat, loss := ParsePingSummary(out)
+	if lat == nil || *lat != 9 || loss == nil || *loss != 0 {
+		t.Fatalf("ping: %v %v", lat, loss)
+	}
+	if lat, _ := ParsePingSummary("2 packets transmitted, 0 received, 100% packet loss"); lat != nil {
+		t.Fatalf("sin rtt → nil: %v", lat)
+	}
+}
+
+func TestParseDhcp(t *testing.T) {
+	out := "1700000000 aa:bb:cc:dd:ee:ff 192.168.8.21 imac-de-marc 01:aa:bb:cc:dd:ee:ff\n" +
+		"1700000001 11:22:33:44:55:66 192.168.8.34 * *\n"
+	leases := ParseDhcpLeasesFile(out)
+	if len(leases) != 2 || leases[0].MAC != "AA:BB:CC:DD:EE:FF" || leases[0].Hostname != "imac-de-marc" || leases[1].Hostname != "" {
+		t.Fatalf("leases: %+v", leases)
+	}
+	ubus := `{"lease":[{"mac":"aa:bb:cc:dd:ee:ff","ip":"192.168.8.21","hostname":"imac"}]}`
+	leases, err := ParseDhcpUbus([]byte(ubus))
+	if err != nil || len(leases) != 1 || leases[0].IP != "192.168.8.21" {
+		t.Fatalf("ubus dhcp: %v %+v", err, leases)
+	}
+	if _, err := ParseDhcpUbus([]byte("Command failed")); err == nil {
+		t.Fatal("ubus roto debería dar error")
+	}
+}
+
+func TestParseWireless(t *testing.T) {
+	out := "A4:83:E7:21:0B:3C -48 5\nEC:71:DB:44:12:8A -72 2.4\n"
+	m := ParseWirelessClients(out)
+	if len(m) != 2 || m["A4:83:E7:21:0B:3C"].Band != "5 GHz" || m["A4:83:E7:21:0B:3C"].SignalDbm != -48 || m["EC:71:DB:44:12:8A"].Band != "2.4 GHz" {
+		t.Fatalf("wireless: %+v", m)
+	}
+	sta := `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"sta"}}]}}`
+	wifi, err := ParseWirelessUplink([]byte(sta))
+	if err != nil || !wifi {
+		t.Fatalf("sta: %v %v", wifi, err)
+	}
+	ap := `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`
+	wifi, _ = ParseWirelessUplink([]byte(ap))
+	if wifi {
+		t.Fatal("solo AP → cable")
+	}
+}
+
+func TestParsePortsYLayout(t *testing.T) {
+	states := ParsePortStates("eth0 up 2500\nlan1 up 1000\nlan2 down -1\nwlan0 up 0\n")
+	if len(states) != 4 || states[0].Speed != "2 Gbps" || states[2].Up || states[2].Speed != "—" {
+		t.Fatalf("states: %+v", states)
+	}
+	board := `{"network":{"lan":{"ports":["lan1","lan2","lan3","lan4"],"device":"br-lan"},"wan":{"device":"wan","protocol":"dhcp"}}}`
+	layout, err := ParsePortLayout(board)
+	if err != nil || len(layout) != 5 || layout[0].ID != "wan" || layout[1].Label != "LAN 1" {
+		t.Fatalf("layout: %v %+v", err, layout)
+	}
+	// AP en bridge: wan en br-lan → se re-etiqueta LAN 5
+	ports := BuildEthPorts(layout, states, map[string]bool{"wan": true})
+	if len(ports) != 5 || ports[0].Label != "LAN 5" {
+		t.Fatalf("ethports bridge: %+v", ports)
+	}
+	// Sin layout: fallback heurístico
+	ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\n"), nil)
+	if len(ports) != 3 || ports[0].ID != "wan" || ports[1].ID != "lan2" || ports[2].ID != "lan10" {
+		t.Fatalf("ethports fallback: %+v", ports)
+	}
+}
+
+func TestParseFdbYRadios(t *testing.T) {
+	fdb := ParseBridgeFdb("==PORTS==\n0x1 lan1\n0x2 lan2\n==MACS==\n1 aa:bb:cc:dd:ee:ff\n2 11:22:33:44:55:66\n")
+	if len(fdb) != 2 || fdb["AA:BB:CC:DD:EE:FF"] != "lan1" || fdb["11:22:33:44:55:66"] != "lan2" {
+		t.Fatalf("fdb: %+v", fdb)
+	}
+	radios := ParseRadios("2.4|6|HT20|20|3\n5|36|HT80|23|7\n")
+	if len(radios) != 2 || radios[0].Name != "2.4 GHz" || radios[0].Clients != 3 || radios[1].WidthMhz != 80 || radios[1].PowerDbm != 23 {
+		t.Fatalf("radios: %+v", radios)
+	}
+}
+
+// ---------------------------------------------------------------------------
+// Prober local con runner fake
+// ---------------------------------------------------------------------------
+
+type fakeRunner struct{ outs map[string]string }
+
+func (f fakeRunner) Run(_ context.Context, cmd string, _ time.Duration) (string, error) {
+	if out, ok := f.outs[cmd]; ok {
+		return out, nil
+	}
+	return "", &fakeErr{cmd}
+}
+
+type fakeErr struct{ cmd string }
+
+func (e *fakeErr) Error() string { return "no existe: " + e.cmd }
+
+func TestProberBuild(t *testing.T) {
+	run := fakeRunner{outs: map[string]string{
+		CmdUbusSystemInfo:  `{"uptime":90061,"load":[0.1,0.2,0.3],"memory":{"total":256000000,"free":100000000,"buffered":0,"available":128000000}}`,
+		CmdUbusSystemBoard: `{"model":"TP-Link EAP225","hostname":"patio","release":{"version":"23.05","description":"OpenWrt 23.05"}}`,
+		CmdProcStat:        "cpu  4705 356 584 3699 23 0 23 0 0 0\n",
+		CmdTemp:            "43500\n",
+		CmdNetDev:          "  eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
+		CmdBridgeMAC:       "94:83:c4:00:00:09\n",
+		CmdIwinfoAssoc:     "EC:71:DB:44:12:8A -55 2.4\n",
+		CmdRadios:          "2.4|6|HT20|20|1\n",
+		CmdDhcpFile:        "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
+		CmdBridgeFDB:       "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
+		CmdPortStates:      "lan1 up 1000\nwan down -1\n",
+		CmdUbusWireless:    `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`,
+	}}
+	p := NewProber(run, Options{GwPingTarget: "192.168.8.1"})
+
+	// Primera muestra: cpu/net sin delta (null), el resto presente
+	pl := p.Build(context.Background(), "patio", "0.1.0")
+	if pl.Router != "patio" || pl.Version != "0.1.0" || pl.Ts <= 0 {
+		t.Fatalf("cabecera: %+v", pl)
+	}
+	sd := pl.Data.System
+	if sd == nil || sd.SysInfo == nil || sd.SysInfo.Uptime != 90061 || sd.Board.Hostname != "patio" {
+		t.Fatalf("system: %+v", sd)
+	}
+	if sd.CPU != nil || sd.RxBps != nil {
+		t.Fatalf("primera muestra sin delta: %v %v", sd.CPU, sd.RxBps)
+	}
+	if sd.Temp == nil || *sd.Temp != 44 || sd.Backhaul != "cable" || sd.BridgeMAC != "94:83:C4:00:00:09" {
+		t.Fatalf("temp/backhaul/mac: %+v", sd)
+	}
+	if pl.Data.Wireless.Clients["EC:71:DB:44:12:8A"].SignalDbm != -55 || len(pl.Data.Wireless.Radios) != 1 {
+		t.Fatalf("wireless: %+v", pl.Data.Wireless)
+	}
+	if len(pl.Data.DHCP.Leases) != 1 || pl.Data.DHCP.Leases[0].IP != "192.168.8.71" {
+		t.Fatalf("dhcp: %+v", pl.Data.DHCP)
+	}
+	if pl.Data.FDB.MACs["EC:71:DB:44:12:8A"] != "lan1" || len(pl.Data.FDB.Ports) == 0 {
+		t.Fatalf("fdb: %+v", pl.Data.FDB)
+	}
+
+	// Segunda muestra (contadores avanzados): ya hay delta de cpu/net
+	run.outs[CmdProcStat] = "cpu  4805 356 584 3799 23 0 23 0 0 0\n"
+	run.outs[CmdNetDev] = "  eth0: 2000000 0 0 0 0 0 0 0 1000000 0\n"
+	pl2 := p.Build(context.Background(), "patio", "0.1.0")
+	if pl2.Data.System.CPU == nil || pl2.Data.System.RxBps == nil {
+		t.Fatal("segunda muestra debería tener delta cpu/net")
+	}
+}
+
+func TestProberSondasFallidasSeccionAusente(t *testing.T) {
+	// Equipo sin ubus/iwinfo/brctl (todo falla salvo /proc): las secciones
+	// wireless/dhcp/fdb quedan ausentes (nil) → el servidor conserva lo último.
+	run := fakeRunner{outs: map[string]string{
+		CmdProcStat: "cpu  4705 356 584 3699 23 0 23 0 0 0\n",
+		CmdTemp:     "43500\n",
+		CmdNetDev:   "  eth0: 1000 0 0 0 0 0 0 0 500 0\n",
+	}}
+	p := NewProber(run, Options{})
+	pl := p.Build(context.Background(), "patio", "0.1.0")
+	if pl.Data.System == nil {
+		t.Fatal("system debería existir (proc funciona)")
+	}
+	if pl.Data.Wireless != nil || pl.Data.DHCP != nil || pl.Data.FDB != nil {
+		t.Fatalf("secciones fallidas deberían ser nil: %+v", pl.Data)
+	}
+	// JSON de las secciones ausentes: omitempty las omite
+	if strings.Contains(payloadJSON(t, pl), `"wireless"`) {
+		t.Fatal("wireless ausente no debería serializarse")
+	}
+}
+
+func payloadJSON(t *testing.T, pl *Payload) string {
+	t.Helper()
+	data, err := json.Marshal(pl)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return string(data)
+}

+ 1 - 0
app/.gitignore

@@ -0,0 +1 @@
+dev-dist/

+ 3 - 0
app/package.json

@@ -61,6 +61,9 @@
     "tailwind-merge": "^3.4.0",
     "vaul": "^1.1.2",
     "vite-plugin-pwa": "^1.3.0",
+    "workbox-core": "^7.4.1",
+    "workbox-precaching": "^7.4.1",
+    "workbox-routing": "^7.4.1",
     "zod": "^4.3.5"
   },
   "devDependencies": {

+ 95 - 4
app/public/locales/en/translation.json

@@ -45,6 +45,34 @@
       "offline": "offline",
       "weak": "weak signal",
       "other": "other"
+    },
+    "filterByCategory": "Filter by category",
+    "urgentBadge": "URGENT",
+    "configButton": "Configure alerts",
+    "configTitle": "Alert settings",
+    "configDescription": "Choose which events are kept in your history and counted on the bell, per category.",
+    "configSaved": "Saved",
+    "configSaveError": "Could not save — please try again",
+    "categories": {
+      "router": "Router",
+      "internet": "Internet",
+      "clients": "Clients",
+      "signal": "Signal",
+      "vpn": "VPN",
+      "system": "System"
+    },
+    "categoryDescriptions": {
+      "router": "Router status, temperature and reboots",
+      "internet": "WAN outages and recoveries",
+      "clients": "Devices joining the network (known and unknown)",
+      "signal": "Weak WiFi coverage on clients and nodes",
+      "vpn": "WireGuard handshakes and sessions",
+      "system": "Firmware, backups and services (AdGuard, NAS)"
+    },
+    "levels": {
+      "urgent": "Urgent only",
+      "all": "Everything",
+      "none": "Nothing"
     }
   },
   "auth": {
@@ -112,6 +140,14 @@
     "viewDetailShort": "View detail"
   },
   "devices": {
+    "badges": {
+      "ct": "CT",
+      "ctTip": "Container on {{host}}",
+      "hypervisor": "Hypervisor",
+      "hypervisorTip": "Host with CTs/VMs nested behind its virtual bridge",
+      "managedSwitch": "Managed switch",
+      "managedSwitchTip": "Switch identified via LLDP"
+    },
     "bandAll": "All",
     "changeView": "Change view",
     "clearFilters": "Clear filters",
@@ -124,6 +160,7 @@
     "detail": {
       "dhcpLease": "DHCP lease",
       "firstSeen": "First seen",
+      "infra": "Infrastructure",
       "manufacturer": "Manufacturer (OUI)",
       "protected": "Protected",
       "rename": "Rename device",
@@ -138,6 +175,7 @@
     "filterByRouter": "Filter by router",
     "gridView": "Grid view",
     "groups": {
+      "infra": "Infra",
       "iot": "IoT & home",
       "moviles": "Mobiles",
       "ordenadores": "Computers",
@@ -178,6 +216,7 @@
       "ordenador": "computer",
       "portatil": "laptop",
       "servidor": "server",
+      "switch": "switch",
       "tablet": "tablet",
       "tv": "TV"
     },
@@ -366,6 +405,13 @@
     }
   },
   "routers": {
+    "agent": {
+      "badge": "Agent",
+      "freshTip": "netpulse-agent v{{version}} · pushes every 15 s",
+      "freshTipUnknown": "netpulse-agent · pushes every 15 s",
+      "stale": "Agent down",
+      "staleTip": "No data from agent — polling via SSH"
+    },
     "colClients": "Clients",
     "colCpu": "CPU",
     "colDevice": "Device",
@@ -409,13 +455,18 @@
       "wiredLink": "Physical cable (WAN, uplinks, devices)",
       "wifiUplink": "WiFi uplink (wireless backhaul)",
       "lldpIdentified": "Identified via LLDP",
-      "inferredSwitch": "Inferred switch or bridge (no IP)"
+      "inferredSwitch": "Inferred switch or bridge (no IP)",
+      "hypervisorHost": "Hypervisor (host with +N badge)",
+      "ctGrid": "CT/VM nested in a grid under its host"
     },
     "links": {
       "colLink": "Link",
       "colSpeed": "Speed",
       "congestedChannel": "Congested channel",
       "fiberWan": "WAN fiber",
+      "hypervisorCable": "Hypervisor cable",
+      "inferredSwitch": "Inferred switch · {{port}}",
+      "managedSwitch": "Managed switch",
       "throughput": "Link throughput",
       "title": "Links between devices",
       "wifiUplink": "WiFi uplink"
@@ -424,6 +475,8 @@
     "peerAria": "{{name}}, active WireGuard tunnel, {{ip}}",
     "plan": "Plan",
     "received": "Received",
+    "refreshNow": "Refresh now",
+    "refreshing": "Refreshing…",
     "resetView": "Center and reset view",
     "routerAria": "{{name}}, {{model}}, {{clients}} clients",
     "sent": "Sent",
@@ -454,7 +507,7 @@
       "inferred": "inferred",
       "managed": "managed switch",
       "noIp": "no IP · not directly queryable",
-      "port": "Gateway port",
+      "port": "Port on {{router}}",
       "macs": "Learned MACs",
       "fdbNote": "FDB: {{count}} heterogeneous MACs on a single physical port. Probably a switch; we cannot tell for sure without LLDP."
     },
@@ -470,6 +523,9 @@
     "peers": {
       "overflowTitle": "{{count}} more peers",
       "overflowAria": "{{count}} additional WireGuard peers"
+    },
+    "ring": {
+      "overflowAria": "{{count}} more clients on {{router}}"
     }
   },
   "settings": {
@@ -481,7 +537,17 @@
       "madeAtHome": "Support the project on Ko-fi",
       "privacy": "100% private · 0% cloud",
       "title": "About",
-      "versionNote": "v1.0.0"
+      "versionNote": "v1.0.0",
+      "system": "System",
+      "sysApp": "App",
+      "sysGo": "Go",
+      "sysReact": "React",
+      "sysOs": "OS",
+      "sysKernel": "Kernel",
+      "sysCpu": "CPU",
+      "sysRam": "RAM",
+      "sysUptime": "Uptime",
+      "demoNoServer": "Server data unavailable (demo)"
     },
     "accent": "Accent",
     "accentAmber": "Amber",
@@ -523,7 +589,7 @@
       "badge": "Alerts badge in the navigation",
       "badgeCaption": "Counter next to \"Alerts\"",
       "caption": "In-app notices",
-      "note": "These are only in-app notices. NetPulse does not send push notifications in this phase.",
+      "note": "These are only in-app notices. To get alerts when the app is closed, enable “Push notifications”.",
       "pulse": "Pulsing dot on devices with warnings",
       "pulseCaption": "Animated dot on cards with warn",
       "sound": "Sound when an alert arrives",
@@ -531,6 +597,25 @@
       "soundOn": "On — plays a soft beep",
       "title": "Visual notifications"
     },
+    "push": {
+      "title": "Push notifications",
+      "caption": "Urgent alerts even when the app is closed",
+      "checking": "Checking support…",
+      "enable": "Enable",
+      "disable": "Disable",
+      "enabling": "Enabling…",
+      "disabling": "Disabling…",
+      "stateOn": "Enabled",
+      "stateOnCaption": "This device receives urgent alerts even when NetPulse is closed.",
+      "stateOffCaption": "Get urgent alerts on this device even when the app is not open.",
+      "denied": "Permission denied in the browser. To re-enable it: click the lock (or tune) icon in the address bar → Permissions → Notifications → Allow, then reload the page.",
+      "unsupported": "This browser does not support push notifications (it needs Service Worker, the Push API and the Notifications API).",
+      "insecure": "Push notifications require a secure context (HTTPS). On the local network they only work via localhost; over http://<lan-ip> the browser blocks them.",
+      "demoNote": "Not available in the local demo: push notifications need the NetPulse backend (without a server, a subscription would never receive anything).",
+      "errorServer": "Could not reach the push server. Please try again.",
+      "errorGeneric": "Push notifications could not be enabled on this device.",
+      "note": "Only alerts marked as urgent arrive (configured in Alerts). The notice is shown by the operating system with the NetPulse icon."
+    },
     "pwa": {
       "caption": "Installable app · PWA",
       "desc": "Install it as an app: fullscreen launch, no browser bar and instant access.",
@@ -562,6 +647,9 @@
       "demoCaption": "Local simulated data, no connection to your network.",
       "exitDemo": "Exit demo mode",
       "changePassword": "Change my password",
+      "name": "Name",
+      "nameHint": "This is how the Summary greets you; it's not your username",
+      "nameSaved": "Name saved",
       "pwCurrent": "Current password",
       "pwNew": "New password",
       "pwConfirm": "Repeat password",
@@ -585,6 +673,7 @@
       "gateway": "Is the gateway",
       "gatewayBadge": "Main",
       "add": "Add",
+      "addDevice": "Add device",
       "adding": "Adding…",
       "delete": "Delete",
       "deleteConfirm": "Delete {name}? Metrics history is kept.",
@@ -610,6 +699,7 @@
       "roleAdmin": "Admin",
       "you": "You",
       "add": "Create user",
+      "createUser": "Create user",
       "adding": "Creating…",
       "delete": "Delete",
       "deleteConfirm": "Delete user {name}?",
@@ -629,6 +719,7 @@
       "user": "GL UI username",
       "pass": "GL UI password",
       "passKeep": "Saved (type to change)",
+      "edit": "Edit",
       "configured": "Configured",
       "notConfigured": "Not configured",
       "save": "Save",

+ 95 - 4
app/public/locales/es/translation.json

@@ -45,6 +45,34 @@
       "offline": "offline",
       "weak": "señal débil",
       "other": "otros"
+    },
+    "filterByCategory": "Filtrar por categoría",
+    "urgentBadge": "URGENTE",
+    "configButton": "Configurar alertas",
+    "configTitle": "Configuración de alertas",
+    "configDescription": "Elige qué eventos entran en tu historial y cuentan en la campana, por categoría.",
+    "configSaved": "Guardado",
+    "configSaveError": "No se pudo guardar — inténtalo de nuevo",
+    "categories": {
+      "router": "Router",
+      "internet": "Internet",
+      "clients": "Clientes",
+      "signal": "Señal",
+      "vpn": "VPN",
+      "system": "Sistema"
+    },
+    "categoryDescriptions": {
+      "router": "Estado, temperatura y reinicios de los routers",
+      "internet": "Cortes y recuperaciones de la conexión WAN",
+      "clients": "Dispositivos que se unen a la red (conocidos y desconocidos)",
+      "signal": "Cobertura WiFi débil en clientes y nodos",
+      "vpn": "Handshakes y sesiones de WireGuard",
+      "system": "Firmware, copias de seguridad y servicios (AdGuard, NAS)"
+    },
+    "levels": {
+      "urgent": "Solo urgentes",
+      "all": "Todo",
+      "none": "Nada"
     }
   },
   "auth": {
@@ -112,6 +140,14 @@
     "viewDetailShort": "Ver detalle"
   },
   "devices": {
+    "badges": {
+      "ct": "CT",
+      "ctTip": "Contenedor en {{host}}",
+      "hypervisor": "Hipervisor",
+      "hypervisorTip": "Host con CTs/VMs anidados tras su bridge virtual",
+      "managedSwitch": "Switch gestionado",
+      "managedSwitchTip": "Switch identificado vía LLDP"
+    },
     "bandAll": "Todas",
     "changeView": "Cambiar vista",
     "clearFilters": "Limpiar filtros",
@@ -124,6 +160,7 @@
     "detail": {
       "dhcpLease": "Concesión DHCP",
       "firstSeen": "Primera vez vista",
+      "infra": "Infraestructura",
       "manufacturer": "Fabricante (OUI)",
       "protected": "Protegido",
       "rename": "Renombrar dispositivo",
@@ -138,6 +175,7 @@
     "filterByRouter": "Filtrar por router",
     "gridView": "Vista de tarjetas",
     "groups": {
+      "infra": "Infra",
       "iot": "IoT y hogar",
       "moviles": "Móviles",
       "ordenadores": "Ordenadores",
@@ -178,6 +216,7 @@
       "ordenador": "ordenador",
       "portatil": "portátil",
       "servidor": "servidor",
+      "switch": "switch",
       "tablet": "tablet",
       "tv": "TV"
     },
@@ -366,6 +405,13 @@
     }
   },
   "routers": {
+    "agent": {
+      "badge": "Agente",
+      "freshTip": "netpulse-agent v{{version}} · empuja cada 15 s",
+      "freshTipUnknown": "netpulse-agent · empuja cada 15 s",
+      "stale": "Agente caído",
+      "staleTip": "Sin datos del agente — sondeando por SSH"
+    },
     "colClients": "Clientes",
     "colCpu": "CPU",
     "colDevice": "Equipo",
@@ -409,13 +455,18 @@
       "wiredLink": "Cable físico (WAN, uplinks, equipos)",
       "wifiUplink": "Uplink wifi (backhaul inalámbrico)",
       "lldpIdentified": "Identificado vía LLDP",
-      "inferredSwitch": "Switch o bridge inferido (sin IP)"
+      "inferredSwitch": "Switch o bridge inferido (sin IP)",
+      "hypervisorHost": "Hipervisor (host con badge +N)",
+      "ctGrid": "CT/VM anidado en grid bajo su host"
     },
     "links": {
       "colLink": "Enlace",
       "colSpeed": "Velocidad",
       "congestedChannel": "Canal congestionado",
       "fiberWan": "Fibra WAN",
+      "hypervisorCable": "Cable de hipervisor",
+      "inferredSwitch": "Switch inferido · {{port}}",
+      "managedSwitch": "Switch gestionado",
       "throughput": "Throughput del enlace",
       "title": "Enlaces entre equipos",
       "wifiUplink": "WiFi uplink"
@@ -424,6 +475,8 @@
     "peerAria": "{{name}}, túnel WireGuard activo, {{ip}}",
     "plan": "Plan",
     "received": "Recibido",
+    "refreshNow": "Refrescar ahora",
+    "refreshing": "Actualizando…",
     "resetView": "Centrar y restablecer vista",
     "routerAria": "{{name}}, {{model}}, {{clients}} clientes",
     "sent": "Enviado",
@@ -454,7 +507,7 @@
       "inferred": "inferido",
       "managed": "switch gestionado",
       "noIp": "sin IP · no consultable directamente",
-      "port": "Puerto del gateway",
+      "port": "Puerto de {{router}}",
       "macs": "MACs aprendidas",
       "fdbNote": "FDB: {{count}} MACs heterogéneas en un solo puerto físico. Probablemente un switch; no podemos afirmarlo sin LLDP."
     },
@@ -470,6 +523,9 @@
     "peers": {
       "overflowTitle": "{{count}} peers más",
       "overflowAria": "{{count}} peers WireGuard adicionales"
+    },
+    "ring": {
+      "overflowAria": "{{count}} clientes más en {{router}}"
     }
   },
   "settings": {
@@ -481,7 +537,17 @@
       "madeAtHome": "Apoya el proyecto en Ko-fi",
       "privacy": "100% privado · 0% nube",
       "title": "Acerca de",
-      "versionNote": "v1.0.0"
+      "versionNote": "v1.0.0",
+      "system": "Sistema",
+      "sysApp": "App",
+      "sysGo": "Go",
+      "sysReact": "React",
+      "sysOs": "SO",
+      "sysKernel": "Kernel",
+      "sysCpu": "CPU",
+      "sysRam": "RAM",
+      "sysUptime": "Tiempo activo",
+      "demoNoServer": "Datos del servidor no disponibles (demo)"
     },
     "accent": "Acento",
     "accentAmber": "Ámbar",
@@ -523,7 +589,7 @@
       "badge": "Badge de avisos en la navegación",
       "badgeCaption": "Contador junto a «Alertas»",
       "caption": "Avisos dentro de la app",
-      "note": "Son solo avisos dentro de la app. NetPulse no envía notificaciones push en esta fase.",
+      "note": "Son solo avisos dentro de la app. Para recibir alertas con la app cerrada, activa las «Notificaciones push».",
       "pulse": "Punto pulsante en equipos con aviso",
       "pulseCaption": "Dot animado en tarjetas con warn",
       "sound": "Sonido al llegar una alerta",
@@ -531,6 +597,25 @@
       "soundOn": "Activado — suena un beep suave",
       "title": "Notificaciones visuales"
     },
+    "push": {
+      "title": "Notificaciones push",
+      "caption": "Alertas urgentes incluso con la app cerrada",
+      "checking": "Comprobando soporte…",
+      "enable": "Activar",
+      "disable": "Desactivar",
+      "enabling": "Activando…",
+      "disabling": "Desactivando…",
+      "stateOn": "Activadas",
+      "stateOnCaption": "Este dispositivo recibe las alertas urgentes aunque NetPulse esté cerrado.",
+      "stateOffCaption": "Recibe las alertas urgentes en este dispositivo aunque no tengas la app abierta.",
+      "denied": "Permiso denegado en el navegador. Para reactivarlo: pulsa el candado (o el icono de ajustes) de la barra de direcciones → Permisos → Notificaciones → Permitir, y recarga la página.",
+      "unsupported": "Este navegador no admite notificaciones push (hacen falta Service Worker, Push API y la API de notificaciones).",
+      "insecure": "Las notificaciones push exigen un contexto seguro (HTTPS). En la red local solo funcionan accediendo por localhost; desde http://<ip-de-la-lan> el navegador las bloquea.",
+      "demoNote": "No disponible en la demo local: las notificaciones push necesitan el backend de NetPulse (sin servidor, una suscripción nunca recibiría nada).",
+      "errorServer": "No se pudo contactar con el servidor push. Inténtalo de nuevo.",
+      "errorGeneric": "No se pudieron activar las notificaciones push en este dispositivo.",
+      "note": "Solo llegan las alertas marcadas como urgentes (se configura en Alertas). El aviso lo muestra el sistema operativo con el icono de NetPulse."
+    },
     "pwa": {
       "caption": "App instalable · PWA",
       "desc": "Instálala como app: arranque a pantalla completa, sin barra del navegador y acceso instantáneo.",
@@ -562,6 +647,9 @@
       "demoCaption": "Datos simulados locales, sin conexión a tu red.",
       "exitDemo": "Salir del modo demo",
       "changePassword": "Cambiar mi contraseña",
+      "name": "Nombre",
+      "nameHint": "Así te saluda el Resumen; no es tu nombre de usuario",
+      "nameSaved": "Nombre guardado",
       "pwCurrent": "Contraseña actual",
       "pwNew": "Nueva contraseña",
       "pwConfirm": "Repite la contraseña",
@@ -585,6 +673,7 @@
       "gateway": "Es la puerta de enlace",
       "gatewayBadge": "Principal",
       "add": "Añadir",
+      "addDevice": "Añadir dispositivo",
       "adding": "Añadiendo…",
       "delete": "Eliminar",
       "deleteConfirm": "¿Eliminar {name}? El histórico de métricas se conserva.",
@@ -610,6 +699,7 @@
       "roleAdmin": "Admin",
       "you": "Tú",
       "add": "Crear usuario",
+      "createUser": "Crear usuario",
       "adding": "Creando…",
       "delete": "Eliminar",
       "deleteConfirm": "¿Eliminar al usuario {name}?",
@@ -629,6 +719,7 @@
       "user": "Usuario de la interfaz GL",
       "pass": "Contraseña de la interfaz GL",
       "passKeep": "Guardada (escribe para cambiar)",
+      "edit": "Editar",
       "configured": "Configurado",
       "notConfigured": "Sin configurar",
       "save": "Guardar",

+ 22 - 2
app/src/components/AuthGate.tsx

@@ -26,9 +26,17 @@ async function checkSession(): Promise<{ state: GateState; auth: AuthUser | null
     if (!res.ok) return { state: 'demo', auth: null }
     // La preview estática responde HTML con 200 (SPA fallback): no es sesión
     if (!(res.headers.get('content-type') ?? '').includes('application/json')) return { state: 'demo', auth: null }
-    const data = (await res.json()) as { user?: string; role?: 'admin' | 'user'; language?: 'auto' | 'es' | 'en' }
+    const data = (await res.json()) as {
+      user?: string
+      role?: 'admin' | 'user'
+      language?: 'auto' | 'es' | 'en'
+      displayName?: string
+    }
     if (!data?.user) return { state: 'demo', auth: null }
-    return { state: 'authed', auth: { user: data.user, role: data.role ?? 'user', language: data.language ?? 'auto' } }
+    return {
+      state: 'authed',
+      auth: { user: data.user, role: data.role ?? 'user', language: data.language ?? 'auto', displayName: data.displayName ?? '' },
+    }
   } catch {
     return { state: 'demo', auth: null }
   }
@@ -82,6 +90,18 @@ export function AuthGate({ children }: { children: React.ReactNode }) {
     // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [])
 
+  // Refetch bajo demanda (SPEC-65 D65-5): tras cambiar displayName/idioma, la
+  // página emite 'netpulse-auth-refresh' y el contexto se actualiza sin reload.
+  useEffect(() => {
+    const onRefresh = () => {
+      void checkSession().then(({ state: s, auth: a }) => {
+        if (s === 'authed') setAuth(a)
+      })
+    }
+    window.addEventListener('netpulse-auth-refresh', onRefresh)
+    return () => window.removeEventListener('netpulse-auth-refresh', onRefresh)
+  }, [])
+
   if (state === 'loading') return <GateSkeleton />
   if (state === 'login') return <Navigate to="/login" replace />
   return <AuthProvider auth={auth}>{children}</AuthProvider>

+ 5 - 1
app/src/components/RouterCard.tsx

@@ -8,6 +8,8 @@ import type { Router } from '@/data/mock'
 import { HealthRing, STATUS_COLORS } from '@/components/HealthRing'
 import { Sparkline } from '@/components/Sparkline'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 
 function MiniMetric({
@@ -38,6 +40,7 @@ interface RouterCardProps {
 /** Tarjeta de router (design.md §10.2): StatusRing, mini-métricas, sparkline, chevron. */
 export function RouterCard({ router, index = 0, className }: RouterCardProps) {
   const { t } = useTranslation()
+  const agent = useAgentFor(router.id)
   const warn = router.status === 'warn'
   const offline = router.status === 'offline'
   return (
@@ -63,11 +66,12 @@ export function RouterCard({ router, index = 0, className }: RouterCardProps) {
               <RouterIcon className="h-5 w-5" strokeWidth={1.75} />
             </div>
             <div className="min-w-0">
-              <div className="flex items-center gap-2">
+              <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                 <span className="truncate font-display text-h2 text-text-primary">{router.name}</span>
                 <span className="shrink-0 rounded-full bg-accent-soft px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">
                   {roleLabel(router.roleBadge)}
                 </span>
+                <AgentBadge agent={agent} className="shrink-0" />
               </div>
               <div className="truncate text-caption text-text-muted">{router.modelShort}</div>
             </div>

+ 35 - 0
app/src/components/routers/AgentBadge.tsx

@@ -0,0 +1,35 @@
+import { useTranslation } from 'react-i18next'
+import type { AgentInfo } from '@/data/types'
+import { StatusPill } from '@/components/StatusPill'
+import { cn } from '@/lib/utils'
+
+interface AgentBadgeProps {
+  /** Agente del router; undefined/null → no se renderiza nada (demo, sin agentes) */
+  agent: AgentInfo | undefined
+  className?: string
+}
+
+/**
+ * Badge "Agente" (Fase 6 piloto):
+ * - `fresh` → tono info discreto, tooltip con versión y cadencia de push.
+ * - caído  → tono warn pulsante, tooltip "sondeando por SSH" (las alertas de
+ *   categoría system ya narran la caída/recuperación; aquí solo el estado).
+ */
+export function AgentBadge({ agent, className }: AgentBadgeProps) {
+  const { t } = useTranslation()
+  if (!agent) return null
+  const title = agent.fresh
+    ? agent.version
+      ? t('routers.agent.freshTip', { version: agent.version })
+      : t('routers.agent.freshTipUnknown')
+    : t('routers.agent.staleTip')
+  return (
+    <span title={title} className={cn('inline-flex', className)}>
+      <StatusPill
+        tone={agent.fresh ? 'info' : 'warn'}
+        label={agent.fresh ? t('routers.agent.badge') : t('routers.agent.stale')}
+        pulse={!agent.fresh}
+      />
+    </span>
+  )
+}

+ 5 - 1
app/src/components/routers/FleetCard.tsx

@@ -10,6 +10,8 @@ import { HealthRing } from '@/components/HealthRing'
 import { MetricBar } from '@/components/MetricBar'
 import { Sparkline } from '@/components/Sparkline'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
@@ -57,6 +59,7 @@ interface FleetCardProps {
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
   const { t } = useTranslation()
   const { isDemo } = useNetPulse()
+  const agent = useAgentFor(router.id)
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
   const reduce = useReducedMotion()
@@ -104,8 +107,9 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
               <RouterIcon className="h-[22px] w-[22px]" strokeWidth={1.75} />
             </motion.div>
             <div className="min-w-0">
-              <div className="flex items-center gap-2">
+              <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                 <h3 className="truncate font-display text-h2 text-text-primary">{router.name}</h3>
+                <AgentBadge agent={agent} />
               </div>
               <div className="truncate text-caption text-text-muted">
                 {isGateway ? 'GL.iNet Flint 2 · GL-MT6000' : `OpenWrt · ${router.modelShort}`}

+ 11 - 3
app/src/components/routers/FleetTable.tsx

@@ -9,6 +9,7 @@ import { fmtEs } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
 import { MetricBar } from '@/components/MetricBar'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
 import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
 import { cn } from '@/lib/utils'
 
@@ -76,10 +77,11 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
   const { t } = useTranslation()
   const navigate = useNavigate()
   const reduce = useReducedMotion()
-  const { routers } = useNetPulse()
+  const { routers, agents } = useNetPulse()
   const [sortKey, setSortKey] = useState<SortKey>('name')
   const [asc, setAsc] = useState(true)
   const [openId, setOpenId] = useState<string | null>(null)
+  const agentBySlug = useMemo(() => new Map(agents.map((a) => [a.slug, a])), [agents])
 
   const sorted = useMemo(() => {
     const arr = [...routers]
@@ -162,7 +164,10 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                         <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                       </span>
                       <span>
-                        <span className="block font-medium text-text-primary">{r.name}</span>
+                        <span className="flex items-center gap-2">
+                          <span className="font-medium text-text-primary">{r.name}</span>
+                          <AgentBadge agent={agentBySlug.get(r.id)} />
+                        </span>
                         <span className="block text-caption text-text-muted">{r.modelShort}</span>
                       </span>
                     </div>
@@ -221,7 +226,10 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                   )}>
                     <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                   </span>
-                  <span className="truncate font-medium text-text-primary">{r.name}</span>
+                  <span className="min-w-0">
+                    <span className="block truncate font-medium text-text-primary">{r.name}</span>
+                    <AgentBadge agent={agentBySlug.get(r.id)} className="mt-1" />
+                  </span>
                 </span>
                 <span className="flex shrink-0 items-center gap-2">
                   <StatusPill

+ 12 - 0
app/src/components/routers/RouterDetailHeader.tsx

@@ -6,6 +6,8 @@ import { roleLabel } from '@/i18n'
 import type { Router } from '@/data/mock'
 import { HealthRing } from '@/components/HealthRing'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 
 /** ① Detail header (router-detail.md §①) — identidad + StatusRing 96px. */
@@ -13,6 +15,7 @@ export function RouterDetailHeader({ router }: { router: Router }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const isGateway = router.roleBadge === 'Principal'
+  const agent = useAgentFor(router.id)
   const pills = [
     { label: roleLabel(router.roleBadge), tone: 'accent' as const, pulse: false },
     {
@@ -73,6 +76,15 @@ export function RouterDetailHeader({ router }: { router: Router }) {
                   <StatusPill tone={p.tone} label={p.label} pulse={p.pulse} />
                 </motion.span>
               ))}
+              {agent && (
+                <motion.span
+                  initial={reduce ? false : { opacity: 0, scale: 0.9 }}
+                  animate={{ opacity: 1, scale: 1 }}
+                  transition={{ duration: 0.2, delay: 0.15 + pills.length * 0.06 }}
+                >
+                  <AgentBadge agent={agent} />
+                </motion.span>
+              )}
             </div>
           </div>
         </div>

+ 16 - 11
app/src/components/routers/routerExtras.ts

@@ -95,13 +95,16 @@ export const routerExtras: Record<string, RouterExtras> = {
     backhaulSignal: [],
     radios: [],
     ports: [],
-    // GL-MT6000: 1× WAN 2.5G + 4× LAN 1G
+    // GL-MT6000: 1× WAN 2.5G + 4× LAN 1G + 1× LAN 2.5G — canon D4:
+    // lan1 = uplink Salón (LLDP), lan2 = uplink Estudio (LLDP), lan3 = switch
+    // inferido, lan4 = NAS, lan5 = Proxmox pve (2.5G).
     ethPorts: [
       { id: 'wan', label: 'WAN', up: true, speed: '2.5 Gbps', connectedTo: 'Fiber ONT · Digi', detail: '84.122.x.x · full duplex' },
-      { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'Living Room · AX3000T', detail: 'Living Room AP uplink (192.168.8.2)' },
-      { id: 'lan2', label: 'LAN 2', up: true, speed: '1 Gbps', connectedTo: 'NAS Synology', detail: '192.168.8.10 · cable' },
-      { id: 'lan3', label: 'LAN 3', up: true, speed: '1 Gbps', connectedTo: 'Study · NanoPi R4S', detail: 'Study AP uplink (192.168.8.3)' },
-      { id: 'lan4', label: 'LAN 4', up: false },
+      { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'Living Room · AX3000T', detail: 'Living Room AP uplink (192.168.8.2) · LLDP' },
+      { id: 'lan2', label: 'LAN 2', up: true, speed: '1 Gbps', connectedTo: 'Study · NanoPi R4S', detail: 'Study AP uplink (192.168.8.3) · LLDP' },
+      { id: 'lan3', label: 'LAN 3', up: true, speed: '1 Gbps', connectedTo: 'Switch sin gestión (inferido)', detail: '8 MACs · sin IP (FDB)' },
+      { id: 'lan4', label: 'LAN 4', up: true, speed: '1 Gbps', connectedTo: 'NAS Synology', detail: '192.168.8.10 · cable' },
+      { id: 'lan5', label: 'LAN 5', up: true, speed: '2.5 Gbps', connectedTo: 'Proxmox pve', detail: '192.168.8.5 · 2.5G · 10 CT' },
     ],
   },
   living: {
@@ -126,15 +129,16 @@ export const routerExtras: Record<string, RouterExtras> = {
       { name: 'br-lan', up: true, speed: '—', role: 'Bridge LAN' },
       { name: 'eth0', up: true, speed: '1 Gbps', role: 'Uplink to Gateway' },
       { name: 'lan1', up: true, speed: '1 Gbps', role: 'PS5' },
+      { name: 'lan3', up: true, speed: '1 Gbps', role: 'Switch GS308E (LLDP)' },
       { name: 'phy0-ap0', up: true, speed: '—', role: 'Radio 2.4 GHz' },
       { name: 'phy1-ap0', up: true, speed: '—', role: 'Radio 5 GHz' },
     ],
-    // AX3000T: 1× WAN + 3× LAN
+    // AX3000T: 1× WAN + 3× LAN — canon D4: lan3 = uplink del GS308E (up).
     ethPorts: [
       { id: 'wan', label: 'WAN', up: true, speed: '1 Gbps', connectedTo: 'Uplink → Gateway', detail: 'Gateway · LAN 1 (192.168.8.1)' },
       { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'PS5', detail: '192.168.8.31 · cable' },
       { id: 'lan2', label: 'LAN 2', up: false },
-      { id: 'lan3', label: 'LAN 3', up: false },
+      { id: 'lan3', label: 'LAN 3', up: true, speed: '1 Gbps', connectedTo: 'Switch GS308E', detail: '192.168.8.13 · LLDP · uplink ge5' },
     ],
   },
   estudio: {
@@ -159,14 +163,15 @@ export const routerExtras: Record<string, RouterExtras> = {
     ports: [
       { name: 'br-lan', up: true, speed: '—', role: 'Bridge LAN' },
       { name: 'eth0', up: true, speed: '1 Gbps', role: 'Uplink to Gateway' },
-      { name: 'eth1', up: true, speed: '1 Gbps', role: 'Study switch' },
+      { name: 'eth1', up: true, speed: '1 Gbps', role: 'Unmanaged switch' },
       { name: 'phy0-ap0', up: true, speed: '—', role: 'Radio 2.4 GHz' },
       { name: 'phy1-ap0', up: true, speed: '—', role: 'Radio 5 GHz' },
     ],
-    // NanoPi R4S: 2× 1G (WAN + LAN)
+    // NanoPi R4S: 2× 1G (WAN + LAN) — canon D4: lan1 = switch sin gestión.
+    // Solo panel: la topología no lo muestra (regla "inferred solo en gateway").
     ethPorts: [
-      { id: 'wan', label: 'WAN', up: true, speed: '1 Gbps', connectedTo: 'Uplink → Gateway', detail: 'Gateway · LAN 3 (192.168.8.1)' },
-      { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'Study switch', detail: '8-port switch · 4 in use' },
+      { id: 'wan', label: 'WAN', up: true, speed: '1 Gbps', connectedTo: 'Uplink → Gateway', detail: 'Gateway · LAN 2 (192.168.8.1)' },
+      { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'Switch sin gestión', detail: '8 puertos · 4 en uso · la topología no lo muestra' },
     ],
   },
   patio: {

+ 30 - 0
app/src/components/topology/LegendCard.tsx

@@ -62,6 +62,28 @@ function InferredSample() {
   )
 }
 
+/** Muestra de host hipervisor: chip con badge +N */
+function HypervisorSample() {
+  return (
+    <svg width="26" height="14" viewBox="0 0 26 14" aria-hidden="true">
+      <rect x="1" y="3" width="14" height="10" rx="3" fill="none" stroke={COLOR.ok} strokeWidth="1.4" />
+      <rect x="13" y="0" width="12" height="8" rx="4" fill="rgb(var(--canvas))" stroke={COLOR.tunnel} strokeWidth="1.1" />
+      <text x="19" y="6.2" textAnchor="middle" fontSize="5.5" fontWeight="800" fill={COLOR.tunnel}>+N</text>
+    </svg>
+  )
+}
+
+/** Muestra de CT/VM anidado en grid bajo el host */
+function CtSample() {
+  return (
+    <svg width="26" height="14" viewBox="0 0 26 14" aria-hidden="true">
+      <rect x="1" y="1" width="10" height="12" rx="2.5" fill="none" stroke={COLOR.ok} strokeWidth="1.4" />
+      <rect x="15" y="1" width="10" height="12" rx="2.5" fill="none" stroke="rgb(var(--text-muted))" strokeWidth="1.2" />
+      <text x="20" y="9.5" textAnchor="middle" fontSize="5.5" fontWeight="800" fill="rgb(var(--text-muted))">CT</text>
+    </svg>
+  )
+}
+
 /** Muestra de línea dashed WireGuard, auto-animada en loop */
 function WgSample() {
   const reduce = useReducedMotion()
@@ -133,6 +155,14 @@ export function LegendContent({ model, compact = false }: { model: TopologyModel
             <InferredSample />
             {t('topology.legend.inferredSwitch')}
           </motion.li>
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <HypervisorSample />
+            {t('topology.legend.hypervisorHost')}
+          </motion.li>
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <CtSample />
+            {t('topology.legend.ctGrid')}
+          </motion.li>
         </ul>
       </div>
       <div>

+ 2 - 1
app/src/components/topology/LinksTable.tsx

@@ -73,13 +73,14 @@ function rowMotion(reduce: boolean, i: number) {
 }
 
 function LinkNames({ row }: { row: BackhaulRow }) {
+  const { t } = useTranslation()
   return (
     <span className="flex items-center gap-1.5">
       <span className="font-medium text-text-primary">{row.a}</span>
       <span className={cn('text-text-muted', row.kind === 'wg' && 'text-tunnel')} aria-hidden>
         {row.kind === 'wg' ? '⇢' : '↔'}
       </span>
-      <span className="font-medium text-text-primary">{row.b}</span>
+      <span className="font-medium text-text-primary">{row.bKey ? t(row.bKey, row.bVars) : row.b}</span>
     </span>
   )
 }

+ 44 - 5
app/src/components/topology/TopologyMap.tsx

@@ -93,7 +93,18 @@ function MiniStat({ label, value, hot }: { label: string; value: string; hot?: b
   )
 }
 
-function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; wan: WanInfo }) {
+function TooltipCard({
+  tip,
+  touch,
+  wan,
+  routerName,
+}: {
+  tip: TooltipState
+  touch: boolean
+  wan: WanInfo
+  /** nombre visible del router del que cuelga un nodo (D8: tooltip dist) */
+  routerName: (id: string) => string
+}) {
   const { t } = useTranslation()
   return (
     <div
@@ -189,7 +200,7 @@ function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; w
             {[tip.node.ip, tip.node.port].filter(Boolean).join(' · ')}
           </div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
-            <MiniStat label={t('topology.dist.port')} value={tip.node.port} />
+            <MiniStat label={t('topology.dist.port', { router: routerName(tip.node.routerId) })} value={tip.node.port} />
             <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
           {tip.node.lldp && (
@@ -212,7 +223,7 @@ function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; w
           </div>
           <div className="mt-0.5 text-caption text-text-muted">{t('topology.dist.noIp')}</div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
-            <MiniStat label={t('topology.dist.port')} value={tip.node.port} />
+            <MiniStat label={t('topology.dist.port', { router: routerName(tip.node.routerId) })} value={tip.node.port} />
             <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
           <div className="mt-2 text-caption leading-snug text-text-secondary">
@@ -363,7 +374,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const navigate = useNavigate()
-  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, internetNode, links, peerNodes, relatedTo, routerNodes, wan } = model
+  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const viewRef = useRef<View>({ ...INITIAL_VIEW })
@@ -599,6 +610,11 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   const related = useMemo(() => (hoverNode ? relatedTo(hoverNode) : null), [hoverNode])
   /** chip por id (para resolver el host de un CT en tooltips) */
   const chipById = useMemo(() => new Map(chips.map((c) => [c.id, c])), [chips])
+  /** nombre visible de un router por id (D8: "Puerto de <router>") */
+  const routerName = useCallback(
+    (id: string) => routerNodes.find((n) => n.id === id)?.router.name ?? id,
+    [routerNodes],
+  )
   /** datos del tooltip de un chip: +N si es host hipervisor, host si es CT */
   const chipTip = useCallback(
     (chip: ChipNode): TooltipData => ({
@@ -1001,6 +1017,29 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           </g>
         )}
 
+        {/* --------- Clientes ocultos del anillo ("+N", semántica server) ------ */}
+        {ringOverflowChips.map((chip, i) => {
+          const routerName = routerNodes.find((n) => n.id === chip.routerId)?.router.name ?? chip.routerId
+          return (
+            <g key={`ring-overflow-${chip.routerId}`} transform={`translate(${chip.x} ${chip.y})`}>
+              <motion.g
+                initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.6 }}
+                animate={{ opacity: nodeOpacity(`ring-overflow-${chip.routerId}`), scale: 1 }}
+                transition={reduce ? { duration: 0 } : { delay: (2.2 + i * 0.1) * T, duration: 0.35 }}
+                style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
+              >
+                <g role="img" aria-label={t('topology.ring.overflowAria', { count: chip.count, router: routerName })}>
+                  <title>{t('topology.ring.overflowAria', { count: chip.count, router: routerName })}</title>
+                  <rect x={-15} y={-11} width={30} height={22} rx={8} fill="rgb(var(--elevated))" stroke={COLOR.accent} strokeWidth={1.5} />
+                  <text x={0} y={3.5} textAnchor="middle" fontSize={9.5} fontWeight={700} fill={COLOR.accent}>
+                    +{chip.count}
+                  </text>
+                </g>
+              </motion.g>
+            </g>
+          )
+        })}
+
         {/* ------------------------- Nodos de distribución (switch inferido) --- */}
         {distNodes.map((dv, i) => (
           <DistNodeGroup
@@ -1121,7 +1160,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       </svg>
 
       {/* tooltip flotante */}
-      {tooltip && <TooltipCard tip={tooltip} touch={!hoverCapable} wan={wan} />}
+      {tooltip && <TooltipCard tip={tooltip} touch={!hoverCapable} wan={wan} routerName={routerName} />}
     </div>
   )
 }

+ 238 - 8
app/src/components/topology/model.ts

@@ -15,7 +15,7 @@
  * con arcos prohibidos (uplink, etiqueta, WAN, abanico cableado); cableados
  * en abanicos por hub; CTs en grid bajo el host.
  */
-import type { Band, Device, DistributionNode, Router, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
+import type { Band, Device, DistributionNode, Router, TopoSemantics, TopoSemLink, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
 
 /** viewBox del lienzo SVG */
 export const VB_W = 1000
@@ -97,6 +97,9 @@ export interface BackhaulRow {
   id: string // coincide con TopoLink.id
   a: string
   b: string
+  /** clave i18n de `b` cuando el nombre del extremo B se traduce (p. ej. "Switch inferido · lan3") */
+  bKey?: string
+  bVars?: Record<string, string | number>
   kind: TopoLinkKind
   type: string
   speed: string
@@ -114,6 +117,23 @@ export interface TopologyInput {
   wan: WanInfo
   wireguard: WireGuardStats
   distributionNodes?: DistributionNode[]
+  /**
+   * Semántica de topología precalculada server-side (SPEC-65 D65-3/D65-9 B2):
+   * anillos (miembros y orden), enlaces (from/to/kind) y "+N" de peers
+   * ocultos. La GEOMETRÍA (coordenadas, radios, paths) sigue 100% aquí.
+   * Ausente (servidor viejo o demo local) → cálculo local exacto de siempre.
+   */
+  topology?: TopoSemantics
+  /** Versión del view-model (SPEC-65 D65-4): la semántica aplica si vm >= 1. */
+  vm?: number
+}
+
+/** Chip "+N" de un anillo desbordado (posición ya calculada, geometría local). */
+export interface RingOverflowChip {
+  routerId: string
+  count: number
+  x: number
+  y: number
 }
 
 export interface TopologyModel {
@@ -132,6 +152,11 @@ export interface TopologyModel {
   ctCountByHost: Map<string, number>
   /** radios de los anillos wifi realmente usados por router (guías punteadas) */
   ringRadii: Map<string, number[]>
+  /**
+   * Chips "+N" por anillo desbordado (SPEC-65 D65-3 hiddenPeers, solo con
+   * semántica server-side): clientes del anillo que exceden el aforo visible.
+   */
+  ringOverflowChips: RingOverflowChip[]
   links: TopoLink[]
   totalPackets: number
   activeLinkCount: number
@@ -338,7 +363,10 @@ function flowFor(mbps: number, alive = false): { packets: number; packetDur: num
 // Builder
 // ---------------------------------------------------------------------------
 
-export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [] }: TopologyInput): TopologyModel {
+export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [], topology, vm }: TopologyInput): TopologyModel {
+  // SPEC-65 D65-3/D65-9 B2: la semántica server-side aplica con vm >= 1 y
+  // `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)
 
@@ -351,7 +379,13 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
 
   const internetNode = { id: 'internet' as const, ...INTERNET_COORD }
 
-  const online = devices.filter((d) => d.online)
+  // D1: el switch gestionado existe como Device Y como distnode managed, pero
+  // en el mapa se representa SOLO como nodo managed: se excluye de los chips
+  // cualquier Device cuya MAC coincida con la chassis-MAC de un distnode.
+  const managedMacs = new Set(
+    distributionNodes.filter((n) => n.kind === 'managed' && n.mac).map((n) => n.mac!.toUpperCase()),
+  )
+  const online = devices.filter((d) => d.online && !managedMacs.has(d.mac.toUpperCase()))
   const deviceById = new Map(online.map((d) => [d.id, d]))
   const distById = new Map(distributionNodes.map((n) => [n.id, n]))
   /** hub al que cuelga un dispositivo: attachTo (si existe y resuelve) o su router.
@@ -365,7 +399,36 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     if (isWired(d) && !d.port && gatewayNode) return gatewayNode.id
     return d.routerId
   }
-  const childrenOf = (hubId: string) => online.filter((d) => hubOf(d) === hubId)
+  // SPEC-65 D65-3/D65-9 B2: con semántica server-side, los anillos llegan
+  // calculados (miembros y orden: cableados primero, luego 5/2.4 GHz) junto
+  // con el "+N" (hiddenPeers = ring − aforo visible de los anillos canónicos:
+  // gateway 5+8=13, AP 7+13=20). Sin semántica, fallback al cálculo local.
+  const GW_RING_VISIBLE = GATEWAY_RINGS.reduce((a, r) => a + r.cap, 0)
+  const AP_RING_VISIBLE = AP_RINGS.reduce((a, r) => a + r.cap, 0)
+  const ringOrder = new Map<string, string[]>()
+  const ringVisible = new Map<string, Set<string>>()
+  const ringOverflow = new Map<string, number>()
+  if (sem) {
+    for (const node of routerNodes) {
+      const ring = sem.rings[node.id] ?? []
+      ringOrder.set(node.id, ring)
+      const cap = node.id === gatewayNode?.id ? GW_RING_VISIBLE : AP_RING_VISIBLE
+      ringVisible.set(node.id, new Set(ring.slice(0, cap)))
+      const hidden = sem.hiddenPeers?.[node.id] ?? 0
+      if (hidden > 0) ringOverflow.set(node.id, hidden)
+    }
+  }
+  const childrenOf = (hubId: string): Device[] => {
+    const ring = ringOrder.get(hubId)
+    if (ring) return ring.map((id) => deviceById.get(id)).filter((d): d is Device => d !== undefined)
+    return online.filter((d) => hubOf(d) === hubId)
+  }
+  /** Chips visibles del anillo: con semántica, los ocultos ("+N") no se pintan. */
+  const isVisibleInRing = (d: Device): boolean => {
+    if (!sem) return true
+    const vis = ringVisible.get(hubOf(d))
+    return vis ? vis.has(d.id) : true
+  }
   const isWired = (d: Device) => d.band === 'cable'
 
   /** Hubs que son dispositivos con hijos propios (switch gestionado, hipervisor) */
@@ -392,7 +455,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const dists = distributionNodes.filter(
       (n) => n.routerId === node.id && (n.kind === 'inferred' || n.kind === 'managed'),
     )
-    const directWired = childrenOf(node.id).filter(isWired)
+    const directWired = childrenOf(node.id).filter((d) => isWired(d) && isVisibleInRing(d))
     const hubs = directWired.filter((d) => deviceHubs.has(d.id))
     const plain = directWired.filter((d) => !deviceHubs.has(d.id))
 
@@ -459,7 +522,9 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const ringRadii = new Map<string, number[]>()
   for (const node of routerNodes) {
     const isGw = node.id === gatewayNode?.id
-    const wifi = childrenOf(node.id).filter((d) => !isWired(d)).map((d) => mkChip(d, node.id))
+    const wifi = childrenOf(node.id)
+      .filter((d) => !isWired(d) && isVisibleInRing(d))
+      .map((d) => mkChip(d, node.id))
     if (wifi.length === 0) continue
     const excludes: [number, number][] = []
     if (isGw) {
@@ -549,6 +614,19 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     chips.push(...kids)
   }
 
+  // Chips "+N" de anillos desbordados (solo con semántica server-side):
+  // posición en el anillo externo — geometría 100% local (ángulo libre:
+  // gateway 60° entre el fan WAN y el uplink patio; AP 250° bajo el router).
+  const ringOverflowChips: RingOverflowChip[] = []
+  for (const [routerId, count] of ringOverflow) {
+    const node = routerById.get(routerId)
+    if (!node) continue
+    const radii = ringRadii.get(routerId)
+    const isGw = routerId === gatewayNode?.id
+    const r = radii?.[radii.length - 1] ?? (isGw ? GATEWAY_RINGS : AP_RINGS)[(isGw ? GATEWAY_RINGS : AP_RINGS).length - 1].r
+    ringOverflowChips.push({ routerId, count, ...pos(node.x, node.y, isGw ? 60 : 250, r) })
+  }
+
   // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------
   // Hay 4 coordenadas canónicas: los activos que exceden se agrupan en el
   // chip "+N" (antes se descartaban silenciosamente).
@@ -678,6 +756,109 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     })
   })
 
+  // SPEC-65 D65-3/D65-9 B2: con semántica server-side, la LISTA de enlaces
+  // (from/to/kind) la manda el servidor; aquí solo se asigna la geometría
+  // (paths, etiquetas, flujo). En canon hay paridad 1:1 con los enlaces
+  // derivados localmente (golden test Go), así que se reutiliza la geometría
+  // ya calculada; para un enlace sin equivalente local (live con datos que
+  // el cálculo local no reproduce) se genera con las mismas reglas visuales.
+  if (sem) {
+    /** Geometría de un enlace semántico sin equivalente derivado localmente. */
+    const semLinkGeometry = (sl: TopoSemLink, wgIdx: number): TopoLink | null => {
+      const curve = (a: { x: number; y: number; r: number }, b: { x: number; y: number }): string => {
+        const edge = pos(a.x, a.y, angleTo(a.x, a.y, b.x, b.y), a.r + 2)
+        const dx = b.x - edge.x
+        const dy = b.y - edge.y
+        return `M ${edge.x} ${edge.y} Q ${edge.x + dx * 0.5 - dy * 0.1} ${edge.y + dy * 0.5 + dx * 0.1}, ${b.x} ${b.y}`
+      }
+      switch (sl.kind) {
+        case 'wan': {
+          if (!gatewayNode || sl.to !== gatewayNode.id) return null
+          return {
+            id: 'wan', kind: 'wan',
+            d: 'M 500 92 C 500 122, 500 162, 500 208',
+            lx: 518, ly: 162, label: `Fibra ${wan.plan} · ${wan.latencyMs} ms`,
+            width: 3, ...flowFor(600),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'uplink': {
+          const i = apNodes.findIndex((n) => n.id === sl.to)
+          const node = i >= 0 ? apNodes[i] : routerById.get(sl.to)
+          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
+          return {
+            id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
+            d: p?.d ?? (from ? curve(from, node) : ''),
+            lx: p?.lx ?? 0, ly: p?.ly ?? 0,
+            label,
+            width: isWifi ? 2 : 3, ...flowFor(Math.max(subtreeTraffic(node.id), isWifi ? 40 : 120)),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'dist': {
+          const dv = distNodes.find((n) => n.id === sl.to)
+          const rn = routerById.get(sl.from)
+          if (!dv || !rn) return null
+          const edge = pos(rn.x, rn.y, angleTo(rn.x, rn.y, dv.x, dv.y), rn.r + 2)
+          const mid = { x: (edge.x + dv.x) / 2, y: (edge.y + dv.y) / 2 }
+          return {
+            id: `dist-${dv.id}`, kind: 'dist',
+            d: `M ${edge.x} ${edge.y} Q ${mid.x + 6} ${mid.y - 6}, ${dv.x} ${dv.y}`,
+            lx: 0, ly: 0, label: '',
+            width: 2.5, ...flowFor(subtreeTraffic(dv.id), true),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'wired': {
+          const chip = chipById.get(sl.to)
+          const hub = hubPos(sl.from)
+          if (!chip || !hub) return null
+          const mbps = deviceHubs.has(chip.id) ? chip.device.trafficMbps + subtreeTraffic(chip.id) : chip.device.trafficMbps
+          return {
+            id: `wired-${chip.id}`, kind: 'wired',
+            d: curve(hub, chip),
+            lx: 0, ly: 0, label: '',
+            width: chip.isCt ? 1.2 : 1.4, ...flowFor(mbps, true),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'wg': {
+          const pn = peerNodes.find((p) => p.id === sl.from)
+          if (!pn) return null
+          const p = WG_PATHS[wgIdx] ?? { d: '', dur: 3.2 }
+          const d = p.d || `M ${pn.x + 7} ${pn.y + 18} C ${pn.x + 60} ${pn.y + 56}, ${internetNode.x - 40} ${internetNode.y + 36}, ${internetNode.x - 26} ${internetNode.y + 22}`
+          return {
+            id: `wg-${pn.peer.id}`, kind: 'wg',
+            d, lx: 0, ly: 0, label: '',
+            width: 2, packets: 1, packetDur: p.dur,
+            from: sl.from, to: sl.to,
+          }
+        }
+      }
+    }
+    const derivedByKey = new Map(links.map((l) => [`${l.kind}|${l.from}|${l.to}`, l] as const))
+    const semLinks: TopoLink[] = []
+    let wgIdx = 0
+    for (const sl of sem.links) {
+      const key = `${sl.kind}|${sl.from}|${sl.to}` as const
+      const hit = derivedByKey.get(key)
+      if (hit) {
+        semLinks.push(hit)
+        derivedByKey.delete(key)
+        if (sl.kind === 'wg') wgIdx++
+        continue
+      }
+      const gen = semLinkGeometry(sl, sl.kind === 'wg' ? wgIdx++ : 0)
+      if (gen) semLinks.push(gen)
+    }
+    links.length = 0
+    links.push(...semLinks)
+  }
+
   /** Guardrail de rendimiento: máx ~60 paquetes simultáneos (mockup) */
   let totalPackets = links.reduce((acc, l) => acc + l.packets, 0)
   if (totalPackets > 60) {
@@ -691,8 +872,17 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     }
   }
 
-  /** Enlaces activos de la red (WAN + uplinks + distribución), sin túneles */
-  const activeLinkCount = links.filter((l) => l.kind === 'wan' || l.kind === 'uplink' || l.kind === 'dist').length
+  /** Enlaces activos de la red: WAN + uplinks + distribución (dist-*) + el
+   *  cable de cada host hipervisor (wired-<host>) — sin túneles WG. Cuadra
+   *  con las filas físicas de la LinksTable (D7); la única fila no contada
+   *  es el túnel WireGuard (se muestra aparte, tone 'tunnel'). */
+  const activeLinkCount = links.filter(
+    (l) =>
+      l.kind === 'wan' ||
+      l.kind === 'uplink' ||
+      l.kind === 'dist' ||
+      (l.kind === 'wired' && hypervisorHosts.has(l.to)),
+  ).length
 
   // Tabla de backhauls (topology.md §④)
   const backhauls: BackhaulRow[] = []
@@ -718,6 +908,45 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       sparkColor: isWifi ? COLOR.warn : COLOR.accent,
     })
   }
+  // D7: enlaces de distribución — el mapa ya los dibuja (dist-*) y
+  // activeLinkCount los cuenta; la tabla también los lista.
+  for (const dv of distNodes) {
+    const rn = routerById.get(dv.node.routerId)
+    if (!rn) continue
+    if (dv.node.kind === 'managed') {
+      backhauls.push({
+        id: `dist-${dv.id}`, a: rn.router.name,
+        b: [dv.node.name, dv.node.ip, 'LLDP', dv.node.port].filter(Boolean).join(' · '),
+        kind: 'dist', type: 'topology.links.managedSwitch',
+        speed: '1 Gbps', signal: '<1 ms',
+        tone: 'ok', statusLabel: 'common.status.online',
+        spark: rn.router.sparkline, sparkColor: COLOR.accent,
+      })
+    } else {
+      backhauls.push({
+        id: `dist-${dv.id}`, a: rn.router.name,
+        b: '', bKey: 'topology.links.inferredSwitch', bVars: { port: dv.node.port },
+        kind: 'dist', type: 'common.cable',
+        speed: '1 Gbps', signal: '<1 ms',
+        tone: 'ok', statusLabel: 'common.status.online',
+        spark: rn.router.sparkline, sparkColor: COLOR.ok,
+      })
+    }
+  }
+  // D7: cable del hipervisor (host con sus CTs/VMs anidados).
+  for (const dn of distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId)) {
+    const host = deviceById.get(dn.hostDeviceId!)
+    const rn = routerById.get(dn.routerId)
+    if (!host || !rn) continue
+    backhauls.push({
+      id: `wired-${host.id}`, a: rn.router.name,
+      b: `${host.name} · ${dn.port} · ${ctCountByHost.get(host.id) ?? 0} CT`,
+      kind: 'wired', type: 'topology.links.hypervisorCable',
+      speed: '—', signal: '—',
+      tone: 'ok', statusLabel: 'common.status.online',
+      spark: host.sparkline, sparkColor: COLOR.ok,
+    })
+  }
   // La tabla canónica muestra un único túnel (el más reciente)
   for (const node of peerNodes.slice(0, 1)) {
     const device = devices.find((d) => d.id === node.peer.id)
@@ -762,6 +991,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     ctsByHost,
     ctCountByHost,
     ringRadii,
+    ringOverflowChips,
     links,
     totalPackets,
     activeLinkCount,

+ 2 - 0
app/src/data/AuthContext.tsx

@@ -9,6 +9,8 @@ export interface AuthUser {
   role: 'admin' | 'user'
   /** 'auto' (navegador) | 'es' | 'en' — fuente de verdad: users.language */
   language?: 'auto' | 'es' | 'en'
+  /** Nombre para saludar (SPEC-65 D65-5); '' = usar username */
+  displayName?: string
 }
 
 const AuthContext = createContext<AuthUser | null>(null)

+ 227 - 3
app/src/data/DataProvider.tsx

@@ -15,8 +15,12 @@
 import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
 import type {
   AdGuardStats,
+  AgentInfo,
+  AlertCategory,
+  AlertConfigLevel,
   AlertEvent,
   AlertQuery,
+  AlertsConfig,
   Device,
   DeviceQuery,
   DeviceTotals,
@@ -26,10 +30,12 @@ import type {
   Paged,
   Router,
   TimeRange,
+  TopoSemantics,
   TrafficPoint,
   WanInfo,
   WireGuardStats,
 } from '@/data/types'
+import { VM_SUPPORTED } from '@/data/types'
 import {
   adguard as mockAdGuard,
   alerts as mockAlerts,
@@ -42,6 +48,12 @@ import {
   wan as mockWan,
   wireguard as mockWireguard,
 } from '@/data/mock'
+import {
+  countUnreadAlerts,
+  loadDemoAlertsConfig,
+  normalizeAlertsConfig,
+  saveDemoAlertsConfig,
+} from '@/data/alertConfig'
 import { buildClientDevices } from '@/pages/devices-data'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import type { RouterExtras } from '@/components/routers/routerExtras'
@@ -74,17 +86,53 @@ export interface NetPulseData {
   topDevices: Device[]
   alerts: AlertEvent[]
   unreadAlerts: number
+  /**
+   * Versión del view-model del último overview (SPEC-65 D65-4). En demo y
+   * antes del primer fetch vale VM_SUPPORTED (el canon local es vm=1).
+   */
+  vm: number
+  /**
+   * Semántica de topología precalculada por el servidor (SPEC-65 D65-3).
+   * Ausente en demo y con servidores viejos → model.ts usa su cálculo local.
+   */
+  topology?: TopoSemantics
 }
 
 export interface NetPulseApi extends NetPulseData {
   connectionStatus: ConnectionStatus
+  /**
+   * Agentes nativos registrados (GET /api/agents, Fase 6). El `slug` casa con
+   * el `id` del router. En demo: lista vacía (sin badges, comportamiento
+   * honesto — no se mockean agentes). Se refresca cada ~30 s en live.
+   */
+  agents: AgentInfo[]
   /** true = sin backend: dataset local del mockup con tick simulado */
   isDemo: boolean
   /** Re-pide `/api/overview` (live); en demo es no-op */
   refresh: () => void
+  /** Date.now() del último snapshot fresco (SSE o fetch de overview); 0 si aún no hubo */
+  lastSnapshotAt: number
+  /**
+   * POST /api/refresh (live): fuerza un sondeo inmediato en el backend; el
+   * snapshot fresco llega por SSE. Resuelve `true` si toca esperar snapshot
+   * (202 o 429 — el tick de 5 s lo empuja igualmente) y `false` si no hay
+   * backend (demo) o falló la petición. En demo es no-op → false.
+   */
+  requestServerRefresh: () => Promise<boolean>
   getRouterDetail: (id: string) => Promise<RouterDetailData | null>
   getDevices: (params?: DeviceQuery) => Promise<Paged<Device>>
   getAlerts: (params?: AlertQuery) => Promise<Paged<AlertEvent>>
+  /**
+   * Configuración de alertas por categoría (SPEC-ALERTAS §2). Live: GET/PUT
+   * /api/alerts/config (kv en backend). Demo: localStorage (UI demostrable).
+   */
+  alertsConfig: AlertsConfig
+  /** Cambia el nivel de UNA categoría (PUT parcial en live). Resuelve true si persistió. */
+  setAlertConfig: (category: AlertCategory, level: AlertConfigLevel) => Promise<boolean>
+  /** Read state en SERVIDOR (live): POST /api/alerts/read. Demo: estado local. Optimista. */
+  markAlertsRead: (ids: string[]) => void
+  /** POST /api/alerts/read-all (live). Demo: estado local. Optimista. */
+  markAllAlertsRead: () => void
 }
 
 // ---------------------------------------------------------------------------
@@ -105,6 +153,7 @@ function initialBundle(): NetPulseData {
     topDevices: [...mockDevices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
     alerts: mockAlerts,
     unreadAlerts: mockAlerts.filter((a) => !a.read).length,
+    vm: VM_SUPPORTED,
   }
 }
 
@@ -152,6 +201,7 @@ function emptyBundle(): NetPulseData {
     topDevices: [],
     alerts: [],
     unreadAlerts: 0,
+    vm: VM_SUPPORTED,
   }
 }
 
@@ -248,9 +298,14 @@ function toQuery(params: Record<string, string | number | undefined>): string {
   return s ? `?${s}` : ''
 }
 
+/** Flag de módulo (B3): el aviso de vm > VM_SUPPORTED sale UNA sola vez. */
+let vmVersionWarned = false
+
 const BACKOFF_MS = [2000, 5000, 15000]
 const POLL_MS = 15000
 const DEMO_TICK_MS = 3000
+// Refresco del estado de agentes (fresh cambia solo en el backend, TTL ~90 s)
+const AGENTS_POLL_MS = 30000
 
 // ---------------------------------------------------------------------------
 // Provider
@@ -264,13 +319,36 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   // isDemo desde el primer render si hay flag de demo (evita que los managers
   // de Ajustes disparen fetches antes del boot y fuercen redirect a /login)
   const [isDemo, setIsDemo] = useState(() => sessionStorage.getItem('netpulse-demo') === '1')
+  // Marca temporal del último snapshot fresco (el botón "Refrescar" gira
+  // hasta que esto avanza o expira su timeout de seguridad)
+  const [lastSnapshotAt, setLastSnapshotAt] = useState(0)
+  // Config de alertas: arranca con la demo (localStorage); en live la
+  // reemplaza GET /api/alerts/config durante el boot
+  const [alertsConfig, setAlertsConfigState] = useState<AlertsConfig>(loadDemoAlertsConfig)
+  // Agentes nativos (live); demo = siempre vacío
+  const [agents, setAgents] = useState<AgentInfo[]>([])
 
   // Refs para closures estables (getters async con la misma firma en ambos modos)
   const bundleRef = useRef(bundle)
   bundleRef.current = bundle
   const modeRef = useRef<'boot' | 'live' | 'demo'>('boot')
+  // Se sincroniza en applyAlertsConfig y en el fetch del boot (nunca en render)
+  const configRef = useRef(alertsConfig)
 
   const applyOverview = useCallback((o: OverviewBundle) => {
+    // SPEC-65 D65-4/D65-9 B3: view-model versionado. Un `vm` mayor que el
+    // soportado avisa UNA sola vez por consola y nunca rompe la UI. Servidor
+    // viejo sin `vm` → se asume la versión soportada. En demo no aplica
+    // (el canon local es vm=1 y no pasa por aquí).
+    const vm = o.vm ?? VM_SUPPORTED
+    if (vm > VM_SUPPORTED && !vmVersionWarned) {
+      vmVersionWarned = true
+      console.warn(
+        `[NetPulse] El servidor sirve view-model vm=${vm}, pero esta app soporta hasta vm=${VM_SUPPORTED}. ` +
+          'La UI sigue funcionando; actualiza la app para ver los campos nuevos.',
+      )
+    }
+    setLastSnapshotAt(Date.now())
     setBundle((prev) => ({
       ...prev,
       health: o.health,
@@ -284,6 +362,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       topDevices: o.topDevices,
       alerts: o.alerts,
       unreadAlerts: o.unreadAlerts,
+      vm,
+      topology: o.topology,
     }))
   }, [])
 
@@ -294,6 +374,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     let pollId: number | undefined
     let reconnectId: number | undefined
     let tickId: number | undefined
+    let agentsPollId: number | undefined
     let backoffIdx = 0
 
     const fetchJson = async (url: string): Promise<Response> => {
@@ -385,18 +466,49 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       }
     }
 
+    const fetchAlertsConfig = async (): Promise<void> => {
+      try {
+        const res = await fetchJson('/api/alerts/config')
+        if (!res.ok) return
+        const cfg = normalizeAlertsConfig(await res.json())
+        if (!disposed) {
+          configRef.current = cfg
+          setAlertsConfigState(cfg)
+        }
+      } catch {
+        /* sin config: se quedan los defaults del SPEC §2 */
+      }
+    }
+
+    // Agentes nativos (Fase 6): no forman parte del overview; se sondean
+    // aparte cada ~30 s. Sin agentes registrados → [] (sin badges).
+    const fetchAgents = async (): Promise<void> => {
+      try {
+        const res = await fetchJson('/api/agents')
+        if (!res.ok) return
+        const json = (await res.json()) as { agents?: AgentInfo[] } | AgentInfo[]
+        const list = Array.isArray(json) ? json : (json.agents ?? [])
+        if (!disposed) setAgents(list)
+      } catch {
+        /* sin agentes: se mantiene el último estado conocido */
+      }
+    }
+
     const startLive = async () => {
       modeRef.current = 'live'
       setIsDemo(false)
       setBundle(emptyBundle()) // live: cero datos del mockup, solo backend
       const ok = await fetchOverview()
       await fetchDevices()
+      await fetchAlertsConfig()
+      await fetchAgents()
       if (disposed) return
       if (ok) setConnectionStatus('connected')
       else {
         setConnectionStatus('reconnecting')
         pollId = window.setInterval(() => void fetchOverview(), POLL_MS)
       }
+      agentsPollId = window.setInterval(() => void fetchAgents(), AGENTS_POLL_MS)
       startSse()
     }
 
@@ -404,6 +516,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       modeRef.current = 'demo'
       setIsDemo(true)
       setConnectionStatus('demo')
+      // Demo: el badge de no leídas respeta la config guardada (SPEC §2)
+      setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, configRef.current) }))
       tickId = window.setInterval(() => {
         if (!disposed) setBundle((prev) => demoTick(prev))
       }, DEMO_TICK_MS)
@@ -427,6 +541,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       stopPolling()
       window.clearTimeout(reconnectId)
       window.clearInterval(tickId)
+      window.clearInterval(agentsPollId)
     }
   }, [applyOverview])
 
@@ -445,6 +560,106 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [applyOverview])
 
+  // Sondeo manual (botón "Refrescar" de Topología): el backend sondea ya y
+  // empuja el snapshot por SSE; aquí solo se dispara la petición. Un 429
+  // (anti-martilleo, min 5 s) también cuenta como "espera": el tick regular
+  // de 5 s del poller empujará un snapshot fresco antes del timeout del botón.
+  const requestServerRefresh = useCallback(async (): Promise<boolean> => {
+    if (modeRef.current !== 'live') return false
+    try {
+      const res = await fetch('/api/refresh', { method: 'POST' })
+      if (res.status === 401) redirectLogin()
+      return res.status === 202 || res.status === 429
+    } catch {
+      return false
+    }
+  }, [])
+
+  // -- Alertas: config + read state (SPEC-ALERTAS §2/§4) -----------------------
+
+  /** Aplica una config nueva al estado y, en demo, la persiste y recalcula el badge. */
+  const applyAlertsConfig = useCallback((cfg: AlertsConfig) => {
+    configRef.current = cfg
+    setAlertsConfigState(cfg)
+    if (modeRef.current !== 'live') {
+      saveDemoAlertsConfig(cfg)
+      setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, cfg) }))
+    }
+  }, [])
+
+  const setAlertConfig = useCallback(
+    async (category: AlertCategory, level: AlertConfigLevel): Promise<boolean> => {
+      const optimistic = { ...configRef.current, [category]: level }
+      applyAlertsConfig(optimistic)
+      if (modeRef.current !== 'live') return true
+      try {
+        const res = await fetch('/api/alerts/config', {
+          method: 'PUT',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ [category]: level }),
+        })
+        if (res.status === 401) redirectLogin()
+        if (!res.ok) {
+          // Resync con la verdad del servidor (p. ej. 400 por valor inválido)
+          const g = await fetch('/api/alerts/config')
+          if (g.status === 401) redirectLogin()
+          if (g.ok) applyAlertsConfig(normalizeAlertsConfig(await g.json()))
+          return false
+        }
+        applyAlertsConfig(normalizeAlertsConfig(await res.json()))
+        refresh() // la lista/badge pueden cambiar con la nueva config
+        return true
+      } catch {
+        return false
+      }
+    },
+    [applyAlertsConfig, refresh],
+  )
+
+  /** Marca leídas de forma optimista; en live además POST /api/alerts/read. */
+  const markAlertsRead = useCallback((ids: string[]) => {
+    if (ids.length === 0) return
+    const idSet = new Set(ids)
+    setBundle((prev) => {
+      const alerts = prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a))
+      const unreadAlerts =
+        modeRef.current === 'live'
+          ? alerts.filter((a) => !a.read).length
+          : countUnreadAlerts(alerts, configRef.current)
+      return { ...prev, alerts, unreadAlerts }
+    })
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/read', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ ids }),
+        })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* el próximo snapshot/SSE resincroniza el read state */
+      }
+    })()
+  }, [])
+
+  const markAllAlertsRead = useCallback(() => {
+    setBundle((prev) => ({
+      ...prev,
+      alerts: prev.alerts.map((a) => ({ ...a, read: true })),
+      unreadAlerts: 0,
+    }))
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/read-all', { method: 'POST' })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* idem: resync por snapshot */
+      }
+    })()
+  }, [])
+
   const getRouterDetail = useCallback(async (id: string): Promise<RouterDetailData | null> => {
     if (modeRef.current === 'live') {
       const res = await fetch(`/api/routers/${encodeURIComponent(id)}`)
@@ -515,15 +730,17 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   }, [])
 
   const getAlerts = useCallback(async (params: AlertQuery = {}): Promise<Paged<AlertEvent>> => {
-    const { severity, page = 1, pageSize = 20 } = params
+    const { severity, category, unread, page = 1, pageSize = 20 } = params
     if (modeRef.current === 'live') {
-      const res = await fetch(`/api/alerts${toQuery({ severity, page, pageSize })}`)
+      const res = await fetch(`/api/alerts${toQuery({ severity, category, unread: unread ? 1 : undefined, page, pageSize })}`)
       if (res.status === 401) redirectLogin()
       if (!res.ok) throw new Error(`GET /api/alerts → ${res.status}`)
       return (await res.json()) as Paged<AlertEvent>
     }
     let items = bundleRef.current.alerts
     if (severity) items = items.filter((a) => a.severity === severity)
+    if (category) items = items.filter((a) => a.category === category)
+    if (unread) items = items.filter((a) => !a.read)
     const start = (page - 1) * pageSize
     return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
   }, [])
@@ -532,13 +749,20 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     () => ({
       ...bundle,
       connectionStatus,
+      agents,
       isDemo,
       refresh,
+      lastSnapshotAt,
+      requestServerRefresh,
       getRouterDetail,
       getDevices,
       getAlerts,
+      alertsConfig,
+      setAlertConfig,
+      markAlertsRead,
+      markAllAlertsRead,
     }),
-    [bundle, connectionStatus, isDemo, refresh, getRouterDetail, getDevices, getAlerts],
+    [bundle, connectionStatus, agents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 83 - 0
app/src/data/alertConfig.ts

@@ -0,0 +1,83 @@
+/**
+ * NetPulse — Configuración de alertas por categoría (SPEC-ALERTAS §2).
+ *
+ * Niveles: "urgent" (solo eventos urgentes) · "all" (todo) · "none" (se
+ * descarta: no se guarda, no cuenta, no empuja). En modo live la fuente de
+ * verdad es el backend (GET/PUT /api/alerts/config, persistencia kv); en demo
+ * (sin backend) vive en localStorage para que la UI sea demostrable.
+ */
+
+import type { AlertCategory, AlertConfigLevel, AlertEvent, AlertsConfig } from '@/data/types'
+
+export const ALERT_CATEGORIES: readonly AlertCategory[] = [
+  'router',
+  'internet',
+  'clients',
+  'signal',
+  'vpn',
+  'system',
+]
+
+export const ALERT_CONFIG_LEVELS: readonly AlertConfigLevel[] = ['urgent', 'all', 'none']
+
+/** Defaults del SPEC §2 (mismo JSON que `alerts.config.v1` en el backend). */
+export const DEFAULT_ALERTS_CONFIG: AlertsConfig = {
+  router: 'urgent',
+  internet: 'urgent',
+  clients: 'urgent',
+  signal: 'none',
+  vpn: 'none',
+  system: 'all',
+}
+
+const DEMO_CONFIG_KEY = 'netpulse-alerts-config-v1'
+
+const isLevel = (v: unknown): v is AlertConfigLevel =>
+  typeof v === 'string' && (ALERT_CONFIG_LEVELS as readonly string[]).includes(v)
+
+/** Normaliza un mapa cualquiera a las 6 claves (rellena defaults, descarta inválidos). */
+export function normalizeAlertsConfig(raw: unknown): AlertsConfig {
+  const cfg = { ...DEFAULT_ALERTS_CONFIG }
+  if (raw && typeof raw === 'object') {
+    for (const cat of ALERT_CATEGORIES) {
+      const v = (raw as Record<string, unknown>)[cat]
+      if (isLevel(v)) cfg[cat] = v
+    }
+  }
+  return cfg
+}
+
+/** Config demo: localStorage con defaults si no hay nada guardado. */
+export function loadDemoAlertsConfig(): AlertsConfig {
+  try {
+    const raw = localStorage.getItem(DEMO_CONFIG_KEY)
+    if (raw) return normalizeAlertsConfig(JSON.parse(raw))
+  } catch {
+    /* localStorage no disponible o JSON corrupto → defaults */
+  }
+  return { ...DEFAULT_ALERTS_CONFIG }
+}
+
+export function saveDemoAlertsConfig(cfg: AlertsConfig): void {
+  try {
+    localStorage.setItem(DEMO_CONFIG_KEY, JSON.stringify(cfg))
+  } catch {
+    /* sin localStorage: la config vive solo en estado */
+  }
+}
+
+/**
+ * ¿Pasa un evento el filtro de su categoría? (semántica §2: none descarta,
+ * urgent solo deja los urgentes). Categoría desconocida → 'all' (no esconder).
+ */
+export function passesAlertConfig(ev: Pick<AlertEvent, 'category' | 'urgent'>, cfg: AlertsConfig): boolean {
+  const level: AlertConfigLevel = cfg[ev.category] ?? 'all'
+  if (level === 'none') return false
+  if (level === 'urgent') return ev.urgent
+  return true
+}
+
+/** No leídas que pasan la config — el contador de la campana en demo. */
+export function countUnreadAlerts(alerts: Pick<AlertEvent, 'category' | 'urgent' | 'read'>[], cfg: AlertsConfig): number {
+  return alerts.filter((a) => !a.read && passesAlertConfig(a, cfg)).length
+}

+ 57 - 1
app/src/data/alertFeed.ts

@@ -94,6 +94,10 @@ export function buildAlertFeed(
   const canon = new Proxy(byId as Record<string, AlertEvent>, {
     get: (target, id: string) => target[id] ?? fallbackCanon[id],
   })
+  // Ts de los eventos de presentación (no canónicos): escalonados en
+  // coherencia con su string "hace X" (SPEC-ALERTAS §5)
+  const now = Math.floor(Date.now() / 1000)
+  const ago = (s: number) => now - s
 
   return [
   // ————— Hoy —————
@@ -146,10 +150,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-pico-trafico',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Pico de tráfico',
     description: '412 Mbps de bajada — streaming 4K en TV Samsung',
     time: 'hace 1 h',
+    ts: ago(3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -168,10 +175,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-backup-nas',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Backup del NAS completado',
     description: 'Copia nocturna adelantada — pico de subida de 96 Mbps',
     time: 'hace 1 h',
+    ts: ago(3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -199,10 +209,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-dns-robot',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Consultas DNS inusuales',
     description: "AdGuard: +340 % desde 'Robot aspirador' (reintentos)",
     time: 'hace 5 h',
+    ts: ago(5 * 3600),
     read: true,
     routerId: 'patio',
     day: 'hoy',
@@ -220,10 +233,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-wg-trabajo',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'Túnel WireGuard cerrado',
     description: 'Portátil trabajo se desconectó tras 6 h de sesión',
     time: 'hace 6 h',
+    ts: ago(6 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -256,10 +272,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-macbook-vpn',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'MacBook Air conectado por VPN',
     description: 'Handshake desde 79.153.x.x · túnel 10.0.0.3',
     time: 'hace 1 día',
+    ts: ago(24 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -277,10 +296,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-canal-patio',
+    category: 'signal',
+    urgent: false,
     severity: 'info',
     title: 'Canal 2.4 GHz cambiado',
     description: 'Patio: canal 6 → 11 (selección automática)',
     time: 'hace 1 día',
+    ts: ago(24 * 3600),
     read: true,
     routerId: 'patio',
     day: 'ayer',
@@ -295,10 +317,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-perdida-ok',
+    category: 'internet',
+    urgent: false,
     severity: 'ok',
     title: 'Pérdida de paquetes resuelta',
     description: 'La WAN vuelve a estar estable (0 % de pérdida)',
     time: 'hace 1 día',
+    ts: ago(25 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -314,10 +339,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-nest-hub',
+    category: 'clients',
+    urgent: false,
     severity: 'info',
     title: 'Nuevo dispositivo',
     description: "'Nest Hub' se ha unido a Estudio",
     time: 'hace 1 día',
+    ts: ago(26 * 3600),
     read: true,
     routerId: 'estudio',
     day: 'ayer',
@@ -334,10 +362,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-adguard-listas',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Listas de AdGuard actualizadas',
     description: '218 442 reglas activas en 6 listas de filtros',
     time: 'hace 1 día',
+    ts: ago(27 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -348,10 +379,13 @@ export function buildAlertFeed(
   // ————— 12 nov (arranque del historial, 32 días) —————
   {
     id: 'evt-reinicio-gateway',
+    category: 'router',
+    urgent: false,
     severity: 'info',
     title: 'Reinicio programado del Gateway',
     description: 'Mantenimiento a las 03:12 — el uptime actual arranca aquí',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -366,10 +400,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-wg-setup',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'WireGuard configurado',
     description: `Servidor ${wg.interface} activo con ${wg.peers.length} peers (${wg.subnet})`,
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -378,10 +415,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-adguard-on',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'AdGuard Home activado',
     description: 'DNS de la red apuntando a 192.168.8.1:3000',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -390,10 +430,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-netpulse-start',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'NetPulse empezó a monitorizar',
     description: 'Primer evento del historial — bienvenido a bordo',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     day: '12nov',
     kind: 'sistema',
@@ -416,12 +459,25 @@ const LIVE_KIND: [RegExp, AlertKind][] = [
   [/^alert-(nuevo|device)/, 'dispositivos'],
 ]
 
+/** Respaldo por categoría (SPEC-ALERTAS §1) cuando el id no casa con LIVE_KIND. */
+const KIND_BY_CATEGORY: Record<AlertEvent['category'], AlertKind> = {
+  router: 'router',
+  internet: 'router',
+  clients: 'dispositivos',
+  signal: 'router',
+  vpn: 'wireguard',
+  system: 'sistema',
+}
+
 /** Mapea las alertas reales a FeedEvent sin contexto inventado. */
 export function buildLiveFeed(canonAlerts: AlertEvent[]): FeedEvent[] {
   return canonAlerts.map((a) => ({
     ...a,
     day: 'hoy' as FeedDay,
-    kind: LIVE_KIND.find(([re]) => re.test(a.id))?.[1] ?? (a.routerId ? 'router' : 'sistema'),
+    kind:
+      LIVE_KIND.find(([re]) => re.test(a.id))?.[1] ??
+      KIND_BY_CATEGORY[a.category] ??
+      (a.routerId ? 'router' : 'sistema'),
   }))
 }
 

+ 2544 - 0
app/src/data/demo-canon.json

@@ -0,0 +1,2544 @@
+{
+  "routers": [
+    {
+      "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": 23,
+      "ram": 41,
+      "temp": 54,
+      "uptime": "32d 14h",
+      "clients": 26,
+      "sparkline": [
+        8,
+        6,
+        5,
+        5,
+        6,
+        9,
+        18,
+        32,
+        41,
+        38,
+        35,
+        44,
+        52,
+        48,
+        45,
+        55,
+        68,
+        84,
+        96,
+        120,
+        150,
+        110,
+        84,
+        40
+      ],
+      "backhaul": "cable"
+    },
+    {
+      "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": 12,
+      "ram": 38,
+      "temp": 47,
+      "uptime": "32d 14h",
+      "clients": 20,
+      "sparkline": [
+        4,
+        3,
+        3,
+        2,
+        3,
+        5,
+        10,
+        22,
+        28,
+        26,
+        24,
+        30,
+        38,
+        35,
+        33,
+        42,
+        55,
+        72,
+        88,
+        105,
+        132,
+        92,
+        61,
+        28
+      ],
+      "backhaul": "cable",
+      "lldp": {
+        "chassis": "Flint 2",
+        "mgmt": "192.168.8.1",
+        "caps": "Bridge, Router",
+        "portDesc": "lan1"
+      }
+    },
+    {
+      "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": 18,
+      "ram": 44,
+      "temp": 51,
+      "uptime": "11d 3h",
+      "clients": 8,
+      "sparkline": [
+        2,
+        2,
+        1,
+        1,
+        2,
+        4,
+        8,
+        15,
+        22,
+        25,
+        24,
+        22,
+        26,
+        24,
+        21,
+        24,
+        28,
+        31,
+        29,
+        24,
+        18,
+        12,
+        8,
+        4
+      ],
+      "backhaul": "cable",
+      "lldp": {
+        "chassis": "Flint 2",
+        "mgmt": "192.168.8.1",
+        "caps": "Bridge, Router",
+        "portDesc": "lan2"
+      }
+    },
+    {
+      "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": 31,
+      "ram": 57,
+      "temp": 71,
+      "uptime": "4d 2h",
+      "clients": 5,
+      "hotMetric": "temp",
+      "sparkline": [
+        1,
+        1,
+        1,
+        1,
+        1,
+        2,
+        3,
+        5,
+        7,
+        8,
+        8,
+        9,
+        10,
+        9,
+        8,
+        9,
+        11,
+        12,
+        13,
+        12,
+        9,
+        6,
+        4,
+        2
+      ],
+      "backhaul": "wifi"
+    }
+  ],
+  "devices": [
+    {
+      "id": "imac-salon",
+      "name": "iMac Salón",
+      "type": "ordenador",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.21",
+      "mac": "A4:83:E7:21:0B:3C",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -48,
+      "trafficMbps": 32.4,
+      "online": true,
+      "sparkline": [
+        12,
+        15,
+        18,
+        22,
+        26,
+        30,
+        34,
+        32,
+        28,
+        30,
+        32,
+        31
+      ],
+      "hostname": "imac-de-marc",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 320 días",
+      "traffic24hRx": "38 GB",
+      "traffic24hTx": "2,1 GB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "tv-samsung",
+      "name": "TV Samsung",
+      "type": "tv",
+      "manufacturer": "Samsung",
+      "ip": "192.168.8.34",
+      "mac": "8C:EA:48:5D:2F:91",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -52,
+      "trafficMbps": 18.1,
+      "online": true,
+      "sparkline": [
+        8,
+        10,
+        14,
+        16,
+        18,
+        20,
+        19,
+        18,
+        17,
+        18,
+        18,
+        18
+      ],
+      "hostname": "samsung-tv-salon",
+      "dhcpLease": "renueva en 7 h 48 min",
+      "firstSeen": "hace 290 días",
+      "traffic24hRx": "54 GB",
+      "traffic24hTx": "1,2 GB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "pixel-8-pro",
+      "name": "Pixel 8 Pro",
+      "type": "movil",
+      "manufacturer": "Google",
+      "ip": "192.168.8.45",
+      "mac": "F2:6D:19:A8:44:C2",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -41,
+      "trafficMbps": 6.2,
+      "online": true,
+      "sparkline": [
+        3,
+        4,
+        5,
+        7,
+        6,
+        8,
+        6,
+        5,
+        7,
+        6,
+        6,
+        6
+      ],
+      "hostname": "pixel-8-pro",
+      "dhcpLease": "renueva en 9 h 12 min",
+      "firstSeen": "hace 214 días",
+      "traffic24hRx": "4,2 GB",
+      "traffic24hTx": "310 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "macbook-air",
+      "name": "MacBook Air",
+      "type": "portatil",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.23",
+      "mac": "3C:22:FB:71:9E:05",
+      "routerId": "estudio",
+      "band": "5 GHz",
+      "signalDbm": -45,
+      "trafficMbps": 4.8,
+      "online": true,
+      "sparkline": [
+        2,
+        3,
+        4,
+        5,
+        5,
+        6,
+        5,
+        4,
+        5,
+        5,
+        5,
+        5
+      ],
+      "hostname": "macbook-air-de-ana",
+      "dhcpLease": "renueva en 5 h 31 min",
+      "firstSeen": "hace 260 días",
+      "traffic24hRx": "18 GB",
+      "traffic24hTx": "2,2 GB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "ps5",
+      "name": "PS5",
+      "type": "consola",
+      "manufacturer": "Sony",
+      "ip": "192.168.8.31",
+      "mac": "78:C8:81:0A:6B:D4",
+      "routerId": "living",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 12.7,
+      "online": true,
+      "sparkline": [
+        4,
+        6,
+        8,
+        10,
+        12,
+        14,
+        13,
+        12,
+        13,
+        12,
+        13,
+        13
+      ],
+      "port": "lan1",
+      "hostname": "ps5-salon",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 300 días",
+      "traffic24hRx": "92 GB",
+      "traffic24hTx": "4,8 GB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "robot-aspirador",
+      "name": "Robot aspirador",
+      "type": "iot",
+      "manufacturer": "Roborock",
+      "ip": "192.168.8.61",
+      "mac": "B0:4A:39:2E:77:10",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -67,
+      "trafficMbps": 0.02,
+      "online": true,
+      "sparkline": [
+        0.01,
+        0.02,
+        0.02,
+        0.03,
+        0.02,
+        0.02,
+        0.02,
+        0.02,
+        0.02,
+        0.02,
+        0.02,
+        0.02
+      ],
+      "hostname": "roborock-s8",
+      "dhcpLease": "renueva en 10 h 2 min",
+      "firstSeen": "hace 180 días",
+      "traffic24hRx": "340 MB",
+      "traffic24hTx": "28 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "camara-porche",
+      "name": "Cámara porche",
+      "type": "camara",
+      "manufacturer": "Reolink",
+      "ip": "192.168.8.71",
+      "mac": "EC:71:DB:44:12:8A",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -72,
+      "trafficMbps": 1.1,
+      "online": true,
+      "sparkline": [
+        1,
+        1.1,
+        1.1,
+        1.2,
+        1.1,
+        1,
+        1.1,
+        1.1,
+        1.2,
+        1.1,
+        1.1,
+        1.1
+      ],
+      "hostname": "reolink-porche",
+      "dhcpLease": "renueva en 3 h 57 min",
+      "firstSeen": "hace 150 días",
+      "traffic24hRx": "11 GB",
+      "traffic24hTx": "640 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "nest-mini",
+      "name": "Nest Mini",
+      "type": "altavoz",
+      "manufacturer": "Google",
+      "ip": "192.168.8.52",
+      "mac": "1A:2B:3C:4D:5E:6F",
+      "routerId": "estudio",
+      "band": "2.4 GHz",
+      "signalDbm": -55,
+      "trafficMbps": 0.4,
+      "online": true,
+      "sparkline": [
+        0.3,
+        0.4,
+        0.4,
+        0.5,
+        0.4,
+        0.4,
+        0.4,
+        0.4,
+        0.4,
+        0.4,
+        0.4,
+        0.4
+      ],
+      "hostname": "nest-mini-estudio",
+      "dhcpLease": "renueva en 8 h 20 min",
+      "firstSeen": "hace 240 días",
+      "traffic24hRx": "1,4 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "nas-synology",
+      "name": "NAS Synology",
+      "type": "servidor",
+      "manufacturer": "Synology",
+      "ip": "192.168.8.10",
+      "mac": "00:11:32:9C:51:B7",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 2.3,
+      "online": true,
+      "sparkline": [
+        1,
+        1.5,
+        2,
+        2.5,
+        3,
+        2.8,
+        2.4,
+        2.2,
+        2.3,
+        2.3,
+        2.3,
+        2.3
+      ],
+      "port": "lan4",
+      "hostname": "diskstation",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 320 días",
+      "traffic24hRx": "96 GB",
+      "traffic24hTx": "1,1 TB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "galaxy-tab-s9",
+      "name": "Galaxy Tab S9",
+      "type": "tablet",
+      "manufacturer": "Samsung",
+      "ip": "192.168.8.48",
+      "mac": "D6:91:2F:07:B3:55",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -50,
+      "trafficMbps": 1.8,
+      "online": true,
+      "sparkline": [
+        0,
+        0,
+        0,
+        0,
+        0,
+        0,
+        0,
+        0,
+        0.5,
+        1.2,
+        1.6,
+        1.8
+      ],
+      "hostname": "galaxy-tab-s9",
+      "dhcpLease": "renueva en 11 h 5 min",
+      "firstSeen": "hoy",
+      "traffic24hRx": "640 MB",
+      "traffic24hTx": "48 MB",
+      "adguard": true,
+      "group": "moviles",
+      "isNew": true,
+      "newThisWeek": true
+    },
+    {
+      "id": "iphone-ana",
+      "name": "iPhone de Ana",
+      "type": "movil",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.44",
+      "mac": "F4:D4:88:19:C2:71",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -46,
+      "trafficMbps": 2.1,
+      "online": true,
+      "sparkline": [
+        2.44,
+        2.86,
+        1.84,
+        1.52,
+        1.73,
+        2.62,
+        1.67,
+        1.89,
+        2.69,
+        1.91,
+        2.38,
+        2.1
+      ],
+      "hostname": "iphone-de-ana",
+      "dhcpLease": "renueva en 6 h 40 min",
+      "firstSeen": "hace 190 días",
+      "traffic24hRx": "2,8 GB",
+      "traffic24hTx": "240 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "macbook-pro",
+      "name": "MacBook Pro de Marc",
+      "type": "portatil",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.26",
+      "mac": "F0:18:98:5A:11:E9",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -44,
+      "trafficMbps": 8.6,
+      "online": true,
+      "sparkline": [
+        10.25,
+        10.6,
+        6.14,
+        7.7,
+        6.7,
+        11.16,
+        10.48,
+        6.81,
+        9.67,
+        7.71,
+        6.9,
+        8.6
+      ],
+      "hostname": "macbook-pro-marc",
+      "dhcpLease": "renueva en 4 h 16 min",
+      "firstSeen": "hace 230 días",
+      "traffic24hRx": "12,4 GB",
+      "traffic24hTx": "1,9 GB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "pc-sobremesa",
+      "name": "PC de sobremesa",
+      "type": "ordenador",
+      "manufacturer": "ASUSTeK",
+      "ip": "192.168.8.11",
+      "mac": "04:D4:C4:8B:30:A7",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 21.3,
+      "online": true,
+      "sparkline": [
+        26.07,
+        23.45,
+        28.77,
+        22.73,
+        15.69,
+        28.73,
+        17.94,
+        14.51,
+        20.6,
+        18.79,
+        27.03,
+        21.3
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "desktop-8f2k1",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 310 días",
+      "traffic24hRx": "84 GB",
+      "traffic24hTx": "6,2 GB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "raspberry-pi",
+      "name": "Raspberry Pi 4",
+      "type": "servidor",
+      "manufacturer": "Raspberry Pi",
+      "ip": "192.168.8.12",
+      "mac": "DC:A6:32:4F:77:02",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.8,
+      "online": true,
+      "sparkline": [
+        1,
+        0.78,
+        0.95,
+        0.99,
+        0.55,
+        1.12,
+        1.01,
+        1.1,
+        0.65,
+        0.69,
+        0.75,
+        0.8
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "raspberrypi",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 320 días",
+      "traffic24hRx": "3,4 GB",
+      "traffic24hTx": "890 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "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": -58,
+      "trafficMbps": 0.6,
+      "online": true,
+      "sparkline": [
+        0.79,
+        0.42,
+        0.52,
+        0.47,
+        0.84,
+        0.42,
+        0.79,
+        0.69,
+        0.78,
+        0.5,
+        0.64,
+        0.6
+      ],
+      "hostname": "nest-doorbell",
+      "dhcpLease": "renueva en 9 h 44 min",
+      "firstSeen": "hace 170 días",
+      "traffic24hRx": "1,2 GB",
+      "traffic24hTx": "140 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "enchufe-lavadora",
+      "name": "Enchufe lavadora",
+      "type": "iot",
+      "manufacturer": "TP-Link",
+      "ip": "192.168.8.81",
+      "mac": "50:C7:BF:22:E1:9C",
+      "routerId": "flint2",
+      "band": "2.4 GHz",
+      "signalDbm": -62,
+      "trafficMbps": 0.01,
+      "online": true,
+      "sparkline": [
+        0.02,
+        0.02,
+        0,
+        0.01,
+        0.02,
+        0,
+        0.01,
+        0.01,
+        0.01,
+        0.01,
+        0,
+        0.01
+      ],
+      "hostname": "tapo-p110-lavadora",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 140 días",
+      "traffic24hRx": "8 MB",
+      "traffic24hTx": "2 MB",
+      "adguard": false,
+      "group": "iot"
+    },
+    {
+      "id": "pixel-7",
+      "name": "Pixel 7",
+      "type": "movil",
+      "manufacturer": "Google",
+      "ip": "192.168.8.46",
+      "mac": "3C:5A:B4:08:D7:5E",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -49,
+      "trafficMbps": 1.4,
+      "online": true,
+      "sparkline": [
+        1.94,
+        1.74,
+        1.87,
+        1.58,
+        1.85,
+        1.12,
+        1.9,
+        1.3,
+        1.37,
+        1.13,
+        1.68,
+        1.4
+      ],
+      "hostname": "pixel-7",
+      "dhcpLease": "renueva en 7 h 3 min",
+      "firstSeen": "hace 205 días",
+      "traffic24hRx": "1,9 GB",
+      "traffic24hTx": "180 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "ipad-air",
+      "name": "iPad Air",
+      "type": "tablet",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.47",
+      "mac": "8C:85:90:2F:B4:11",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -54,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "ipad-air",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 260 días",
+      "traffic24hRx": "6,4 GB",
+      "traffic24hTx": "520 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "portatil-trabajo",
+      "name": "Portátil trabajo",
+      "type": "portatil",
+      "manufacturer": "Lenovo",
+      "ip": "192.168.8.27",
+      "mac": "54:EE:75:9A:03:F1",
+      "routerId": "flint2",
+      "band": "5 GHz",
+      "signalDbm": -50,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "thinkpad-t14",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 160 días",
+      "traffic24hRx": "812 MB",
+      "traffic24hTx": "121 MB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "kindle",
+      "name": "Kindle Paperwhite",
+      "type": "desconocido",
+      "manufacturer": "Amazon",
+      "ip": "192.168.8.49",
+      "mac": "44:65:0D:71:28:C3",
+      "routerId": "flint2",
+      "band": "2.4 GHz",
+      "signalDbm": -58,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "kindle-paperwhite",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 220 días",
+      "traffic24hRx": "220 MB",
+      "traffic24hTx": "8 MB",
+      "adguard": true,
+      "group": "otros",
+      "iconOverride": "BookOpen"
+    },
+    {
+      "id": "bombilla-1",
+      "name": "Bombilla salón 1",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.90",
+      "mac": "CC:86:EC:10:04:21",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -58,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        0.01,
+        0.02,
+        -0,
+        0.01,
+        0.01,
+        0.01,
+        -0,
+        -0,
+        0.01,
+        0.01,
+        -0,
+        0.005
+      ],
+      "hostname": "tradfri-1",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "bombilla-2",
+      "name": "Bombilla salón 2",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.91",
+      "mac": "CC:86:EC:10:04:22",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -59,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        0.01,
+        0.01,
+        0.02,
+        0.01,
+        0.01,
+        0.01,
+        0.01,
+        -0,
+        0.01,
+        0.01,
+        0.01,
+        0.005
+      ],
+      "hostname": "tradfri-2",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "bombilla-3",
+      "name": "Bombilla lámpara pie",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.92",
+      "mac": "CC:86:EC:10:04:23",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -61,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        0.01,
+        0.01,
+        0.01,
+        0.02,
+        0.01,
+        0.01,
+        -0,
+        0.01,
+        0.01,
+        0.01,
+        0,
+        0.005
+      ],
+      "hostname": "tradfri-3",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "bombilla-4",
+      "name": "Bombilla entrada",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.93",
+      "mac": "CC:86:EC:10:04:24",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -64,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        0.02,
+        0.01,
+        0.01,
+        -0,
+        0.01,
+        0.01,
+        0.01,
+        0.01,
+        0,
+        0.01,
+        0.01,
+        0.005
+      ],
+      "hostname": "tradfri-4",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "bombilla-5",
+      "name": "Bombilla pasillo",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.94",
+      "mac": "CC:86:EC:10:04:25",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -66,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        -0,
+        0,
+        0,
+        0,
+        0,
+        0.01,
+        -0,
+        0.01,
+        -0,
+        0.01,
+        0.01,
+        0.005
+      ],
+      "hostname": "tradfri-5",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "bombilla-6",
+      "name": "Bombilla cocina",
+      "type": "iot",
+      "manufacturer": "Ikea Trådfri",
+      "ip": "192.168.8.95",
+      "mac": "CC:86:EC:10:04:26",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -60,
+      "trafficMbps": 0,
+      "online": true,
+      "sparkline": [
+        -0,
+        -0,
+        -0,
+        0.01,
+        0,
+        0.02,
+        0.01,
+        0.01,
+        0.01,
+        0.01,
+        -0,
+        0.005
+      ],
+      "hostname": "tradfri-6",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "4 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "chromecast",
+      "name": "Chromecast HD",
+      "type": "tv",
+      "manufacturer": "Google",
+      "ip": "192.168.8.36",
+      "mac": "54:60:09:E3:5B:0A",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -54,
+      "trafficMbps": 3.9,
+      "online": true,
+      "sparkline": [
+        2.65,
+        3.32,
+        3.28,
+        3.29,
+        4.65,
+        3.72,
+        4.01,
+        5.46,
+        5.1,
+        2.99,
+        3.91,
+        3.9
+      ],
+      "hostname": "chromecast-hd",
+      "dhcpLease": "renueva en 6 h 12 min",
+      "firstSeen": "hace 200 días",
+      "traffic24hRx": "21 GB",
+      "traffic24hTx": "380 MB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "homepod-mini",
+      "name": "HomePod mini",
+      "type": "altavoz",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.53",
+      "mac": "F0:D1:A9:3E:77:5C",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -47,
+      "trafficMbps": 0.3,
+      "online": true,
+      "sparkline": [
+        0.21,
+        0.22,
+        0.2,
+        0.3,
+        0.34,
+        0.3,
+        0.2,
+        0.39,
+        0.35,
+        0.23,
+        0.2,
+        0.3
+      ],
+      "hostname": "homepod-mini",
+      "dhcpLease": "renueva en 10 h 41 min",
+      "firstSeen": "hace 190 días",
+      "traffic24hRx": "2,2 GB",
+      "traffic24hTx": "96 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "galaxy-s23",
+      "name": "Galaxy S23",
+      "type": "movil",
+      "manufacturer": "Samsung",
+      "ip": "192.168.8.42",
+      "mac": "5C:0A:5B:88:1D:E4",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -51,
+      "trafficMbps": 0.9,
+      "online": true,
+      "sparkline": [
+        0.67,
+        1.25,
+        1.18,
+        1.07,
+        1,
+        0.95,
+        0.97,
+        1.06,
+        0.89,
+        0.66,
+        1.02,
+        0.9
+      ],
+      "hostname": "galaxy-s23",
+      "dhcpLease": "renueva en 8 h 55 min",
+      "firstSeen": "hace 175 días",
+      "traffic24hRx": "3,2 GB",
+      "traffic24hTx": "290 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "echo-dot",
+      "name": "Echo Dot",
+      "type": "altavoz",
+      "manufacturer": "Amazon",
+      "ip": "192.168.8.54",
+      "mac": "74:C2:46:19:F0:6B",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -56,
+      "trafficMbps": 0.2,
+      "online": true,
+      "sparkline": [
+        0.15,
+        0.25,
+        0.23,
+        0.27,
+        0.21,
+        0.22,
+        0.14,
+        0.21,
+        0.17,
+        0.14,
+        0.16,
+        0.2
+      ],
+      "hostname": "echo-dot-cocina",
+      "dhcpLease": "renueva en 11 h 18 min",
+      "firstSeen": "hace 210 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "74 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "nintendo-switch",
+      "name": "Nintendo Switch",
+      "type": "consola",
+      "manufacturer": "Nintendo",
+      "ip": "192.168.8.33",
+      "mac": "58:BD:A3:4C:E2:09",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -53,
+      "trafficMbps": 0.1,
+      "online": true,
+      "sparkline": [
+        0.03,
+        0.15,
+        0.1,
+        -0,
+        0.11,
+        0.16,
+        0.15,
+        0.08,
+        0,
+        0,
+        0.2,
+        0.1
+      ],
+      "hostname": "switch-oled",
+      "dhcpLease": "renueva en 5 h 47 min",
+      "firstSeen": "hace 240 días",
+      "traffic24hRx": "8,6 GB",
+      "traffic24hTx": "310 MB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "portatil-invitado",
+      "name": "Portátil invitado",
+      "type": "portatil",
+      "manufacturer": "Desconocido",
+      "ip": "192.168.8.29",
+      "mac": "A2:7E:9C:41:0B:6D",
+      "routerId": "living",
+      "band": "5 GHz",
+      "signalDbm": -58,
+      "trafficMbps": 0.7,
+      "online": true,
+      "sparkline": [
+        0.59,
+        0.7,
+        0.58,
+        0.63,
+        0.68,
+        0.84,
+        0.52,
+        0.59,
+        0.92,
+        0.49,
+        0.66,
+        0.7
+      ],
+      "hostname": "unknown-7f2a",
+      "dhcpLease": "renueva en 2 h 9 min",
+      "firstSeen": "hoy",
+      "traffic24hRx": "480 MB",
+      "traffic24hTx": "62 MB",
+      "adguard": false,
+      "group": "ordenadores",
+      "isNew": true,
+      "newThisWeek": true
+    },
+    {
+      "id": "portatil-antiguo",
+      "name": "Portátil antiguo",
+      "type": "portatil",
+      "manufacturer": "HP",
+      "ip": "192.168.8.28",
+      "mac": "3C:52:82:5D:90:17",
+      "routerId": "living",
+      "band": "2.4 GHz",
+      "signalDbm": -62,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "hp-pavilion-15",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 300 días",
+      "traffic24hRx": "0 MB",
+      "traffic24hTx": "0 MB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "mac-mini",
+      "name": "Mac mini",
+      "type": "ordenador",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.22",
+      "mac": "A4:83:E7:66:2C:98",
+      "routerId": "estudio",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 1.9,
+      "online": true,
+      "sparkline": [
+        1.9,
+        2.16,
+        1.53,
+        1.83,
+        1.45,
+        1.25,
+        2.4,
+        2.08,
+        2.53,
+        2.7,
+        1.66,
+        1.9
+      ],
+      "hostname": "mac-mini",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "44 GB",
+      "traffic24hTx": "5,6 GB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "enchufe-ventilador",
+      "name": "Enchufe ventilador",
+      "type": "iot",
+      "manufacturer": "TP-Link",
+      "ip": "192.168.8.82",
+      "mac": "9C:53:22:B1:4E:70",
+      "routerId": "estudio",
+      "band": "2.4 GHz",
+      "signalDbm": -59,
+      "trafficMbps": 0.01,
+      "online": true,
+      "sparkline": [
+        0.01,
+        0.01,
+        0,
+        0.01,
+        0,
+        0,
+        0.01,
+        0.01,
+        0.01,
+        0.02,
+        0.02,
+        0.01
+      ],
+      "hostname": "tapo-p110-ventilador",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 120 días",
+      "traffic24hRx": "7 MB",
+      "traffic24hTx": "2 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "ipad-pro",
+      "name": "iPad Pro",
+      "type": "tablet",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.51",
+      "mac": "F0:18:98:91:5A:2B",
+      "routerId": "estudio",
+      "band": "5 GHz",
+      "signalDbm": -49,
+      "trafficMbps": 0.8,
+      "online": true,
+      "sparkline": [
+        0.85,
+        0.7,
+        1.02,
+        1.05,
+        0.54,
+        0.61,
+        1.05,
+        0.7,
+        0.82,
+        1.12,
+        0.81,
+        0.8
+      ],
+      "hostname": "ipad-pro",
+      "dhcpLease": "renueva en 9 h 26 min",
+      "firstSeen": "hace 160 días",
+      "traffic24hRx": "5,1 GB",
+      "traffic24hTx": "390 MB",
+      "adguard": true,
+      "group": "moviles"
+    },
+    {
+      "id": "hue-hub",
+      "name": "Hub Philips Hue",
+      "type": "iot",
+      "manufacturer": "Signify",
+      "ip": "192.168.8.15",
+      "mac": "00:17:88:2A:91:CE",
+      "routerId": "estudio",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.02,
+      "online": true,
+      "sparkline": [
+        0.02,
+        0.01,
+        0.03,
+        0,
+        0.04,
+        0.01,
+        0.02,
+        0.01,
+        0.01,
+        0.04,
+        0,
+        0.02
+      ],
+      "hostname": "philips-hue-bridge",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 280 días",
+      "traffic24hRx": "96 MB",
+      "traffic24hTx": "22 MB",
+      "adguard": false,
+      "group": "iot"
+    },
+    {
+      "id": "sonos-one",
+      "name": "Sonos One",
+      "type": "altavoz",
+      "manufacturer": "Sonos",
+      "ip": "192.168.8.55",
+      "mac": "48:A6:B8:14:72:E0",
+      "routerId": "estudio",
+      "band": "2.4 GHz",
+      "signalDbm": -57,
+      "trafficMbps": 0.5,
+      "online": true,
+      "sparkline": [
+        0.56,
+        0.71,
+        0.48,
+        0.43,
+        0.7,
+        0.43,
+        0.68,
+        0.33,
+        0.35,
+        0.68,
+        0.57,
+        0.5
+      ],
+      "hostname": "sonos-one-estudio",
+      "dhcpLease": "renueva en 10 h 4 min",
+      "firstSeen": "hace 195 días",
+      "traffic24hRx": "3,8 GB",
+      "traffic24hTx": "110 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "iphone-trabajo",
+      "name": "iPhone de trabajo",
+      "type": "movil",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.50",
+      "mac": "8C:85:90:47:C1:93",
+      "routerId": "estudio",
+      "band": "5 GHz",
+      "signalDbm": -47,
+      "trafficMbps": 0.3,
+      "online": true,
+      "sparkline": [
+        0.35,
+        0.38,
+        0.24,
+        0.31,
+        0.4,
+        0.27,
+        0.29,
+        0.4,
+        0.4,
+        0.41,
+        0.24,
+        0.3
+      ],
+      "hostname": "iphone-15-pro-work",
+      "dhcpLease": "renueva en 3 h 38 min",
+      "firstSeen": "hoy",
+      "traffic24hRx": "320 MB",
+      "traffic24hTx": "41 MB",
+      "adguard": true,
+      "group": "moviles",
+      "isNew": true,
+      "newThisWeek": true
+    },
+    {
+      "id": "macbook-viejo",
+      "name": "MacBook viejo",
+      "type": "portatil",
+      "manufacturer": "Apple",
+      "ip": "192.168.8.25",
+      "mac": "3C:22:FB:0E:66:A1",
+      "routerId": "estudio",
+      "band": "2.4 GHz",
+      "signalDbm": -60,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "macbook-pro-2015",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 320 días",
+      "traffic24hRx": "0 MB",
+      "traffic24hTx": "0 MB",
+      "adguard": true,
+      "group": "ordenadores"
+    },
+    {
+      "id": "camara-jardin",
+      "name": "Cámara jardín",
+      "type": "camara",
+      "manufacturer": "Reolink",
+      "ip": "192.168.8.73",
+      "mac": "EC:71:DB:44:12:9B",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -74,
+      "trafficMbps": 1.4,
+      "online": true,
+      "sparkline": [
+        1.84,
+        2,
+        1.08,
+        1.52,
+        1.59,
+        1.63,
+        0.97,
+        1.11,
+        1.9,
+        1.79,
+        1.04,
+        1.4
+      ],
+      "hostname": "reolink-jardin",
+      "dhcpLease": "renueva en 8 h 49 min",
+      "firstSeen": "hace 4 días",
+      "traffic24hRx": "14 GB",
+      "traffic24hTx": "820 MB",
+      "adguard": true,
+      "group": "iot",
+      "newThisWeek": true
+    },
+    {
+      "id": "sensor-riego",
+      "name": "Sensor de riego",
+      "type": "iot",
+      "manufacturer": "Tuya",
+      "ip": "192.168.8.89",
+      "mac": "D8:1F:12:5B:08:44",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -71,
+      "trafficMbps": 0.01,
+      "online": true,
+      "sparkline": [
+        0.02,
+        0.02,
+        0.02,
+        0.02,
+        0.01,
+        0.02,
+        0.01,
+        0,
+        0.02,
+        0.02,
+        0.02,
+        0.01
+      ],
+      "hostname": "tuya-riego-01",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 5 días",
+      "traffic24hRx": "2 MB",
+      "traffic24hTx": "1 MB",
+      "adguard": false,
+      "group": "iot",
+      "newThisWeek": true
+    },
+    {
+      "id": "enchufe-calefactor",
+      "name": "Enchufe calefactor",
+      "type": "iot",
+      "manufacturer": "TP-Link",
+      "ip": "192.168.8.80",
+      "mac": "50:C7:BF:31:7A:05",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -75,
+      "trafficMbps": 0.02,
+      "online": true,
+      "sparkline": [
+        0.03,
+        0.03,
+        0.03,
+        0.04,
+        0.02,
+        0.03,
+        0.01,
+        0.03,
+        0.02,
+        0.03,
+        0.02,
+        0.02
+      ],
+      "hostname": "tapo-p110-calefactor",
+      "dhcpLease": "renueva en 12 h 0 min",
+      "firstSeen": "hace 96 días",
+      "traffic24hRx": "6 MB",
+      "traffic24hTx": "2 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "camara-garaje",
+      "name": "Cámara garaje",
+      "type": "camara",
+      "manufacturer": "Reolink",
+      "ip": "192.168.8.74",
+      "mac": "EC:71:DB:44:13:02",
+      "routerId": "patio",
+      "band": "2.4 GHz",
+      "signalDbm": -78,
+      "trafficMbps": 0,
+      "online": false,
+      "sparkline": [],
+      "hostname": "reolink-garaje",
+      "dhcpLease": "Expirado",
+      "firstSeen": "hace 130 días",
+      "traffic24hRx": "0 MB",
+      "traffic24hTx": "0 MB",
+      "adguard": false,
+      "group": "iot"
+    },
+    {
+      "id": "switch-netgear",
+      "name": "Switch GS308E",
+      "type": "switch",
+      "manufacturer": "Netgear",
+      "ip": "192.168.8.13",
+      "mac": "28:C6:8E:1D:90:44",
+      "routerId": "living",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.02,
+      "online": true,
+      "sparkline": [
+        0.03,
+        0.01,
+        0.02,
+        0.04,
+        0,
+        0,
+        0.01,
+        0.03,
+        0,
+        0.01,
+        0.04,
+        0.02
+      ],
+      "port": "lan3",
+      "lldp": {
+        "chassis": "GS308E",
+        "mgmt": "192.168.8.13",
+        "caps": "Bridge",
+        "portDesc": "ge5"
+      },
+      "attachTo": "living",
+      "infra": "managed-switch",
+      "hostname": "gs308e",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 300 días",
+      "traffic24hRx": "64 MB",
+      "traffic24hTx": "12 MB",
+      "adguard": false,
+      "group": "red",
+      "iconOverride": "Network"
+    },
+    {
+      "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": null,
+      "trafficMbps": 9.8,
+      "online": true,
+      "sparkline": [
+        3,
+        5,
+        7,
+        9,
+        11,
+        12,
+        10,
+        9,
+        10,
+        9,
+        10,
+        9.8
+      ],
+      "attachTo": "dist-living-lan3",
+      "hostname": "xbox-series-s",
+      "dhcpLease": "renueva en 4 h 12 min",
+      "firstSeen": "hace 140 días",
+      "traffic24hRx": "31 GB",
+      "traffic24hTx": "1,9 GB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "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": null,
+      "trafficMbps": 15.2,
+      "online": true,
+      "sparkline": [
+        6,
+        8,
+        10,
+        12,
+        14,
+        16,
+        15,
+        14,
+        15,
+        15,
+        15,
+        15.2
+      ],
+      "attachTo": "dist-living-lan3",
+      "hostname": "apple-tv-4k",
+      "dhcpLease": "renueva en 6 h 3 min",
+      "firstSeen": "hace 210 días",
+      "traffic24hRx": "88 GB",
+      "traffic24hTx": "3,4 GB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "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": null,
+      "trafficMbps": 0.6,
+      "online": true,
+      "sparkline": [
+        0.4,
+        0.5,
+        0.5,
+        0.6,
+        0.6,
+        0.7,
+        0.6,
+        0.6,
+        0.6,
+        0.6,
+        0.6,
+        0.6
+      ],
+      "attachTo": "dist-living-lan3",
+      "hostname": "denon-avr",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 320 días",
+      "traffic24hRx": "640 MB",
+      "traffic24hTx": "42 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "pve",
+      "name": "Proxmox pve",
+      "type": "servidor",
+      "manufacturer": "Supermicro",
+      "ip": "192.168.8.5",
+      "mac": "3C:52:82:10:20:30",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 12.3,
+      "online": true,
+      "sparkline": [
+        8,
+        9,
+        10,
+        11,
+        12,
+        13,
+        12,
+        12,
+        12,
+        12,
+        12,
+        12.3
+      ],
+      "port": "lan5",
+      "infra": "hypervisor",
+      "hostname": "pve",
+      "dhcpLease": "IP fija (reserva)",
+      "firstSeen": "hace 400 días",
+      "traffic24hRx": "1,2 TB",
+      "traffic24hTx": "96 GB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-pihole",
+      "name": "Pi-hole",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.41",
+      "mac": "BC:24:11:00:20:10",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 6.1,
+      "online": true,
+      "sparkline": [
+        4.1,
+        5.1,
+        6.1,
+        7.1,
+        8.1,
+        4.1,
+        5.1,
+        6.1,
+        7.1,
+        8.1,
+        4.1,
+        5.1
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-pihole",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-home-assistant",
+      "name": "Home Assistant",
+      "type": "iot",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.42",
+      "mac": "BC:24:11:00:21:11",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 4.2,
+      "online": true,
+      "sparkline": [
+        3.2,
+        4.2,
+        5.2,
+        6.2,
+        2.2,
+        3.2,
+        4.2,
+        5.2,
+        6.2,
+        2.2,
+        3.2,
+        4.2
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-home-assistant",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-nextcloud",
+      "name": "Nextcloud",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.43",
+      "mac": "BC:24:11:00:22:12",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 7.8,
+      "online": true,
+      "sparkline": [
+        7.8,
+        8.8,
+        9.8,
+        5.8,
+        6.8,
+        7.8,
+        8.8,
+        9.8,
+        5.8,
+        6.8,
+        7.8,
+        8.8
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-nextcloud",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-jellyfin",
+      "name": "Jellyfin",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.44",
+      "mac": "BC:24:11:00:23:13",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 9.4,
+      "online": true,
+      "sparkline": [
+        10.4,
+        11.4,
+        7.4,
+        8.4,
+        9.4,
+        10.4,
+        11.4,
+        7.4,
+        8.4,
+        9.4,
+        10.4,
+        11.4
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-jellyfin",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-immich",
+      "name": "Immich",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.45",
+      "mac": "BC:24:11:00:24:14",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 3.3,
+      "online": true,
+      "sparkline": [
+        5.3,
+        1.2999999999999998,
+        2.3,
+        3.3,
+        4.3,
+        5.3,
+        1.2999999999999998,
+        2.3,
+        3.3,
+        4.3,
+        5.3,
+        1.2999999999999998
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-immich",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-gitea",
+      "name": "Gitea",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.46",
+      "mac": "BC:24:11:00:25:15",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 1.2,
+      "online": true,
+      "sparkline": [
+        0.1,
+        0.19999999999999996,
+        1.2,
+        2.2,
+        3.2,
+        0.1,
+        0.19999999999999996,
+        1.2,
+        2.2,
+        3.2,
+        0.1,
+        0.19999999999999996
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-gitea",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-uptime-kuma",
+      "name": "Uptime Kuma",
+      "type": "iot",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.47",
+      "mac": "BC:24:11:00:26:16",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.4,
+      "online": true,
+      "sparkline": [
+        0.1,
+        0.3999999999999999,
+        1.4,
+        2.4,
+        0.1,
+        0.1,
+        0.3999999999999999,
+        1.4,
+        2.4,
+        0.1,
+        0.1,
+        0.3999999999999999
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-uptime-kuma",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-adguard-sync",
+      "name": "AdGuard sync",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.48",
+      "mac": "BC:24:11:00:27:17",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.8,
+      "online": true,
+      "sparkline": [
+        0.8,
+        1.8,
+        2.8,
+        0.1,
+        0.1,
+        0.8,
+        1.8,
+        2.8,
+        0.1,
+        0.1,
+        0.8,
+        1.8
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-adguard-sync",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-postgres",
+      "name": "Postgres",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.49",
+      "mac": "BC:24:11:00:28:18",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 2.1,
+      "online": true,
+      "sparkline": [
+        3.1,
+        4.1,
+        0.10000000000000009,
+        1.1,
+        2.1,
+        3.1,
+        4.1,
+        0.10000000000000009,
+        1.1,
+        2.1,
+        3.1,
+        4.1
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-postgres",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "ct-redis",
+      "name": "Redis",
+      "type": "servidor",
+      "manufacturer": "Proxmox VE (CT)",
+      "ip": "192.168.8.50",
+      "mac": "BC:24:11:00:29:19",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.9,
+      "online": true,
+      "sparkline": [
+        2.9,
+        0.1,
+        0.1,
+        0.8999999999999999,
+        1.9,
+        2.9,
+        0.1,
+        0.1,
+        0.8999999999999999,
+        1.9,
+        2.9,
+        0.1
+      ],
+      "attachTo": "pve",
+      "infra": "ct",
+      "hostname": "ct-redis",
+      "dhcpLease": "renueva en 3 h 10 min",
+      "firstSeen": "hace 90 días",
+      "traffic24hRx": "1,1 GB",
+      "traffic24hTx": "88 MB",
+      "adguard": true,
+      "group": "red"
+    },
+    {
+      "id": "tv-salon-cable",
+      "name": "TV Salón (cable)",
+      "type": "tv",
+      "manufacturer": "Samsung",
+      "ip": "192.168.8.61",
+      "mac": "8C:EA:48:AA:02:02",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 24.4,
+      "online": true,
+      "sparkline": [
+        22.9,
+        23.4,
+        23.9,
+        24.4,
+        22.9,
+        23.4,
+        23.9,
+        24.4,
+        22.9,
+        23.4,
+        23.9,
+        24.4
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "tv-salon-cable",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "impresora-hp",
+      "name": "Impresora HP",
+      "type": "iot",
+      "manufacturer": "HP",
+      "ip": "192.168.8.62",
+      "mac": "3C:D9:2B:AA:03:03",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.1,
+      "online": true,
+      "sparkline": [
+        0.05,
+        0.05,
+        0.10000000000000009,
+        0.05,
+        0.05,
+        0.05,
+        0.10000000000000009,
+        0.05,
+        0.05,
+        0.05,
+        0.10000000000000009,
+        0.05
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "impresora-hp",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "iot",
+      "iconOverride": "Printer"
+    },
+    {
+      "id": "xbox-one",
+      "name": "Xbox One",
+      "type": "consola",
+      "manufacturer": "Microsoft",
+      "ip": "192.168.8.64",
+      "mac": "7C:ED:8D:AA:05:05",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 4.2,
+      "online": true,
+      "sparkline": [
+        3.7,
+        4.2,
+        2.7,
+        3.2,
+        3.7,
+        4.2,
+        2.7,
+        3.2,
+        3.7,
+        4.2,
+        2.7,
+        3.2
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "xbox-one",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "otros"
+    },
+    {
+      "id": "receptor-av",
+      "name": "Receptor AV",
+      "type": "altavoz",
+      "manufacturer": "Denon",
+      "ip": "192.168.8.65",
+      "mac": "00:05:CD:AA:06:06",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.3,
+      "online": true,
+      "sparkline": [
+        0.30000000000000004,
+        0.05,
+        0.05,
+        0.05,
+        0.30000000000000004,
+        0.05,
+        0.05,
+        0.05,
+        0.30000000000000004,
+        0.05,
+        0.05,
+        0.05
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "receptor-av",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "iot"
+    },
+    {
+      "id": "deco-orange",
+      "name": "Deco Orange",
+      "type": "tv",
+      "manufacturer": "Sagemcom",
+      "ip": "192.168.8.66",
+      "mac": "48:83:B4:AA:07:07",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 1.1,
+      "online": true,
+      "sparkline": [
+        0.05,
+        0.10000000000000009,
+        0.6000000000000001,
+        1.1,
+        0.05,
+        0.10000000000000009,
+        0.6000000000000001,
+        1.1,
+        0.05,
+        0.10000000000000009,
+        0.6000000000000001,
+        1.1
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "deco-orange",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "tv"
+    },
+    {
+      "id": "pc-invitado",
+      "name": "PC invitado",
+      "type": "ordenador",
+      "manufacturer": "—",
+      "ip": "192.168.8.67",
+      "mac": "A2:F4:11:AA:08:08",
+      "routerId": "flint2",
+      "band": "cable",
+      "signalDbm": null,
+      "trafficMbps": 0.8,
+      "online": true,
+      "sparkline": [
+        0.05,
+        0.30000000000000004,
+        0.8,
+        0.05,
+        0.05,
+        0.30000000000000004,
+        0.8,
+        0.05,
+        0.05,
+        0.30000000000000004,
+        0.8,
+        0.05
+      ],
+      "attachTo": "dist-flint2-lan3",
+      "hostname": "pc-invitado",
+      "dhcpLease": "renueva en 5 h 22 min",
+      "firstSeen": "hace 60 días",
+      "traffic24hRx": "2,4 GB",
+      "traffic24hTx": "120 MB",
+      "adguard": true,
+      "group": "ordenadores"
+    }
+  ],
+  "deviceTotals": {
+    "total": 65,
+    "online": 59,
+    "knownOffline": 6,
+    "newToday": 3
+  },
+  "distributionNodes": [
+    {
+      "id": "dist-flint2-lan3",
+      "kind": "inferred",
+      "routerId": "flint2",
+      "port": "lan3",
+      "macCount": 8
+    },
+    {
+      "id": "dist-pve",
+      "kind": "hypervisor",
+      "routerId": "flint2",
+      "port": "lan5",
+      "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",
+      "mac": "28:C6:8E:1D:90:44",
+      "lldp": {
+        "chassis": "GS308E",
+        "mgmt": "192.168.8.13",
+        "caps": "Bridge",
+        "portDesc": "ge5"
+      }
+    }
+  ],
+  "adguard": {
+    "host": "192.168.8.1",
+    "port": 3000,
+    "status": "active",
+    "queries24h": 84312,
+    "blocked24h": 15687,
+    "blockedPct": 18.6,
+    "trackersBlocked": 9204,
+    "dnsLatencyMs": 14,
+    "clientsUsing": 60,
+    "clientsTotal": 65,
+    "topBlocked": [
+      {
+        "domain": "graph.facebook.com",
+        "count": 1204
+      },
+      {
+        "domain": "adservice.google.com",
+        "count": 986
+      },
+      {
+        "domain": "metrics.icloud.com",
+        "count": 731
+      },
+      {
+        "domain": "telemetry.nvidia.com",
+        "count": 512
+      },
+      {
+        "domain": "ads.tiktok.com",
+        "count": 448
+      }
+    ],
+    "filterLists": 6,
+    "rules": 218442
+  },
+  "wireguard": {
+    "interface": "wg0",
+    "subnet": "10.0.0.1/24",
+    "status": "active",
+    "peers": [
+      {
+        "id": "pixel-8-pro",
+        "name": "Pixel 8 Pro",
+        "type": "movil",
+        "tunnelIp": "10.0.0.2",
+        "active": true,
+        "lastHandshake": "hace 38 s",
+        "rx": "1,2 GB",
+        "tx": "214 MB"
+      },
+      {
+        "id": "macbook-air",
+        "name": "MacBook Air",
+        "type": "portatil",
+        "tunnelIp": "10.0.0.3",
+        "active": true,
+        "lastHandshake": "hace 1 min",
+        "rx": "640 MB",
+        "tx": "88 MB"
+      },
+      {
+        "id": "ipad-air",
+        "name": "iPad Air",
+        "type": "tablet",
+        "tunnelIp": "10.0.0.4",
+        "active": false,
+        "lastHandshake": "hace 2 días",
+        "rx": "3,1 GB",
+        "tx": "402 MB"
+      },
+      {
+        "id": "portatil-trabajo",
+        "name": "Portátil trabajo",
+        "type": "portatil",
+        "tunnelIp": "10.0.0.5",
+        "active": false,
+        "lastHandshake": "hace 6 h",
+        "rx": "812 MB",
+        "tx": "121 MB"
+      },
+      {
+        "id": "casa-familia",
+        "name": "Casa familia",
+        "type": "sitio",
+        "tunnelIp": "10.0.0.6",
+        "active": false,
+        "lastHandshake": "hace 9 días",
+        "rx": "12 GB",
+        "tx": "4,2 GB"
+      }
+    ]
+  },
+  "wan": {
+    "plan": "600/600 Mbps",
+    "downMbps": 84.2,
+    "upMbps": 12.6,
+    "latencyMs": 8,
+    "lossPct": 0,
+    "publicIp": "84.122.x.x",
+    "isp": "Digi",
+    "peakTodayMbps": 412,
+    "peakTodayTime": "21:14",
+    "avgDownMbps": 61,
+    "total24h": "1,32 TB"
+  },
+  "health": {
+    "score": 92,
+    "label": "Excelente",
+    "caption": "Puntuación de salud de la red",
+    "note": "Penalizado por la temperatura del Patio.",
+    "breakdown": [
+      {
+        "label": "temp. Patio",
+        "delta": -4
+      },
+      {
+        "label": "cobertura Patio",
+        "delta": -2
+      },
+      {
+        "label": "canal 2.4 GHz congestionado",
+        "delta": -2
+      }
+    ]
+  }
+}

+ 38 - 330
app/src/data/mock.ts

@@ -1,7 +1,13 @@
 /**
  * NetPulse — Datos mock canónicos (design.md §11).
  * CONTRATO: todas las páginas importan de `@/data/mock`.
- * No modificar valores sin actualizar design.md.
+ *
+ * SPEC-65 D65-1 (single-source): el canon (routers, devices, deviceTotals,
+ * distributionNodes, adguard, wireguard, wan, health) vive SOLO en
+ * `demo-canon.json`, generado desde Go (`go run ./cmd/gen-demo-canon` en
+ * server-go). NUNCA editar el JSON a mano: hay un test Go de frescura.
+ * Aquí quedan solo: paleta, tráfico local del tick demo (random walk — no
+ * está en el JSON a propósito), alertas del tick demo y helpers.
  */
 
 // ---------------------------------------------------------------------------
@@ -10,10 +16,12 @@
 // ---------------------------------------------------------------------------
 
 import { numLocale } from '@/i18n'
+import canon from '@/data/demo-canon.json'
 import type {
   AdGuardStats,
   AlertEvent,
   Device,
+  DeviceTotals,
   DistributionNode,
   HealthScore,
   Router,
@@ -29,6 +37,7 @@ export type {
   AlertSeverity,
   Band,
   Device,
+  DeviceInfra,
   DeviceTotals,
   DeviceType,
   DistributionNode,
@@ -38,6 +47,8 @@ export type {
   Router,
   Status,
   TimeRange,
+  TopoSemantics,
+  TopoSemLink,
   TrafficPoint,
   WanInfo,
   WGPeer,
@@ -50,105 +61,21 @@ export type {
 
 export const CHART_COLORS = ['#22D3EE', '#A78BFA', '#34D399', '#FBBF24', '#FB7185', '#60A5FA'] as const
 
-// ---------------------------------------------------------------------------
-// Routers (canon §11)
-// ---------------------------------------------------------------------------
-
-export const routers: Router[] = [
-  {
-    id: 'flint2',
-    name: 'Gateway',
-    model: 'GL.iNet Flint 2 (GL-MT6000)',
-    modelShort: 'GL.iNet Flint 2',
-    role: 'Main gateway',
-    roleBadge: 'Principal',
-    ip: '192.168.8.1',
-    backhaul: 'cable',
-    status: 'online',
-    health: 98,
-    cpu: 23,
-    ram: 41,
-    temp: 54,
-    uptime: '32d 14h',
-    clients: 33,
-    sparkline: [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: 'Living Room',
-    model: 'OpenWrt AP (Xiaomi AX3000T)',
-    modelShort: 'Xiaomi AX3000T',
-    role: 'Access point',
-    roleBadge: 'AP',
-    ip: '192.168.8.2',
-    backhaul: 'cable',
-    lldp: { chassis: 'AX3000T', caps: 'Bridge, Wlan', portDesc: 'eth0' },
-    status: 'online',
-    health: 95,
-    cpu: 12,
-    ram: 38,
-    temp: 47,
-    uptime: '32d 14h',
-    clients: 22,
-    sparkline: [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: 'Study',
-    model: 'OpenWrt (NanoPi R4S)',
-    modelShort: 'NanoPi R4S',
-    role: 'AP + switch',
-    roleBadge: 'AP',
-    ip: '192.168.8.3',
-    backhaul: 'cable',
-    lldp: { chassis: 'NanoPi-R4S', caps: 'Bridge, Router', portDesc: 'eth0' },
-    status: 'online',
-    health: 92,
-    cpu: 18,
-    ram: 44,
-    temp: 51,
-    uptime: '11d 3h',
-    clients: 9,
-    sparkline: [2, 2, 1, 1, 2, 4, 8, 15, 22, 25, 24, 22, 26, 24, 21, 24, 28, 31, 29, 24, 18, 12, 8, 4],
-  },
-  {
-    id: 'patio',
-    name: 'Patio',
-    model: 'OpenWrt (TP-Link EAP225)',
-    modelShort: 'TP-Link EAP225',
-    role: 'Outdoor AP',
-    roleBadge: 'AP',
-    ip: '192.168.8.4',
-    backhaul: 'wifi',
-    status: 'warn',
-    health: 68,
-    cpu: 31,
-    ram: 57,
-    temp: 71,
-    uptime: '4d 2h',
-    clients: 6,
-    hotMetric: 'temp',
-    sparkline: [1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2],
-  },
-]
 
 // ---------------------------------------------------------------------------
-// WAN (vía Flint 2)
+// Canon demo (SPEC-65 D65-1): re-exportado desde demo-canon.json con casteo
+// explícito al contrato de `@/data/types` (el JSON se tipa por inferencia).
+// Los valores del JSON son la verdad reconciliada del canon Go de fase 6.
 // ---------------------------------------------------------------------------
 
-export const wan: WanInfo = {
-  plan: '600/600 Mbps',
-  downMbps: 84.2,
-  upMbps: 12.6,
-  latencyMs: 8,
-  lossPct: 0,
-  publicIp: '84.122.x.x',
-  isp: 'Digi',
-  peakTodayMbps: 412,
-  peakTodayTime: '21:14',
-  avgDownMbps: 61,
-  total24h: '1.32 TB',
-}
+export const routers = canon.routers as unknown as Router[]
+export const devices = canon.devices as unknown as Device[]
+export const deviceTotals: DeviceTotals = canon.deviceTotals
+export const distributionNodes = canon.distributionNodes as unknown as DistributionNode[]
+export const adguard = canon.adguard as unknown as AdGuardStats
+export const wireguard = canon.wireguard as unknown as WireGuardStats
+export const wan: WanInfo = canon.wan
+export const healthScore = canon.health as unknown as HealthScore
 
 // ---------------------------------------------------------------------------
 // Tráfico WAN — series por rango (valle nocturno 5–15, pico tarde 300–412,
@@ -198,254 +125,35 @@ export const trafficByRange: Record<TimeRange, TrafficPoint[]> = {
   ],
 }
 
-// ---------------------------------------------------------------------------
-// Health Score global
-// ---------------------------------------------------------------------------
-
-export const healthScore: HealthScore = {
-  score: 92,
-  label: 'Excelente',
-  caption: 'Network health score',
-  note: 'Penalized by the Patio temperature.',
-  breakdown: [
-    { label: 'Patio temp.', delta: -4 },
-    { label: 'Patio coverage', delta: -2 },
-    { label: 'congested 2.4 GHz channel', delta: -2 },
-  ],
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos (totales + destacados)
-// ---------------------------------------------------------------------------
-
-export const deviceTotals = {
-  total: 67,
-  online: 59,
-  knownOffline: 8,
-  newToday: 3,
-}
-
-export const devices: Device[] = [
-  {
-    id: 'imac-salon', name: 'iMac Living Room', type: 'ordenador', manufacturer: 'Apple',
-    ip: '192.168.8.21', mac: 'A4:83:E7:21:0B:3C', routerId: 'living', band: '5 GHz',
-    signalDbm: -48, trafficMbps: 32.4, online: true,
-    sparkline: [12, 15, 18, 22, 26, 30, 34, 32, 28, 30, 32, 31],
-  },
-  {
-    id: 'tv-samsung', name: 'TV Samsung', type: 'tv', manufacturer: 'Samsung',
-    ip: '192.168.8.34', mac: '8C:EA:48:5D:2F:91', routerId: 'living', band: '5 GHz',
-    signalDbm: -52, trafficMbps: 18.1, online: true,
-    sparkline: [8, 10, 14, 16, 18, 20, 19, 18, 17, 18, 18, 18],
-  },
-  {
-    id: 'pixel-8-pro', name: 'Pixel 8 Pro', type: 'movil', manufacturer: 'Google',
-    ip: '192.168.8.45', mac: 'F2:6D:19:A8:44:C2', routerId: 'flint2', band: '5 GHz',
-    signalDbm: -41, trafficMbps: 6.2, online: true,
-    sparkline: [3, 4, 5, 7, 6, 8, 6, 5, 7, 6, 6, 6],
-  },
-  {
-    id: 'macbook-air', name: 'MacBook Air', type: 'portatil', manufacturer: 'Apple',
-    ip: '192.168.8.23', mac: '3C:22:FB:71:9E:05', routerId: 'estudio', band: '5 GHz',
-    signalDbm: -45, trafficMbps: 4.8, online: true,
-    sparkline: [2, 3, 4, 5, 5, 6, 5, 4, 5, 5, 5, 5],
-  },
-  {
-    id: 'ps5', name: 'PS5', type: 'consola', manufacturer: 'Sony',
-    ip: '192.168.8.31', mac: '78:C8:81:0A:6B:D4', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 12.7, online: true, port: 'lan2',
-    sparkline: [4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13],
-  },
-  {
-    id: 'robot-aspirador', name: 'Robot vacuum', type: 'iot', manufacturer: 'Roborock',
-    ip: '192.168.8.61', mac: 'B0:4A:39:2E:77:10', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -67, trafficMbps: 0.02, online: true,
-    sparkline: [0.01, 0.02, 0.02, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02],
-  },
-  {
-    id: 'camara-porche', name: 'Porch camera', type: 'camara', manufacturer: 'Reolink',
-    ip: '192.168.8.71', mac: 'EC:71:DB:44:12:8A', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -72, trafficMbps: 1.1, online: true,
-    sparkline: [1, 1.1, 1.1, 1.2, 1.1, 1, 1.1, 1.1, 1.2, 1.1, 1.1, 1.1],
-  },
-  {
-    id: 'nest-mini', name: 'Nest Mini', type: 'altavoz', manufacturer: 'Google',
-    ip: '192.168.8.52', mac: '1A:2B:3C:4D:5E:6F', routerId: 'estudio', band: '2.4 GHz',
-    signalDbm: -55, trafficMbps: 0.4, online: true,
-    sparkline: [0.3, 0.4, 0.4, 0.5, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4],
-  },
-  {
-    id: 'nas-synology', name: 'NAS Synology', type: 'servidor', manufacturer: 'Synology',
-    ip: '192.168.8.10', mac: '00:11:32:9C:51:B7', routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: 2.3, online: true, port: 'lan1',
-    sparkline: [1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3],
-  },
-  {
-    id: 'bombillas-ikea', name: 'Ikea bulbs ×6', type: 'iot', manufacturer: 'Ikea',
-    ip: '192.168.8.8x', mac: '—', routerId: 'living', band: '2.4 GHz',
-    signalDbm: -60, trafficMbps: 0, online: true,
-    sparkline: [0, 0, 0.01, 0, 0, 0.01, 0, 0, 0, 0.01, 0, 0],
-  },
-  {
-    id: 'galaxy-tab-s9', name: 'Galaxy Tab S9', type: 'tablet', manufacturer: 'Samsung',
-    ip: '192.168.8.48', mac: 'D6:91:2F:07:B3:55', routerId: 'living', band: '5 GHz',
-    signalDbm: -50, trafficMbps: 1.8, online: true, isNew: true,
-    sparkline: [0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1.2, 1.6, 1.8],
-  },
-
-  // -- Fixtures de topología v5 (mockup aprobado: switch gestionado LLDP, --
-  // -- hipervisor con CTs anidados, switch/bridge inferido vía FDB) ----------
-
-  // 3 clientes tras el switch gestionado GS308E (Salón, lan3) — el switch se
-  // modela como DistributionNode kind='managed' (identificado vía LLDP), igual
-  // que lo emitirá el backend demo (C2).
-  {
-    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: null, trafficMbps: 9.8, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [3, 5, 7, 9, 11, 12, 10, 9, 10, 9, 10, 9.8],
-  },
-  {
-    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: null, trafficMbps: 15.2, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [6, 8, 10, 12, 14, 16, 15, 14, 15, 15, 15, 15.2],
-  },
-  {
-    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: null, trafficMbps: 0.6, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
-  },
-
-  // Hipervisor Proxmox (gateway lan2) + 10 CTs anidados (MACs OUI BC:24:11)
-  {
-    id: 'pve', name: 'Proxmox pve', type: 'servidor', manufacturer: 'Supermicro',
-    ip: '192.168.8.5', mac: '3C:52:82:10:20:30', routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: 12.3, online: true, port: 'lan2',
-    sparkline: [8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3],
-  },
-  ...([
-    ['ct-pihole', 'Pi-hole', 'servidor', 8.41, 6.1],
-    ['ct-home-assistant', 'Home Assistant', 'iot', 8.42, 4.2],
-    ['ct-nextcloud', 'Nextcloud', 'servidor', 8.43, 7.8],
-    ['ct-jellyfin', 'Jellyfin', 'servidor', 8.44, 9.4],
-    ['ct-immich', 'Immich', 'servidor', 8.45, 3.3],
-    ['ct-gitea', 'Gitea', 'servidor', 8.46, 1.2],
-    ['ct-uptime-kuma', 'Uptime Kuma', 'iot', 8.47, 0.4],
-    ['ct-adguard-sync', 'AdGuard sync', 'servidor', 8.48, 0.8],
-    ['ct-postgres', 'Postgres', 'servidor', 8.49, 2.1],
-    ['ct-redis', 'Redis', 'servidor', 8.50, 0.9],
-  ] as const).map(([id, name, type, ipSuffix, mbps], i): Device => ({
-    id, name, type: type as Device['type'], manufacturer: 'Proxmox VE (CT)',
-    ip: `192.168.${ipSuffix}`, mac: `BC:24:11:00:2${i}:${(0x10 + i).toString(16).toUpperCase().padStart(2, '0')}`,
-    routerId: 'flint2', band: 'cable', signalDbm: null, trafficMbps: mbps, online: true,
-    attachTo: 'pve',
-    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.1, mbps - 2 + ((i + j) % 5))),
-  })),
-
-  // Tras el switch/bridge inferido (gateway lan3, OUI heterogéneo, sin IP)
-  ...([
-    ['pc-sobremesa', 'PC Desktop', 'ordenador', 'Intel NIC', '78:2B:CB:AA:01:01', 8.60, 18.9],
-    ['tv-salon-cable', 'TV Living (wired)', 'tv', 'Samsung', '8C:EA:48:AA:02:02', 8.61, 24.4],
-    ['impresora-hp', 'HP Printer', 'iot', 'HP', '3C:D9:2B:AA:03:03', 8.62, 0.1],
-    ['raspberry-pi', 'Raspberry Pi', 'servidor', 'Raspberry Pi Ltd', 'DC:A6:32:AA:04:04', 8.63, 1.7],
-    ['xbox-one', 'Xbox One', 'consola', 'Microsoft', '7C:ED:8D:AA:05:05', 8.64, 4.2],
-    ['receptor-av', 'AV Receiver', 'altavoz', 'Denon', '00:05:CD:AA:06:06', 8.65, 0.3],
-    ['deco-orange', 'Orange STB', 'tv', 'Sagemcom', '48:83:B4:AA:07:07', 8.66, 1.1],
-    ['pc-invitado', 'Guest PC', 'ordenador', '—', 'A2:F4:11:AA:08:08', 8.67, 0.8],
-  ] as const).map(([id, name, type, man, mac, ipSuffix, mbps], i): Device => ({
-    id, name, type: type as Device['type'], manufacturer: man,
-    ip: `192.168.${ipSuffix}`, mac, routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: mbps, online: true, attachTo: 'dist-flint2-lan3',
-    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.05, mbps - 1.5 + ((i + j) % 4) * 0.5)),
-  })),
-]
-
-// ---------------------------------------------------------------------------
-// Nodos de distribución (topología v5): inferidos del FDB en live; en demo,
-// fixtures equivalentes al mockup aprobado (switch lan3 + hipervisor lan2).
-// ---------------------------------------------------------------------------
-
-export const distributionNodes: 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' },
-  // Switch gestionado Netgear GS308E en el AP Salón (lan3), identificado vía
-  // LLDP (chasis + IP de mgmt + caps + puerto remoto). 4 MACs: switch + 3 equipos.
-  {
-    id: 'dist-living-lan3', kind: 'managed', routerId: 'living', port: 'lan3', macCount: 4,
-    name: 'GS308E', ip: '192.168.8.13',
-    lldp: { chassis: 'GS308E', mgmt: '192.168.8.13', caps: 'Bridge', portDesc: 'ge5' },
-  },
-]
-
-// ---------------------------------------------------------------------------
-// AdGuard Home (en Flint 2, :3000)
-// ---------------------------------------------------------------------------
-
-export const adguard: AdGuardStats = {
-  host: '192.168.8.1',
-  port: 3000,
-  status: 'active',
-  queries24h: 84312,
-  blocked24h: 15687,
-  blockedPct: 18.6,
-  trackersBlocked: 9204,
-  dnsLatencyMs: 14,
-  clientsUsing: 60,
-  clientsTotal: 67,
-  topBlocked: [
-    { domain: 'graph.facebook.com', count: 1204 },
-    { domain: 'adservice.google.com', count: 986 },
-    { domain: 'metrics.icloud.com', count: 731 },
-    { domain: 'telemetry.nvidia.com', count: 512 },
-    { domain: 'ads.tiktok.com', count: 448 },
-  ],
-  filterLists: 6,
-  rules: 218442,
-}
-
-// ---------------------------------------------------------------------------
-// WireGuard (servidor en Flint 2, wg0 · 10.0.0.1/24)
-// ---------------------------------------------------------------------------
-
-export const wireguard: WireGuardStats = {
-  interface: 'wg0',
-  subnet: '10.0.0.1/24',
-  status: 'active',
-  peers: [
-    { id: 'pixel-8-pro', name: 'Pixel 8 Pro', type: 'movil', tunnelIp: '10.0.0.2', active: true, lastHandshake: '38s ago', rx: '1.2 GB', tx: '214 MB' },
-    { id: 'macbook-air', name: 'MacBook Air', type: 'portatil', tunnelIp: '10.0.0.3', active: true, lastHandshake: '1 min ago', rx: '640 MB', tx: '88 MB' },
-    { id: 'ipad-air', name: 'iPad Air', type: 'tablet', tunnelIp: '10.0.0.4', active: false, lastHandshake: '2 days ago', rx: '3.1 GB', tx: '402 MB' },
-    { id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', tunnelIp: '10.0.0.5', active: false, lastHandshake: '6h ago', rx: '812 MB', tx: '121 MB' },
-    { id: 'casa-familia', name: 'Family home', type: 'sitio', tunnelIp: '10.0.0.6', active: false, lastHandshake: '9 days ago', rx: '12 GB', tx: '4.2 GB' },
-  ],
-}
-
 // ---------------------------------------------------------------------------
 // Alertas (canon §11)
 // ---------------------------------------------------------------------------
 
+// Ts unix SEGUNDOS escalonados en coherencia con el string legado
+// ("38s ago" → now-38, "12 min ago" → now-720, ...) — espejo del canon Go
+// (server-go/internal/adapters/demo_dataset.go canonAlerts, SPEC-ALERTAS §5).
+const alertNow = Math.floor(Date.now() / 1000)
+
 export const alerts: AlertEvent[] = [
   {
-    id: 'alert-temp-patio', severity: 'warn', title: 'High temperature on Patio',
-    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', read: false, routerId: 'patio',
+    id: 'alert-temp-patio', category: 'router', urgent: true, severity: 'warn', title: 'High temperature on Patio',
+    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', ts: alertNow - 12 * 60, read: false, routerId: 'patio',
   },
   {
-    id: 'alert-firmware-estudio', severity: 'warn', title: 'Firmware available',
-    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', read: false, routerId: 'estudio',
+    id: 'alert-firmware-estudio', category: 'system', urgent: false, severity: 'warn', title: 'Firmware available',
+    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', ts: alertNow - 3 * 3600, read: false, routerId: 'estudio',
   },
   {
-    id: 'alert-nuevo-tab', severity: 'info', title: 'New device',
-    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', read: true, routerId: 'living',
+    id: 'alert-nuevo-tab', category: 'clients', urgent: false, severity: 'info', title: 'New device',
+    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', ts: alertNow - 26 * 60, read: true, routerId: 'living',
   },
   {
-    id: 'alert-handshake-wg', severity: 'info', title: 'WireGuard handshake',
-    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', read: true, routerId: 'flint2',
+    id: 'alert-handshake-wg', category: 'vpn', urgent: false, severity: 'info', title: 'WireGuard handshake',
+    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', ts: alertNow - 38, read: true, routerId: 'flint2',
   },
   {
-    id: 'alert-backup-adguard', severity: 'ok', title: 'AdGuard backup completed',
-    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', read: true, routerId: 'flint2',
+    id: 'alert-backup-adguard', category: 'system', urgent: false, severity: 'ok', title: 'AdGuard backup completed',
+    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', ts: alertNow - 24 * 3600, read: true, routerId: 'flint2',
   },
 ]
 

+ 92 - 0
app/src/data/push.ts

@@ -0,0 +1,92 @@
+/**
+ * NetPulse — capa de datos Web Push (SPEC-PUSH §2).
+ *
+ * Contrato con el backend (server-go, tras auth de sesión):
+ * - GET  /api/push/vapid-key   → {"key":"<base64url>"}  (clave pública VAPID)
+ * - POST /api/push/subscribe   body {endpoint, keys:{auth,p256dh}} → 201/200
+ * - POST /api/push/unsubscribe body {endpoint} → 204
+ *
+ * En la demo local (sin backend) la tarjeta de Ajustes NO simula la
+ * activación: una suscripción push sin servidor nunca recibiría nada y
+ * daría una falsa sensación de funcionalidad. Se muestra el estado
+ * degradado "no disponible en la demo local".
+ */
+
+/** Suscripción tal y como la espera el backend (PushSubscription.toJSON()). */
+export interface PushSubscriptionPayload {
+  endpoint: string
+  keys: { auth: string; p256dh: string }
+}
+
+function redirectLogin(): never {
+  window.dispatchEvent(new Event('netpulse-unauthorized'))
+  window.location.assign('/login')
+  throw new Error('unauthorized')
+}
+
+/** GET /api/push/vapid-key → clave pública VAPID (base64url). null si no hay backend push. */
+export async function getVapidKey(): Promise<string | null> {
+  try {
+    const res = await fetch('/api/push/vapid-key')
+    if (res.status === 401) redirectLogin()
+    if (!res.ok) return null
+    const json = (await res.json()) as { key?: string }
+    return typeof json.key === 'string' && json.key.length > 0 ? json.key : null
+  } catch {
+    return null
+  }
+}
+
+/** POST /api/push/subscribe (upsert por endpoint). true si el servidor la aceptó. */
+export async function postPushSubscribe(sub: PushSubscriptionPayload): Promise<boolean> {
+  try {
+    const res = await fetch('/api/push/subscribe', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify(sub),
+    })
+    if (res.status === 401) redirectLogin()
+    return res.ok // 200/201
+  } catch {
+    return false
+  }
+}
+
+/** POST /api/push/unsubscribe. El resultado no bloquea la baja local. */
+export async function postPushUnsubscribe(endpoint: string): Promise<boolean> {
+  try {
+    const res = await fetch('/api/push/unsubscribe', {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ endpoint }),
+    })
+    if (res.status === 401) redirectLogin()
+    return res.ok // 204
+  } catch {
+    return false
+  }
+}
+
+/** Clave VAPID pública (base64url) → applicationServerKey para pushManager.subscribe(). */
+export function urlBase64ToUint8Array(base64url: string): Uint8Array {
+  const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
+  const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4)
+  const raw = atob(padded)
+  const out = new Uint8Array(raw.length)
+  for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i)
+  return out
+}
+
+/**
+ * Contexto de soporte Web Push (evaluar en cliente, no en SSR).
+ * - `insecure`: Web Push exige contexto seguro; en LAN por HTTP solo
+ *   funciona en localhost (o con HTTPS). Aviso propio en la tarjeta.
+ * - `unsupported`: sin ServiceWorker, PushManager o Notification.
+ */
+export function pushContext(): 'ok' | 'insecure' | 'unsupported' {
+  if (!window.isSecureContext) return 'insecure'
+  if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
+    return 'unsupported'
+  }
+  return 'ok'
+}

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

@@ -99,6 +99,13 @@ export interface AdGuardStats {
 
 export type PeerType = 'movil' | 'portatil' | 'tablet' | 'sitio'
 
+/**
+ * Rol de infraestructura sellado server-side (SPEC-65 D65-2):
+ * "hypervisor" (host Proxmox/VMware/…), "ct" (CT/VM anidado bajo un
+ * hipervisor), "managed-switch" (switch con gestión identificado por LLDP).
+ */
+export type DeviceInfra = 'hypervisor' | 'ct' | 'managed-switch'
+
 export interface WGPeer {
   id: string
   name: string
@@ -167,6 +174,12 @@ export interface Device {
    * (hipervisor / switch gestionado identificado).
    */
   attachTo?: string
+  /**
+   * Rol de infraestructura sellado server-side (SPEC-65 D65-2): la app NO
+   * infiere; pinta el badge si viene. Ausente = dispositivo normal (la app
+   * puede seguir infiriendo como fallback para datos viejos, B2).
+   */
+  infra?: DeviceInfra
 }
 
 /**
@@ -191,17 +204,38 @@ export interface DistributionNode {
   /** Managed: IP de gestión anunciada por LLDP. */
   ip?: string
   lldp?: LldpInfo | null
+  /**
+   * Managed: chassis-MAC del switch (D1). El switch gestionado existe a la
+   * vez como Device (visible en /devices); el mapa excluye su chip filtrando
+   * los Devices cuya MAC coincide con esta — se representa SOLO como nodo.
+   */
+  mac?: string
 }
 
 export type AlertSeverity = 'warn' | 'critical' | 'info' | 'ok'
 
+/** Taxonomía de categorías de alerta (SPEC-ALERTAS §1, espejo del backend Go). */
+export type AlertCategory = 'router' | 'internet' | 'clients' | 'signal' | 'vpn' | 'system'
+
+/** Nivel de configuración por categoría (SPEC-ALERTAS §2). */
+export type AlertConfigLevel = 'urgent' | 'all' | 'none'
+
+/** Configuración de alertas: las 6 categorías con su nivel. */
+export type AlertsConfig = Record<AlertCategory, AlertConfigLevel>
+
 export interface AlertEvent {
   id: string
+  /** Categoría del evento (filtrado + configuración por nivel) */
+  category: AlertCategory
+  /** true = "rompe silencio" (badge URGENTE; push en Bloque C) */
+  urgent: boolean
   severity: AlertSeverity
   title: string
   description: string
-  /** Timestamp relativo ya formateado: "hace 12 min" */
+  /** LEGADO display: "hace 12 min" — fallback si `ts` no es válido */
   time: string
+  /** Unix SEGUNDOS; el frontend calcula el tiempo relativo */
+  ts: number
   read: boolean
   routerId?: string
 }
@@ -218,6 +252,36 @@ export interface DeviceTotals {
   newToday: number
 }
 
+/**
+ * Versión del view-model que la app soporta (SPEC-65 D65-4). Si el servidor
+ * manda `vm` mayor → la app avisa una vez por consola y sigue (nunca rompe).
+ */
+export const VM_SUPPORTED = 1
+
+/** Enlace semántico del mapa (SPEC-65 D65-3), sin geometría. */
+export interface TopoSemLink {
+  /** id: router | device | distnode | "internet" | "peer-<wgPeerId>" */
+  from: string
+  to: string
+  kind: 'wan' | 'uplink' | 'wired' | 'dist' | 'wg'
+  /** puerto físico si aplica */
+  port?: string
+}
+
+/**
+ * Modelo SEMÁNTICO de la topología (SPEC-65 D65-3): asignaciones de anillo,
+ * enlaces y conteos de peers ocultos llegan calculados del servidor; la app
+ * conserva solo la geometría de píxeles. Ausente en snapshots viejos → la
+ * app usa su cálculo local como fallback.
+ */
+export interface TopoSemantics {
+  links: TopoSemLink[]
+  /** routerId → ids de Device en su anillo (cableados primero, luego 5/2.4 GHz) */
+  rings: Record<string, string[]>
+  /** routerId → nº de clientes no pintados como chip (el "+N") */
+  hiddenPeers?: Record<string, number>
+}
+
 /** Bundle de `GET /api/overview` y del evento SSE `snapshot`. */
 export interface OverviewBundle {
   health: HealthScore
@@ -236,9 +300,31 @@ export interface OverviewBundle {
    * colector o primera pasada): el mapa cuelga los cableados del router.
    */
   distributionNodes?: DistributionNode[]
+  /**
+   * Versión del view-model (SPEC-65 D65-4). Siempre presente en servidores
+   * nuevos; ausente en servidores viejos (se asume VM_SUPPORTED).
+   */
+  vm?: number
+  /** Semántica de topología precalculada (SPEC-65 D65-3); ausente = fallback local. */
+  topology?: TopoSemantics
   ts: number
 }
 
+/**
+ * Item de `GET /api/agents` (Fase 6): agente nativo registrado en un router.
+ * `slug` coincide con el `id` del router (mismo alfabeto que routerstore).
+ * `fresh` = el agente empujó dentro del TTL (~90 s); false → caído, el
+ * backend vuelve a sondear por SSH.
+ */
+export interface AgentInfo {
+  slug: string
+  /** Unix SEGUNDOS del último push; null si nunca empujó */
+  lastSeen: number | null
+  /** Versión del binario netpulse-agent ("" si aún no se conoce) */
+  version?: string
+  fresh: boolean
+}
+
 /** Respuesta paginada (`GET /api/devices`, `GET /api/alerts`). */
 export interface Paged<T> {
   items: T[]
@@ -258,9 +344,11 @@ export interface DeviceQuery {
   pageSize?: number
 }
 
-/** Parámetros de `GET /api/alerts?severity=&page=&pageSize=`. */
+/** Parámetros de `GET /api/alerts?severity=&category=&unread=&page=&pageSize=`. */
 export interface AlertQuery {
   severity?: AlertSeverity
+  category?: AlertCategory
+  unread?: boolean
   page?: number
   pageSize?: number
 }

+ 8 - 0
app/src/hooks/useAgentFor.ts

@@ -0,0 +1,8 @@
+import { useNetPulse } from '@/data/DataProvider'
+import type { AgentInfo } from '@/data/types'
+
+/** Agente nativo registrado en un router: casa `slug` con `router.id` (Fase 6). */
+export function useAgentFor(routerId: string): AgentInfo | undefined {
+  const { agents } = useNetPulse()
+  return agents.find((a) => a.slug === routerId)
+}

+ 16 - 9
app/src/hooks/useServicesVisibility.ts

@@ -26,23 +26,30 @@ export function getServicesVisibility(): ServicesVisibility {
 export function useServicesVisibility(): [ServicesVisibility, (k: keyof ServicesVisibility, v: boolean) => void] {
   const [services, setServices] = useState<ServicesVisibility>(getServicesVisibility)
 
-  // Sincroniza entre pestañas/componentes (Ajustes y Home a la vez)
+  // Sincroniza entre pestañas/componentes (Ajustes y Home a la vez). El evento
+  // 'storage' no salta en la misma pestaña: se emite además uno custom.
   useEffect(() => {
     const onStorage = (e: StorageEvent) => {
       if (e.key === KEY) setServices(getServicesVisibility())
     }
+    const onLocal = () => setServices(getServicesVisibility())
     window.addEventListener('storage', onStorage)
-    return () => window.removeEventListener('storage', onStorage)
+    window.addEventListener('netpulse-services-changed', onLocal)
+    return () => {
+      window.removeEventListener('storage', onStorage)
+      window.removeEventListener('netpulse-services-changed', onLocal)
+    }
   }, [])
 
   const set = useCallback((k: keyof ServicesVisibility, v: boolean) => {
-    setServices((prev) => {
-      const next = { ...prev, [k]: v }
-      try {
-        localStorage.setItem(KEY, JSON.stringify(next))
-      } catch {}
-      return next
-    })
+    // localStorage es la fuente de verdad compartida: escribir ANTES de emitir
+    // el evento (nunca dentro del updater: React puede diferirlo/re-ejecutarlo)
+    const next = { ...getServicesVisibility(), [k]: v }
+    try {
+      localStorage.setItem(KEY, JSON.stringify(next))
+    } catch {}
+    setServices(next)
+    window.dispatchEvent(new Event('netpulse-services-changed'))
   }, [])
 
   return [services, set]

+ 29 - 4
app/src/i18n.ts

@@ -40,18 +40,43 @@ export function numLocale(): string {
 }
 
 const REL_RE = /^hace\s+(\d+)\s*(s|min|h|días?|d)$/
+const REL_RE_EN = /^(\d+)\s*(s|sec|min|h|hr|d|days?)\s+ago$/
 
-/** Convierte tiempos relativos canónicos del dataset ("hace 12 min", "hoy") al idioma activo */
+/** Convierte tiempos relativos canónicos del dataset ("hace 12 min", "12 min ago", "hoy") al idioma activo */
 export function relTime(s: string): string {
   const t = s.trim()
-  if (t === 'hoy') return i18n.t('common.today')
-  const m = REL_RE.exec(t)
+  if (t === 'hoy' || t.toLowerCase() === 'today') return i18n.t('common.today')
+  const m = REL_RE.exec(t) ?? REL_RE_EN.exec(t)
   if (!m) return s
   const n = Number(m[1])
-  const unit = m[2] === 's' ? 's' : m[2] === 'min' ? 'min' : m[2] === 'h' ? 'h' : 'd'
+  const u = m[2]
+  const unit = u === 's' || u === 'sec' ? 's' : u === 'min' ? 'min' : u === 'h' || u === 'hr' ? 'h' : 'd'
   return i18n.t(`common.ago.${unit}`, { count: n, n })
 }
 
+/**
+ * Tiempo relativo desde un timestamp unix en SEGUNDOS (SPEC-ALERTAS §1: el
+ * frontend calcula el relativo; el string `time` queda como fallback legado).
+ * Devuelve null si `ts` no es usable (0/NaN/futuro lejano) → usar `relTime(time)`.
+ */
+export function relTimeFromTs(ts: number | undefined, nowMs = Date.now()): string | null {
+  if (!ts || !Number.isFinite(ts) || ts <= 0) return null
+  const diffS = Math.floor(nowMs / 1000) - ts
+  if (diffS < 0) return null
+  if (diffS < 60) return i18n.t('common.ago.s', { count: diffS, n: diffS })
+  const min = Math.floor(diffS / 60)
+  if (min < 60) return i18n.t('common.ago.min', { count: min, n: min })
+  const h = Math.floor(min / 60)
+  if (h < 24) return i18n.t('common.ago.h', { count: h, n: h })
+  const d = Math.floor(h / 24)
+  return i18n.t('common.ago.d', { count: d, n: d })
+}
+
+/** Relativo de una alerta: desde `ts` si es válido; si no, el string legado. */
+export function alertRelTime(ev: { ts?: number; time: string }): string {
+  return relTimeFromTs(ev.ts) ?? relTime(ev.time)
+}
+
 /** Uptime canónico tipo "12d 4h" → "12 días, 4 h" / "12 days, 4 h" */
 export function fmtUptime(uptime: string): string {
   const m = /^(\d+)d\s*(\d+)h$/.exec(uptime.trim())

+ 214 - 25
app/src/pages/Alerts.tsx

@@ -5,19 +5,28 @@ import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
 import {
   AlertTriangle,
   ArrowRight,
+  Check,
   CheckCheck,
   CheckCircle2,
   ChevronRight,
+  Globe,
   Info,
   Laptop,
   MoreVertical,
   OctagonX,
+  Router,
+  Server,
+  Settings2,
+  Shield,
+  Signal,
   Smartphone,
   Tablet,
+  Users,
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
-import { relTime } from '@/i18n'
-import type { AlertSeverity } from '@/data/mock'
+import { alertRelTime, relTime } from '@/i18n'
+import type { AlertCategory, AlertConfigLevel, AlertSeverity } from '@/data/types'
+import { ALERT_CATEGORIES } from '@/data/alertConfig'
 import { CountUp } from '@/components/CountUp'
 import { EmptyState } from '@/components/EmptyState'
 import { SegmentedControl } from '@/components/SegmentedControl'
@@ -52,6 +61,21 @@ const SEVERITY: Record<AlertSeverity, { icon: LucideIcon; tile: string; dot: str
 
 const PEER_ICONS = { movil: Smartphone, portatil: Laptop, tablet: Tablet } as const
 
+// ---------------------------------------------------------------------------
+// Categorías (SPEC-ALERTAS §1): chips de filtro + configuración por nivel
+// ---------------------------------------------------------------------------
+
+const CATEGORY_META: Record<AlertCategory, { icon: LucideIcon; tile: string }> = {
+  router: { icon: Router, tile: 'bg-warn/10 text-warn' },
+  internet: { icon: Globe, tile: 'bg-info/10 text-info' },
+  clients: { icon: Users, tile: 'bg-accent-soft text-accent' },
+  signal: { icon: Signal, tile: 'bg-tunnel/10 text-tunnel' },
+  vpn: { icon: Shield, tile: 'bg-tunnel/10 text-tunnel' },
+  system: { icon: Server, tile: 'bg-ok/10 text-ok' },
+}
+
+const LEVEL_ORDER: readonly AlertConfigLevel[] = ['urgent', 'all', 'none']
+
 // ---------------------------------------------------------------------------
 // Filtros
 // ---------------------------------------------------------------------------
@@ -252,7 +276,14 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce }: FeedRowProps)
       >
         <div className="min-w-0 flex-1">
           <div className="flex items-center justify-between gap-2">
-            <span className="truncate text-sm font-medium text-text-primary">{ev.title}</span>
+            <span className="flex min-w-0 items-center gap-2">
+              <span className="truncate text-sm font-medium text-text-primary">{ev.title}</span>
+              {ev.urgent && (
+                <span className="shrink-0 rounded-md bg-danger/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.05em] text-danger">
+                  {t('alerts.urgentBadge')}
+                </span>
+              )}
+            </span>
             <span className="flex shrink-0 items-center gap-2">
               <AnimatePresence initial={false}>
                 {!read && (
@@ -265,7 +296,7 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce }: FeedRowProps)
                   />
                 )}
               </AnimatePresence>
-              <span className="font-mono text-caption text-text-muted">{relTime(ev.time)}</span>
+              <span className="font-mono text-caption text-text-muted">{alertRelTime(ev)}</span>
             </span>
           </div>
           <p className="mt-0.5 truncate text-caption text-text-secondary">{ev.description}</p>
@@ -303,7 +334,17 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce }: FeedRowProps)
 export default function Alerts() {
   const { t } = useTranslation()
   const reduce = useReducedMotion() ?? false
-  const { alerts, wireguard, routers, isDemo } = useNetPulse()
+  const {
+    alerts,
+    wireguard,
+    routers,
+    isDemo,
+    unreadAlerts,
+    alertsConfig,
+    setAlertConfig,
+    markAlertsRead,
+    markAllAlertsRead,
+  } = useNetPulse()
   // Feed: demo = diseño enriquecido del mockup; live = SOLO alertas reales
   const alertFeed = useMemo(
     () =>
@@ -312,39 +353,64 @@ export default function Alerts() {
         : buildLiveFeed(alerts),
     [alerts, wireguard, routers, isDemo],
   )
-  const [readIds, setReadIds] = useState<ReadonlySet<string>>(new Set())
   const [sev, setSev] = useState<SevFilter>('todas')
   const [kind, setKind] = useState<KindFilter>('todos')
+  const [cats, setCats] = useState<ReadonlySet<AlertCategory>>(new Set())
   const [searchParams] = useSearchParams()
   const [onlyUnread, setOnlyUnread] = useState(() => searchParams.get('unread') === '1')
   const [expandedId, setExpandedId] = useState<string | null>(null)
   const [burst, setBurst] = useState(0)
+  const [configOpen, setConfigOpen] = useState(false)
+  const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
+  const saveTimerRef = useRef<number | undefined>(undefined)
   const [loadState, setLoadState] = useState<'idle' | 'loading' | 'done'>('idle')
   const sentinelRef = useRef<HTMLDivElement>(null)
 
-  const isRead = (ev: FeedEvent) => ev.read || readIds.has(ev.id)
-  const unread = alertFeed.filter((ev) => !isRead(ev)).length
+  // Read state: el SERVIDOR es la fuente de verdad (ev.read viene del backend
+  // vía overview/SSE; en demo, del estado del provider). Nada de useState local.
+  const isRead = (ev: FeedEvent) => ev.read
+  const unread = unreadAlerts
 
   const markAllRead = () => {
-    setReadIds(new Set(alertFeed.map((ev) => ev.id)))
+    markAllAlertsRead()
     setBurst((b) => b + 1)
   }
 
   const toggleEvent = (ev: FeedEvent) => {
-    setReadIds((prev) => (prev.has(ev.id) ? prev : new Set(prev).add(ev.id)))
+    if (!ev.read) markAlertsRead([ev.id])
     setExpandedId((cur) => (cur === ev.id ? null : ev.id))
   }
 
+  const toggleCat = (cat: AlertCategory) => {
+    setCats((prev) => {
+      const next = new Set(prev)
+      if (next.has(cat)) next.delete(cat)
+      else next.add(cat)
+      return next
+    })
+  }
+
+  const changeLevel = (cat: AlertCategory, level: AlertConfigLevel) => {
+    window.clearTimeout(saveTimerRef.current)
+    setSaveState('saving')
+    void setAlertConfig(cat, level).then((ok) => {
+      setSaveState(ok ? 'saved' : 'error')
+      saveTimerRef.current = window.setTimeout(() => setSaveState('idle'), 2500)
+    })
+  }
+
+  useEffect(() => () => window.clearTimeout(saveTimerRef.current), [])
+
   const filtered = useMemo(
     () =>
       alertFeed.filter((ev) => {
         if (sev !== 'todas' && ev.severity !== SEV_MATCH[sev]) return false
         if (kind !== 'todos' && ev.kind !== kind) return false
+        if (cats.size > 0 && !cats.has(ev.category)) return false
         if (onlyUnread && isRead(ev)) return false
         return true
       }),
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-    [alertFeed, sev, kind, onlyUnread, readIds],
+    [alertFeed, sev, kind, cats, onlyUnread],
   )
 
   const groups = useMemo(
@@ -372,7 +438,7 @@ export default function Alerts() {
     return () => io.disconnect()
   }, [loadState, filtered.length])
 
-  const filterKey = `${sev}|${kind}|${onlyUnread}`
+  const filterKey = `${sev}|${kind}|${[...cats].sort().join(',')}|${onlyUnread}`
 
   return (
     <div className="mx-auto w-full max-w-[1100px]">
@@ -408,18 +474,34 @@ export default function Alerts() {
           </motion.p>
         </div>
 
-        {/* Desktop: botón ghost · Móvil: menú MoreVertical */}
-        <button
-          type="button"
-          onClick={markAllRead}
-          disabled={unread === 0}
-          className="hidden h-9 shrink-0 items-center gap-2 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:cursor-not-allowed disabled:opacity-40 md:inline-flex"
-        >
-          <motion.span key={burst} animate={reduce ? undefined : { scale: [1, 1.2, 1] }} transition={{ duration: 0.35 }}>
-            <CheckCheck className="h-4 w-4" strokeWidth={1.75} />
-          </motion.span>
-          {t('alerts.markAllRead')}
-        </button>
+        {/* Desktop: botones ghost · Móvil: menú MoreVertical */}
+        <div className="hidden shrink-0 items-center gap-2 md:flex">
+          <button
+            type="button"
+            onClick={() => setConfigOpen((v) => !v)}
+            aria-expanded={configOpen}
+            className={cn(
+              'inline-flex h-9 items-center gap-2 rounded-lg border px-3 text-xs font-medium transition-colors duration-150',
+              configOpen
+                ? 'border-accent/40 bg-accent-soft text-accent'
+                : 'border-border bg-elevated text-text-secondary hover:border-accent/40 hover:text-accent',
+            )}
+          >
+            <Settings2 className="h-4 w-4" strokeWidth={1.75} />
+            {t('alerts.configButton')}
+          </button>
+          <button
+            type="button"
+            onClick={markAllRead}
+            disabled={unread === 0}
+            className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:cursor-not-allowed disabled:opacity-40"
+          >
+            <motion.span key={burst} animate={reduce ? undefined : { scale: [1, 1.2, 1] }} transition={{ duration: 0.35 }}>
+              <CheckCheck className="h-4 w-4" strokeWidth={1.75} />
+            </motion.span>
+            {t('alerts.markAllRead')}
+          </button>
+        </div>
         <div className="md:hidden">
           <DropdownMenu>
             <DropdownMenuTrigger asChild>
@@ -432,6 +514,13 @@ export default function Alerts() {
               </button>
             </DropdownMenuTrigger>
             <DropdownMenuContent align="end" className="border-border bg-elevated">
+              <DropdownMenuItem
+                onSelect={() => setConfigOpen((v) => !v)}
+                className="gap-2 text-text-primary focus:bg-hover"
+              >
+                <Settings2 className="h-4 w-4" strokeWidth={1.75} />
+                {t('alerts.configButton')}
+              </DropdownMenuItem>
               <DropdownMenuItem
                 disabled={unread === 0}
                 onSelect={markAllRead}
@@ -506,6 +595,83 @@ export default function Alerts() {
         )
       })()}
 
+      {/* ②bis Configuración de alertas por categoría (SPEC-ALERTAS §2) */}
+      <AnimatePresence initial={false}>
+        {configOpen && (
+          <motion.section
+            key="alerts-config"
+            initial={reduce ? false : { height: 0, opacity: 0 }}
+            animate={{ height: 'auto', opacity: 1 }}
+            exit={{ height: 0, opacity: 0 }}
+            transition={{ duration: 0.25, ease: 'easeOut' }}
+            className="overflow-hidden"
+            aria-label={t('alerts.configTitle')}
+          >
+            <div className="mt-4 rounded-2xl border border-border bg-surface p-4 md:p-5">
+              <div className="flex items-start justify-between gap-3">
+                <div>
+                  <h2 className="font-display text-h2 text-text-primary">{t('alerts.configTitle')}</h2>
+                  <p className="mt-1 max-w-prose text-caption leading-snug text-text-muted">
+                    {t('alerts.configDescription')}
+                  </p>
+                </div>
+                <span
+                  aria-live="polite"
+                  className={cn(
+                    'flex shrink-0 items-center gap-1.5 text-caption font-medium',
+                    saveState === 'error' ? 'text-danger' : 'text-ok',
+                    (saveState === 'idle' || saveState === 'saving') && 'invisible',
+                  )}
+                >
+                  {saveState === 'error' ? (
+                    t('alerts.configSaveError')
+                  ) : (
+                    <>
+                      <Check className="h-3.5 w-3.5" strokeWidth={2} />
+                      {t('alerts.configSaved')}
+                    </>
+                  )}
+                </span>
+              </div>
+              <ul className="mt-3 divide-y divide-border/60">
+                {ALERT_CATEGORIES.map((cat) => {
+                  const meta = CATEGORY_META[cat]
+                  const Icon = meta.icon
+                  return (
+                    <li
+                      key={cat}
+                      className="flex flex-col gap-2.5 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4"
+                    >
+                      <div className="flex min-w-0 items-start gap-3">
+                        <span className={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-lg', meta.tile)}>
+                          <Icon className="h-[18px] w-[18px]" strokeWidth={1.75} />
+                        </span>
+                        <div className="min-w-0">
+                          <div className="text-sm font-medium text-text-primary">
+                            {t(`alerts.categories.${cat}`)}
+                          </div>
+                          <p className="mt-0.5 text-caption leading-snug text-text-muted">
+                            {t(`alerts.categoryDescriptions.${cat}`)}
+                          </p>
+                        </div>
+                      </div>
+                      <SegmentedControl
+                        size="sm"
+                        options={LEVEL_ORDER.map((lv) => ({ value: lv, label: t(`alerts.levels.${lv}`) }))}
+                        value={alertsConfig[cat]}
+                        onChange={(v) => changeLevel(cat, v)}
+                        ariaLabel={t(`alerts.categories.${cat}`)}
+                        className="shrink-0 self-start sm:self-auto"
+                      />
+                    </li>
+                  )
+                })}
+              </ul>
+            </div>
+          </motion.section>
+        )}
+      </AnimatePresence>
+
       {/* ③ Filtros */}
       <div className="mt-5 flex flex-wrap items-center gap-2.5 md:gap-3">
         <SegmentedControl options={SEV_OPTIONS.map((o) => ({ value: o.value, label: t(o.labelKey) }))} value={sev} onChange={(v) => setSev(v)} ariaLabel={t('alerts.filterBySeverity')} />
@@ -526,6 +692,29 @@ export default function Alerts() {
             ))}
           </SelectContent>
         </Select>
+        <div role="group" aria-label={t('alerts.filterByCategory')} className="flex flex-wrap items-center gap-1.5">
+          {ALERT_CATEGORIES.map((cat) => {
+            const Icon = CATEGORY_META[cat].icon
+            const active = cats.has(cat)
+            return (
+              <button
+                key={cat}
+                type="button"
+                aria-pressed={active}
+                onClick={() => toggleCat(cat)}
+                className={cn(
+                  'inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-xs font-medium transition-colors duration-150',
+                  active
+                    ? 'border-accent/40 bg-accent-soft text-accent'
+                    : 'border-border bg-elevated text-text-secondary hover:text-text-primary',
+                )}
+              >
+                <Icon className="h-3.5 w-3.5" strokeWidth={1.75} />
+                {t(`alerts.categories.${cat}`)}
+              </button>
+            )
+          })}
+        </div>
         <button
           type="button"
           role="switch"

+ 88 - 7
app/src/pages/Devices.tsx

@@ -141,6 +141,44 @@ function signalTextClass(dbm: number | null): string {
   return 'text-warn'
 }
 
+// ---------------------------------------------------------------------------
+// Taxonomía de infraestructura (D6): hipervisor (host con CTs), CT (contenedor
+// anidado, tooltip con su host) y switch gestionado. SPEC-65 D65-2/B2: si el
+// servidor sella `device.infra` manda; si no, fallback a la inferencia local
+// de attachTo/lldp + los distributionNodes del provider.
+// ---------------------------------------------------------------------------
+
+type InfraKind = 'hypervisor' | 'ct' | 'managedSwitch'
+
+interface InfraInfo {
+  kind: InfraKind
+  /** nombre del host (solo CT) */
+  host?: string
+}
+
+const INFRA_BADGE_CLASS: Record<InfraKind, string> = {
+  hypervisor: 'border-tunnel/40 bg-tunnel/10 text-tunnel',
+  ct: 'border-border bg-elevated text-text-muted',
+  managedSwitch: 'border-accent/30 bg-accent-soft text-accent',
+}
+
+/** Badge de infraestructura con tooltip explicativo (D6). */
+function InfraBadge({ info }: { info: InfraInfo }) {
+  const { t } = useTranslation()
+  const tip = info.kind === 'ct' ? t('devices.badges.ctTip', { host: info.host }) : t(`devices.badges.${info.kind}Tip`)
+  return (
+    <span
+      title={tip}
+      className={cn(
+        'inline-flex w-fit shrink-0 items-center rounded-full border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide',
+        INFRA_BADGE_CLASS[info.kind],
+      )}
+    >
+      {t(`devices.badges.${info.kind}`)}
+    </span>
+  )
+}
+
 const EASE_OUT = [0.16, 1, 0.3, 1] as [number, number, number, number]
 
 // ---------------------------------------------------------------------------
@@ -504,10 +542,12 @@ function DetailItem({ label, children, mono }: { label: string; children: React.
 function DeviceDetail({
   device,
   name,
+  infra,
   onRename,
 }: {
   device: ClientDevice
   name: string
+  infra?: InfraInfo
   onRename: (id: string, name: string | null) => void
 }) {
   // El panel se desmonta al colapsar: el borrador siempre arranca del nombre actual
@@ -545,6 +585,14 @@ function DeviceDetail({
           )}
         </div>
       </div>
+      {infra && (
+        <DetailItem label={t('devices.detail.infra')}>
+          <InfraBadge info={infra} />
+          {infra.kind === 'ct' && infra.host && (
+            <span className="ml-1.5 text-caption text-text-muted">{t('devices.badges.ctTip', { host: infra.host })}</span>
+          )}
+        </DetailItem>
+      )}
       <div className="col-span-2">
         <label htmlFor={`rename-${device.id}`} className="text-label uppercase text-text-muted">
           {t('devices.detail.rename')}
@@ -698,6 +746,7 @@ const ROW_GRID =
 function ListRow({
   device,
   name,
+  infra,
   expanded,
   index,
   onToggle,
@@ -707,6 +756,7 @@ function ListRow({
 }: {
   device: ClientDevice
   name: string
+  infra?: InfraInfo
   expanded: boolean
   index: number
   onToggle: () => void
@@ -749,6 +799,7 @@ function ListRow({
             <div className="flex items-center gap-2">
               <span className="truncate text-sm font-medium text-text-primary">{name}</span>
               {device.isNew && <NewPill />}
+              {infra && <InfraBadge info={infra} />}
               {!device.online && <StatusPill tone="muted" label={t('common.status.offline')} />}
             </div>
             <div className="truncate text-caption text-text-muted">{device.manufacturer}</div>
@@ -792,7 +843,7 @@ function ListRow({
         <DeviceRow device={{ ...device, name }} variant="full" onClick={onToggle} />
       </div>
       <ExpandPanel open={expanded}>
-        <DeviceDetail device={device} name={name} onRename={onRename} />
+        <DeviceDetail device={device} name={name} infra={infra} onRename={onRename} />
       </ExpandPanel>
     </motion.div>
   )
@@ -830,6 +881,7 @@ function SignalBars({ device }: { device: ClientDevice }) {
 function GridCard({
   device,
   name,
+  infra,
   expanded,
   index,
   onToggle,
@@ -838,6 +890,7 @@ function GridCard({
 }: {
   device: ClientDevice
   name: string
+  infra?: InfraInfo
   expanded: boolean
   index: number
   onToggle: () => void
@@ -876,7 +929,10 @@ function GridCard({
           <DeviceTile device={device} size="lg" />
           {!device.online ? <StatusPill tone="muted" label={t('common.status.offline')} /> : device.isNew ? <NewPill /> : null}
         </div>
-        <div className="mt-3 truncate text-sm font-medium text-text-primary">{name}</div>
+        <div className="mt-3 flex items-center gap-2">
+          <span className="truncate text-sm font-medium text-text-primary">{name}</span>
+          {infra && <InfraBadge info={infra} />}
+        </div>
         <div className="truncate text-caption text-text-muted">
           {device.manufacturer} · <span className="font-mono">{device.ip}</span>
         </div>
@@ -894,7 +950,7 @@ function GridCard({
         </div>
       </div>
       <ExpandPanel open={expanded}>
-        <DeviceDetail device={device} name={name} onRename={onRename} />
+        <DeviceDetail device={device} name={name} infra={infra} onRename={onRename} />
       </ExpandPanel>
     </motion.div>
   )
@@ -908,12 +964,35 @@ export default function Devices() {
   const { t } = useTranslation()
   const navigate = useNavigate()
   const reduce = useReducedMotion()
-  const { devices, deviceTotals, isDemo, routers } = useNetPulse()
+  const { devices, deviceTotals, isDemo, routers, distributionNodes } = useNetPulse()
   const [renames, setRename] = useRenames()
 
-  // Lista enriquecida de clientes: en demo local expande el canon a los 47
-  // del mockup; en live solo fusiona metadatos conocidos sobre la API.
-  const allDevices = useMemo(() => buildClientDevices(devices, isDemo), [devices, isDemo])
+  // Lista enriquecida de clientes: en demo local expande el canon a los 65
+  // del dataset reconciliado; en live solo fusiona metadatos conocidos sobre
+  // la API. D6: los equipos de infraestructura (host hipervisor, sus CTs y
+  // switches gestionados con LLDP) se reclasifican al grupo de filtro 'infra'.
+  const { allDevices, infraById } = useMemo(() => {
+    const list = buildClientDevices(devices, isDemo)
+    const hosts = new Set(
+      distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId!),
+    )
+    const byId = new Map(list.map((d) => [d.id, d]))
+    const infra = new Map<string, InfraInfo>()
+    for (const d of list) {
+      // SPEC-65 D65-2/B2: prioridad al sello server-side `device.infra`;
+      // la inferencia local queda como fallback para datos viejos.
+      const sealed = d.infra
+      if (sealed === 'hypervisor' || (!sealed && hosts.has(d.id))) {
+        infra.set(d.id, { kind: 'hypervisor' })
+      } else if (sealed === 'ct' || (!sealed && d.attachTo && hosts.has(d.attachTo))) {
+        infra.set(d.id, { kind: 'ct', host: byId.get(d.attachTo ?? '')?.name ?? d.attachTo })
+      } else if (sealed === 'managed-switch' || (!sealed && d.lldp)) {
+        infra.set(d.id, { kind: 'managedSwitch' })
+      }
+    }
+    if (infra.size === 0) return { allDevices: list, infraById: infra }
+    return { allDevices: list.map((d) => (infra.has(d.id) ? { ...d, group: 'infra' as const } : d)), infraById: infra }
+  }, [devices, isDemo, distributionNodes])
 
   const [searchParams] = useSearchParams()
   const [query, setQuery] = useState(() => searchParams.get('q') ?? '')
@@ -1207,6 +1286,7 @@ export default function Devices() {
                   key={d.id}
                   device={d}
                   name={nameOf(d)}
+                  infra={infraById.get(d.id)}
                   expanded={expandedId === d.id}
                   index={i}
                   onToggle={() => setExpandedId((prev) => (prev === d.id ? null : d.id))}
@@ -1226,6 +1306,7 @@ export default function Devices() {
                 key={d.id}
                 device={d}
                 name={nameOf(d)}
+                infra={infraById.get(d.id)}
                 expanded={expandedId === d.id}
                 index={i}
                 onToggle={() => setExpandedId((prev) => (prev === d.id ? null : d.id))}

+ 492 - 12
app/src/pages/Settings.tsx

@@ -1,9 +1,11 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router-dom'
 import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
 import {
   BadgeCheck,
+  BellOff,
+  BellRing,
   Check,
   Copy,
   Download,
@@ -14,6 +16,7 @@ import {
   LogOut,
   MonitorSmartphone,
   Moon,
+  Pencil,
   Plus,
   Radar,
   Router as RouterIcon,
@@ -30,6 +33,7 @@ import { Slider } from '@/components/ui/slider'
 import { Switch } from '@/components/ui/switch'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
+import { getVapidKey, postPushSubscribe, postPushUnsubscribe, pushContext, urlBase64ToUint8Array } from '@/data/push'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
 import { cn } from '@/lib/utils'
@@ -267,6 +271,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [copied, setCopied] = useState(false)
   const [scanning, setScanning] = useState(false)
   const [candidates, setCandidates] = useState<DiscoverCandidate[] | null>(null)
+  const [showAddForm, setShowAddForm] = useState(false)
 
   const load = useCallback(async () => {
     try {
@@ -403,6 +408,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
       setName('')
       setType('openwrt')
       setGateway(false)
+      setShowAddForm(false)
       await load()
       refresh()
       onSaved()
@@ -444,16 +450,16 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
               <RouterIcon className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
               <div className="min-w-0 flex-1">
                 <div className="flex items-center gap-2">
-                  <span className="truncate text-sm font-medium text-text-primary">{r.name || r.host}</span>
+                  <span className="truncate font-mono text-sm font-medium text-text-primary">{r.host}</span>
                   {r.is_gateway && (
                     <span className="rounded-full bg-accent-soft px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-accent">
                       {t('settings.routers.gatewayBadge')}
                     </span>
                   )}
                 </div>
-                <div className="font-mono text-caption text-text-muted">
-                  {r.host} · {r.type === 'glinet' ? 'GL.iNet' : 'OpenWrt'}
-                </div>
+                {r.name && r.name !== r.host && (
+                  <div className="truncate text-caption text-text-muted">{r.name}</div>
+                )}
               </div>
               {confirmDeleteFor === r.id ? (
                 <span className="flex shrink-0 items-center gap-1.5">
@@ -550,8 +556,19 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
         )}
       </div>
 
-      {/* Formulario de alta */}
-      <form onSubmit={(e) => void add(e)} className="mt-4 border-t border-border pt-4">
+      {/* Alta manual colapsada tras botón (SPEC-65 D65-7a) */}
+      <div className="mt-4 border-t border-border pt-4">
+        <button
+          type="button"
+          aria-expanded={showAddForm}
+          onClick={() => setShowAddForm((v) => !v)}
+          className="flex items-center gap-2 rounded-lg border border-border bg-elevated px-3.5 py-2 text-sm font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+        >
+          <Plus className="h-4 w-4" strokeWidth={1.75} />
+          {t('settings.routers.addDevice')}
+        </button>
+        {showAddForm && (
+        <form onSubmit={(e) => void add(e)} className="mt-3">
         <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
           <input
             type="text"
@@ -596,7 +613,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
         </div>
         {error && <p className="mt-2 text-caption text-danger">{error}</p>}
         <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.routers.hint')}</p>
-      </form>
+        </form>
+        )}
+      </div>
 
       {/* Clave pública SSH del servidor */}
       <div className="mt-4 border-t border-border pt-4">
@@ -647,6 +666,7 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   const [newUser, setNewUser] = useState('')
   const [newPass, setNewPass] = useState('')
   const [newAdmin, setNewAdmin] = useState(false)
+  const [showCreateForm, setShowCreateForm] = useState(false)
   const [submitting, setSubmitting] = useState(false)
 
   const load = useCallback(async () => {
@@ -697,6 +717,7 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
       setNewUser('')
       setNewPass('')
       setNewAdmin(false)
+      setShowCreateForm(false)
       await load()
       onSaved()
     } catch {
@@ -858,7 +879,19 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
         ))}
       </ul>
 
-      <form onSubmit={(e) => void add(e)} className="mt-4 border-t border-border pt-4">
+      {/* Alta de usuario colapsada tras botón (SPEC-65 D65-7b) */}
+      <div className="mt-4 border-t border-border pt-4">
+        <button
+          type="button"
+          aria-expanded={showCreateForm}
+          onClick={() => setShowCreateForm((v) => !v)}
+          className="flex items-center gap-2 rounded-lg border border-border bg-elevated px-3.5 py-2 text-sm font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+        >
+          <Plus className="h-4 w-4" strokeWidth={1.75} />
+          {t('settings.users.createUser')}
+        </button>
+        {showCreateForm && (
+        <form onSubmit={(e) => void add(e)} className="mt-3">
         <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
           <input
             type="text"
@@ -896,7 +929,9 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
           </button>
         </div>
         {error && <p className="mt-2 text-caption text-danger">{error}</p>}
-      </form>
+        </form>
+        )}
+      </div>
     </Card>
   )
 }
@@ -914,6 +949,7 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [user, setUser] = useState('root')
   const [password, setPassword] = useState('')
   const [passSet, setPassSet] = useState(false)
+  const [editing, setEditing] = useState(false)
   const [saving, setSaving] = useState(false)
   const [error, setError] = useState<string | null>(null)
 
@@ -952,6 +988,7 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
       if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
       setPassSet(true)
       setPassword('')
+      setEditing(false)
       onSaved()
     } catch {
       setError(t('settings.adguard.errorGeneric'))
@@ -960,6 +997,32 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     }
   }
 
+  // SPEC-65 D65-7c: configurado y sin editar → vista compacta (icono + host +
+  // chip ok + Editar). Sin configurar → form directo como antes.
+  if (passSet && !editing) {
+    return (
+      <Card title={t('settings.adguard.title')} caption={t('settings.adguard.caption')} index={5} reduce={reduce}>
+        <div className="flex items-center gap-3 rounded-xl border border-border bg-elevated px-3.5 py-2.5">
+          <ShieldCheck className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
+          <span className="min-w-0 flex-1 truncate font-mono text-sm font-medium text-text-primary">{host}</span>
+          <span className="flex shrink-0 items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-ok">
+            {t('settings.adguard.configured')}
+          </span>
+          <button
+            type="button"
+            onClick={() => setEditing(true)}
+            aria-label={t('settings.adguard.edit')}
+            title={t('settings.adguard.edit')}
+            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+          >
+            <Pencil className="h-4 w-4" strokeWidth={1.75} />
+          </button>
+        </div>
+        <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.adguard.hint')}</p>
+      </Card>
+    )
+  }
+
   return (
     <Card title={t('settings.adguard.title')} caption={t('settings.adguard.caption')} index={5} reduce={reduce}>
       <form onSubmit={(e) => void save(e)}>
@@ -1002,6 +1065,19 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           >
             {saving ? t('settings.adguard.saving') : t('settings.adguard.save')}
           </button>
+          {passSet && editing && (
+            <button
+              type="button"
+              onClick={() => {
+                setEditing(false)
+                setPassword('')
+                setError(null)
+              }}
+              className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-text-secondary transition-colors duration-150 hover:text-text-primary"
+            >
+              {t('settings.users.cancel')}
+            </button>
+          )}
         </div>
         {error && <p className="mt-2 text-caption text-danger">{error}</p>}
         <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.adguard.hint')}</p>
@@ -1011,6 +1087,114 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
 }
 
 
+// ---------------------------------------------------------------------------
+// Bloque «Sistema» en Acerca de (SPEC-65 D65-6/7e): GET /api/system/info
+// ---------------------------------------------------------------------------
+
+interface SystemInfoData {
+  version: string
+  goVersion: string
+  os: string
+  arch: string
+  distro: string
+  kernel: string
+  cpuModel: string
+  cpuCores: number
+  memTotalMb: number
+  uptimeS: number
+  demo: boolean
+}
+
+function fmtUptime(s: number): string {
+  if (!s || s <= 0) return '—'
+  const d = Math.floor(s / 86400)
+  const h = Math.floor((s % 86400) / 3600)
+  const m = Math.floor((s % 3600) / 60)
+  if (d > 0) return `${d}d ${h}h`
+  if (h > 0) return `${h}h ${m}m`
+  if (m > 0) return `${m}m`
+  return `${Math.floor(s)}s`
+}
+
+function SystemInfoBlock() {
+  const { t } = useTranslation()
+  const [info, setInfo] = useState<SystemInfoData | null>(null)
+  const [failed, setFailed] = useState(false)
+
+  useEffect(() => {
+    let disposed = false
+    void (async () => {
+      try {
+        const res = await fetch('/api/system/info')
+        // La preview estática responde HTML con 200: no es el endpoint
+        if (!res.ok || !(res.headers.get('content-type') ?? '').includes('application/json')) {
+          throw new Error(`HTTP ${res.status}`)
+        }
+        const json = (await res.json()) as SystemInfoData
+        if (!disposed) setInfo(json)
+      } catch {
+        if (!disposed) setFailed(true)
+      }
+    })()
+    return () => {
+      disposed = true
+    }
+  }, [])
+
+  // Fetch fallido o servidor en demo: solo App + React + caption (SPEC-65 D65-7e)
+  const server = info && !info.demo ? info : null
+  const rows: { label: string; value: string }[] = [
+    { label: t('settings.about.sysApp'), value: `v${server?.version || pkg.version}` },
+    ...(server ? [{ label: t('settings.about.sysGo'), value: server.goVersion || '—' }] : []),
+    { label: t('settings.about.sysReact'), value: React.version },
+    ...(server
+      ? [
+          { label: t('settings.about.sysOs'), value: `${server.distro || server.os} ${server.arch}`.trim() || '—' },
+          { label: t('settings.about.sysKernel'), value: server.kernel || '—' },
+          {
+            label: t('settings.about.sysCpu'),
+            value: server.cpuModel ? `${server.cpuModel} (${server.cpuCores})` : server.cpuCores > 0 ? `${server.cpuCores}` : '—',
+          },
+          {
+            label: t('settings.about.sysRam'),
+            value: server.memTotalMb > 0 ? `${(server.memTotalMb / 1024).toFixed(1)} GiB` : '—',
+          },
+          { label: t('settings.about.sysUptime'), value: fmtUptime(server.uptimeS) },
+        ]
+      : []),
+  ]
+
+  return (
+    <div className="mt-5 border-t border-border pt-4">
+      <div className="text-caption font-semibold uppercase tracking-[0.06em] text-text-muted">
+        {t('settings.about.system')}
+      </div>
+      {!info && !failed ? (
+        <div className="mt-2.5 grid animate-pulse grid-cols-1 gap-x-6 gap-y-2.5 sm:grid-cols-2" aria-hidden="true">
+          {Array.from({ length: 4 }).map((_, i) => (
+            <div key={i} className="flex items-baseline justify-between gap-3">
+              <span className="h-3 w-14 rounded bg-elevated" />
+              <span className="h-3 w-24 rounded bg-elevated" />
+            </div>
+          ))}
+        </div>
+      ) : (
+        <>
+          <dl className="mt-2.5 grid grid-cols-1 gap-x-6 gap-y-1.5 sm:grid-cols-2">
+            {rows.map((r) => (
+              <div key={r.label} className="flex items-baseline justify-between gap-3">
+                <dt className="shrink-0 text-caption text-text-muted">{r.label}</dt>
+                <dd className="truncate font-mono text-caption text-text-secondary">{r.value}</dd>
+              </div>
+            ))}
+          </dl>
+          {!server && <p className="mt-2 text-caption text-text-muted">{t('settings.about.demoNoServer')}</p>}
+        </>
+      )}
+    </div>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
@@ -1046,6 +1230,196 @@ function ServicesCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   )
 }
 
+// ---------------------------------------------------------------------------
+// Tarjeta «Notificaciones push» (SPEC-PUSH §2)
+// ---------------------------------------------------------------------------
+
+type PushCardState =
+  | 'loading'
+  | 'insecure' // sin contexto seguro (HTTP en LAN que no sea localhost)
+  | 'unsupported' // sin SW / PushManager / Notification
+  | 'demo' // demo local: no se simula (una suscripción sin servidor nunca recibiría nada)
+  | 'denied' // permiso de notificaciones denegado en el navegador
+  | 'enabled' // suscripción push activa
+  | 'disabled' // todo listo, falta activar
+
+function PushNotificationsCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const [state, setState] = useState<PushCardState>('loading')
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+
+  // Detección del estado real: soporte → demo → permiso → suscripción viva
+  useEffect(() => {
+    let cancelled = false
+    void (async () => {
+      const ctx = pushContext()
+      if (ctx !== 'ok') {
+        setState(ctx)
+        return
+      }
+      if (isDemo) {
+        setState('demo')
+        return
+      }
+      if (Notification.permission === 'denied') {
+        setState('denied')
+        return
+      }
+      try {
+        const reg = await navigator.serviceWorker.getRegistration()
+        const sub = reg ? await reg.pushManager.getSubscription() : null
+        if (!cancelled) setState(sub ? 'enabled' : 'disabled')
+      } catch {
+        if (!cancelled) setState('disabled')
+      }
+    })()
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+
+  /** requestPermission → pushManager.subscribe(VAPID) → POST /api/push/subscribe */
+  const enable = useCallback(async () => {
+    if (busy) return
+    setBusy(true)
+    setError(null)
+    try {
+      const perm = await Notification.requestPermission()
+      if (perm !== 'granted') {
+        setState(perm === 'denied' ? 'denied' : 'disabled')
+        return
+      }
+      const vapid = await getVapidKey()
+      if (!vapid) {
+        setError(t('settings.push.errorServer'))
+        return
+      }
+      const reg = await navigator.serviceWorker.ready
+      // Timeout de seguridad: si el push service del navegador no responde
+      // (sin red, FCM inalcanzable…) el botón no se queda «Activando…»
+      const sub = await Promise.race([
+        reg.pushManager.subscribe({
+          userVisibleOnly: true,
+          applicationServerKey: urlBase64ToUint8Array(vapid) as BufferSource,
+        }),
+        new Promise<never>((_, reject) =>
+          window.setTimeout(() => reject(new Error('push subscribe timeout')), 15000),
+        ),
+      ])
+      const json = sub.toJSON()
+      const ok = await postPushSubscribe({
+        endpoint: sub.endpoint,
+        keys: { auth: json.keys?.auth ?? '', p256dh: json.keys?.p256dh ?? '' },
+      })
+      if (!ok) {
+        // El servidor no la guardó: baja local para no dejar estado fantasma
+        await sub.unsubscribe().catch(() => false)
+        setError(t('settings.push.errorServer'))
+        return
+      }
+      setState('enabled')
+      onSaved()
+    } catch {
+      setError(t('settings.push.errorGeneric'))
+    } finally {
+      setBusy(false)
+    }
+  }, [busy, t, onSaved])
+
+  /** Baja local + POST /api/push/unsubscribe (best-effort: el servidor purga 404/410) */
+  const disable = useCallback(async () => {
+    if (busy) return
+    setBusy(true)
+    setError(null)
+    try {
+      const reg = await navigator.serviceWorker.getRegistration()
+      const sub = reg ? await reg.pushManager.getSubscription() : null
+      if (sub) {
+        const endpoint = sub.endpoint
+        await sub.unsubscribe().catch(() => false)
+        await postPushUnsubscribe(endpoint)
+      }
+      setState('disabled')
+      onSaved()
+    } catch {
+      setError(t('settings.push.errorGeneric'))
+    } finally {
+      setBusy(false)
+    }
+  }, [busy, t, onSaved])
+
+  const btnBase =
+    'flex shrink-0 items-center gap-1.5 rounded-lg px-3.5 py-2 text-xs font-semibold transition-opacity hover:opacity-90 disabled:opacity-50'
+
+  return (
+    <Card title={t('settings.push.title')} caption={t('settings.push.caption')} index={4} reduce={reduce}>
+      {state === 'loading' && <p className="text-caption text-text-muted">{t('settings.push.checking')}</p>}
+
+      {state === 'enabled' && (
+        <div className="flex flex-wrap items-center justify-between gap-3">
+          <div className="flex min-w-0 items-center gap-2.5">
+            <span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-ok">
+              <BellRing className="h-3.5 w-3.5" strokeWidth={2} />
+              {t('settings.push.stateOn')}
+            </span>
+            <p className="text-caption leading-snug text-text-muted">{t('settings.push.stateOnCaption')}</p>
+          </div>
+          <button type="button" disabled={busy} onClick={() => void disable()} className={cn(btnBase, 'border border-border bg-elevated text-text-primary')}>
+            <BellOff className="h-3.5 w-3.5" strokeWidth={2} />
+            {busy ? t('settings.push.disabling') : t('settings.push.disable')}
+          </button>
+        </div>
+      )}
+
+      {state === 'disabled' && (
+        <div className="flex flex-wrap items-center justify-between gap-3">
+          <p className="min-w-0 flex-1 text-caption leading-snug text-text-secondary">{t('settings.push.stateOffCaption')}</p>
+          <button type="button" disabled={busy} onClick={() => void enable()} className={cn(btnBase, 'bg-accent text-canvas')}>
+            <BellRing className="h-3.5 w-3.5" strokeWidth={2} />
+            {busy ? t('settings.push.enabling') : t('settings.push.enable')}
+          </button>
+        </div>
+      )}
+
+      {state === 'denied' && (
+        <p className="rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-relaxed text-warn">
+          {t('settings.push.denied')}
+        </p>
+      )}
+
+      {state === 'unsupported' && (
+        <p className="rounded-xl bg-elevated px-3.5 py-2.5 text-caption leading-relaxed text-text-muted">
+          {t('settings.push.unsupported')}
+        </p>
+      )}
+
+      {state === 'insecure' && (
+        <p className="rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-relaxed text-warn">
+          {t('settings.push.insecure')}
+        </p>
+      )}
+
+      {state === 'demo' && (
+        <p className="rounded-xl bg-elevated px-3.5 py-2.5 text-caption leading-relaxed text-text-muted">
+          {t('settings.push.demoNote')}
+        </p>
+      )}
+
+      {error && (
+        <p role="alert" className="mt-3 rounded-lg bg-danger/10 px-3 py-2 text-caption text-danger">
+          {error}
+        </p>
+      )}
+
+      {(state === 'enabled' || state === 'disabled') && (
+        <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.push.note')}</p>
+      )}
+    </Card>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
@@ -1055,6 +1429,8 @@ export default function Settings() {
   const reduce = useReducedMotion() ?? false
   const { devices, routers, wan, isDemo } = useNetPulse()
   const auth = useAuth()
+  // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
+  const [services] = useServicesVisibility()
 
   // ——— Idioma ('en' por defecto; 'auto' sigue al navegador; persistido) ———
   const [lang, setLang] = useState<'auto' | 'es' | 'en'>(() => {
@@ -1128,6 +1504,71 @@ export default function Settings() {
     }
   }, [pwBusy, pwCurrent, pwNew, pwConfirm, t, notify])
 
+  // ——— Nombre para el saludo del Resumen (SPEC-65 D65-5/7d) ———
+  const [nameDraft, setNameDraft] = useState('')
+  const [nameBaseline, setNameBaseline] = useState('')
+  const [nameBusy, setNameBusy] = useState(false)
+  const [nameError, setNameError] = useState<string | null>(null)
+  useEffect(() => {
+    let v = auth?.displayName ?? ''
+    if (isDemo) {
+      try {
+        v = localStorage.getItem('netpulse-displayname') ?? v
+      } catch {
+        /* modo privado */
+      }
+    }
+    // eslint-disable-next-line react-hooks/set-state-in-effect -- sincroniza el draft con auth/localStorage al montar y tras cada refetch de /api/auth/me
+    setNameBaseline(v)
+    // eslint-disable-next-line react-hooks/set-state-in-effect
+    setNameDraft(v)
+  }, [isDemo, auth?.displayName])
+
+  const saveDisplayName = useCallback(async () => {
+    const v = nameDraft.trim()
+    if (nameBusy || v === nameBaseline) return
+    setNameBusy(true)
+    setNameError(null)
+    if (isDemo) {
+      try {
+        localStorage.setItem('netpulse-displayname', v)
+      } catch {
+        /* modo privado */
+      }
+      window.dispatchEvent(new Event('netpulse-auth-refresh'))
+      setNameBaseline(v)
+      setNameDraft(v)
+      setNameBusy(false)
+      notify()
+      return
+    }
+    try {
+      const res = await fetch('/api/users/me/display-name', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ displayName: v }),
+      })
+      if (res.status === 404 || res.status === 405) {
+        // Endpoint aún no desplegado: fallback local (mismo almacén que el demo)
+        try {
+          localStorage.setItem('netpulse-displayname', v)
+        } catch {
+          /* modo privado */
+        }
+      } else if (!res.ok && res.status !== 204) {
+        throw new Error(`HTTP ${res.status}`)
+      }
+      window.dispatchEvent(new Event('netpulse-auth-refresh'))
+      setNameBaseline(v)
+      setNameDraft(v)
+      notify()
+    } catch {
+      setNameError(t('settings.users.errorGeneric'))
+    } finally {
+      setNameBusy(false)
+    }
+  }, [nameDraft, nameBaseline, nameBusy, isDemo, notify, t])
+
 
   // ——— Tema (compatible con ThemeToggle: 'netpulse-theme' = light|dark) ———
   const [mode, setMode] = useStoredState<ThemeMode>(
@@ -1630,6 +2071,11 @@ export default function Settings() {
           </Card>
         </div>
 
+        {/* Notificaciones push (Web Push nativo, SPEC-PUSH §2) */}
+        <div className="lg:col-span-7">
+          <PushNotificationsCard reduce={reduce} onSaved={notify} />
+        </div>
+
         {/* Gestión de routers — solo con backend (modo live) */}
         {!isDemo && (
           <div className="lg:col-span-12">
@@ -1637,8 +2083,8 @@ export default function Settings() {
           </div>
         )}
 
-        {/* AdGuard Home (GL.iNet) — solo admin y modo live */}
-        {!isDemo && auth?.role === 'admin' && (
+        {/* AdGuard Home (GL.iNet) — solo admin, modo live y servicio visible */}
+        {!isDemo && auth?.role === 'admin' && services.adguard && (
           <div className="lg:col-span-12">
             <AdGuardManager reduce={reduce} onSaved={notify} />
           </div>
@@ -1654,6 +2100,37 @@ export default function Settings() {
         {/* Mi sesión: cambiar contraseña + cerrar sesión (patrón easyzfs) */}
         <div className="lg:col-span-12">
           <Card title={t('settings.session.title')} index={5} reduce={reduce}>
+            {/* Nombre para el saludo del Resumen (SPEC-65 D65-7d) */}
+            <div className="mb-4 max-w-md">
+              <label htmlFor="session-display-name" className="text-sm font-medium text-text-primary">
+                {t('settings.session.name')}
+              </label>
+              <div className="mt-2 flex items-center gap-2">
+                <input
+                  id="session-display-name"
+                  type="text"
+                  value={nameDraft}
+                  maxLength={40}
+                  onChange={(e) => setNameDraft(e.target.value)}
+                  placeholder={auth?.user ?? ''}
+                  className="h-10 min-w-0 flex-1 rounded-lg border border-border bg-elevated px-3 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                />
+                <button
+                  type="button"
+                  onClick={() => void saveDisplayName()}
+                  disabled={nameBusy || nameDraft.trim() === nameBaseline}
+                  className="flex h-10 shrink-0 items-center rounded-lg bg-accent px-4 text-sm font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
+                >
+                  {t('settings.adguard.save')}
+                </button>
+              </div>
+              <p className="mt-1.5 text-caption text-text-muted">{t('settings.session.nameHint')}</p>
+              {nameError && (
+                <p role="alert" className="mt-1.5 text-caption text-danger">
+                  {nameError}
+                </p>
+              )}
+            </div>
             <div className="flex flex-wrap items-center gap-3">
               {!isDemo && (
                 <button
@@ -1830,6 +2307,9 @@ export default function Settings() {
 
             </div>
 
+            {/* Sistema: datos del servidor (SPEC-65 D65-7e) */}
+            <SystemInfoBlock />
+
             <p className="mt-5 border-t border-border pt-3 font-mono text-caption text-text-muted">
               {t('settings.about.footer')}
             </p>

+ 64 - 8
app/src/pages/Topology.tsx

@@ -2,11 +2,11 @@
  * NetPulse — Página Topología `/topology` (topology.md).
  * Header con controles → mapa SVG animado (pan/zoom) → leyenda + enlaces.
  */
-import { useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router-dom'
 import { motion, useReducedMotion } from 'framer-motion'
-import { ChevronRight, Maximize, ZoomIn, ZoomOut } from 'lucide-react'
+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'
@@ -21,19 +21,22 @@ const EASE = [0.16, 1, 0.3, 1] as [number, number, number, number]
 function ControlButton({
   label,
   onClick,
+  disabled,
   children,
 }: {
   label: string
   onClick?: () => void
+  disabled?: boolean
   children: React.ReactNode
 }) {
   return (
     <button
       type="button"
       onClick={onClick}
+      disabled={disabled}
       aria-label={label}
       title={label}
-      className="flex h-9 w-9 items-center justify-center rounded-lg text-text-secondary transition-colors duration-150 hover:bg-hover hover:text-text-primary active:bg-hover"
+      className="flex h-9 w-9 items-center justify-center rounded-lg text-text-secondary transition-colors duration-150 hover:bg-hover hover:text-text-primary active:bg-hover disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-text-secondary"
     >
       {children}
     </button>
@@ -43,16 +46,54 @@ function ControlButton({
 export default function Topology() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { routers, devices, wan, wireguard, distributionNodes } = useNetPulse()
+  const { routers, devices, wan, wireguard, distributionNodes, topology, vm, lastSnapshotAt, requestServerRefresh } =
+    useNetPulse()
   const model = useMemo(
-    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes }),
-    [routers, devices, wan, wireguard, distributionNodes],
+    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes, topology, vm }),
+    [routers, devices, wan, wireguard, distributionNodes, topology, vm],
   )
   const [showLabels, setShowLabels] = useState(true)
   const [flow, setFlow] = useState(true)
   const [hoverLink, setHoverLink] = useState<string | null>(null)
   const mapApi = useRef<TopologyMapApi>({})
 
+  // Botón "Refrescar": POST /api/refresh → el backend sondea ya y empuja el
+  // snapshot por SSE. El icono gira hasta que llega ese snapshot (sin recargar
+  // ni re-montar el grafo) o hasta el timeout de seguridad de 10 s.
+  const [refreshing, setRefreshing] = useState(false)
+  const refreshStartRef = useRef(0)
+  const refreshTimeoutRef = useRef<number | undefined>(undefined)
+
+  const stopRefreshSpin = () => {
+    window.clearTimeout(refreshTimeoutRef.current)
+    refreshTimeoutRef.current = undefined
+    refreshStartRef.current = 0
+    setRefreshing(false)
+  }
+
+  useEffect(() => {
+    if (refreshing && refreshStartRef.current > 0 && lastSnapshotAt >= refreshStartRef.current) {
+      stopRefreshSpin()
+    }
+  }, [lastSnapshotAt, refreshing])
+
+  useEffect(() => () => window.clearTimeout(refreshTimeoutRef.current), [])
+
+  const handleRefresh = () => {
+    if (refreshing) return
+    setRefreshing(true)
+    refreshStartRef.current = Date.now()
+    void requestServerRefresh().then((waiting) => {
+      if (waiting) {
+        // 202/429: espera al próximo snapshot SSE (o al timeout de 10 s)
+        refreshTimeoutRef.current = window.setTimeout(stopRefreshSpin, 10_000)
+      } else {
+        // Demo local o petición fallida: no llegará snapshot; spin breve
+        refreshTimeoutRef.current = window.setTimeout(stopRefreshSpin, 800)
+      }
+    })
+  }
+
   const controlMotion = (i: number) =>
     reduce
       ? {}
@@ -102,20 +143,35 @@ export default function Topology() {
           <motion.div
             {...controlMotion(0)}
             className="flex items-center gap-0.5 rounded-xl border border-border bg-surface p-1"
+          >
+            <ControlButton
+              label={refreshing ? t('topology.refreshing') : t('topology.refreshNow')}
+              onClick={handleRefresh}
+              disabled={refreshing}
+            >
+              <RefreshCw
+                className={`h-[18px] w-[18px] ${refreshing ? 'animate-spin' : ''}`}
+                strokeWidth={1.75}
+              />
+            </ControlButton>
+          </motion.div>
+          <motion.div
+            {...controlMotion(1)}
+            className="flex items-center gap-0.5 rounded-xl border border-border bg-surface p-1"
             role="group"
             aria-label={t('topology.zoomControls')}
           >
             {zoomControls}
           </motion.div>
           <motion.label
-            {...controlMotion(1)}
+            {...controlMotion(2)}
             className="flex cursor-pointer items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm font-medium text-text-secondary"
           >
             <Switch checked={showLabels} onCheckedChange={setShowLabels} aria-label={t('topology.showLabels')} />
             {t('topology.labels')}
           </motion.label>
           <motion.label
-            {...controlMotion(2)}
+            {...controlMotion(3)}
             className="flex cursor-pointer items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm font-medium text-text-secondary"
           >
             <Switch checked={flow} onCheckedChange={setFlow} aria-label={t('topology.animateFlow')} />

+ 70 - 315
app/src/pages/devices-data.ts

@@ -1,13 +1,20 @@
 /**
- * Devices — extensión local del canon (design.md §11 / devices.md §④).
- * Los 10 dispositivos destacados de `@/data/mock` se reutilizan tal cual;
- * la entrada agregada "Bombillas Ikea ×6" se expande en sus 6 bombillas
- * individuales y se añaden los clientes restantes hasta los totales del
- * canon: 46 conocidos · 38 online · 8 offline (Gateway 13, Salón 18,
- * Estudio 9, Patio 6). Nada aquí contradice `@/data/mock`.
+ * Devices — enriquecido local de clientes (design.md §11 / devices.md §④).
+ *
+ * SPEC-65 D65-1 (single-source): el canon de dispositivos (65 IDs únicos,
+ * D3/D5: 59 online · 6 offline · 3 nuevos hoy; online por router Gateway 26,
+ * Salón 20, Estudio 8, Patio 5) vive SOLO en `@/data/demo-canon.json`
+ * (re-exportado por `@/data/mock`) y ya trae inline los metadatos de cliente
+ * (hostname, DHCP, primer visto, tráfico 24h, AdGuard, grupo). Este módulo
+ * ya NO expande ni duplica el canon: solo fusiona metadatos.
+ * - Canon con metadatos inline (demo local o API demo): se usan tal cual
+ *   (el JSON es la verdad reconciliada).
+ * - Live sin metadatos (servidor real): se fusionan los detalles conocidos
+ *   por id (CANON_DETAILS) o se derivan valores plausibles — nunca se
+ *   inventan dispositivos que la API no ha reportado.
  */
 import type { LucideIcon } from 'lucide-react'
-import { BookOpen, Printer } from 'lucide-react'
+import { BookOpen, Network, Printer } from 'lucide-react'
 import type { Device } from '@/data/mock'
 import { devices as canonDevices } from '@/data/mock'
 
@@ -15,7 +22,7 @@ import { devices as canonDevices } from '@/data/mock'
 // Tipos
 // ---------------------------------------------------------------------------
 
-export type FilterGroup = 'moviles' | 'ordenadores' | 'tv' | 'iot' | 'red' | 'otros'
+export type FilterGroup = 'infra' | 'moviles' | 'ordenadores' | 'tv' | 'iot' | 'red' | 'otros'
 
 export interface ClientDevice extends Device {
   hostname: string
@@ -36,19 +43,15 @@ export interface ClientDevice extends Device {
   iconOverride?: LucideIcon
 }
 
-export const GROUP_LABELS: Record<FilterGroup, string> = {
-  moviles: 'Mobiles',
-  ordenadores: 'Computers',
-  tv: 'TV & consoles',
-  iot: 'IoT & home',
-  red: 'Network',
-  otros: 'Others',
-}
-
-export const GROUP_ORDER: FilterGroup[] = ['moviles', 'ordenadores', 'tv', 'iot', 'red', 'otros']
+// 'infra' primero (D6): hipervisores, CTs y switches gestionados de un vistazo.
+// El grupo 'infra' no deriva del `type`: lo asigna Devices.tsx cruzando
+// device.infra (sellado server-side, SPEC-65 D65-2) o, como fallback,
+// attachTo/lldp con los distributionNodes del provider.
+export const GROUP_ORDER: FilterGroup[] = ['infra', 'moviles', 'ordenadores', 'tv', 'iot', 'red', 'otros']
 
 // ---------------------------------------------------------------------------
-// Detalles extra de los dispositivos canónicos (mock.ts §Dispositivos)
+// Detalles extra de los dispositivos canónicos: fallback para live cuando la
+// API no trae metadatos inline (el canon JSON del demo ya los trae todos).
 // ---------------------------------------------------------------------------
 
 const CANON_DETAILS: Record<string, Omit<ClientDevice, keyof Device>> = {
@@ -92,297 +95,17 @@ const CANON_DETAILS: Record<string, Omit<ClientDevice, keyof Device>> = {
     hostname: 'galaxy-tab-s9', dhcpLease: 'renews in 11h 5min', firstSeen: 'today',
     traffic24hRx: '640 MB', traffic24hTx: '48 MB', adguard: true, group: 'moviles', newThisWeek: true,
   },
-}
-
-// ---------------------------------------------------------------------------
-// Sparkline determinista (mock): paseo pseudo-aleatorio alrededor de `base`
-// ---------------------------------------------------------------------------
-
-function spark(seed: number, base: number, spread: number): number[] {
-  let s = seed
-  const out: number[] = []
-  for (let i = 0; i < 12; i++) {
-    s = (s * 9301 + 49297) % 233280
-    const r = s / 233280
-    out.push(Math.max(0, +(base + (r - 0.45) * spread).toFixed(2)))
-  }
-  out[out.length - 1] = base
-  return out
-}
-
-function extra(spec: Omit<Device, 'sparkline'> & { seed?: number; spread?: number }): Device {
-  const { seed = 1, spread, ...d } = spec
-  return { ...d, sparkline: d.online ? spark(seed, d.trafficMbps, spread ?? d.trafficMbps * 0.8) : [] }
-}
-
-function bulb(n: number, name: string, ip: string, mac: string, dbm: number): ClientDevice {
-  return {
-    id: `bombilla-${n}`, name, type: 'iot', manufacturer: 'Ikea Trådfri',
-    ip, mac, routerId: 'living', band: '2.4 GHz', signalDbm: dbm,
-    trafficMbps: 0, online: true, sparkline: spark(40 + n, 0.005, 0.02),
-    hostname: `tradfri-${n}`, dhcpLease: 'renews in 12h 0min', firstSeen: '280 days ago',
-    traffic24hRx: '4 MB', traffic24hTx: '1 MB', adguard: true, group: 'iot',
-  }
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos adicionales (canon: los 10 destacados ya están en mock.ts;
-// aquí están el resto hasta 47 — devices.md §④ "29 adicionales plausibles")
-// ---------------------------------------------------------------------------
-
-const ADDITIONAL: ClientDevice[] = [
-  // —— Gateway (flint2): 13 totales (canon: pixel-8-pro, nas-synology) ——
-  {
-    ...extra({ id: 'iphone-ana', name: "Ana's iPhone", type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.44', mac: 'F4:D4:88:19:C2:71', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -46, trafficMbps: 2.1, online: true, seed: 11 }),
-    hostname: 'iphone-de-ana', dhcpLease: 'renews in 6h 40min', firstSeen: '190 days ago',
-    traffic24hRx: '2.8 GB', traffic24hTx: '240 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'macbook-pro', name: "Marc's MacBook Pro", type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.26', mac: 'F0:18:98:5A:11:E9', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -44, trafficMbps: 8.6, online: true, seed: 12 }),
-    hostname: 'macbook-pro-marc', dhcpLease: 'renews in 4h 16min', firstSeen: '230 days ago',
-    traffic24hRx: '12.4 GB', traffic24hTx: '1.9 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'pc-sobremesa', name: 'Desktop PC', type: 'ordenador', manufacturer: 'ASUSTeK',
-      ip: '192.168.8.11', mac: '04:D4:C4:8B:30:A7', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 21.3, online: true, seed: 13 }),
-    hostname: 'desktop-8f2k1', dhcpLease: 'Static IP (reservation)', firstSeen: '310 days ago',
-    traffic24hRx: '84 GB', traffic24hTx: '6.2 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'raspberry-pi', name: 'Raspberry Pi 4', type: 'servidor', manufacturer: 'Raspberry Pi',
-      ip: '192.168.8.12', mac: 'DC:A6:32:4F:77:02', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 0.8, online: true, seed: 14 }),
-    hostname: 'raspberrypi', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
-    traffic24hRx: '3.4 GB', traffic24hTx: '890 MB', adguard: true, group: 'red',
-  },
-  // (El switch Netgear GS308E ya no es un Device: el backend demo lo emite
-  // como DistributionNode kind='managed' — dist-living-lan3, ver mock.ts.)
-  {
-    ...extra({ id: 'timbre-nest', name: 'Nest doorbell', type: 'camara', manufacturer: 'Google',
-      ip: '192.168.8.72', mac: 'F4:F5:D8:66:01:B8', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -58, trafficMbps: 0.6, online: true, seed: 16 }),
-    hostname: 'nest-doorbell', dhcpLease: 'renews in 9h 44min', firstSeen: '170 days ago',
-    traffic24hRx: '1.2 GB', traffic24hTx: '140 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'enchufe-lavadora', name: 'Washing machine plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.81', mac: '50:C7:BF:22:E1:9C', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0.01, online: true, seed: 17, spread: 0.02 }),
-    hostname: 'tapo-p110-lavadora', dhcpLease: 'renews in 12h 0min', firstSeen: '140 days ago',
-    traffic24hRx: '8 MB', traffic24hTx: '2 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ id: 'pixel-7', name: 'Pixel 7', type: 'movil', manufacturer: 'Google',
-      ip: '192.168.8.46', mac: '3C:5A:B4:08:D7:5E', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -49, trafficMbps: 1.4, online: true, seed: 18 }),
-    hostname: 'pixel-7', dhcpLease: 'renews in 7h 3min', firstSeen: '205 days ago',
-    traffic24hRx: '1.9 GB', traffic24hTx: '180 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'impresora-hp', name: 'HP Printer', type: 'desconocido', manufacturer: 'HP',
-      ip: '192.168.8.14', mac: '3C:52:82:AB:19:60', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -60, trafficMbps: 0, online: false }),
-    hostname: 'hp-laserjet-m209', dhcpLease: 'Expired', firstSeen: '250 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'otros',
-    iconOverride: Printer,
-  },
-  {
-    ...extra({ id: 'ipad-air', name: 'iPad Air', type: 'tablet', manufacturer: 'Apple',
-      ip: '192.168.8.47', mac: '8C:85:90:2F:B4:11', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -54, trafficMbps: 0, online: false }),
-    hostname: 'ipad-air', dhcpLease: 'Expired', firstSeen: '260 days ago',
-    traffic24hRx: '6.4 GB', traffic24hTx: '520 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', manufacturer: 'Lenovo',
-      ip: '192.168.8.27', mac: '54:EE:75:9A:03:F1', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -50, trafficMbps: 0, online: false }),
-    hostname: 'thinkpad-t14', dhcpLease: 'Expired', firstSeen: '160 days ago',
-    traffic24hRx: '812 MB', traffic24hTx: '121 MB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'kindle', name: 'Kindle Paperwhite', type: 'desconocido', manufacturer: 'Amazon',
-      ip: '192.168.8.49', mac: '44:65:0D:71:28:C3', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -58, trafficMbps: 0, online: false }),
-    hostname: 'kindle-paperwhite', dhcpLease: 'Expired', firstSeen: '220 days ago',
-    traffic24hRx: '220 MB', traffic24hTx: '8 MB', adguard: true, group: 'otros',
-    iconOverride: BookOpen,
-  },
-]
-
-const LIVING: ClientDevice[] = [
-  // —— Salón (living): 18 totales (canon: imac, tv-samsung, ps5, galaxy-tab-s9) ——
-  bulb(1, 'Living room bulb 1', '192.168.8.90', 'CC:86:EC:10:04:21', -58),
-  bulb(2, 'Living room bulb 2', '192.168.8.91', 'CC:86:EC:10:04:22', -59),
-  bulb(3, 'Floor lamp bulb', '192.168.8.92', 'CC:86:EC:10:04:23', -61),
-  bulb(4, 'Entryway bulb', '192.168.8.93', 'CC:86:EC:10:04:24', -64),
-  bulb(5, 'Hallway bulb', '192.168.8.94', 'CC:86:EC:10:04:25', -66),
-  bulb(6, 'Kitchen bulb', '192.168.8.95', 'CC:86:EC:10:04:26', -60),
-  {
-    ...extra({ id: 'chromecast', name: 'Chromecast HD', type: 'tv', manufacturer: 'Google',
-      ip: '192.168.8.36', mac: '54:60:09:E3:5B:0A', routerId: 'living', band: '5 GHz',
-      signalDbm: -54, trafficMbps: 3.9, online: true, seed: 21 }),
-    hostname: 'chromecast-hd', dhcpLease: 'renews in 6h 12min', firstSeen: '200 days ago',
-    traffic24hRx: '21 GB', traffic24hTx: '380 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'homepod-mini', name: 'HomePod mini', type: 'altavoz', manufacturer: 'Apple',
-      ip: '192.168.8.53', mac: 'F0:D1:A9:3E:77:5C', routerId: 'living', band: '5 GHz',
-      signalDbm: -47, trafficMbps: 0.3, online: true, seed: 22 }),
-    hostname: 'homepod-mini', dhcpLease: 'renews in 10h 41min', firstSeen: '190 days ago',
-    traffic24hRx: '2.2 GB', traffic24hTx: '96 MB', adguard: true, group: 'iot',
+  // D1: el GS308E vuelve a ser Device (además del distnode managed del canon).
+  // Su grupo visible es 'infra' (lo reasigna Devices.tsx con device.infra/lldp).
+  'switch-netgear': {
+    hostname: 'gs308e', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
+    traffic24hRx: '96 MB', traffic24hTx: '42 MB', adguard: false, group: 'red',
   },
-  {
-    ...extra({ id: 'galaxy-s23', name: 'Galaxy S23', type: 'movil', manufacturer: 'Samsung',
-      ip: '192.168.8.42', mac: '5C:0A:5B:88:1D:E4', routerId: 'living', band: '5 GHz',
-      signalDbm: -51, trafficMbps: 0.9, online: true, seed: 23 }),
-    hostname: 'galaxy-s23', dhcpLease: 'renews in 8h 55min', firstSeen: '175 days ago',
-    traffic24hRx: '3.2 GB', traffic24hTx: '290 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'echo-dot', name: 'Echo Dot', type: 'altavoz', manufacturer: 'Amazon',
-      ip: '192.168.8.54', mac: '74:C2:46:19:F0:6B', routerId: 'living', band: '2.4 GHz',
-      signalDbm: -56, trafficMbps: 0.2, online: true, seed: 24 }),
-    hostname: 'echo-dot-cocina', dhcpLease: 'renews in 11h 18min', firstSeen: '210 days ago',
-    traffic24hRx: '1.1 GB', traffic24hTx: '74 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'nintendo-switch', name: 'Nintendo Switch', type: 'consola', manufacturer: 'Nintendo',
-      ip: '192.168.8.33', mac: '58:BD:A3:4C:E2:09', routerId: 'living', band: '5 GHz',
-      signalDbm: -53, trafficMbps: 0.1, online: true, seed: 25, spread: 0.3 }),
-    hostname: 'switch-oled', dhcpLease: 'renews in 5h 47min', firstSeen: '240 days ago',
-    traffic24hRx: '8.6 GB', traffic24hTx: '310 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'portatil-invitado', name: 'Guest laptop', type: 'portatil', manufacturer: 'Desconocido',
-      ip: '192.168.8.29', mac: 'A2:7E:9C:41:0B:6D', routerId: 'living', band: '5 GHz',
-      signalDbm: -58, trafficMbps: 0.7, online: true, isNew: true, seed: 26 }),
-    hostname: 'unknown-7f2a', dhcpLease: 'renews in 2h 9min', firstSeen: 'today',
-    traffic24hRx: '480 MB', traffic24hTx: '62 MB', adguard: false, group: 'ordenadores',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'xbox-series-s', name: 'Xbox Series S', type: 'consola', manufacturer: 'Microsoft',
-      ip: '192.168.8.32', mac: '7C:1E:52:06:AA:3F', routerId: 'living', band: '5 GHz',
-      signalDbm: -55, trafficMbps: 0, online: false }),
-    hostname: 'xbox-series-s', dhcpLease: 'Expired', firstSeen: '230 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'portatil-antiguo', name: 'Old laptop', type: 'portatil', manufacturer: 'HP',
-      ip: '192.168.8.28', mac: '3C:52:82:5D:90:17', routerId: 'living', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0, online: false }),
-    hostname: 'hp-pavilion-15', dhcpLease: 'Expired', firstSeen: '300 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const ESTUDIO: ClientDevice[] = [
-  // —— Estudio: 9 totales (canon: macbook-air, nest-mini) ——
-  {
-    ...extra({ id: 'mac-mini', name: 'Mac mini', type: 'ordenador', manufacturer: 'Apple',
-      ip: '192.168.8.22', mac: 'A4:83:E7:66:2C:98', routerId: 'estudio', band: 'cable',
-      signalDbm: null, trafficMbps: 1.9, online: true, seed: 31 }),
-    hostname: 'mac-mini', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '44 GB', traffic24hTx: '5.6 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'enchufe-ventilador', name: 'Fan plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.82', mac: '9C:53:22:B1:4E:70', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -59, trafficMbps: 0.01, online: true, seed: 32, spread: 0.02 }),
-    hostname: 'tapo-p110-ventilador', dhcpLease: 'renews in 12h 0min', firstSeen: '120 days ago',
-    traffic24hRx: '7 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'ipad-pro', name: 'iPad Pro', type: 'tablet', manufacturer: 'Apple',
-      ip: '192.168.8.51', mac: 'F0:18:98:91:5A:2B', routerId: 'estudio', band: '5 GHz',
-      signalDbm: -49, trafficMbps: 0.8, online: true, seed: 33 }),
-    hostname: 'ipad-pro', dhcpLease: 'renews in 9h 26min', firstSeen: '160 days ago',
-    traffic24hRx: '5.1 GB', traffic24hTx: '390 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'hue-hub', name: 'Hub Philips Hue', type: 'iot', manufacturer: 'Signify',
-      ip: '192.168.8.15', mac: '00:17:88:2A:91:CE', routerId: 'estudio', band: 'cable',
-      signalDbm: null, trafficMbps: 0.02, online: true, seed: 34, spread: 0.04 }),
-    hostname: 'philips-hue-bridge', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '96 MB', traffic24hTx: '22 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ id: 'sonos-one', name: 'Sonos One', type: 'altavoz', manufacturer: 'Sonos',
-      ip: '192.168.8.55', mac: '48:A6:B8:14:72:E0', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -57, trafficMbps: 0.5, online: true, seed: 35 }),
-    hostname: 'sonos-one-estudio', dhcpLease: 'renews in 10h 4min', firstSeen: '195 days ago',
-    traffic24hRx: '3.8 GB', traffic24hTx: '110 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'iphone-trabajo', name: 'Work iPhone', type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.50', mac: '8C:85:90:47:C1:93', routerId: 'estudio', band: '5 GHz',
-      signalDbm: -47, trafficMbps: 0.3, online: true, isNew: true, seed: 36 }),
-    hostname: 'iphone-15-pro-work', dhcpLease: 'renews in 3h 38min', firstSeen: 'today',
-    traffic24hRx: '320 MB', traffic24hTx: '41 MB', adguard: true, group: 'moviles',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'macbook-viejo', name: 'Old MacBook', type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.25', mac: '3C:22:FB:0E:66:A1', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -60, trafficMbps: 0, online: false }),
-    hostname: 'macbook-pro-2015', dhcpLease: 'Expired', firstSeen: '320 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const PATIO: ClientDevice[] = [
-  // —— Patio: 6 totales (canon: robot-aspirador, camara-porche) ——
-  {
-    ...extra({ id: 'camara-jardin', name: 'Garden camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.73', mac: 'EC:71:DB:44:12:9B', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -74, trafficMbps: 1.4, online: true, seed: 41 }),
-    hostname: 'reolink-jardin', dhcpLease: 'renews in 8h 49min', firstSeen: '4 days ago',
-    traffic24hRx: '14 GB', traffic24hTx: '820 MB', adguard: true, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'sensor-riego', name: 'Irrigation sensor', type: 'iot', manufacturer: 'Tuya',
-      ip: '192.168.8.89', mac: 'D8:1F:12:5B:08:44', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -71, trafficMbps: 0.01, online: true, seed: 42, spread: 0.02 }),
-    hostname: 'tuya-riego-01', dhcpLease: 'renews in 12h 0min', firstSeen: '5 days ago',
-    traffic24hRx: '2 MB', traffic24hTx: '1 MB', adguard: false, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'enchufe-calefactor', name: 'Heater plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.80', mac: '50:C7:BF:31:7A:05', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -75, trafficMbps: 0.02, online: true, seed: 43, spread: 0.03 }),
-    hostname: 'tapo-p110-calefactor', dhcpLease: 'renews in 12h 0min', firstSeen: '96 days ago',
-    traffic24hRx: '6 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'camara-garaje', name: 'Garage camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.74', mac: 'EC:71:DB:44:13:02', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -78, trafficMbps: 0, online: false }),
-    hostname: 'reolink-garaje', dhcpLease: 'Expired', firstSeen: '130 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: false, group: 'iot',
-  },
-]
-
-// ---------------------------------------------------------------------------
-// Lista completa: 47 clientes (los 10 del canon — salvo el agregado de
-// bombillas, que se expande — + 37 adicionales)
-// ---------------------------------------------------------------------------
+}
 
 // ---------------------------------------------------------------------------
 // Builder: enriquece una lista de `Device` (mock local o API) con los
 // metadatos de cliente (hostname, DHCP, AdGuard, grupo de filtro).
-// - `withSynthetic=true` (modo demo local, sin backend): expande el canon a
-//   los 47 clientes del mockup (agregado de bombillas + adicionales).
-// - `withSynthetic=false` (backend live): solo fusiona detalles conocidos por
-//   id y deriva valores plausibles para clientes nuevos — nunca inventa
-//   dispositivos que la API no ha reportado.
 // ---------------------------------------------------------------------------
 
 const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
@@ -400,6 +123,9 @@ const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
   desconocido: 'otros',
 }
 
+/** Iconos lucide referenciados POR NOMBRE en el canon JSON (iconOverride). */
+const ICON_BY_NAME: Record<string, LucideIcon> = { BookOpen, Network, Printer }
+
 function slug(name: string): string {
   return (
     name
@@ -424,19 +150,48 @@ function defaultDetails(d: Device): Omit<ClientDevice, keyof Device> {
   }
 }
 
-export function buildClientDevices(canon: Device[], withSynthetic: boolean): ClientDevice[] {
-  const expanded: ClientDevice[] = canon
-    .filter((d) => !withSynthetic || d.id !== 'bombillas-ikea')
-    .map((d) => ({ ...d, ...(CANON_DETAILS[d.id] ?? defaultDetails(d)) }))
-  if (!withSynthetic) return expanded
-  return [...expanded, ...ADDITIONAL, ...LIVING, ...ESTUDIO, ...PATIO]
+/** Metadatos de cliente que pueden venir inline (canon JSON / API demo). */
+interface InlineDetails {
+  hostname?: string
+  dhcpLease?: string
+  firstSeen?: string
+  traffic24hRx?: string
+  traffic24hTx?: string
+  adguard?: boolean
+  group?: FilterGroup
+  iconOverride?: string
+  newThisWeek?: boolean
+}
+
+/** Extrae los metadatos inline del canon; null si el Device no los trae. */
+function inlineDetails(d: Device): Omit<ClientDevice, keyof Device> | null {
+  const raw = d as Device & InlineDetails
+  if (typeof raw.hostname !== 'string' || typeof raw.group !== 'string') return null
+  return {
+    hostname: raw.hostname,
+    dhcpLease: raw.dhcpLease ?? '—',
+    firstSeen: raw.firstSeen ?? '—',
+    traffic24hRx: raw.traffic24hRx ?? '—',
+    traffic24hTx: raw.traffic24hTx ?? '—',
+    adguard: raw.adguard ?? true,
+    group: raw.group ?? TYPE_TO_GROUP[d.type],
+    newThisWeek: raw.newThisWeek,
+    iconOverride: raw.iconOverride ? ICON_BY_NAME[raw.iconOverride] : undefined,
+  }
 }
 
-const canonExpanded: ClientDevice[] = canonDevices
-  .filter((d) => d.id !== 'bombillas-ikea')
-  .map((d) => ({ ...d, ...CANON_DETAILS[d.id] }))
+/**
+ * Fusiona metadatos de cliente sobre la lista de Devices. Prioridad:
+ * inline (canon JSON / API demo) > CANON_DETAILS (ids conocidos) > defaults.
+ * `withSynthetic` se conserva por compatibilidad de firma: desde D65-1 el
+ * canon ya llega completo (65 IDs) y nunca se sintetizan devices extra.
+ */
+export function buildClientDevices(canon: Device[], withSynthetic = false): ClientDevice[] {
+  void withSynthetic // legado de la firma: el canon ya viene completo (D65-1)
+  return canon.map((d) => ({ ...d, ...(inlineDetails(d) ?? CANON_DETAILS[d.id] ?? defaultDetails(d)) }))
+}
 
-export const allDevices: ClientDevice[] = [...canonExpanded, ...ADDITIONAL, ...LIVING, ...ESTUDIO, ...PATIO]
+export const allDevices: ClientDevice[] = buildClientDevices(canonDevices, true)
 
 /** Señal débil: online con < −70 dBm (devices.md §②) */
 export const weakSignalCount = allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < -70).length

+ 19 - 2
app/src/sections/HeroStrip.tsx

@@ -1,5 +1,5 @@
 import { motion, useReducedMotion } from 'framer-motion'
-import { Fragment } from 'react'
+import { Fragment, useEffect, useState } from 'react'
 import { ArrowDown, ArrowUp, Gauge, MonitorSmartphone } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import { healthLabel } from '@/i18n'
@@ -53,7 +53,24 @@ export function HeroStrip() {
   const { refreshKey } = useDashboard()
   const { deviceTotals, health: healthScore, wan } = useNetPulse()
   const auth = useAuth()
-  const greeting = t(greetingKey()) + (auth?.user ? t('home.greetingName', { name: auth.user }) : '')
+  // SPEC-65 D65-5: saluda con displayName || username. En demo (sin backend)
+  // el nombre vive en localStorage ('netpulse-displayname').
+  const [demoName, setDemoName] = useState('')
+  useEffect(() => {
+    if (auth) return
+    const read = () => {
+      try {
+        setDemoName(localStorage.getItem('netpulse-displayname') ?? '')
+      } catch {
+        /* modo privado */
+      }
+    }
+    read()
+    window.addEventListener('netpulse-auth-refresh', read)
+    return () => window.removeEventListener('netpulse-auth-refresh', read)
+  }, [auth])
+  const name = auth ? auth.displayName || auth.user : demoName
+  const greeting = t(greetingKey()) + (name ? t('home.greetingName', { name }) : '')
   const words = greeting.split(' ')
 
   return (

+ 93 - 0
app/src/sw.ts

@@ -0,0 +1,93 @@
+/// <reference lib="webworker" />
+/**
+ * NetPulse — Service Worker propio (vite-plugin-pwa `injectManifest`).
+ *
+ * ¿Por qué injectManifest y no generateSW + importScripts?
+ * generateSW no admite handlers custom (Web Push exige `push` y
+ * `notificationclick`). La alternativa "mínima" (importScripts de un
+ * push-sw.js estático en public/) dejaba la lógica push fuera del build TS
+ * (sin type-check, sin minificar, archivo separado que versionar a mano) y
+ * además ese archivo caía dentro del propio glob de precache. Con
+ * injectManifest el SW es un único bundle TS versionado y el precache
+ * app-shell se inyecta en self.__WB_MANIFEST con los mismos globPatterns
+ * de siempre (16 entradas).
+ */
+import { clientsClaim } from 'workbox-core'
+import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
+import { NavigationRoute, registerRoute } from 'workbox-routing'
+
+declare let self: ServiceWorkerGlobalScope
+
+// registerType: 'autoUpdate' — el SW nuevo toma el control sin esperar al
+// cierre de pestañas (equivale al comportamiento anterior con generateSW).
+self.skipWaiting()
+clientsClaim()
+
+// Punto de inyección de workbox-build: el literal `self.__WB_MANIFEST` se
+// sustituye por el manifiesto de precache en el build (no refactorizar).
+precacheAndRoute(self.__WB_MANIFEST)
+cleanupOutdatedCaches()
+
+// App-shell offline para navegaciones (equivale a `navigateFallback:
+// 'index.html'` de generateSW). En dev NO se registra: el SW de desarrollo
+// no precachea index.html y esta ruta serviría un HTML congelado.
+if (!import.meta.env.DEV) {
+  registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html')))
+}
+
+// ---------------------------------------------------------------------------
+// Web Push (SPEC-PUSH §2)
+// Payload: {title, body, category, severity, url:"/alerts", tag}
+// ---------------------------------------------------------------------------
+
+interface PushPayload {
+  title?: string
+  body?: string
+  category?: string
+  severity?: string
+  url?: string
+  tag?: string
+}
+
+self.addEventListener('push', (event: PushEvent) => {
+  event.waitUntil(onPush(event))
+})
+
+async function onPush(event: PushEvent): Promise<void> {
+  let payload: PushPayload = {}
+  try {
+    if (event.data) payload = event.data.json() as PushPayload
+  } catch {
+    // Payload no-JSON: notificación genérica (nunca romper el handler)
+    payload = {}
+  }
+  await self.registration.showNotification(payload.title || 'NetPulse', {
+    body: payload.body ?? '',
+    icon: '/icon-192.png',
+    badge: '/icon-192.png',
+    // tag = dedup nativo del navegador (SPEC: tag = id del evento)
+    tag: payload.tag ?? 'netpulse-alert',
+    data: { url: payload.url ?? '/alerts' },
+  })
+}
+
+self.addEventListener('notificationclick', (event: NotificationEvent) => {
+  event.notification.close()
+  const url = (event.notification.data as { url?: string } | undefined)?.url ?? '/alerts'
+  event.waitUntil(focusOrOpen(url))
+})
+
+/** Foco a una ventana ya abierta de la app (navegándola a `url`) o abre una nueva. */
+async function focusOrOpen(url: string): Promise<void> {
+  const target = new URL(url, self.location.origin).pathname
+  const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
+  for (const client of windows) {
+    if (new URL(client.url).origin !== self.location.origin) continue
+    await client.focus()
+    if (new URL(client.url).pathname !== target) {
+      await client.navigate(target)
+    }
+    return
+  }
+  await self.clients.openWindow(target)
+}

+ 15 - 3
app/vite.config.ts

@@ -11,6 +11,11 @@ export default defineConfig({
   plugins: [
     react(),
     VitePWA({
+      // injectManifest: SW propio (src/sw.ts) con handlers Web Push;
+      // generateSW no permite handlers custom (SPEC-PUSH §2).
+      strategies: 'injectManifest',
+      srcDir: 'src',
+      filename: 'sw.ts',
       registerType: 'autoUpdate',
       includeAssets: ['logo.svg', 'apple-touch-icon.png', 'icon-192.png', 'icon-512.png'],
       manifest: {
@@ -28,10 +33,17 @@ export default defineConfig({
           { src: 'icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable any' },
         ],
       },
-      workbox: {
-        // App-shell precache; los datos son mock locales (siempre "frescos")
+      injectManifest: {
+        // App-shell precache (mismo glob que con generateSW: 16 entradas);
+        // el fallback de navegación vive ahora en src/sw.ts (NavigationRoute)
         globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],
-        navigateFallback: 'index.html',
+      },
+      // SW también en dev: permite probar el alta push en local (localhost
+      // es contexto seguro). La ruta de navegación offline se desactiva en
+      // dev dentro de src/sw.ts para no congelar el index.html.
+      devOptions: {
+        enabled: true,
+        type: 'module',
       },
     }),
   ],

+ 7 - 1
docs/AGENTE-OPENWRT.md

@@ -1,6 +1,12 @@
 # Fase 6 — Agente nativo OpenWrt (`netpulse-agent`)
 
-> Estado: **diseño propuesto** (pendiente de aprobación). No implementado.
+> Estado: **piloto implementado** (2026-08-02): ingesta `POST /api/ingest/agent`
+> + tokens por equipo + adapter live-agent con fallback SSH + binario
+> `agent/` (probe compartido, push con backoff, procd, install-agent.sh).
+> Medido: **5,8 MB arm64** (suelo realista con TLS/x509; el objetivo inicial
+> ≤ 3 MB no es alcanzable sin renunciar a HTTPS — cabe sobrado en MT6000/MT7981;
+> la variante `/tmp` cubre flashes justas). Pendiente incremento 2: netlink/
+> nl80211 nativo, eventos ubus, `.ipk`, medición en hardware real.
 > Base: auditoría del collector piloto (2026-08-02) y la decisión de tiers:
 > Tier 0 = SSH agentless (actual, obligatorio) · Tier 1 = `lldpd` ·
 > **Tier 2 = agente nativo opcional por equipo.**

+ 203 - 0
install-agent.sh

@@ -0,0 +1,203 @@
+#!/bin/sh
+# =============================================================================
+# NetPulse Agent — one-liner installer (OpenWrt, vía SSH desde esta máquina)
+#
+#   Instala el agente nativo netpulse-agent en un router/AP OpenWrt: copia el
+#   binario (arm64/armv7), escribe /etc/netpulse-agent.env (chmod 600) e
+#   instala el servicio procd (respawn) habilitado y arrancado.
+#
+# Uso (el token lo genera POST /api/agents y se muestra UNA sola vez):
+#   sh install-agent.sh --host 192.168.8.3 \
+#       --server http://192.168.8.1:3000 --slug patio --token <64-hex>
+#   sh install-agent.sh --host 192.168.8.3 --server ... --slug ... --token ... \
+#       --binary ./netpulse-agent          # binario local (sin descarga)
+#   sh install-agent.sh --host 192.168.8.3 --uninstall
+#
+# Opciones:
+#   --host X        IP/host del router (obligatorio)
+#   --server X      URL del servidor NetPulse (obligatoria salvo --uninstall)
+#   --slug X        slug del equipo en NetPulse (obligatorio salvo --uninstall)
+#   --token X       token del equipo (obligatorio salvo --uninstall)
+#   --ssh-user X    usuario SSH del router (default: root)
+#   --binary X      binario local a copiar (default: descarga de la release)
+#   --version X.Y.Z versión a descargar (default: latest)
+#   --tmp           instala el binario en /tmp (RAM) en vez de /usr/sbin:
+#                   para equipos con flash justa. OJO: /tmp se pierde al
+#                   reiniciar — tras un reboot hay que reejecutar este script
+#                   (variante documentada del SPEC; el .ipk llega en el incr. 2)
+#   --uninstall     detiene y elimina servicio, binario y config del router
+#
+# Requisitos: ssh/scp al router (OpenWrt con dropbear), curl o wget local.
+# =============================================================================
+set -eu
+
+GH_REPO="gnacho/netpulse"
+BIN_NAME="netpulse-agent"
+ENV_FILE="/etc/netpulse-agent.env"
+INIT_NAME="netpulse-agent"
+INIT_DST="/etc/init.d/$INIT_NAME"
+
+HOST=""; SERVER=""; SLUG=""; TOKEN=""; SSH_USER="root"; BINARY=""; VERSION=""; USE_TMP=0; UNINSTALL=0
+
+if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
+    C_G=$(printf '\033[32m'); C_R=$(printf '\033[31m'); C_Y=$(printf '\033[33m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
+else C_G=""; C_R=""; C_Y=""; C_B=""; C_0=""; fi
+info()  { printf '%s--%s %s\n' "$C_B" "$C_0" "$*"; }
+ok()    { printf '%s✓%s %s\n' "$C_G" "$C_0" "$*"; }
+warn()  { printf '%s!%s %s\n' "$C_Y" "$C_0" "$*" >&2; }
+fatal() { _c=$1; shift; printf '%s✗ %s%s\n' "$C_R" "$*" "$C_0" >&2; exit "$_c"; }
+
+usage() { sed -n '2,33p' "$0"; exit 0; }
+
+for arg in "$@"; do
+    case "$arg" in
+        --host=*)     HOST="${arg#*=}" ;;
+        --server=*)   SERVER="${arg#*=}" ;;
+        --slug=*)     SLUG="${arg#*=}" ;;
+        --token=*)    TOKEN="${arg#*=}" ;;
+        --ssh-user=*) SSH_USER="${arg#*=}" ;;
+        --binary=*)   BINARY="${arg#*=}" ;;
+        --version=*)  VERSION="${arg#*=}" ;;
+        --tmp)        USE_TMP=1 ;;
+        --uninstall)  UNINSTALL=1 ;;
+        -h|--help)    usage ;;
+        *) fatal 10 "opción desconocida: $arg (prueba --help)" ;;
+    esac
+done
+
+[ -n "$HOST" ] || fatal 11 "falta --host (IP del router)"
+SSH="$SSH_USER@$HOST"
+command -v ssh >/dev/null 2>&1 || fatal 12 "necesito ssh"
+command -v scp >/dev/null 2>&1 || fatal 12 "necesito scp"
+
+# --------------------------------------------------------------- uninstall --
+if [ "$UNINSTALL" -eq 1 ]; then
+    info "desinstalando $BIN_NAME de $SSH"
+    ssh "$SSH" "
+        $INIT_DST stop 2>/dev/null || true
+        $INIT_DST disable 2>/dev/null || true
+        rm -f $INIT_DST $ENV_FILE /usr/sbin/$BIN_NAME /tmp/$BIN_NAME
+    "
+    ok "$BIN_NAME desinstalado de $HOST"
+    exit 0
+fi
+
+[ -n "$SERVER" ] || fatal 11 "falta --server (URL de NetPulse)"
+[ -n "$SLUG" ]   || fatal 11 "falta --slug"
+[ -n "$TOKEN" ]  || fatal 11 "falta --token (se muestra una vez al crearlo: POST /api/agents)"
+SERVER="${SERVER%/}"
+
+ssh -o ConnectTimeout=8 -o BatchMode=yes "$SSH" true \
+    || fatal 13 "no hay SSH a $SSH (¿dropbear + clave autorizada?)"
+
+# ------------------------------------------------------------------ binario --
+BIN_DST="/usr/sbin/$BIN_NAME"
+[ "$USE_TMP" -eq 1 ] && BIN_DST="/tmp/$BIN_NAME"
+
+TMP=$(mktemp -d) || fatal 34 "mktemp falló"
+cleanup() { rm -rf "$TMP"; }
+trap cleanup EXIT INT TERM
+
+if [ -n "$BINARY" ]; then
+    [ -f "$BINARY" ] || fatal 30 "binario local no encontrado: $BINARY"
+    cp "$BINARY" "$TMP/$BIN_NAME"
+    info "usando binario local: $BINARY"
+else
+    ARCH=$(ssh "$SSH" uname -m) || fatal 31 "no pude detectar la arquitectura de $HOST"
+    case "$ARCH" in
+        aarch64|arm64) GOARCH=arm64 ;;
+        armv7l|armv7)  GOARCH=armv7 ;;
+        *) fatal 20 "arquitectura no soportada: $ARCH (release: arm64, armv7)" ;;
+    esac
+    if command -v curl >/dev/null 2>&1; then FETCH="curl -fsSL --retry 3 --connect-timeout 10"
+    elif command -v wget >/dev/null 2>&1; then FETCH="wget -q -O-"
+    else fatal 21 "necesito curl o wget"; fi
+    fetch_to() { $FETCH "$1" > "$2"; }
+    command -v sha256sum >/dev/null 2>&1 || fatal 21 "falta sha256sum"
+    if [ -z "$VERSION" ]; then
+        info "resolviendo última release"
+        VERSION=$($FETCH "https://api.github.com/repos/$GH_REPO/releases/latest" \
+            | grep '"tag_name"' | head -1 | cut -d'"' -f4) \
+            || fatal 31 "no pude resolver la última release; usa --version=X.Y.Z"
+    fi
+    VERSION_NORM=$(echo "$VERSION" | sed 's/^v//')
+    ASSET="${BIN_NAME}_${VERSION_NORM}_linux_${GOARCH}.tar.gz"
+    BASE_URL="https://github.com/$GH_REPO/releases/download/$VERSION"
+    info "descargando $ASSET"
+    fetch_to "$BASE_URL/$ASSET" "$TMP/$ASSET" || fatal 32 "descarga falló: $BASE_URL/$ASSET"
+    fetch_to "$BASE_URL/checksums.txt" "$TMP/checksums.txt" || fatal 32 "checksums.txt no está en $VERSION"
+    SUM_FILE=$(sha256sum "$TMP/$ASSET" | awk '{print $1}')
+    SUM_REF=$(grep "  $ASSET\$" "$TMP/checksums.txt" | awk '{print $1}')
+    [ -n "$SUM_REF" ] || fatal 33 "$ASSET no está en checksums.txt"
+    [ "$SUM_FILE" = "$SUM_REF" ] || fatal 33 "sha256 NO COINCIDE para $ASSET"
+    ok "sha256 verificado"
+    tar -xzf "$TMP/$ASSET" -C "$TMP"
+fi
+[ -s "$TMP/$BIN_NAME" ] || fatal 34 "no hay binario que instalar"
+
+# ------------------------------------------------------------------ install --
+info "copiando binario → $SSH:$BIN_DST"
+scp -q "$TMP/$BIN_NAME" "$SSH:$BIN_DST"
+ssh "$SSH" "chmod 0755 $BIN_DST"
+ok "binario en $BIN_DST"
+
+# Config (chmod 600: el token solo lo lee root)
+info "escribiendo $ENV_FILE (chmod 600)"
+ssh "$SSH" "cat > $ENV_FILE && chmod 600 $ENV_FILE" <<EOF
+# netpulse-agent — config (generado por install-agent.sh)
+NETPULSE_SERVER=$SERVER
+NETPULSE_SLUG=$SLUG
+NETPULSE_TOKEN=$TOKEN
+# NETPULSE_INTERVAL=15
+# NETPULSE_WAN_TARGET=1.1.1.1      # solo si este equipo es el gateway
+# NETPULSE_GW_TARGET=192.168.8.1   # ping al gateway (APs)
+# NETPULSE_INSECURE_TLS=1          # solo si el servidor usa cert autofirmado
+EOF
+ok "config escrita"
+
+# Servicio procd (respawn)
+info "instalando servicio procd"
+SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+if [ -f "$SCRIPT_DIR/agent/deploy/$INIT_NAME.init" ]; then
+    scp -q "$SCRIPT_DIR/agent/deploy/$INIT_NAME.init" "$SSH:$INIT_DST"
+else
+    # Instalación vía curl|sh (sin repo a mano): init embebido — es el MISMO
+    # contenido que agent/deploy/netpulse-agent.init (mantener ambos a la par).
+    ssh "$SSH" "cat > $INIT_DST" <<'INITEOF'
+#!/bin/sh /etc/rc.common
+# netpulse-agent — agente nativo NetPulse para OpenWrt (SPEC-AGENTE-PILOTO §2)
+START=99
+STOP=10
+USE_PROCD=1
+
+BIN=/usr/sbin/netpulse-agent
+[ -x "$BIN" ] || BIN=/tmp/netpulse-agent
+
+start_service() {
+    procd_open_instance netpulse-agent
+    procd_set_param command "$BIN"
+    procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
+    procd_set_param stdout 1
+    procd_set_param stderr 1
+    procd_set_param file /etc/netpulse-agent.env
+    procd_close_instance
+}
+INITEOF
+fi
+ssh "$SSH" "chmod 0755 $INIT_DST && $INIT_DST enable && $INIT_DST restart"
+ok "servicio $INIT_NAME habilitado y arrancado"
+
+sleep 2
+if ssh "$SSH" "logread -e $INIT_NAME" 2>/dev/null | tail -2 | grep -q .; then
+    info "últimas líneas de syslog:"
+    ssh "$SSH" "logread -e $INIT_NAME | tail -2" || true
+fi
+
+printf '\n%s================ %s instalado ================%s\n' "$C_G" "$BIN_NAME" "$C_0"
+printf 'Router:   %s (slug: %s)\n' "$HOST" "$SLUG"
+printf 'Binario:  %s%s\n' "$BIN_DST" "$( [ "$USE_TMP" -eq 1 ] && echo '  (variante /tmp: se pierde al reiniciar — reejecuta el instalador tras un reboot)' || true)"
+printf 'Config:   %s (chmod 600; edítalo y haz /etc/init.d/%s restart)\n' "$ENV_FILE" "$INIT_NAME"
+printf 'Servidor: %s\n' "$SERVER"
+printf 'Logs:     ssh %s logread -e %s\n' "$SSH" "$INIT_NAME"
+printf 'Verifica: GET %s/api/agents (last_seen + versión en unos 15 s)\n' "$SERVER"
+printf '%s================================================%s\n\n' "$C_G" "$C_0"

+ 64 - 0
server-go/cmd/gen-demo-canon/main.go

@@ -0,0 +1,64 @@
+// gen-demo-canon — genera app/src/data/demo-canon.json desde el canon Go
+// (SPEC-65 D65-1: la fuente de verdad única del demo es Go).
+//
+// Uso: go run ./cmd/gen-demo-canon [-out ruta.json]
+// Sin -out, resuelve <repo>/app/src/data/demo-canon.json localizando la raíz
+// del repo (directorio que contiene server-go/go.mod) desde el cwd.
+package main
+
+import (
+	"encoding/json"
+	"flag"
+	"fmt"
+	"os"
+	"path/filepath"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+func repoRoot() (string, error) {
+	dir, err := os.Getwd()
+	if err != nil {
+		return "", err
+	}
+	for {
+		if st, err := os.Stat(filepath.Join(dir, "server-go", "go.mod")); err == nil && !st.IsDir() {
+			return dir, nil
+		}
+		parent := filepath.Dir(dir)
+		if parent == dir {
+			return "", fmt.Errorf("no se encuentra la raíz del repo (server-go/go.mod) desde el cwd")
+		}
+		dir = parent
+	}
+}
+
+func main() {
+	out := flag.String("out", "", "ruta de salida (por defecto <repo>/app/src/data/demo-canon.json)")
+	flag.Parse()
+	path := *out
+	if path == "" {
+		root, err := repoRoot()
+		if err != nil {
+			fmt.Fprintln(os.Stderr, "gen-demo-canon:", err)
+			os.Exit(1)
+		}
+		path = filepath.Join(root, "app", "src", "data", "demo-canon.json")
+	}
+	canon := adapters.BuildDemoCanon()
+	b, err := json.MarshalIndent(canon, "", "  ")
+	if err != nil {
+		fmt.Fprintln(os.Stderr, "gen-demo-canon:", err)
+		os.Exit(1)
+	}
+	b = append(b, '\n')
+	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+		fmt.Fprintln(os.Stderr, "gen-demo-canon:", err)
+		os.Exit(1)
+	}
+	if err := os.WriteFile(path, b, 0o644); err != nil {
+		fmt.Fprintln(os.Stderr, "gen-demo-canon:", err)
+		os.Exit(1)
+	}
+	fmt.Printf("demo-canon: %d devices → %s (%d bytes)\n", len(canon.Devices), path, len(b))
+}

+ 36 - 3
server-go/cmd/netpulse/main.go

@@ -19,15 +19,18 @@ import (
 	"os"
 	"os/signal"
 	"path/filepath"
+	"strconv"
 	"syscall"
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 	"github.com/gnacho/netpulse/server-go/internal/poller"
+	"github.com/gnacho/netpulse/server-go/internal/push"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
@@ -77,19 +80,42 @@ func run() error {
 
 	// Adapter: DEMO_MODE=1 → demo (dataset canónico + random walk);
 	// live → sondeo real (SSH/ubus) de los routers configurados.
+	// Registry de agentes nativos (Fase 6): en live alimenta el adapter
+	// live-agent (Tier 2 con degrade a SSH); en demo solo registra pushes
+	// (last_seen/versión para GET /api/agents) sin tocar el dataset canónico.
+	agentTTL := adapters.AgentTTLDefault
+	if v := os.Getenv("NETPULSE_AGENT_TTL_S"); v != "" {
+		if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
+			agentTTL = time.Duration(sec) * time.Second
+		}
+	}
+	agentReg := adapters.NewAgentRegistry(agentTTL)
 	var adapter adapters.Snapshotter
 	if cfg.DemoMode {
-		adapter = adapters.NewDemo()
+		adapter = adapters.NewDemo(alerts.New(dbHandle, nil))
 	} else {
 		pool, err := adapters.NewSSHPool(cfg.SSHKeyPath)
 		if err != nil {
 			log.Printf("[netpulse] aviso: pool SSH no disponible (%v); sirviendo dataset demo", err)
-			adapter = adapters.NewDemo()
+			adapter = adapters.NewDemo(alerts.New(dbHandle, nil))
 		} else {
-			adapter = adapters.NewLive(cfg, dbHandle, routers, pool)
+			live := adapters.NewLive(cfg, dbHandle, routers, pool)
+			live.SetAgents(agentReg)
+			adapter = live
 		}
 	}
 
+	// Web Push (Bloque C): par VAPID en kv (primer arranque) + Notifier
+	// asíncrono conectado al motor de alertas del adapter (solo eventos
+	// urgentes que pasan config). Si falla, el resto del servidor sigue.
+	var pushNotifier *push.Notifier
+	if pub, priv, err := push.EnsureVAPIDKeys(dbHandle); err != nil {
+		log.Printf("[netpulse] aviso: Web Push desactivado (%v)", err)
+	} else {
+		pushNotifier = push.NewNotifier(dbHandle, pub, priv)
+		adapter.AlertsEngine().SetNotifier(pushNotifier)
+	}
+
 	// Dependencia sse↔poller resuelta con un holder (como index.js:40-45).
 	var p *poller.Poller
 	hub := sse.NewHub(dbHandle, cfg.MaxSSEClients, func() any {
@@ -118,9 +144,11 @@ func run() error {
 		Secret:  secret,
 		Static:  static,
 		Updater: upd,
+		Agents:  agentReg,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},
+		PollNow: p.PollNow,
 		Started: time.Now(),
 	})
 
@@ -160,6 +188,11 @@ func run() error {
 		upd.Stop()
 		hub.NotifyShutdown()
 		_ = adapter.Close()
+		// Tras parar poller y adapter ya nadie emite alertas: se puede
+		// cerrar el worker de push sin riesgo de Notify sobre canal cerrado.
+		if pushNotifier != nil {
+			pushNotifier.Close()
+		}
 		// Salvavidas de 3 s: salir igualmente aunque el server no cierre.
 		lifeline := time.AfterFunc(3*time.Second, func() {
 			_ = dbHandle.Close()

+ 7 - 0
server-go/go.mod

@@ -3,13 +3,20 @@ module github.com/gnacho/netpulse/server-go
 go 1.25.0
 
 require (
+	github.com/SherClockHolmes/webpush-go v1.4.0
+	github.com/gnacho/netpulse/agent v0.0.0
 	golang.org/x/crypto v0.54.0
 	golang.org/x/text v0.40.0
 	modernc.org/sqlite v1.55.0
 )
 
+// Módulo hermano en el mismo repo: sondas/parseo compartido con el agente
+// nativo (SPEC-AGENTE-PILOTO §2). Solo stdlib — no arrastra dependencias.
+replace github.com/gnacho/netpulse/agent => ../agent
+
 require (
 	github.com/dustin/go-humanize v1.0.1 // indirect
+	github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
 	github.com/google/uuid v1.6.0 // indirect
 	github.com/mattn/go-isatty v0.0.20 // indirect
 	github.com/ncruces/go-strftime v1.0.0 // indirect

+ 71 - 2
server-go/go.sum

@@ -1,5 +1,10 @@
+github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s=
+github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA=
 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
+github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
 github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
 github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -12,20 +17,84 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF
 github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
+golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
+golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
 golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
 golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
 golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
 golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
-golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
-golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
+golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
+golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
+golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
+golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
 golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
 golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
 golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
+golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
+golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
+golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
+golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
+golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
 golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
 golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
+golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
 golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
 golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
 modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
 modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
 modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=

+ 36 - 9
server-go/internal/adapters/adapters_test.go

@@ -29,7 +29,7 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	if *flint.CPU != 23 || *flint.RAM != 41 || *flint.Temp != 54 {
 		t.Fatalf("flint2 cpu/ram/temp: %v/%v/%v", *flint.CPU, *flint.RAM, *flint.Temp)
 	}
-	if flint.Clients != 33 || flint.Health != 98 {
+	if flint.Clients != 26 || flint.Health != 98 {
 		t.Fatalf("flint2 clients/health: %v/%v", flint.Clients, flint.Health)
 	}
 	// WAN
@@ -51,10 +51,13 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	if p0.ID != "pixel-8-pro" || !p0.Active || p0.Rx != "1,2 GB" || p0.Tx != "214 MB" || p0.LastHandshake != "hace 38 s" {
 		t.Fatalf("peer0: %+v", p0)
 	}
-	// DeviceTotals
-	if ov.DeviceTotals != (DeviceTotals{Total: 66, Online: 58, KnownOffline: 8, NewToday: 3}) {
+	// DeviceTotals (D5: derivados del dataset reconciliado — 65 IDs únicos)
+	if ov.DeviceTotals != (DeviceTotals{Total: 65, Online: 59, KnownOffline: 6, NewToday: 3}) {
 		t.Fatalf("deviceTotals: %+v", ov.DeviceTotals)
 	}
+	if ov.Adguard.ClientsTotal != 65 {
+		t.Fatalf("adguard clientsTotal: %v", ov.Adguard.ClientsTotal)
+	}
 	// Health
 	if ov.Health.Score != 92 || ov.Health.Label != "Excelente" || len(ov.Health.Breakdown) != 3 {
 		t.Fatalf("health: %+v", ov.Health)
@@ -69,10 +72,10 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	}
 }
 
-func TestDemoDevices66YTop(t *testing.T) {
+func TestDemoDevices65YTop(t *testing.T) {
 	d := NewDemo()
 	devs := d.GetDevices(context.Background())
-	if len(devs) != 66 {
+	if len(devs) != 65 {
 		t.Fatalf("devices: %d", len(devs))
 	}
 	offline := 0
@@ -84,7 +87,7 @@ func TestDemoDevices66YTop(t *testing.T) {
 			t.Fatalf("sparkline offline debe ser [] no null: %s", dev.ID)
 		}
 	}
-	if offline != 8 {
+	if offline != 6 {
 		t.Fatalf("offline: %d", offline)
 	}
 	ov, _ := d.GetOverview(context.Background())
@@ -509,11 +512,20 @@ func TestDemoNodoManagedCanon(t *testing.T) {
 		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
+	// SPEC-CANON D1: el nodo managed lleva la chassis-MAC del switch.
+	if managed.Mac != "28:C6:8E:1D:90:44" {
+		t.Fatalf("mac del nodo managed: %q", managed.Mac)
+	}
+	// SPEC-CANON D1/D2: el GS308E existe A LA VEZ como Device (con lldp,
+	// attachTo al router y port de uplink — NUNCA a su propio nodo) y sus
+	// 3 clientes cuelgan del nodo.
 	fan := 0
-	for _, dev := range d.GetDevices(context.Background()) {
+	var sw *Device
+	devices := d.GetDevices(context.Background())
+	for i := range devices {
+		dev := &devices[i]
 		if dev.ID == "switch-netgear" {
-			t.Fatal("switch-netgear no debe existir como Device (es el nodo managed)")
+			sw = dev
 		}
 		if dev.AttachTo == "dist-living-lan3" {
 			fan++
@@ -525,6 +537,21 @@ func TestDemoNodoManagedCanon(t *testing.T) {
 	if fan != 3 {
 		t.Fatalf("abanico del managed: %d (esperaba 3)", fan)
 	}
+	if sw == nil {
+		t.Fatal("switch-netgear debe existir como Device (SPEC-CANON D1)")
+	}
+	if sw.Type != "switch" || !sw.Online || sw.IP != "192.168.8.13" {
+		t.Fatalf("GS308E device: %+v", sw)
+	}
+	if sw.Lldp == nil || sw.Lldp.Chassis != "GS308E" {
+		t.Fatalf("GS308E device sin lldp: %+v", sw.Lldp)
+	}
+	if sw.AttachTo == "dist-living-lan3" {
+		t.Fatalf("el switch NO cuelga de su propio nodo: %+v", sw)
+	}
+	if sw.AttachTo != "living" || sw.Port != "lan3" {
+		t.Fatalf("GS308E attachTo/port de uplink: %+v", sw)
+	}
 }
 
 // Canon demo de Router.Lldp (Fase 5, ítem 4 de C2): los AP cableados

+ 264 - 0
server-go/internal/adapters/agent.go

@@ -0,0 +1,264 @@
+// agent.go — Adapter live-agent (SPEC-AGENTE-PILOTO §1): el último payload
+// empujado por el agente nativo a POST /api/ingest/agent ES el estado actual
+// del router. Si el agente deja de empujar (> AgentTTL, ~3 intervalos), el
+// router degrada a Tier 0 (SSH) con alerta category system urgent=false
+// ("Agente caído en <nombre> — volviendo a SSH"); al volver el agente se
+// retoma solo y se emite la alerta ok de recuperación.
+//
+// El registry guarda los payloads TAL CUAL llegan (shapes de agent/probe) y
+// Live los convierte a routerPolled con el mismo anti-parpadeo del pipeline
+// SSH (snapshot → SSE → persistencia sin cambios).
+package adapters
+
+import (
+	"fmt"
+	"math"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// AgentTTLDefault: 3 intervalos de push de 15 s (default del agente) + margen.
+const AgentTTLDefault = 90 * time.Second
+
+// AgentState es el último push conocido de un agente.
+type AgentState struct {
+	Payload  *probe.Payload
+	LastSeen time.Time
+	Version  string
+}
+
+// AgentRegistry guarda el último payload por slug (thread-safe: lo escribe el
+// handler de ingesta y lo lee el sondeo live).
+type AgentRegistry struct {
+	mu     sync.Mutex
+	ttl    time.Duration
+	now    func() time.Time
+	states map[string]*AgentState
+}
+
+// NewAgentRegistry crea el registry con el TTL de expiración dado
+// (<= 0 → AgentTTLDefault).
+func NewAgentRegistry(ttl time.Duration) *AgentRegistry {
+	if ttl <= 0 {
+		ttl = AgentTTLDefault
+	}
+	return &AgentRegistry{ttl: ttl, now: time.Now, states: map[string]*AgentState{}}
+}
+
+// SetClock sustituye el reloj (solo tests).
+func (r *AgentRegistry) SetClock(f func() time.Time) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	r.now = f
+}
+
+// Ingest registra un push (último payload = estado actual del router).
+func (r *AgentRegistry) Ingest(p *probe.Payload) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	r.states[p.Router] = &AgentState{Payload: p, LastSeen: r.now(), Version: p.Version}
+}
+
+// Info devuelve last_seen + versión para GET /api/agents (sin exponer el payload).
+func (r *AgentRegistry) Info(slug string) (lastSeen time.Time, version string, ok bool) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, found := r.states[slug]
+	if !found {
+		return time.Time{}, "", false
+	}
+	return st.LastSeen, st.Version, true
+}
+
+// Fresh devuelve el último payload si está dentro del TTL.
+func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, ok := r.states[slug]
+	if !ok || r.now().Sub(st.LastSeen) > r.ttl {
+		return nil, false
+	}
+	return st.Payload, true
+}
+
+// Expired reporta si el slug tiene agente conocido pero su último push
+// expiró (candidato a degradar a SSH con aviso).
+func (r *AgentRegistry) Expired(slug string) bool {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	st, ok := r.states[slug]
+	return ok && r.now().Sub(st.LastSeen) > r.ttl
+}
+
+// Forget borra el estado del slug (revocación de token).
+func (r *AgentRegistry) Forget(slug string) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	delete(r.states, slug)
+}
+
+// ---------------------------------------------------------------------------
+// Integración con Live
+// ---------------------------------------------------------------------------
+
+// SetAgents enchufa el registry de agentes al adapter live (nil = sin
+// soporte de agentes; todo va por SSH como antes).
+func (l *Live) SetAgents(r *AgentRegistry) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	l.agents = r
+}
+
+// agentName: nombre para las alertas (cfg.Name o Host como el resto).
+func agentName(cfg RouterConfig) string {
+	if cfg.Name != "" {
+		return cfg.Name
+	}
+	return cfg.Host
+}
+
+// pollRouterAgent: si el agente del router está fresco, construye el sondeo
+// desde su payload (Tier 2); si expiró, emite UNA vez la alerta de caída y
+// devuelve (nil, nil) para que el caller siga por SSH (Tier 0).
+// (fresh, polled) — fresh=false ⇒ el caller hace el sondeo SSH normal.
+func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
+	l.mu.Lock()
+	reg := l.agents
+	l.mu.Unlock()
+	if reg == nil {
+		return false, nil
+	}
+	if p, ok := reg.Fresh(cfg.ID); ok {
+		// Recuperación: estaba caído y volvió a empujar → alerta ok.
+		l.mu.Lock()
+		if l.agentDown[cfg.ID] {
+			l.agentDown[cfg.ID] = false
+			name := agentName(cfg)
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-agent-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false,
+				Severity:    "ok",
+				Title:       "Agente recuperado en " + name,
+				Description: fmt.Sprintf("El agente de %s vuelve a empujar datos — sondeo nativo reanudado", name),
+				Time:        "ahora mismo", RouterID: cfg.ID,
+			})
+		}
+		l.mu.Unlock()
+		return true, l.polledFromAgent(cfg, p)
+	}
+	if reg.Expired(cfg.ID) {
+		l.mu.Lock()
+		if !l.agentDown[cfg.ID] {
+			l.agentDown[cfg.ID] = true
+			name := agentName(cfg)
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false,
+				Severity:    "warn",
+				Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),
+				Description: fmt.Sprintf("Sin datos del agente de %s — sondeo SSH reanudado", name),
+				Time:        "ahora mismo", RouterID: cfg.ID,
+			})
+		}
+		l.mu.Unlock()
+	}
+	return false, nil
+}
+
+// polledFromAgent convierte el payload del agente en el routerPolled del
+// pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
+// que pollRouter: sección ausente en el payload = sonda fallida → conserva
+// el último dato bueno cacheado.
+func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled {
+	l.mu.Lock()
+	cached := l.extrasCache[cfg.ID]
+	l.mu.Unlock()
+
+	out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}}
+	sysInfo := &SysInfo{}
+	ramPct := 0
+
+	if sd := p.Data.System; sd != nil {
+		if sd.SysInfo != nil {
+			sysInfo = sd.SysInfo
+		}
+		out.board = sd.Board
+		if sd.Board != nil {
+			l.mu.Lock()
+			l.boardCache[cfg.ID] = sd.Board
+			l.mu.Unlock()
+		}
+		if sd.CPU != nil {
+			out.cpu = *sd.CPU
+		}
+		if sd.Temp != nil {
+			out.temp = *sd.Temp
+		}
+		out.net = &NetDevBps{RxBps: sd.RxBps, TxBps: sd.TxBps}
+		out.latencyMs = sd.LatencyMs
+		out.lossPct = sd.LossPct
+		out.backhaul = sd.Backhaul
+		out.brMac = sd.BridgeMAC
+	}
+	mem := sysInfo.Memory
+	if mem.Total > 0 {
+		avail := mem.Available
+		if avail == 0 {
+			avail = mem.Free + mem.Buffered
+		}
+		ramPct = int(math.Round((mem.Total - avail) / mem.Total * 100))
+	}
+	out.sysInfo = sysInfo
+	out.ram = ramPct
+	out.uptimeSec = sysInfo.Uptime
+
+	// Secciones con anti-parpadeo (nil en el payload = sonda fallida).
+	if wd := p.Data.Wireless; wd != nil {
+		if wd.Clients != nil {
+			out.wireless = wd.Clients
+		}
+		if len(wd.Radios) > 0 {
+			out.radios = radiosToAdapter(wd.Radios)
+		}
+	}
+	if dd := p.Data.DHCP; dd != nil {
+		out.leases = dd.Leases
+	}
+	if fd := p.Data.FDB; fd != nil {
+		if fd.MACs != nil {
+			out.fdb = fd.MACs
+		}
+		if len(fd.Ports) > 0 {
+			out.ports = ethPortsToAdapter(fd.Ports)
+		}
+	}
+
+	if cached == nil {
+		cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
+			wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
+	}
+	if out.ports == nil {
+		out.ports = cached.ports
+	}
+	if out.radios == nil {
+		out.radios = cached.radios
+	}
+	if out.wireless == nil {
+		out.wireless = cached.wireless
+	}
+	if out.fdb == nil {
+		out.fdb = cached.fdb
+	}
+	l.mu.Lock()
+	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
+		wireless: out.wireless, fdb: out.fdb}
+	l.mu.Unlock()
+
+	if out.leases == nil {
+		out.leases = []DhcpLease{}
+	}
+	return out
+}

+ 206 - 0
server-go/internal/adapters/agent_live_test.go

@@ -0,0 +1,206 @@
+// agent_live_test.go — Adapter live-agent (SPEC-AGENTE-PILOTO §1): payload
+// fresco = estado del router sin SSH; expiración → degrade SSH + alerta
+// category system urgent=false; vuelta del agente → alerta ok de recuperación.
+package adapters
+
+import (
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+)
+
+func f64(v float64) *float64 { return &v }
+func i(v int) *int           { return &v }
+
+// testPayload es un push completo del AP "patio" (shapes de agent/probe).
+func testPayload() *probe.Payload {
+	pl := &probe.Payload{Router: "patio", Ts: time.Now().Unix(), Version: "0.1.0"}
+	sys := &probe.SysInfo{Uptime: 90061}
+	sys.Memory.Total = 256e6
+	sys.Memory.Available = 128e6
+	pl.Data.System = &probe.SystemData{
+		SysInfo:   sys,
+		Board:     &probe.BoardInfo{Model: "TP-Link EAP225", Hostname: "patio"},
+		CPU:       i(12), Temp: i(43),
+		RxBps: f64(1e6), TxBps: f64(2e6),
+		LatencyMs: f64(3), Backhaul: "cable",
+		BridgeMAC: "94:83:C4:00:00:09",
+	}
+	pl.Data.Wireless = &probe.WirelessData{
+		Clients: map[string]probe.WirelessClient{
+			"EC:71:DB:44:12:8A": {SignalDbm: -55, Band: "2.4 GHz"},
+		},
+		Radios: []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20, PowerDbm: 20, Clients: 1}},
+	}
+	pl.Data.DHCP = &probe.DHCPData{Leases: []probe.DhcpLease{
+		{MAC: "EC:71:DB:44:12:8A", IP: "192.168.8.71", Hostname: "movil"},
+	}}
+	pl.Data.FDB = &probe.FDBData{
+		MACs:  map[string]string{"EC:71:DB:44:12:8A": "lan1"},
+		Ports: []probe.EthPort{{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps"}},
+	}
+	return pl
+}
+
+func TestAgentRegistry(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	if _, ok := reg.Fresh("patio"); ok {
+		t.Fatal("sin estado no debería haber payload fresco")
+	}
+	reg.Ingest(testPayload())
+	p, ok := reg.Fresh("patio")
+	if !ok || p.Version != "0.1.0" {
+		t.Fatalf("payload fresco esperado: %v %v", ok, p)
+	}
+	seen, ver, ok := reg.Info("patio")
+	if !ok || ver != "0.1.0" || !seen.Equal(now) {
+		t.Fatalf("Info: %v %q %v", seen, ver, ok)
+	}
+	now = now.Add(91 * time.Second)
+	if _, ok := reg.Fresh("patio"); ok {
+		t.Fatal("tras el TTL no debería estar fresco")
+	}
+	if !reg.Expired("patio") {
+		t.Fatal("tras el TTL debería estar expirado")
+	}
+	reg.Forget("patio")
+	if reg.Expired("patio") {
+		t.Fatal("Forget borra el estado")
+	}
+}
+
+// newLiveAgentTest: Live con pool SSH real (clave efímera) apuntando a un
+// puerto cerrado — el fallback SSH falla al instante (connection refused).
+func newLiveAgentTest(t *testing.T, reg *AgentRegistry) *Live {
+	t.Helper()
+	keyPath := t.TempDir() + "/id_ed25519"
+	if err := sshkey.EnsureKeypair(keyPath); err != nil {
+		t.Fatalf("ssh key: %v", err)
+	}
+	pool, err := NewSSHPool(keyPath)
+	if err != nil {
+		t.Fatalf("pool: %v", err)
+	}
+	t.Cleanup(func() { pool.Close() })
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "patio", Name: "Patio", Host: "127.0.0.1", Type: "openwrt"},
+	}, pool)
+	l.SetAgents(reg)
+	return l
+}
+
+func findAlert(list []AlertEvent, titlePart string) *AlertEvent {
+	for i, a := range list {
+		if strings.Contains(a.Title, titlePart) {
+			return &list[i]
+		}
+	}
+	return nil
+}
+
+func TestLiveAgentFreshSkipsSSH(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	l := newLiveAgentTest(t, reg)
+	reg.Ingest(testPayload())
+
+	p, err := l.pollRouter(t.Context(), RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1"})
+	if err != nil {
+		t.Fatalf("pollRouter con agente fresco: %v", err)
+	}
+	// Datos del payload, no de SSH (el host es inalcanzable por SSH)
+	if p.cpu != 12 || p.temp != 43 || p.ram != 50 || p.uptimeSec != 90061 {
+		t.Fatalf("system: cpu=%d temp=%d ram=%d uptime=%v", p.cpu, p.temp, p.ram, p.uptimeSec)
+	}
+	if p.net == nil || p.net.RxBps == nil || *p.net.RxBps != 1e6 {
+		t.Fatalf("net: %+v", p.net)
+	}
+	if len(p.leases) != 1 || p.leases[0].Hostname != "movil" {
+		t.Fatalf("leases: %+v", p.leases)
+	}
+	if p.wireless["EC:71:DB:44:12:8A"].SignalDbm != -55 {
+		t.Fatalf("wireless: %+v", p.wireless)
+	}
+	if p.fdb["EC:71:DB:44:12:8A"] != "lan1" || len(p.ports) != 1 || p.ports[0].Speed != "1 Gbps" {
+		t.Fatalf("fdb/ports: %+v %+v", p.fdb, p.ports)
+	}
+	if len(p.radios) != 1 || p.radios[0].Name != "2.4 GHz" || p.brMac != "94:83:C4:00:00:09" || p.backhaul != "cable" {
+		t.Fatalf("radios/brMac/backhaul: %+v %q %q", p.radios, p.brMac, p.backhaul)
+	}
+	if p.board == nil || p.board.Model != "TP-Link EAP225" || p.latencyMs == nil || *p.latencyMs != 3 {
+		t.Fatalf("board/latency: %+v %v", p.board, p.latencyMs)
+	}
+}
+
+func TestLiveAgentFallbackAndRecovery(t *testing.T) {
+	reg := NewAgentRegistry(50 * time.Millisecond)
+	l := newLiveAgentTest(t, reg)
+	cfg := RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1"}
+	reg.Ingest(testPayload())
+
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente fresco: %v", err)
+	}
+	// Expira el agente → degrade a SSH (falla: host inalcanzable) + alerta
+	time.Sleep(60 * time.Millisecond)
+	if _, err := l.pollRouter(t.Context(), cfg); err == nil {
+		t.Fatal("con agente expirado debería intentar SSH y fallar (127.0.0.1 sin sshd)")
+	}
+	down := findAlert(l.engine.List(), "Agente caído en Patio")
+	if down == nil {
+		t.Fatalf("alerta de caída esperada: %+v", l.engine.List())
+	}
+	if down.Category != alerts.CatSystem || down.Urgent || !strings.Contains(down.Title, "volviendo a SSH") {
+		t.Fatalf("alerta caída: %+v", down)
+	}
+	// La alerta se emite UNA vez (no cada tick)
+	if _, err := l.pollRouter(t.Context(), cfg); err == nil {
+		t.Fatal("SSH sigue fallando")
+	}
+	if n := 0; true {
+		for _, a := range l.engine.List() {
+			if strings.Contains(a.Title, "Agente caído") {
+				n++
+			}
+		}
+		if n != 1 {
+			t.Fatalf("alerta de caída duplicada: %d", n)
+		}
+	}
+	// Vuelve el agente → se retoma sin SSH y hay alerta ok de recuperación
+	reg.Ingest(testPayload())
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente recuperado: %v", err)
+	}
+	ok := findAlert(l.engine.List(), "Agente recuperado en Patio")
+	if ok == nil || ok.Category != alerts.CatSystem || ok.Urgent || ok.Severity != "ok" {
+		t.Fatalf("alerta recuperación: %+v", ok)
+	}
+}
+
+func TestLiveAgentAntiFlicker(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	l := newLiveAgentTest(t, reg)
+	cfg := RouterConfig{ID: "patio", Name: "Patio", Host: "127.0.0.1"}
+	reg.Ingest(testPayload())
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("primer push: %v", err)
+	}
+	// Segundo push con secciones fallidas (nil) → conserva el último dato bueno
+	p2 := &probe.Payload{Router: "patio", Ts: time.Now().Unix(), Version: "0.1.0"}
+	p2.Data.System = testPayload().Data.System
+	reg.Ingest(p2)
+	p, err := l.pollRouter(t.Context(), cfg)
+	if err != nil {
+		t.Fatalf("segundo push: %v", err)
+	}
+	if len(p.wireless) != 1 || len(p.radios) != 1 || len(p.ports) != 1 || len(p.fdb) != 1 {
+		t.Fatalf("anti-parpadeo: %+v %+v %+v %+v", p.wireless, p.radios, p.ports, p.fdb)
+	}
+}

+ 193 - 0
server-go/internal/adapters/alerts_live_test.go

@@ -0,0 +1,193 @@
+// alerts_live_test.go — taxonomía SPEC-ALERTAS §1 en la demo y en los
+// eventos live nuevos (router recuperado, WAN caído, desconocido se conecta)
+// y migración de los 4 sitios históricos al motor.
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// Las 5 alertas canon pasan por el motor con config default y sobreviven
+// (SPEC-ALERTAS §5), con Category/Urgent/Ts correctos.
+func TestDemoCanonAlertsThroughEngine(t *testing.T) {
+	d := NewDemo()
+	list := d.GetAlerts(t.Context())
+	if len(list) != 5 {
+		t.Fatalf("canon: %d alertas, esperaba 5", len(list))
+	}
+	want := map[string]struct {
+		cat    string
+		urgent bool
+		sev    string
+		read   bool
+	}{
+		"alert-temp-patio":       {alerts.CatRouter, true, "warn", false},
+		"alert-firmware-estudio": {alerts.CatSystem, false, "warn", false},
+		"alert-nuevo-tab":        {alerts.CatClients, false, "info", true},
+		"alert-handshake-wg":     {alerts.CatVPN, false, "info", true},
+		"alert-backup-adguard":   {alerts.CatSystem, false, "ok", true},
+	}
+	for _, a := range list {
+		w, ok := want[a.ID]
+		if !ok {
+			t.Fatalf("alerta inesperada: %s", a.ID)
+		}
+		if a.Category != w.cat || a.Urgent != w.urgent || a.Severity != w.sev {
+			t.Fatalf("%s taxonomía: (%s,%v,%s), esperaba (%s,%v,%s)",
+				a.ID, a.Category, a.Urgent, a.Severity, w.cat, w.urgent, w.sev)
+		}
+		if a.Read != w.read {
+			t.Fatalf("%s read: %v, esperaba %v", a.ID, a.Read, w.read)
+		}
+		if a.Ts <= 0 {
+			t.Fatalf("%s sin Ts", a.ID)
+		}
+		if a.Time == "" {
+			t.Fatalf("%s sin Time legado", a.ID)
+		}
+	}
+	// El orden canónico se conserva (seed en inverso + prepend).
+	order := []string{"alert-temp-patio", "alert-firmware-estudio", "alert-nuevo-tab", "alert-handshake-wg", "alert-backup-adguard"}
+	for i, id := range order {
+		if list[i].ID != id {
+			t.Fatalf("orden canon: posición %d = %s, esperaba %s", i, list[i].ID, id)
+		}
+	}
+	// UnreadAlerts del overview = no leídas del motor (2 en el canon).
+	ov, err := d.GetOverview(t.Context())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if ov.UnreadAlerts != 2 {
+		t.Fatalf("unreadAlerts: %d, esperaba 2", ov.UnreadAlerts)
+	}
+}
+
+// liveTestLive: Live mínimo con motor en memoria para probar las emisiones.
+func liveTestLive() *Live {
+	return &Live{
+		engine:     alerts.New(nil, nil),
+		lastStatus: map[string]string{},
+		wanDown:    map[string]int{},
+		onlineMacs: map[string]bool{},
+	}
+}
+
+func TestLiveRouterRecoveredTaxonomy(t *testing.T) {
+	l := liveTestLive()
+	// Con el default router:urgent el evento (urgent=false) se filtra EN
+	// CREACIÓN (semántica SPEC §2): es lo esperado.
+	l.mu.Lock()
+	l.emitRouterRecovered("patio", "Patio")
+	l.mu.Unlock()
+	if len(l.engine.List()) != 0 {
+		t.Fatal("con router:urgent, 'recuperado' (no urgente) debía filtrarse")
+	}
+	// Con router:all pasa, con la taxonomía exacta del SPEC §1.
+	if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
+		t.Fatal(err)
+	}
+	l.mu.Lock()
+	l.emitRouterRecovered("patio", "Patio")
+	l.mu.Unlock()
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("alertas: %d", len(list))
+	}
+	a := list[0]
+	if a.Category != alerts.CatRouter || a.Urgent || a.Severity != "ok" {
+		t.Fatalf("recuperado: (%s,%v,%s), esperaba (router,false,ok)", a.Category, a.Urgent, a.Severity)
+	}
+	if a.RouterID != "patio" || a.Ts == 0 {
+		t.Fatalf("recuperado: %+v", a)
+	}
+}
+
+func TestLiveWanDownTaxonomyAndDebounce(t *testing.T) {
+	l := liveTestLive()
+	cfg := &RouterConfig{ID: "flint2", Name: "Flint 2", Host: "192.168.8.1"}
+	loss0, loss100 := 0.0, 100.0
+	// 1er sondeo con 100 % pérdida: aún no alerta (debounce 2 como offline)
+	l.mu.Lock()
+	l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
+	l.mu.Unlock()
+	if len(l.engine.List()) != 0 {
+		t.Fatal("WAN down no debía alertar al primer sondeo")
+	}
+	// 2º seguido: alerta internet/urgent/critical
+	l.mu.Lock()
+	l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
+	l.mu.Unlock()
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("WAN down: %d alertas", len(list))
+	}
+	a := list[0]
+	if a.Category != alerts.CatInternet || !a.Urgent || a.Severity != "critical" {
+		t.Fatalf("WAN down: (%s,%v,%s), esperaba (internet,true,critical)", a.Category, a.Urgent, a.Severity)
+	}
+	// 3er sondeo: no re-alerta (estado ya "down"); el dedup también lo evita
+	l.mu.Lock()
+	l.trackWanDown(cfg, &routerPolled{lossPct: &loss100})
+	l.mu.Unlock()
+	if len(l.engine.List()) != 1 {
+		t.Fatal("WAN down re-alertó sin recuperación")
+	}
+	// Recuperación: pérdida < 100 resetea (próxima caída vuelve a alertar)
+	l.mu.Lock()
+	l.trackWanDown(cfg, &routerPolled{lossPct: &loss0})
+	l.mu.Unlock()
+	if l.lastStatus["flint2:wan"] != "up" || l.wanDown["flint2"] != 0 {
+		t.Fatalf("reset WAN: %v", l.lastStatus)
+	}
+}
+
+func TestLiveUnknownDeviceTaxonomy(t *testing.T) {
+	l := liveTestLive()
+	l.mu.Lock()
+	l.emitUnknownDevice(Device{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", RouterID: "living", Online: true})
+	l.mu.Unlock()
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("desconocido: %d alertas", len(list))
+	}
+	a := list[0]
+	if a.Category != alerts.CatClients || !a.Urgent || a.Severity != "warn" {
+		t.Fatalf("desconocido: (%s,%v,%s), esperaba (clients,true,warn)", a.Category, a.Urgent, a.Severity)
+	}
+}
+
+func TestLiveTrackUnknownDevices(t *testing.T) {
+	l := liveTestLive()
+	unknown := Device{MAC: "11:22:33:44:55:66", Name: "11:22:33:44:55:66", RouterID: "living", Online: true}
+	named := Device{MAC: "77:88:99:AA:BB:CC", Name: "Galaxy Tab", RouterID: "living", Online: true}
+
+	// Primer ciclo: siembra de base, NUNCA alerta (anti-avalancha de arranque)
+	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("primer ciclo no debía alertar")
+	}
+	// Sigue online: no re-alerta
+	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("reconexión sin caída no debía alertar")
+	}
+	// Se desconecta y vuelve: AHORA sí alerta (sin nombre → desconocido)
+	l.trackUnknownDevices([]Device{named})
+	l.trackUnknownDevices([]Device{unknown, named})
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("reconexión de desconocido: %d alertas", len(list))
+	}
+	if list[0].Category != alerts.CatClients || !list[0].Urgent {
+		t.Fatalf("taxonomía: %+v", list[0])
+	}
+	// El dispositivo CON nombre nunca alerta aunque se reconecte
+	l.trackUnknownDevices([]Device{unknown})
+	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 1 {
+		t.Fatal("dispositivo conocido no debía alertar")
+	}
+}

+ 63 - 34
server-go/internal/adapters/demo.go

@@ -3,6 +3,7 @@
 //   - cpu/ram/temp ±2 máx (acotados 2-95 / 10-92 / 30-82)
 //   - tráfico ±5 %, latencia WAN acotada 6–11 ms
 //   - AdGuard siempre creciente, bytes WG crecientes solo en peers activos
+//
 // El PRIMER snapshot (antes del primer Tick) es exactamente el canon.
 package adapters
 
@@ -13,6 +14,8 @@ import (
 	"sort"
 	"sync"
 	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
 
 const demoGatewayID = "flint2"
@@ -32,7 +35,7 @@ type Demo struct {
 	wan       WAN
 	adguard   AdGuardStats
 	wireguard WireGuardStats
-	alerts    []AlertEvent
+	engine    *alerts.Engine
 	devices   []Device
 	extras    map[string]*demoExtras
 	wgBytes   map[string]*wgByteCounter
@@ -44,18 +47,27 @@ type Demo struct {
 }
 
 // NewDemo crea el adapter demo con una copia fresca del dataset canónico.
-func NewDemo() *Demo {
+// Las 5 alertas canónicas entran en el motor vía Seed (SPEC-ALERTAS §5:
+// deben sobrevivir con los defaults — nótese que con el filtrado estricto
+// de creación, "vpn:none" y "clients:urgent" descartarían 2 de las 5; Seed
+// omite SOLO el filtro de config y mantiene dedup/cap/read-state). Si se
+// pasa un engine (main lo crea con kv) se usa; si no, memoria (tests).
+func NewDemo(engine ...*alerts.Engine) *Demo {
+	eng := alerts.New(nil, nil)
+	if len(engine) > 0 && engine[0] != nil {
+		eng = engine[0]
+	}
 	wg := canonWireguard()
 	d := &Demo{
-		rng:       rand.New(rand.NewSource(time.Now().UnixNano())),
-		routers:   canonRouters(),
-		wan:       canonWAN(),
-		adguard:   canonAdguard(),
-		wireguard: wg,
-		alerts:    canonAlerts(),
-		devices:   canonAllDevices(),
-		extras:    canonRouterExtras(),
-		wgBytes:   map[string]*wgByteCounter{},
+		rng:           rand.New(rand.NewSource(time.Now().UnixNano())),
+		routers:       canonRouters(),
+		wan:           canonWAN(),
+		adguard:       canonAdguard(),
+		wireguard:     wg,
+		engine:        eng,
+		devices:       canonAllDevices(),
+		extras:        canonRouterExtras(),
+		wgBytes:       map[string]*wgByteCounter{},
 		adguardSeries: buildAdGuardSeries(),
 		wanLatency: &WANLatency{
 			Last24h: canonWANLatency24h(),
@@ -67,6 +79,26 @@ func NewDemo() *Demo {
 	for _, p := range wg.Peers {
 		d.wgBytes[p.ID] = &wgByteCounter{rx: parseBytes(p.Rx), tx: parseBytes(p.Tx), active: p.Active}
 	}
+	// SPEC-CANON D5: totales y clientes por router DERIVADOS del dataset
+	// (los literales de canonRouters/canonAdguard son solo el canon base).
+	for i := range d.routers {
+		d.routers[i].Clients = onlineClientsOf(d.devices, d.routers[i].ID)
+	}
+	d.adguard.ClientsTotal = len(d.devices)
+	// Las 5 canon entran al motor en ORDEN INVERSO (Seed prepende) para que el
+	// feed quede en el orden canónico; después se marca el read-state del
+	// canon (3 leídas) en el read-set del servidor.
+	canon := canonAlerts()
+	for i := len(canon) - 1; i >= 0; i-- {
+		eng.Seed(canon[i])
+	}
+	readIDs := []string{}
+	for _, a := range canon {
+		if a.Read {
+			readIDs = append(readIDs, a.ID)
+		}
+	}
+	eng.MarkRead(readIDs...)
 	return d
 }
 
@@ -165,24 +197,22 @@ func (d *Demo) GetOverview(context.Context) (*Overview, error) {
 }
 
 func (d *Demo) buildOverview() *Overview {
-	unread := 0
-	for _, a := range d.alerts {
-		if !a.Read {
-			unread++
-		}
-	}
+	wg := d.wireguardSnapshot()
+	dists := canonDistributionNodes()
 	return &Overview{
-		Health:       canonHealthScore(),
-		WAN:          d.wan,
-		Traffic:      canonTraffic(),
-		Adguard:      d.adguard,
-		Wireguard:    d.wireguardSnapshot(),
-		Routers:      d.routersCopy(),
-		DeviceTotals: DeviceTotals{Total: 66, Online: 58, KnownOffline: 8, NewToday: 3},
-		TopDevices:   d.topDevices(5),
-		Alerts:       d.alertsCopy(),
-		UnreadAlerts: unread,
-		DistributionNodes: canonDistributionNodes(),
+		Health:            canonHealthScore(),
+		WAN:               d.wan,
+		Traffic:           canonTraffic(),
+		Adguard:           d.adguard,
+		Wireguard:         wg,
+		Routers:           d.routersCopy(),
+		DeviceTotals:      deviceTotalsOf(d.devices), // D5: derivado del dataset
+		TopDevices:        d.topDevices(5),
+		Alerts:            d.alertsCopy(),
+		UnreadAlerts:      d.engine.UnreadCount(),
+		DistributionNodes: dists,
+		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists), // SPEC-65 D65-3
+		VM:                ViewModelVersion,                                    // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}
 }
@@ -203,9 +233,7 @@ func (d *Demo) routersCopy() []Router {
 }
 
 func (d *Demo) alertsCopy() []AlertEvent {
-	out := make([]AlertEvent, len(d.alerts))
-	copy(out, d.alerts)
-	return out
+	return d.engine.List()
 }
 
 func (d *Demo) devicesCopy() []Device {
@@ -299,13 +327,14 @@ func (d *Demo) GetDevices(context.Context) []Device {
 	return d.devicesCopy()
 }
 
-// GetAlerts devuelve las 5 alertas canónicas.
+// GetAlerts devuelve las 5 alertas canónicas (via motor; read-set aplicado).
 func (d *Demo) GetAlerts(context.Context) []AlertEvent {
-	d.mu.Lock()
-	defer d.mu.Unlock()
 	return d.alertsCopy()
 }
 
+// AlertsEngine: motor de alertas del adapter (SPEC-ALERTAS §3).
+func (d *Demo) AlertsEngine() *alerts.Engine { return d.engine }
+
 // GetMetricsRows (demo.js:189-203). El poller no persiste en demo, pero la
 // interfaz lo exige.
 func (d *Demo) GetMetricsRows(context.Context) []MetricsRow {

+ 47 - 0
server-go/internal/adapters/demo_canon.go

@@ -0,0 +1,47 @@
+// demo_canon.go — Serialización del canon demo a JSON (SPEC-65 D65-1).
+//
+// La fuente de verdad única del canon es Go (demo_dataset.go/demo_extras.go);
+// app/src/data/demo-canon.json es un ARTEFACTO GENERADO (cmd/gen-demo-canon)
+// que la app importa en build. El test de frescura
+// (demo_canon_json_test.go) exige que el JSON commiteado coincida con lo que
+// produce BuildDemoCanon — si diverge: go run ./cmd/gen-demo-canon.
+//
+// NO se incluyen: traffic (series con random walk), alerts (tienen Seed del
+// engine) ni topDevices (la app los deriva ordenando por trafficMbps).
+package adapters
+
+// DemoCanonJSON es el contenido EXACTO de app/src/data/demo-canon.json
+// (claves camelCase, mismas formas que el contrato API de types.go).
+type DemoCanonJSON struct {
+	Routers           []Router           `json:"routers"`
+	Devices           []Device           `json:"devices"`
+	DeviceTotals      DeviceTotals       `json:"deviceTotals"`
+	DistributionNodes []DistributionNode `json:"distributionNodes"`
+	Adguard           AdGuardStats       `json:"adguard"`
+	Wireguard         WireGuardStats     `json:"wireguard"`
+	WAN               WAN                `json:"wan"`
+	Health            HealthScore        `json:"health"`
+}
+
+// BuildDemoCanon construye el canon completo con los agregados DERIVADOS del
+// dataset (SPEC-CANON D5): deviceTotals con deviceTotalsOf (NO literal),
+// router.clients con onlineClientsOf y adguard.clientsTotal = IDs únicos.
+func BuildDemoCanon() DemoCanonJSON {
+	devices := canonAllDevices()
+	routers := canonRouters()
+	for i := range routers {
+		routers[i].Clients = onlineClientsOf(devices, routers[i].ID)
+	}
+	adguard := canonAdguard()
+	adguard.ClientsTotal = len(devices)
+	return DemoCanonJSON{
+		Routers:           routers,
+		Devices:           devices,
+		DeviceTotals:      deviceTotalsOf(devices),
+		DistributionNodes: canonDistributionNodes(),
+		Adguard:           adguard,
+		Wireguard:         canonWireguard(),
+		WAN:               canonWAN(),
+		Health:            canonHealthScore(),
+	}
+}

+ 41 - 0
server-go/internal/adapters/demo_canon_json_test.go

@@ -0,0 +1,41 @@
+package adapters
+
+import (
+	"encoding/json"
+	"os"
+	"path/filepath"
+	"reflect"
+	"testing"
+)
+
+// Test de frescura del canon (SPEC-65 D65-1): app/src/data/demo-canon.json es
+// un artefacto GENERADO desde el canon Go — el test exige igualdad profunda
+// con BuildDemoCanon (tras normalizar ambos lados vía JSON marshal/unmarshal,
+// para comparar la forma serializada y no los tipos Go). Si diverge:
+//
+//	regenerar: go run ./cmd/gen-demo-canon
+func TestDemoCanonJSONFresco(t *testing.T) {
+	path := filepath.Join("..", "..", "..", "app", "src", "data", "demo-canon.json")
+	raw, err := os.ReadFile(path)
+	if err != nil {
+		t.Fatalf("leer %s: %v — regenerar: go run ./cmd/gen-demo-canon", path, err)
+	}
+	normalize := func(v any) any {
+		b, err := json.Marshal(v)
+		if err != nil {
+			t.Fatalf("marshal: %v", err)
+		}
+		var out any
+		if err := json.Unmarshal(b, &out); err != nil {
+			t.Fatalf("unmarshal: %v", err)
+		}
+		return out
+	}
+	var disk any
+	if err := json.Unmarshal(raw, &disk); err != nil {
+		t.Fatalf("%s no es JSON válido: %v", path, err)
+	}
+	if !reflect.DeepEqual(normalize(disk), normalize(BuildDemoCanon())) {
+		t.Fatalf("demo-canon.json desactualizado respecto al canon Go — regenerar: go run ./cmd/gen-demo-canon")
+	}
+}

+ 187 - 0
server-go/internal/adapters/demo_canon_test.go

@@ -0,0 +1,187 @@
+package adapters
+
+import (
+	"context"
+	"testing"
+)
+
+// Tests del canon reconciliado (SPEC-CANON fase 6, D1/D3/D4/D5). Fijan la
+// enumeración del dataset: sin IDs duplicadas, totales derivados, el switch
+// gestionado como Device + distnode managed y los puertos del gateway.
+
+func deviceByID(t *testing.T, devices []Device, id string) Device {
+	t.Helper()
+	for _, d := range devices {
+		if d.ID == id {
+			return d
+		}
+	}
+	t.Fatalf("device %q no existe en el dataset", id)
+	return Device{}
+}
+
+// D3: una sola identidad por ID en el dataset reconciliado.
+func TestCanonDatasetSinIDsDuplicadas(t *testing.T) {
+	devices := canonAllDevices()
+	seen := map[string]int{}
+	for _, d := range devices {
+		seen[d.ID]++
+	}
+	for id, n := range seen {
+		if n != 1 {
+			t.Fatalf("ID duplicada %q: %d definiciones", id, n)
+		}
+	}
+	// Las dos identidades reconciliadas, en su versión final:
+	xbox := deviceByID(t, devices, "xbox-series-s")
+	if !xbox.Online || xbox.Band != "cable" || xbox.AttachTo != "dist-living-lan3" {
+		t.Fatalf("xbox-series-s debería ser la cableada al GS308E: %+v", xbox)
+	}
+	hp := deviceByID(t, devices, "impresora-hp")
+	if !hp.Online || hp.Band != "cable" || hp.AttachTo != "dist-flint2-lan3" {
+		t.Fatalf("impresora-hp debería ser la cableada al switch inferido: %+v", hp)
+	}
+}
+
+// D5: los totales se derivan del dataset — la enumeración manda.
+func TestCanonTotalesDerivadosDelDataset(t *testing.T) {
+	devices := canonAllDevices()
+	totals := deviceTotalsOf(devices)
+	// Enumeración del canon reconciliado: 65 IDs únicos, 59 online, 6
+	// offline conocidos, 3 nuevos hoy.
+	if totals != (DeviceTotals{Total: 65, Online: 59, KnownOffline: 6, NewToday: 3}) {
+		t.Fatalf("enumeración del dataset: %+v", totals)
+	}
+
+	d := NewDemo()
+	ov, err := d.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if ov.DeviceTotals != totals {
+		t.Fatalf("overview.deviceTotals no derivado del dataset: %+v vs %+v", ov.DeviceTotals, totals)
+	}
+	if ov.Adguard.ClientsTotal != totals.Total {
+		t.Fatalf("adguard.clientsTotal=%d, dataset=%d", ov.Adguard.ClientsTotal, totals.Total)
+	}
+	// router.clients = recuento real online por router; la suma = online.
+	sum := 0
+	porRouter := map[string]int{}
+	for _, r := range ov.Routers {
+		porRouter[r.ID] = r.Clients
+		sum += r.Clients
+		if want := onlineClientsOf(devices, r.ID); r.Clients != want {
+			t.Fatalf("router %s clients=%d, enumeración=%d", r.ID, r.Clients, want)
+		}
+	}
+	if sum != totals.Online {
+		t.Fatalf("suma de clients por router=%d, online=%d", sum, totals.Online)
+	}
+	// Canon fijado: flint2/living/estudio/patio = 26/20/8/5.
+	want := map[string]int{"flint2": 26, "living": 20, "estudio": 8, "patio": 5}
+	for id, w := range want {
+		if porRouter[id] != w {
+			t.Fatalf("router %s clients=%d, canon=%d", id, porRouter[id], w)
+		}
+	}
+}
+
+// D1: el switch gestionado GS308E es Device (type switch, lldp, attachTo al
+// router, port de uplink) Y DistributionNode managed con Mac — y su Device
+// NO cuelga de su propio nodo (D2, paridad con inferTopology).
+func TestCanonSwitchGestionadoDeviceYNodo(t *testing.T) {
+	devices := canonAllDevices()
+	sw := deviceByID(t, devices, "switch-netgear")
+	if sw.Type != "switch" || sw.IP != "192.168.8.13" || !sw.Online {
+		t.Fatalf("GS308E device: %+v", sw)
+	}
+	if sw.RouterID != "living" || sw.AttachTo != "living" || sw.Port != "lan3" {
+		t.Fatalf("GS308E attachTo/port de uplink: %+v", sw)
+	}
+	if sw.Lldp == nil || sw.Lldp.Chassis != "GS308E" || sw.Lldp.Mgmt != "192.168.8.13" {
+		t.Fatalf("GS308E device sin lldp: %+v", sw.Lldp)
+	}
+
+	var managed *DistributionNode
+	for i, dn := range canonDistributionNodes() {
+		if dn.Kind == "managed" {
+			if managed != nil {
+				t.Fatalf("más de un distnode managed")
+			}
+			managed = &canonDistributionNodes()[i]
+		}
+	}
+	if managed == nil {
+		t.Fatal("no hay distnode managed")
+	}
+	if managed.ID != "dist-living-lan3" || managed.Mac == "" {
+		t.Fatalf("distnode managed sin mac: %+v", managed)
+	}
+	if managed.Mac != sw.MAC {
+		t.Fatalf("distnode.Mac=%q ≠ device.MAC=%q (la app cruza ambas para ocultar el chip)", managed.Mac, sw.MAC)
+	}
+	if sw.AttachTo == managed.ID {
+		t.Fatalf("el switch NO debe colgar de su propio nodo: %+v", sw)
+	}
+	// Y llega por el adapter demo (overview + devices).
+	d := NewDemo()
+	ov, _ := d.GetOverview(context.Background())
+	found := false
+	for _, dn := range ov.DistributionNodes {
+		if dn.ID == "dist-living-lan3" {
+			found = true
+			if dn.Mac != "28:C6:8E:1D:90:44" {
+				t.Fatalf("overview distnode managed mac: %q", dn.Mac)
+			}
+		}
+	}
+	if !found {
+		t.Fatal("overview sin dist-living-lan3")
+	}
+	deviceByID(t, d.GetDevices(context.Background()), "switch-netgear")
+}
+
+// D4: puertos del gateway y del Salón en devices y distnodes.
+func TestCanonPuertosD4(t *testing.T) {
+	devices := canonAllDevices()
+	if d := deviceByID(t, devices, "nas-synology"); d.Port != "lan4" {
+		t.Fatalf("NAS port: %q (D4: lan4)", d.Port)
+	}
+	if d := deviceByID(t, devices, "pve"); d.Port != "lan5" {
+		t.Fatalf("pve port: %q (D4: lan5)", d.Port)
+	}
+	if d := deviceByID(t, devices, "ps5"); d.Port != "lan1" {
+		t.Fatalf("PS5 port: %q (D4: lan1)", d.Port)
+	}
+	for _, dn := range canonDistributionNodes() {
+		if dn.ID == "dist-pve" && dn.Port != "lan5" {
+			t.Fatalf("dist-pve port: %q (D4: lan5)", dn.Port)
+		}
+		if dn.ID == "dist-flint2-lan3" && dn.Port != "lan3" {
+			t.Fatalf("dist-flint2-lan3 port: %q", dn.Port)
+		}
+	}
+	// Panel ethPorts del gateway cuadra con la tabla D4.
+	extras := canonRouterExtras()["flint2"]
+	ports := map[string]EthPort{}
+	for _, p := range extras.EthPorts {
+		ports[p.ID] = p
+	}
+	if ports["lan3"].ConnectedTo != "Switch sin gestión" || !ports["lan3"].Up {
+		t.Fatalf("flint2 lan3 (switch inferido): %+v", ports["lan3"])
+	}
+	if ports["lan4"].ConnectedTo != "NAS Synology" || !ports["lan4"].Up {
+		t.Fatalf("flint2 lan4 (NAS): %+v", ports["lan4"])
+	}
+	if ports["lan5"].ConnectedTo != "Proxmox pve" || ports["lan5"].Speed != "2.5 Gbps" || !ports["lan5"].Up {
+		t.Fatalf("flint2 lan5 (pve 2.5G): %+v", ports["lan5"])
+	}
+	// Salón: lan3 = GS308E UP (antes "libre/down").
+	living := map[string]EthPort{}
+	for _, p := range canonRouterExtras()["living"].EthPorts {
+		living[p.ID] = p
+	}
+	if !living["lan3"].Up || living["lan3"].ConnectedTo != "GS308E" {
+		t.Fatalf("living lan3 (GS308E up): %+v", living["lan3"])
+	}
+}

+ 110 - 41
server-go/internal/adapters/demo_dataset.go

@@ -1,15 +1,25 @@
 // 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 66 dispositivos (canon +
+// health score, AdGuard, WireGuard, alertas, los 65 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).
+// SPEC-CANON (fase 6): D1 switch gestionado = Device + distnode managed;
+// D3 una sola identidad por ID; D4 puertos del gateway; D5 totales
+// DERIVADOS del dataset (deviceTotalsOf / onlineClientsOf), no literales.
+// SPEC-65 D65-2: Device.Infra sellado en el canon (pve=hypervisor, sus
+// CTs/VMs=ct, switch-netgear=managed-switch).
+//
+//go:generate go run ../../cmd/gen-demo-canon
 package adapters
 
 import (
 	"fmt"
 	"math"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
 
 func iptr(v int) *int { return &v }
@@ -18,23 +28,26 @@ func iptr(v int) *int { return &v }
 // Routers / WAN / tráfico / health / AdGuard / WireGuard / alertas (canon)
 // ---------------------------------------------------------------------------
 
+// canonRouters: SPEC-CANON D5 — Clients es el recuento real de clientes
+// ONLINE por router del dataset (NewDemo lo re-deriva con onlineClientsOf;
+// estos literales solo documentan el canon y deben coincidir con él).
 func canonRouters() []Router {
 	return []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,
+			Health: 98, CPU: iptr(23), RAM: iptr(41), Temp: iptr(54), Uptime: "32d 14h", Clients: 26,
 			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,
+			Health: 95, CPU: iptr(12), RAM: iptr(38), Temp: iptr(47), Uptime: "32d 14h", Clients: 20,
 			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,
+			Health: 92, CPU: iptr(18), RAM: iptr(44), Temp: iptr(51), Uptime: "11d 3h", Clients: 8,
 			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"},
@@ -42,7 +55,7 @@ func canonRouters() []Router {
 		// 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",
+			Health: 68, CPU: iptr(31), RAM: iptr(57), Temp: iptr(71), Uptime: "4d 2h", Clients: 5, 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}},
 	}
@@ -103,7 +116,8 @@ func canonAdguard() AdGuardStats {
 	return AdGuardStats{
 		Host: "192.168.8.1", Port: 3000, Status: "active",
 		Queries24h: 84312, Blocked24h: 15687, BlockedPct: 18.6, TrackersBlocked: 9204,
-		DNSLatencyMs: 14, ClientsUsing: 60, ClientsTotal: 67,
+		// ClientsTotal = IDs únicos del dataset (D5; NewDemo lo re-deriva).
+		DNSLatencyMs: 14, ClientsUsing: 60, ClientsTotal: 65,
 		TopBlocked: []TopBlocked{
 			{Domain: "graph.facebook.com", Count: 1204},
 			{Domain: "adservice.google.com", Count: 986},
@@ -128,18 +142,22 @@ func canonWireguard() WireGuardStats {
 	}
 }
 
+// canonAlerts: las 5 alertas canónicas con Category/Urgent/Ts (SPEC-ALERTAS
+// §1 y §5). Los Ts son unix SEGUNDOS escalonados en coherencia con el string
+// legado ("hace 38 s" → now-38, "hace 12 min" → now-720, ...).
 func canonAlerts() []AlertEvent {
+	now := time.Now().Unix()
 	return []AlertEvent{
-		{ID: "alert-temp-patio", Severity: "warn", Title: "Temperatura alta en Patio",
-			Description: "71 °C, por encima del umbral (65 °C)", Time: "hace 12 min", Read: false, RouterID: "patio"},
-		{ID: "alert-firmware-estudio", Severity: "warn", Title: "Firmware disponible",
-			Description: "OpenWrt 24.10.1 para Estudio", Time: "hace 3 h", Read: false, RouterID: "estudio"},
-		{ID: "alert-nuevo-tab", Severity: "info", Title: "Nuevo dispositivo",
-			Description: "'Galaxy Tab S9' se ha unido a Salón", Time: "hace 26 min", Read: true, RouterID: "living"},
-		{ID: "alert-handshake-wg", Severity: "info", Title: "Handshake WireGuard",
-			Description: "Pixel 8 Pro conectado desde 5.224.x.x", Time: "hace 38 s", Read: true, RouterID: "flint2"},
-		{ID: "alert-backup-adguard", Severity: "ok", Title: "Copia de AdGuard completada",
-			Description: "Configuración y listas respaldadas en el NAS", Time: "hace 1 día", Read: true, RouterID: "flint2"},
+		{ID: "alert-temp-patio", Category: alerts.CatRouter, Urgent: true, Severity: "warn", Title: "Temperatura alta en Patio",
+			Description: "71 °C, por encima del umbral (65 °C)", Time: "hace 12 min", Ts: now - 12*60, Read: false, RouterID: "patio"},
+		{ID: "alert-firmware-estudio", Category: alerts.CatSystem, Urgent: false, Severity: "warn", Title: "Firmware disponible",
+			Description: "OpenWrt 24.10.1 para Estudio", Time: "hace 3 h", Ts: now - 3*3600, Read: false, RouterID: "estudio"},
+		{ID: "alert-nuevo-tab", Category: alerts.CatClients, Urgent: false, Severity: "info", Title: "Nuevo dispositivo",
+			Description: "'Galaxy Tab S9' se ha unido a Salón", Time: "hace 26 min", Ts: now - 26*60, Read: true, RouterID: "living"},
+		{ID: "alert-handshake-wg", Category: alerts.CatVPN, Urgent: false, Severity: "info", Title: "Handshake WireGuard",
+			Description: "Pixel 8 Pro conectado desde 5.224.x.x", Time: "hace 38 s", Ts: now - 38, Read: true, RouterID: "flint2"},
+		{ID: "alert-backup-adguard", Category: alerts.CatSystem, Urgent: false, Severity: "ok", Title: "Copia de AdGuard completada",
+			Description: "Configuración y listas respaldadas en el NAS", Time: "hace 1 día", Ts: now - 24*3600, Read: true, RouterID: "flint2"},
 	}
 }
 
@@ -221,7 +239,7 @@ func canonDevices() []Device {
 			Traffic24hRx: "18 GB", Traffic24hTx: "2,2 GB", Adguard: boolp(true), Group: "ordenadores"},
 		{ID: "ps5", Name: "PS5", Type: "consola", Manufacturer: "Sony",
 			IP: "192.168.8.31", MAC: "78:C8:81:0A:6B:D4", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 12.7, Online: true, Port: "lan2",
+			SignalDbm: nil, TrafficMbps: 12.7, Online: true, Port: "lan1",
 			Sparkline: []float64{4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13},
 			Hostname:  "ps5-salon", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 300 días",
 			Traffic24hRx: "92 GB", Traffic24hTx: "4,8 GB", Adguard: boolp(true), Group: "tv"},
@@ -245,7 +263,7 @@ func canonDevices() []Device {
 			Traffic24hRx: "1,4 GB", Traffic24hTx: "88 MB", Adguard: boolp(true), Group: "iot"},
 		{ID: "nas-synology", Name: "NAS Synology", Type: "servidor", Manufacturer: "Synology",
 			IP: "192.168.8.10", MAC: "00:11:32:9C:51:B7", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 2.3, Online: true, Port: "lan1",
+			SignalDbm: nil, TrafficMbps: 2.3, Online: true, Port: "lan4",
 			Sparkline: []float64{1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3},
 			Hostname:  "diskstation", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 320 días",
 			Traffic24hRx: "96 GB", Traffic24hTx: "1,1 TB", Adguard: boolp(true), Group: "red"},
@@ -278,10 +296,11 @@ 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", ""),
-		// 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.
+		// NOTA (SPEC-CANON D1): el switch gestionado GS308E (Salón lan3)
+		// vuelve a ser Device — ver topologyDevices, junto a sus clientes —
+		// ADEMÁS de seguir siendo el DistributionNode "managed"
+		// dist-living-lan3. La app excluye su chip del mapa cruzando
+		// Device.MAC con DistributionNode.Mac.
 		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),
@@ -294,10 +313,9 @@ func additionalDevices() []Device {
 			IP: "192.168.8.46", MAC: "3C:5A:B4:08:D7:5E", RouterID: "flint2", Band: "5 GHz",
 			SignalDbm: iptr(-49), TrafficMbps: 1.4, Online: true}, 18, 0),
 			"pixel-7", "renueva en 7 h 3 min", "hace 205 días", "1,9 GB", "180 MB", true, "moviles", ""),
-		withDetails(devExtra(Device{ID: "impresora-hp", Name: "Impresora HP", Type: "desconocido", Manufacturer: "HP",
-			IP: "192.168.8.14", MAC: "3C:52:82:AB:19:60", RouterID: "flint2", Band: "2.4 GHz",
-			SignalDbm: iptr(-60), TrafficMbps: 0, Online: false}, 1, 0),
-			"hp-laserjet-m209", "Expirado", "hace 250 días", "0 MB", "0 MB", true, "otros", "Printer"),
+		// SPEC-CANON D3: la identidad vieja wifi/offline de impresora-hp se
+		// elimina — la única es la cableada al switch inferido
+		// (topologyDevices, attachTo dist-flint2-lan3).
 		withDetails(devExtra(Device{ID: "ipad-air", Name: "iPad Air", Type: "tablet", Manufacturer: "Apple",
 			IP: "192.168.8.47", MAC: "8C:85:90:2F:B4:11", RouterID: "flint2", Band: "5 GHz",
 			SignalDbm: iptr(-54), TrafficMbps: 0, Online: false}, 1, 0),
@@ -341,10 +359,9 @@ func additionalDevices() []Device {
 			IP: "192.168.8.29", MAC: "A2:7E:9C:41:0B:6D", RouterID: "living", Band: "5 GHz",
 			SignalDbm: iptr(-58), TrafficMbps: 0.7, Online: true, IsNew: true}, 26, 0),
 			"unknown-7f2a", "renueva en 2 h 9 min", "hoy", "480 MB", "62 MB", false, "ordenadores", ""),
-		withDetails(devExtra(Device{ID: "xbox-series-s", Name: "Xbox Series S", Type: "consola", Manufacturer: "Microsoft",
-			IP: "192.168.8.32", MAC: "7C:1E:52:06:AA:3F", RouterID: "living", Band: "5 GHz",
-			SignalDbm: iptr(-55), TrafficMbps: 0, Online: false}, 1, 0),
-			"xbox-series-s", "Expirado", "hace 230 días", "0 MB", "0 MB", true, "tv", ""),
+		// SPEC-CANON D3: la identidad vieja wifi/offline de xbox-series-s se
+		// elimina — la única es la cableada al GS308E (topologyDevices,
+		// attachTo dist-living-lan3).
 		withDetails(devExtra(Device{ID: "portatil-antiguo", Name: "Portátil antiguo", Type: "portatil", Manufacturer: "HP",
 			IP: "192.168.8.28", MAC: "3C:52:82:5D:90:17", RouterID: "living", Band: "2.4 GHz",
 			SignalDbm: iptr(-62), TrafficMbps: 0, Online: false}, 1, 0),
@@ -414,10 +431,11 @@ func withDetails(d Device, hostname, lease, firstSeen, rx, tx string, adguard bo
 	return d
 }
 
-// canonAllDevices: los 66 clientes (canon expandido + adicionales + fixtures
+// canonAllDevices: los 65 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).
+// SPEC-CANON D1/D3: el GS308E vuelve a ser Device (además del distnode
+// managed) y xbox-series-s/impresora-hp tienen UNA sola identidad.
 func canonAllDevices() []Device {
 	out := canonDevices()
 	out = append(out, additionalDevices()...)
@@ -427,10 +445,21 @@ func canonAllDevices() []Device {
 
 // topologyDevices: fixtures NUEVAS de topología v5 (mockup aprobado
 // 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).
+// enriquecen in situ en additionalDevices — no se duplican. SPEC-CANON D1:
+// el GS308E existe como Device (badge "Switch gestionado", con Lldp,
+// attachTo al router Salón y port de su uplink) Y como DistributionNode
+// managed dist-living-lan3; la app no renderiza su chip cruzando MACs.
 func topologyDevices() []Device {
 	out := []Device{
+		// Switch gestionado Netgear GS308E (Salón lan3), identificado por
+		// LLDP. Device + nodo managed a la vez (SPEC-CANON D1): attachTo al
+		// router y port de uplink — NUNCA cuelga de su propio nodo (D2).
+		withDetails(devExtra(Device{ID: "switch-netgear", Name: "Switch GS308E", Type: "switch", Manufacturer: "Netgear",
+			IP: "192.168.8.13", MAC: "28:C6:8E:1D:90:44", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.02, Online: true, AttachTo: "living", Port: "lan3",
+			Infra: "managed-switch",
+			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"),
 		// 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",
@@ -448,10 +477,11 @@ func topologyDevices() []Device {
 			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)
+		// Hipervisor Proxmox (gateway lan5, 2.5G — SPEC-CANON D4); sus 10 CTs
+		// se anidan (OUI BC:24:11)
 		withDetails(Device{ID: "pve", Name: "Proxmox pve", Type: "servidor", Manufacturer: "Supermicro",
 			IP: "192.168.8.5", MAC: "3C:52:82:10:20:30", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 12.3, Online: true, Port: "lan2",
+			SignalDbm: nil, TrafficMbps: 12.3, Online: true, Port: "lan5", Infra: "hypervisor",
 			Sparkline: []float64{8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3}},
 			"pve", "IP fija (reserva)", "hace 400 días", "1,2 TB", "96 GB", true, "red", ""),
 	}
@@ -479,7 +509,7 @@ func topologyDevices() []Device {
 		out = append(out, withDetails(Device{
 			ID: c.id, Name: c.name, Type: c.typ, Manufacturer: "Proxmox VE (CT)",
 			IP: c.ip, MAC: fmt.Sprintf("BC:24:11:00:2%d:%02X", i, 0x10+i), RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: mbps, Online: true, AttachTo: "pve", Sparkline: sp},
+			SignalDbm: nil, TrafficMbps: mbps, Online: true, AttachTo: "pve", Infra: "ct", Sparkline: sp},
 			c.id, "renueva en 3 h 10 min", "hace 90 días", "1,1 GB", "88 MB", true, "red", ""))
 	}
 	// Tras el switch/bridge inferido (gateway lan3, OUI heterogéneo, sin IP).
@@ -513,11 +543,15 @@ func topologyDevices() []Device {
 		case "altavoz":
 			grp = "iot"
 		}
+		icon := ""
+		if b.id == "impresora-hp" {
+			icon = "Printer" // paridad con el mock viejo (devices-data.ts)
+		}
 		out = append(out, withDetails(Device{
 			ID: b.id, Name: b.name, Type: b.typ, Manufacturer: b.man,
 			IP: b.ip, MAC: b.mac, RouterID: "flint2", Band: "cable",
 			SignalDbm: nil, TrafficMbps: mbps, Online: true, AttachTo: "dist-flint2-lan3", Sparkline: sp},
-			b.id, "renueva en 5 h 22 min", "hace 60 días", "2,4 GB", "120 MB", true, grp, ""))
+			b.id, "renueva en 5 h 22 min", "hace 60 días", "2,4 GB", "120 MB", true, grp, icon))
 	}
 	return out
 }
@@ -525,13 +559,14 @@ func topologyDevices() []Device {
 // 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).
+// sus 3 clientes en abanico). SPEC-CANON D1: el nodo managed lleva Mac
+// (chassis-MAC) para que la app excluya el chip del Device del switch.
 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-pve", Kind: "hypervisor", RouterID: "flint2", Port: "lan5", 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",
+			Name: "GS308E", Ip: "192.168.8.13", Mac: "28:C6:8E:1D:90:44",
 			Lldp: &LldpInfo{Chassis: "GS308E", Mgmt: "192.168.8.13", Caps: "Bridge", PortDesc: "ge5"}},
 	}
 }
@@ -539,3 +574,37 @@ func canonDistributionNodes() []DistributionNode {
 // boolp: los literales demo fijan adguard explícito (true/false) como en el
 // dataset JS; live lo deja nil para omitir el campo.
 func boolp(b bool) *bool { return &b }
+
+// ---------------------------------------------------------------------------
+// D5 — totales DERIVADOS del dataset (nunca literales escritos a mano)
+// ---------------------------------------------------------------------------
+
+// deviceTotalsOf enumera el dataset y deriva deviceTotals: total = IDs
+// únicos del dataset reconciliado, online/offline por estado, newToday =
+// dispositivos con IsNew.
+func deviceTotalsOf(devices []Device) DeviceTotals {
+	t := DeviceTotals{Total: len(devices)}
+	for _, d := range devices {
+		if d.Online {
+			t.Online++
+		} else {
+			t.KnownOffline++
+		}
+		if d.IsNew {
+			t.NewToday++
+		}
+	}
+	return t
+}
+
+// onlineClientsOf: recuento real de clientes ONLINE de un router
+// (router.clients — SPEC-CANON D5).
+func onlineClientsOf(devices []Device, routerID string) int {
+	n := 0
+	for _, d := range devices {
+		if d.RouterID == routerID && d.Online {
+			n++
+		}
+	}
+	return n
+}

+ 16 - 10
server-go/internal/adapters/demo_extras.go

@@ -65,7 +65,9 @@ func canonRouterExtras() map[string]*demoExtras {
 			Soc: "MediaTek MT7986A", Flash: "8 GB eMMC", RamMb: 512,
 			BandSplit: demoBandSplit{Band24: 4, Band5: 10, Cable: 3},
 			TrafficNow: 84.2,
-			// GL-MT6000: 1× WAN 2.5G + 4× LAN 1G
+			// GL-MT6000: 1× WAN 2.5G + 4× LAN 1G + 1× LAN 2.5G.
+			// SPEC-CANON D4: lan1/lan2 = uplinks LLDP (Salón/Estudio),
+			// lan3 = switch tonto inferido, lan4 = NAS, lan5 = pve 2.5G.
 			GatewayLatencySpark: []float64{},
 			BackhaulSignal:      []float64{},
 			Radios:              []Radio{},
@@ -73,9 +75,10 @@ func canonRouterExtras() map[string]*demoExtras {
 			EthPorts: []EthPort{
 				{ID: "wan", Label: "WAN", Up: true, Speed: "2.5 Gbps", ConnectedTo: "ONT fibra · Digi", Detail: "84.122.x.x · full duplex"},
 				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "Salón · AX3000T", Detail: "Uplink AP Salón (192.168.8.2)"},
-				{ID: "lan2", Label: "LAN 2", Up: true, Speed: "1 Gbps", ConnectedTo: "NAS Synology", Detail: "192.168.8.10 · cable"},
-				{ID: "lan3", Label: "LAN 3", Up: true, Speed: "1 Gbps", ConnectedTo: "Estudio · NanoPi R4S", Detail: "Uplink AP Estudio (192.168.8.3)"},
-				{ID: "lan4", Label: "LAN 4", Up: false},
+				{ID: "lan2", Label: "LAN 2", Up: true, Speed: "1 Gbps", ConnectedTo: "Estudio · NanoPi R4S", Detail: "Uplink AP Estudio (192.168.8.3)"},
+				{ID: "lan3", Label: "LAN 3", Up: true, Speed: "1 Gbps", ConnectedTo: "Switch sin gestión", Detail: "Inferido por FDB · 8 MACs"},
+				{ID: "lan4", Label: "LAN 4", Up: true, Speed: "1 Gbps", ConnectedTo: "NAS Synology", Detail: "192.168.8.10 · cable"},
+				{ID: "lan5", Label: "LAN 5", Up: true, Speed: "2.5 Gbps", ConnectedTo: "Proxmox pve", Detail: "192.168.8.5 · hipervisor · 10 CT"},
 			},
 		},
 		"living": {
@@ -98,12 +101,13 @@ func canonRouterExtras() map[string]*demoExtras {
 				{Name: "phy0-ap0", Up: true, Speed: "—", Role: "Radio 2.4 GHz"},
 				{Name: "phy1-ap0", Up: true, Speed: "—", Role: "Radio 5 GHz"},
 			},
-			// AX3000T: 1× WAN + 3× LAN
+			// AX3000T: 1× WAN + 3× LAN (SPEC-CANON D4: lan1 = PS5,
+			// lan3 = GS308E UP — el switch gestionado, dist-living-lan3)
 			EthPorts: []EthPort{
 				{ID: "wan", Label: "WAN", Up: true, Speed: "1 Gbps", ConnectedTo: "Uplink → Gateway", Detail: "Gateway · LAN 1 (192.168.8.1)"},
 				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "PS5", Detail: "192.168.8.31 · cable"},
 				{ID: "lan2", Label: "LAN 2", Up: false},
-				{ID: "lan3", Label: "LAN 3", Up: false},
+				{ID: "lan3", Label: "LAN 3", Up: true, Speed: "1 Gbps", ConnectedTo: "GS308E", Detail: "Switch gestionado · 192.168.8.13 · LLDP"},
 			},
 		},
 		"estudio": {
@@ -122,14 +126,16 @@ func canonRouterExtras() map[string]*demoExtras {
 			Ports: []demoPortState{
 				{Name: "br-lan", Up: true, Speed: "—", Role: "Bridge LAN"},
 				{Name: "eth0", Up: true, Speed: "1 Gbps", Role: "Uplink al Gateway"},
-				{Name: "eth1", Up: true, Speed: "1 Gbps", Role: "Switch estudio"},
+				{Name: "eth1", Up: true, Speed: "1 Gbps", Role: "Switch sin gestión"},
 				{Name: "phy0-ap0", Up: true, Speed: "—", Role: "Radio 2.4 GHz"},
 				{Name: "phy1-ap0", Up: true, Speed: "—", Role: "Radio 5 GHz"},
 			},
-			// NanoPi R4S: 2× 1G (WAN + LAN)
+			// NanoPi R4S: 2× 1G (WAN + LAN). SPEC-CANON D4: lan1 = switch sin
+			// gestión — SOLO panel; la topología no lo muestra (los nodos
+			// "inferred" solo se anclan en el gateway, ver topology.go).
 			EthPorts: []EthPort{
-				{ID: "wan", Label: "WAN", Up: true, Speed: "1 Gbps", ConnectedTo: "Uplink → Gateway", Detail: "Gateway · LAN 3 (192.168.8.1)"},
-				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "Switch estudio", Detail: "Switch 8 puertos · 4 en uso"},
+				{ID: "wan", Label: "WAN", Up: true, Speed: "1 Gbps", ConnectedTo: "Uplink → Gateway", Detail: "Gateway · LAN 2 (192.168.8.1)"},
+				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "Switch sin gestión", Detail: "Switch 8 puertos · 4 en uso"},
 			},
 		},
 		"patio": {

+ 102 - 0
server-go/internal/adapters/infra_test.go

@@ -0,0 +1,102 @@
+package adapters
+
+import "testing"
+
+// SPEC-65 D65-2: Device.infra sellado server-side ("hypervisor" | "ct" |
+// "managed-switch"); ausente = dispositivo normal.
+
+// Demo: el canon sella pve=hypervisor, sus 10 CTs/VMs=ct y
+// switch-netgear=managed-switch; ningún otro device lleva infra.
+func TestInfraSelladoDemoCanon(t *testing.T) {
+	devices := canonAllDevices()
+	cts := 0
+	for _, d := range devices {
+		switch {
+		case d.ID == "pve":
+			if d.Infra != "hypervisor" {
+				t.Fatalf("pve.infra=%q, esperaba hypervisor", d.Infra)
+			}
+		case d.ID == "switch-netgear":
+			if d.Infra != "managed-switch" {
+				t.Fatalf("switch-netgear.infra=%q, esperaba managed-switch", d.Infra)
+			}
+		case len(d.ID) > 3 && d.ID[:3] == "ct-":
+			if d.Infra != "ct" {
+				t.Fatalf("%s.infra=%q, esperaba ct", d.ID, d.Infra)
+			}
+			cts++
+		default:
+			if d.Infra != "" {
+				t.Fatalf("%s no debería llevar infra: %q", d.ID, d.Infra)
+			}
+		}
+	}
+	if cts != 10 {
+		t.Fatalf("CTs del pve: %d, esperaba 10", cts)
+	}
+	// Y llega al snapshot del overview.
+	d := NewDemo()
+	ov, err := d.GetOverview(t.Context())
+	if err != nil {
+		t.Fatal(err)
+	}
+	found := map[string]string{}
+	for _, dev := range ov.TopDevices {
+		found[dev.ID] = dev.Infra
+	}
+	for _, dev := range d.GetDevices(t.Context()) {
+		if dev.ID == "pve" && dev.Infra != "hypervisor" {
+			t.Fatalf("pve.infra en /api/devices: %q", dev.Infra)
+		}
+	}
+}
+
+// Live: el pipeline de topología sella el host del hipervisor y sus VMs.
+func TestInfraSelladoLiveHipervisor(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"3C:52:82:10:20:30": "lan2", // host (OUI normal)
+		"BC:24:11:00:20:10": "lan2", // CT1 (OUI Proxmox)
+		"BC:24:11:00:20:11": "lan2", // CT2
+	})
+	devices := []Device{
+		dev("3C:52:82:10:20:30", "flint2", "cable"),
+		dev("BC:24:11:00:20:10", "flint2", "cable"),
+		dev("BC:24:11:00:20:11", "flint2", "cable"),
+	}
+	devices, _ = inferTopology(polled, devices)
+	if devices[0].Infra != "hypervisor" {
+		t.Fatalf("host.infra=%q, esperaba hypervisor", devices[0].Infra)
+	}
+	for _, d := range devices[1:] {
+		if d.Infra != "ct" {
+			t.Fatalf("CT %s.infra=%q, esperaba ct", d.MAC, d.Infra)
+		}
+	}
+}
+
+// Live: un vecino LLDP managed cuya chassis-MAC existe como Device queda
+// sellado managed-switch.
+func TestInfraSelladoLiveManagedSwitch(t *testing.T) {
+	polled := polledWithFDB("living", "C1:83:C4:00:00:02", map[string]string{
+		"28:C6:8E:1D:90:44": "lan3", // chassis-MAC del GS308E
+		"7C:ED:8D:4A:11:22": "lan3", // cliente tras el switch
+	})
+	polled["living"].lldp = []LldpNeighbor{{
+		Port: "lan3", ChassisMac: "28:C6:8E:1D:90:44", Chassis: "GS308E",
+		Mgmt: "192.168.8.13", Caps: []string{"Bridge"},
+	}}
+	devices := []Device{
+		dev("28:C6:8E:1D:90:44", "living", "cable"),
+		dev("7C:ED:8D:4A:11:22", "living", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "managed" {
+		t.Fatalf("distnode managed esperado: %+v", dists)
+	}
+	if devices[0].Infra != "managed-switch" {
+		t.Fatalf("switch.infra=%q, esperaba managed-switch", devices[0].Infra)
+	}
+	if devices[1].Infra != "" {
+		t.Fatalf("el cliente tras el switch no lleva infra: %q", devices[1].Infra)
+	}
+}

+ 159 - 56
server-go/internal/adapters/live.go

@@ -18,6 +18,7 @@ import (
 	"sync"
 	"time"
 
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 )
@@ -118,18 +119,26 @@ 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
-	backhaulCache map[string]backhaulCacheEntry
-	lldpCache     map[string]lldpCacheEntry
+	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
+	engine         *alerts.Engine
+	wgActive       map[string]bool
+	weakAlerted    map[string]int64
+	onlineMacs     map[string]bool
+	seenOnlineMacs bool
+	wanDown        map[string]int
+	backhaulCache  map[string]backhaulCacheEntry
+	lldpCache      map[string]lldpCacheEntry
+
+	// Agentes nativos (Tier 2): último payload por slug + flag de caída
+	// (degradado a SSH tras emitir la alerta, SPEC-AGENTE-PILOTO §1).
+	agents    *AgentRegistry
+	agentDown map[string]bool
 
 	agStd *AdGuardClient
 	agGL  *AdGuardGlinetClient
@@ -157,10 +166,14 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		extrasCache:   map[string]*extrasSnapshot{},
 		lastPolled:    map[string]*routerPolled{},
 		failCount:     map[string]int{},
+		engine:        alerts.New(d, nil),
 		wgActive:      map[string]bool{},
 		weakAlerted:   map[string]int64{},
+		onlineMacs:    map[string]bool{},
+		wanDown:       map[string]int{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
+		agentDown:     map[string]bool{},
 	}
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
@@ -404,8 +417,13 @@ func (l *Live) metricsHistory(routerID, rang string) []histPoint {
 	return out
 }
 
-// pollRouter sondea un router; error si está inalcanzable.
+// pollRouter sondea un router; error si está inalcanzable. Si el router tiene
+// agente nativo con payload fresco (Tier 2), el sondeo viene del último push
+// y NO se toca SSH; si el agente expiró, se degrada a Tier 0 (SSH) con aviso.
 func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
+	if fresh, p := l.pollRouterAgent(cfg); fresh {
+		return p, nil
+	}
 	l.mu.Lock()
 	client := l.clients[cfg.ID]
 	gw := l.gatewayCfg
@@ -694,7 +712,20 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 		if res.err == nil {
 			polled[res.cfg.ID] = res.p
 			l.failCount[res.cfg.ID] = 0
+			// Router recuperado (offline→online, SPEC-ALERTAS §1)
+			if l.lastStatus[res.cfg.ID] == "offline" {
+				name := res.cfg.Name
+				if name == "" {
+					name = res.cfg.Host
+				}
+				l.emitRouterRecovered(res.cfg.ID, name)
+			}
 			l.lastStatus[res.cfg.ID] = "online"
+			// WAN/Internet caído: gateway OK pero ping a internet con 100 %
+			// de pérdida en 2 sondeos seguidos (mismo debounce que offline).
+			if l.gatewayCfg != nil && res.cfg.ID == l.gatewayCfg.ID {
+				l.trackWanDown(&res.cfg, res.p)
+			}
 			continue
 		}
 		fails := l.failCount[res.cfg.ID] + 1
@@ -706,16 +737,14 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 			if name == "" {
 				name = res.cfg.Host
 			}
-			l.alerts = append([]AlertEvent{{
+			l.engine.Emit(AlertEvent{
 				ID:       fmt.Sprintf("alert-offline-%s-%d", res.cfg.ID, time.Now().UnixMilli()),
-				Severity: "critical",
-				Title:    name + " offline",
+				Category: alerts.CatRouter, Urgent: true,
+				Severity:    "critical",
+				Title:       name + " offline",
 				Description: fmt.Sprintf("Sin respuesta de %s: %v", res.cfg.Host, res.err),
-				Time:     "ahora mismo", Read: false, RouterID: res.cfg.ID,
-			}}, l.alerts...)
-			if len(l.alerts) > 100 {
-				l.alerts = l.alerts[:100]
-			}
+				Time:        "ahora mismo", RouterID: res.cfg.ID,
+			})
 		}
 		if fails >= 2 {
 			l.lastStatus[res.cfg.ID] = "offline"
@@ -725,6 +754,87 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	return polled
 }
 
+// emitRouterRecovered: evento "router recuperado" (offline→online;
+// category router, urgent false, severity ok — SPEC-ALERTAS §1).
+// Debe llamarse con l.mu tomado (mismo contexto que el resto de emisiones).
+func (l *Live) emitRouterRecovered(routerID, name string) {
+	l.engine.Emit(AlertEvent{
+		ID:       fmt.Sprintf("alert-recovered-%s-%d", routerID, time.Now().UnixMilli()),
+		Category: alerts.CatRouter, Urgent: false,
+		Severity:    "ok",
+		Title:       name + " recuperado",
+		Description: fmt.Sprintf("%s vuelve a responder", name),
+		Time:        "ahora mismo", RouterID: routerID,
+	})
+}
+
+// trackWanDown detecta "WAN/Internet caído" (category internet, urgent true,
+// critical — SPEC-ALERTAS §1): el gateway responde por SSH pero su ping a
+// internet da 100 % de pérdida en 2 sondeos seguidos (debounce como offline).
+// Al recuperarse la WAN se resetea el estado (la próxima caída vuelve a
+// alertar). Debe llamarse con l.mu tomado.
+func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
+	key := cfg.ID + ":wan"
+	if p == nil || p.lossPct == nil || *p.lossPct < 100 {
+		l.wanDown[cfg.ID] = 0
+		l.lastStatus[key] = "up"
+		return
+	}
+	l.wanDown[cfg.ID]++
+	if l.wanDown[cfg.ID] >= 2 && l.lastStatus[key] != "down" {
+		l.lastStatus[key] = "down"
+		name := cfg.Name
+		if name == "" {
+			name = cfg.Host
+		}
+		l.engine.Emit(AlertEvent{
+			ID:       fmt.Sprintf("alert-wan-%s-%d", cfg.ID, time.Now().UnixMilli()),
+			Category: alerts.CatInternet, Urgent: true,
+			Severity:    "critical",
+			Title:       "Internet caído",
+			Description: fmt.Sprintf("%s responde pero no alcanza internet (100 %% de pérdida)", name),
+			Time:        "ahora mismo", RouterID: cfg.ID,
+		})
+	}
+}
+
+// trackUnknownDevices emite "dispositivo desconocido se conecta" cuando un
+// cliente SIN nombre (Name == MAC, sin hostname DHCP ni alias — device_attrib
+// no guarda alias) pasa de no-online a online. El primer ciclo de sondeo del
+// proceso NO alerta (evita la avalancha de arranque: todo lo ya conectado
+// sería "nuevo"). Toma l.mu internamente.
+func (l *Live) trackUnknownDevices(devices []Device) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	nowOnline := map[string]bool{}
+	for _, d := range devices {
+		if !d.Online {
+			continue
+		}
+		nowOnline[d.MAC] = true
+		if l.seenOnlineMacs && !l.onlineMacs[d.MAC] && d.Name == d.MAC {
+			l.emitUnknownDevice(d)
+		}
+	}
+	l.onlineMacs = nowOnline
+	l.seenOnlineMacs = true
+}
+
+// emitUnknownDevice: evento "dispositivo desconocido se conecta" (category
+// clients, urgent true, warn — SPEC-ALERTAS §1). "Desconocido" = sin nombre/
+// alias: device_attrib no guarda alias, así que la señal práctica es un
+// cliente sin hostname DHCP (Name == MAC). Debe llamarse con l.mu tomado.
+func (l *Live) emitUnknownDevice(d Device) {
+	l.engine.Emit(AlertEvent{
+		ID:       fmt.Sprintf("alert-unknown-%s-%d", d.MAC, time.Now().UnixMilli()),
+		Category: alerts.CatClients, Urgent: true,
+		Severity:    "warn",
+		Title:       "Dispositivo desconocido",
+		Description: fmt.Sprintf("%s se ha conectado a %s", d.MAC, d.RouterID),
+		Time:        "ahora mismo", RouterID: d.RouterID,
+	})
+}
+
 // pollAdGuard: stats del cliente configurado; fallback inactivo si falla.
 func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
 	std, gl := l.getAdguardClient()
@@ -790,15 +900,13 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 					name = p.Name
 				}
 			}
-			l.alerts = append([]AlertEvent{{
-				ID: fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
+				Category: alerts.CatVPN, Urgent: false,
 				Severity: "info", Title: "Handshake WireGuard",
 				Description: name + " conectado",
-				Time:        "ahora mismo", Read: false, RouterID: gw.ID,
-			}}, l.alerts...)
-			if len(l.alerts) > 100 {
-				l.alerts = l.alerts[:100]
-			}
+				Time:        "ahora mismo", RouterID: gw.ID,
+			})
 		}
 	}
 	l.wgActive = activeNow
@@ -917,7 +1025,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		lease, hasLease := leasesByMac[mac]
 		s, isSeen := seen[mac]
 		d := Device{
-			ID: strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
+			ID:  strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
 			MAC: mac, Manufacturer: "Desconocido",
 			TrafficMbps: 0, Sparkline: []float64{},
 			RouterID: gwID, Band: "—",
@@ -1067,15 +1175,13 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		// Alerta de temperatura UNA vez por proceso (flag, como el JS)
 		if router.Temp != nil && *router.Temp > 65 && l.lastStatus[cfg.ID+":temp"] != "warn" {
 			l.lastStatus[cfg.ID+":temp"] = "warn"
-			l.alerts = append([]AlertEvent{{
-				ID: fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
+				Category: alerts.CatRouter, Urgent: true,
 				Severity: "warn", Title: "Temperatura alta en " + router.Name,
 				Description: fmt.Sprintf("%d °C, por encima del umbral (65 °C)", *router.Temp),
-				Time:        "ahora mismo", Read: false, RouterID: cfg.ID,
-			}}, l.alerts...)
-			if len(l.alerts) > 100 {
-				l.alerts = l.alerts[:100]
-			}
+				Time:        "ahora mismo", RouterID: cfg.ID,
+			})
 		}
 		l.mu.Unlock()
 		routerList = append(routerList, router)
@@ -1090,19 +1196,18 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 			last := l.weakAlerted[d.MAC]
 			if time.Now().UnixMilli()-last > 24*3600e3 {
 				l.weakAlerted[d.MAC] = time.Now().UnixMilli()
-				l.alerts = append([]AlertEvent{{
-					ID: fmt.Sprintf("alert-weak-%s-%d", d.MAC, time.Now().UnixMilli()),
+				l.engine.Emit(AlertEvent{
+					ID:       fmt.Sprintf("alert-weak-%s-%d", d.MAC, time.Now().UnixMilli()),
+					Category: alerts.CatSignal, Urgent: false,
 					Severity: "warn", Title: "Señal débil en " + d.Name,
 					Description: fmt.Sprintf("%d dBm en %s — revisa cobertura o acerca un AP", *d.SignalDbm, d.RouterID),
-					Time:        "ahora mismo", Read: false, RouterID: d.RouterID,
-				}}, l.alerts...)
-				if len(l.alerts) > 100 {
-					l.alerts = l.alerts[:100]
-				}
+					Time:        "ahora mismo", RouterID: d.RouterID,
+				})
 			}
 			l.mu.Unlock()
 		}
 	}
+	l.trackUnknownDevices(devices)
 	// Clientes reales por router (atribución wireless/FDB, no leases)
 	for i := range routerList {
 		n := 0
@@ -1152,15 +1257,10 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	if len(top) > 5 {
 		top = top[:5]
 	}
-	l.mu.Lock()
-	alertsCopy := append([]AlertEvent(nil), l.alerts...)
-	l.mu.Unlock()
-	unread := 0
-	for _, a := range alertsCopy {
-		if !a.Read {
-			unread++
-		}
-	}
+	// El motor de alertas es el dueño de la lista y del read-state
+	// (SPEC-ALERTAS §3-4): UnreadAlerts = no leídas que pasaron config.
+	alertsCopy := l.engine.List()
+	unread := l.engine.UnreadCount()
 	return &Overview{
 		Health:  computeHealth(routerList, adguard),
 		WAN:     wan,
@@ -1171,6 +1271,8 @@ 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
+		VM:                ViewModelVersion,                                            // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}, nil
 }
@@ -1404,7 +1506,7 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	}
 	detail := &RouterDetail{
 		Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
-		Series: PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
+		Series:  PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
 		Clients: clients, Extras: extras,
 	}
 	if gw != nil && id == gw.ID {
@@ -1454,11 +1556,12 @@ func (l *Live) GetDevices(context.Context) []Device {
 
 // GetAlerts: copia de las alertas en memoria.
 func (l *Live) GetAlerts(context.Context) []AlertEvent {
-	l.mu.Lock()
-	defer l.mu.Unlock()
-	return append([]AlertEvent(nil), l.alerts...)
+	return l.engine.List()
 }
 
+// AlertsEngine: motor de alertas del adapter (SPEC-ALERTAS §3).
+func (l *Live) AlertsEngine() *alerts.Engine { return l.engine }
+
 // GetMetricsRows: filas para el poller (index.js:725-739).
 func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
 	l.mu.Lock()

+ 68 - 440
server-go/internal/adapters/openwrt.go

@@ -17,11 +17,10 @@ import (
 	"fmt"
 	"io"
 	"net/http"
-	"regexp"
-	"sort"
-	"strconv"
 	"strings"
 	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
 )
 
 const (
@@ -51,6 +50,18 @@ type netSample struct {
 	at     time.Time
 }
 
+// Aliases a los shapes compartidos de agent/probe: el agente nativo parsea
+// LOCALMENTE con el mismo package (misma fuente de verdad) y empuja esos
+// shapes al endpoint de ingesta (SPEC-AGENTE-PILOTO §1-2).
+type (
+	SysInfo        = probe.SysInfo
+	BoardInfo      = probe.BoardInfo
+	DhcpLease      = probe.DhcpLease
+	WirelessClient = probe.WirelessClient
+	PortState      = probe.PortState
+	PortLayout     = probe.PortLayout
+)
+
 // NewOpenWrtClient crea el cliente de un router.
 func NewOpenWrtClient(cfg RouterConfig, pool *SSHPool, user, password string) *OpenWrtClient {
 	if user == "" {
@@ -177,17 +188,6 @@ func (c *OpenWrtClient) UbusCall(object, method string, params any) (json.RawMes
 // Sonda de sistema
 // ---------------------------------------------------------------------------
 
-// BoardInfo: ubus system board (metadatos estáticos; lo cachea el live).
-type BoardInfo struct {
-	Model    string `json:"model"`
-	Hostname string `json:"hostname"`
-	System   string `json:"system"`
-	Release  struct {
-		Version     string `json:"version"`
-		Description string `json:"description"`
-	} `json:"release"`
-}
-
 // GetBoard: modelo, release, kernel → metadatos estáticos del router.
 func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
 	raw, err := c.UbusCall("system", "board", nil)
@@ -201,18 +201,6 @@ func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
 	return &b, nil
 }
 
-// SysInfo: ubus system info (uptime, memoria, load).
-type SysInfo struct {
-	Uptime float64   `json:"uptime"`
-	Load   []float64 `json:"load"`
-	Memory struct {
-		Total     float64 `json:"total"`
-		Free      float64 `json:"free"`
-		Buffered  float64 `json:"buffered"`
-		Available float64 `json:"available"`
-	} `json:"memory"`
-}
-
 // GetSysInfo: uptime, memoria, load.
 func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
 	raw, err := c.UbusCall("system", "info", nil)
@@ -232,7 +220,7 @@ func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
 
 // GetCPUPercent: CPU % por delta de /proc/stat. Primera muestra: nil.
 func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
-	out, err := c.pool.Run(c.Host, "grep '^cpu ' /proc/stat", 0)
+	out, err := c.pool.Run(c.Host, probe.CmdProcStat, 0)
 	if err != nil {
 		return nil, err
 	}
@@ -245,56 +233,24 @@ func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
 	if prev == nil {
 		return nil, nil
 	}
-	dTotal := cur.total - prev.total
-	dIdle := cur.idleAll - prev.idleAll
-	if dTotal <= 0 {
-		return nil, nil
-	}
-	v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
-	return &v, nil
+	return probe.CPUPercent(probe.CPUSample{Total: prev.total, IdleAll: prev.idleAll},
+		probe.CPUSample{Total: cur.total, IdleAll: cur.idleAll}), nil
 }
 
-// parseProcStat parsea "cpu  user nice system idle iowait irq softirq ...".
+// parseProcStat parsea "cpu  user nice system idle iowait irq softirq ..."
+// (delega en el parseo compartido con el agente nativo).
 func parseProcStat(out string) (cpuSample, error) {
-	fields := strings.Fields(strings.TrimSpace(out))
-	if len(fields) < 5 || fields[0] != "cpu" {
-		return cpuSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
-	}
-	nums := make([]float64, 0, len(fields)-1)
-	for _, f := range fields[1:] {
-		n, err := strconv.ParseFloat(f, 64)
-		if err != nil {
-			n = 0
-		}
-		nums = append(nums, n)
-	}
-	get := func(i int) float64 {
-		if i < len(nums) {
-			return nums[i]
-		}
-		return 0
-	}
-	idleAll := get(3) + get(4)                          // idle + iowait
-	nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
-	return cpuSample{total: idleAll + nonIdle, idleAll: idleAll}, nil
+	s, err := probe.ParseProcStat(out)
+	return cpuSample{total: s.Total, idleAll: s.IdleAll}, err
 }
 
 // GetTempC: °C del primer thermal zone disponible (nil si no hay).
 func (c *OpenWrtClient) GetTempC() (*int, error) {
-	out, err := c.pool.Run(c.Host,
-		`for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && cat "$f" && break; done`, 0)
+	out, err := c.pool.Run(c.Host, probe.CmdTemp, 0)
 	if err != nil {
 		return nil, err
 	}
-	milli, err := strconv.Atoi(strings.TrimSpace(out))
-	if err != nil {
-		return nil, nil
-	}
-	v := milli / 1000
-	if milli%1000 >= 500 {
-		v++
-	}
-	return &v, nil
+	return probe.ParseTempC(out), nil
 }
 
 // NetDevBps es el resultado del delta de /proc/net/dev.
@@ -303,12 +259,10 @@ type NetDevBps struct {
 	TxBps *float64
 }
 
-var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
-
 // GetNetDevBps: tráfico agregado por delta (excluye lo, bridges, ifb, wg,
 // tun/tap para no duplicar contadores). Primera muestra: null/null.
 func (c *OpenWrtClient) GetNetDevBps() (*NetDevBps, error) {
-	out, err := c.pool.Run(c.Host, "cat /proc/net/dev | tail -n +3", 0)
+	out, err := c.pool.Run(c.Host, probe.CmdNetDev, 0)
 	if err != nil {
 		return nil, err
 	}
@@ -320,119 +274,51 @@ func (c *OpenWrtClient) GetNetDevBps() (*NetDevBps, error) {
 	if prev == nil {
 		return res, nil
 	}
-	dt := now.Sub(prev.at).Seconds()
-	if dt <= 0 {
-		return res, nil
-	}
-	rxBps := round0(max0((rx - prev.rx) * 8 / dt))
-	txBps := round0(max0((tx - prev.tx) * 8 / dt))
-	res.RxBps = &rxBps
-	res.TxBps = &txBps
+	res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
 	return res, nil
 }
 
-// parseNetDev suma rx/tx de las interfaces físicas.
+// parseNetDev suma rx/tx de las interfaces físicas (compartido con el agente).
 func parseNetDev(out string) (rx, tx float64) {
-	lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
-	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
-		m := lineRe.FindStringSubmatch(line)
-		if m == nil || netdevSkipRe.MatchString(m[1]) {
-			continue
-		}
-		fields := strings.Fields(strings.TrimSpace(m[2]))
-		num := func(i int) float64 {
-			if i < len(fields) {
-				n, _ := strconv.ParseFloat(fields[i], 64)
-				return n
-			}
-			return 0
-		}
-		rx += num(0)
-		tx += num(8)
-	}
-	return rx, tx
+	return probe.ParseNetDev(out)
 }
 
-var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
-var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)/[\d.]+/[\d.]+ ms`)
-
 // GetWanLatency: ping a internet (solo gateway) → latencia avg + pérdida.
 func (c *OpenWrtClient) GetWanLatency(target string) (latency *float64, loss *float64, err error) {
 	if target == "" {
 		target = "1.1.1.1"
 	}
-	out, err := c.pool.Run(c.Host, fmt.Sprintf("ping -c 3 -W 2 %s 2>/dev/null | tail -2", target), 0)
+	out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingWan, target), 0)
 	if err != nil {
 		return nil, nil, err
 	}
-	if m := pingRTTRe.FindStringSubmatch(out); m != nil {
-		v, _ := strconv.ParseFloat(m[1], 64)
-		v = float64(int(v + 0.5))
-		latency = &v
-	}
-	if m := pingLossRe.FindStringSubmatch(out); m != nil {
-		v, _ := strconv.ParseFloat(m[1], 64)
-		loss = &v
-	}
+	latency, loss = probe.ParsePingSummary(out)
 	return latency, loss, nil
 }
 
 // GetGatewayLatency: ping corto al gateway desde un AP (avg, redondeado).
 func (c *OpenWrtClient) GetGatewayLatency(gatewayHost string) (*float64, error) {
-	out, err := c.pool.Run(c.Host, fmt.Sprintf("ping -c 2 -W 2 %s 2>/dev/null | tail -1", gatewayHost), 0)
+	out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingGateway, gatewayHost), 0)
 	if err != nil {
 		return nil, err
 	}
-	if m := pingRTTRe.FindStringSubmatch(out); m != nil {
-		v, _ := strconv.ParseFloat(m[1], 64)
-		v = float64(int(v + 0.5))
-		return &v, nil
-	}
-	return nil, nil
+	latency, _ := probe.ParsePingSummary(out)
+	return latency, nil
 }
 
 // ---------------------------------------------------------------------------
 // Clientes (DHCP + wireless)
 // ---------------------------------------------------------------------------
 
-// DhcpLease es {mac, ip, hostname} (mac en mayúsculas).
-type DhcpLease struct {
-	MAC      string
-	IP       string
-	Hostname string
-}
-
 // GetDhcpLeases: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases.
 func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
-	type leaseJSON struct {
-		MAC      string `json:"mac"`
-		IPAddr   string `json:"ip-address"`
-		IP       string `json:"ip"`
-		Hostname string `json:"hostname"`
-	}
 	raw, err := c.UbusCall("dhcp", "ipv4leases", nil)
 	if err == nil {
-		var data struct {
-			Lease  []leaseJSON `json:"lease"`
-			Leases []leaseJSON `json:"leases"`
-		}
-		if json.Unmarshal(raw, &data) == nil {
-			leases := data.Lease
-			if leases == nil {
-				leases = data.Leases
-			}
-			out := make([]DhcpLease, 0, len(leases))
-			for _, l := range leases {
-				ip := l.IPAddr
-				if ip == "" {
-					ip = l.IP
-				}
-				out = append(out, DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname})
-			}
-			return out
+		if leases, perr := probe.ParseDhcpUbus(raw); perr == nil {
+			return leases
 		}
 	}
-	out, serr := c.pool.Run(c.Host, "cat /tmp/dhcp.leases 2>/dev/null || true", 0)
+	out, serr := c.pool.Run(c.Host, probe.CmdDhcpFile, 0)
 	if serr != nil {
 		return []DhcpLease{}
 	}
@@ -442,37 +328,12 @@ func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
 // parseDhcpLeasesFile parsea /tmp/dhcp.leases:
 // <expiry> <mac> <ip> <hostname> <clientid>
 func parseDhcpLeasesFile(out string) []DhcpLease {
-	leases := []DhcpLease{}
-	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
-		if line == "" {
-			continue
-		}
-		p := strings.Fields(line)
-		if len(p) < 3 {
-			continue
-		}
-		hostname := ""
-		if len(p) > 3 && p[3] != "*" {
-			hostname = p[3]
-		}
-		leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname})
-	}
-	return leases
-}
-
-// WirelessClient es {signalDbm, band} por MAC.
-type WirelessClient struct {
-	SignalDbm int
-	Band      string
+	return probe.ParseDhcpLeasesFile(out)
 }
 
 // GetWirelessClients: iwinfo assoclist por radio → mapa MAC → cliente.
 func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
-	out, err := c.pool.Run(c.Host,
-		`for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do `+
-			`freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); `+
-			`iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do `+
-			`echo "$mac $sig $freq"; done; done`, iwinfoTimeout)
+	out, err := c.pool.Run(c.Host, probe.CmdIwinfoAssoc, iwinfoTimeout)
 	if err != nil {
 		return map[string]WirelessClient{}
 	}
@@ -481,27 +342,7 @@ func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
 
 // parseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
 func parseWirelessClients(out string) map[string]WirelessClient {
-	m := map[string]WirelessClient{}
-	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
-		if line == "" {
-			continue
-		}
-		p := strings.Fields(line)
-		if len(p) < 2 {
-			continue
-		}
-		freq := 0.0
-		if len(p) > 2 {
-			freq, _ = strconv.ParseFloat(p[2], 64)
-		}
-		sig, _ := strconv.Atoi(p[1])
-		band := "2.4 GHz"
-		if freq >= 5 {
-			band = "5 GHz"
-		}
-		m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
-	}
-	return m
+	return probe.ParseWirelessClients(out)
 }
 
 // GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
@@ -519,47 +360,16 @@ func (c *OpenWrtClient) GetWirelessUplink() (bool, error) {
 // 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
+	return probe.ParseWirelessUplink(raw)
 }
 
 // ---------------------------------------------------------------------------
 // Puertos
 // ---------------------------------------------------------------------------
 
-// PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
-type PortState struct {
-	Name  string
-	Up    bool
-	Speed string // "1 Gbps" | "100 Mbps" | "—"
-}
-
 // GetPortStates: estado de interfaces desde /sys (SSH).
 func (c *OpenWrtClient) GetPortStates() []PortState {
-	out, err := c.pool.Run(c.Host,
-		`for d in /sys/class/net/*; do i=$(basename "$d"); `+
-			`echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1)"; done`, 0)
+	out, err := c.pool.Run(c.Host, probe.CmdPortStates, 0)
 	if err != nil {
 		return []PortState{}
 	}
@@ -568,41 +378,13 @@ func (c *OpenWrtClient) GetPortStates() []PortState {
 
 // parsePortStates parsea líneas "<name> <operstate> <speed>".
 func parsePortStates(out string) []PortState {
-	ports := []PortState{}
-	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
-		if line == "" {
-			continue
-		}
-		p := strings.Fields(line)
-		if len(p) < 3 {
-			continue
-		}
-		mbps, _ := strconv.Atoi(p[2])
-		speed := "—"
-		if mbps > 0 {
-			if mbps >= 1000 {
-				speed = strconv.Itoa(mbps/1000) + " Gbps"
-			} else {
-				speed = strconv.Itoa(mbps) + " Mbps"
-			}
-		}
-		ports = append(ports, PortState{Name: p[0], Up: p[1] == "up", Speed: speed})
-	}
-	return ports
-}
-
-// PortLayout es una boca del layout canónico (/etc/board.json).
-type PortLayout struct {
-	ID    string
-	Name  string
-	Label string
-	Role  string // "lan" | "wan"
+	return probe.ParsePortStates(out)
 }
 
 // GetPortLayout: layout canónico desde /etc/board.json (estático; lo cachea
 // el live). WAN normalizado a id 'wan'.
 func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
-	out, err := c.pool.Run(c.Host, "cat /etc/board.json 2>/dev/null", 0)
+	out, err := c.pool.Run(c.Host, probe.CmdBoardJSON, 0)
 	if err != nil {
 		return nil, err
 	}
@@ -611,170 +393,61 @@ func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
 
 // parsePortLayout parsea board.json → [{id, name, label, role}].
 func parsePortLayout(out string) ([]PortLayout, error) {
-	var board struct {
-		Network struct {
-			Lan struct {
-				Ports []string `json:"ports"`
-			} `json:"lan"`
-			Wan struct {
-				Device string `json:"device"`
-			} `json:"wan"`
-		} `json:"network"`
-	}
-	if err := json.Unmarshal([]byte(out), &board); err != nil {
-		return nil, err
-	}
-	ports := []PortLayout{}
-	for _, name := range board.Network.Lan.Ports {
-		ports = append(ports, PortLayout{ID: name, Name: name, Label: strings.Replace(name, "lan", "LAN ", 1), Role: "lan"})
-	}
-	if wanDev := board.Network.Wan.Device; wanDev != "" {
-		ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
-	}
-	return ports, nil
+	return probe.ParsePortLayout(out)
 }
 
 // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
 // fallback heurístico sin config. Devuelve []EthPort listo para el detalle.
 func (c *OpenWrtClient) GetEthPorts(layout []PortLayout) []EthPort {
 	states := c.GetPortStates()
-	byName := map[string]PortState{}
-	for _, p := range states {
-		byName[p.Name] = p
-	}
+	members := map[string]bool{}
 	if len(layout) > 0 {
 		// Miembros del bridge: si "wan" está en br-lan, este router es un AP
-		brif, _ := c.pool.Run(c.Host, "ls /sys/class/net/br-lan/brif/ 2>/dev/null", 0)
-		members := map[string]bool{}
+		brif, _ := c.pool.Run(c.Host, probe.CmdBrifMembers, 0)
 		for _, l := range strings.Split(strings.TrimSpace(brif), "\n") {
 			if l != "" {
 				members[l] = true
 			}
 		}
-		lanCount := 0
-		for _, p := range layout {
-			if p.Role == "lan" {
-				lanCount++
-			}
-		}
-		ports := make([]EthPort, 0, len(layout))
-		for _, p := range layout {
-			st, ok := byName[p.Name]
-			up := ok && st.Up
-			label := p.Label
-			if p.Role == "wan" && members[p.Name] {
-				label = "LAN " + strconv.Itoa(lanCount+1)
-			}
-			ep := EthPort{ID: p.ID, Label: label, Up: up}
-			if up {
-				ep.Speed = st.Speed
-			}
-			ports = append(ports, ep)
-		}
-		return ports
-	}
-	// Fallback sin config
-	lanRe := regexp.MustCompile(`^lan\d+$`)
-	lans := []PortState{}
-	for _, p := range states {
-		if lanRe.MatchString(p.Name) {
-			lans = append(lans, p)
-		}
 	}
-	sort.Slice(lans, func(i, j int) bool { return naturalLess(lans[i].Name, lans[j].Name) })
-	ports := make([]EthPort, 0, len(lans)+1)
-	for _, p := range lans {
-		ep := EthPort{ID: p.Name, Label: strings.Replace(p.Name, "lan", "LAN ", 1), Up: p.Up}
+	return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members))
+}
+
+// ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
+func ethPortsToAdapter(in []probe.EthPort) []EthPort {
+	out := make([]EthPort, 0, len(in))
+	for _, p := range in {
+		ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up}
 		if p.Up {
 			ep.Speed = p.Speed
 		}
-		ports = append(ports, ep)
-	}
-	wanName := ""
-	if _, ok := byName["wan"]; ok {
-		wanName = "wan"
-	} else if _, ok := byName["pppoe-wan"]; ok {
-		wanName = "eth1"
-	} else if _, ok := byName["eth1"]; ok {
-		wanName = "eth1"
-	}
-	if wanName != "" {
-		st := byName[wanName]
-		ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
-		if st.Up {
-			ep.Speed = st.Speed
-		}
-		ports = append([]EthPort{ep}, ports...)
+		out = append(out, ep)
 	}
-	return ports
+	return out
 }
 
 // naturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
 func naturalLess(a, b string) bool {
-	re := regexp.MustCompile(`^(.*?)(\d+)$`)
-	ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
-	if ma != nil && mb != nil && ma[1] == mb[1] {
-		na, _ := strconv.Atoi(ma[2])
-		nb, _ := strconv.Atoi(mb[2])
-		return na < nb
-	}
-	return a < b
+	return probe.NaturalLess(a, b)
 }
 
 // GetBridgeFdb: MAC aprendida → puerto (brctl showmacs + port_no).
 func (c *OpenWrtClient) GetBridgeFdb() map[string]string {
-	out, err := c.pool.Run(c.Host,
-		`echo "==PORTS=="; for d in /sys/class/net/br-lan/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; `+
-			`echo "==MACS=="; brctl showmacs br-lan 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}'`, 0)
+	out, err := c.pool.Run(c.Host, probe.CmdBridgeFDB, 0)
 	if err != nil {
 		return map[string]string{}
 	}
 	return parseBridgeFdb(out)
 }
 
-var fdbPortRe = regexp.MustCompile(`^(lan\d+|wan)$`)
-
 // parseBridgeFdb parsea la salida ==PORTS==/==MACS== del JS.
 func parseBridgeFdb(out string) map[string]string {
-	m := map[string]string{}
-	portNames := map[string]string{}
-	section := byte(0)
-	for _, line := range strings.Split(out, "\n") {
-		t := strings.TrimSpace(line)
-		if strings.HasPrefix(t, "==PORTS==") {
-			section = 'p'
-			continue
-		}
-		if strings.HasPrefix(t, "==MACS==") {
-			section = 'm'
-			continue
-		}
-		p := strings.Fields(t)
-		if len(p) < 2 {
-			continue
-		}
-		switch section {
-		case 'p':
-			no, name := p[0], p[1]
-			if strings.HasPrefix(no, "0x") {
-				if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
-					no = strconv.FormatInt(n, 10)
-				}
-			}
-			portNames[no] = name
-		case 'm':
-			no, mac := p[0], p[1]
-			if port, ok := portNames[no]; ok && mac != "" && fdbPortRe.MatchString(port) {
-				m[strings.ToUpper(mac)] = port
-			}
-		}
-	}
-	return m
+	return probe.ParseBridgeFdb(out)
 }
 
 // GetBridgeMac: MAC del bridge br-lan (para reconocer uplinks).
 func (c *OpenWrtClient) GetBridgeMac() string {
-	out, err := c.pool.Run(c.Host, "cat /sys/class/net/br-lan/address 2>/dev/null", 0)
+	out, err := c.pool.Run(c.Host, probe.CmdBridgeMAC, 0)
 	if err != nil {
 		return ""
 	}
@@ -787,69 +460,24 @@ func (c *OpenWrtClient) GetBridgeMac() string {
 
 // GetRadios: radios activas agregadas por banda (iwinfo info + assoclist).
 func (c *OpenWrtClient) GetRadios() []Radio {
-	out, err := c.pool.Run(c.Host,
-		`for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do `+
-			`info=$(iwinfo "$i" info 2>/dev/null) || continue; `+
-			`echo "$info" | grep -q ESSID || continue; `+
-			`freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); `+
-			`ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); `+
-			`ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); `+
-			`tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); `+
-			`n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); `+
-			`echo "$freq|$ch|$ht|$tx|$n"; done`, iwinfoTimeout)
+	out, err := c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
 	if err != nil {
 		return []Radio{}
 	}
 	return parseRadios(out)
 }
 
-var nonDigitRe = regexp.MustCompile(`\D`)
-
 // parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
 func parseRadios(out string) []Radio {
-	byBand := map[string]*Radio{}
-	order := []string{}
-	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
-		if line == "" {
-			continue
-		}
-		p := strings.Split(line, "|")
-		if len(p) < 5 {
-			continue
-		}
-		freq, _ := strconv.ParseFloat(p[0], 64)
-		if freq == 0 {
-			continue
-		}
-		band := "2.4 GHz"
-		if freq >= 5 {
-			band = "5 GHz"
-		}
-		width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
-		if width == 0 {
-			width = 20
-		}
-		ch, _ := strconv.Atoi(p[1])
-		tx, _ := strconv.Atoi(p[3])
-		n, _ := strconv.Atoi(p[4])
-		if cur, ok := byBand[band]; ok {
-			cur.Clients += n
-		} else {
-			byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n}
-			order = append(order, band)
-		}
-	}
-	radios := []Radio{}
-	for _, b := range order {
-		radios = append(radios, *byBand[b])
-	}
-	return radios
+	return radiosToAdapter(probe.ParseRadios(out))
 }
 
-func round0(v float64) float64 { return float64(int64(v + 0.5)) }
-func max0(v float64) float64 {
-	if v < 0 {
-		return 0
+// radiosToAdapter convierte el shape compartido al Radio del contrato.
+func radiosToAdapter(in []probe.Radio) []Radio {
+	out := make([]Radio, 0, len(in))
+	for _, r := range in {
+		out = append(out, Radio{Name: r.Name, Channel: r.Channel,
+			WidthMhz: r.WidthMhz, PowerDbm: r.PowerDbm, Clients: r.Clients})
 	}
-	return v
+	return out
 }

+ 263 - 0
server-go/internal/adapters/topo_semantics.go

@@ -0,0 +1,263 @@
+// topo_semantics.go — Builder del modelo SEMÁNTICO de topología (SPEC-65
+// D65-3), compartido demo/live. Porta a Go la lógica de asignación de
+// anillos y enlaces de app/src/components/topology/model.ts
+// (buildTopologyModel), SIN geometría: nada de coordenadas, radios, paths
+// SVG ni flujo de paquetes — eso queda en la app.
+//
+// Paridad con model.ts (canon demo fijada en topo_semantics_test.go):
+//   - El switch gestionado existe como Device Y como distnode managed: se
+//     excluye de chips/enlaces cualquier Device cuya MAC coincida con la
+//     chassis-MAC de un distnode managed (D1).
+//   - Anclaje al gateway: cableado SIN evidencia (ni attachTo ni puerto FDB)
+//     cuelga del gateway, no de su AP.
+//   - Solo los distnodes inferred|managed son hubs de enlaces "dist"; el
+//     hipervisor enlaza vía su Device host (sus CTs/VMs cuelgan del host).
+//   - Peers WG: los activos que exceden las 4 coordenadas canónicas no
+//     generan enlace (la app los agrupa en su chip "+N" de peers).
+package adapters
+
+import "strings"
+
+// Capacidad de los anillos canónicos de model.ts (GATEWAY_RINGS 5+8,
+// AP_RINGS 7+13): el límite de chips visibles por anillo que aplica la app.
+// HiddenPeers = clientes del anillo - visibles con este mismo límite.
+const (
+	topoGatewayRingCap = 13
+	topoAPRingCap      = 20
+)
+
+// maxTopoPeerChips: coordenadas canónicas de peers WG en model.ts (4); los
+// activos que exceden no se trazan como túnel propio.
+const maxTopoPeerChips = 4
+
+// BuildTopoSemantics deriva enlaces, anillos y peers ocultos del mismo bundle
+// que hoy consume la app (routers, devices, wireguard, distributionNodes).
+func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode) *TopoSemantics {
+	sem := &TopoSemantics{Links: []TopoLink{}, Rings: map[string][]string{}}
+	if len(routers) == 0 {
+		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 := routers[0]
+	for _, r := range routers {
+		if r.RoleBadge == "Principal" {
+			gateway = r
+			break
+		}
+	}
+	aps := make([]Router, 0, 3)
+	for _, r := range routers {
+		if r.ID == gateway.ID {
+			continue
+		}
+		if len(aps) >= 3 {
+			break
+		}
+		aps = append(aps, r)
+	}
+	routerNodes := append([]Router{gateway}, aps...)
+	inRouter := map[string]bool{}
+	for _, r := range routerNodes {
+		inRouter[r.ID] = true
+	}
+
+	// D1: los Devices cuya MAC es la chassis-MAC de un distnode managed se
+	// representan SOLO como nodo managed (sin chip ni enlaces propios).
+	managedMacs := map[string]bool{}
+	for _, n := range dists {
+		if n.Kind == "managed" && n.Mac != "" {
+			managedMacs[strings.ToUpper(n.Mac)] = true
+		}
+	}
+	online := make([]Device, 0, len(devices))
+	for _, d := range devices {
+		if !d.Online || managedMacs[strings.ToUpper(d.MAC)] {
+			continue
+		}
+		online = append(online, d)
+	}
+	deviceByID := map[string]Device{}
+	for _, d := range online {
+		deviceByID[d.ID] = d
+	}
+	distByID := map[string]DistributionNode{}
+	for _, n := range dists {
+		distByID[n.ID] = n
+	}
+
+	// hubOf: attachTo (si resuelve a router/distnode/device conocido) o su
+	// router; un cableado SIN evidencia (ni attachTo ni puerto FDB) se ancla
+	// al GATEWAY (regla 2-Ago-2026 de model.ts).
+	hubOf := func(d Device) string {
+		if d.AttachTo != "" {
+			if inRouter[d.AttachTo] {
+				return d.AttachTo
+			}
+			if _, ok := distByID[d.AttachTo]; ok {
+				return d.AttachTo
+			}
+			if _, ok := deviceByID[d.AttachTo]; ok {
+				return d.AttachTo
+			}
+		}
+		if d.Band == "cable" && d.Port == "" {
+			return gateway.ID
+		}
+		return d.RouterID
+	}
+
+	// deviceHubs: dispositivos con hijos propios (switch gestionado,
+	// hipervisor), en orden de descubrimiento (orden del dataset, como el
+	// Set de JS). hypervisorHosts: hosts con distnode kind=hypervisor.
+	var deviceHubOrder []string
+	deviceHubs := map[string]bool{}
+	for _, d := range online {
+		if d.AttachTo == "" || deviceHubs[d.AttachTo] {
+			continue
+		}
+		if _, ok := deviceByID[d.AttachTo]; ok {
+			deviceHubs[d.AttachTo] = true
+			deviceHubOrder = append(deviceHubOrder, d.AttachTo)
+		}
+	}
+	hypervisorHosts := map[string]bool{}
+	for _, n := range dists {
+		if n.Kind == "hypervisor" && n.HostDeviceID != "" {
+			hypervisorHosts[n.HostDeviceID] = true
+		}
+	}
+
+	wiredLink := func(from string, d Device) {
+		sem.Links = append(sem.Links, TopoLink{From: from, To: d.ID, Kind: "wired", Port: d.Port})
+	}
+
+	// -- enlaces (mismo orden que model.ts) --------------------------------
+	sem.Links = append(sem.Links, TopoLink{From: "internet", To: gateway.ID, Kind: "wan"})
+	for _, ap := range aps {
+		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)
+		}
+		sem.Links = append(sem.Links, l)
+	}
+	// router → distnode (solo inferred|managed son hubs propios en el mapa)
+	for _, rn := range routerNodes {
+		for _, dn := range dists {
+			if dn.RouterID != rn.ID || (dn.Kind != "inferred" && dn.Kind != "managed") {
+				continue
+			}
+			sem.Links = append(sem.Links, TopoLink{From: rn.ID, To: dn.ID, Kind: "dist", Port: dn.Port})
+		}
+	}
+	// cableados directos del router (sin los device-hubs, que enlazan después)
+	for _, rn := range routerNodes {
+		for _, d := range online {
+			if d.Band != "cable" || deviceHubs[d.ID] || hubOf(d) != rn.ID {
+				continue
+			}
+			wiredLink(rn.ID, d)
+		}
+	}
+	// hijos cableados de device-hubs NO hipervisor (los CTs van en su fase)
+	for _, hubID := range deviceHubOrder {
+		if hypervisorHosts[hubID] {
+			continue
+		}
+		for _, d := range online {
+			if d.Band != "cable" || hubOf(d) != hubID {
+				continue
+			}
+			wiredLink(hubID, d)
+		}
+	}
+	// el cable del propio hub (chip con hijos; el hipervisor entre ellos)
+	for _, hubID := range deviceHubOrder {
+		wiredLink(hubOf(deviceByID[hubID]), deviceByID[hubID])
+	}
+	// hijos cableados de distnodes (abanico alrededor del círculo)
+	for _, rn := range routerNodes {
+		for _, dn := range dists {
+			if dn.RouterID != rn.ID || (dn.Kind != "inferred" && dn.Kind != "managed") {
+				continue
+			}
+			for _, d := range online {
+				if d.Band != "cable" || hubOf(d) != dn.ID {
+					continue
+				}
+				wiredLink(dn.ID, d)
+			}
+		}
+	}
+	// CTs/VMs anidados bajo el host hipervisor (línea desde el host)
+	for _, dn := range dists {
+		if dn.Kind != "hypervisor" || dn.HostDeviceID == "" {
+			continue
+		}
+		if _, ok := deviceByID[dn.HostDeviceID]; !ok {
+			continue
+		}
+		for _, d := range online {
+			if hubOf(d) != dn.HostDeviceID {
+				continue
+			}
+			wiredLink(dn.HostDeviceID, d)
+		}
+	}
+	// túneles WG: peers activos con coordenada canónica (máx 4)
+	n := 0
+	for _, p := range wg.Peers {
+		if !p.Active {
+			continue
+		}
+		if n >= maxTopoPeerChips {
+			break
+		}
+		sem.Links = append(sem.Links, TopoLink{From: "peer-" + p.ID, To: "internet", Kind: "wg"})
+		n++
+	}
+
+	// -- anillos por router --------------------------------------------------
+	// Anillo = chips que cuelgan DIRECTAMENTE del router (cableados directos,
+	// incluidos los device-hubs, y wifi). Orden SPEC-65: cableados primero,
+	// luego por banda 5GHz/2.4GHz, estable (orden del dataset).
+	for _, rn := range routerNodes {
+		var wired, g5, g24, other []string
+		for _, d := range online {
+			if hubOf(d) != rn.ID {
+				continue
+			}
+			switch d.Band {
+			case "cable":
+				wired = append(wired, d.ID)
+			case "5 GHz":
+				g5 = append(g5, d.ID)
+			case "2.4 GHz":
+				g24 = append(g24, d.ID)
+			default:
+				other = append(other, d.ID)
+			}
+		}
+		ring := make([]string, 0, len(wired)+len(g5)+len(g24)+len(other))
+		ring = append(ring, wired...)
+		ring = append(ring, g5...)
+		ring = append(ring, g24...)
+		ring = append(ring, other...)
+		if len(ring) == 0 {
+			continue
+		}
+		sem.Rings[rn.ID] = ring
+		cap := topoAPRingCap
+		if rn.ID == gateway.ID {
+			cap = topoGatewayRingCap
+		}
+		if hidden := len(ring) - cap; hidden > 0 {
+			if sem.HiddenPeers == nil {
+				sem.HiddenPeers = map[string]int{}
+			}
+			sem.HiddenPeers[rn.ID] = hidden
+		}
+	}
+	return sem
+}

+ 150 - 0
server-go/internal/adapters/topo_semantics_test.go

@@ -0,0 +1,150 @@
+package adapters
+
+import (
+	"reflect"
+	"testing"
+)
+
+// Golden test de la topología semántica (SPEC-65 D65-3): para el canon demo,
+// los links/rings/hiddenPeers del builder Go deben coincidir con lo que
+// produce hoy buildTopologyModel de app/src/components/topology/model.ts
+// (revisado a mano contra model.ts @ audit/v2-main):
+//   - wan + 3 uplinks (living/estudio con puerto LLDP del gateway; patio wifi)
+//   - 2 enlaces dist (switch inferido del gateway y GS308E managed del Salón)
+//   - cableados directos: nas/mac-mini/hue-hub anclados al GATEWAY (mac-mini y
+//     hue-hub son de Estudio pero no tienen evidencia: ni attachTo ni puerto
+//     FDB → regla de anclaje al gateway), ps5 al Salón, pve (host hipervisor)
+//   - 8 clientes tras el switch inferido + 3 tras el GS308E + 10 CTs del pve
+//   - 2 túneles WG (los 2 peers activos)
+//   - El GS308E (switch-netgear) NO genera chips/enlaces: su MAC es la
+//     chassis-MAC del distnode managed (D1)
+//   - Anillos: cableados primero, luego 5GHz, luego 2.4GHz (orden dataset)
+//   - hiddenPeers ausente: todos los anillos bajo el límite de chips visibles
+//     de la app (gateway 13, AP 20)
+func TestTopoSemanticsGoldenCanon(t *testing.T) {
+	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes())
+
+	wantLinks := []TopoLink{
+		{From: "internet", To: "flint2", Kind: "wan"},
+		{From: "flint2", To: "living", Kind: "uplink", Port: "lan1"},
+		{From: "flint2", To: "estudio", Kind: "uplink", Port: "lan2"},
+		{From: "flint2", To: "patio", Kind: "uplink"},
+		{From: "flint2", To: "dist-flint2-lan3", Kind: "dist", Port: "lan3"},
+		{From: "living", To: "dist-living-lan3", Kind: "dist", Port: "lan3"},
+		{From: "flint2", To: "nas-synology", Kind: "wired", Port: "lan4"},
+		{From: "flint2", To: "mac-mini", Kind: "wired"},
+		{From: "flint2", To: "hue-hub", Kind: "wired"},
+		{From: "living", To: "ps5", Kind: "wired", Port: "lan1"},
+		{From: "flint2", To: "pve", Kind: "wired", Port: "lan5"},
+		{From: "dist-flint2-lan3", To: "pc-sobremesa", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "raspberry-pi", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "tv-salon-cable", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "impresora-hp", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "xbox-one", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "receptor-av", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "deco-orange", Kind: "wired"},
+		{From: "dist-flint2-lan3", To: "pc-invitado", Kind: "wired"},
+		{From: "dist-living-lan3", To: "xbox-series-s", Kind: "wired"},
+		{From: "dist-living-lan3", To: "apple-tv-4k", Kind: "wired"},
+		{From: "dist-living-lan3", To: "receptor-denon", Kind: "wired"},
+		{From: "pve", To: "ct-pihole", Kind: "wired"},
+		{From: "pve", To: "ct-home-assistant", Kind: "wired"},
+		{From: "pve", To: "ct-nextcloud", Kind: "wired"},
+		{From: "pve", To: "ct-jellyfin", Kind: "wired"},
+		{From: "pve", To: "ct-immich", Kind: "wired"},
+		{From: "pve", To: "ct-gitea", Kind: "wired"},
+		{From: "pve", To: "ct-uptime-kuma", Kind: "wired"},
+		{From: "pve", To: "ct-adguard-sync", Kind: "wired"},
+		{From: "pve", To: "ct-postgres", Kind: "wired"},
+		{From: "pve", To: "ct-redis", Kind: "wired"},
+		{From: "peer-pixel-8-pro", To: "internet", Kind: "wg"},
+		{From: "peer-macbook-air", To: "internet", Kind: "wg"},
+	}
+	if !reflect.DeepEqual(sem.Links, wantLinks) {
+		t.Fatalf("links:\n got: %+v\nwant: %+v", sem.Links, wantLinks)
+	}
+
+	wantRings := map[string][]string{
+		"flint2": {"nas-synology", "mac-mini", "hue-hub", "pve",
+			"pixel-8-pro", "iphone-ana", "macbook-pro", "pixel-7",
+			"timbre-nest", "enchufe-lavadora"},
+		"living": {"ps5",
+			"imac-salon", "tv-samsung", "galaxy-tab-s9", "chromecast", "homepod-mini",
+			"galaxy-s23", "nintendo-switch", "portatil-invitado",
+			"bombilla-1", "bombilla-2", "bombilla-3", "bombilla-4", "bombilla-5",
+			"bombilla-6", "echo-dot"},
+		"estudio": {"macbook-air", "ipad-pro", "iphone-trabajo",
+			"nest-mini", "enchufe-ventilador", "sonos-one"},
+		"patio": {"robot-aspirador", "camara-porche", "camara-jardin",
+			"sensor-riego", "enchufe-calefactor"},
+	}
+	if !reflect.DeepEqual(sem.Rings, wantRings) {
+		t.Fatalf("rings:\n got: %+v\nwant: %+v", sem.Rings, wantRings)
+	}
+
+	// Todos los anillos bajo el límite de chips visibles → sin "+N".
+	if len(sem.HiddenPeers) != 0 {
+		t.Fatalf("hiddenPeers debería estar vacío en el canon: %+v", sem.HiddenPeers)
+	}
+}
+
+// HiddenPeers: superado el límite de chips visibles del anillo (gateway 13,
+// AP 20), el exceso se reporta como "+N" por router.
+func TestTopoSemanticsHiddenPeers(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", RoleBadge: "Principal"},
+		{ID: "ap", RoleBadge: "AP"},
+	}
+	devices := make([]Device, 0, 15+22)
+	for i := 0; i < 15; i++ {
+		devices = append(devices, Device{
+			ID: "gw-" + string(rune('a'+i)), MAC: "00:00:00:00:01:" + string(rune('A'+i)),
+			RouterID: "gw", Band: "5 GHz", Online: true,
+		})
+	}
+	for i := 0; i < 22; i++ {
+		devices = append(devices, Device{
+			ID: "ap-" + string(rune('a'+i)), MAC: "00:00:00:00:02:" + string(rune('A'+i)),
+			RouterID: "ap", Band: "2.4 GHz", Online: true,
+		})
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil)
+	want := map[string]int{"gw": 2, "ap": 2} // 15-13 y 22-20
+	if !reflect.DeepEqual(sem.HiddenPeers, want) {
+		t.Fatalf("hiddenPeers: got %+v want %+v", sem.HiddenPeers, want)
+	}
+	if got := len(sem.Rings["gw"]); got != 15 {
+		t.Fatalf("el anillo conserva TODOS los clientes (visibles+ocultos): %d", got)
+	}
+}
+
+// El overview demo lleva topology y vm SIEMPRE (SPEC-65 D65-3/D65-4).
+func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
+	d := NewDemo()
+	ov, err := d.GetOverview(t.Context())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if ov.VM != ViewModelVersion {
+		t.Fatalf("overview.vm=%d, ViewModelVersion=%d", ov.VM, ViewModelVersion)
+	}
+	if ov.Topology == nil {
+		t.Fatal("overview.Topology ausente en demo")
+	}
+	// Mismo resultado que el builder puro sobre el canon.
+	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes())
+	if !reflect.DeepEqual(ov.Topology, want) {
+		t.Fatalf("overview.Topology != builder canon:\n got: %+v\nwant: %+v", ov.Topology, want)
+	}
+}
+
+// Sin routers: semántica vacía pero no nil (la app cae a su cálculo propio).
+func TestTopoSemanticsSinRouters(t *testing.T) {
+	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil)
+	if sem == nil || sem.Links == nil || sem.Rings == nil {
+		t.Fatalf("semántica vacía debe tener links/rings no-nil: %+v", sem)
+	}
+	if len(sem.Links) != 0 || len(sem.Rings) != 0 {
+		t.Fatalf("sin routers no hay links ni anillos: %+v", sem)
+	}
+}

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

@@ -167,9 +167,13 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 						ID: id, Kind: "hypervisor", RouterID: routerID, Port: port,
 						MacCount: len(kept), HostDeviceID: devices[hidx].ID, Name: devices[hidx].Name,
 					})
+					// SPEC-65 D65-2: sellado de infra — host = hypervisor,
+					// las MACs con OUI de hipervisor anidadas bajo él = ct.
+					devices[hidx].Infra = "hypervisor"
 					for _, mac := range vmMACs {
 						if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
 							devices[idx].AttachTo = devices[hidx].ID
+							devices[idx].Infra = "ct"
 						}
 					}
 					continue
@@ -183,9 +187,22 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 				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(),
+					MacCount: len(kept), Name: nb.displayName(), Ip: nb.Mgmt,
+					Mac: nb.ChassisMac, Lldp: nb.info(),
 				})
+				// SPEC-65 D65-2: el vecino LLDP managed que existe como Device
+				// queda sellado como managed-switch.
+				if idx, ok := byMAC[nb.ChassisMac]; ok {
+					devices[idx].Infra = "managed-switch"
+				}
 				for _, mac := range kept {
+					// SPEC-CANON D2: la chassis-MAC del propio switch NO cuelga
+					// de su propio nodo — su Device queda con attachTo al
+					// router + port de uplink (el switch es Device Y nodo a la
+					// vez, sin self-attach ni doble conteo).
+					if mac == nb.ChassisMac {
+						continue
+					}
 					if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
 						devices[idx].AttachTo = id
 					}

+ 23 - 6
server-go/internal/adapters/topology_test.go

@@ -209,8 +209,10 @@ func gs308eNeighbor() []LldpNeighbor {
 }
 
 // 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.
+// las aprendidas → nodo "managed" con Name/Ip/Mac/Lldp; los equipos cuelgan
+// de él igual que del inferido. SPEC-CANON D1/D2: el switch existe A LA VEZ
+// como Device (con Lldp, attachTo al router, port de uplink) y como nodo
+// managed (con Mac = chassis-MAC), y NUNCA cuelga de su propio nodo.
 func TestInferTopologySwitchManagedLldp(t *testing.T) {
 	polled := map[string]*routerPolled{
 		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
@@ -237,17 +239,32 @@ func TestInferTopologySwitchManagedLldp(t *testing.T) {
 	if dn.Name != "GS308E" || dn.Ip != "192.168.8.13" {
 		t.Fatalf("name/ip: %+v", dn)
 	}
+	// D1: el nodo managed lleva la chassis-MAC del switch (la app la usa para
+	// excluir su chip del mapa).
+	if dn.Mac != "28:C6:8E:1D:90:44" {
+		t.Fatalf("mac del nodo managed: %q", dn.Mac)
+	}
 	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 {
+	// D2: los clientes tras el switch cuelgan del nodo managed…
+	for _, d := range devices[1:] {
 		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)
+	// …pero el propio switch NO cuelga de su propio nodo: sigue existiendo
+	// como Device identificado (Lldp), con su puerto de uplink y attachTo al
+	// router (vacío = router por defecto).
+	sw := devices[0]
+	if sw.AttachTo != "" {
+		t.Fatalf("el switch NO debe colgar de su propio nodo: attachTo=%q", sw.AttachTo)
+	}
+	if sw.Port != "lan3" {
+		t.Fatalf("puerto de uplink del switch: %q", sw.Port)
+	}
+	if sw.Lldp == nil || sw.Lldp.Chassis != "GS308E" {
+		t.Fatalf("Device.Lldp del switch: %+v", sw.Lldp)
 	}
 }
 

+ 65 - 25
server-go/internal/adapters/types.go

@@ -11,7 +11,11 @@
 //   - Epochs: ms en DB, SEGUNDOS en Overview.Ts.
 package adapters
 
-import "context"
+import (
+	"context"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
 
 // ---------------------------------------------------------------------------
 // Bloques del Overview (SPEC §7.8)
@@ -169,6 +173,11 @@ type Device struct {
 	// AttachTo: hub del que cuelga en el mapa (router por defecto; id de
 	// DistributionNode inferido o de otro Device — hipervisor/switch).
 	AttachTo string `json:"attachTo,omitempty"`
+	// Infra: rol de infraestructura sellado server-side (Fase 6.5). La app NO
+	// infiere: pinta badge si viene. "hypervisor" (host Proxmox/VMware/…),
+	// "ct" (CT/VM anidado bajo hipervisor), "managed-switch" (switch con gestión
+	// identificado por LLDP — hoy switch-netgear).
+	Infra string `json:"infra,omitempty"` // "hypervisor"|"ct"|"managed-switch"
 	// --- extras demo (omitempty = ausentes en live) ---
 	Hostname     string `json:"hostname,omitempty"`
 	DHCPLease    string `json:"dhcpLease,omitempty"`
@@ -199,27 +208,50 @@ type LldpInfo struct {
 // 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"|"managed"
-	RouterID string    `json:"routerId"`
-	Port     string    `json:"port"`
-	MacCount int       `json:"macCount"`
+	ID       string `json:"id"`
+	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"`
+	HostDeviceID string `json:"hostDeviceId,omitempty"`
+	Name         string `json:"name,omitempty"`
+	Ip           string `json:"ip,omitempty"` // managed: mgmt-ip anunciada por LLDP
+	// Mac: chassis-MAC del vecino cuando kind='managed' (SPEC-CANON D1). La
+	// app la usa para excluir del mapa el chip del Device del switch (que
+	// existe como Device Y como nodo managed, sin duplicar el render).
+	Mac  string    `json:"mac,omitempty"`
+	Lldp *LldpInfo `json:"lldp,omitempty"`
 }
 
-// AlertEvent (máx 100 en memoria, más recientes primero).
-type AlertEvent struct {
-	ID          string `json:"id"`
-	Severity    string `json:"severity"` // "warn"|"critical"|"info"|"ok"
-	Title       string `json:"title"`
-	Description string `json:"description"`
-	Time        string `json:"time"` // relativo ES ("hace 12 min") — el frontend lo muestra tal cual
-	Read        bool   `json:"read"`
-	RouterID    string `json:"routerId"`
+// AlertEvent vive en internal/alerts (SPEC-ALERTAS §1: Category/Urgent/Ts);
+// el alias mantiene el contrato adapters.AlertEvent para handlers y tests.
+type AlertEvent = alerts.AlertEvent
+
+// ViewModelVersion es la versión del view-model de presentación (SPEC-65
+// D65-4). La API es un view-model versionado: un cliente debe rechazar/avisar
+// si `vm` supera la versión que soporta. Bump = cualquier cambio incompatible
+// de forma (añadir campos opcionales NO bumpea).
+const ViewModelVersion = 1
+
+// TopoSemantics: modelo semántico de la topología (Fase 6.5). La app conserva
+// SOLO la geometría de píxeles; asignaciones de anillo, enlaces y conteos de
+// peers ocultos llegan calculados.
+type TopoSemantics struct {
+	Links []TopoLink `json:"links"`
+	// Rings: routerId → ids de Device en su anillo (orden: cableados primero,
+	// luego por banda 5GHz/2.4GHz, estable).
+	Rings map[string][]string `json:"rings"`
+	// HiddenPeers: routerId → nº de clientes no pintados como chip (el "+N").
+	HiddenPeers map[string]int `json:"hiddenPeers,omitempty"`
+}
+
+// TopoLink es un enlace semántico del mapa (sin geometría).
+type TopoLink struct {
+	From string `json:"from"` // id: router | device | distnode | "internet" | "peer-<wgPeerId>"
+	To   string `json:"to"`
+	Kind string `json:"kind"`           // "wan"|"uplink"|"wired"|"dist"|"wg"
+	Port string `json:"port,omitempty"` // puerto físico si aplica
 }
 
 // Overview es el bundle completo (SPEC §7.8). Ts en SEGUNDOS.
@@ -238,7 +270,12 @@ type Overview struct {
 	// v5). Vacío/ausente si aún no hay datos FDB: el mapa cuelga los
 	// cableados del router (degradación amable).
 	DistributionNodes []DistributionNode `json:"distributionNodes,omitempty"`
-	Ts                int64              `json:"ts"` // floor(now/1000) — SEGUNDOS
+	// 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"`
+	// VM: versión del view-model (SPEC-65 D65-4). SIEMPRE presente.
+	VM int `json:"vm"`
+	Ts int64 `json:"ts"` // floor(now/1000) — SEGUNDOS
 }
 
 // ---------------------------------------------------------------------------
@@ -299,12 +336,12 @@ type RouterDetail struct {
 	Clients  []Device   `json:"clients"`
 	Extras   any        `json:"extras"`
 	// --- solo gateway (demo: solo flint2; live: solo el gateway) ---
-	Adguard          *AdGuardStats  `json:"adguard,omitempty"`
+	Adguard          *AdGuardStats   `json:"adguard,omitempty"`
 	Wireguard        *WireGuardStats `json:"wireguard,omitempty"`
-	AdguardSeries24h []AdGuardHour  `json:"adguardSeries24h,omitempty"`
-	WANLatency       *WANLatency    `json:"wanLatency,omitempty"`
-	WGPeerExtras     any            `json:"wgPeerExtras,omitempty"`
-	WGTotals30d      *WGTotals      `json:"wgTotals30d,omitempty"`
+	AdguardSeries24h []AdGuardHour   `json:"adguardSeries24h,omitempty"`
+	WANLatency       *WANLatency     `json:"wanLatency,omitempty"`
+	WGPeerExtras     any             `json:"wgPeerExtras,omitempty"`
+	WGTotals30d      *WGTotals       `json:"wgTotals30d,omitempty"`
 }
 
 // AdGuardHour es un punto de la serie horaria AdGuard del detalle del gateway
@@ -436,6 +473,9 @@ type Snapshotter interface {
 	GetDevices(ctx context.Context) []Device
 	// GetAlerts lista las alertas (más recientes primero, máx 100).
 	GetAlerts(ctx context.Context) []AlertEvent
+	// AlertsEngine expone el motor de alertas (SPEC-ALERTAS §3): config,
+	// read-state y UnreadCount viven ahí (server truth).
+	AlertsEngine() *alerts.Engine
 	// GetMetricsRows devuelve las filas para la tabla metrics del tick
 	// actual (el poller solo persiste si Mode() != "demo").
 	GetMetricsRows(ctx context.Context) []MetricsRow

+ 355 - 0
server-go/internal/alerts/alerts.go

@@ -0,0 +1,355 @@
+// Package alerts — motor de alertas (SPEC-ALERTAS §1-3): dueño de la lista
+// de eventos (máx 100, más recientes primero), config por categoría con 3
+// niveles (none/urgent/all) aplicada EN CREACIÓN, dedup de 5 min por
+// (category,title,routerId), read-state en servidor y hook Notifier para el
+// push (Bloque C; nil = no-op).
+//
+// Persistencia: tabla kv (misma DB que el resto del servidor):
+//   - alerts.config.v1: JSON {"router":"urgent",...} (6 claves, defaults).
+//   - alerts.read.v1:   JSON array de IDs leídos (cap 200, FIFO).
+package alerts
+
+import (
+	"encoding/json"
+	"fmt"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// Categorías (taxonomía exacta del SPEC §1).
+const (
+	CatRouter   = "router"
+	CatInternet = "internet"
+	CatClients  = "clients"
+	CatSignal   = "signal"
+	CatVPN      = "vpn"
+	CatSystem   = "system"
+)
+
+// Categories lista las 6 categorías válidas (orden estable para mensajes).
+var Categories = []string{CatRouter, CatInternet, CatClients, CatSignal, CatVPN, CatSystem}
+
+// Niveles de configuración por categoría (SPEC §2).
+const (
+	LevelNone   = "none"   // el evento se descarta (no se guarda, no cuenta, no empuja)
+	LevelUrgent = "urgent" // solo pasan eventos Urgent=true
+	LevelAll    = "all"    // pasan todos (los urgentes además notifican)
+)
+
+var levels = map[string]bool{LevelNone: true, LevelUrgent: true, LevelAll: true}
+
+// Claves kv y límites (SPEC §2-3).
+const (
+	configKey   = "alerts.config.v1"
+	readKey     = "alerts.read.v1"
+	MaxEvents   = 100
+	MaxReadIDs  = 200
+	DedupWindow = 5 * time.Minute
+)
+
+// AlertEvent (máx 100 en memoria, más recientes primero).
+type AlertEvent struct {
+	ID          string `json:"id"`
+	Category    string `json:"category"` // taxonomía SPEC §1
+	Urgent      bool   `json:"urgent"`   // "rompe silencio" (push + badge)
+	Severity    string `json:"severity"` // display: "warn"|"critical"|"info"|"ok"
+	Title       string `json:"title"`
+	Description string `json:"description"`
+	Time        string `json:"time"` // LEGADO display; se sigue rellenando
+	Ts          int64  `json:"ts"`   // unix SEGUNDOS; el frontend calcula el relativo
+	Read        bool   `json:"read"`
+	RouterID    string `json:"routerId"`
+}
+
+// Notifier es el hook de push (Bloque C lo implementa; ahora nil/no-op).
+// Se llama SOLO para eventos que pasan config Y son Urgent=true.
+type Notifier interface {
+	Notify(ev AlertEvent)
+}
+
+// DefaultConfig devuelve una copia de los defaults del SPEC §2.
+func DefaultConfig() map[string]string {
+	return map[string]string{
+		CatRouter:   LevelUrgent,
+		CatInternet: LevelUrgent,
+		CatClients:  LevelUrgent,
+		CatSignal:   LevelNone,
+		CatVPN:      LevelNone,
+		CatSystem:   LevelAll,
+	}
+}
+
+// Engine es el motor: aplica config/dedup/cap en Emit y guarda el read-state.
+// Seguro para uso concurrente (los adapters emiten desde varios goroutines).
+type Engine struct {
+	mu       sync.Mutex
+	db       *db.DB // nil → solo memoria (tests)
+	notifier Notifier
+	now      func() time.Time
+
+	cfg     map[string]string
+	list    []AlertEvent
+	dedup   map[string]int64 // key (cat|title|routerId) → último emit (unix ms)
+	readSet map[string]bool
+	readOrd []string // FIFO de IDs (cap 200) para podar readSet
+}
+
+// New crea el motor cargando config y read-state de kv (si db != nil).
+func New(d *db.DB, n Notifier) *Engine {
+	e := &Engine{
+		db:       d,
+		notifier: n,
+		now:      time.Now,
+		cfg:      DefaultConfig(),
+		dedup:    map[string]int64{},
+		readSet:  map[string]bool{},
+	}
+	if d != nil {
+		var raw string
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", configKey).Scan(&raw); err == nil {
+			saved := map[string]string{}
+			if json.Unmarshal([]byte(raw), &saved) == nil {
+				for _, cat := range Categories {
+					if lv, ok := saved[cat]; ok && levels[lv] {
+						e.cfg[cat] = lv
+					}
+				}
+			}
+		}
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", readKey).Scan(&raw); err == nil {
+			ids := []string{}
+			if json.Unmarshal([]byte(raw), &ids) == nil {
+				for _, id := range ids {
+					if id != "" && !e.readSet[id] {
+						e.readSet[id] = true
+						e.readOrd = append(e.readOrd, id)
+					}
+				}
+			}
+		}
+	}
+	return e
+}
+
+// SetNotifier sustituye el hook Notifier (wiring de Bloque C desde main;
+// nil = no-op). Seguro en caliente: Emit lo lee bajo el mismo mutex.
+func (e *Engine) SetNotifier(n Notifier) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	e.notifier = n
+}
+
+// SetClock sustituye el reloj (solo tests).
+func (e *Engine) SetClock(f func() time.Time) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	e.now = f
+}
+
+// Config devuelve una copia de la config efectiva (siempre las 6 claves).
+func (e *Engine) Config() map[string]string {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	out := make(map[string]string, len(e.cfg))
+	for k, v := range e.cfg {
+		out[k] = v
+	}
+	return out
+}
+
+// SetConfig aplica un parche parcial {"signal":"all"}: valida categorías y
+// niveles (error → 400 en la API), fusiona y persiste en kv.
+func (e *Engine) SetConfig(patch map[string]string) error {
+	badCats, badVals := []string{}, []string{}
+	for k, v := range patch {
+		if !contains(Categories, k) {
+			badCats = append(badCats, k)
+		} else if !levels[v] {
+			badVals = append(badVals, fmt.Sprintf("%s=%q", k, v))
+		}
+	}
+	if len(badCats) > 0 || len(badVals) > 0 {
+		sort.Strings(badCats)
+		sort.Strings(badVals)
+		parts := []string{}
+		if len(badCats) > 0 {
+			parts = append(parts, "categorías desconocidas: "+strings.Join(badCats, ", "))
+		}
+		if len(badVals) > 0 {
+			parts = append(parts, "niveles inválidos: "+strings.Join(badVals, ", "))
+		}
+		return fmt.Errorf("config inválida (%s)", strings.Join(parts, "; "))
+	}
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	for k, v := range patch {
+		e.cfg[k] = v
+	}
+	e.saveConfigLocked()
+	return nil
+}
+
+// Emit aplica la semántica none/urgent/all EN CREACIÓN, el dedup de 5 min y
+// el cap de 100; devuelve true si el evento pasó (se guardó). Los urgentes
+// que pasan disparan el Notifier (hook de Bloque C).
+func (e *Engine) Emit(ev AlertEvent) bool {
+	e.mu.Lock()
+	level, known := e.cfg[ev.Category]
+	if known {
+		if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
+			e.mu.Unlock()
+			return false
+		}
+	}
+	// Categoría desconocida: pasa (la validación estricta es de SetConfig).
+	now := e.now()
+	key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
+	if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
+		e.mu.Unlock()
+		return false
+	}
+	e.dedup[key] = now.UnixMilli()
+	if ev.Ts == 0 {
+		ev.Ts = now.Unix()
+	}
+	if ev.Time == "" {
+		ev.Time = "ahora mismo"
+	}
+	ev.Read = false
+	e.list = append([]AlertEvent{ev}, e.list...)
+	if len(e.list) > MaxEvents {
+		e.list = e.list[:MaxEvents]
+	}
+	n := e.notifier
+	e.mu.Unlock()
+	if n != nil && ev.Urgent {
+		n.Notify(ev)
+	}
+	return true
+}
+
+// Seed inserta un evento histórico (arranque del modo demo) SIN aplicar el
+// filtro de config — el SPEC §5 exige que las 5 canon sobrevivan con los
+// defaults aunque "vpn:none"/"clients:urgent" descartarían 2 en creación —.
+// Mantiene dedup, cap y Read=false; NO dispara el Notifier (son historia).
+// Devuelve true si se guardó.
+func (e *Engine) Seed(ev AlertEvent) bool {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	now := e.now()
+	key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
+	if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
+		return false
+	}
+	e.dedup[key] = now.UnixMilli()
+	if ev.Ts == 0 {
+		ev.Ts = now.Unix()
+	}
+	if ev.Time == "" {
+		ev.Time = "ahora mismo"
+	}
+	ev.Read = false
+	e.list = append([]AlertEvent{ev}, e.list...)
+	if len(e.list) > MaxEvents {
+		e.list = e.list[:MaxEvents]
+	}
+	return true
+}
+
+// List devuelve copia de los eventos (más recientes primero) con Read
+// aplicado desde el read-set del servidor.
+func (e *Engine) List() []AlertEvent {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	out := make([]AlertEvent, len(e.list))
+	for i, ev := range e.list {
+		ev.Read = e.readSet[ev.ID]
+		out[i] = ev
+	}
+	return out
+}
+
+// UnreadCount cuenta eventos almacenados (ya pasaron config) no leídos.
+// Es la fuente de Overview.UnreadAlerts (server truth, SPEC §4).
+func (e *Engine) UnreadCount() int {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	n := 0
+	for _, ev := range e.list {
+		if !e.readSet[ev.ID] {
+			n++
+		}
+	}
+	return n
+}
+
+// MarkRead marca IDs como leídos (persiste; cap 200 FIFO).
+func (e *Engine) MarkRead(ids ...string) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	for _, id := range ids {
+		if id == "" || e.readSet[id] {
+			continue
+		}
+		e.readSet[id] = true
+		e.readOrd = append(e.readOrd, id)
+	}
+	for len(e.readOrd) > MaxReadIDs {
+		delete(e.readSet, e.readOrd[0])
+		e.readOrd = e.readOrd[1:]
+	}
+	e.saveReadLocked()
+}
+
+// MarkAllRead marca leídas todas las alertas actuales.
+func (e *Engine) MarkAllRead() {
+	e.mu.Lock()
+	ids := make([]string, 0, len(e.list))
+	for _, ev := range e.list {
+		ids = append(ids, ev.ID)
+	}
+	e.mu.Unlock()
+	e.MarkRead(ids...)
+}
+
+func (e *Engine) saveConfigLocked() {
+	if e.db == nil {
+		return
+	}
+	raw, err := json.Marshal(e.cfg)
+	if err != nil {
+		return
+	}
+	_, _ = e.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		configKey, string(raw))
+}
+
+func (e *Engine) saveReadLocked() {
+	if e.db == nil {
+		return
+	}
+	raw, err := json.Marshal(e.readOrd)
+	if err != nil {
+		return
+	}
+	_, _ = e.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		readKey, string(raw))
+}
+
+func contains(list []string, v string) bool {
+	for _, x := range list {
+		if x == v {
+			return true
+		}
+	}
+	return false
+}
+
+// IsCategory reporta si v es una categoría válida (validación de query).
+func IsCategory(v string) bool { return contains(Categories, v) }

+ 252 - 0
server-go/internal/alerts/alerts_test.go

@@ -0,0 +1,252 @@
+// alerts_test.go — tests del motor (SPEC-ALERTAS §2-4): defaults, validación,
+// filtrado none/urgent/all en creación, dedup 5 min, cap 100, read-state
+// (FIFO 200, persistencia kv) y hook Notifier.
+package alerts
+
+import (
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func ev(id, cat string, urgent bool) AlertEvent {
+	return AlertEvent{ID: id, Category: cat, Urgent: urgent, Severity: "warn",
+		Title: "t-" + id, RouterID: "r1"}
+}
+
+func TestDefaultConfig(t *testing.T) {
+	e := New(nil, nil)
+	cfg := e.Config()
+	want := DefaultConfig()
+	if len(cfg) != 6 {
+		t.Fatalf("config: %d claves, esperaba 6", len(cfg))
+	}
+	for _, cat := range Categories {
+		if cfg[cat] != want[cat] {
+			t.Fatalf("default %s: %q, esperaba %q", cat, cfg[cat], want[cat])
+		}
+	}
+	// Defaults exactos del SPEC §2
+	if cfg[CatRouter] != "urgent" || cfg[CatInternet] != "urgent" ||
+		cfg[CatClients] != "urgent" || cfg[CatSignal] != "none" ||
+		cfg[CatVPN] != "none" || cfg[CatSystem] != "all" {
+		t.Fatalf("defaults SPEC: %v", cfg)
+	}
+}
+
+func TestSetConfigPartialAndValidation(t *testing.T) {
+	e := New(nil, nil)
+	if err := e.SetConfig(map[string]string{"vpn": "all"}); err != nil {
+		t.Fatalf("SetConfig parcial: %v", err)
+	}
+	cfg := e.Config()
+	if cfg["vpn"] != "all" {
+		t.Fatalf("vpn: %q", cfg["vpn"])
+	}
+	// El resto sigue en defaults
+	if cfg["router"] != "urgent" || cfg["signal"] != "none" {
+		t.Fatalf("merge parcial rompió defaults: %v", cfg)
+	}
+	// Categoría desconocida → error
+	if err := e.SetConfig(map[string]string{"wifi": "all"}); err == nil {
+		t.Fatal("categoría desconocida debía fallar")
+	}
+	// Nivel inválido → error
+	if err := e.SetConfig(map[string]string{"vpn": "todo"}); err == nil {
+		t.Fatal("nivel inválido debía fallar")
+	}
+	// Y no deja la config a medias
+	if e.Config()["vpn"] != "all" {
+		t.Fatalf("config tras error: %v", e.Config())
+	}
+}
+
+func TestEmitFiltering(t *testing.T) {
+	e := New(nil, nil)
+	// none → descarta (signal por defecto)
+	if e.Emit(ev("s1", CatSignal, true)) {
+		t.Fatal("signal:none debía descartar")
+	}
+	// urgent → solo urgentes (clients por defecto)
+	if e.Emit(ev("c1", CatClients, false)) {
+		t.Fatal("clients:urgent debía descartar no-urgente")
+	}
+	if !e.Emit(ev("c2", CatClients, true)) {
+		t.Fatal("clients:urgent debía aceptar urgente")
+	}
+	// all → pasa todo (system por defecto)
+	if !e.Emit(ev("y1", CatSystem, false)) {
+		t.Fatal("system:all debía aceptar no-urgente")
+	}
+	if got := len(e.List()); got != 2 {
+		t.Fatalf("lista: %d, esperaba 2", got)
+	}
+	// Cambio de nivel reconfigura el filtrado
+	if err := e.SetConfig(map[string]string{"signal": "all"}); err != nil {
+		t.Fatal(err)
+	}
+	if !e.Emit(ev("s2", CatSignal, false)) {
+		t.Fatal("signal:all debía aceptar")
+	}
+}
+
+func TestEmitDefaultsFillTsAndTime(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(AlertEvent{ID: "a1", Category: CatSystem, Severity: "ok", Title: "x", RouterID: "r"})
+	got := e.List()[0]
+	if got.Ts == 0 || got.Time == "" {
+		t.Fatalf("Ts/Time no rellenados: %+v", got)
+	}
+	if got.Read {
+		t.Fatal("Read debe nacer false")
+	}
+}
+
+func TestDedupWindow(t *testing.T) {
+	e := New(nil, nil)
+	now := time.Unix(1_700_000_000, 0)
+	e.SetClock(func() time.Time { return now })
+	base := AlertEvent{ID: "d1", Category: CatSystem, Severity: "ok", Title: "mismo", RouterID: "r1"}
+	if !e.Emit(base) {
+		t.Fatal("primer emit debía pasar")
+	}
+	// Mismo (category,title,routerId) dentro de 5 min → ignorado (aunque cambie el ID)
+	dup := base
+	dup.ID = "d2"
+	if e.Emit(dup) {
+		t.Fatal("dedup 5 min debía ignorar")
+	}
+	// Distinto routerId → otra clave, pasa
+	other := base
+	other.ID, other.RouterID = "d3", "r2"
+	if !e.Emit(other) {
+		t.Fatal("routerId distinto debía pasar")
+	}
+	// Tras la ventana → vuelve a pasar
+	now = now.Add(DedupWindow + time.Second)
+	dup.ID = "d4"
+	if !e.Emit(dup) {
+		t.Fatal("tras 5 min debía pasar de nuevo")
+	}
+}
+
+func TestCap100(t *testing.T) {
+	e := New(nil, nil)
+	for i := 0; i < 105; i++ {
+		e.Emit(AlertEvent{ID: fmt.Sprintf("e%d", i), Category: CatSystem,
+			Severity: "ok", Title: fmt.Sprintf("t%d", i), RouterID: "r"})
+	}
+	list := e.List()
+	if len(list) != MaxEvents {
+		t.Fatalf("cap: %d, esperaba %d", len(list), MaxEvents)
+	}
+	if list[0].ID != "e104" {
+		t.Fatalf("más reciente primero: %s", list[0].ID)
+	}
+}
+
+func TestReadStateAndUnread(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(ev("a", CatSystem, false))
+	e.Emit(ev("b", CatSystem, false))
+	e.Emit(ev("c", CatSystem, false))
+	if got := e.UnreadCount(); got != 3 {
+		t.Fatalf("unread: %d, esperaba 3", got)
+	}
+	e.MarkRead("a", "b")
+	if got := e.UnreadCount(); got != 1 {
+		t.Fatalf("unread tras read: %d, esperaba 1", got)
+	}
+	for _, x := range e.List() {
+		want := x.ID == "a" || x.ID == "b"
+		if x.Read != want {
+			t.Fatalf("Read de %s: %v, esperaba %v", x.ID, x.Read, want)
+		}
+	}
+	e.MarkAllRead()
+	if got := e.UnreadCount(); got != 0 {
+		t.Fatalf("unread tras read-all: %d", got)
+	}
+}
+
+func TestReadSetFIFOCap(t *testing.T) {
+	e := New(nil, nil)
+	ids := make([]string, 0, MaxReadIDs+10)
+	for i := 0; i < MaxReadIDs+10; i++ {
+		ids = append(ids, fmt.Sprintf("id%d", i))
+	}
+	e.MarkRead(ids...)
+	if len(e.readOrd) != MaxReadIDs {
+		t.Fatalf("readOrd: %d, esperaba %d", len(e.readOrd), MaxReadIDs)
+	}
+	if e.readSet["id0"] {
+		t.Fatal("FIFO debía expulsar el más antiguo")
+	}
+	if !e.readSet["id209"] {
+		t.Fatal("el más reciente debe seguir en el set")
+	}
+}
+
+func TestPersistenceRoundtrip(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	e := New(d, nil)
+	if err := e.SetConfig(map[string]string{"vpn": "all", "signal": "urgent"}); err != nil {
+		t.Fatal(err)
+	}
+	e.Emit(ev("p1", CatSystem, false))
+	e.Emit(ev("p2", CatSystem, false))
+	e.MarkRead("p1")
+
+	// Motor nuevo sobre la misma DB: config y read-state sobreviven
+	e2 := New(d, nil)
+	cfg := e2.Config()
+	if cfg["vpn"] != "all" || cfg["signal"] != "urgent" || cfg["router"] != "urgent" {
+		t.Fatalf("config persistida: %v", cfg)
+	}
+	e2.Seed(ev("p1", CatSystem, false))
+	e2.Seed(ev("p2", CatSystem, false))
+	for _, x := range e2.List() {
+		if (x.ID == "p1") != x.Read {
+			t.Fatalf("read persistido de %s: %v", x.ID, x.Read)
+		}
+	}
+	if got := e2.UnreadCount(); got != 1 {
+		t.Fatalf("unread persistido: %d, esperaba 1", got)
+	}
+}
+
+type spyNotifier struct{ got []AlertEvent }
+
+func (s *spyNotifier) Notify(ev AlertEvent) { s.got = append(s.got, ev) }
+
+func TestNotifierOnlyUrgentThatPass(t *testing.T) {
+	spy := &spyNotifier{}
+	e := New(nil, spy)
+	e.Emit(ev("n1", CatSystem, false)) // pasa, no urgente → sin notify
+	e.Emit(ev("n2", CatSystem, true))  // pasa, urgente → notify
+	e.Emit(ev("n3", CatSignal, true))  // signal:none → descartado, sin notify
+	if len(spy.got) != 1 || spy.got[0].ID != "n2" {
+		t.Fatalf("notifier: %+v", spy.got)
+	}
+}
+
+func TestSeedSkipsConfigButKeepsDedup(t *testing.T) {
+	e := New(nil, nil)
+	// Seed ignora el filtro (vpn:none) — historia del demo (SPEC §5)
+	if !e.Seed(ev("h1", CatVPN, false)) {
+		t.Fatal("Seed debía guardar pese a vpn:none")
+	}
+	if e.Seed(AlertEvent{ID: "h2", Category: CatVPN, Title: "t-h1", RouterID: "r1"}) {
+		t.Fatal("Seed debía respetar dedup")
+	}
+	if got := len(e.List()); got != 1 {
+		t.Fatalf("lista: %d", got)
+	}
+}

+ 5 - 2
server-go/internal/auth/middleware.go

@@ -44,11 +44,14 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 }
 
 // RequireAuth es middleware global: todo /api/* exige sesión salvo
-// /api/health y /api/auth/login. Fallo → 401 {error:'unauthorized'}.
+// /api/health, /api/auth/login y /api/ingest/agent (este último lleva auth
+// propia Bearer por token de equipo, SPEC-AGENTE-PILOTO §1 — la sesión es de
+// humanos). Fallo → 401 {error:'unauthorized'}.
 func RequireAuth(d *db.DB, secret string, next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		path := r.URL.Path
-		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" {
+		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" ||
+			path == "/api/ingest/agent" {
 			next.ServeHTTP(w, r)
 			return
 		}

+ 11 - 0
server-go/internal/db/db.go

@@ -85,6 +85,15 @@ CREATE TABLE IF NOT EXISTS routers (
   is_gateway INTEGER NOT NULL DEFAULT 0,
   created_at INTEGER NOT NULL
 );
+-- Suscripciones Web Push (Fase 6 Bloque C; sin paridad Node: el push es
+-- nuevo en Go). created_at en milisegundos como el resto de epochs.
+CREATE TABLE IF NOT EXISTS push_subscriptions (
+  endpoint TEXT PRIMARY KEY,
+  keys_auth TEXT NOT NULL,
+  keys_p256dh TEXT NOT NULL,
+  user_agent TEXT,
+  created_at INTEGER NOT NULL
+);
 `
 
 // DB envuelve *sql.DB con los jobs y helpers de paridad.
@@ -145,6 +154,8 @@ func Open(dataDir string) (*DB, error) {
 	migrate(sqldb, "sessions", "ua", "ALTER TABLE sessions ADD COLUMN ua TEXT")
 	migrate(sqldb, "sessions", "user_id", "ALTER TABLE sessions ADD COLUMN user_id INTEGER")
 	migrate(sqldb, "users", "language", "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
+	// SPEC-65 D65-5: nombre visible por usuario ("" = usar el username).
+	migrate(sqldb, "users", "display_name", "ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''")
 
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// DB para que el siguiente arranque no dispare una "migración" espuria

+ 300 - 0
server-go/internal/httpapi/agent.go

@@ -0,0 +1,300 @@
+// agent.go — Fase 6 piloto (SPEC-AGENTE-PILOTO §1):
+//
+//   POST /api/ingest/agent  — ingesta de agentes nativos. NO va detrás del
+//                             middleware de sesión: auth propia Bearer con
+//                             token por equipo (guardado sha256 en kv
+//                             agent.token.<slug>). Rate limit por IP 30/min,
+//                             body cap 2 MB.
+//   POST   /api/agents      — crear token para un slug (sesión). El token se
+//                             muestra UNA sola vez, con el one-liner de
+//                             instalación. Nunca se vuelve a servir.
+//   GET    /api/agents      — slugs con agente + last_seen + versión.
+//   DELETE /api/agents/{slug} — revocar (borra el token; el agente recibe 401).
+package httpapi
+
+import (
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/subtle"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"regexp"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+const (
+	// ingestBodyCap: body máximo del push del agente (2 MB, SPEC §1).
+	ingestBodyCap = 2 << 20
+	// ingestRateLimit: pushes por IP y ventana (30/min, SPEC §1).
+	ingestRateLimit  = 30
+	ingestRateWindow = time.Minute
+	// agentTokenKeyPrefix: kv agent.token.<slug> = sha256 hex del token.
+	agentTokenKeyPrefix = "agent.token."
+)
+
+// agentSlugRe: slugs de equipo válidos (mismo alfabeto que routerstore).
+var agentSlugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
+
+// ---------------------------------------------------------------------------
+// Rate limit por IP (ventana fija de 1 min; purga oportunista)
+// ---------------------------------------------------------------------------
+
+type ipRateLimit struct {
+	mu     sync.Mutex
+	hits   map[string]*ipHit
+	limit  int
+	window time.Duration
+	now    func() time.Time
+}
+
+type ipHit struct {
+	count int
+	reset time.Time
+}
+
+func newIPRateLimit(limit int, window time.Duration) *ipRateLimit {
+	return &ipRateLimit{hits: map[string]*ipHit{}, limit: limit, window: window, now: time.Now}
+}
+
+// allow registra un intento de ip; false → retryAfterSec hasta el reset.
+func (l *ipRateLimit) allow(ip string) (bool, int) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	// Purga oportunista para no crecer sin límite en redes con muchos clientes
+	if len(l.hits) > 1024 {
+		now := l.now()
+		for k, h := range l.hits {
+			if now.After(h.reset) {
+				delete(l.hits, k)
+			}
+		}
+	}
+	h, ok := l.hits[ip]
+	if !ok || l.now().After(h.reset) {
+		l.hits[ip] = &ipHit{count: 1, reset: l.now().Add(l.window)}
+		return true, 0
+	}
+	if h.count >= l.limit {
+		return false, int(time.Until(h.reset).Seconds()) + 1
+	}
+	h.count++
+	return true, 0
+}
+
+// ---------------------------------------------------------------------------
+// Tokens de agente (kv, sha256 — el token en claro solo vive en la respuesta
+// de creación y en el env del router)
+// ---------------------------------------------------------------------------
+
+func agentTokenKey(slug string) string { return agentTokenKeyPrefix + slug }
+
+// hashAgentToken: sha256 hex del token (lo único que se persiste).
+func hashAgentToken(token string) string {
+	sum := sha256.Sum256([]byte(token))
+	return hex.EncodeToString(sum[:])
+}
+
+// newAgentToken genera un token aleatorio de 32 bytes en hex (64 chars).
+func newAgentToken() (string, error) {
+	buf := make([]byte, 32)
+	if _, err := rand.Read(buf); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(buf), nil
+}
+
+// checkAgentToken: ¿el Bearer es válido para el slug? (comparación en
+// tiempo constante sobre los hashes).
+func (s *server) checkAgentToken(slug, token string) bool {
+	if token == "" || s.db == nil {
+		return false
+	}
+	var stored string
+	if err := s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&stored); err != nil {
+		return false
+	}
+	got := hashAgentToken(token)
+	return subtle.ConstantTimeCompare([]byte(got), []byte(stored)) == 1
+}
+
+// ---------------------------------------------------------------------------
+// POST /api/ingest/agent (auth Bearer propia; exenta del middleware de sesión)
+// ---------------------------------------------------------------------------
+
+func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
+	// 429: ráfaga por IP (antes de leer el body, como el login)
+	if ok, retry := s.ingestLimit.allow(auth.ClientIP(r)); !ok {
+		w.Header().Set("Retry-After", fmt.Sprintf("%d", retry))
+		writeJSON(w, http.StatusTooManyRequests, map[string]any{
+			"error":         "rate_limited",
+			"retryAfterSec": retry,
+		})
+		return
+	}
+	// 413: body cap 2 MB
+	body, err := io.ReadAll(io.LimitReader(r.Body, ingestBodyCap+1))
+	if err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_payload")
+		return
+	}
+	if len(body) > ingestBodyCap {
+		writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large")
+		return
+	}
+	// 400: JSON + campos mínimos del contrato
+	var p probe.Payload
+	if err := json.Unmarshal(body, &p); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_payload", "JSON inválido")
+		return
+	}
+	if !agentSlugRe.MatchString(p.Router) || p.Ts <= 0 {
+		writeError(w, http.StatusBadRequest, "invalid_payload",
+			`Se esperaba { "router": "<slug>", "ts": <unix>, "data": {...} }`)
+		return
+	}
+	// 401: Bearer inválido para ese slug
+	token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+	if !s.checkAgentToken(p.Router, token) {
+		writeError(w, http.StatusUnauthorized, "unauthorized")
+		return
+	}
+	if s.agents == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable",
+			"el servidor no tiene registry de agentes")
+		return
+	}
+	s.agents.Ingest(&p)
+	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
+}
+
+// ---------------------------------------------------------------------------
+// Gestión de tokens (sesión): POST/GET /api/agents, DELETE /api/agents/{slug}
+// ---------------------------------------------------------------------------
+
+// agentCreateResponse es la ÚNICA respuesta que incluye el token en claro.
+type agentCreateResponse struct {
+	Slug    string `json:"slug"`
+	Token   string `json:"token"`
+	Install string `json:"install"`
+}
+
+// handleAgentsCreate: genera (o rota) el token de un slug. 201 con el token
+// en claro UNA vez + el one-liner de instalación.
+func (s *server) handleAgentsCreate(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Slug string `json:"slug"`
+	}
+	if !readJSONBody(r, &body) || !agentSlugRe.MatchString(body.Slug) {
+		writeError(w, http.StatusBadRequest, "invalid_body",
+			`Se esperaba { "slug": "<equipo>" } (a-z, 0-9, guiones)`)
+		return
+	}
+	token, err := newAgentToken()
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "token_error")
+		return
+	}
+	if _, err := s.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		agentTokenKey(body.Slug), hashAgentToken(token)); err != nil {
+		writeError(w, http.StatusInternalServerError, "token_error")
+		return
+	}
+	writeJSON(w, http.StatusCreated, agentCreateResponse{
+		Slug:    body.Slug,
+		Token:   token,
+		Install: s.agentInstallLine(r, body.Slug, token),
+	})
+}
+
+// agentInstallLine: one-liner de instalación vía SSH desde esta máquina
+// (install-agent.sh, hermano de install-collector.sh). El host del router se
+// resuelve de la tabla routers si el slug existe.
+func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
+	host := "<ip-del-router>"
+	if s.db != nil {
+		for _, rc := range routerstore.ListRouters(s.db.DB) {
+			if rc.ID == slug {
+				host = rc.Host
+				break
+			}
+		}
+	}
+	scheme := "http"
+	if auth.IsSecureRequest(r) {
+		scheme = "https"
+	}
+	server := scheme + "://" + r.Host
+	return fmt.Sprintf(
+		"curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --host %s --server %s --slug %s --token %s",
+		host, server, slug, token)
+}
+
+// agentListItem: lo que ve la UI — NUNCA el token ni su hash.
+type agentListItem struct {
+	Slug     string `json:"slug"`
+	LastSeen *int64 `json:"lastSeen"` // unix SEGUNDOS; null si nunca empujó
+	Version  string `json:"version,omitempty"`
+	Fresh    bool   `json:"fresh"`
+}
+
+// handleAgentsList: slugs con token + last_seen + versión.
+func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
+	out := []agentListItem{}
+	if s.db != nil {
+		rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
+		if err == nil {
+			defer rows.Close()
+			for rows.Next() {
+				var key string
+				if rows.Scan(&key) != nil {
+					continue
+				}
+				slug := strings.TrimPrefix(key, agentTokenKeyPrefix)
+				item := agentListItem{Slug: slug}
+				if s.agents != nil {
+					if seen, version, ok := s.agents.Info(slug); ok {
+						ts := seen.Unix()
+						item.LastSeen = &ts
+						item.Version = version
+					}
+					_, item.Fresh = s.agents.Fresh(slug)
+				}
+				out = append(out, item)
+			}
+		}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"agents": out})
+}
+
+// handleAgentsDelete: revoca el token del slug (el agente recibirá 401 en su
+// próximo push) y olvida su estado. 404 si no existía.
+func (s *server) handleAgentsDelete(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if !agentSlugRe.MatchString(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	res, err := s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error")
+		return
+	}
+	if n, _ := res.RowsAffected(); n == 0 {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if s.agents != nil {
+		s.agents.Forget(slug)
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 298 - 0
server-go/internal/httpapi/agent_api_test.go

@@ -0,0 +1,298 @@
+// agent_api_test.go — Fase 6 piloto (SPEC-AGENTE-PILOTO §1): ingesta con
+// token válido/inválido, body grande, rate limit, payload inválido (no rompe
+// el pipeline), y gestión de tokens (crear/listar/revocar; el token solo se
+// muestra una vez y NUNCA sale por GET).
+package httpapi_test
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+type agentTestServer struct {
+	*httptest.Server
+	db     *db.DB
+	agents *adapters.AgentRegistry
+	cookie string
+}
+
+// makeAgentTestServer: app real con registry de agentes + sesión admin.
+func makeAgentTestServer(t *testing.T) *agentTestServer {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	reg := adapters.NewAgentRegistry(90 * time.Second)
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
+		Agents: reg, Started: time.Now(),
+	})
+	srv := httptest.NewServer(handler)
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	if status != 204 {
+		t.Fatalf("login: %d", status)
+	}
+	ts := &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+// createAgentToken crea el token de un slug vía API (con sesión) y devuelve
+// (status, token, install).
+func createAgentToken(t *testing.T, ts *agentTestServer, slug string) (int, string, string) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(fmt.Sprintf(`{"slug":%q}`, slug)))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST /api/agents: %v", err)
+	}
+	defer res.Body.Close()
+	var body struct {
+		Slug    string `json:"slug"`
+		Token   string `json:"token"`
+		Install string `json:"install"`
+	}
+	data, _ := io.ReadAll(res.Body)
+	_ = json.Unmarshal(data, &body)
+	return res.StatusCode, body.Token, body.Install
+}
+
+// ingest hace un push de agente; ip fija la X-Forwarded-For (rate limit).
+func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("X-Forwarded-For", ip)
+	if token != "" {
+		req.Header.Set("Authorization", "Bearer "+token)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("ingest: %v", err)
+	}
+	return res
+}
+
+const validPayload = `{"router":"patio","ts":1754140000,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`
+
+func TestIngestTokenValidoEInvalido(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, install := createAgentToken(t, ts, "patio")
+	if status != 201 || token == "" {
+		t.Fatalf("create: %d token=%q", status, token)
+	}
+	if !strings.Contains(install, "install-agent.sh") || !strings.Contains(install, token) || !strings.Contains(install, "--slug patio") {
+		t.Fatalf("one-liner: %q", install)
+	}
+	// kv guarda sha256, NUNCA el token en claro
+	var stored string
+	if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.token.patio'").Scan(&stored); err != nil {
+		t.Fatalf("kv: %v", err)
+	}
+	sum := sha256.Sum256([]byte(token))
+	if stored != hex.EncodeToString(sum[:]) || strings.Contains(stored, token) {
+		t.Fatalf("kv debería guardar sha256: %q", stored)
+	}
+	// Ingesta sin sesión (exenta del middleware) + token válido → 202
+	res := ingest(t, ts, token, "10.0.0.1", validPayload)
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("ingest válido: %d", res.StatusCode)
+	}
+	if _, version, ok := ts.agents.Info("patio"); !ok || version != "0.1.0" {
+		t.Fatalf("registry no actualizado: %v %q", ok, version)
+	}
+	// Token inválido → 401; sin token → 401; token de otro slug → 401
+	for _, tok := range []string{"", "deadbeef", token + "00"} {
+		res := ingest(t, ts, tok, "10.0.0.2", validPayload)
+		res.Body.Close()
+		if res.StatusCode != 401 {
+			t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
+		}
+	}
+}
+
+func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	_, token, _ := createAgentToken(t, ts, "patio")
+
+	// 413: body > 2 MB
+	big := strings.Repeat("x", (2<<20)+100)
+	res := ingest(t, ts, token, "10.0.1.1", big)
+	res.Body.Close()
+	if res.StatusCode != 413 {
+		t.Fatalf("body grande: %d", res.StatusCode)
+	}
+	// 400: JSON roto, slug inválido, ts ausente — y NADA se rompe después
+	for _, p := range []string{
+		`{no json`,
+		`{"router":"PATIO!","ts":1,"data":{}}`,
+		`{"router":"patio","data":{}}`,
+		`{"router":"patio","ts":-3,"data":{}}`,
+	} {
+		res := ingest(t, ts, token, "10.0.1.2", p)
+		res.Body.Close()
+		if res.StatusCode != 400 {
+			t.Fatalf("payload %q debería dar 400, dio %d", p, res.StatusCode)
+		}
+	}
+	// El pipeline sigue sano tras los 400
+	res = ingest(t, ts, token, "10.0.1.2", validPayload)
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("ingest tras 400s: %d", res.StatusCode)
+	}
+}
+
+func TestIngestRateLimit(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	_, token, _ := createAgentToken(t, ts, "patio")
+	// 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
+	for i := 0; i < 30; i++ {
+		res := ingest(t, ts, token, "10.0.2.1", validPayload)
+		res.Body.Close()
+		if res.StatusCode != 202 {
+			t.Fatalf("push %d: %d", i, res.StatusCode)
+		}
+	}
+	res := ingest(t, ts, token, "10.0.2.1", validPayload)
+	defer res.Body.Close()
+	if res.StatusCode != 429 {
+		t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
+	}
+	var body map[string]any
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("429 json: %v", err)
+	}
+	if body["error"] != "rate_limited" || res.Header.Get("Retry-After") == "" {
+		t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
+	}
+	// Otra IP no está limitada
+	res2 := ingest(t, ts, token, "10.0.2.2", validPayload)
+	res2.Body.Close()
+	if res2.StatusCode != 202 {
+		t.Fatalf("otra IP: %d", res2.StatusCode)
+	}
+}
+
+func TestAgentsListYRevocacion(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	// GET /api/agents exige sesión
+	res := get(t, ts.URL, "/api/agents", "")
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("GET /api/agents sin sesión: %d", res.StatusCode)
+	}
+
+	_, token, _ := createAgentToken(t, ts, "patio")
+	if _, token2, _ := createAgentToken(t, ts, "living"); token2 == "" {
+		t.Fatal("segundo token")
+	}
+
+	// Lista: 2 slugs, lastSeen null (nunca empujaron), SIN token ni hash
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body := readJSON(t, res)
+	agents, _ := body["agents"].([]any)
+	if len(agents) != 2 {
+		t.Fatalf("agents: %v", body)
+	}
+	raw, _ := json.Marshal(body)
+	if strings.Contains(string(raw), token) || strings.Contains(string(raw), "token") {
+		t.Fatalf("GET /api/agents no debería exponer tokens: %s", raw)
+	}
+
+	// Tras un push: lastSeen (unix s) + versión + fresh
+	res2 := ingest(t, ts, token, "10.0.3.1", validPayload)
+	res2.Body.Close()
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body = readJSON(t, res)
+	agents, _ = body["agents"].([]any)
+	var patio map[string]any
+	for _, a := range agents {
+		m, _ := a.(map[string]any)
+		if m["slug"] == "patio" {
+			patio = m
+		}
+	}
+	if patio == nil || patio["lastSeen"] == nil || patio["version"] != "0.1.0" || patio["fresh"] != true {
+		t.Fatalf("patio tras push: %v", patio)
+	}
+
+	// Revocar → 204; el push siguiente recibe 401; GET ya no lo lista
+	req, _ := http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	resDel, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("DELETE: %v", err)
+	}
+	resDel.Body.Close()
+	if resDel.StatusCode != 204 {
+		t.Fatalf("DELETE: %d", resDel.StatusCode)
+	}
+	res3 := ingest(t, ts, token, "10.0.3.2", validPayload)
+	res3.Body.Close()
+	if res3.StatusCode != 401 {
+		t.Fatalf("push tras revocar: %d", res3.StatusCode)
+	}
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body = readJSON(t, res)
+	agents, _ = body["agents"].([]any)
+	if len(agents) != 1 {
+		t.Fatalf("tras revocar: %v", body)
+	}
+	// Revocar de nuevo → 404
+	req, _ = http.NewRequest("DELETE", ts.URL+"/api/agents/patio", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	resDel, _ = http.DefaultClient.Do(req)
+	resDel.Body.Close()
+	if resDel.StatusCode != 404 {
+		t.Fatalf("DELETE 2ª vez: %d", resDel.StatusCode)
+	}
+}
+
+func TestAgentsCreateValidaSlug(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	for _, slug := range []string{"", "PATIO", "con espacios", "-x", strings.Repeat("a", 65)} {
+		status, _, _ := createAgentToken(t, ts, slug)
+		if status != 400 {
+			t.Fatalf("slug %q debería dar 400, dio %d", slug, status)
+		}
+	}
+}

+ 197 - 0
server-go/internal/httpapi/alerts_api_test.go

@@ -0,0 +1,197 @@
+// alerts_api_test.go — contrato de los endpoints de alertas (SPEC-ALERTAS §4):
+// GET /api/alerts (+category, +unread=1), GET/PUT /api/alerts/config,
+// POST /api/alerts/read y /api/alerts/read-all (server truth en overview).
+package httpapi_test
+
+import (
+	"bytes"
+	"encoding/json"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+func doJSON(t *testing.T, method, base, path, cookie string, body string) *http.Response {
+	t.Helper()
+	var rd io.Reader
+	if body != "" {
+		rd = bytes.NewBufferString(body)
+	}
+	req, _ := http.NewRequest(method, base+path, rd)
+	if body != "" {
+		req.Header.Set("Content-Type", "application/json")
+	}
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("%s %s: %v", method, path, err)
+	}
+	return res
+}
+
+func alertItems(t *testing.T, res *http.Response) []map[string]any {
+	t.Helper()
+	defer res.Body.Close()
+	var body struct {
+		Items []map[string]any `json:"items"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("json: %v", err)
+	}
+	return body.Items
+}
+
+func TestAlertsContractFields(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+
+	res := get(t, ts.URL, "/api/alerts", cookie)
+	items := alertItems(t, res)
+	if len(items) != 5 {
+		t.Fatalf("alertas demo: %d, esperaba 5", len(items))
+	}
+	for _, a := range items {
+		if a["category"] == nil || a["category"] == "" {
+			t.Fatalf("alerta sin category: %v", a["id"])
+		}
+		if _, ok := a["urgent"].(bool); !ok {
+			t.Fatalf("alerta sin urgent bool: %v", a["id"])
+		}
+		if ts64, ok := a["ts"].(float64); !ok || ts64 <= 0 {
+			t.Fatalf("alerta sin ts: %v", a["id"])
+		}
+	}
+	// Filtro por categoría: vpn → solo el handshake
+	items = alertItems(t, get(t, ts.URL, "/api/alerts?category=vpn", cookie))
+	if len(items) != 1 || items[0]["id"] != "alert-handshake-wg" {
+		t.Fatalf("category=vpn: %v", items)
+	}
+	// Categoría inválida → 400
+	res = get(t, ts.URL, "/api/alerts?category=wifi", cookie)
+	if res.StatusCode != 400 {
+		t.Fatalf("category inválida: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+	// unread=1 → las 2 no leídas del canon
+	items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
+	if len(items) != 2 {
+		t.Fatalf("unread=1: %d, esperaba 2", len(items))
+	}
+	for _, a := range items {
+		if a["read"] == true {
+			t.Fatalf("unread=1 devolvió leída: %v", a["id"])
+		}
+	}
+	// Combinado: category + unread
+	items = alertItems(t, get(t, ts.URL, "/api/alerts?category=clients&unread=1", cookie))
+	if len(items) != 0 {
+		t.Fatalf("clients&unread: %d, esperaba 0 (la canon clients está leída)", len(items))
+	}
+}
+
+func TestAlertsConfigEndpoints(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+
+	res := get(t, ts.URL, "/api/alerts/config", cookie)
+	cfg := readJSON(t, res)
+	if len(cfg) != 6 {
+		t.Fatalf("config: %d claves, esperaba 6", len(cfg))
+	}
+	want := map[string]string{"router": "urgent", "internet": "urgent", "clients": "urgent",
+		"signal": "none", "vpn": "none", "system": "all"}
+	for k, v := range want {
+		if cfg[k] != v {
+			t.Fatalf("default %s: %v, esperaba %s", k, cfg[k], v)
+		}
+	}
+	// PUT parcial → 200 y devuelve la config efectiva completa
+	res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"all"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT config: %d", res.StatusCode)
+	}
+	cfg = readJSON(t, res)
+	if cfg["vpn"] != "all" || cfg["router"] != "urgent" {
+		t.Fatalf("PUT parcial: %v", cfg)
+	}
+	// Roundtrip: GET refleja el cambio (persistido en kv)
+	cfg = readJSON(t, get(t, ts.URL, "/api/alerts/config", cookie))
+	if cfg["vpn"] != "all" {
+		t.Fatalf("roundtrip: %v", cfg)
+	}
+	// Nivel inválido → 400
+	res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"vpn":"todo"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("nivel inválido: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+	// Categoría desconocida → 400
+	res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `{"wifi":"all"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("categoría desconocida: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+	// Body no-JSON → 400
+	res = doJSON(t, "PUT", ts.URL, "/api/alerts/config", cookie, `nope`)
+	if res.StatusCode != 400 {
+		t.Fatalf("body inválido: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+}
+
+func TestAlertsReadEndpoints(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+
+	unreadOf := func() float64 {
+		res := get(t, ts.URL, "/api/overview", cookie)
+		body := readJSON(t, res)
+		return body["unreadAlerts"].(float64)
+	}
+	if got := unreadOf(); got != 2 {
+		t.Fatalf("unreadAlerts inicial: %v, esperaba 2", got)
+	}
+	// POST read {ids}: marca una
+	res := doJSON(t, "POST", ts.URL, "/api/alerts/read", cookie, `{"ids":["alert-temp-patio"]}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("read: %d", res.StatusCode)
+	}
+	res.Body.Close()
+	if got := unreadOf(); got != 1 {
+		t.Fatalf("unreadAlerts tras read: %v, esperaba 1", got)
+	}
+	items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
+	for _, a := range items {
+		if a["id"] == "alert-temp-patio" && a["read"] != true {
+			t.Fatal("read no aplicado en GET /api/alerts")
+		}
+	}
+	// POST read-all → 0 en overview (server truth)
+	res = doJSON(t, "POST", ts.URL, "/api/alerts/read-all", cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("read-all: %d", res.StatusCode)
+	}
+	res.Body.Close()
+	if got := unreadOf(); got != 0 {
+		t.Fatalf("unreadAlerts tras read-all: %v, esperaba 0", got)
+	}
+	items = alertItems(t, get(t, ts.URL, "/api/alerts?unread=1", cookie))
+	if len(items) != 0 {
+		t.Fatalf("unread=1 tras read-all: %d", len(items))
+	}
+}
+
+// writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
+func TestAlertsNoTrailingNewline(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	res := get(t, ts.URL, "/api/alerts/config", cookie)
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	if strings.HasSuffix(string(raw), "\n") {
+		t.Fatal("writeJSON no debe terminar en \\n")
+	}
+}

+ 12 - 5
server-go/internal/httpapi/auth.go

@@ -47,7 +47,8 @@ func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
 	w.WriteHeader(http.StatusNoContent)
 }
 
-// handleMe: {user, role, language, mode} (language releído de users).
+// handleMe: {user, role, language, displayName, mode} (language/displayName
+// releídos de users; SPEC-65 D65-5: displayName "" = no puesto).
 func (s *server) handleMe(mode string) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		user := auth.UserFromContext(r.Context())
@@ -60,11 +61,17 @@ func (s *server) handleMe(mode string) http.HandlerFunc {
 		if err := s.db.QueryRow("SELECT language FROM users WHERE id = ?", user.ID).Scan(&lang); err == nil && lang != nil {
 			language = *lang
 		}
+		displayName := ""
+		var dn *string
+		if err := s.db.QueryRow("SELECT display_name FROM users WHERE id = ?", user.ID).Scan(&dn); err == nil && dn != nil {
+			displayName = *dn
+		}
 		writeJSON(w, http.StatusOK, map[string]any{
-			"user":     user.Username,
-			"role":     user.Role,
-			"language": language,
-			"mode":     mode,
+			"user":        user.Username,
+			"role":        user.Role,
+			"language":    language,
+			"displayName": displayName,
+			"mode":        mode,
 		})
 	}
 }

+ 70 - 9
server-go/internal/httpapi/data.go

@@ -9,6 +9,7 @@ import (
 	"strings"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
 
 var bands = []string{"5 GHz", "2.4 GHz", "cable"}
@@ -92,19 +93,27 @@ func paginate[T any](items []T, page, pageSize int64) map[string]any {
 }
 
 // handleOverview: último overview del poller o GetOverview en caliente.
+// El read-state de alertas se aplica SIEMPRE al servir (server truth,
+// SPEC-ALERTAS §4): el caché del poller puede llevar hasta 5 s de retraso
+// y el badge debe reflejar read/read-all al instante.
 func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
+	var ov *adapters.Overview
 	if s.lastOv != nil {
-		if ov := s.lastOv(); ov != nil {
-			writeJSON(w, http.StatusOK, ov)
+		ov = s.lastOv()
+	}
+	if ov == nil {
+		fresh, err := s.adapter.GetOverview(r.Context())
+		if err != nil || fresh == nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
 			return
 		}
+		ov = fresh
 	}
-	ov, err := s.adapter.GetOverview(r.Context())
-	if err != nil || ov == nil {
-		writeError(w, http.StatusInternalServerError, "internal_error")
-		return
-	}
-	writeJSON(w, http.StatusOK, ov)
+	out := *ov
+	engine := s.adapter.AlertsEngine()
+	out.Alerts = engine.List()
+	out.UnreadAlerts = engine.UnreadCount()
+	writeJSON(w, http.StatusOK, &out)
 }
 
 // handleRouters: {routers: [Router…]}.
@@ -192,7 +201,8 @@ func deviceMatches(d adapters.Device, query string) bool {
 	return false
 }
 
-// handleAlerts: severity + paginación (default pageSize=20).
+// handleAlerts: severity + category + unread=1 + paginación (default
+// pageSize=20). El read-state lo aplica el motor (SPEC-ALERTAS §3-4).
 func (s *server) handleAlerts(w http.ResponseWriter, r *http.Request) {
 	page, pageSize, ok := parsePagination(r, 20)
 	if !ok {
@@ -204,17 +214,68 @@ func (s *server) handleAlerts(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusBadRequest, "invalid_query", "severity debe ser una de: "+strings.Join(severities, ", "))
 		return
 	}
+	category := r.URL.Query().Get("category")
+	if category != "" && !alerts.IsCategory(category) {
+		writeError(w, http.StatusBadRequest, "invalid_query", "category debe ser una de: "+strings.Join(alerts.Categories, ", "))
+		return
+	}
+	unreadOnly := r.URL.Query().Get("unread") == "1"
 	items := s.adapter.GetAlerts(r.Context())
 	filtered := make([]adapters.AlertEvent, 0, len(items))
 	for _, a := range items {
 		if severity != "" && a.Severity != severity {
 			continue
 		}
+		if category != "" && a.Category != category {
+			continue
+		}
+		if unreadOnly && a.Read {
+			continue
+		}
 		filtered = append(filtered, a)
 	}
 	writeJSON(w, http.StatusOK, paginate(filtered, page, pageSize))
 }
 
+// handleAlertsConfig (GET): las 6 categorías con su nivel efectivo.
+func (s *server) handleAlertsConfigGet(w http.ResponseWriter, _ *http.Request) {
+	writeJSON(w, http.StatusOK, s.adapter.AlertsEngine().Config())
+}
+
+// handleAlertsConfigPut (PUT): parche parcial {"signal":"all"}; valida
+// categorías y niveles (400 en inválido, SPEC-ALERTAS §4).
+func (s *server) handleAlertsConfigPut(w http.ResponseWriter, r *http.Request) {
+	var patch map[string]string
+	if !readJSONBody(r, &patch) || patch == nil {
+		writeError(w, http.StatusBadRequest, "invalid_body", "body JSON inválido")
+		return
+	}
+	if err := s.adapter.AlertsEngine().SetConfig(patch); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_config", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, s.adapter.AlertsEngine().Config())
+}
+
+// handleAlertsRead (POST): body {"ids":["a","b"]} → marca leídas.
+func (s *server) handleAlertsRead(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		IDs []string `json:"ids"`
+	}
+	if !readJSONBody(r, &body) {
+		writeError(w, http.StatusBadRequest, "invalid_body", "body JSON inválido")
+		return
+	}
+	s.adapter.AlertsEngine().MarkRead(body.IDs...)
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// handleAlertsReadAll (POST): marca todas como leídas.
+func (s *server) handleAlertsReadAll(w http.ResponseWriter, _ *http.Request) {
+	s.adapter.AlertsEngine().MarkAllRead()
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
 // handleTopology: {routers, devices} sin paginar.
 func (s *server) handleTopology(w http.ResponseWriter, r *http.Request) {
 	routers := s.adapter.GetRouters(r.Context())

+ 131 - 0
server-go/internal/httpapi/display_name_test.go

@@ -0,0 +1,131 @@
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// SPEC-65 D65-5: display name por usuario — roundtrip completo.
+func TestDisplayNameRoundtrip(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// Al inicio: displayName "" (no puesto)
+	res := get(t, srv.URL, "/api/auth/me", cookie)
+	body := readJSON(t, res)
+	if body["displayName"] != "" {
+		t.Fatalf("displayName inicial: %v", body)
+	}
+
+	put := func(payload string) (int, map[string]any) {
+		req, _ := http.NewRequest("PUT", srv.URL+"/api/users/me/display-name", strings.NewReader(payload))
+		req.Header.Set("Cookie", "session="+cookie)
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatalf("PUT display-name: %v", err)
+		}
+		if res.StatusCode == 204 {
+			res.Body.Close()
+			return res.StatusCode, nil
+		}
+		return res.StatusCode, readJSON(t, res)
+	}
+
+	// Guardar (con espacios alrededor: se hace trim) → 204 y aparece en /me
+	st, _ := put(`{"displayName":"  Nacho 🚀  "}`)
+	if st != 204 {
+		t.Fatalf("PUT display-name: got %d want 204", st)
+	}
+	body = readJSON(t, get(t, srv.URL, "/api/auth/me", cookie))
+	if body["displayName"] != "Nacho 🚀" {
+		t.Fatalf("displayName tras guardar: %v", body)
+	}
+	// Persiste en DB (lectura directa, misma fila que sirve /me)
+	var dn string
+	if err := srv.db.QueryRow("SELECT display_name FROM users WHERE username = 'admin'").Scan(&dn); err != nil || dn != "Nacho 🚀" {
+		t.Fatalf("display_name en DB: %q err=%v", dn, err)
+	}
+
+	// 40 runes exactos → 204; 41 runes → 400
+	st, _ = put(`{"displayName":"` + strings.Repeat("á", 40) + `"}`)
+	if st != 204 {
+		t.Fatalf("40 runes: got %d want 204", st)
+	}
+	st, body = put(`{"displayName":"` + strings.Repeat("a", 41) + `"}`)
+	if st != 400 || body["error"] != "invalid_input" {
+		t.Fatalf("41 runes: got %d %v want 400", st, body)
+	}
+
+	// HTML → 400
+	st, body = put(`{"displayName":"<b>x</b>"}`)
+	if st != 400 || body["error"] != "invalid_input" {
+		t.Fatalf("con <>: got %d %v want 400", st, body)
+	}
+	st, _ = put(`{"displayName":"a>b"}`)
+	if st != 400 {
+		t.Fatalf("con >: got %d want 400", st)
+	}
+
+	// Body inválido → 400
+	st, _ = put(`{"displayName":42}`)
+	if st != 400 {
+		t.Fatalf("tipo inválido: got %d want 400", st)
+	}
+	st, _ = put(`{}`)
+	if st != 400 {
+		t.Fatalf("sin displayName: got %d want 400", st)
+	}
+
+	// Vacío permitido (= volver al username) → 204 y displayName ""
+	st, _ = put(`{"displayName":"   "}`)
+	if st != 204 {
+		t.Fatalf("vacío: got %d want 204", st)
+	}
+	body = readJSON(t, get(t, srv.URL, "/api/auth/me", cookie))
+	if body["displayName"] != "" {
+		t.Fatalf("displayName tras vaciar: %v", body)
+	}
+}
+
+// GET /api/users incluye displayName por usuario (admin).
+func TestListUsersIncluyeDisplayName(t *testing.T) {
+	srv := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// Alta de una usuaria no-admin y display name propio (fuera del gate admin)
+	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"clave-ana-1","role":"user"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ := http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 201 {
+		t.Fatalf("crear ana: got %d want 201", res.StatusCode)
+	}
+	_, anaCookie, _ := loginCookie(t, srv.URL, "ana", "clave-ana-1")
+	req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/display-name", strings.NewReader(`{"displayName":"Ana"}`))
+	req.Header.Set("Cookie", "session="+anaCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("display-name no-admin: got %d want 204", res.StatusCode)
+	}
+
+	res = get(t, srv.URL, "/api/users", adminCookie)
+	body := readJSON(t, res)
+	users, ok := body["users"].([]any)
+	if !ok {
+		t.Fatalf("users: %v", body)
+	}
+	names := map[string]any{}
+	for _, u := range users {
+		m := u.(map[string]any)
+		names[fmt.Sprint(m["username"])] = m["displayName"]
+	}
+	if names["ana"] != "Ana" {
+		t.Fatalf("displayName de ana en /api/users: %v", names["ana"])
+	}
+	if names["admin"] != "" {
+		t.Fatalf("displayName de admin debería ser \"\": %v", names["admin"])
+	}
+}

+ 13 - 10
server-go/internal/httpapi/httpapi_test.go

@@ -146,7 +146,7 @@ func TestLoginCorrectoYMe(t *testing.T) {
 		t.Fatalf("me: got %d want 200", res.StatusCode)
 	}
 	body := readJSON(t, res)
-	want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "mode": "demo"}
+	want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "displayName": "", "mode": "demo"}
 	for k, v := range want {
 		if body[k] != v {
 			t.Fatalf("me[%s]: got %v want %v (body=%v)", k, body[k], v, body)
@@ -173,12 +173,15 @@ func TestOverviewProtegido(t *testing.T) {
 		t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
 	}
 	ov := readJSON(t, res2)
-	// Shape del overview (claves del contrato)
-	for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "ts"} {
+	// Shape del overview (claves del contrato; vm SIEMPRE, SPEC-65 D65-4)
+	for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "vm", "ts"} {
 		if _, ok := ov[k]; !ok {
 			t.Fatalf("overview sin clave %q", k)
 		}
 	}
+	if ov["vm"] != float64(1) {
+		t.Fatalf("vm debe ser 1 (ViewModelVersion): %v", ov["vm"])
+	}
 	if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
 		t.Fatalf("routers: %v", ov["routers"])
 	}
@@ -490,11 +493,11 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	srv := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
 
-	// Paginación: 66 dispositivos del dataset canónico (47 base − GS308E, que
-	// ahora es nodo managed, + 20 fixtures topología v5)
+	// Paginación: 65 dispositivos del dataset canónico reconciliado
+	// (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
 	res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
 	body := readJSON(t, res)
-	if body["total"].(float64) != 66 || len(body["items"].([]any)) != 10 {
+	if body["total"].(float64) != 65 || 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 {
@@ -502,7 +505,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)) != 6 {
+	if len(body["items"].([]any)) != 5 {
 		t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
 	}
 	// Sin solape con la página anterior
@@ -526,7 +529,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) != 21 { // 18 base + 3 clientes del switch gestionado (nodo managed)
+	if body["total"].(float64) != 21 { // 17 base + GS308E (Device, D1) + 3 clientes del switch gestionado
 		t.Fatalf("routerId=living: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?band=cable", cookie)
@@ -536,12 +539,12 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 			t.Fatalf("band=cable con item de otra banda: %v", it)
 		}
 	}
-	if body["total"].(float64) != 26 { // 6 base + 20 fixtures cable (3 netgear + pve + 10 CTs + 6 tras switch)
+	if body["total"].(float64) != 27 { // 6 base + 21 fixtures cable (GS308E + 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)
 	body = readJSON(t, res)
-	if body["total"].(float64) != 8 {
+	if body["total"].(float64) != 6 {
 		t.Fatalf("status=offline: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?type=movil", cookie)

+ 89 - 0
server-go/internal/httpapi/push.go

@@ -0,0 +1,89 @@
+// push.go — endpoints Web Push (SPEC-PUSH §1), tras auth de sesión:
+//
+//	GET  /api/push/vapid-key   → {"key":"<base64url>"} (clave pública VAPID)
+//	POST /api/push/subscribe   {endpoint, keys:{auth,p256dh}} → 201/200 (upsert)
+//	POST /api/push/unsubscribe {endpoint} → 204
+package httpapi
+
+import (
+	"net/http"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/push"
+)
+
+// Límites defensivos de longitud (los push endpoints reales son < 1 KB).
+const (
+	maxEndpointLen = 2048
+	maxPushKeyLen  = 512
+)
+
+// handlePushVapidKey (GET): clave pública VAPID para pushManager.subscribe().
+// Asegura el par en kv si faltara (main ya lo genera en el arranque).
+func (s *server) handlePushVapidKey(w http.ResponseWriter, _ *http.Request) {
+	pub, _, err := push.EnsureVAPIDKeys(s.db)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo obtener la clave VAPID")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"key": pub})
+}
+
+type pushSubscribeBody struct {
+	Endpoint string `json:"endpoint"`
+	Keys     struct {
+		Auth   string `json:"auth"`
+		P256dh string `json:"p256dh"`
+	} `json:"keys"`
+}
+
+// handlePushSubscribe (POST): upsert por endpoint. 201 si es nueva, 200 si
+// actualizó una existente (la app solo exige res.ok).
+func (s *server) handlePushSubscribe(w http.ResponseWriter, r *http.Request) {
+	var body pushSubscribeBody
+	if !readJSONBody(r, &body) {
+		writeError(w, http.StatusBadRequest, "invalid_body", "JSON esperado: {endpoint, keys:{auth, p256dh}}")
+		return
+	}
+	body.Endpoint = strings.TrimSpace(body.Endpoint)
+	if body.Endpoint == "" || len(body.Endpoint) > maxEndpointLen ||
+		body.Keys.Auth == "" || len(body.Keys.Auth) > maxPushKeyLen ||
+		body.Keys.P256dh == "" || len(body.Keys.P256dh) > maxPushKeyLen {
+		writeError(w, http.StatusBadRequest, "invalid_body", "endpoint, keys.auth y keys.p256dh son obligatorios")
+		return
+	}
+	created, err := push.UpsertSubscription(s.db, push.Subscription{
+		Endpoint:  body.Endpoint,
+		Auth:      body.Keys.Auth,
+		P256dh:    body.Keys.P256dh,
+		UserAgent: r.UserAgent(),
+		CreatedAt: db.NowMS(),
+	})
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo guardar la suscripción")
+		return
+	}
+	status := http.StatusOK
+	if created {
+		status = http.StatusCreated
+	}
+	writeJSON(w, status, map[string]any{"ok": true})
+}
+
+// handlePushUnsubscribe (POST): baja por endpoint. 204 siempre (idempotente:
+// dar de baja dos veces no es error; la app no bloquea la baja local).
+func (s *server) handlePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Endpoint string `json:"endpoint"`
+	}
+	if !readJSONBody(r, &body) || strings.TrimSpace(body.Endpoint) == "" {
+		writeError(w, http.StatusBadRequest, "invalid_body", "endpoint es obligatorio")
+		return
+	}
+	if err := push.DeleteSubscription(s.db, body.Endpoint); err != nil {
+		writeError(w, http.StatusInternalServerError, "push_unavailable", "no se pudo borrar la suscripción")
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 118 - 0
server-go/internal/httpapi/push_api_test.go

@@ -0,0 +1,118 @@
+// push_api_test.go — contrato de los endpoints Web Push (SPEC-PUSH §1):
+// auth de sesión obligatoria en los 3, vapid-key estable, subscribe 201/200
+// (upsert por endpoint) y unsubscribe 204 idempotente.
+package httpapi_test
+
+import (
+	"io"
+	"strings"
+	"testing"
+)
+
+func TestPushAuthRequired(t *testing.T) {
+	ts := makeTestServer(t)
+	for _, tc := range []struct{ method, path, body string }{
+		{"GET", "/api/push/vapid-key", ""},
+		{"POST", "/api/push/subscribe", `{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"}}`},
+		{"POST", "/api/push/unsubscribe", `{"endpoint":"https://x/y"}`},
+	} {
+		res := doJSON(t, tc.method, ts.URL, tc.path, "", tc.body)
+		if res.StatusCode != 401 {
+			t.Fatalf("%s %s sin sesión: %d, esperaba 401", tc.method, tc.path, res.StatusCode)
+		}
+		res.Body.Close()
+	}
+}
+
+func TestPushEndpointsContract(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+
+	// GET vapid-key: {"key":...} no vacía y ESTABLE entre llamadas; sin '\n'.
+	res := get(t, ts.URL, "/api/push/vapid-key", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("vapid-key: %d", res.StatusCode)
+	}
+	raw, _ := io.ReadAll(res.Body)
+	res.Body.Close()
+	if strings.HasSuffix(string(raw), "\n") {
+		t.Fatal("writeJSON no debe terminar en \\n")
+	}
+	s := string(raw)
+	if !strings.HasPrefix(s, `{"key":"`) || !strings.HasSuffix(s, `"}`) || len(s) <= len(`{"key":""}`) {
+		t.Fatalf("vapid-key body inesperado: %s", s)
+	}
+	res = get(t, ts.URL, "/api/push/vapid-key", cookie)
+	raw2, _ := io.ReadAll(res.Body)
+	res.Body.Close()
+	if string(raw) != string(raw2) {
+		t.Fatalf("vapid-key no estable: %s vs %s", raw, raw2)
+	}
+
+	count := func() int {
+		var n int
+		if err := ts.db.QueryRow("SELECT COUNT(*) FROM push_subscriptions").Scan(&n); err != nil {
+			t.Fatalf("count: %v", err)
+		}
+		return n
+	}
+
+	// POST subscribe: 201 la primera vez.
+	body := `{"endpoint":"https://push.example/abc","keys":{"auth":"a1","p256dh":"p1"}}`
+	res = doJSON(t, "POST", ts.URL, "/api/push/subscribe", cookie, body)
+	if res.StatusCode != 201 {
+		t.Fatalf("subscribe nuevo: %d, esperaba 201", res.StatusCode)
+	}
+	res.Body.Close()
+	if count() != 1 {
+		t.Fatalf("suscripciones: %d, esperaba 1", count())
+	}
+	// Upsert del mismo endpoint (claves nuevas): 200, sin duplicar.
+	body = `{"endpoint":"https://push.example/abc","keys":{"auth":"a2","p256dh":"p2"}}`
+	res = doJSON(t, "POST", ts.URL, "/api/push/subscribe", cookie, body)
+	if res.StatusCode != 200 {
+		t.Fatalf("subscribe upsert: %d, esperaba 200", res.StatusCode)
+	}
+	res.Body.Close()
+	if count() != 1 {
+		t.Fatalf("upsert duplicó: %d filas", count())
+	}
+	var auth string
+	if err := ts.db.QueryRow("SELECT keys_auth FROM push_subscriptions WHERE endpoint = ?", "https://push.example/abc").Scan(&auth); err != nil || auth != "a2" {
+		t.Fatalf("upsert no actualizó claves: auth=%q err=%v", auth, err)
+	}
+	// Cuerpos inválidos → 400.
+	for _, bad := range []string{
+		`nope`,
+		`{"endpoint":"","keys":{"auth":"a","p256dh":"p"}}`,
+		`{"endpoint":"https://x/y"}`,
+		`{"endpoint":"https://x/y","keys":{"auth":"","p256dh":"p"}}`,
+	} {
+		res = doJSON(t, "POST", ts.URL, "/api/push/subscribe", cookie, bad)
+		if res.StatusCode != 400 {
+			t.Fatalf("subscribe body %s: %d, esperaba 400", bad, res.StatusCode)
+		}
+		res.Body.Close()
+	}
+
+	// POST unsubscribe: 204 y la fila desaparece; idempotente.
+	res = doJSON(t, "POST", ts.URL, "/api/push/unsubscribe", cookie, `{"endpoint":"https://push.example/abc"}`)
+	if res.StatusCode != 204 {
+		t.Fatalf("unsubscribe: %d, esperaba 204", res.StatusCode)
+	}
+	res.Body.Close()
+	if count() != 0 {
+		t.Fatalf("tras unsubscribe: %d filas", count())
+	}
+	res = doJSON(t, "POST", ts.URL, "/api/push/unsubscribe", cookie, `{"endpoint":"https://push.example/abc"}`)
+	if res.StatusCode != 204 {
+		t.Fatalf("unsubscribe idempotente: %d, esperaba 204", res.StatusCode)
+	}
+	res.Body.Close()
+	// Unsubscribe sin endpoint → 400.
+	res = doJSON(t, "POST", ts.URL, "/api/push/unsubscribe", cookie, `{"endpoint":""}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("unsubscribe sin endpoint: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+}

+ 41 - 0
server-go/internal/httpapi/refresh.go

@@ -0,0 +1,41 @@
+// refresh.go — POST /api/refresh: sondeo manual bajo demanda (botón
+// "Refrescar" de la página Topología). No devuelve datos: encola un ciclo de
+// sondeo inmediato (tier rápido; los caches LLDP 45 s / backhaul 5 min del
+// adapter live se respetan) y el snapshot fresco llega por el SSE normal.
+// Anti-martilleo: mínimo 5 s entre refreshes manuales → 429 + Retry-After.
+package httpapi
+
+import (
+	"math"
+	"net/http"
+	"strconv"
+	"time"
+)
+
+// refreshMinInterval es el mínimo entre sondeos manuales (global: el sondeo
+// es de todos los routers, da igual qué usuario lo pida).
+const refreshMinInterval = 5 * time.Second
+
+func (s *server) handleRefresh(w http.ResponseWriter, _ *http.Request) {
+	s.refreshMu.Lock()
+	if since := time.Since(s.lastRefresh); since < refreshMinInterval {
+		retry := int(math.Ceil((refreshMinInterval - since).Seconds()))
+		s.refreshMu.Unlock()
+		w.Header().Set("Retry-After", strconv.Itoa(retry))
+		writeJSON(w, http.StatusTooManyRequests, map[string]any{
+			"error":         "rate_limited",
+			"retryAfterSec": retry,
+		})
+		return
+	}
+	s.lastRefresh = time.Now()
+	s.refreshMu.Unlock()
+
+	// Dispara el sondeo en background (nil en tests sin poller → no-op). En
+	// modo demo el poller re-emite el snapshot demo por SSE igualmente; en
+	// live sondea todos los routers (tier rápido). Nunca 500 por esto.
+	if s.pollNow != nil {
+		s.pollNow()
+	}
+	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
+}

+ 140 - 0
server-go/internal/httpapi/refresh_test.go

@@ -0,0 +1,140 @@
+// refresh_test.go — contrato de POST /api/refresh (sondeo manual):
+// 401 sin sesión, 202 {"ok":true} autenticado (dispara PollNow), 429 con
+// Retry-After en ráfaga (< 5 s desde el anterior). En demo no hay 500.
+package httpapi_test
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// makeRefreshServer es makeTestServer + espía de PollNow.
+func makeRefreshServer(t *testing.T) (*testServer, *atomic.Int32) {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	var polls atomic.Int32
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(),
+		Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Secret:  secret,
+		PollNow: func() { polls.Add(1) },
+		Started: time.Now(),
+	})
+	srv := httptest.NewServer(handler)
+	ts := &testServer{Server: srv, db: d, secret: secret}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts, &polls
+}
+
+func postRefresh(t *testing.T, base, cookie string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest("POST", base+"/api/refresh", nil)
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST /api/refresh: %v", err)
+	}
+	return res
+}
+
+func TestRefreshSinSesion401(t *testing.T) {
+	srv, polls := makeRefreshServer(t)
+	res := postRefresh(t, srv.URL, "")
+	body := readJSON(t, res)
+	if res.StatusCode != 401 || body["error"] != "unauthorized" {
+		t.Fatalf("sin sesión: got %d %v", res.StatusCode, body)
+	}
+	if polls.Load() != 0 {
+		t.Fatal("sin sesión no debe disparar sondeo")
+	}
+}
+
+func TestRefreshAutenticado202(t *testing.T) {
+	srv, polls := makeRefreshServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res := postRefresh(t, srv.URL, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 202 || body["ok"] != true {
+		t.Fatalf("autenticado: got %d %v", res.StatusCode, body)
+	}
+	if len(body) != 1 {
+		t.Fatalf("body con claves extra: %v", body)
+	}
+	if polls.Load() != 1 {
+		t.Fatalf("PollNow llamado %d veces, want 1", polls.Load())
+	}
+	// El refresh manual lleva Cache-Control: no-store (como el resto de /api/*).
+	if cc := res.Header.Get("Cache-Control"); cc != "no-store" {
+		t.Fatalf("Cache-Control: %q", cc)
+	}
+}
+
+func TestRefreshRafaga429(t *testing.T) {
+	srv, polls := makeRefreshServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res := postRefresh(t, srv.URL, cookie)
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("1er refresh: got %d want 202", res.StatusCode)
+	}
+	// Ráfaga inmediata → 429 con Retry-After, sin disparar otro sondeo.
+	res = postRefresh(t, srv.URL, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 429 || body["error"] != "rate_limited" {
+		t.Fatalf("ráfaga: got %d %v", res.StatusCode, body)
+	}
+	retry, ok := body["retryAfterSec"].(float64)
+	if !ok || retry <= 0 || retry > 5 {
+		t.Fatalf("retryAfterSec: %v", body)
+	}
+	if ra := res.Header.Get("Retry-After"); ra == "" {
+		t.Fatal("429 sin header Retry-After")
+	}
+	if polls.Load() != 1 {
+		t.Fatalf("PollNow llamado %d veces, want 1 (429 no sondea)", polls.Load())
+	}
+}
+
+func TestRefreshSinPollerNoRompe(t *testing.T) {
+	// Deps sin PollNow (modo demo mínimo): 202 igualmente, nunca 500.
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res := postRefresh(t, srv.URL, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 202 || body["ok"] != true {
+		t.Fatalf("sin poller: got %d %v", res.StatusCode, body)
+	}
+}

+ 42 - 3
server-go/internal/httpapi/server.go

@@ -14,6 +14,7 @@ import (
 	"encoding/json"
 	"net/http"
 	"strings"
+	"sync"
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
@@ -38,9 +39,15 @@ type Deps struct {
 	Secret  string
 	Static  *staticspa.Handler
 	Updater *updater.Updater // nil → sin rutas /api/update/*
+	// Agents: registry de agentes nativos (ingesta POST /api/ingest/agent y
+	// last_seen/versión de GET /api/agents). nil → ingesta 503.
+	Agents *adapters.AgentRegistry
 	// LastOverview devuelve el último overview del poller (nil si aún no hay).
 	LastOverview func() *adapters.Overview
-	Started      time.Time
+	// PollNow dispara un ciclo de sondeo inmediato (POST /api/refresh);
+	// nil → el refresh manual es no-op (tests sin poller).
+	PollNow func()
+	Started time.Time
 }
 
 type server struct {
@@ -49,15 +56,25 @@ type server struct {
 	adapter adapters.Snapshotter
 	hub     *sse.Hub
 	secret  string
+	agents  *adapters.AgentRegistry
 	lastOv  func() *adapters.Overview
+	pollNow func()
 	started time.Time
+
+	// Anti-martilleo de POST /api/refresh (global, min 5 s entre sondeos).
+	refreshMu   sync.Mutex
+	lastRefresh time.Time
+
+	// Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
+	ingestLimit *ipRateLimit
 }
 
 // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
 func NewHandler(d Deps) http.Handler {
 	s := &server{
 		cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
-		secret: d.Secret, lastOv: d.LastOverview, started: d.Started,
+		secret: d.Secret, agents: d.Agents, lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
+		ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
 	}
 	mode := d.Adapter.Mode()
 
@@ -78,13 +95,35 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/routers/{id}", s.handleRouterDetail)
 	mux.HandleFunc("GET /api/devices", s.handleDevices)
 	mux.HandleFunc("GET /api/alerts", s.handleAlerts)
+	mux.HandleFunc("GET /api/alerts/config", s.handleAlertsConfigGet)
+	mux.HandleFunc("PUT /api/alerts/config", s.handleAlertsConfigPut)
+	mux.HandleFunc("POST /api/alerts/read", s.handleAlertsRead)
+	mux.HandleFunc("POST /api/alerts/read-all", s.handleAlertsReadAll)
 	mux.HandleFunc("GET /api/topology", s.handleTopology)
 	mux.HandleFunc("GET /api/dawn", s.handleDawn)
 	mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
+	mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
+
+	// --- Sondeo manual (botón "Refrescar" de Topología; 202 + SSE empuja) ---
+	mux.HandleFunc("POST /api/refresh", s.handleRefresh)
+
+	// --- Agentes nativos (Fase 6) ---
+	// Ingesta: SIN sesión (auth Bearer propia; exenta en RequireAuth).
+	mux.HandleFunc("POST /api/ingest/agent", s.handleIngestAgent)
+	// Gestión de tokens: tras sesión como el resto del API.
+	mux.HandleFunc("POST /api/agents", s.handleAgentsCreate)
+	mux.HandleFunc("GET /api/agents", s.handleAgentsList)
+	mux.HandleFunc("DELETE /api/agents/{slug}", s.handleAgentsDelete)
+
+	// --- Web Push (Fase 6 Bloque C; tras sesión como el resto del API) ---
+	mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)
+	mux.HandleFunc("POST /api/push/subscribe", s.handlePushSubscribe)
+	mux.HandleFunc("POST /api/push/unsubscribe", s.handlePushUnsubscribe)
 
 	// --- Users ---
-	// Idioma propio: FUERA del gate admin (se registra antes en Node).
+	// Idioma y nombre propios: FUERA del gate admin (se registran antes en Node).
 	mux.HandleFunc("PUT /api/users/me/language", s.handleMyLanguage)
+	mux.HandleFunc("PUT /api/users/me/display-name", s.handleMyDisplayName)
 	// Resto: solo admin.
 	mux.Handle("GET /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleListUsers)))
 	mux.Handle("POST /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleCreateUser)))

+ 112 - 0
server-go/internal/httpapi/system.go

@@ -0,0 +1,112 @@
+// system.go — GET /api/system/info (SPEC-65 D65-6): datos REALES del
+// proceso/servidor (nunca hardcodeados), autenticado (cualquier usuario).
+// Las lecturas de /proc y /etc tienen fallback amable ("" / 0) si no son
+// legibles (p.ej. contenedor sin /proc completo); los parseadores son
+// funciones puras para testearlas con fixtures.
+package httpapi
+
+import (
+	"net/http"
+	"os"
+	"runtime"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// systemInfo es la respuesta de GET /api/system/info.
+type systemInfo struct {
+	Version    string `json:"version"`    // versión de la app (const Version, la de update.go)
+	GoVersion  string `json:"goVersion"`  // runtime.Version()
+	OS         string `json:"os"`         // runtime.GOOS
+	Arch       string `json:"arch"`       // runtime.GOARCH
+	Distro     string `json:"distro"`     // /etc/os-release PRETTY_NAME ("" si no legible)
+	Kernel     string `json:"kernel"`     // /proc/sys/kernel/osrelease ("" si no legible)
+	CPUModel   string `json:"cpuModel"`   // /proc/cpuinfo "model name" (o "Model" en ARM)
+	CPUCores   int    `json:"cpuCores"`   // runtime.NumCPU()
+	MemTotalMb int64  `json:"memTotalMb"` // /proc/meminfo MemTotal → MiB
+	UptimeS    int64  `json:"uptimeS"`    // uptime del PROCESO netpulse, segundos
+	Demo       bool   `json:"demo"`       // DEMO_MODE activo
+}
+
+// parseOsReleasePretty extrae PRETTY_NAME de un contenido de os-release
+// ("" si ausente). Tolera comillas y espacios.
+func parseOsReleasePretty(content string) string {
+	for _, line := range strings.Split(content, "\n") {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, "PRETTY_NAME=") {
+			continue
+		}
+		v := strings.TrimPrefix(line, "PRETTY_NAME=")
+		v = strings.TrimSpace(v)
+		v = strings.Trim(v, `"`)
+		return v
+	}
+	return ""
+}
+
+// parseCPUModel devuelve la primera entrada "model name" (x86) o "Model"
+// (ARM/DeviceTree) de un contenido de /proc/cpuinfo ("" si ninguna).
+func parseCPUModel(content string) string {
+	for _, line := range strings.Split(content, "\n") {
+		key, val, ok := strings.Cut(line, ":")
+		if !ok {
+			continue
+		}
+		switch strings.TrimSpace(key) {
+		case "model name", "Model":
+			return strings.TrimSpace(val)
+		}
+	}
+	return ""
+}
+
+// parseMemTotalMB convierte MemTotal (kB) de un contenido de /proc/meminfo a
+// MiB (0 si ausente o inválido).
+func parseMemTotalMB(content string) int64 {
+	for _, line := range strings.Split(content, "\n") {
+		if !strings.HasPrefix(line, "MemTotal:") {
+			continue
+		}
+		fields := strings.Fields(line)
+		if len(fields) < 2 {
+			return 0
+		}
+		kb, err := strconv.ParseInt(fields[1], 10, 64)
+		if err != nil {
+			return 0
+		}
+		return kb / 1024
+	}
+	return 0
+}
+
+// readFileOrEmpty lee un fichero de texto del sistema ("" si no legible).
+func readFileOrEmpty(path string) string {
+	b, err := os.ReadFile(path)
+	if err != nil {
+		return ""
+	}
+	return string(b)
+}
+
+// handleSystemInfo: 200 con los datos del proceso/servidor (sesión).
+func (s *server) handleSystemInfo(w http.ResponseWriter, _ *http.Request) {
+	started := s.started
+	if started.IsZero() {
+		started = time.Now() // tests sin Started: uptime ~0 en vez de negativo
+	}
+	writeJSON(w, http.StatusOK, systemInfo{
+		Version:    Version,
+		GoVersion:  runtime.Version(),
+		OS:         runtime.GOOS,
+		Arch:       runtime.GOARCH,
+		Distro:     parseOsReleasePretty(readFileOrEmpty("/etc/os-release")),
+		Kernel:     strings.TrimSpace(readFileOrEmpty("/proc/sys/kernel/osrelease")),
+		CPUModel:   parseCPUModel(readFileOrEmpty("/proc/cpuinfo")),
+		CPUCores:   runtime.NumCPU(),
+		MemTotalMb: parseMemTotalMB(readFileOrEmpty("/proc/meminfo")),
+		UptimeS:    int64(time.Since(started).Seconds()),
+		Demo:       s.adapter.Mode() == "demo",
+	})
+}

+ 57 - 0
server-go/internal/httpapi/system_api_test.go

@@ -0,0 +1,57 @@
+package httpapi_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+)
+
+// SPEC-65 D65-6: GET /api/system/info — autenticado (cualquier usuario),
+// datos reales del proceso con la forma exacta del contrato.
+func TestSystemInfo(t *testing.T) {
+	srv := makeTestServer(t)
+
+	// Sin sesión → 401
+	res := get(t, srv.URL, "/api/system/info", "")
+	if res.StatusCode != 401 {
+		res.Body.Close()
+		t.Fatalf("sin cookie: got %d want 401", res.StatusCode)
+	}
+	res.Body.Close()
+
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res = get(t, srv.URL, "/api/system/info", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("con cookie: got %d want 200", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	// Forma exacta: las 11 claves del contrato, ni una más
+	want := map[string]bool{
+		"version": true, "goVersion": true, "os": true, "arch": true, "distro": true,
+		"kernel": true, "cpuModel": true, "cpuCores": true, "memTotalMb": true,
+		"uptimeS": true, "demo": true,
+	}
+	if len(body) != len(want) {
+		t.Fatalf("claves: got %v", body)
+	}
+	for k := range want {
+		if _, ok := body[k]; !ok {
+			t.Fatalf("falta clave %q en %v", k, body)
+		}
+	}
+	if body["version"] != httpapi.Version {
+		t.Fatalf("version=%v, want %s (misma fuente que update.go)", body["version"], httpapi.Version)
+	}
+	if goVer, ok := body["goVersion"].(string); !ok || len(goVer) < 3 || goVer[:2] != "go" {
+		t.Fatalf("goVersion: %v", body["goVersion"])
+	}
+	if cores, ok := body["cpuCores"].(float64); !ok || cores < 1 {
+		t.Fatalf("cpuCores: %v", body["cpuCores"])
+	}
+	if up, ok := body["uptimeS"].(float64); !ok || up < 0 {
+		t.Fatalf("uptimeS: %v", body["uptimeS"])
+	}
+	if body["demo"] != true {
+		t.Fatalf("demo: %v (el servidor de test es DEMO_MODE=1)", body["demo"])
+	}
+}

+ 58 - 0
server-go/internal/httpapi/system_internal_test.go

@@ -0,0 +1,58 @@
+package httpapi
+
+import "testing"
+
+// Tests de los parseadores puros de /api/system/info (SPEC-65 D65-6) con
+// fixtures literales de /etc/os-release, /proc/cpuinfo y /proc/meminfo.
+
+func TestParseOsReleasePretty(t *testing.T) {
+	cases := []struct {
+		name, content, want string
+	}{
+		{"debian", "NAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12\"\nPRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\n", "Debian GNU/Linux 12 (bookworm)"},
+		{"sin comillas", "PRETTY_NAME=Ubuntu 24.04 LTS\nNAME=Ubuntu\n", "Ubuntu 24.04 LTS"},
+		{"openwrt", "NAME=\"OpenWrt\"\nPRETTY_NAME=\"OpenWrt 24.10.1\"\n", "OpenWrt 24.10.1"},
+		{"ausente", "NAME=\"Algo\"\nVERSION_ID=\"1\"\n", ""},
+		{"vacío", "", ""},
+	}
+	for _, c := range cases {
+		if got := parseOsReleasePretty(c.content); got != c.want {
+			t.Fatalf("%s: parseOsReleasePretty=%q, want %q", c.name, got, c.want)
+		}
+	}
+}
+
+func TestParseCPUModel(t *testing.T) {
+	x86 := "processor\t: 0\nvendor_id\t: GenuineIntel\nmodel name\t: Intel(R) N100\n\ncpu cores\t: 4\n"
+	if got := parseCPUModel(x86); got != "Intel(R) N100" {
+		t.Fatalf("x86: %q", got)
+	}
+	arm := "processor\t: 0\nBogoMIPS\t: 38.40\nFeatures\t: fp asimd\nCPU implementer\t: 0x41\nModel\t\t: Raspberry Pi 4 Model B Rev 1.4\n"
+	if got := parseCPUModel(arm); got != "Raspberry Pi 4 Model B Rev 1.4" {
+		t.Fatalf("arm: %q", got)
+	}
+	// model name gana aunque haya varias entradas (la primera)
+	multi := "model name\t: Fake CPU A\n\nmodel name\t: Fake CPU B\n"
+	if got := parseCPUModel(multi); got != "Fake CPU A" {
+		t.Fatalf("multi: %q", got)
+	}
+	if got := parseCPUModel("nada\nque\tvalga\n"); got != "" {
+		t.Fatalf("sin modelo: %q", got)
+	}
+}
+
+func TestParseMemTotalMB(t *testing.T) {
+	mem := "MemTotal:        8175476 kB\nMemFree:         1234567 kB\nMemAvailable:    4000000 kB\n"
+	if got := parseMemTotalMB(mem); got != 8175476/1024 {
+		t.Fatalf("memTotal: %d", got)
+	}
+	if got := parseMemTotalMB("MemFree: 10 kB\n"); got != 0 {
+		t.Fatalf("sin MemTotal: %d", got)
+	}
+	if got := parseMemTotalMB("MemTotal: abc kB\n"); got != 0 {
+		t.Fatalf("MemTotal inválido: %d", got)
+	}
+	if got := parseMemTotalMB(""); got != 0 {
+		t.Fatalf("vacío: %d", got)
+	}
+}

+ 39 - 9
server-go/internal/httpapi/users.go

@@ -1,6 +1,7 @@
 // users.go — CRUD de usuarios (paridad routes/users.js).
 //
 //	PUT  /api/users/me/language   (cualquier rol — fuera del gate admin)
+//	PUT  /api/users/me/display-name (cualquier rol — fuera del gate admin)
 //	GET  /api/users               (admin)
 //	POST /api/users               (admin) → 201 · 400 · 409
 //	PUT  /api/users/:id/password  (admin) → 204 (invalida sus sesiones)
@@ -14,6 +15,7 @@ import (
 	"regexp"
 	"strconv"
 	"strings"
+	"unicode/utf8"
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/db"
@@ -52,6 +54,31 @@ func (s *server) adminCount() int {
 	return n
 }
 
+// handleMyDisplayName (SPEC-65 D65-5): {displayName: string} → 204 (fuera del
+// gate admin). Trim, máx 40 runes, vacío permitido (= volver al username) y
+// sin '<' ni '>' (el frontend ya escapa, pero no se permite HTML).
+func (s *server) handleMyDisplayName(w http.ResponseWriter, r *http.Request) {
+	me := auth.UserFromContext(r.Context())
+	var body struct {
+		DisplayName *string `json:"displayName"`
+	}
+	if !readJSONBody(r, &body) || body.DisplayName == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", `Se esperaba { "displayName": string }`)
+		return
+	}
+	name := strings.TrimSpace(*body.DisplayName)
+	if utf8.RuneCountInString(name) > 40 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "displayName máximo 40 caracteres")
+		return
+	}
+	if strings.ContainsAny(name, "<>") {
+		writeError(w, http.StatusBadRequest, "invalid_input", "displayName no puede contener '<' ni '>'")
+		return
+	}
+	_, _ = s.db.Exec("UPDATE users SET display_name = ? WHERE id = ?", name, me.ID)
+	w.WriteHeader(http.StatusNoContent)
+}
+
 // handleMyLanguage: {language: auto|es|en} → 204 (fuera del gate admin).
 func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
 	me := auth.UserFromContext(r.Context())
@@ -67,9 +94,10 @@ func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
 	w.WriteHeader(http.StatusNoContent)
 }
 
-// handleListUsers: {users:[{id, username, role, language, created_at}]} por username.
+// handleListUsers: {users:[{id, username, role, language, displayName, created_at}]}
+// por username (SPEC-65 D65-5: displayName, "" si no puesto).
 func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
-	rows, err := s.db.Query("SELECT id, username, role, language, created_at FROM users ORDER BY username")
+	rows, err := s.db.Query("SELECT id, username, role, language, display_name, created_at FROM users ORDER BY username")
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
 		return
@@ -78,13 +106,14 @@ func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
 	users := []map[string]any{}
 	for rows.Next() {
 		var (
-			id        int64
-			username  string
-			role      string
-			language  sql.NullString
-			createdAt int64
+			id          int64
+			username    string
+			role        string
+			language    sql.NullString
+			displayName sql.NullString
+			createdAt   int64
 		)
-		if err := rows.Scan(&id, &username, &role, &language, &createdAt); err != nil {
+		if err := rows.Scan(&id, &username, &role, &language, &displayName, &createdAt); err != nil {
 			continue
 		}
 		var lang any
@@ -92,7 +121,8 @@ func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
 			lang = language.String
 		}
 		users = append(users, map[string]any{
-			"id": id, "username": username, "role": role, "language": lang, "created_at": createdAt,
+			"id": id, "username": username, "role": role, "language": lang,
+			"displayName": displayName.String, "created_at": createdAt,
 		})
 	}
 	writeJSON(w, http.StatusOK, map[string]any{"users": users})

+ 23 - 2
server-go/internal/poller/poller.go

@@ -36,6 +36,9 @@ type Poller struct {
 	stopCh chan struct{}
 	doneCh chan struct{}
 	once   sync.Once
+
+	// tickMu serializa los ticks (ticker 5 s + sondeos manuales PollNow).
+	tickMu sync.Mutex
 }
 
 // New crea el poller.
@@ -58,7 +61,7 @@ func (p *Poller) LastOverview() *adapters.Overview {
 func (p *Poller) Start() {
 	go func() {
 		defer close(p.doneCh)
-		p.tick()
+		p.tickOnce()
 		t := time.NewTicker(TickMS)
 		defer t.Stop()
 		for {
@@ -66,12 +69,30 @@ func (p *Poller) Start() {
 			case <-p.stopCh:
 				return
 			case <-t.C:
-				p.tick()
+				p.tickOnce()
 			}
 		}
 	}()
 }
 
+// PollNow solicita un ciclo de sondeo inmediato (POST /api/refresh). No
+// bloquea al caller HTTP: el tick corre en background y el snapshot fresco
+// llega por el broadcast SSE normal. Si ya hay un tick en curso (manual o
+// del ticker) no apila otro: ese snapshot también estará fresco.
+func (p *Poller) PollNow() {
+	go p.tickOnce()
+}
+
+// tickOnce ejecuta un tick solo si no hay otro en curso (evita solapar
+// sondeos SSH de todos los routers cuando coinciden ticker y refresh manual).
+func (p *Poller) tickOnce() {
+	if !p.tickMu.TryLock() {
+		return
+	}
+	defer p.tickMu.Unlock()
+	p.tick()
+}
+
 // Stop detiene el bucle y espera a que termine el tick en curso.
 func (p *Poller) Stop() {
 	p.once.Do(func() {

+ 163 - 0
server-go/internal/push/notifier.go

@@ -0,0 +1,163 @@
+// notifier.go — push.Notifier: implementa alerts.Notifier (SPEC-PUSH §1).
+// Notify NUNCA bloquea al llamador (el motor de alertas lo invoca desde el
+// ciclo de sondeo): encola el evento y un worker único lo drena, enviando a
+// todas las suscripciones con timeout de 10 s por envío. 404/410 del push
+// service → suscripción muerta → se purga de la DB.
+package push
+
+import (
+	"context"
+	"encoding/json"
+	"io"
+	"log/slog"
+	"net/http"
+	"sync"
+	"time"
+
+	webpush "github.com/SherClockHolmes/webpush-go"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+const (
+	// queueCap acota la cola: ráfagas de urgentes no pueden crecer sin
+	// límite; si se llena se descarta (el panel ya muestra la alerta).
+	queueCap = 64
+	// sendTimeout por envío individual (SPEC-PUSH §1: 10 s).
+	sendTimeout = 10 * time.Second
+	// ttl de la notificación en el push service (1 h: si el móvil está
+	// apagado más tiempo, la alerta ya es historia).
+	ttlSeconds = 3600
+	// subscriber VAPID (sub del JWT; informativo para el push service).
+	// webpush-go antepone "mailto:" si no empieza por "https:".
+	subscriber = "netpulse@localhost"
+)
+
+// payload es el JSON cifrado que recibe el Service Worker (contrato con
+// app/src/sw.ts: {title, body, category, severity, url, tag}).
+type payload struct {
+	Title    string `json:"title"`
+	Body     string `json:"body"`
+	Category string `json:"category"`
+	Severity string `json:"severity"`
+	URL      string `json:"url"`
+	Tag      string `json:"tag"` // alertId: dedup nativo del navegador
+}
+
+// Notifier implementa alerts.Notifier con entrega asíncrona.
+type Notifier struct {
+	db     *db.DB
+	pub    string
+	priv   string
+	client *http.Client
+
+	ch   chan alerts.AlertEvent
+	done chan struct{} // cerrado en Close: Notify posterior es no-op
+	once sync.Once
+	wg   sync.WaitGroup
+}
+
+// NewNotifier crea el Notifier y arranca su worker. pub/priv son el par
+// VAPID de EnsureVAPIDKeys.
+func NewNotifier(d *db.DB, pub, priv string) *Notifier {
+	n := &Notifier{
+		db:     d,
+		pub:    pub,
+		priv:   priv,
+		client: &http.Client{Timeout: sendTimeout},
+		ch:     make(chan alerts.AlertEvent, queueCap),
+		done:   make(chan struct{}),
+	}
+	n.wg.Add(1)
+	go n.worker()
+	return n
+}
+
+// Notify encola el evento y vuelve inmediatamente (nunca bloquea el poll).
+// Si la cola está llena descarta con aviso: el evento ya está en /api/alerts.
+func (n *Notifier) Notify(ev alerts.AlertEvent) {
+	select {
+	case <-n.done:
+		return
+	case n.ch <- ev:
+	default:
+		slog.Warn("push: cola llena, notificación descartada", "alertId", ev.ID, "title", ev.Title)
+	}
+}
+
+// Close para el worker y espera al envío en curso (acotado por sendTimeout).
+func (n *Notifier) Close() {
+	n.once.Do(func() {
+		close(n.done)
+		close(n.ch)
+		n.wg.Wait()
+	})
+}
+
+func (n *Notifier) worker() {
+	defer n.wg.Done()
+	for ev := range n.ch {
+		n.sendAll(ev)
+	}
+}
+
+// payloadJSON serializa el cuerpo de la notificación (SPEC-PUSH §1).
+func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
+	return json.Marshal(payload{
+		Title:    ev.Title,
+		Body:     ev.Description,
+		Category: ev.Category,
+		Severity: ev.Severity,
+		URL:      "/alerts",
+		Tag:      ev.ID,
+	})
+}
+
+// sendAll envía el evento a TODAS las suscripciones y purga las muertas.
+func (n *Notifier) sendAll(ev alerts.AlertEvent) {
+	body, err := payloadJSON(ev)
+	if err != nil {
+		slog.Error("push: payload no serializable", "alertId", ev.ID, "error", err)
+		return
+	}
+	subs, err := ListSubscriptions(n.db)
+	if err != nil {
+		slog.Error("push: no se pudieron listar suscripciones", "alertId", ev.ID, "error", err)
+		return
+	}
+	for _, s := range subs {
+		n.sendOne(ev, body, s)
+	}
+}
+
+func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
+	resp, err := webpush.SendNotificationWithContext(context.Background(), body,
+		&webpush.Subscription{
+			Endpoint: s.Endpoint,
+			Keys:     webpush.Keys{Auth: s.Auth, P256dh: s.P256dh},
+		},
+		&webpush.Options{
+			HTTPClient:      n.client,
+			Subscriber:      subscriber,
+			VAPIDPublicKey:  n.pub,
+			VAPIDPrivateKey: n.priv,
+			TTL:             ttlSeconds,
+		})
+	if err != nil {
+		slog.Warn("push: envío fallido", "alertId", ev.ID, "endpoint", s.Endpoint, "error", err)
+		return
+	}
+	defer resp.Body.Close()
+	_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
+	if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone {
+		// Suscripción muerta (expirada o dada de baja): purgar (SPEC-PUSH §1).
+		if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
+			slog.Error("push: no se pudo purgar suscripción muerta", "endpoint", s.Endpoint, "error", err)
+		}
+		slog.Info("push: suscripción purgada", "endpoint", s.Endpoint, "status", resp.StatusCode)
+		return
+	}
+	if resp.StatusCode >= 400 {
+		slog.Warn("push: push service respondió error", "alertId", ev.ID, "endpoint", s.Endpoint, "status", resp.StatusCode)
+	}
+}

+ 110 - 0
server-go/internal/push/push.go

@@ -0,0 +1,110 @@
+// Package push — Web Push nativo (SPEC-PUSH §1): par VAPID en kv, store de
+// suscripciones (tabla push_subscriptions) y Notifier que implementa
+// alerts.Notifier enviando a TODAS las suscripciones sin bloquear el poll
+// (cola interna acotada + worker único).
+//
+// Claves kv:
+//   - push.vapid.private / push.vapid.public: par VAPID (base64url) generado
+//     en el primer arranque (o en el primer uso si falta).
+package push
+
+import (
+	"database/sql"
+	"errors"
+	"fmt"
+
+	webpush "github.com/SherClockHolmes/webpush-go"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// Claves kv del par VAPID (SPEC-PUSH §1).
+const (
+	vapidPrivateKey = "push.vapid.private"
+	vapidPublicKey  = "push.vapid.public"
+)
+
+// Subscription es una fila de push_subscriptions.
+type Subscription struct {
+	Endpoint  string
+	Auth      string
+	P256dh    string
+	UserAgent string
+	CreatedAt int64 // epoch ms (convención del resto de la DB)
+}
+
+// EnsureVAPIDKeys devuelve (public, private) del par VAPID; si no existe en
+// kv lo genera y lo persiste (idempotente: la pública es estable entre
+// llamadas y entre reinicios).
+func EnsureVAPIDKeys(d *db.DB) (pub, priv string, err error) {
+	pub = kvGet(d, vapidPublicKey)
+	priv = kvGet(d, vapidPrivateKey)
+	if pub != "" && priv != "" {
+		return pub, priv, nil
+	}
+	priv, pub, err = webpush.GenerateVAPIDKeys()
+	if err != nil {
+		return "", "", fmt.Errorf("generar par VAPID: %w", err)
+	}
+	for _, kv := range [][2]string{{vapidPrivateKey, priv}, {vapidPublicKey, pub}} {
+		if _, err := d.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+			kv[0], kv[1]); err != nil {
+			return "", "", fmt.Errorf("guardar %s: %w", kv[0], err)
+		}
+	}
+	return pub, priv, nil
+}
+
+func kvGet(d *db.DB, key string) string {
+	var v string
+	if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
+		return "" // sql.ErrNoRows incluido: tratado como "no existe"
+	}
+	return v
+}
+
+// UpsertSubscription inserta o actualiza por endpoint (la app re-suscribe el
+// mismo endpoint al rotar claves). Devuelve created=true si era nueva.
+func UpsertSubscription(d *db.DB, s Subscription) (created bool, err error) {
+	var exists int
+	err = d.QueryRow("SELECT 1 FROM push_subscriptions WHERE endpoint = ?", s.Endpoint).Scan(&exists)
+	if err != nil && !errors.Is(err, sql.ErrNoRows) {
+		return false, err
+	}
+	created = errors.Is(err, sql.ErrNoRows)
+	if s.CreatedAt == 0 {
+		s.CreatedAt = db.NowMS()
+	}
+	_, err = d.Exec(`INSERT INTO push_subscriptions (endpoint, keys_auth, keys_p256dh, user_agent, created_at)
+		VALUES (?, ?, ?, ?, ?)
+		ON CONFLICT(endpoint) DO UPDATE SET keys_auth=excluded.keys_auth,
+			keys_p256dh=excluded.keys_p256dh, user_agent=excluded.user_agent`,
+		s.Endpoint, s.Auth, s.P256dh, s.UserAgent, s.CreatedAt)
+	return created, err
+}
+
+// DeleteSubscription borra por endpoint (idempotente: no error si no existe).
+func DeleteSubscription(d *db.DB, endpoint string) error {
+	_, err := d.Exec("DELETE FROM push_subscriptions WHERE endpoint = ?", endpoint)
+	return err
+}
+
+// ListSubscriptions devuelve todas las suscripciones registradas.
+func ListSubscriptions(d *db.DB) ([]Subscription, error) {
+	rows, err := d.Query("SELECT endpoint, keys_auth, keys_p256dh, user_agent, created_at FROM push_subscriptions")
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []Subscription{}
+	for rows.Next() {
+		var s Subscription
+		var ua sql.NullString
+		if err := rows.Scan(&s.Endpoint, &s.Auth, &s.P256dh, &ua, &s.CreatedAt); err != nil {
+			return nil, err
+		}
+		s.UserAgent = ua.String
+		out = append(out, s)
+	}
+	return out, rows.Err()
+}

+ 327 - 0
server-go/internal/push/push_test.go

@@ -0,0 +1,327 @@
+// push_test.go — contrato del Bloque C (SPEC-PUSH §1): VAPID estable en kv,
+// roundtrip del store de suscripciones, purga de suscripciones muertas
+// (404/410) y Notify con payload cifrado verificable contra un push service
+// simulado con httptest (descifrado aes128gcm RFC 8291/8188).
+package push_test
+
+import (
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/sha256"
+	"encoding/base64"
+	"encoding/binary"
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/push"
+	"golang.org/x/crypto/hkdf"
+)
+
+func openDB(t *testing.T) (*db.DB, string) {
+	t.Helper()
+	dir := t.TempDir()
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d, dir
+}
+
+func TestVAPIDStable(t *testing.T) {
+	d, dir := openDB(t)
+	pub1, priv1, err := push.EnsureVAPIDKeys(d)
+	if err != nil {
+		t.Fatalf("EnsureVAPIDKeys: %v", err)
+	}
+	if pub1 == "" || priv1 == "" || pub1 == priv1 {
+		t.Fatalf("par VAPID inválido: pub=%q priv=%q", pub1, priv1)
+	}
+	// Segunda llamada: mismo par (no regenera).
+	pub2, priv2, _ := push.EnsureVAPIDKeys(d)
+	if pub1 != pub2 || priv1 != priv2 {
+		t.Fatal("VAPID no estable entre llamadas")
+	}
+	// Reinicio (reabrir la misma DB): mismo par (persistido en kv).
+	d.Close()
+	d2, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("reabrir db: %v", err)
+	}
+	defer d2.Close()
+	pub3, priv3, _ := push.EnsureVAPIDKeys(d2)
+	if pub1 != pub3 || priv1 != priv3 {
+		t.Fatal("VAPID no estable entre reinicios")
+	}
+}
+
+func TestStoreRoundtrip(t *testing.T) {
+	d, _ := openDB(t)
+	sub := push.Subscription{Endpoint: "https://push.example/abc", Auth: "a", P256dh: "p", UserAgent: "test-ua"}
+	created, err := push.UpsertSubscription(d, sub)
+	if err != nil || !created {
+		t.Fatalf("upsert nuevo: created=%v err=%v", created, err)
+	}
+	// Upsert del mismo endpoint: actualiza, no duplica.
+	sub.Auth = "a2"
+	created, err = push.UpsertSubscription(d, sub)
+	if err != nil || created {
+		t.Fatalf("upsert existente: created=%v err=%v", created, err)
+	}
+	subs, err := push.ListSubscriptions(d)
+	if err != nil || len(subs) != 1 {
+		t.Fatalf("list: %v %v", subs, err)
+	}
+	if subs[0].Auth != "a2" || subs[0].P256dh != "p" || subs[0].UserAgent != "test-ua" || subs[0].CreatedAt <= 0 {
+		t.Fatalf("fila: %+v", subs[0])
+	}
+	if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
+		t.Fatalf("delete: %v", err)
+	}
+	// Idempotente: borrar de nuevo no es error.
+	if err := push.DeleteSubscription(d, sub.Endpoint); err != nil {
+		t.Fatalf("delete idempotente: %v", err)
+	}
+	subs, _ = push.ListSubscriptions(d)
+	if len(subs) != 0 {
+		t.Fatalf("tras delete: %d suscripciones", len(subs))
+	}
+}
+
+// browserSub simula una PushSubscription del navegador: par ECDH P-256 y
+// auth secret (16 B), devueltos para poder descifrar en el test.
+type browserSub struct {
+	auth  []byte
+	priv  []byte
+	pub   []byte // uncompressed point (65 B)
+	authB string
+	pubB  string
+}
+
+func newBrowserSub(t *testing.T) browserSub {
+	t.Helper()
+	priv, x, y, err := elliptic.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatalf("keypair navegador: %v", err)
+	}
+	pub := elliptic.Marshal(elliptic.P256(), x, y)
+	auth := make([]byte, 16)
+	if _, err := rand.Read(auth); err != nil {
+		t.Fatalf("auth secret: %v", err)
+	}
+	return browserSub{
+		auth:  auth,
+		priv:  priv,
+		pub:   pub,
+		authB: base64.RawURLEncoding.EncodeToString(auth),
+		pubB:  base64.RawURLEncoding.EncodeToString(pub),
+	}
+}
+
+type capturedPush struct {
+	method string
+	header http.Header
+	body   []byte
+}
+
+// decryptAES128GCM descifra el cuerpo tal y como lo haría el navegador
+// (RFC 8291 §3.4 + RFC 8188 §2: header salt|rs|idlen|keyid en el cuerpo,
+// registro único con delimitador 0x02 y padding de ceros al final).
+func decryptAES128GCM(t *testing.T, ua browserSub, body []byte) []byte {
+	t.Helper()
+	if len(body) < 16+4+1+65+17 {
+		t.Fatalf("cuerpo cifrado demasiado corto: %d B", len(body))
+	}
+	salt := body[:16]
+	rs := binary.BigEndian.Uint32(body[16:20])
+	idlen := int(body[20])
+	asPub := body[21 : 21+idlen]
+	ciphertext := body[21+idlen:]
+	if rs < uint32(len(ciphertext)) {
+		t.Fatalf("record size incoherente: rs=%d ct=%d", rs, len(ciphertext))
+	}
+
+	curve := elliptic.P256()
+	x, y := elliptic.Unmarshal(curve, asPub)
+	if x == nil {
+		t.Fatal("clave efímera del servidor no es un punto válido")
+	}
+	sx, _ := curve.ScalarMult(x, y, ua.priv)
+	secret := make([]byte, 32)
+	sx.FillBytes(secret)
+
+	read := func(prkSecret, hkdfSalt, info []byte, n int) []byte {
+		out := make([]byte, n)
+		if _, err := io.ReadFull(hkdf.New(sha256.New, prkSecret, hkdfSalt, info), out); err != nil {
+			t.Fatalf("hkdf: %v", err)
+		}
+		return out
+	}
+	info := append(append([]byte("WebPush: info\x00"), ua.pub...), asPub...)
+	ikm := read(secret, ua.auth, info, 32)
+	cek := read(ikm, salt, []byte("Content-Encoding: aes128gcm\x00"), 16)
+	nonce := read(ikm, salt, []byte("Content-Encoding: nonce\x00"), 12)
+
+	block, err := aes.NewCipher(cek)
+	if err != nil {
+		t.Fatalf("aes: %v", err)
+	}
+	gcm, err := cipher.NewGCM(block)
+	if err != nil {
+		t.Fatalf("gcm: %v", err)
+	}
+	plain, err := gcm.Open(nil, nonce, ciphertext, nil)
+	if err != nil {
+		t.Fatalf("descifrado GCM (¿claves mal derivadas?): %v", err)
+	}
+	// Quitar padding: ceros finales + delimitador 0x02 (registro final).
+	i := len(plain) - 1
+	for i >= 0 && plain[i] == 0 {
+		i--
+	}
+	if i < 0 || plain[i] != 0x02 {
+		t.Fatalf("delimitador 0x02 no encontrado (plain=%d B)", len(plain))
+	}
+	return plain[:i]
+}
+
+func testEvent() alerts.AlertEvent {
+	return alerts.AlertEvent{
+		ID:          "alert-test-1",
+		Category:    alerts.CatRouter,
+		Urgent:      true,
+		Severity:    "critical",
+		Title:       "Router sin respuesta",
+		Description: "Sin respuesta de 192.168.8.1",
+	}
+}
+
+func newNotifier(t *testing.T, d *db.DB) *push.Notifier {
+	t.Helper()
+	pub, priv, err := push.EnsureVAPIDKeys(d)
+	if err != nil {
+		t.Fatalf("vapid: %v", err)
+	}
+	n := push.NewNotifier(d, pub, priv)
+	t.Cleanup(n.Close)
+	return n
+}
+
+// El Notifier envía un POST cifrado aes128gcm con cabecera VAPID al endpoint
+// suscrito, y el payload descifrado cumple el contrato del SW.
+func TestNotifierSendsEncryptedPayload(t *testing.T) {
+	d, _ := openDB(t)
+	pub, _, _ := push.EnsureVAPIDKeys(d)
+	ua := newBrowserSub(t)
+
+	got := make(chan capturedPush, 1)
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		body, _ := io.ReadAll(r.Body)
+		got <- capturedPush{method: r.Method, header: r.Header.Clone(), body: body}
+		w.WriteHeader(http.StatusCreated)
+	}))
+	defer srv.Close()
+
+	if _, err := push.UpsertSubscription(d, push.Subscription{
+		Endpoint: srv.URL, Auth: ua.authB, P256dh: ua.pubB,
+	}); err != nil {
+		t.Fatalf("upsert: %v", err)
+	}
+
+	n := newNotifier(t, d)
+	n.Notify(testEvent())
+
+	var req capturedPush
+	select {
+	case req = <-got:
+	case <-time.After(15 * time.Second):
+		t.Fatal("el push service simulado no recibió nada en 15 s")
+	}
+
+	if req.method != http.MethodPost {
+		t.Fatalf("método: %s, esperaba POST", req.method)
+	}
+	if enc := req.header.Get("Content-Encoding"); enc != "aes128gcm" {
+		t.Fatalf("Content-Encoding: %q", enc)
+	}
+	if ttl := req.header.Get("TTL"); ttl != "3600" {
+		t.Fatalf("TTL: %q", ttl)
+	}
+	authz := req.header.Get("Authorization")
+	if !strings.HasPrefix(authz, "vapid t=") || !strings.Contains(authz, ", k=") {
+		t.Fatalf("Authorization VAPID: %q", authz)
+	}
+	if !strings.Contains(authz, ", k="+pub) {
+		t.Fatal("la cabecera VAPID no lleva la clave pública servida en /api/push/vapid-key")
+	}
+
+	plain := decryptAES128GCM(t, ua, req.body)
+	var p struct {
+		Title    string `json:"title"`
+		Body     string `json:"body"`
+		Category string `json:"category"`
+		Severity string `json:"severity"`
+		URL      string `json:"url"`
+		Tag      string `json:"tag"`
+	}
+	if err := json.Unmarshal(plain, &p); err != nil {
+		t.Fatalf("payload no es JSON: %v (%q)", err, plain)
+	}
+	if p.Title != "Router sin respuesta" || p.Body != "Sin respuesta de 192.168.8.1" ||
+		p.Category != "router" || p.Severity != "critical" || p.URL != "/alerts" || p.Tag != "alert-test-1" {
+		t.Fatalf("payload: %+v", p)
+	}
+}
+
+// Un push service que responde 410 (suscripción expirada) provoca la purga
+// de la fila; el resto de suscripciones se conserva.
+func TestNotifierPurgesGoneSubscription(t *testing.T) {
+	d, _ := openDB(t)
+	ua := newBrowserSub(t)
+
+	got := make(chan struct{}, 2)
+	dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		got <- struct{}{}
+		w.WriteHeader(http.StatusGone)
+	}))
+	defer dead.Close()
+	alive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		got <- struct{}{}
+		w.WriteHeader(http.StatusCreated)
+	}))
+	defer alive.Close()
+
+	for _, ep := range []string{dead.URL, alive.URL} {
+		if _, err := push.UpsertSubscription(d, push.Subscription{Endpoint: ep, Auth: ua.authB, P256dh: ua.pubB}); err != nil {
+			t.Fatalf("upsert: %v", err)
+		}
+	}
+
+	n := newNotifier(t, d)
+	n.Notify(testEvent())
+	for i := 0; i < 2; i++ {
+		select {
+		case <-got:
+		case <-time.After(15 * time.Second):
+			t.Fatalf("solo %d/2 envíos recibidos", i)
+		}
+	}
+	n.Close() // drena el worker: la purga ya ocurrió
+
+	subs, err := push.ListSubscriptions(d)
+	if err != nil {
+		t.Fatalf("list: %v", err)
+	}
+	if len(subs) != 1 || subs[0].Endpoint != alive.URL {
+		t.Fatalf("tras purga: %+v", subs)
+	}
+}