Forráskód Böngészése

feat: switch management phase 3 - port alerts, health score and front panel (#323)

* feat(alerts): add port monitor with flapping detection

Add PortMonitor to track per-port state transitions and emit smart
alerts. Flapping detection fires when a port transitions up/down more
than 5 times in a 10-minute window. Also fixes parseSpeedMbps to handle
space-separated speed strings like "1 Gbps".

Closes #303

* feat(alerts): add ghost port detection to port monitor

Alert when a port with stable historical traffic drops to zero bytes
for 3 consecutive polls. Requires at least 12 prior speed samples to
avoid false positives on newly observed or idle ports.

Closes #307

* feat(alerts): add degraded link detection to port monitor

Track negotiated speed per port over time. Alert when speed drops
sustainably below half the historical dominant speed for 3 consecutive
polls, indicating a damaged cable or failing NIC.

Closes #308

* feat: per-switch-port health score with breakdown signals

Compute per-port health scores (0-100) from link state, utilization,
error rates, and flapping frequency. Expose health in EthPort.Health
for managed switches. Includes comprehensive test coverage.

Closes #299

* feat: switch front panel widget with per-port status LEDs

Visual front panel representation for managed switches with colored
LED indicators per port (healthy/degraded/critical/free). Shows speed
labels, health score badges, and detailed tooltips on hover. Responsive
layout with mobile collapse. Includes health badge on PortPanel ports.

Closes #306

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 hónapja
szülő
commit
3bd2c16ea0

+ 32 - 0
app/public/locales/en/translation.json

@@ -521,6 +521,38 @@
       "seriesTx": "Transmit",
       "seriesTx": "Transmit",
       "seriesNoData": "No historical data"
       "seriesNoData": "No historical data"
     },
     },
+    "switchPanel": {
+      "title": "Switch front panel",
+      "summary_one": "{{used}} of {{total}} port in use",
+      "summary_other": "{{used}} of {{total}} ports in use",
+      "healthy_one": "{{count}} healthy",
+      "healthy_other": "{{count}} healthy",
+      "degraded_one": "{{count}} degraded",
+      "degraded_other": "{{count}} degraded",
+      "critical_one": "{{count}} critical",
+      "critical_other": "{{count}} critical",
+      "free": "Free",
+      "speed": "Speed",
+      "traffic": "Traffic",
+      "errors": "Errors",
+      "healthBreakdown": "Health",
+      "unknownDevice": "unknown device",
+      "ariaUsed": "Port {{label}}: {{device}}",
+      "ariaFree": "Port {{label}}: free",
+      "expand": "Expand panel",
+      "collapse": "Collapse panel",
+      "legendHealthy": "Healthy",
+      "legendDegraded": "Degraded",
+      "legendCritical": "Critical",
+      "legendFree": "Free",
+      "signals": {
+        "link_up": "link",
+        "link_down": "no link",
+        "utilization": "utilization",
+        "errors": "errors",
+        "flapping": "flapping"
+      }
+    },
     "radios": {
     "radios": {
       "channel": "Channel",
       "channel": "Channel",
       "clear": "Clear channel",
       "clear": "Clear channel",

+ 32 - 0
app/public/locales/es/translation.json

@@ -521,6 +521,38 @@
       "seriesTx": "Envío",
       "seriesTx": "Envío",
       "seriesNoData": "Sin datos históricos"
       "seriesNoData": "Sin datos históricos"
     },
     },
+    "switchPanel": {
+      "title": "Panel frontal del switch",
+      "summary_one": "{{used}} de {{total}} puerto en uso",
+      "summary_other": "{{used}} de {{total}} puertos en uso",
+      "healthy_one": "{{count}} sano",
+      "healthy_other": "{{count}} sanos",
+      "degraded_one": "{{count}} degradado",
+      "degraded_other": "{{count}} degradados",
+      "critical_one": "{{count}} crítico",
+      "critical_other": "{{count}} críticos",
+      "free": "Libre",
+      "speed": "Velocidad",
+      "traffic": "Tráfico",
+      "errors": "Errores",
+      "healthBreakdown": "Salud",
+      "unknownDevice": "dispositivo desconocido",
+      "ariaUsed": "Puerto {{label}}: {{device}}",
+      "ariaFree": "Puerto {{label}}: libre",
+      "expand": "Expandir panel",
+      "collapse": "Contraer panel",
+      "legendHealthy": "Sano",
+      "legendDegraded": "Degradado",
+      "legendCritical": "Crítico",
+      "legendFree": "Libre",
+      "signals": {
+        "link_up": "enlace",
+        "link_down": "sin enlace",
+        "utilization": "uso",
+        "errors": "errores",
+        "flapping": "flapping"
+      }
+    },
     "radios": {
     "radios": {
       "channel": "Canal",
       "channel": "Canal",
       "clear": "Canal despejado",
       "clear": "Canal despejado",

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

@@ -97,6 +97,18 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
             <div className={cn('font-mono text-[10px] font-semibold tracking-wide', isWan ? 'text-accent' : 'text-text-secondary')}>
             <div className={cn('font-mono text-[10px] font-semibold tracking-wide', isWan ? 'text-accent' : 'text-text-secondary')}>
               {port.label}
               {port.label}
             </div>
             </div>
+            {port.health && port.up && (
+              <div
+                className={cn(
+                  'mx-auto mt-0.5 inline-block rounded-full px-1.5 py-px font-mono text-[9px] font-bold',
+                  port.health.score >= 85 && 'bg-ok/15 text-ok',
+                  port.health.score >= 60 && port.health.score < 85 && 'bg-warn/15 text-warn',
+                  port.health.score < 60 && 'bg-error/15 text-error',
+                )}
+              >
+                {port.health.score}
+              </div>
+            )}
             {port.up ? (
             {port.up ? (
               <>
               <>
                 <div className="mt-0.5 w-full truncate text-caption font-medium text-text-primary">
                 <div className="mt-0.5 w-full truncate text-caption font-medium text-text-primary">

+ 246 - 0
app/src/components/routers/SwitchFrontPanel.tsx

@@ -0,0 +1,246 @@
+import { motion, useReducedMotion } from 'framer-motion'
+import { useTranslation } from 'react-i18next'
+import { useState } from 'react'
+import { Link } from 'react-router'
+import type { EthPort, PortHealth } from '@/components/routers/routerExtras'
+import { SectionHeader } from '@/components/SectionHeader'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { ChevronDown, ChevronUp } from 'lucide-react'
+
+function fmtPortBps(bps?: number): string {
+  if (bps === undefined || Number.isNaN(bps)) return '-'
+  if (bps >= 1e9) return `${(bps / 1e9).toFixed(1)} Gbps`
+  if (bps >= 1e6) return `${(bps / 1e6).toFixed(1)} Mbps`
+  if (bps >= 1e3) return `${Math.round(bps / 1e3)} kbps`
+  return `${Math.round(bps)} bps`
+}
+
+function healthColor(health?: PortHealth, up?: boolean): string {
+  if (!up) return 'bg-border-strong/40'
+  if (!health) return 'bg-ok'
+  if (health.score >= 85) return 'bg-ok'
+  if (health.score >= 60) return 'bg-warn'
+  return 'bg-error'
+}
+
+function healthGlow(health?: PortHealth, up?: boolean): string {
+  if (!up) return ''
+  if (!health) return 'shadow-[0_0_4px_theme(colors.ok/0.4)]'
+  if (health.score >= 85) return 'shadow-[0_0_4px_theme(colors.ok/0.4)]'
+  if (health.score >= 60) return 'shadow-[0_0_4px_theme(colors.warn/0.4)]'
+  return 'shadow-[0_0_6px_theme(colors.error/0.5)]'
+}
+
+function speedLabel(speed?: string): string {
+  if (!speed) return ''
+  const s = speed.toLowerCase()
+  if (s.includes('10 g') || s.includes('10g')) return '10G'
+  if (s.includes('2.5 g') || s.includes('2.5g')) return '2.5G'
+  if (s.includes('1 g') || s.includes('1g')) return '1G'
+  if (s.includes('100 m') || s.includes('100m')) return '100M'
+  if (s.includes('10 m') || s.includes('10m')) return '10M'
+  return ''
+}
+
+function PortLed({ port, index }: { port: EthPort; index: number }) {
+  const { t } = useTranslation()
+  const reduce = useReducedMotion()
+  const ledColor = healthColor(port.health, port.up)
+  const glow = healthGlow(port.health, port.up)
+  const spd = speedLabel(port.speed)
+
+  return (
+    <Tooltip>
+      <TooltipTrigger asChild>
+        <motion.div
+          initial={reduce ? false : { opacity: 0, scale: 0.8 }}
+          animate={{ opacity: 1, scale: 1 }}
+          transition={{ duration: 0.2, delay: index * 0.02 }}
+          className="group flex w-[44px] shrink-0 flex-col items-center gap-0.5"
+          role="img"
+          aria-label={
+            port.up
+              ? t('switchPanel.ariaUsed', { label: port.label, device: port.connectedTo ?? t('switchPanel.unknownDevice') })
+              : t('switchPanel.ariaFree', { label: port.label })
+          }
+        >
+          <div className={cn('h-2.5 w-2.5 rounded-full transition-all duration-300', ledColor, glow)} />
+          <div className="font-mono text-[9px] font-medium leading-none text-text-secondary">{port.label.replace(/\s+/g, '')}</div>
+          {spd && <div className="font-mono text-[8px] leading-none text-text-muted">{spd}</div>}
+        </motion.div>
+      </TooltipTrigger>
+      <TooltipContent
+        side="top"
+        align="center"
+        sideOffset={8}
+        className="w-60 border border-border-strong bg-elevated p-3 text-text-primary shadow-xl"
+      >
+        {port.up ? (
+          <div>
+            <div className="flex items-center justify-between gap-2">
+              <span className="font-display text-sm font-semibold">{port.label}</span>
+              {port.health && <HealthBadge health={port.health} />}
+            </div>
+            {port.connectedTo && (
+              <div className="mt-1.5 text-caption font-medium text-text-primary">
+                {port.connectedTo === port.label && port.deviceMac ? (
+                  <span className="font-mono text-[10px] text-text-muted">{port.deviceMac}</span>
+                ) : port.deviceMac ? (
+                  <Link
+                    to={`/devices?q=${encodeURIComponent(port.deviceMac)}`}
+                    className="transition-colors hover:text-accent hover:underline"
+                    onClick={(e) => e.stopPropagation()}
+                  >
+                    {port.connectedTo}
+                  </Link>
+                ) : (
+                  port.connectedTo
+                )}
+              </div>
+            )}
+            <div className="mt-2 grid grid-cols-2 gap-1.5">
+              {port.speed && (
+                <div className="rounded-lg bg-canvas/60 px-2 py-1">
+                  <div className="text-caption uppercase tracking-wider text-text-muted">{t('switchPanel.speed')}</div>
+                  <div className="font-mono text-mono-sm text-text-primary">{port.speed}</div>
+                </div>
+              )}
+              {port.deviceMac && (
+                <div className="rounded-lg bg-canvas/60 px-2 py-1">
+                  <div className="text-caption uppercase tracking-wider text-text-muted">MAC</div>
+                  <div className="truncate font-mono text-mono-sm text-text-primary">{port.deviceMac}</div>
+                </div>
+              )}
+              {(port.rxBps !== undefined || port.txBps !== undefined) && (
+                <div className="col-span-2 rounded-lg bg-canvas/60 px-2 py-1">
+                  <div className="text-caption uppercase tracking-wider text-text-muted">{t('switchPanel.traffic')}</div>
+                  <div className="font-mono text-mono-sm text-text-primary">
+                    ↓ {fmtPortBps(port.rxBps)} / ↑ {fmtPortBps(port.txBps)}
+                  </div>
+                </div>
+              )}
+              {(port.rxErrors ?? 0) + (port.txErrors ?? 0) > 0 && (
+                <div className="col-span-2 rounded-lg bg-canvas/60 px-2 py-1">
+                  <div className="text-caption uppercase tracking-wider text-text-muted">{t('switchPanel.errors')}</div>
+                  <div className="font-mono text-mono-sm text-warn">
+                    RX {port.rxErrors ?? 0} / TX {port.txErrors ?? 0}
+                  </div>
+                </div>
+              )}
+            </div>
+            {port.health && port.health.breakdown.length > 0 && (
+              <div className="mt-2 border-t border-border/40 pt-2">
+                <div className="text-caption uppercase tracking-wider text-text-muted">{t('switchPanel.healthBreakdown')}</div>
+                <div className="mt-1 flex flex-wrap gap-1">
+                  {port.health.breakdown.map((item) => (
+                    <span
+                      key={item.signal}
+                      className={cn(
+                        'rounded px-1.5 py-0.5 text-[10px] font-medium',
+                        item.status === 'ok' && 'bg-ok/15 text-ok',
+                        item.status === 'warn' && 'bg-warn/15 text-warn',
+                        item.status === 'crit' && 'bg-error/15 text-error',
+                      )}
+                    >
+                      {t(`switchPanel.signals.${item.signal}`, item.signal)}
+                    </span>
+                  ))}
+                </div>
+              </div>
+            )}
+          </div>
+        ) : (
+          <div className="flex items-center justify-between">
+            <span className="font-display text-sm font-semibold">{port.label}</span>
+            <span className="text-caption text-text-muted">{t('switchPanel.free')}</span>
+          </div>
+        )}
+      </TooltipContent>
+    </Tooltip>
+  )
+}
+
+function HealthBadge({ health }: { health: PortHealth }) {
+  const color =
+    health.score >= 85
+      ? 'bg-ok/15 text-ok'
+      : health.score >= 60
+        ? 'bg-warn/15 text-warn'
+        : 'bg-error/15 text-error'
+  return (
+    <span className={cn('rounded-full px-2 py-0.5 font-mono text-[10px] font-bold', color)}>
+      {health.score}
+    </span>
+  )
+}
+
+export function SwitchFrontPanel({
+  ports,
+  className,
+}: {
+  ports: EthPort[]
+  className?: string
+}) {
+  const { t } = useTranslation()
+  const [collapsed, setCollapsed] = useState(false)
+  const lanPorts = ports.filter((p) => p.id !== 'wan')
+  const portCount = lanPorts.length
+  const used = lanPorts.filter((p) => p.up).length
+  const healthy = lanPorts.filter((p) => p.up && p.health && p.health.score >= 85).length
+  const degraded = lanPorts.filter((p) => p.up && p.health && p.health.score < 85 && p.health.score >= 60).length
+  const critical = lanPorts.filter((p) => p.up && p.health && p.health.score < 60).length
+
+  if (portCount < 8) return null
+
+  return (
+    <section className={cn('rounded-2xl border border-border bg-surface p-5 md:p-6', className)}>
+      <div className="flex items-center justify-between">
+        <div>
+          <SectionHeader title={t('switchPanel.title')} />
+          <p className="mt-1 text-caption text-text-muted">
+            {t('switchPanel.summary', { used, total: portCount })}
+            {healthy > 0 && ` · ${t('switchPanel.healthy', { count: healthy })}`}
+            {degraded > 0 && ` · ${t('switchPanel.degraded', { count: degraded })}`}
+            {critical > 0 && ` · ${t('switchPanel.critical', { count: critical })}`}
+          </p>
+        </div>
+        <button
+          type="button"
+          onClick={() => setCollapsed((v) => !v)}
+          className="rounded-lg p-2 text-text-muted transition-colors hover:bg-elevated hover:text-text-primary md:hidden"
+          aria-label={collapsed ? t('switchPanel.expand') : t('switchPanel.collapse')}
+        >
+          {collapsed ? <ChevronDown className="h-4 w-4" /> : <ChevronUp className="h-4 w-4" />}
+        </button>
+      </div>
+
+      {!collapsed && (
+        <div className="mt-4 rounded-xl border border-border/70 bg-elevated/40 px-3 py-3">
+          <div className="flex flex-wrap items-end gap-x-1 gap-y-2">
+            {lanPorts.map((p, i) => (
+              <PortLed key={p.id} port={p} index={i} />
+            ))}
+          </div>
+        </div>
+      )}
+
+      {!collapsed && (
+        <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-caption text-text-muted">
+          <span className="inline-flex items-center gap-1.5">
+            <span className="h-2 w-2 rounded-full bg-ok" /> {t('switchPanel.legendHealthy')}
+          </span>
+          <span className="inline-flex items-center gap-1.5">
+            <span className="h-2 w-2 rounded-full bg-warn" /> {t('switchPanel.legendDegraded')}
+          </span>
+          <span className="inline-flex items-center gap-1.5">
+            <span className="h-2 w-2 rounded-full bg-error" /> {t('switchPanel.legendCritical')}
+          </span>
+          <span className="inline-flex items-center gap-1.5">
+            <span className="h-2 w-2 rounded-full bg-border-strong/40" /> {t('switchPanel.legendFree')}
+          </span>
+        </div>
+      )}
+    </section>
+  )
+}

+ 14 - 0
app/src/components/routers/routerExtras.ts

@@ -47,6 +47,19 @@ export interface SfpInfo {
   present: boolean
   present: boolean
 }
 }
 
 
+/** Per-port health breakdown item (issue #299). */
+export interface PortHealthItem {
+  signal: string
+  weight: number
+  status: 'ok' | 'warn' | 'crit'
+}
+
+/** Per-port health score (issue #299). */
+export interface PortHealth {
+  score: number
+  breakdown: PortHealthItem[]
+}
+
 /** Boca física RJ45 del chasis (panel visual de puertos). */
 /** Boca física RJ45 del chasis (panel visual de puertos). */
 export interface EthPort {
 export interface EthPort {
   id: string
   id: string
@@ -64,6 +77,7 @@ export interface EthPort {
   connectedTo?: string // "NAS Synology" | "Salón · AX3000T"
   connectedTo?: string // "NAS Synology" | "Salón · AX3000T"
   deviceMac?: string // MAC del dispositivo conectado (para enlazar a /devices)
   deviceMac?: string // MAC del dispositivo conectado (para enlazar a /devices)
   detail?: string // "192.168.8.10 · full duplex"
   detail?: string // "192.168.8.10 · full duplex"
+  health?: PortHealth // health score del puerto (#299)
 }
 }
 
 
 export interface BackhaulInfo {
 export interface BackhaulInfo {

+ 10 - 1
app/src/pages/RouterDetail.tsx

@@ -9,6 +9,7 @@ import type { RouterDetailData } from '@/data/DataProvider'
 import { AdGuardPanel } from '@/components/routers/AdGuardPanel'
 import { AdGuardPanel } from '@/components/routers/AdGuardPanel'
 import { BackhaulPanel } from '@/components/routers/BackhaulPanel'
 import { BackhaulPanel } from '@/components/routers/BackhaulPanel'
 import { PortPanel } from '@/components/routers/PortPanel'
 import { PortPanel } from '@/components/routers/PortPanel'
+import { SwitchFrontPanel } from '@/components/routers/SwitchFrontPanel'
 import { RadiosPorts } from '@/components/routers/RadiosPorts'
 import { RadiosPorts } from '@/components/routers/RadiosPorts'
 import { RouterClients } from '@/components/routers/RouterClients'
 import { RouterClients } from '@/components/routers/RouterClients'
 import { RouterDetailHeader } from '@/components/routers/RouterDetailHeader'
 import { RouterDetailHeader } from '@/components/routers/RouterDetailHeader'
@@ -136,10 +137,18 @@ export default function RouterDetail() {
         <>
         <>
           <AdGuardPanel />
           <AdGuardPanel />
           <WireGuardPanel />
           <WireGuardPanel />
+          {router.type === 'managed-switch' && detail?.extras?.ethPorts && (
+            <SwitchFrontPanel ports={detail.extras.ethPorts} className="lg:col-span-12" />
+          )}
           <PortPanel router={router} extras={detail?.extras} className="lg:col-span-12" />
           <PortPanel router={router} extras={detail?.extras} className="lg:col-span-12" />
         </>
         </>
       ) : (
       ) : (
-        <RadiosPorts router={router} extras={detail?.extras} />
+        <>
+          {router.type === 'managed-switch' && detail?.extras?.ethPorts && (
+            <SwitchFrontPanel ports={detail.extras.ethPorts} className="lg:col-span-12" />
+          )}
+          <RadiosPorts router={router} extras={detail?.extras} />
+        </>
       )}
       )}
 
 
       {/* VLANs del bridge (issue #315, read-only) */}
       {/* VLANs del bridge (issue #315, read-only) */}

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

@@ -585,6 +585,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	l.mu.Unlock()
 	l.mu.Unlock()
 
 
 	l.recordPortSamples(cfg.ID, out.ports)
 	l.recordPortSamples(cfg.ID, out.ports)
+	l.portMon.Observe(cfg.ID, out.ports, l.engine)
 
 
 	if out.leases == nil {
 	if out.leases == nil {
 		out.leases = []DhcpLease{}
 		out.leases = []DhcpLease{}

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

@@ -245,6 +245,10 @@ type Live struct {
 	// vivo" (#281). Se limpia cuando el acceso SSH se recupera.
 	// vivo" (#281). Se limpia cuando el acceso SSH se recupera.
 	sshAuthFailAlerted map[string]bool
 	sshAuthFailAlerted map[string]bool
 
 
+	// portMon (issue #303/#307/#308): monitor de estado de puertos para
+	// detección de flapping, ghost port y link degradado.
+	portMon *PortMonitor
+
 	// now: reloj inyectable para tests deterministas (nil → time.Now).
 	// now: reloj inyectable para tests deterministas (nil → time.Now).
 	// Mismo patrón que AgentRegistry.SetClock.
 	// Mismo patrón que AgentRegistry.SetClock.
 	now func() time.Time
 	now func() time.Time
@@ -298,6 +302,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		agentDownConfirm:     3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
 		agentDownConfirm:     3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
 		routerMacs:           map[string]string{},
 		routerMacs:           map[string]string{},
 		sshAuthFailAlerted:   map[string]bool{},
 		sshAuthFailAlerted:   map[string]bool{},
+		portMon:              NewPortMonitor(),
 	}
 	}
 	l.loadRouterMacs()
 	l.loadRouterMacs()
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
@@ -880,6 +885,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		tempV = *temp
 		tempV = *temp
 	}
 	}
 	l.recordPortSamples(cfg.ID, portsGood)
 	l.recordPortSamples(cfg.ID, portsGood)
+	l.portMon.Observe(cfg.ID, portsGood, l.engine)
 	return &routerPolled{
 	return &routerPolled{
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
 		cpu: cpuV, ram: ramPct, temp: tempV,
 		cpu: cpuV, ram: ramPct, temp: tempV,
@@ -1450,12 +1456,14 @@ func parseSpeedMbps(s string) int {
 	s = strings.ReplaceAll(s, "Bps", "")
 	s = strings.ReplaceAll(s, "Bps", "")
 	s = strings.TrimSpace(s)
 	s = strings.TrimSpace(s)
 	if strings.HasSuffix(s, "G") {
 	if strings.HasSuffix(s, "G") {
-		if v, err := strconv.ParseFloat(strings.TrimSuffix(s, "G"), 64); err == nil {
+		numStr := strings.TrimSpace(strings.TrimSuffix(s, "G"))
+		if v, err := strconv.ParseFloat(numStr, 64); err == nil {
 			return int(v * 1000)
 			return int(v * 1000)
 		}
 		}
 	}
 	}
 	if strings.HasSuffix(s, "M") {
 	if strings.HasSuffix(s, "M") {
-		if v, err := strconv.ParseFloat(strings.TrimSuffix(s, "M"), 64); err == nil {
+		numStr := strings.TrimSpace(strings.TrimSuffix(s, "M"))
+		if v, err := strconv.ParseFloat(numStr, 64); err == nil {
 			return int(v)
 			return int(v)
 		}
 		}
 	}
 	}
@@ -2374,6 +2382,8 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		}
 		}
 		enriched = append(enriched, port)
 		enriched = append(enriched, port)
 	}
 	}
+	// Per-port health score (issue #299): compute from recent series + flapping.
+	l.enrichPortHealth(id, enriched)
 	radios := []Radio{}
 	radios := []Radio{}
 	if p != nil && p.radios != nil {
 	if p != nil && p.radios != nil {
 		radios = p.radios
 		radios = p.radios

+ 205 - 0
server-go/internal/adapters/porthhealth.go

@@ -0,0 +1,205 @@
+// Package adapters - per-port health score (issue #299).
+//
+// ComputePortHealth aggregates signals from a single port into a 0-100 score
+// with a breakdown of weighted signals. Signals: link_up (30%), utilization
+// (25%), errors (25%), flapping (20%).
+package adapters
+
+import (
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/portseries"
+)
+
+// PortHealthItem is a single signal in the port health breakdown.
+type PortHealthItem struct {
+	Signal string `json:"signal"`
+	Weight int    `json:"weight"`
+	Status string `json:"status"` // "ok"|"warn"|"crit"
+}
+
+// PortHealth is the per-port health score (0-100) with breakdown.
+type PortHealth struct {
+	Score     int              `json:"score"`
+	Breakdown []PortHealthItem `json:"breakdown"`
+}
+
+// computePortHealthFromSignals builds a PortHealth from pre-computed signal values.
+// linkUp: whether the port is operationally up.
+// utilPct: utilization percentage (0-100+).
+// errorRate: errors per second (delta errors / delta time).
+// flapCount: number of state transitions in the observation window.
+func computePortHealthFromSignals(linkUp bool, utilPct float64, errorRate float64, flapCount int) PortHealth {
+	if !linkUp {
+		return PortHealth{
+			Score: 0,
+			Breakdown: []PortHealthItem{
+				{Signal: "link_down", Weight: 100, Status: "crit"},
+			},
+		}
+	}
+
+	score := 100
+	breakdown := []PortHealthItem{}
+
+	linkItem := PortHealthItem{Signal: "link_up", Weight: 30, Status: "ok"}
+	breakdown = append(breakdown, linkItem)
+
+	utilStatus := "ok"
+	utilPenalty := 0
+	if utilPct > 95 {
+		utilStatus = "crit"
+		utilPenalty = 25
+	} else if utilPct > 90 {
+		utilStatus = "warn"
+		utilPenalty = 15
+	} else if utilPct > 80 {
+		utilStatus = "warn"
+		utilPenalty = 8
+	}
+	score -= utilPenalty
+	breakdown = append(breakdown, PortHealthItem{Signal: "utilization", Weight: 25, Status: utilStatus})
+
+	errStatus := "ok"
+	errPenalty := 0
+	if errorRate > 10 {
+		errStatus = "crit"
+		errPenalty = 25
+	} else if errorRate > 1 {
+		errStatus = "warn"
+		errPenalty = 15
+	} else if errorRate > 0.1 {
+		errStatus = "warn"
+		errPenalty = 5
+	}
+	score -= errPenalty
+	breakdown = append(breakdown, PortHealthItem{Signal: "errors", Weight: 25, Status: errStatus})
+
+	flapStatus := "ok"
+	flapPenalty := 0
+	if flapCount > 10 {
+		flapStatus = "crit"
+		flapPenalty = 20
+	} else if flapCount > 5 {
+		flapStatus = "warn"
+		flapPenalty = 12
+	} else if flapCount > 2 {
+		flapStatus = "warn"
+		flapPenalty = 5
+	}
+	score -= flapPenalty
+	breakdown = append(breakdown, PortHealthItem{Signal: "flapping", Weight: 20, Status: flapStatus})
+
+	if score < 0 {
+		score = 0
+	}
+	return PortHealth{Score: score, Breakdown: breakdown}
+}
+
+// ComputePortHealth computes the health score for a single port from its
+// current state, historical samples, and flapping count.
+func ComputePortHealth(port EthPort, series []portseries.PortPoint, flappingCount int) PortHealth {
+	if !port.Up {
+		return computePortHealthFromSignals(false, 0, 0, 0)
+	}
+
+	utilPct := computeUtilization(port, series)
+	errorRate := computeErrorRate(series)
+
+	return computePortHealthFromSignals(true, utilPct, errorRate, flappingCount)
+}
+
+// computeUtilization estimates utilization % from the port's current speed
+// and recent traffic rates. Falls back to 0 if speed cannot be parsed.
+func computeUtilization(port EthPort, series []portseries.PortPoint) float64 {
+	speedMbps := parseSpeedMbps(port.Speed)
+	if speedMbps <= 0 {
+		if len(series) > 0 {
+			speedMbps = series[len(series)-1].SpeedMbps
+		}
+	}
+	if speedMbps <= 0 {
+		return 0
+	}
+
+	var rxBps, txBps float64
+	if port.RxBps > 0 || port.TxBps > 0 {
+		rxBps = port.RxBps
+		txBps = port.TxBps
+	} else if len(series) > 0 {
+		last := series[len(series)-1]
+		rxBps = last.RxBps
+		txBps = last.TxBps
+	}
+
+	capacityBps := float64(speedMbps) * 1e6
+	if capacityBps <= 0 {
+		return 0
+	}
+	maxBps := rxBps
+	if txBps > maxBps {
+		maxBps = txBps
+	}
+	return (maxBps / capacityBps) * 100
+}
+
+// computeErrorRate computes errors/second from the series delta. Returns 0
+// if there are fewer than 2 points or the time span is zero.
+func computeErrorRate(series []portseries.PortPoint) float64 {
+	if len(series) < 2 {
+		return 0
+	}
+	first := series[0]
+	last := series[len(series)-1]
+	span := last.TS.Sub(first.TS).Seconds()
+	if span <= 0 {
+		return 0
+	}
+	errDelta := float64(last.RxErrors+last.TxErrors) - float64(first.RxErrors+first.TxErrors)
+	if errDelta < 0 {
+		errDelta = 0
+	}
+	return errDelta / span
+}
+
+// parseSpeedMbps is defined in live.go
+
+// enrichPortHealth computes and attaches health scores to each port in the
+// slice. Requires access to the port series store (db.PortSeries). Flapping
+// is estimated from speed-to-zero transitions in the last hour.
+func (l *Live) enrichPortHealth(routerID string, ports []EthPort) {
+	if l.db == nil || l.db.PortSeries == nil || len(ports) == 0 {
+		return
+	}
+	now := time.Now()
+	from := now.Add(-1 * time.Hour)
+	for i := range ports {
+		series, err := l.db.PortSeries.GetSeries(routerID, ports[i].ID, from, now, "raw")
+		if err != nil || len(series) == 0 {
+			h := ComputePortHealth(ports[i], nil, 0)
+			ports[i].Health = &h
+			continue
+		}
+		flapCount := estimateFlapping(series)
+		h := ComputePortHealth(ports[i], series, flapCount)
+		ports[i].Health = &h
+	}
+}
+
+// estimateFlapping counts link-down events (speed dropping to 0) in the series
+// as a proxy for flapping. A transition from >0 to 0 counts as one flap.
+func estimateFlapping(series []portseries.PortPoint) int {
+	if len(series) < 2 {
+		return 0
+	}
+	count := 0
+	prevUp := series[0].SpeedMbps > 0
+	for _, p := range series[1:] {
+		up := p.SpeedMbps > 0
+		if prevUp && !up {
+			count++
+		}
+		prevUp = up
+	}
+	return count
+}

+ 156 - 0
server-go/internal/adapters/porthhealth_test.go

@@ -0,0 +1,156 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/portseries"
+)
+
+func TestComputePortHealth_LinkDown(t *testing.T) {
+	port := EthPort{ID: "lan1", Label: "LAN 1", Up: false}
+	health := ComputePortHealth(port, nil, 0)
+	if health.Score != 0 {
+		t.Errorf("expected score 0 for down port, got %d", health.Score)
+	}
+	if len(health.Breakdown) != 1 {
+		t.Fatalf("expected 1 breakdown item, got %d", len(health.Breakdown))
+	}
+	if health.Breakdown[0].Signal != "link_down" {
+		t.Errorf("expected signal link_down, got %s", health.Breakdown[0].Signal)
+	}
+}
+
+func TestComputePortHealth_Perfect(t *testing.T) {
+	port := EthPort{
+		ID:     "lan1",
+		Label:  "LAN 1",
+		Up:     true,
+		Speed:  "1 Gbps",
+		RxBps:  1000,
+		TxBps:  1000,
+		RxErrs: 0,
+		TxErrs: 0,
+	}
+	health := ComputePortHealth(port, nil, 0)
+	if health.Score != 100 {
+		t.Errorf("expected score 100 for perfect port, got %d", health.Score)
+	}
+	if len(health.Breakdown) != 4 {
+		t.Fatalf("expected 4 breakdown items, got %d", len(health.Breakdown))
+	}
+}
+
+func TestComputePortHealth_HighUtilization(t *testing.T) {
+	port := EthPort{
+		ID:    "lan1",
+		Label: "LAN 1",
+		Up:    true,
+		Speed: "1 Gbps",
+		RxBps: 950e6,
+		TxBps: 100e6,
+	}
+	health := ComputePortHealth(port, nil, 0)
+	if health.Score >= 90 {
+		t.Errorf("expected score <90 for 95%% util, got %d", health.Score)
+	}
+	found := false
+	for _, item := range health.Breakdown {
+		if item.Signal == "utilization" && item.Status != "ok" {
+			found = true
+		}
+	}
+	if !found {
+		t.Error("expected utilization signal to be warn/crit")
+	}
+}
+
+func TestComputePortHealth_Errors(t *testing.T) {
+	now := time.Now()
+	series := []portseries.PortPoint{
+		{TS: now.Add(-10 * time.Second), RxErrors: 0, TxErrors: 0},
+		{TS: now, RxErrors: 100, TxErrors: 100},
+	}
+	port := EthPort{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps"}
+	health := ComputePortHealth(port, series, 0)
+	if health.Score >= 90 {
+		t.Errorf("expected score <90 for high error rate, got %d", health.Score)
+	}
+	found := false
+	for _, item := range health.Breakdown {
+		if item.Signal == "errors" && item.Status == "crit" {
+			found = true
+		}
+	}
+	if !found {
+		t.Error("expected errors signal to be crit")
+	}
+}
+
+func TestComputePortHealth_Flapping(t *testing.T) {
+	port := EthPort{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps"}
+	health := ComputePortHealth(port, nil, 15)
+	if health.Score >= 85 {
+		t.Errorf("expected score <85 for 15 flaps, got %d", health.Score)
+	}
+	found := false
+	for _, item := range health.Breakdown {
+		if item.Signal == "flapping" && item.Status == "crit" {
+			found = true
+		}
+	}
+	if !found {
+		t.Error("expected flapping signal to be crit")
+	}
+}
+
+func TestParseSpeedMbps(t *testing.T) {
+	tests := []struct {
+		input string
+		want  int
+	}{
+		{"1 Gbps", 1000},
+		{"100 Mbps", 100},
+		{"2.5 Gbps", 2500},
+		{"10 Mbps", 10},
+		{"", 0},
+		{"invalid", 0},
+	}
+	for _, tc := range tests {
+		got := parseSpeedMbps(tc.input)
+		if got != tc.want {
+			t.Errorf("parseSpeedMbps(%q) = %d, want %d", tc.input, got, tc.want)
+		}
+	}
+}
+
+func TestComputeUtilization(t *testing.T) {
+	port := EthPort{Speed: "1 Gbps", RxBps: 500e6, TxBps: 100e6}
+	util := computeUtilization(port, nil)
+	if util < 49 || util > 51 {
+		t.Errorf("expected ~50%% util, got %.1f%%", util)
+	}
+
+	port2 := EthPort{Speed: "1 Gbps", RxBps: 0, TxBps: 0}
+	util2 := computeUtilization(port2, nil)
+	if util2 != 0 {
+		t.Errorf("expected 0%% util, got %.1f%%", util2)
+	}
+}
+
+func TestComputeErrorRate(t *testing.T) {
+	now := time.Now()
+	series := []portseries.PortPoint{
+		{TS: now.Add(-10 * time.Second), RxErrors: 0, TxErrors: 0},
+		{TS: now, RxErrors: 30, TxErrors: 20},
+	}
+	rate := computeErrorRate(series)
+	if rate < 4.9 || rate > 5.1 {
+		t.Errorf("expected ~5 errors/sec, got %.2f", rate)
+	}
+
+	rate2 := computeErrorRate(nil)
+	if rate2 != 0 {
+		t.Errorf("expected 0 for empty series, got %.2f", rate2)
+	}
+}

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

@@ -0,0 +1,193 @@
+package adapters
+
+import (
+	"fmt"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+const (
+	flapWindow         = 10 * time.Minute
+	flapThreshold      = 5
+	ghostConsecutive   = 3
+	ghostMinHistory   = 12
+	degradedConsec     = 3
+	degradedMinHistory = 12
+)
+
+type portKey struct {
+	routerID string
+	portID   string
+}
+
+type portState struct {
+	up           bool
+	transitions  []time.Time
+	speedMbps    int
+	speedHistory []int
+	trafficTotal uint64
+	zeroStreak   int
+	hadTraffic   bool
+}
+
+type PortMonitor struct {
+	mu     sync.Mutex
+	states map[portKey]*portState
+	now    func() time.Time
+}
+
+func NewPortMonitor() *PortMonitor {
+	return &PortMonitor{
+		states: map[portKey]*portState{},
+		now:    time.Now,
+	}
+}
+
+func (pm *PortMonitor) SetClock(f func() time.Time) {
+	pm.mu.Lock()
+	defer pm.mu.Unlock()
+	pm.now = f
+}
+
+func (pm *PortMonitor) Observe(routerID string, ports []EthPort, engine *alerts.Engine) {
+	pm.mu.Lock()
+	defer pm.mu.Unlock()
+	now := pm.now()
+	for _, p := range ports {
+		if p.ID == "" {
+			continue
+		}
+		key := portKey{routerID, p.ID}
+		st, ok := pm.states[key]
+		if !ok {
+			st = &portState{up: p.Up}
+			pm.states[key] = st
+		}
+		pm.updateSpeedHistory(st, p)
+		pm.checkFlapping(key, st, p, now, engine)
+		pm.checkGhost(key, st, p, engine)
+		pm.checkDegraded(key, st, p, engine)
+	}
+}
+
+func (pm *PortMonitor) updateSpeedHistory(st *portState, p EthPort) {
+	spd := parseSpeedMbps(p.Speed)
+	if !p.Up || spd == 0 {
+		st.speedHistory = nil
+		st.speedMbps = 0
+		return
+	}
+	st.speedHistory = append(st.speedHistory, spd)
+	if len(st.speedHistory) > 200 {
+		st.speedHistory = st.speedHistory[len(st.speedHistory)-200:]
+	}
+	st.speedMbps = spd
+}
+
+func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now time.Time, engine *alerts.Engine) {
+	if p.Up != st.up {
+		st.transitions = append(st.transitions, now)
+		st.up = p.Up
+	}
+	cutoff := now.Add(-flapWindow)
+	kept := st.transitions[:0]
+	for _, t := range st.transitions {
+		if !t.Before(cutoff) {
+			kept = append(kept, t)
+		}
+	}
+	st.transitions = kept
+	if len(st.transitions) >= flapThreshold {
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-flap-%s-%s", key.routerID, key.portID),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "warn",
+			Title:       fmt.Sprintf("Port flapping: %s on %s", p.Label, key.routerID),
+			Description: fmt.Sprintf("%d transitions in %s", len(st.transitions), flapWindow),
+			Hint:        alerts.HintFor(alerts.HintPortFlapping),
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
+	}
+}
+
+func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, engine *alerts.Engine) {
+	total := p.RxBytes + p.TxBytes
+	if !p.Up {
+		st.zeroStreak = 0
+		st.hadTraffic = false
+		st.trafficTotal = 0
+		return
+	}
+	if total > st.trafficTotal {
+		st.hadTraffic = true
+		st.zeroStreak = 0
+	} else if st.hadTraffic {
+		st.zeroStreak++
+	}
+	st.trafficTotal = total
+	if len(st.speedHistory) < ghostMinHistory {
+		return
+	}
+	if st.zeroStreak >= ghostConsecutive {
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-ghost-%s-%s", key.routerID, key.portID),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "warn",
+			Title:       fmt.Sprintf("Ghost port: %s went silent", p.Label),
+			Description: fmt.Sprintf("Port had traffic but zero bytes for %d consecutive polls", st.zeroStreak),
+			Hint:        alerts.HintFor(alerts.HintGhostPort),
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
+	}
+}
+
+func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, engine *alerts.Engine) {
+	if len(st.speedHistory) < degradedMinHistory {
+		return
+	}
+	prev := dominantSpeed(st.speedHistory[:len(st.speedHistory)-degradedConsec])
+	if prev == 0 {
+		return
+	}
+	recent := st.speedHistory[len(st.speedHistory)-degradedConsec:]
+	allBelow := true
+	for _, s := range recent {
+		if s >= prev/2 {
+			allBelow = false
+			break
+		}
+	}
+	if allBelow && st.speedMbps < prev {
+		engine.Emit(alerts.AlertEvent{
+			ID:          fmt.Sprintf("alert-degraded-%s-%s", key.routerID, key.portID),
+			Category:    alerts.CatSystem,
+			Urgent:      false,
+			Severity:    "warn",
+			Title:       fmt.Sprintf("Degraded link: %s at %dMbps (was %dMbps)", p.Label, st.speedMbps, prev),
+			Description: fmt.Sprintf("Port negotiated speed dropped from %d to %d Mbps for %d consecutive polls", prev, st.speedMbps, degradedConsec),
+			Hint:        alerts.HintFor(alerts.HintDegradedLink),
+			Time:        "ahora mismo",
+			RouterID:    key.routerID,
+		})
+	}
+}
+
+func dominantSpeed(history []int) int {
+	counts := map[int]int{}
+	for _, s := range history {
+		counts[s]++
+	}
+	best, bestN := 0, 0
+	for spd, n := range counts {
+		if n > bestN || (n == bestN && spd > best) {
+			best, bestN = spd, n
+		}
+	}
+	return best
+}

+ 233 - 0
server-go/internal/adapters/portmonitor_test.go

@@ -0,0 +1,233 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func TestPortMonitorFlapping(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	for i := 0; i < flapThreshold; i++ {
+		port.Up = !port.Up
+		now = now.Add(30 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	found := false
+	for _, ev := range engine.List() {
+		if ev.Title == "Port flapping: LAN1 on r1" {
+			found = true
+			if ev.Category != alerts.CatSystem {
+				t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
+			}
+			if ev.Hint == "" {
+				t.Error("hint should not be empty")
+			}
+			break
+		}
+	}
+	if !found {
+		t.Error("flapping alert not emitted")
+	}
+}
+
+func TestPortMonitorFlappingNoAlertBelowThreshold(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	for i := 0; i < flapThreshold-1; i++ {
+		port.Up = !port.Up
+		now = now.Add(30 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	for _, ev := range engine.List() {
+		if ev.Title == "Port flapping: LAN1 on r1" {
+			t.Error("flapping alert should not fire below threshold")
+		}
+	}
+}
+
+func TestPortMonitorFlappingWindowExpiry(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	for i := 0; i < flapThreshold-1; i++ {
+		port.Up = !port.Up
+		now = now.Add(30 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	now = now.Add(flapWindow + time.Minute)
+	pm.SetClock(func() time.Time { return now })
+	port.Up = !port.Up
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	for _, ev := range engine.List() {
+		if ev.Title == "Port flapping: LAN1 on r1" {
+			t.Error("flapping alert should not fire after window expires")
+		}
+	}
+}
+
+func TestPortMonitorGhostPort(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 0, TxBytes: 0, Speed: "1 Gbps"}
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	for i := 0; i < ghostMinHistory; i++ {
+		port.RxBytes += 1000
+		port.TxBytes += 500
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	for i := 0; i < ghostConsecutive; i++ {
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	found := false
+	for _, ev := range engine.List() {
+		if ev.Title == "Ghost port: LAN1 went silent" {
+			found = true
+			if ev.Category != alerts.CatSystem {
+				t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
+			}
+			break
+		}
+	}
+	if !found {
+		t.Error("ghost port alert not emitted")
+	}
+}
+
+func TestPortMonitorGhostPortNoAlertWithoutHistory(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, RxBytes: 100, TxBytes: 100, Speed: "1 Gbps"}
+
+	for i := 0; i < ghostConsecutive+2; i++ {
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	for _, ev := range engine.List() {
+		if ev.Title == "Ghost port: LAN1 went silent" {
+			t.Error("ghost port should not fire without sufficient history")
+		}
+	}
+}
+
+func TestPortMonitorDegradedLink(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps", RxBytes: 100, TxBytes: 100}
+
+	for i := 0; i < degradedMinHistory; i++ {
+		port.RxBytes += 1000
+		port.TxBytes += 500
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	port.Speed = "100 Mbps"
+	for i := 0; i < degradedConsec; i++ {
+		port.RxBytes += 500
+		port.TxBytes += 200
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	found := false
+	for _, ev := range engine.List() {
+		if ev.Title == "Degraded link: LAN1 at 100Mbps (was 1000Mbps)" {
+			found = true
+			if ev.Category != alerts.CatSystem {
+				t.Errorf("category = %q, want %q", ev.Category, alerts.CatSystem)
+			}
+			break
+		}
+	}
+	if !found {
+		t.Errorf("degraded link alert not emitted; alerts: %v", engine.List())
+	}
+}
+
+func TestPortMonitorDegradedLinkNoAlertWhenStable(t *testing.T) {
+	pm := NewPortMonitor()
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 8, 28, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "eth0", Label: "LAN1", Up: true, Speed: "1 Gbps", RxBytes: 100, TxBytes: 100}
+
+	for i := 0; i < degradedMinHistory+degradedConsec; i++ {
+		port.RxBytes += 1000
+		port.TxBytes += 500
+		now = now.Add(45 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	for _, ev := range engine.List() {
+		if ev.Title == "Degraded link: LAN1 at 1000Mbps (was 1000Mbps)" {
+			t.Error("degraded link should not fire when speed is stable")
+		}
+	}
+}
+
+func TestDominantSpeed(t *testing.T) {
+	cases := []struct {
+		in   []int
+		want int
+	}{
+		{[]int{1000, 1000, 1000, 100}, 1000},
+		{[]int{100, 100, 100, 1000}, 100},
+		{[]int{}, 0},
+		{[]int{1000}, 1000},
+	}
+	for _, tc := range cases {
+		got := dominantSpeed(tc.in)
+		if got != tc.want {
+			t.Errorf("dominantSpeed(%v) = %d, want %d", tc.in, got, tc.want)
+		}
+	}
+}

+ 2 - 0
server-go/internal/adapters/snmp_live.go

@@ -85,6 +85,8 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		fdbMap[e.MAC] = name
 		fdbMap[e.MAC] = name
 	}
 	}
 
 
+	l.portMon.Observe(cfg.ID, ethPorts, l.engine)
+
 	var uptimeSec float64
 	var uptimeSec float64
 	if sysInfo != nil {
 	if sysInfo != nil {
 		uptimeSec = float64(sysInfo.UpTimeSec)
 		uptimeSec = float64(sysInfo.UpTimeSec)

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

@@ -409,6 +409,9 @@ type EthPort struct {
 	ConnectedTo string   `json:"connectedTo,omitempty"`
 	ConnectedTo string   `json:"connectedTo,omitempty"`
 	DeviceMac   string   `json:"deviceMac,omitempty"`
 	DeviceMac   string   `json:"deviceMac,omitempty"`
 	Detail      string   `json:"detail,omitempty"`
 	Detail      string   `json:"detail,omitempty"`
+	// Health: per-port health score (issue #299). Ausente si no se ha
+	// calculado (demo sin datos, puertos sin muestras).
+	Health *PortHealth `json:"health,omitempty"`
 }
 }
 
 
 // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
 // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).

+ 13 - 9
server-go/internal/alerts/alerts.go

@@ -70,15 +70,17 @@ type AlertEvent struct {
 
 
 // Stable alert-type slugs (issue #310): keys of the Hints map.
 // Stable alert-type slugs (issue #310): keys of the Hints map.
 const (
 const (
-	HintAgentDown     = "agent-down"
-	HintGatewayUnrch  = "gateway-unreachable"
-	HintHighTemp      = "high-temperature"
-	HintPortFlapping  = "port-flapping"
-	HintDeviceOffline = "device-offline"
-	HintUnknownDevice = "unknown-device"
-	HintFirmware      = "firmware-outdated"
-	HintWanDown       = "wan-down"
-	HintWifiWeak      = "wifi-weak"
+	HintAgentDown      = "agent-down"
+	HintGatewayUnrch   = "gateway-unreachable"
+	HintHighTemp       = "high-temperature"
+	HintPortFlapping   = "port-flapping"
+	HintDeviceOffline  = "device-offline"
+	HintUnknownDevice  = "unknown-device"
+	HintFirmware       = "firmware-outdated"
+	HintWanDown        = "wan-down"
+	HintWifiWeak       = "wifi-weak"
+	HintGhostPort      = "ghost-port"
+	HintDegradedLink   = "degraded-link"
 )
 )
 
 
 // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
 // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
@@ -93,6 +95,8 @@ var Hints = map[string]string{
 	HintFirmware:      "NetPulse es de solo lectura: actualiza el firmware desde LuCI.",
 	HintFirmware:      "NetPulse es de solo lectura: actualiza el firmware desde LuCI.",
 	HintWanDown:       "Comprueba el módem/ONT y contacta con tu operador si la caída persiste.",
 	HintWanDown:       "Comprueba el módem/ONT y contacta con tu operador si la caída persiste.",
 	HintWifiWeak:      "Acerca el dispositivo a un punto de acceso o reubica el AP.",
 	HintWifiWeak:      "Acerca el dispositivo a un punto de acceso o reubica el AP.",
+	HintGhostPort:     "Revisa el cable y el dispositivo conectado: un puerto activo que enmudece suele indicar un cable suelto o un equipo apagado.",
+	HintDegradedLink:  "Revisa el cable y los conectores: un enlace degradado suele ser síntoma de cable dañado o conector flojo.",
 }
 }
 
 
 // HintFor returns the suggestion for a slug, or "" when it does not exist.
 // HintFor returns the suggestion for a slug, or "" when it does not exist.