Parcourir la source

feat(topology): manual overrides layer + tagging UI (#142) (#143)

* feat(topology): manual overrides layer (issue #142, Phase A)

Add a persisted manual-overrides layer applied AFTER auto-discovery so the
topology builder can group VMs under their real hypervisor even when the
host port also carries unrelated physical devices, and can tag manual
switches / assign devices to hosts.

- DB table topology_overrides (mac, kind hypervisor|switch|attach, name,
  parent, enabled, timestamps) in schemaSQL.
- adapters.applyTopologyOverrides (pure, tested): 'hypervisor' nests the
  same-port hypervisor-OUI CTs under the tagged host; 'switch' promotes the
  port to a managed distnode; 'attach' anchors a target MAC under a parent.
  Applied in buildOverview right after inferTopology.
- topo_semantics: device-hub hanging from an inferred|managed distnode no
  longer double-emits its cable (regression from hypervisor nesting).
- admin API: GET/POST/PUT/DELETE /api/topology/overrides.
- Tests: override logic (mixed-port hypervisor, attach, switch, disabled,
  MAC normalization), store CRUD, and no-dup cable with a device-hub under
  a distnode.

Verified in production (CT 226): citadel-01/02 tagged hypervisor, CTs
(helios, jellyfin, hermesagent, vikunja) nest under their hosts and Home
Assistant (randomized MAC) attaches to citadel-01; no duplicated links.

* feat(topology): manual tagging UI (issue #142, Phase B)

Add the admin-facing UI to tag hardware without using the raw API:

- New TopologyOverridesManager component (CRUD against
  /api/topology/overrides): list with kind badges, enable/disable toggle,
  inline edit and delete-with-confirm; add form with MAC, kind segmented
  control (hypervisor/switch/attach) and parent for attach.
- Settings: new admin card 'Topology - manual tagging' (live+admin only).
- Topology: 'Tag devices' button (admin+live) opens a side sheet with the
  manager; clicking a device chip on the map no longer navigates but opens
  the sheet with that MAC preselected.
- i18n es/en for all new strings.
- types.ts: TopologyOverride + TopologyOverrideKind.

Verified in production (CT 226) with Playwright: sheet opens from button and
from chip click, the 3 production overrides list correctly, and a full
create+delete cycle leaves no trace via the API.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho il y a 3 mois
Parent
commit
bdf0630939

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

@@ -601,6 +601,7 @@
     "tunnel": "Tunnel",
     "weakSignal": "Weak signal",
     "zoomControls": "Map zoom controls",
+    "tagDevices": "Tag devices",
     "zoomIn": "Zoom in",
     "zoomOut": "Zoom out",
     "dawn": {
@@ -823,6 +824,33 @@
       "save": "Save",
       "saving": "Saving…"
     },
+    "overrides": {
+      "title": "Topology — manual tagging",
+      "caption": "Manual layer on top of auto-discovery: tag a device as hypervisor or switch, or attach a device to a host. Changes show up on the map after refresh.",
+      "hint": "Auto-discovery (FDB/LLDP) can't always tell which real host sits behind a shared port. Tagging by hand clears it up: a hypervisor nests its CTs under it, a switch manages its port, and \"attach\" hangs a device from a host.",
+      "empty": "No overrides yet. Add the first one with the \"Add\" button.",
+      "add": "Add",
+      "adding": "Adding…",
+      "addDevice": "Tag another device",
+      "mac": "MAC address",
+      "name": "Name (optional)",
+      "kind": "Type",
+      "kindHypervisor": "Hypervisor",
+      "kindSwitch": "Switch",
+      "kindAttach": "Attach",
+      "kind": {
+        "hypervisor": "Hypervisor",
+        "switch": "Switch",
+        "attach": "Attach"
+      },
+      "parent": "Host MAC to hang from",
+      "enabled": "Enabled",
+      "edit": "Edit",
+      "delete": "Delete",
+      "save": "Save",
+      "saving": "Saving…",
+      "errorGeneric": "Could not save the override."
+    },
     "saved": "Preferences saved",
     "services": {
       "title": "Services",

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

@@ -601,6 +601,7 @@
     "tunnel": "Túnel",
     "weakSignal": "Señal débil",
     "zoomControls": "Controles de zoom del mapa",
+    "tagDevices": "Etiquetar dispositivos",
     "zoomIn": "Acercar",
     "zoomOut": "Alejar",
     "dawn": {
@@ -823,6 +824,33 @@
       "save": "Guardar",
       "saving": "Guardando…"
     },
+    "overrides": {
+      "title": "Topología — etiquetado manual",
+      "caption": "Capa manual sobre el autodiscover: marca un equipo como hipervisor o switch, o asigna un dispositivo a un host. Los cambios se aplican en el mapa al refrescar.",
+      "hint": "El autodiscover (FDB/LLDP) no siempre sabe qué host real hay tras un puerto compartido. Etiquetar a mano lo aclara: un hipervisor agrupa sus CTs bajo él, un switch gestiona su puerto y «asignar» cuelga un dispositivo de un host.",
+      "empty": "Sin overrides todavía. Añade el primero con el botón «Añadir».",
+      "add": "Añadir",
+      "adding": "Añadiendo…",
+      "addDevice": "Etiquetar otro equipo",
+      "mac": "Dirección MAC",
+      "name": "Nombre (opcional)",
+      "kind": "Tipo",
+      "kindHypervisor": "Hipervisor",
+      "kindSwitch": "Switch",
+      "kindAttach": "Asignar",
+      "kind": {
+        "hypervisor": "Hipervisor",
+        "switch": "Switch",
+        "attach": "Asignar"
+      },
+      "parent": "MAC del host del que cuelga",
+      "enabled": "Activado",
+      "edit": "Editar",
+      "delete": "Eliminar",
+      "save": "Guardar",
+      "saving": "Guardando…",
+      "errorGeneric": "No se pudo guardar el override."
+    },
     "saved": "Preferencias guardadas",
     "services": {
       "title": "Servicios",

+ 12 - 1
app/src/components/topology/TopologyMap.tsx

@@ -368,9 +368,15 @@ interface TopologyMapProps {
   flow: boolean
   hoverLink: string | null
   onHoverLink: (id: string | null) => void
+  /**
+   * Modo etiquetado (issue #142 Fase B): si se pasa, el clic en un chip NO
+   * navega a /devices sino que notifica el dispositivo para abrir el panel
+   * de overrides manuales. Ausente → comportamiento normal.
+   */
+  onTagDevice?: (device: Device) => void
 }
 
-export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHoverLink }: TopologyMapProps) {
+export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHoverLink, onTagDevice }: TopologyMapProps) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const navigate = useNavigate()
@@ -1067,6 +1073,11 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             onHover={(e) => handleNodeHover(chipTip(chip), e)}
             onLeave={closeHover}
             onClick={(e) => {
+              if (onTagDevice) {
+                nodeClick(e, chipTip(chip))
+                onTagDevice(chip.device)
+                return
+              }
               if (chip.isCt) {
                 nodeClick(e, chipTip(chip))
                 return

+ 385 - 0
app/src/components/topology/TopologyOverridesManager.tsx

@@ -0,0 +1,385 @@
+/**
+ * NetPulse — Gestor de overrides manuales de topología (issue #142, Fase B).
+ * Capa 2 sobre el autodiscover: el admin etiqueta hardware como hipervisor o
+ * switch y asigna dispositivos a hosts (kind 'attach'). CRUD contra
+ * /api/topology/overrides; los cambios se reflejan en el mapa al refrescar el
+ * overview (el builder aplica los overrides server-side).
+ */
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Pencil, Plus, Tag, Trash2 } from 'lucide-react'
+import { SegmentedControl } from '@/components/SegmentedControl'
+import { Switch } from '@/components/ui/switch'
+import { useNetPulse } from '@/data/DataProvider'
+import { cn } from '@/lib/utils'
+import type { TopologyOverride, TopologyOverrideKind } from '@/data/types'
+
+interface Props {
+  onSaved?: () => void
+  /** MAC pre-seleccionada (desde el clic en el mapa) */
+  initialMac?: string
+}
+
+interface OverrideDraft {
+  mac: string
+  kind: TopologyOverrideKind
+  name: string
+  parent: string
+}
+
+const EMPTY: OverrideDraft = { mac: '', kind: 'hypervisor', name: '', parent: '' }
+
+const KIND_STYLE: Record<TopologyOverrideKind, string> = {
+  hypervisor: 'bg-ok/10 text-ok',
+  switch: 'bg-accent-soft text-accent',
+  attach: 'bg-info/10 text-info',
+}
+
+export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
+  const { t } = useTranslation()
+  const { refresh } = useNetPulse()
+  const [list, setList] = useState<TopologyOverride[]>([])
+  const [loading, setLoading] = useState(true)
+  const [error, setError] = useState<string | null>(null)
+  const [draft, setDraft] = useState<OverrideDraft>(EMPTY)
+  const [submitting, setSubmitting] = useState(false)
+  const [showAddForm, setShowAddForm] = useState(false)
+  const [confirmDeleteFor, setConfirmDeleteFor] = useState<string | null>(null)
+  const [editing, setEditing] = useState<TopologyOverride | null>(null)
+  const [editDraft, setEditDraft] = useState<OverrideDraft>(EMPTY)
+  const [editSubmitting, setEditSubmitting] = useState(false)
+
+  const load = useCallback(async () => {
+    try {
+      const res = await fetch('/api/topology/overrides')
+      if (res.status === 401) {
+        window.location.assign('/login')
+        return
+      }
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      const json = (await res.json()) as { overrides: TopologyOverride[] }
+      setList(json.overrides)
+      setError(null)
+    } catch {
+      setError(t('settings.overrides.errorGeneric'))
+    } finally {
+      setLoading(false)
+    }
+  }, [t])
+
+  useEffect(() => {
+    void load()
+  }, [load])
+
+  // Pre-selección desde el mapa: rellena el draft de alta y lo abre.
+  useEffect(() => {
+    if (!initialMac) return
+    setDraft((d) => ({ ...d, mac: initialMac }))
+    setShowAddForm(true)
+    setEditing(null)
+  }, [initialMac])
+
+  const submit = async (e: React.FormEvent) => {
+    e.preventDefault()
+    if (!draft.mac.trim() || submitting) return
+    setSubmitting(true)
+    setError(null)
+    try {
+      const res = await fetch('/api/topology/overrides', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          mac: draft.mac.trim(),
+          kind: draft.kind,
+          name: draft.name.trim() || undefined,
+          parent: draft.kind === 'attach' ? draft.parent.trim() || undefined : undefined,
+        }),
+      })
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      setDraft(EMPTY)
+      setShowAddForm(false)
+      await load()
+      refresh()
+      onSaved?.()
+    } catch {
+      setError(t('settings.overrides.errorGeneric'))
+    } finally {
+      setSubmitting(false)
+    }
+  }
+
+  const openEdit = (o: TopologyOverride) => {
+    setEditing(o)
+    setEditDraft({ mac: o.mac, kind: o.kind, name: o.name ?? '', parent: o.parent ?? '' })
+    setError(null)
+  }
+
+  const saveEdit = async (e: React.FormEvent) => {
+    e.preventDefault()
+    if (!editing || editSubmitting) return
+    setEditSubmitting(true)
+    setError(null)
+    try {
+      const res = await fetch(`/api/topology/overrides/${encodeURIComponent(editing.id)}`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          kind: editDraft.kind,
+          name: editDraft.name.trim() || undefined,
+          parent: editDraft.kind === 'attach' ? editDraft.parent.trim() || undefined : undefined,
+        }),
+      })
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      setEditing(null)
+      await load()
+      refresh()
+      onSaved?.()
+    } catch {
+      setError(t('settings.overrides.errorGeneric'))
+    } finally {
+      setEditSubmitting(false)
+    }
+  }
+
+  const toggleEnabled = async (o: TopologyOverride) => {
+    try {
+      const res = await fetch(`/api/topology/overrides/${encodeURIComponent(o.id)}`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ enabled: !o.enabled }),
+      })
+      if (!res.ok) throw new Error(`HTTP ${res.status}`)
+      await load()
+      refresh()
+      onSaved?.()
+    } catch {
+      setError(t('settings.overrides.errorGeneric'))
+    }
+  }
+
+  const remove = async (o: TopologyOverride) => {
+    try {
+      const res = await fetch(`/api/topology/overrides/${encodeURIComponent(o.id)}`, { method: 'DELETE' })
+      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
+      setConfirmDeleteFor(null)
+      await load()
+      refresh()
+      onSaved?.()
+    } catch {
+      setError(t('settings.overrides.errorGeneric'))
+    }
+  }
+
+  const kindOptions = [
+    { value: 'hypervisor' as const, label: t('settings.overrides.kindHypervisor') },
+    { value: 'switch' as const, label: t('settings.overrides.kindSwitch') },
+    { value: 'attach' as const, label: t('settings.overrides.kindAttach') },
+  ]
+
+  return (
+    <div className="space-y-3">
+      <p className="text-caption leading-relaxed text-text-muted">{t('settings.overrides.hint')}</p>
+
+      {error && <p className="text-caption text-danger">{error}</p>}
+
+      {/* Lista */}
+      {loading ? (
+        <p className="text-caption text-text-muted">…</p>
+      ) : list.length === 0 ? (
+        <p className="rounded-xl bg-elevated px-3.5 py-2.5 text-caption leading-relaxed text-text-muted">
+          {t('settings.overrides.empty')}
+        </p>
+      ) : (
+        <ul className="flex flex-col gap-2">
+          {list.map((o) => (
+            <li
+              key={o.id}
+              className={cn(
+                'flex items-center gap-3 rounded-xl border border-border bg-elevated px-3.5 py-2.5',
+                !o.enabled && 'opacity-50',
+              )}
+            >
+              <Tag className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
+              <div className="min-w-0 flex-1">
+                <div className="flex flex-wrap items-center gap-2">
+                  <span className="truncate font-mono text-sm font-medium text-text-primary">{o.mac}</span>
+                  <span
+                    className={cn(
+                      'rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider',
+                      KIND_STYLE[o.kind],
+                    )}
+                  >
+                    {t(`settings.overrides.kind.${o.kind}`)}
+                  </span>
+                  {o.kind === 'attach' && o.parent && (
+                    <span className="truncate font-mono text-caption text-text-muted">→ {o.parent}</span>
+                  )}
+                </div>
+                {o.name && <div className="truncate text-caption text-text-muted">{o.name}</div>}
+              </div>
+              <label className="flex shrink-0 cursor-pointer items-center" title={t('settings.overrides.enabled')}>
+                <Switch checked={o.enabled} onCheckedChange={() => void toggleEnabled(o)} aria-label={t('settings.overrides.enabled')} />
+              </label>
+              {confirmDeleteFor === o.id ? (
+                <span className="flex shrink-0 items-center gap-1.5">
+                  <button
+                    type="button"
+                    onClick={() => void remove(o)}
+                    className="rounded-lg bg-danger px-2.5 py-1.5 text-[11px] font-semibold text-canvas transition-opacity hover:opacity-90"
+                  >
+                    {t('settings.users.confirmDelete')}
+                  </button>
+                  <button
+                    type="button"
+                    onClick={() => setConfirmDeleteFor(null)}
+                    className="rounded-lg border border-border px-2.5 py-1.5 text-[11px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+                  >
+                    {t('settings.users.cancel')}
+                  </button>
+                </span>
+              ) : (
+                <span className="flex shrink-0 items-center gap-1.5">
+                  <button
+                    type="button"
+                    onClick={() => openEdit(o)}
+                    aria-label={t('settings.overrides.edit')}
+                    className="flex h-8 w-8 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-3.5 w-3.5" strokeWidth={1.75} />
+                  </button>
+                  <button
+                    type="button"
+                    onClick={() => setConfirmDeleteFor(o.id)}
+                    aria-label={t('settings.overrides.delete')}
+                    className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-danger/40 hover:text-danger"
+                  >
+                    <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+                  </button>
+                </span>
+              )}
+            </li>
+          ))}
+        </ul>
+      )}
+
+      {/* Alta */}
+      <div className="border-t border-border pt-3">
+        <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.overrides.add')}
+        </button>
+        {showAddForm && (
+          <form onSubmit={(e) => void submit(e)} className="mt-3 space-y-2.5">
+            <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+              <input
+                type="text"
+                required
+                value={draft.mac}
+                onChange={(e) => setDraft((d) => ({ ...d, mac: e.target.value }))}
+                placeholder="AA:BB:CC:DD:EE:FF"
+                aria-label={t('settings.overrides.mac')}
+                className="rounded-lg border border-border bg-canvas px-3 py-2 font-mono text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+              <input
+                type="text"
+                value={draft.name}
+                onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))}
+                placeholder={t('settings.overrides.name')}
+                aria-label={t('settings.overrides.name')}
+                className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            </div>
+            <SegmentedControl
+              options={kindOptions}
+              value={draft.kind}
+              onChange={(v) => setDraft((d) => ({ ...d, kind: v }))}
+              ariaLabel={t('settings.overrides.kind')}
+            />
+            {draft.kind === 'attach' && (
+              <input
+                type="text"
+                required
+                value={draft.parent}
+                onChange={(e) => setDraft((d) => ({ ...d, parent: e.target.value }))}
+                placeholder={t('settings.overrides.parent')}
+                aria-label={t('settings.overrides.parent')}
+                className="w-full rounded-lg border border-border bg-canvas px-3 py-2 font-mono text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            )}
+            <div className="flex items-center justify-end gap-2">
+              <button
+                type="submit"
+                disabled={submitting || !draft.mac.trim() || (draft.kind === 'attach' && !draft.parent.trim())}
+                className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-medium text-canvas transition-opacity duration-150 hover:opacity-90 disabled:opacity-40"
+              >
+                <Plus className="h-4 w-4" strokeWidth={2} />
+                {submitting ? t('settings.overrides.adding') : t('settings.overrides.add')}
+              </button>
+            </div>
+          </form>
+        )}
+      </div>
+
+      {/* Edición inline */}
+      {editing && (
+        <form onSubmit={(e) => void saveEdit(e)} className="mt-3 border-t border-border pt-3">
+          <div className="mb-2 flex items-center gap-2">
+            <Pencil className="h-4 w-4 text-accent" strokeWidth={1.75} />
+            <span className="truncate font-mono text-sm font-medium text-text-primary">{editing.mac}</span>
+          </div>
+          <div className="space-y-2.5">
+            <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+              <input
+                type="text"
+                value={editDraft.name}
+                onChange={(e) => setEditDraft((d) => ({ ...d, name: e.target.value }))}
+                placeholder={t('settings.overrides.name')}
+                aria-label={t('settings.overrides.name')}
+                className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            </div>
+            <SegmentedControl
+              options={kindOptions}
+              value={editDraft.kind}
+              onChange={(v) => setEditDraft((d) => ({ ...d, kind: v }))}
+              ariaLabel={t('settings.overrides.kind')}
+            />
+            {editDraft.kind === 'attach' && (
+              <input
+                type="text"
+                required
+                value={editDraft.parent}
+                onChange={(e) => setEditDraft((d) => ({ ...d, parent: e.target.value }))}
+                placeholder={t('settings.overrides.parent')}
+                aria-label={t('settings.overrides.parent')}
+                className="w-full rounded-lg border border-border bg-canvas px-3 py-2 font-mono text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            )}
+            <div className="flex items-center justify-end gap-2">
+              <button
+                type="button"
+                onClick={() => setEditing(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>
+              <button
+                type="submit"
+                disabled={editSubmitting || (editDraft.kind === 'attach' && !editDraft.parent.trim())}
+                className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-medium text-canvas transition-opacity duration-150 hover:opacity-90 disabled:opacity-40"
+              >
+                <Pencil className="h-4 w-4" strokeWidth={2} />
+                {editSubmitting ? t('settings.overrides.saving') : t('settings.overrides.save')}
+              </button>
+            </div>
+          </div>
+        </form>
+      )}
+    </div>
+  )
+}

+ 23 - 0
app/src/data/types.ts

@@ -268,6 +268,29 @@ export interface TopoSemLink {
   port?: string
 }
 
+/**
+ * Override manual de topología (issue #142, Fase A/B): capa 2 sobre el
+ * autodiscover aplicada server-side. El admin etiqueta hardware sin tocar
+ * la inferencia automática.
+ *   - kind 'hypervisor': el host es un hipervisor; los CTs del mismo puerto
+ *     se anidan bajo él.
+ *   - kind 'switch': el equipo es un switch gestionado (aunque sin LLDP).
+ *   - kind 'attach': el dispositivo cuelga de `parent` (VM con MAC random).
+ */
+export type TopologyOverrideKind = 'hypervisor' | 'switch' | 'attach'
+
+export interface TopologyOverride {
+  /** id = mac normalizada */
+  id: string
+  mac: string
+  kind: TopologyOverrideKind
+  name?: string
+  parent?: string
+  enabled: boolean
+  createdAt: number
+  updatedAt: number
+}
+
 /**
  * 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

+ 17 - 0
app/src/pages/Settings.tsx

@@ -37,6 +37,7 @@ import {
 import type { LucideIcon } from 'lucide-react'
 import { HealthRing } from '@/components/HealthRing'
 import { SegmentedControl } from '@/components/SegmentedControl'
+import { TopologyOverridesManager } from '@/components/topology/TopologyOverridesManager'
 import { Slider } from '@/components/ui/slider'
 import { Switch } from '@/components/ui/switch'
 import { useNetPulse } from '@/data/DataProvider'
@@ -2590,6 +2591,22 @@ export default function Settings() {
           </div>
         )}
 
+        {/* Overrides manuales de topología (issue #142): etiquetar hardware
+            como hipervisor/switch y asignar dispositivos a hosts. Solo admin
+            y modo live; los cambios se aplican server-side en el overview. */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="lg:col-span-12">
+            <Card
+              title={t('settings.overrides.title')}
+              caption={t('settings.overrides.caption')}
+              index={5}
+              reduce={reduce}
+            >
+              <TopologyOverridesManager onSaved={notify} />
+            </Card>
+          </div>
+        )}
+
         {/* Adopción de agentes (pairing token + server fingerprint) */}
         {!isDemo && auth?.role === 'admin' && (
           <div className="lg:col-span-12">

+ 52 - 1
app/src/pages/Topology.tsx

@@ -6,15 +6,19 @@ import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
-import { ChevronRight, Maximize, RefreshCw, ZoomIn, ZoomOut } from 'lucide-react'
+import { ChevronRight, Maximize, RefreshCw, Tag, ZoomIn, ZoomOut } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet'
 import { LegendCard, LegendSheet } from '@/components/topology/LegendCard'
 import { LinksTable } from '@/components/topology/LinksTable'
 
 import { TopologyMap } from '@/components/topology/TopologyMap'
 import type { TopologyMapApi } from '@/components/topology/TopologyMap'
+import { TopologyOverridesManager } from '@/components/topology/TopologyOverridesManager'
 import { buildTopologyModel } from '@/components/topology/model'
 import { useNetPulse } from '@/data/DataProvider'
+import { useAuth } from '@/data/AuthContext'
+import type { Device } from '@/data/mock'
 
 const EASE = [0.16, 1, 0.3, 1] as [number, number, number, number]
 
@@ -46,6 +50,8 @@ function ControlButton({
 export default function Topology() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
+  const { isDemo } = useNetPulse()
+  const auth = useAuth()
   const { routers, devices, wan, wireguard, distributionNodes, topology, vm, lastSnapshotAt, requestServerRefresh } =
     useNetPulse()
   const model = useMemo(
@@ -57,6 +63,17 @@ export default function Topology() {
   const [hoverLink, setHoverLink] = useState<string | null>(null)
   const mapApi = useRef<TopologyMapApi>({})
 
+  // Etiquetado manual (issue #142 Fase B): clic en un chip abre el panel de
+  // overrides con esa MAC preseleccionada. Solo admin y modo live.
+  const canTag = !isDemo && auth?.role === 'admin'
+  const [tagSheetOpen, setTagSheetOpen] = useState(false)
+  const [tagMac, setTagMac] = useState<string | undefined>(undefined)
+
+  const handleTagDevice = (device: Device) => {
+    setTagMac(device.mac ?? device.name)
+    setTagSheetOpen(true)
+  }
+
   // 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.
@@ -140,6 +157,23 @@ export default function Topology() {
         </motion.div>
 
         <div className="flex flex-wrap items-center gap-2">
+          {canTag && (
+            <motion.div {...controlMotion(0)}>
+              <button
+                type="button"
+                onClick={() => {
+                  setTagMac(undefined)
+                  setTagSheetOpen(true)
+                }}
+                aria-label={t('topology.tagDevices')}
+                title={t('topology.tagDevices')}
+                className="flex h-9 items-center gap-1.5 rounded-xl border border-border bg-surface px-3 text-[13px] font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+              >
+                <Tag className="h-4 w-4" strokeWidth={1.75} />
+                <span className="hidden sm:inline">{t('topology.tagDevices')}</span>
+              </button>
+            </motion.div>
+          )}
           <motion.div
             {...controlMotion(0)}
             className="flex items-center gap-0.5 rounded-xl border border-border bg-surface p-1"
@@ -193,6 +227,7 @@ export default function Topology() {
           flow={flow}
           hoverLink={hoverLink}
           onHoverLink={setHoverLink}
+          onTagDevice={canTag ? handleTagDevice : undefined}
         />
         {/* Zoom flotante (móvil: los controles del header quedan lejos del mapa) */}
         <div
@@ -216,6 +251,22 @@ export default function Topology() {
           <LinksTable model={model} hoverLink={hoverLink} onHoverLink={setHoverLink} />
         </div>
       </div>
+
+      {/* Etiquetado manual de hardware (issue #142 Fase B): clic en un chip
+          abre este panel con la MAC preseleccionada; también se abre desde el
+          botón "Etiquetar" del header (sin preselección). */}
+      <Sheet open={tagSheetOpen} onOpenChange={setTagSheetOpen}>
+        <SheetContent side="right" className="w-full max-w-md overflow-y-auto">
+          <SheetHeader>
+            <SheetTitle className="flex items-center gap-2">
+              <Tag className="h-4 w-4 text-accent" strokeWidth={1.75} />
+              {t('topology.tagDevices')}
+            </SheetTitle>
+            <SheetDescription>{t('settings.overrides.caption')}</SheetDescription>
+          </SheetHeader>
+          <TopologyOverridesManager initialMac={tagMac} />
+        </SheetContent>
+      </Sheet>
     </div>
   )
 }

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

@@ -1330,6 +1330,11 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	}
 	devices := l.buildDevices(polled)
 	devices, distNodes := inferTopology(polled, devices)
+	// Capa 2 manual (issue #142): overrides de topología tras el autodiscover.
+	// Sin BD (tests/demo) → no-op.
+	if l.db != nil {
+		devices, distNodes = applyTopologyOverrides(devices, distNodes, loadTopologyOverrides(l.db))
+	}
 	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
 	for _, d := range devices {
 		if d.Online && d.SignalDbm != nil && *d.SignalDbm < -70 {

+ 10 - 1
server-go/internal/adapters/topo_semantics.go

@@ -174,7 +174,16 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 	}
 	// el cable del propio hub (chip con hijos; el hipervisor entre ellos)
 	for _, hubID := range deviceHubOrder {
-		wiredLink(hubOf(deviceByID[hubID]), deviceByID[hubID])
+		hub := deviceByID[hubID]
+		h := hubOf(hub)
+		// Si el hub cuelga de un distnode inferred|managed, su cable ya lo
+		// genera el bucle de hijos de distnodes (más abajo): no duplicar.
+		// (Caso issue #142: host con CTs anidados por override que cuelga de
+		// un distnode inferred — el host es device-hub Y cliente del distnode.)
+		if dn, ok := distByID[h]; ok && (dn.Kind == "inferred" || dn.Kind == "managed") {
+			continue
+		}
+		wiredLink(h, hub)
 	}
 	// hijos cableados de distnodes (abanico alrededor del círculo)
 	for _, rn := range routerNodes {

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

@@ -149,3 +149,43 @@ func TestTopoSemanticsSinRouters(t *testing.T) {
 		t.Fatalf("sin routers no hay links ni anillos: %+v", sem)
 	}
 }
+
+// TestTopoSemanticsDeviceHubBajoDistnode: un device-hub (host con CTs
+// anidados por override, issue #142) que cuelga de un distnode inferred NO
+// debe duplicar su cable: lo genera solo el bucle de hijos de distnodes.
+func TestTopoSemanticsDeviceHubBajoDistnode(t *testing.T) {
+	devices := []Device{
+		{RouterID: "gateway", Band: "cable", Port: "lan1", ID: "host", MAC: "c8:ff:bf:08:6f:ba", AttachTo: "dist-gateway-lan1", Online: true, Infra: "hypervisor"},
+		{RouterID: "gateway", Band: "cable", Port: "lan1", ID: "ct1", MAC: "bc:24:11:00:00:01", AttachTo: "host", Online: true, Infra: "ct"},
+		{RouterID: "gateway", Band: "cable", Port: "lan1", ID: "ct2", MAC: "bc:24:11:00:00:02", AttachTo: "host", Online: true, Infra: "ct"},
+	}
+	routers := []Router{{ID: "gateway", Name: "gateway", RoleBadge: "Principal", Status: "online"}}
+	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred", RouterID: "gateway", Port: "lan1"}}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists)
+
+	var toHost []TopoLink
+	for _, l := range sem.Links {
+		if l.To == "host" {
+			toHost = append(toHost, l)
+		}
+	}
+	// Un solo cable host→su hub (dist-gateway-lan1), no duplicado.
+	if len(toHost) != 1 {
+		t.Fatalf("cable del device-hub duplicado (%d): %+v", len(toHost), toHost)
+	}
+	if toHost[0].From != "dist-gateway-lan1" {
+		t.Errorf("host debe colgar de su distnode: %+v", toHost[0])
+	}
+	// Los CTs cuelgan del host exactamente una vez cada uno.
+	ctLinks := map[string]int{}
+	for _, l := range sem.Links {
+		if l.From == "host" {
+			ctLinks[l.To]++
+		}
+	}
+	for _, ct := range []string{"ct1", "ct2"} {
+		if ctLinks[ct] != 1 {
+			t.Errorf("CT %s debe colgar del host una vez, got %d", ct, ctLinks[ct])
+		}
+	}
+}

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

@@ -48,8 +48,9 @@ var hypervisorOUI = []string{
 }
 
 func isHypervisorMAC(mac string) bool {
+	upper := strings.ToUpper(mac)
 	for _, p := range hypervisorOUI {
-		if strings.HasPrefix(mac, p) {
+		if strings.HasPrefix(upper, p) {
 			return true
 		}
 	}

+ 184 - 0
server-go/internal/adapters/topology_override.go

@@ -0,0 +1,184 @@
+// topology_override.go — Capa 2 manual de topología (issue #142, Fase A):
+// overrides persistidos que se aplican DESPUÉS del autodiscover
+// (inferTopology) y ANTES del modelo semántico (BuildTopoSemantics).
+//
+// Reglas:
+//   - "hypervisor" (MAC): el host es un hipervisor aunque su puerto tenga
+//     varios hosts físicos (caso citadel-01: CTs BC:24:11 mezclados con
+//     otros equipos en el mismo puerto). Las MACs con OUI de hipervisor del
+//     MISMO puerto+router se re-anidan bajo el host. No se crea distnode:
+//     el host actúa de device-hub y BuildTopoSemantics dibuja los CTs bajo
+//     él igual que el switch gestionado (topo_semantics.go:164-174).
+//   - "switch" (MAC): el equipo es un switch gestionado aunque no anuncie
+//     LLDP. Su puerto se convierte en distnode managed y el resto del puerto
+//     se anida bajo él (el Device del propio switch queda como managed-switch,
+//     excluido del mapa por D1).
+//   - "attach" (MAC + Parent): el target cuelga de `parent` (útil para VMs
+//     con MAC random, p.ej. Home Assistant dentro de citadel-01).
+//
+// Función pura (sin BD) para ser testeable.
+package adapters
+
+import (
+	"database/sql"
+	"fmt"
+	"strings"
+)
+
+// queryer: subset de *sql.DB usado para cargar overrides (evita acoplar a db.DB).
+type queryer interface {
+	Query(query string, args ...any) (*sql.Rows, error)
+}
+
+// loadTopologyOverrides lee los overrides enabled de la tabla. Sigue el
+// patrón de lectura directa SQL del Live (device_attrib en live.go:1044).
+func loadTopologyOverrides(q queryer) []TopologyOverride {
+	if q == nil {
+		return nil
+	}
+	rows, err := q.Query(
+		"SELECT id, mac, kind, name, parent, enabled, created_at, updated_at FROM topology_overrides WHERE enabled = 1 ORDER BY created_at ASC")
+	if err != nil {
+		return nil
+	}
+	defer rows.Close()
+	out := []TopologyOverride{}
+	for rows.Next() {
+		var o TopologyOverride
+		var name, parent sql.NullString
+		var enabled int
+		if err := rows.Scan(&o.ID, &o.MAC, &o.Kind, &name, &parent, &enabled, &o.CreatedAt, &o.UpdatedAt); err != nil {
+			continue
+		}
+		o.Name = name.String
+		o.Parent = parent.String
+		o.Enabled = enabled == 1
+		out = append(out, o)
+	}
+	return out
+}
+
+// NormalizeMAC normaliza una MAC a minúsculas sin espacios (formato de
+// comparación de la capa de overrides y del resto del pipeline).
+func NormalizeMAC(mac string) string {
+	return strings.ToLower(strings.TrimSpace(mac))
+}
+
+// deviceIndexByMAC indexa devices por MAC normalizada.
+func deviceIndexByMAC(devices []Device) map[string]int {
+	m := make(map[string]int, len(devices))
+	for i, d := range devices {
+		if d.MAC != "" {
+			m[NormalizeMAC(d.MAC)] = i
+		}
+	}
+	return m
+}
+
+// applyTopologyOverrides aplica la capa 2 manual sobre el resultado del
+// autodiscover. Orden determinista por kind (hypervisor → switch → attach)
+// para que los attaches resuelvan sobre los hosts ya sellados.
+func applyTopologyOverrides(devices []Device, dists []DistributionNode, overrides []TopologyOverride) ([]Device, []DistributionNode) {
+	if len(overrides) == 0 {
+		return devices, dists
+	}
+	byMAC := deviceIndexByMAC(devices)
+
+	// 1) hypervisor: sellar host + re-anidar CTs OUI del mismo puerto.
+	for _, ov := range overrides {
+		if !ov.Enabled || ov.Kind != "hypervisor" {
+			continue
+		}
+		idx, ok := byMAC[NormalizeMAC(ov.MAC)]
+		if !ok {
+			continue
+		}
+		host := &devices[idx]
+		host.Infra = "hypervisor"
+		if host.Port == "" {
+			continue
+		}
+		for i := range devices {
+			d := &devices[i]
+			if d.RouterID != host.RouterID || d.Port != host.Port {
+				continue
+			}
+			if d.ID == host.ID || !isHypervisorMAC(NormalizeMAC(d.MAC)) {
+				continue
+			}
+			d.AttachTo = host.ID
+			d.Infra = "ct"
+		}
+	}
+
+	// 2) switch: el puerto del target → distnode managed; el resto del puerto
+	//    se anida bajo él.
+	for _, ov := range overrides {
+		if !ov.Enabled || ov.Kind != "switch" {
+			continue
+		}
+		idx, ok := byMAC[NormalizeMAC(ov.MAC)]
+		if !ok {
+			continue
+		}
+		sw := &devices[idx]
+		sw.Infra = "managed-switch"
+		if sw.Port == "" {
+			continue
+		}
+		id := fmt.Sprintf("dist-%s-%s", sw.RouterID, sw.Port)
+		name := ov.Name
+		if name == "" {
+			name = sw.Name
+		}
+		var node *DistributionNode
+		for i := range dists {
+			if dists[i].ID == id {
+				node = &dists[i]
+				break
+			}
+		}
+		if node == nil {
+			dists = append(dists, DistributionNode{
+				ID: id, Kind: "managed", RouterID: sw.RouterID, Port: sw.Port,
+				Mac: sw.MAC, Name: name,
+			})
+			node = &dists[len(dists)-1]
+		} else {
+			node.Kind = "managed"
+			node.Mac = sw.MAC
+			if name != "" {
+				node.Name = name
+			}
+		}
+		for i := range devices {
+			d := &devices[i]
+			if d.RouterID != sw.RouterID || d.Port != sw.Port || d.ID == sw.ID {
+				continue
+			}
+			d.AttachTo = id
+		}
+	}
+
+	// 3) attach: el target cuelga de `parent`.
+	for _, ov := range overrides {
+		if !ov.Enabled || ov.Kind != "attach" || ov.Parent == "" {
+			continue
+		}
+		tIdx, ok := byMAC[NormalizeMAC(ov.MAC)]
+		if !ok {
+			continue
+		}
+		pIdx, ok := byMAC[NormalizeMAC(ov.Parent)]
+		if !ok {
+			continue
+		}
+		target := &devices[tIdx]
+		parent := &devices[pIdx]
+		target.AttachTo = parent.ID
+		if parent.Infra == "hypervisor" {
+			target.Infra = "ct"
+		}
+	}
+	return devices, dists
+}

+ 132 - 0
server-go/internal/adapters/topology_override_test.go

@@ -0,0 +1,132 @@
+package adapters
+
+import "testing"
+
+// devOverride crea un Device mínimo para tests de overrides (cable, con puerto).
+func devOverride(id, mac, router, port string) Device {
+	return Device{ID: id, MAC: mac, RouterID: router, Port: port, Band: "cable"}
+}
+
+// TestApplyHypervisorOverridePuertoMezclado: el caso real del usuario — un
+// hipervisor (citadel-01) con CTs BC:24:11 en un puerto donde además hay
+// dispositivos físicos NO relacionados. El autodiscover no los agrupa (varios
+// hosts físicos); el override sí, y SOLO los CTs OUI, no los vecinos.
+func TestApplyHypervisorOverridePuertoMezclado(t *testing.T) {
+	devices := []Device{
+		devOverride("c8-ff-bf-08-6f-ba", "c8:ff:bf:08:6f:ba", "rtr1", "lan4"),
+		devOverride("bc-24-11-00-00-01", "bc:24:11:00:00:01", "rtr1", "lan4"),
+		devOverride("bc-24-11-00-00-02", "bc:24:11:00:00:02", "rtr1", "lan4"),
+		devOverride("marantz", "00:05:cd:00:00:01", "rtr1", "lan4"),
+		devOverride("shield", "48:b0:2d:00:00:01", "rtr1", "lan4"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "hypervisor", MAC: "c8:ff:bf:08:6f:ba", Enabled: true},
+	}
+	out, _ := applyTopologyOverrides(devices, nil, overrides)
+	byID := map[string]Device{}
+	for _, d := range out {
+		byID[d.ID] = d
+	}
+	if byID["c8-ff-bf-08-6f-ba"].Infra != "hypervisor" {
+		t.Errorf("host sin Infra=hypervisor: %+v", byID["c8-ff-bf-08-6f-ba"])
+	}
+	for _, ct := range []string{"bc-24-11-00-00-01", "bc-24-11-00-00-02"} {
+		if byID[ct].AttachTo != "c8-ff-bf-08-6f-ba" || byID[ct].Infra != "ct" {
+			t.Errorf("CT %s no anidado bajo host: %+v", ct, byID[ct])
+		}
+	}
+	// Los físicos del mismo puerto NO se tocan
+	if byID["marantz"].AttachTo != "" || byID["shield"].AttachTo != "" {
+		t.Errorf("dispositivos físicos del puerto no deben anidarse: %+v %+v", byID["marantz"], byID["shield"])
+	}
+}
+
+// TestApplyAttachOverride: VM con MAC random (Home Assistant) anclada a un
+// hipervisor vía override kind=attach.
+func TestApplyAttachOverride(t *testing.T) {
+	devices := []Device{
+		devOverride("c8-ff-bf-08-6f-ba", "c8:ff:bf:08:6f:ba", "rtr1", "lan4"),
+		devOverride("02-78-f4-02-8a-94", "02:78:f4:02:8a:94", "rtr1", "lan4"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "hypervisor", MAC: "c8:ff:bf:08:6f:ba", Enabled: true},
+		{Kind: "attach", MAC: "02:78:f4:02:8a:94", Parent: "c8:ff:bf:08:6f:ba", Enabled: true},
+	}
+	out, _ := applyTopologyOverrides(devices, nil, overrides)
+	byID := map[string]Device{}
+	for _, d := range out {
+		byID[d.ID] = d
+	}
+	if byID["02-78-f4-02-8a-94"].AttachTo != "c8-ff-bf-08-6f-ba" || byID["02-78-f4-02-8a-94"].Infra != "ct" {
+		t.Errorf("VM attach no anclada al host: %+v", byID["02-78-f4-02-8a-94"])
+	}
+}
+
+// TestApplySwitchOverride: un switch manual (sin LLDP) se convierte en nodo
+// managed; el resto del puerto se anida bajo el distnode y el propio switch
+// queda sellado como managed-switch.
+func TestApplySwitchOverride(t *testing.T) {
+	devices := []Device{
+		devOverride("switch-manual", "aa:bb:cc:00:00:01", "rtr1", "lan2"),
+		devOverride("d1", "00:00:00:00:00:01", "rtr1", "lan2"),
+		devOverride("d2", "00:00:00:00:00:02", "rtr1", "lan2"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "switch", MAC: "aa:bb:cc:00:00:01", Name: "switch-manual", Enabled: true},
+	}
+	out, dists := applyTopologyOverrides(devices, nil, overrides)
+	byID := map[string]Device{}
+	for _, d := range out {
+		byID[d.ID] = d
+	}
+	if byID["switch-manual"].Infra != "managed-switch" {
+		t.Errorf("switch sin Infra=managed-switch: %+v", byID["switch-manual"])
+	}
+	if len(dists) != 1 || dists[0].Kind != "managed" || dists[0].Mac != "aa:bb:cc:00:00:01" || dists[0].Name != "switch-manual" {
+		t.Fatalf("distnode managed inesperado: %+v", dists)
+	}
+	id := dists[0].ID
+	if byID["d1"].AttachTo != id || byID["d2"].AttachTo != id {
+		t.Errorf("devices del puerto no anidados bajo el switch: %+v %+v", byID["d1"], byID["d2"])
+	}
+}
+
+// TestApplyOverrideDeshabilitado: un override enabled=false no aplica.
+func TestApplyOverrideDeshabilitado(t *testing.T) {
+	devices := []Device{
+		devOverride("c8-ff-bf-08-6f-ba", "c8:ff:bf:08:6f:ba", "rtr1", "lan4"),
+		devOverride("bc-24-11-00-00-01", "bc:24:11:00:00:01", "rtr1", "lan4"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "hypervisor", MAC: "c8:ff:bf:08:6f:ba", Enabled: false},
+	}
+	out, _ := applyTopologyOverrides(devices, nil, overrides)
+	if out[0].Infra != "" || out[1].AttachTo != "" {
+		t.Errorf("override deshabilitado no debe aplicar: %+v %+v", out[0], out[1])
+	}
+}
+
+// TestApplyOverrideSinOverrides: nil/no-op preserva el resultado.
+func TestApplyOverrideSinOverrides(t *testing.T) {
+	devices := []Device{devOverride("a", "00:00:00:00:00:01", "rtr1", "lan1")}
+	out, dists := applyTopologyOverrides(devices, nil, nil)
+	if len(out) != 1 || out[0].ID != "a" || len(dists) != 0 {
+		t.Errorf("sin overrides no debe cambiar nada")
+	}
+}
+
+// TestApplyHypervisorNormalizaMAC: la MAC del override se normaliza antes de
+// buscar (mayúsculas o espacios no rompen el match).
+func TestApplyHypervisorNormalizaMAC(t *testing.T) {
+	devices := []Device{
+		devOverride("c8-ff-bf-08-6f-ba", "C8:FF:BF:08:6F:BA", "rtr1", "lan4"),
+		devOverride("bc-24-11-00-00-01", "bc:24:11:00:00:01", "rtr1", "lan4"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "hypervisor", MAC: " C8:FF:BF:08:6F:BA ", Enabled: true},
+	}
+	out, _ := applyTopologyOverrides(devices, nil, overrides)
+	if out[0].Infra != "hypervisor" || out[1].AttachTo != "c8-ff-bf-08-6f-ba" {
+		t.Errorf("normalización MAC falló: %+v %+v", out[0], out[1])
+	}
+}

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

@@ -234,6 +234,25 @@ type AlertEvent = alerts.AlertEvent
 // de forma (añadir campos opcionales NO bumpea).
 const ViewModelVersion = 1
 
+// TopologyOverride: capa 2 manual sobre el autodiscover (issue #142). El
+// builder la aplica tras inferTopology y antes de BuildTopoSemantics.
+//   - Kind "hypervisor" (MAC): ese host es un hipervisor; las MACs con OUI
+//     de hipervisor del mismo puerto+router se anidan bajo él.
+//   - Kind "switch" (MAC): ese equipo es un switch gestionado (aunque sin
+//     LLDP); su puerto se convierte en distnode managed.
+//   - Kind "attach" (MAC + Parent): el target cuelga de `parent` (hipervisor
+//     o switch manual).
+type TopologyOverride struct {
+	ID        string `json:"id"`
+	MAC       string `json:"mac"` // target normalizado (minúsculas, ':')
+	Kind      string `json:"kind"`
+	Name      string `json:"name,omitempty"`
+	Parent    string `json:"parent,omitempty"`
+	Enabled   bool   `json:"enabled"`
+	CreatedAt int64  `json:"createdAt"`
+	UpdatedAt int64  `json:"updatedAt"`
+}
+
 // TopoSemantics: modelo semántico de la topología (Fase 4). La app conserva
 // SOLO la geometría de píxeles; asignaciones de anillo, enlaces y conteos de
 // peers ocultos llegan calculados.

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

@@ -172,6 +172,25 @@ CREATE TABLE IF NOT EXISTS roam_events (
 CREATE UNIQUE INDEX IF NOT EXISTS idx_roam_events_dedup ON roam_events(content_hash);
 CREATE INDEX IF NOT EXISTS idx_roam_events_ts ON roam_events(ts_ms DESC);
 CREATE INDEX IF NOT EXISTS idx_roam_events_router_ts ON roam_events(router_id, ts_ms DESC);
+
+-- Overrides manuales de topología (issue #142, Fase A): capa 2 sobre el
+-- autodiscover. El builder los aplica DESPUÉS de inferTopology.
+--   kind 'hypervisor' (target MAC): el dispositivo es un hipervisor; los CTs
+--     con OUI de hipervisor del mismo puerto se anidan bajo él.
+--   kind 'switch' (target MAC): el dispositivo es un switch manual (sin LLDP);
+--     el puerto del target pasa a ser nodo managed con esa MAC.
+--   kind 'attach' (target MAC, parent MAC): el target cuelga del parent.
+CREATE TABLE IF NOT EXISTS topology_overrides (
+  id         TEXT PRIMARY KEY,
+  mac        TEXT NOT NULL,            -- target normalizado (minúsculas, '-')
+  kind       TEXT NOT NULL,            -- 'hypervisor' | 'switch' | 'attach'
+  name       TEXT,                     -- nombre personalizado (opcional)
+  parent     TEXT,                     -- kind='attach': MAC del padre
+  enabled    INTEGER NOT NULL DEFAULT 1,
+  created_at INTEGER NOT NULL,
+  updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_topo_overrides_mac ON topology_overrides(mac);
 `
 
 // DB envuelve *sql.DB con los jobs y helpers de paridad.

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

@@ -237,6 +237,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Ajustes globales en kv (issue #121: orchestration opt-in) ---
 	s.registerSettingsRoutes(mux)
 
+	// --- Overrides manuales de topología (issue #142; solo admin) ---
+	s.registerTopologyOverrideRoutes(mux)
+
 	// --- SSE ---
 	mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
 

+ 98 - 0
server-go/internal/httpapi/topology_override.go

@@ -0,0 +1,98 @@
+// topology_override.go — API admin de overrides manuales de topología
+// (issue #142, Fase A): CRUD sobre la tabla topology_overrides.
+package httpapi
+
+import (
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/topooverride"
+)
+
+// registerTopologyOverrideRoutes registra las rutas admin de overrides:
+//   - GET    /api/topology/overrides          → lista
+//   - POST   /api/topology/overrides          → crear (upsert por MAC)
+//   - PUT    /api/topology/overrides/{id}     → actualizar (id = MAC)
+//   - DELETE /api/topology/overrides/{id}     → borrar
+func (s *server) registerTopologyOverrideRoutes(mux *http.ServeMux) {
+	mux.Handle("GET /api/topology/overrides", auth.RequireAdmin(http.HandlerFunc(s.handleTopologyOverrideList)))
+	mux.Handle("POST /api/topology/overrides", auth.RequireAdmin(http.HandlerFunc(s.handleTopologyOverrideCreate)))
+	mux.Handle("PUT /api/topology/overrides/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleTopologyOverrideUpdate)))
+	mux.Handle("DELETE /api/topology/overrides/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleTopologyOverrideDelete)))
+}
+
+func (s *server) handleTopologyOverrideList(w http.ResponseWriter, r *http.Request) {
+	writeJSON(w, http.StatusOK, map[string]any{"overrides": topooverride.List(s.db.DB)})
+}
+
+func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		MAC    string `json:"mac"`
+		Kind   string `json:"kind"`
+		Name   string `json:"name"`
+		Parent string `json:"parent"`
+	}
+	if !readJSONBody(r, &body) {
+		writeError(w, http.StatusBadRequest, "invalid_body")
+		return
+	}
+	body.MAC = adapters.NormalizeMAC(body.MAC)
+	if body.MAC == "" {
+		writeError(w, http.StatusBadRequest, "invalid_mac")
+		return
+	}
+	if body.Kind != "hypervisor" && body.Kind != "switch" && body.Kind != "attach" {
+		writeError(w, http.StatusBadRequest, "invalid_kind")
+		return
+	}
+	if body.Kind == "attach" && adapters.NormalizeMAC(body.Parent) == "" {
+		writeError(w, http.StatusBadRequest, "attach_requires_parent")
+		return
+	}
+	if body.Kind != "attach" {
+		body.Parent = ""
+	}
+	o, err := topooverride.Add(s.db.DB, topooverride.AddInput{
+		MAC: body.MAC, Kind: body.Kind, Name: body.Name, Parent: body.Parent,
+	})
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	writeJSON(w, http.StatusCreated, map[string]any{"override": o})
+}
+
+func (s *server) handleTopologyOverrideUpdate(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	var body struct {
+		Kind    *string `json:"kind"`
+		Name    *string `json:"name"`
+		Parent  *string `json:"parent"`
+		Enabled *bool   `json:"enabled"`
+	}
+	if !readJSONBody(r, &body) {
+		writeError(w, http.StatusBadRequest, "invalid_body")
+		return
+	}
+	if body.Kind != nil && *body.Kind != "hypervisor" && *body.Kind != "switch" && *body.Kind != "attach" {
+		writeError(w, http.StatusBadRequest, "invalid_kind")
+		return
+	}
+	o, ok := topooverride.Update(s.db.DB, id, topooverride.UpdateInput{
+		Kind: body.Kind, Name: body.Name, Parent: body.Parent, Enabled: body.Enabled,
+	})
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"override": o})
+}
+
+func (s *server) handleTopologyOverrideDelete(w http.ResponseWriter, r *http.Request) {
+	if !topooverride.Remove(s.db.DB, r.PathValue("id")) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 128 - 0
server-go/internal/topooverride/topooverride.go

@@ -0,0 +1,128 @@
+// Package topooverride — almacén de overrides manuales de topología (tabla
+// `topology_overrides`, issue #142 Fase A). Capa 2 sobre el autodiscover:
+// el builder los aplica tras inferTopology. API admin (httpapi) + lectura
+// por el adapter Live (adapters).
+package topooverride
+
+import (
+	"database/sql"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+// List devuelve todos los overrides, enabled primero, por creación.
+func List(db *sql.DB) []adapters.TopologyOverride {
+	rows, err := db.Query(
+		"SELECT id, mac, kind, name, parent, enabled, created_at, updated_at FROM topology_overrides ORDER BY enabled DESC, created_at ASC")
+	if err != nil {
+		return []adapters.TopologyOverride{}
+	}
+	defer rows.Close()
+	out := []adapters.TopologyOverride{}
+	for rows.Next() {
+		var o adapters.TopologyOverride
+		var name, parent sql.NullString
+		var enabled int
+		if err := rows.Scan(&o.ID, &o.MAC, &o.Kind, &name, &parent, &enabled, &o.CreatedAt, &o.UpdatedAt); err != nil {
+			continue
+		}
+		o.Name = name.String
+		o.Parent = parent.String
+		o.Enabled = enabled == 1
+		out = append(out, o)
+	}
+	return out
+}
+
+// AddInput son los datos de alta de un override.
+type AddInput struct {
+	MAC    string
+	Kind   string // "hypervisor" | "switch" | "attach"
+	Name   string
+	Parent string
+}
+
+// Add inserta un override (id = mac normalizada) y devuelve la fila creada.
+// Si ya existe para esa MAC devuelve la existente (no duplica).
+func Add(db *sql.DB, in AddInput) (adapters.TopologyOverride, error) {
+	now := time.Now().UnixMilli()
+	mac := adapters.NormalizeMAC(in.MAC)
+	_, err := db.Exec(
+		`INSERT INTO topology_overrides (id, mac, kind, name, parent, enabled, created_at, updated_at)
+		 VALUES (?, ?, ?, NULLIF(?, ''), NULLIF(?, ''), 1, ?, ?)
+		 ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, name=excluded.name, parent=excluded.parent, updated_at=excluded.updated_at`,
+		mac, mac, in.Kind, in.Name, in.Parent, now, now)
+	if err != nil {
+		return adapters.TopologyOverride{}, err
+	}
+	for _, o := range List(db) {
+		if o.ID == mac {
+			return o, nil
+		}
+	}
+	return adapters.TopologyOverride{}, sql.ErrNoRows
+}
+
+// UpdateInput son los campos editables de un override. Todos opcionales:
+// nil = no tocar el campo.
+type UpdateInput struct {
+	Kind    *string
+	Name    *string
+	Parent  *string
+	Enabled *bool
+}
+
+// Update actualiza un override por id (mac). Devuelve la fila o false si no
+// existe.
+func Update(db *sql.DB, id string, in UpdateInput) (adapters.TopologyOverride, bool) {
+	now := time.Now().UnixMilli()
+	sets := []string{"updated_at = ?"}
+	args := []any{now}
+	if in.Kind != nil {
+		sets = append(sets, "kind = ?")
+		args = append(args, *in.Kind)
+	}
+	if in.Name != nil {
+		sets = append(sets, "name = NULLIF(?, '')")
+		args = append(args, *in.Name)
+	}
+	if in.Parent != nil {
+		sets = append(sets, "parent = NULLIF(?, '')")
+		args = append(args, *in.Parent)
+	}
+	if in.Enabled != nil {
+		en := 0
+		if *in.Enabled {
+			en = 1
+		}
+		sets = append(sets, "enabled = ?")
+		args = append(args, en)
+	}
+	args = append(args, id)
+	res, err := db.Exec("UPDATE topology_overrides SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...)
+	if err != nil {
+		return adapters.TopologyOverride{}, false
+	}
+	n, _ := res.RowsAffected()
+	if n == 0 {
+		return adapters.TopologyOverride{}, false
+	}
+	for _, o := range List(db) {
+		if o.ID == id {
+			return o, true
+		}
+	}
+	return adapters.TopologyOverride{}, false
+}
+
+// Remove borra por id (mac); true si borró (changes > 0).
+func Remove(db *sql.DB, id string) bool {
+	res, err := db.Exec("DELETE FROM topology_overrides WHERE id = ?", id)
+	if err != nil {
+		return false
+	}
+	n, _ := res.RowsAffected()
+	return n > 0
+}

+ 74 - 0
server-go/internal/topooverride/topooverride_test.go

@@ -0,0 +1,74 @@
+package topooverride_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/topooverride"
+)
+
+func TestStoreCRUD(t *testing.T) {
+	dir := t.TempDir()
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	defer d.Close()
+
+	if got := len(topooverride.List(d.DB)); got != 0 {
+		t.Fatalf("BD vacía esperaba 0 overrides, hay %d", got)
+	}
+
+	o, err := topooverride.Add(d.DB, topooverride.AddInput{
+		MAC: " C8:FF:BF:08:6F:BA ", Kind: "hypervisor",
+	})
+	if err != nil {
+		t.Fatalf("Add: %v", err)
+	}
+	if o.ID != "c8:ff:bf:08:6f:ba" {
+		t.Errorf("id debe ser MAC normalizada, got %q", o.ID)
+	}
+	if !o.Enabled {
+		t.Errorf("nuevo override debe estar enabled")
+	}
+
+	// Upsert: mismo id, no duplica
+	if _, err := topooverride.Add(d.DB, topooverride.AddInput{
+		MAC: "c8:ff:bf:08:6f:ba", Kind: "switch",
+	}); err != nil {
+		t.Fatalf("Add duplicado: %v", err)
+	}
+	if got := len(topooverride.List(d.DB)); got != 1 {
+		t.Fatalf("upsert no debe duplicar: %d", got)
+	}
+	list := topooverride.List(d.DB)
+	if list[0].Kind != "switch" {
+		t.Errorf("upsert debe actualizar kind, got %q", list[0].Kind)
+	}
+
+	// Update parcial
+	enabled := false
+	o, ok := topooverride.Update(d.DB, "c8:ff:bf:08:6f:ba", topooverride.UpdateInput{Enabled: &enabled})
+	if !ok {
+		t.Fatal("Update existente devolvió false")
+	}
+	if o.Enabled {
+		t.Errorf("Update enabled=false no aplicó")
+	}
+
+	// Update inexistente
+	if _, ok := topooverride.Update(d.DB, "00:00:00:00:00:00", topooverride.UpdateInput{Enabled: &enabled}); ok {
+		t.Error("Update inexistente debe devolver false")
+	}
+
+	// Remove
+	if !topooverride.Remove(d.DB, "c8:ff:bf:08:6f:ba") {
+		t.Error("Remove existente devolvió false")
+	}
+	if topooverride.Remove(d.DB, "c8:ff:bf:08:6f:ba") {
+		t.Error("Remove inexistente debe devolver false")
+	}
+	if got := len(topooverride.List(d.DB)); got != 0 {
+		t.Fatalf("tras remove debe quedar vacío, hay %d", got)
+	}
+}